@astl/editor 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +96 -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 +42 -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,103 @@
1
+ import type { EditorAdapter, Issue, Severity } from '@astl/core';
2
+ import { type CSSResult, css, html, nothing, svg, type TemplateResult } from 'lit';
3
+ import type { Authoring } from '../authoring.js';
4
+ import { EDITOR_NAMESPACE } from '../messages.js';
5
+
6
+ /** The severity icons (shapes with their own stroke), for the issue list and the inspector's banners. */
7
+ export const SEVERITY_ICONS: Readonly<Record<Severity, TemplateResult>> = {
8
+ error: svg`<circle cx="10" cy="10" r="7.5" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M7 7l6 6m0-6l-6 6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/>`,
9
+ warning: svg`<path d="M10 2.8l7.6 13.4H2.4z" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"/><path d="M10 8v3.6" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><circle cx="10" cy="14" r="1.1" fill="currentColor"/>`,
10
+ };
11
+
12
+ /** Errors first, then warnings; document order within each. */
13
+ export function sortIssues(issues: readonly Issue[]): Issue[] {
14
+ return [...issues].sort((a, b) => Number(a.severity !== 'error') - Number(b.severity !== 'error'));
15
+ }
16
+
17
+ /** Source id an issue can jump to: its component, else its page. */
18
+ export function issueTarget(issue: Issue): string | null {
19
+ return issue.at.element ?? issue.at.page;
20
+ }
21
+
22
+ export const issueStyles: CSSResult = css`
23
+ .issue > button,
24
+ .issue > .static {
25
+ box-sizing: border-box;
26
+ display: flex;
27
+ flex-wrap: wrap;
28
+ align-items: baseline;
29
+ gap: var(--astl-space-1) var(--astl-space-2);
30
+ inline-size: 100%;
31
+ min-block-size: var(--astl-target-min);
32
+ padding-block: var(--astl-space-2);
33
+ padding-inline: var(--astl-space-3);
34
+ border: var(--astl-outline-width) solid var(--astl-line);
35
+ border-inline-start-width: var(--astl-space-1);
36
+ border-radius: var(--astl-radius-m);
37
+ background: var(--astl-surface);
38
+ color: var(--astl-ink);
39
+ text-align: start;
40
+ }
41
+ .issue[data-severity='error'] > * {
42
+ border-inline-start-color: var(--astl-danger);
43
+ }
44
+ .issue[data-severity='warning'] > * {
45
+ border-inline-start-color: var(--astl-warning);
46
+ }
47
+ .severity {
48
+ display: inline-flex;
49
+ align-items: center;
50
+ gap: var(--astl-space-1);
51
+ font-weight: 700;
52
+ }
53
+ .issue[data-severity='error'] .severity {
54
+ color: var(--astl-danger);
55
+ }
56
+ .issue[data-severity='warning'] .severity {
57
+ color: var(--astl-warning);
58
+ }
59
+ .message {
60
+ flex: 1 1 12rem;
61
+ min-inline-size: 0;
62
+ }
63
+ `;
64
+
65
+ /**
66
+ * One issue: severity icon + word + message; a button that selects its element when it has one. With the document the
67
+ * issue is about (`source`), the message names components as authors see them, not by id.
68
+ */
69
+ export function renderIssue(
70
+ issue: Issue,
71
+ authoring: Authoring,
72
+ adapter: EditorAdapter | null,
73
+ source?: string,
74
+ ): TemplateResult {
75
+ const target = issueTarget(issue);
76
+ const label = authoring.t(EDITOR_NAMESPACE, `severity.${issue.severity}`);
77
+ const text = authoring.describe(issue, source);
78
+ const content = html`<span class="severity"
79
+ ><svg class="icon" viewBox="0 0 20 20" aria-hidden="true" focusable="false">${SEVERITY_ICONS[issue.severity]}</svg
80
+ >${label}<span class="astl-vh">:</span></span
81
+ >
82
+ <span class="message">${text}</span>`;
83
+ return html`<li class="issue" data-code=${issue.code} data-severity=${issue.severity}>
84
+ ${
85
+ target === null || adapter === null
86
+ ? html`<div class="static">${content}</div>`
87
+ : html`<button type="button" data-target=${target} aria-label=${authoring.t(EDITOR_NAMESPACE, 'label.text', { label, text })} @click=${() => adapter.select(target)}>${content}</button>`
88
+ }
89
+ </li>`;
90
+ }
91
+
92
+ /** A list of issues, or nothing when empty. */
93
+ export function renderIssues(
94
+ issues: readonly Issue[],
95
+ authoring: Authoring,
96
+ adapter: EditorAdapter | null,
97
+ source?: string,
98
+ ): TemplateResult | typeof nothing {
99
+ if (issues.length === 0) return nothing;
100
+ return html`<ul class="issues" role="list">
101
+ ${sortIssues(issues).map((issue) => renderIssue(issue, authoring, adapter, source))}
102
+ </ul>`;
103
+ }
@@ -0,0 +1,89 @@
1
+ import type { Issue } from '@astl/core';
2
+ import { type CSSResultGroup, html, nothing, type PropertyValues, type TemplateResult } from 'lit';
3
+ import { AuthoringElement } from './base.js';
4
+ import { issueStyles, renderIssues } from './issue-list.js';
5
+ import { kitStyles } from './styles.js';
6
+
7
+ /** Validation waits this long after the last change, so typing is not interrupted. */
8
+ export const VALIDATION_DELAY_MS = 300;
9
+
10
+ /**
11
+ * `<astl-issues>`: live validation of the whole document in the UI locale, errors first. Selecting an issue moves the
12
+ * editor's cursor to its element (`adapter.select`).
13
+ */
14
+ export class AstlIssues extends AuthoringElement {
15
+ static override styles: CSSResultGroup = [kitStyles, issueStyles];
16
+
17
+ #issues: readonly Issue[] | null = null;
18
+ /** The source the issues are about. */
19
+ #source = '';
20
+ #timer: ReturnType<typeof setTimeout> | undefined;
21
+
22
+ /** The issues on screen (null before the first validation). */
23
+ get issues(): readonly Issue[] | null {
24
+ return this.#issues;
25
+ }
26
+
27
+ /** Validates now instead of waiting for the debounce. */
28
+ validate(): void {
29
+ clearTimeout(this.#timer);
30
+ this.#timer = undefined;
31
+ this.#check();
32
+ this.requestUpdate();
33
+ }
34
+
35
+ override connectedCallback(): void {
36
+ super.connectedCallback();
37
+ // Back in the document: the source may have changed while we were not listening.
38
+ if (this.hasUpdated) this.validate();
39
+ }
40
+
41
+ override disconnectedCallback(): void {
42
+ super.disconnectedCallback();
43
+ clearTimeout(this.#timer);
44
+ this.#timer = undefined;
45
+ }
46
+
47
+ protected override willUpdate(changed: PropertyValues<this>): void {
48
+ super.willUpdate(changed);
49
+ if (changed.has('authoring') || changed.has('adapter')) this.#check();
50
+ }
51
+
52
+ #check(): void {
53
+ const { authoring, adapter } = this;
54
+ this.#source = adapter?.getSource() ?? '';
55
+ this.#issues = authoring === null || adapter === null ? null : authoring.validate(this.#source).issues;
56
+ }
57
+
58
+ protected override sourceChanged(): void {
59
+ clearTimeout(this.#timer);
60
+ this.#timer = setTimeout(() => this.validate(), VALIDATION_DELAY_MS);
61
+ }
62
+
63
+ protected override selectionChanged(): void {
64
+ // The list does not depend on the cursor.
65
+ }
66
+
67
+ protected override render(): TemplateResult | typeof nothing {
68
+ const { authoring, adapter } = this;
69
+ if (authoring === null) return nothing;
70
+ // Validation is synchronous: no issues means no adapter (no editor yet, or one that failed to load), so there is
71
+ // no document to check and nothing to say.
72
+ const issues = adapter === null ? null : this.#issues;
73
+ const { lang, dir } = this.ui;
74
+ let summary = '';
75
+ if (issues !== null && issues.length === 0) summary = this.t('issues.none');
76
+ else if (issues !== null) {
77
+ const errors = issues.filter((i) => i.severity === 'error').length;
78
+ summary = this.t('issues.summary', {
79
+ errors: this.t('issues.errors', { count: errors }),
80
+ warnings: this.t('issues.warnings', { count: issues.length - errors }),
81
+ });
82
+ }
83
+ return html`<section class="kit" part="root" lang=${lang} dir=${dir} aria-labelledby="title">
84
+ <h2 class="title" id="title" part="title">${this.t('issues.title')}</h2>
85
+ <p class="note summary" role="status" ?hidden=${issues === null}>${summary}</p>
86
+ ${issues === null ? nothing : renderIssues(issues, authoring, adapter, this.#source)}
87
+ </section>`;
88
+ }
89
+ }
@@ -0,0 +1,461 @@
1
+ import { type CSSResultGroup, css, html, nothing, type TemplateResult } from 'lit';
2
+ import { live } from 'lit/directives/live.js';
3
+ import { type PictureFields, pictureSize, refusalOf, type UploadedAsset } from '../authoring.js';
4
+ import { AuthoringElement } from './base.js';
5
+ import { kitStyles } from './styles.js';
6
+
7
+ /** What `ask` opens the dialog with. */
8
+ export interface PictureRequest {
9
+ /** A picture to edit: its address, alt text and size. Absent: a new picture. */
10
+ readonly current?: PictureFields;
11
+ /** A file to upload first (pasted or dropped), through the authoring's `uploadAsset`. */
12
+ readonly file?: File;
13
+ /** Whether to ask for a caption (a new picture). Default: true for a new picture, false for an edit. */
14
+ readonly caption?: boolean;
15
+ /** Whether `current` is decorative; default: when its alt text is empty. */
16
+ readonly decorative?: boolean;
17
+ /** The picture carries the task (a component's): its alt text is required, with no decorative choice. */
18
+ readonly altRequired?: boolean;
19
+ /** The element and attribute the address is for, as the URL policy is asked; default `img` and `src`. */
20
+ readonly target?: { readonly tag: string; readonly attribute: string };
21
+ }
22
+
23
+ /** A message of the kit's catalog, or with `text` a host's own words in its place (`UploadRefused`). */
24
+ type Message = { readonly key: string; readonly error: boolean; readonly text?: string | undefined } | null;
25
+
26
+ /** How long typing in the address pauses before the preview loads it: one request per address, not per keystroke. */
27
+ export const PREVIEW_DELAY_MS = 600;
28
+
29
+ /**
30
+ * `<astl-picture-dialog>`: asks for a picture in a modal dialog: a file, uploaded with the host's `uploadAsset`, one
31
+ * from the host's library (`pickPicture`), or an address (the only way without either, as it says); the alt text,
32
+ * required unless the picture is decorative (`alt=""`); and, for a new picture, an optional caption. The address must
33
+ * pass the authoring's URL policy, an uploaded or picked one too. `ask` resolves with the fields, or null when the
34
+ * author cancels. While the library is open the dialog steps aside: it closes and keeps every field, so a modal of
35
+ * the host's own, outside the top layer, takes the pointer and the keys; it opens again when the library settles.
36
+ */
37
+ export class AstlPictureDialog extends AuthoringElement {
38
+ static override styles: CSSResultGroup = [
39
+ kitStyles,
40
+ css`
41
+ dialog {
42
+ box-sizing: border-box;
43
+ inline-size: min(32rem, calc(100vw - 2 * var(--astl-space-4)));
44
+ max-block-size: calc(100dvh - 2 * var(--astl-space-4));
45
+ padding: var(--astl-space-4);
46
+ border: var(--astl-outline-width) solid var(--astl-outline);
47
+ border-radius: var(--astl-radius-l);
48
+ background: var(--astl-surface);
49
+ color: var(--astl-ink);
50
+ }
51
+ dialog::backdrop {
52
+ background: color-mix(in srgb, var(--astl-ink) 40%, transparent);
53
+ }
54
+ form {
55
+ display: flex;
56
+ flex-direction: column;
57
+ gap: var(--astl-space-3);
58
+ }
59
+ label {
60
+ display: flex;
61
+ flex-direction: column;
62
+ gap: var(--astl-space-1);
63
+ font-weight: 600;
64
+ }
65
+ label input {
66
+ font-weight: 400;
67
+ }
68
+ label.check {
69
+ flex-direction: row;
70
+ align-items: center;
71
+ min-block-size: var(--astl-target-min);
72
+ font-weight: 400;
73
+ }
74
+ .upload {
75
+ display: flex;
76
+ flex-direction: column;
77
+ align-items: flex-start;
78
+ }
79
+ .sources {
80
+ display: flex;
81
+ flex-wrap: wrap;
82
+ gap: var(--astl-space-2);
83
+ }
84
+ .upload :is(.note, .error),
85
+ .messages :is(.note, .error) {
86
+ margin-block-start: var(--astl-space-2);
87
+ }
88
+ .preview {
89
+ display: block;
90
+ max-inline-size: 100%;
91
+ max-block-size: 10rem;
92
+ object-fit: contain;
93
+ align-self: flex-start;
94
+ border: var(--astl-outline-width) solid var(--astl-line);
95
+ }
96
+ .error {
97
+ margin: 0;
98
+ padding: var(--astl-space-2);
99
+ border-inline-start: var(--astl-space-1) solid var(--astl-danger);
100
+ background: var(--astl-danger-soft);
101
+ }
102
+ .actions {
103
+ display: flex;
104
+ flex-wrap: wrap;
105
+ justify-content: flex-end;
106
+ gap: var(--astl-space-2);
107
+ }
108
+ `,
109
+ ];
110
+
111
+ #resolve: ((fields: PictureFields | null) => void) | null = null;
112
+ #editing = false;
113
+ #withCaption = true;
114
+ #altRequired = false;
115
+ #target: { readonly tag: string; readonly attribute: string } = { tag: 'img', attribute: 'src' };
116
+ #src = '';
117
+ #alt = '';
118
+ #decorative = false;
119
+ #caption = '';
120
+ #width: number | undefined;
121
+ #height: number | undefined;
122
+ /** What the last submit found wrong, shown by the buttons. */
123
+ #message: Message = null;
124
+ /** How the upload or the pick goes, shown by their buttons. */
125
+ #uploadMessage: Message = null;
126
+ /** An upload is under way: nothing is inserted before it ends. */
127
+ #busy = false;
128
+ /** The host's library is open: the dialog stepped aside for it, and its close is no cancel. */
129
+ #picking = false;
130
+ /** Bumped by every upload, pick, `ask` and close: an upload or a pick that ends after one is dropped. */
131
+ #generation = 0;
132
+ /** Aborts the upload or the pick under way (its `signal`). */
133
+ #abort: AbortController | null = null;
134
+ /** The address the preview shows: the current one, the uploaded one, or a typed one once typing pauses. */
135
+ #preview = '';
136
+ #previewTimer: ReturnType<typeof setTimeout> | undefined;
137
+
138
+ /** Opens the dialog. Resolves with the picture's fields, or null when the author cancels. */
139
+ async ask(request: PictureRequest = {}): Promise<PictureFields | null> {
140
+ this.#finish(null);
141
+ const current = request.current;
142
+ this.#editing = current !== undefined;
143
+ this.#withCaption = request.caption ?? !this.#editing;
144
+ this.#altRequired = request.altRequired ?? false;
145
+ this.#target = request.target ?? { tag: 'img', attribute: 'src' };
146
+ this.#src = current?.src ?? '';
147
+ this.#alt = current?.alt ?? '';
148
+ this.#decorative = !this.#altRequired && (request.decorative ?? current?.alt === '');
149
+ this.#caption = current?.caption ?? '';
150
+ this.#width = current?.width;
151
+ this.#height = current?.height;
152
+ this.#preview = this.#src;
153
+ this.#message = null;
154
+ this.#uploadMessage = null;
155
+ this.#stop();
156
+ this.requestUpdate();
157
+ await this.updateComplete;
158
+ const result = new Promise<PictureFields | null>((resolve) => {
159
+ this.#resolve = resolve;
160
+ });
161
+ this.#dialog()?.showModal();
162
+ if (request.file !== undefined) void this.#upload(request.file);
163
+ return result;
164
+ }
165
+
166
+ override disconnectedCallback(): void {
167
+ super.disconnectedCallback();
168
+ // Out of the document the dialog is out of the top layer, and a pick that ends later could not open it again.
169
+ this.#finish(null);
170
+ }
171
+
172
+ #dialog(): HTMLDialogElement | null {
173
+ return this.renderRoot.querySelector('dialog');
174
+ }
175
+
176
+ #finish(fields: PictureFields | null): void {
177
+ const resolve = this.#resolve;
178
+ this.#resolve = null;
179
+ clearTimeout(this.#previewTimer);
180
+ this.#stop();
181
+ const dialog = this.#dialog();
182
+ if (dialog?.open) dialog.close();
183
+ resolve?.(fields);
184
+ }
185
+
186
+ /** Aborts the upload or the pick under way and drops its result. */
187
+ #stop(): void {
188
+ this.#abort?.abort();
189
+ this.#abort = null;
190
+ this.#generation++;
191
+ this.#busy = false;
192
+ this.#picking = false;
193
+ }
194
+
195
+ #allowed(src: string): boolean {
196
+ const policy = this.authoring?.urlPolicy;
197
+ return src.trim() !== '' && policy !== undefined && policy(src, this.#target);
198
+ }
199
+
200
+ /** Takes an uploaded or picked picture when the URL policy allows its address: the address, the preview, the size. */
201
+ #take(asset: UploadedAsset): boolean {
202
+ const src = typeof asset?.src === 'string' ? asset.src.trim() : '';
203
+ if (!this.#allowed(src)) return false;
204
+ this.#src = src;
205
+ this.#preview = src;
206
+ this.#width = pictureSize(asset.width);
207
+ this.#height = pictureSize(asset.height);
208
+ return true;
209
+ }
210
+
211
+ async #upload(file: File): Promise<void> {
212
+ const upload = this.authoring?.uploadAsset ?? null;
213
+ if (upload === null) return;
214
+ this.#stop();
215
+ const id = this.#generation;
216
+ const abort = new AbortController();
217
+ this.#abort = abort;
218
+ this.#busy = true;
219
+ this.#uploadMessage = { key: 'picture.uploading', error: false };
220
+ this.requestUpdate();
221
+ let message: Message;
222
+ try {
223
+ const asset = await upload(file, { signal: abort.signal });
224
+ if (id !== this.#generation) return;
225
+ message = this.#take(asset)
226
+ ? { key: 'picture.uploaded', error: false }
227
+ : { key: 'picture.uploadBlocked', error: true };
228
+ } catch (error) {
229
+ if (id !== this.#generation) return;
230
+ message = { key: 'picture.uploadFailed', error: true, text: refusalOf(error) };
231
+ }
232
+ this.#abort = null;
233
+ this.#busy = false;
234
+ this.#uploadMessage = message;
235
+ this.requestUpdate();
236
+ }
237
+
238
+ /**
239
+ * Opens the host's library (`pickPicture`), stopping the upload under way. The dialog steps aside meanwhile: closed,
240
+ * every field kept, so a modal of the host's own takes the pointer and the keys. When the library settles, the
241
+ * dialog opens again with what it gave (unless the ask ended meanwhile), and the focus goes to the alt text after a
242
+ * picture (to Insert or Save for a decorative one), else back to the library's button.
243
+ */
244
+ async #pick(): Promise<void> {
245
+ const pick = this.authoring?.pickPicture ?? null;
246
+ const dialog = this.#dialog();
247
+ if (pick === null || dialog === null || !dialog.open) return;
248
+ this.#stop();
249
+ const id = this.#generation;
250
+ const abort = new AbortController();
251
+ this.#abort = abort;
252
+ this.#picking = true;
253
+ // What the buttons said was about an earlier upload or pick.
254
+ this.#uploadMessage = null;
255
+ dialog.close();
256
+ let message: Message = null;
257
+ let picked = false;
258
+ try {
259
+ const asset = await pick({ signal: abort.signal });
260
+ if (id !== this.#generation) return;
261
+ // Null: the author closed the library, and nothing changes.
262
+ if (asset != null) {
263
+ picked = this.#take(asset);
264
+ message = picked
265
+ ? { key: 'picture.picked', error: false }
266
+ : { key: 'picture.pickBlocked', error: true };
267
+ }
268
+ } catch (error) {
269
+ if (id !== this.#generation) return;
270
+ message = { key: 'picture.pickFailed', error: true, text: refusalOf(error) };
271
+ }
272
+ this.#abort = null;
273
+ // The fields render before the dialog opens again; the message after, so its live region changes in sight.
274
+ this.requestUpdate();
275
+ await this.updateComplete;
276
+ if (id !== this.#generation) return;
277
+ // Gone with the authoring meanwhile: nothing to open again.
278
+ const shown = this.#dialog();
279
+ if (shown === null) {
280
+ this.#finish(null);
281
+ return;
282
+ }
283
+ this.#picking = false;
284
+ shown.showModal();
285
+ const next = picked ? (this.#decorative ? 'button[type="submit"]' : '#alt') : '[data-library]';
286
+ this.renderRoot.querySelector<HTMLElement>(next)?.focus();
287
+ this.#uploadMessage = message;
288
+ this.requestUpdate();
289
+ }
290
+
291
+ /** A polite status, or an alert for an error: both regions are always there, so screen readers hear the change. */
292
+ #live(message: Message): TemplateResult {
293
+ const said = message === null ? '' : (message.text ?? this.t(message.key));
294
+ return html`<div role="status">${message !== null && !message.error ? html`<p class="note">${said}</p>` : nothing}</div>
295
+ <div role="alert">${message?.error ? html`<p class="error">${said}</p>` : nothing}</div>`;
296
+ }
297
+
298
+ #submit(event: Event): void {
299
+ event.preventDefault();
300
+ if (this.#busy) return;
301
+ const src = this.#src.trim();
302
+ const alt = this.#alt.trim();
303
+ if (src === '') this.#message = { key: 'picture.srcMissing', error: true };
304
+ else if (!this.#allowed(src)) this.#message = { key: 'picture.srcBlocked', error: true };
305
+ else if (!this.#decorative && alt === '') {
306
+ this.#message = { key: this.#altRequired ? 'picture.altRequired' : 'picture.altMissing', error: true };
307
+ } else {
308
+ const caption = this.#withCaption ? this.#caption.trim() : '';
309
+ this.#finish({
310
+ src,
311
+ alt: this.#decorative ? '' : alt,
312
+ ...(this.#width === undefined ? {} : { width: this.#width }),
313
+ ...(this.#height === undefined ? {} : { height: this.#height }),
314
+ ...(caption === '' ? {} : { caption }),
315
+ });
316
+ return;
317
+ }
318
+ this.requestUpdate();
319
+ }
320
+
321
+ protected override render(): TemplateResult | typeof nothing {
322
+ if (this.authoring === null) return nothing;
323
+ const { lang, dir } = this.ui;
324
+ const upload = this.authoring.uploadAsset !== null;
325
+ const library = this.authoring.pickPicture !== null;
326
+ const message = this.#message;
327
+ return html`<dialog
328
+ part="dialog"
329
+ lang=${lang}
330
+ dir=${dir}
331
+ aria-labelledby="picture-title"
332
+ @close=${() => {
333
+ // Escape, or a close the page made. The event comes a task later: a dialog opened again since stays, and one
334
+ // that stepped aside for the host's library still asks.
335
+ if (!this.#picking && !this.#dialog()?.open) this.#finish(null);
336
+ }}
337
+ >
338
+ <form @submit=${(event: Event) => this.#submit(event)} novalidate>
339
+ <h2 class="title" id="picture-title">${this.t(this.#editing ? 'picture.editTitle' : 'picture.title')}</h2>
340
+ ${
341
+ upload || library
342
+ ? html`<div class="upload">
343
+ <div class="sources">
344
+ ${
345
+ upload
346
+ ? html`<button
347
+ type="button"
348
+ part="button"
349
+ ?disabled=${this.#busy}
350
+ @click=${() => this.renderRoot.querySelector<HTMLInputElement>('input[type="file"]')?.click()}
351
+ >
352
+ ${this.t('picture.file')}
353
+ </button>`
354
+ : nothing
355
+ }
356
+ ${
357
+ library
358
+ ? html`<button type="button" part="button" data-library @click=${() => void this.#pick()}>
359
+ ${this.t('picture.library')}
360
+ </button>`
361
+ : nothing
362
+ }
363
+ </div>
364
+ ${
365
+ upload
366
+ ? html`<input
367
+ type="file"
368
+ accept="image/*"
369
+ hidden
370
+ @change=${(event: Event) => {
371
+ const input = event.target as HTMLInputElement;
372
+ const file = input.files?.[0];
373
+ // Picking the same file again uploads it again.
374
+ input.value = '';
375
+ if (file !== undefined) void this.#upload(file);
376
+ }}
377
+ />`
378
+ : nothing
379
+ }
380
+ ${this.#live(this.#uploadMessage)}
381
+ </div>`
382
+ : html`<p class="note">${this.t('picture.urlOnly')}</p>`
383
+ }
384
+ <label>
385
+ ${this.t('picture.src')}
386
+ <input
387
+ type="url"
388
+ inputmode="url"
389
+ autocomplete="off"
390
+ .value=${live(this.#src)}
391
+ @input=${(event: Event) => {
392
+ this.#src = (event.target as HTMLInputElement).value;
393
+ this.#width = undefined;
394
+ this.#height = undefined;
395
+ clearTimeout(this.#previewTimer);
396
+ this.#previewTimer = setTimeout(() => {
397
+ this.#preview = this.#src.trim();
398
+ this.requestUpdate();
399
+ }, PREVIEW_DELAY_MS);
400
+ }}
401
+ />
402
+ </label>
403
+ ${
404
+ this.#allowed(this.#preview)
405
+ ? html`<img class="preview" src=${this.#preview} alt="" referrerpolicy="no-referrer" />`
406
+ : nothing
407
+ }
408
+ <label>
409
+ ${this.t('picture.alt')}
410
+ <input
411
+ type="text"
412
+ id="alt"
413
+ aria-describedby="alt-help"
414
+ .value=${live(this.#alt)}
415
+ ?disabled=${this.#decorative}
416
+ @input=${(event: Event) => {
417
+ this.#alt = (event.target as HTMLInputElement).value;
418
+ }}
419
+ />
420
+ </label>
421
+ <p class="note" id="alt-help">${this.t('picture.altHelp')}</p>
422
+ ${
423
+ this.#altRequired
424
+ ? nothing
425
+ : html`<label class="check">
426
+ <input
427
+ type="checkbox"
428
+ .checked=${this.#decorative}
429
+ @change=${(event: Event) => {
430
+ this.#decorative = (event.target as HTMLInputElement).checked;
431
+ this.requestUpdate();
432
+ }}
433
+ />
434
+ ${this.t('picture.decorative')}
435
+ </label>`
436
+ }
437
+ ${
438
+ this.#withCaption
439
+ ? html`<label>
440
+ ${this.t('picture.caption')}
441
+ <input
442
+ type="text"
443
+ .value=${live(this.#caption)}
444
+ @input=${(event: Event) => {
445
+ this.#caption = (event.target as HTMLInputElement).value;
446
+ }}
447
+ />
448
+ </label>`
449
+ : nothing
450
+ }
451
+ <div class="messages">${this.#live(message)}</div>
452
+ <div class="actions">
453
+ <button type="button" part="button" @click=${() => this.#finish(null)}>${this.t('picture.cancel')}</button>
454
+ <button type="submit" class="primary" part="button" ?disabled=${this.#busy}>
455
+ ${this.t(this.#editing ? 'picture.save' : 'picture.insert')}
456
+ </button>
457
+ </div>
458
+ </form>
459
+ </dialog>`;
460
+ }
461
+ }