@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,770 @@
1
+ import type { MessageParams } from '@astl/core';
2
+ import { PALETTE } from '@astl/tokens';
3
+ import {
4
+ type CSSResultGroup,
5
+ css,
6
+ html,
7
+ LitElement,
8
+ nothing,
9
+ type PropertyDeclarations,
10
+ type PropertyValues,
11
+ type SVGTemplateResult,
12
+ svg,
13
+ type TemplateResult,
14
+ } from 'lit';
15
+ import { type Authoring, refusalOf, type UploadedAsset } from '../authoring.js';
16
+ import type { InspectorChange } from '../edit.js';
17
+ import type {
18
+ PicturePointModel,
19
+ PicturePointsFieldModel,
20
+ PictureRegionModel,
21
+ PictureRegionsFieldModel,
22
+ } from '../inspect.js';
23
+ import { EDITOR_NAMESPACE } from '../messages.js';
24
+ import { kitStyles } from './styles.js';
25
+
26
+ /** Fired with a FieldChange for the inspector to apply. */
27
+ export const FIELD_CHANGE = 'astl-field-change';
28
+
29
+ /** A change of the field, and the source id of the element it is for (an upload may end after the cursor moved). */
30
+ export interface FieldChange {
31
+ readonly change: InspectorChange;
32
+ readonly element: string | null;
33
+ }
34
+
35
+ type Field = PictureRegionsFieldModel | PicturePointsFieldModel;
36
+ type Shape = PictureRegionModel['shape'];
37
+ /** What the field says of its upload or pick: a key of the kit's catalog, or a host's own words (`UploadRefused`). */
38
+ type Status = { readonly key: string; readonly error: boolean; readonly text?: string | undefined };
39
+
40
+ const round = (n: number) => Math.round(Math.min(100, Math.max(0, n)) * 10) / 10;
41
+ const num = (n: number) => String(round(n));
42
+ /** Most zones, pins or polygon points the field lists (and polygons take): more are edited in the source. */
43
+ const MAX_LISTED = 64;
44
+ /** Palette slot of the n-th item (from 0), as a class: `c1` to `c8`. */
45
+ const slot = (index: number) => `c${(index % PALETTE.length) + 1}`;
46
+
47
+ /** The attributes that describe a zone of `shape` around the zone's centre: switching the shape keeps the centre. */
48
+ function reshaped(region: PictureRegionModel, shape: Shape): Record<string, string | null> {
49
+ const box = boundsOf(region);
50
+ const cx = (box.left + box.right) / 2;
51
+ const cy = (box.top + box.bottom) / 2;
52
+ const w = Math.max(1, box.right - box.left);
53
+ const h = Math.max(1, box.bottom - box.top);
54
+ const cleared = { x: null, y: null, width: null, height: null, r: null, points: null };
55
+ if (shape === 'circle') return { ...cleared, shape, x: num(cx), y: num(cy), r: num(w / 2) };
56
+ if (shape === 'polygon') {
57
+ const points = [
58
+ [box.left, box.top],
59
+ [box.right, box.top],
60
+ [box.right, box.bottom],
61
+ [box.left, box.bottom],
62
+ ];
63
+ return { ...cleared, shape, points: points.map(([x = 0, y = 0]) => `${num(x)},${num(y)}`).join(' ') };
64
+ }
65
+ return { ...cleared, shape, x: num(cx - w / 2), y: num(cy - h / 2), width: num(w), height: num(h) };
66
+ }
67
+
68
+ /** A zone's bounding box in percent. */
69
+ function boundsOf(region: PictureRegionModel): { left: number; top: number; right: number; bottom: number } {
70
+ if (region.shape === 'circle') {
71
+ return {
72
+ left: region.x - region.r,
73
+ top: region.y - region.r,
74
+ right: region.x + region.r,
75
+ bottom: region.y + region.r,
76
+ };
77
+ }
78
+ if (region.shape === 'polygon' && region.points.length > 0) {
79
+ // A loop, not Math.min(...xs): a polygon of any size never overflows the call stack.
80
+ const box = { left: 100, top: 100, right: 0, bottom: 0 };
81
+ for (const [x, y] of region.points) {
82
+ box.left = Math.min(box.left, x);
83
+ box.top = Math.min(box.top, y);
84
+ box.right = Math.max(box.right, x);
85
+ box.bottom = Math.max(box.bottom, y);
86
+ }
87
+ return box;
88
+ }
89
+ return { left: region.x, top: region.y, right: region.x + region.width, bottom: region.y + region.height };
90
+ }
91
+
92
+ /** Where a zone's number sits: its centre. */
93
+ function anchorOf(region: PictureRegionModel): readonly [number, number] {
94
+ const box = boundsOf(region);
95
+ return [(box.left + box.right) / 2, (box.top + box.bottom) / 2];
96
+ }
97
+
98
+ /**
99
+ * `<astl-picture-field>`: the inspector's `picture-regions` and `picture-points` fields. The picture (by address,
100
+ * uploaded with the host's `uploadAsset` or chosen from its library, `pickPicture`) with its zones or pins drawn on
101
+ * it in palette colours and numbered; drag on it to draw a zone, click to place a pin; and every value in number
102
+ * fields, so nothing needs a pointer. Changes go to the inspector as `astl-field-change` events.
103
+ */
104
+ export class AstlPictureField extends LitElement {
105
+ static override properties: PropertyDeclarations = {
106
+ field: { attribute: false },
107
+ authoring: { attribute: false },
108
+ element: { attribute: false },
109
+ };
110
+
111
+ static override styles: CSSResultGroup = [
112
+ kitStyles,
113
+ css`
114
+ fieldset {
115
+ display: flex;
116
+ flex-direction: column;
117
+ gap: var(--astl-space-3);
118
+ min-inline-size: 0;
119
+ margin: 0;
120
+ padding: var(--astl-space-3);
121
+ border: var(--astl-outline-width) solid var(--astl-line);
122
+ border-radius: var(--astl-radius-m);
123
+ }
124
+ legend {
125
+ padding-inline: var(--astl-space-1);
126
+ font-weight: 600;
127
+ }
128
+ label {
129
+ display: flex;
130
+ flex-direction: column;
131
+ gap: var(--astl-space-1);
132
+ }
133
+ .canvas {
134
+ position: relative;
135
+ inline-size: 100%;
136
+ touch-action: none;
137
+ cursor: crosshair;
138
+ user-select: none;
139
+ border: var(--astl-outline-width) solid var(--astl-line);
140
+ background: var(--astl-surface-raised);
141
+ }
142
+ .canvas img {
143
+ display: block;
144
+ inline-size: 100%;
145
+ block-size: auto;
146
+ }
147
+ .canvas .blank {
148
+ aspect-ratio: 4 / 3;
149
+ }
150
+ .canvas svg {
151
+ position: absolute;
152
+ inset: 0;
153
+ inline-size: 100%;
154
+ block-size: 100%;
155
+ overflow: visible;
156
+ }
157
+ .shape {
158
+ fill: var(--soft);
159
+ fill-opacity: 0.4;
160
+ stroke: var(--line);
161
+ stroke-width: 2;
162
+ vector-effect: non-scaling-stroke;
163
+ }
164
+ .shape.unflagged {
165
+ fill-opacity: 0.15;
166
+ stroke-dasharray: 6 4;
167
+ }
168
+ .draft {
169
+ fill: none;
170
+ stroke: var(--astl-ink);
171
+ stroke-width: 2;
172
+ stroke-dasharray: 4 3;
173
+ vector-effect: non-scaling-stroke;
174
+ }
175
+ .badge {
176
+ position: absolute;
177
+ inset-inline-start: var(--x);
178
+ inset-block-start: var(--y);
179
+ transform: translate(-50%, -50%);
180
+ display: inline-flex;
181
+ align-items: center;
182
+ justify-content: center;
183
+ box-sizing: border-box;
184
+ min-inline-size: 1.5rem;
185
+ block-size: 1.5rem;
186
+ padding-inline: var(--astl-space-1);
187
+ border: var(--astl-outline-width) solid var(--line);
188
+ border-radius: 999px;
189
+ background: var(--astl-surface);
190
+ color: var(--astl-ink);
191
+ font-size: var(--astl-size-small);
192
+ font-weight: 700;
193
+ pointer-events: none;
194
+ }
195
+ .pin {
196
+ border-width: calc(2 * var(--astl-outline-width));
197
+ }
198
+ .swatch {
199
+ display: inline-flex;
200
+ align-items: center;
201
+ justify-content: center;
202
+ min-inline-size: 1.5rem;
203
+ block-size: 1.5rem;
204
+ margin-inline-end: var(--astl-space-2);
205
+ border: calc(2 * var(--astl-outline-width)) solid var(--line);
206
+ border-radius: 999px;
207
+ background: var(--soft);
208
+ font-weight: 700;
209
+ }
210
+ .items {
211
+ display: flex;
212
+ flex-direction: column;
213
+ gap: var(--astl-space-3);
214
+ margin: 0;
215
+ padding: 0;
216
+ list-style: none;
217
+ }
218
+ .numbers {
219
+ display: grid;
220
+ grid-template-columns: repeat(auto-fill, minmax(7rem, 1fr));
221
+ gap: var(--astl-space-2);
222
+ }
223
+ .numbers label {
224
+ justify-content: flex-end;
225
+ }
226
+ .upload {
227
+ display: flex;
228
+ flex-direction: column;
229
+ align-items: flex-start;
230
+ }
231
+ .upload :is(.note, .error) {
232
+ margin-block-start: var(--astl-space-2);
233
+ }
234
+ .sources {
235
+ display: flex;
236
+ flex-wrap: wrap;
237
+ gap: var(--astl-space-2);
238
+ }
239
+ .error {
240
+ padding: var(--astl-space-2);
241
+ border-inline-start: var(--astl-space-1) solid var(--astl-danger);
242
+ background: var(--astl-danger-soft);
243
+ }
244
+ .vertex {
245
+ display: flex;
246
+ flex-wrap: wrap;
247
+ align-items: flex-end;
248
+ gap: var(--astl-space-2);
249
+ }
250
+ .vertex label {
251
+ flex: 1 1 6rem;
252
+ }
253
+ .c1 { --line: var(--astl-palette-1); --soft: var(--astl-palette-1-soft); }
254
+ .c2 { --line: var(--astl-palette-2); --soft: var(--astl-palette-2-soft); }
255
+ .c3 { --line: var(--astl-palette-3); --soft: var(--astl-palette-3-soft); }
256
+ .c4 { --line: var(--astl-palette-4); --soft: var(--astl-palette-4-soft); }
257
+ .c5 { --line: var(--astl-palette-5); --soft: var(--astl-palette-5-soft); }
258
+ .c6 { --line: var(--astl-palette-6); --soft: var(--astl-palette-6-soft); }
259
+ .c7 { --line: var(--astl-palette-7); --soft: var(--astl-palette-7-soft); }
260
+ .c8 { --line: var(--astl-palette-8); --soft: var(--astl-palette-8-soft); }
261
+ @media (forced-colors: active) {
262
+ .shape {
263
+ fill: none;
264
+ stroke: CanvasText;
265
+ }
266
+ .badge,
267
+ .swatch {
268
+ border-color: CanvasText;
269
+ }
270
+ }
271
+ `,
272
+ ];
273
+
274
+ declare field: Field | null;
275
+ declare authoring: Authoring | null;
276
+ /** The source id of the element the field belongs to (the inspector sets it). */
277
+ declare element: string | null;
278
+
279
+ /** A zone being drawn: where the pointer went down and where it is, in percent. */
280
+ #draft: { readonly x0: number; readonly y0: number; x1: number; y1: number } | null = null;
281
+ /** Width over height of the picture (1 until it loads), so circles stay round. */
282
+ #aspect = 1;
283
+ #status: Status | null = null;
284
+ /** Aborts the upload or the pick under way (its `signal`). */
285
+ #abort: AbortController | null = null;
286
+
287
+ constructor() {
288
+ super();
289
+ this.field = null;
290
+ this.authoring = null;
291
+ this.element = null;
292
+ }
293
+
294
+ protected override willUpdate(changed: PropertyValues<this>): void {
295
+ // Another element's field: an upload message was about the one before.
296
+ if (changed.has('element') && changed.get('element') !== undefined) this.#status = null;
297
+ }
298
+
299
+ #t(key: string, params?: MessageParams): string {
300
+ return this.authoring?.t(EDITOR_NAMESPACE, key, params) ?? key;
301
+ }
302
+
303
+ #change(change: InspectorChange, element: string | null = this.element): void {
304
+ this.dispatchEvent(new CustomEvent<FieldChange>(FIELD_CHANGE, { detail: { change, element } }));
305
+ }
306
+
307
+ /** Whether the URL policy allows the picture, asked as the engine and the player ask it: the element's attribute. */
308
+ #allowed(field: Field, src: string): boolean {
309
+ const context = { tag: field.elementTag, attribute: field.srcAttribute };
310
+ return src.trim() !== '' && (this.authoring?.urlPolicy(src, context) ?? false);
311
+ }
312
+
313
+ /** A fresh local id for a new child: `<tag without astl->-<n>`. */
314
+ #freshId(field: Field): string {
315
+ const taken = new Set(
316
+ field.kind === 'picture-points' ? field.points.map((p) => p.id) : field.regions.map((r) => r.id),
317
+ );
318
+ const prefix = field.tag.replace(/^astl-/, '');
319
+ let n = 1;
320
+ while (taken.has(`${prefix}-${n}`)) n++;
321
+ return `${prefix}-${n}`;
322
+ }
323
+
324
+ #add(field: Field, at?: { x: number; y: number; width?: number; height?: number }): void {
325
+ const id = this.#freshId(field);
326
+ if (field.kind === 'picture-points') {
327
+ const label = this.#t('field.point', { n: field.points.length + 1 });
328
+ this.#change({
329
+ kind: 'child-add',
330
+ tag: field.tag,
331
+ attributes: { id, x: num(at?.x ?? 50), y: num(at?.y ?? 50), label },
332
+ });
333
+ return;
334
+ }
335
+ const width = at?.width ?? 20;
336
+ const height = at?.height ?? 20;
337
+ const x = at === undefined ? 10 : at.x;
338
+ const y = at === undefined ? 10 : at.y;
339
+ // A zone that takes no other shape is written without one.
340
+ const shape: Record<string, string> = field.shapes.length > 1 ? { shape: 'rect' } : {};
341
+ this.#change({
342
+ kind: 'child-add',
343
+ tag: field.tag,
344
+ attributes: { id, ...shape, x: num(x), y: num(y), width: num(width), height: num(height) },
345
+ });
346
+ }
347
+
348
+ /** Writes the address of an uploaded or picked picture into the field's attribute of `element`, if the policy allows. */
349
+ #write(field: Field, asset: UploadedAsset, element: string | null): boolean {
350
+ const src = typeof asset?.src === 'string' ? asset.src.trim() : '';
351
+ if (!this.#allowed(field, src)) return false;
352
+ this.#change({ kind: 'attribute', name: field.srcAttribute, value: src }, element);
353
+ return true;
354
+ }
355
+
356
+ async #upload(field: Field, file: File): Promise<void> {
357
+ const upload = this.authoring?.uploadAsset ?? null;
358
+ if (upload === null) return;
359
+ // The address goes to the element of this field, wherever the cursor is when the upload ends.
360
+ const element = this.element;
361
+ // Another upload or pick replaces this upload.
362
+ this.#abort?.abort();
363
+ const abort = new AbortController();
364
+ this.#abort = abort;
365
+ this.#status = { key: 'picture.uploading', error: false };
366
+ this.requestUpdate();
367
+ let status: Status;
368
+ try {
369
+ const asset = await upload(file, { signal: abort.signal });
370
+ if (abort.signal.aborted) return;
371
+ status = this.#write(field, asset, element)
372
+ ? { key: 'picture.uploaded', error: false }
373
+ : { key: 'picture.uploadBlocked', error: true };
374
+ } catch (error) {
375
+ if (abort.signal.aborted) return;
376
+ status = { key: 'picture.uploadFailed', error: true, text: refusalOf(error) };
377
+ }
378
+ this.#abort = null;
379
+ // Said where it happened only: the field may show another element by now.
380
+ this.#status = this.element === element ? status : null;
381
+ this.requestUpdate();
382
+ }
383
+
384
+ /** Opens the host's library (`pickPicture`) and writes the address it gives, as an upload does. */
385
+ async #pick(field: Field): Promise<void> {
386
+ const pick = this.authoring?.pickPicture ?? null;
387
+ if (pick === null) return;
388
+ const element = this.element;
389
+ // Another upload or pick replaces this pick.
390
+ this.#abort?.abort();
391
+ const abort = new AbortController();
392
+ this.#abort = abort;
393
+ // What the field said was about an earlier upload or pick.
394
+ this.#status = null;
395
+ this.requestUpdate();
396
+ let status: Status | null = null;
397
+ try {
398
+ const asset = await pick({ signal: abort.signal });
399
+ if (abort.signal.aborted) return;
400
+ // Null: the author closed the library, and nothing changes.
401
+ if (asset != null) {
402
+ status = this.#write(field, asset, element)
403
+ ? { key: 'picture.picked', error: false }
404
+ : { key: 'picture.pickBlocked', error: true };
405
+ }
406
+ } catch (error) {
407
+ if (abort.signal.aborted) return;
408
+ status = { key: 'picture.pickFailed', error: true, text: refusalOf(error) };
409
+ }
410
+ this.#abort = null;
411
+ this.#status = this.element === element ? status : null;
412
+ this.requestUpdate();
413
+ // The focus goes back to the library's button, as the dialog gives it back: a host's modal restoring its own
414
+ // cannot see into this shadow root, and the author's place would be lost.
415
+ await this.updateComplete;
416
+ if (this.isConnected) this.renderRoot.querySelector<HTMLElement>('[data-library]')?.focus();
417
+ }
418
+
419
+ /** Pointer position in percent of the picture: the canvas inside its border. */
420
+ #at(event: PointerEvent): { x: number; y: number } {
421
+ const canvas = event.currentTarget as HTMLElement;
422
+ const box = canvas.getBoundingClientRect();
423
+ return {
424
+ x: round(((event.clientX - box.left - canvas.clientLeft) / Math.max(1, canvas.clientWidth)) * 100),
425
+ y: round(((event.clientY - box.top - canvas.clientTop) / Math.max(1, canvas.clientHeight)) * 100),
426
+ };
427
+ }
428
+
429
+ #down(event: PointerEvent): void {
430
+ if (event.button !== 0) return;
431
+ const { x, y } = this.#at(event);
432
+ (event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
433
+ this.#draft = { x0: x, y0: y, x1: x, y1: y };
434
+ }
435
+
436
+ #move(event: PointerEvent): void {
437
+ if (this.#draft === null) return;
438
+ const { x, y } = this.#at(event);
439
+ this.#draft.x1 = x;
440
+ this.#draft.y1 = y;
441
+ this.requestUpdate();
442
+ }
443
+
444
+ #up(field: Field, event: PointerEvent): void {
445
+ const draft = this.#draft;
446
+ this.#draft = null;
447
+ if (draft === null) return;
448
+ const { x, y } = this.#at(event);
449
+ if (field.kind === 'picture-points') {
450
+ this.#add(field, { x, y });
451
+ return;
452
+ }
453
+ const width = Math.abs(x - draft.x0);
454
+ const height = Math.abs(y - draft.y0);
455
+ // A click without a drag: a small zone around it.
456
+ if (width < 2 && height < 2)
457
+ this.#add(field, { x: draft.x0 - 5, y: draft.y0 - 5, width: 10, height: 10 });
458
+ else this.#add(field, { x: Math.min(x, draft.x0), y: Math.min(y, draft.y0), width, height });
459
+ this.requestUpdate();
460
+ }
461
+
462
+ /** A zone in its palette colour: solid, or dashed without the field's flag (a wrong place among right ones). */
463
+ #shape(field: PictureRegionsFieldModel, region: PictureRegionModel): SVGTemplateResult {
464
+ const unflagged = field.flag !== null && !region.flagged;
465
+ const cls = `shape ${slot(region.index)}${unflagged ? ' unflagged' : ''}`;
466
+ if (region.shape === 'circle') {
467
+ return svg`<ellipse class=${cls} cx=${region.x} cy=${region.y} rx=${region.r} ry=${region.r * this.#aspect}></ellipse>`;
468
+ }
469
+ if (region.shape === 'polygon') {
470
+ return svg`<polygon class=${cls} points=${region.points.map(([x, y]) => `${x},${y}`).join(' ')}></polygon>`;
471
+ }
472
+ return svg`<rect class=${cls} x=${region.x} y=${region.y} width=${region.width} height=${region.height}></rect>`;
473
+ }
474
+
475
+ #badge(index: number, [x, y]: readonly [number, number], pin: boolean): TemplateResult {
476
+ return html`<span
477
+ class="badge ${pin ? 'pin ' : ''}${slot(index)}"
478
+ aria-hidden="true"
479
+ data-x=${x}
480
+ data-y=${y}
481
+ >${index + 1}</span
482
+ >`;
483
+ }
484
+
485
+ protected override updated(changed: PropertyValues<this>): void {
486
+ super.updated(changed);
487
+ // Badges are placed through the CSSOM: a strict Content Security Policy blocks a style attribute, which Lit's
488
+ // styleMap writes on its first render.
489
+ for (const badge of this.renderRoot.querySelectorAll<HTMLElement>('.badge')) {
490
+ badge.style.setProperty('--x', `${badge.dataset.x}%`);
491
+ badge.style.setProperty('--y', `${badge.dataset.y}%`);
492
+ }
493
+ }
494
+
495
+ #canvas(field: Field): TemplateResult {
496
+ const draft = this.#draft;
497
+ const shown = this.#allowed(field, field.src);
498
+ const shapes = field.kind === 'picture-regions' ? field.regions.map((r) => this.#shape(field, r)) : [];
499
+ const badges =
500
+ field.kind === 'picture-regions'
501
+ ? field.regions.map((r) => this.#badge(r.index, anchorOf(r), false))
502
+ : field.points.map((p) => this.#badge(p.index, [p.x, p.y], true));
503
+ return html`<div
504
+ class="canvas"
505
+ dir="ltr"
506
+ @pointerdown=${(event: PointerEvent) => this.#down(event)}
507
+ @pointermove=${(event: PointerEvent) => this.#move(event)}
508
+ @pointerup=${(event: PointerEvent) => this.#up(field, event)}
509
+ @pointercancel=${() => {
510
+ this.#draft = null;
511
+ this.requestUpdate();
512
+ }}
513
+ >
514
+ ${
515
+ shown
516
+ ? html`<img
517
+ src=${field.src}
518
+ alt=""
519
+ referrerpolicy="no-referrer"
520
+ draggable="false"
521
+ @load=${(event: Event) => {
522
+ const img = event.target as HTMLImageElement;
523
+ if (img.naturalHeight > 0) this.#aspect = img.naturalWidth / img.naturalHeight;
524
+ this.requestUpdate();
525
+ }}
526
+ />`
527
+ : html`<div class="blank"></div>`
528
+ }
529
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true" focusable="false">
530
+ ${shapes}
531
+ ${
532
+ draft === null || field.kind === 'picture-points'
533
+ ? nothing
534
+ : svg`<rect class="draft" x=${Math.min(draft.x0, draft.x1)} y=${Math.min(draft.y0, draft.y1)}
535
+ width=${Math.abs(draft.x1 - draft.x0)} height=${Math.abs(draft.y1 - draft.y0)}></rect>`
536
+ }
537
+ </svg>
538
+ ${badges}
539
+ </div>`;
540
+ }
541
+
542
+ /** Says that only the first items are listed, when there are more. */
543
+ #more(count: number): TemplateResult | typeof nothing {
544
+ return count > MAX_LISTED
545
+ ? html`<p class="note">${this.#t('field.more', { shown: MAX_LISTED, count })}</p>`
546
+ : nothing;
547
+ }
548
+
549
+ #number(label: string, value: number, commit: (value: string) => void): TemplateResult {
550
+ return html`<label>
551
+ ${label}
552
+ <input
553
+ type="number"
554
+ min="0"
555
+ max="100"
556
+ step="0.1"
557
+ .value=${num(value)}
558
+ @change=${(event: Event) => {
559
+ const raw = (event.target as HTMLInputElement).value;
560
+ if (raw !== '' && Number.isFinite(Number(raw))) commit(num(Number(raw)));
561
+ }}
562
+ />
563
+ </label>`;
564
+ }
565
+
566
+ #labelField(field: Field, index: number, value: string): TemplateResult {
567
+ const optional = field.kind === 'picture-regions';
568
+ return html`<label>
569
+ ${this.#t(optional ? 'field.label.optional' : 'field.label')}
570
+ <input
571
+ type="text"
572
+ dir="auto"
573
+ .value=${value}
574
+ @change=${(event: Event) => {
575
+ const text = (event.target as HTMLInputElement).value.trim();
576
+ this.#change({
577
+ kind: 'child-attributes',
578
+ tag: field.tag,
579
+ index,
580
+ attributes: { label: text === '' && optional ? null : text },
581
+ });
582
+ }}
583
+ />
584
+ </label>`;
585
+ }
586
+
587
+ #region(field: PictureRegionsFieldModel, region: PictureRegionModel): TemplateResult {
588
+ const n = region.index + 1;
589
+ const set = (attributes: Record<string, string | null>) =>
590
+ this.#change({ kind: 'child-attributes', tag: field.tag, index: region.index, attributes });
591
+ const points = region.points;
592
+ const setPoints = (next: readonly (readonly [number, number])[]) =>
593
+ set({ points: next.map(([x, y]) => `${num(x)},${num(y)}`).join(' ') });
594
+ const numbers =
595
+ region.shape === 'circle'
596
+ ? [
597
+ this.#number(this.#t('field.cx'), region.x, (x) => set({ x })),
598
+ this.#number(this.#t('field.cy'), region.y, (y) => set({ y })),
599
+ this.#number(this.#t('field.r'), region.r, (r) => set({ r })),
600
+ ]
601
+ : region.shape === 'rect'
602
+ ? [
603
+ this.#number(this.#t('field.x'), region.x, (x) => set({ x })),
604
+ this.#number(this.#t('field.y'), region.y, (y) => set({ y })),
605
+ this.#number(this.#t('field.width'), region.width, (width) => set({ width })),
606
+ this.#number(this.#t('field.height'), region.height, (height) => set({ height })),
607
+ ]
608
+ : [];
609
+ return html`<li data-index=${region.index}>
610
+ <fieldset>
611
+ <legend><span class="swatch ${slot(region.index)}" aria-hidden="true">${n}</span>${this.#t('field.region', { n })}</legend>
612
+ ${
613
+ // Only zones that take more than one shape choose theirs.
614
+ field.shapes.length > 1
615
+ ? html`<label>
616
+ ${this.#t('field.shape')}
617
+ <select
618
+ @change=${(event: Event) => set(reshaped(region, (event.target as HTMLSelectElement).value as Shape))}
619
+ >
620
+ ${field.shapes.map(
621
+ (shape) =>
622
+ html`<option value=${shape} ?selected=${shape === region.shape}>${this.#t(`field.shape.${shape}`)}</option>`,
623
+ )}
624
+ </select>
625
+ </label>`
626
+ : nothing
627
+ }
628
+ ${numbers.length > 0 ? html`<div class="numbers">${numbers}</div>` : nothing}
629
+ ${
630
+ region.shape === 'polygon'
631
+ ? html`<ol class="items">
632
+ ${points.slice(0, MAX_LISTED).map(
633
+ ([x, y], k) => html`<li class="vertex">
634
+ ${this.#number(this.#t('field.vertex.x', { n: k + 1 }), x, (value) =>
635
+ setPoints(points.map((p, j) => (j === k ? [Number(value), p[1]] : p))),
636
+ )}
637
+ ${this.#number(this.#t('field.vertex.y', { n: k + 1 }), y, (value) =>
638
+ setPoints(points.map((p, j) => (j === k ? [p[0], Number(value)] : p))),
639
+ )}
640
+ <button
641
+ type="button"
642
+ ?disabled=${points.length <= 3}
643
+ @click=${() => setPoints(points.filter((_, j) => j !== k))}
644
+ >
645
+ ${this.#t('field.vertex.remove', { n: k + 1 })}
646
+ </button>
647
+ </li>`,
648
+ )}
649
+ </ol>
650
+ ${this.#more(points.length)}
651
+ <button
652
+ type="button"
653
+ ?disabled=${points.length >= MAX_LISTED}
654
+ @click=${() => {
655
+ const [lx, ly] = points[points.length - 1] ?? [50, 50];
656
+ setPoints([...points, [round(lx + 5), round(ly + 5)]]);
657
+ }}
658
+ >
659
+ ${this.#t('field.vertex.add')}
660
+ </button>`
661
+ : nothing
662
+ }
663
+ ${this.#labelField(field, region.index, region.label)}
664
+ <button type="button" @click=${() => this.#change({ kind: 'child-remove', tag: field.tag, index: region.index })}>
665
+ ${this.#t('field.region.remove', { n })}
666
+ </button>
667
+ </fieldset>
668
+ </li>`;
669
+ }
670
+
671
+ #point(field: PicturePointsFieldModel, point: PicturePointModel): TemplateResult {
672
+ const n = point.index + 1;
673
+ const set = (attributes: Record<string, string | null>) =>
674
+ this.#change({ kind: 'child-attributes', tag: field.tag, index: point.index, attributes });
675
+ return html`<li data-index=${point.index}>
676
+ <fieldset>
677
+ <legend><span class="swatch ${slot(point.index)}" aria-hidden="true">${n}</span>${this.#t('field.point', { n })}</legend>
678
+ <div class="numbers">
679
+ ${this.#number(this.#t('field.x'), point.x, (x) => set({ x }))}
680
+ ${this.#number(this.#t('field.y'), point.y, (y) => set({ y }))}
681
+ </div>
682
+ ${this.#labelField(field, point.index, point.label)}
683
+ <button type="button" @click=${() => this.#change({ kind: 'child-remove', tag: field.tag, index: point.index })}>
684
+ ${this.#t('field.point.remove', { n })}
685
+ </button>
686
+ </fieldset>
687
+ </li>`;
688
+ }
689
+
690
+ protected override render(): TemplateResult | typeof nothing {
691
+ const field = this.field;
692
+ if (field === null || this.authoring === null) return nothing;
693
+ const regions = field.kind === 'picture-regions';
694
+ const upload = this.authoring.uploadAsset !== null;
695
+ const library = this.authoring.pickPicture !== null;
696
+ const status = this.#status;
697
+ const said = status === null ? '' : (status.text ?? this.#t(status.key));
698
+ return html`<fieldset data-tag=${field.tag}>
699
+ <legend>${field.label}</legend>
700
+ ${field.help === null ? nothing : html`<p class="note">${field.help}</p>`}
701
+ <label>
702
+ ${this.#t('field.picture.src')}
703
+ <input
704
+ type="url"
705
+ autocomplete="off"
706
+ .value=${field.src}
707
+ @change=${(event: Event) => {
708
+ const value = (event.target as HTMLInputElement).value.trim();
709
+ this.#change({ kind: 'attribute', name: field.srcAttribute, value: value === '' ? null : value });
710
+ }}
711
+ />
712
+ </label>
713
+ ${
714
+ upload || library
715
+ ? html`<div class="upload">
716
+ <div class="sources">
717
+ ${
718
+ upload
719
+ ? html`<button
720
+ type="button"
721
+ @click=${() => this.renderRoot.querySelector<HTMLInputElement>('input[type="file"]')?.click()}
722
+ >
723
+ ${this.#t('picture.file')}
724
+ </button>`
725
+ : nothing
726
+ }
727
+ ${
728
+ library
729
+ ? html`<button type="button" data-library @click=${() => void this.#pick(field)}>
730
+ ${this.#t('picture.library')}
731
+ </button>`
732
+ : nothing
733
+ }
734
+ </div>
735
+ ${
736
+ upload
737
+ ? html`<input
738
+ type="file"
739
+ accept="image/*"
740
+ hidden
741
+ @change=${(event: Event) => {
742
+ const input = event.target as HTMLInputElement;
743
+ const file = input.files?.[0];
744
+ input.value = '';
745
+ if (file !== undefined) void this.#upload(field, file);
746
+ }}
747
+ />`
748
+ : nothing
749
+ }
750
+ <div role="status">${status !== null && !status.error ? html`<p class="note">${said}</p>` : nothing}</div>
751
+ <div role="alert">${status?.error ? html`<p class="error">${said}</p>` : nothing}</div>
752
+ </div>`
753
+ : html`<p class="note">${this.#t('picture.urlOnly')}</p>`
754
+ }
755
+ ${this.#canvas(field)}
756
+ <p class="note">${this.#t(regions ? 'field.regions.draw' : 'field.points.place')}</p>
757
+ <ol class="items">
758
+ ${
759
+ regions
760
+ ? field.regions.slice(0, MAX_LISTED).map((r) => this.#region(field, r))
761
+ : field.points.slice(0, MAX_LISTED).map((p) => this.#point(field, p))
762
+ }
763
+ </ol>
764
+ ${this.#more(regions ? field.regions.length : field.points.length)}
765
+ <button type="button" data-add @click=${() => this.#add(field)}>
766
+ ${this.#t(regions ? 'field.region.add' : 'field.point.add')}
767
+ </button>
768
+ </fieldset>`;
769
+ }
770
+ }