@openartifactsai/ui 0.0.0-stage → 0.23.0-rc.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 (91) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +82 -4
  5. package/src/button.d.ts +30 -0
  6. package/src/button.js +29 -0
  7. package/src/clicks.d.ts +63 -0
  8. package/src/clicks.js +75 -0
  9. package/src/cn.d.ts +3 -0
  10. package/src/cn.js +5 -0
  11. package/src/color-picker.d.ts +98 -0
  12. package/src/color-picker.js +395 -0
  13. package/src/color.d.ts +150 -0
  14. package/src/color.js +543 -0
  15. package/src/crash-boundary.d.ts +29 -0
  16. package/src/crash-boundary.js +32 -0
  17. package/src/data/google-fonts.json +1775 -0
  18. package/src/drag-cover.d.ts +48 -0
  19. package/src/drag-cover.js +41 -0
  20. package/src/effect-editors.d.ts +48 -0
  21. package/src/effect-editors.js +230 -0
  22. package/src/effects.d.ts +118 -0
  23. package/src/effects.js +425 -0
  24. package/src/escape-to-popup.d.ts +53 -0
  25. package/src/escape-to-popup.js +78 -0
  26. package/src/field-announce.d.ts +28 -0
  27. package/src/field-announce.js +43 -0
  28. package/src/fields.d.ts +176 -0
  29. package/src/fields.js +377 -0
  30. package/src/focusables.d.ts +50 -0
  31. package/src/focusables.js +61 -0
  32. package/src/font-picker.d.ts +62 -0
  33. package/src/font-picker.js +242 -0
  34. package/src/fonts.d.ts +121 -0
  35. package/src/fonts.js +273 -0
  36. package/src/history-diff.d.ts +64 -0
  37. package/src/history-diff.js +151 -0
  38. package/src/history.d.ts +95 -0
  39. package/src/history.js +160 -0
  40. package/src/index.d.ts +38 -0
  41. package/src/index.js +38 -0
  42. package/src/key-chord.d.ts +74 -0
  43. package/src/key-chord.js +228 -0
  44. package/src/keys.d.ts +142 -0
  45. package/src/keys.js +172 -0
  46. package/src/layout.d.ts +74 -0
  47. package/src/layout.js +173 -0
  48. package/src/link-card-view.d.ts +97 -0
  49. package/src/link-card-view.js +175 -0
  50. package/src/link-card.d.ts +136 -0
  51. package/src/link-card.js +158 -0
  52. package/src/menu-shortcuts.d.ts +31 -0
  53. package/src/menu-shortcuts.js +91 -0
  54. package/src/menu.d.ts +120 -0
  55. package/src/menu.js +100 -0
  56. package/src/number-entry.d.ts +140 -0
  57. package/src/number-entry.js +202 -0
  58. package/src/number-limits.d.ts +2 -0
  59. package/src/number-limits.js +2 -0
  60. package/src/number-wheel.d.ts +29 -0
  61. package/src/number-wheel.js +27 -0
  62. package/src/numbers.d.ts +28 -0
  63. package/src/numbers.js +124 -0
  64. package/src/overlays.d.ts +71 -0
  65. package/src/overlays.js +131 -0
  66. package/src/pressed.d.ts +5 -0
  67. package/src/pressed.js +10 -0
  68. package/src/scroll.d.ts +24 -0
  69. package/src/scroll.js +111 -0
  70. package/src/scrub-number-field.d.ts +79 -0
  71. package/src/scrub-number-field.js +254 -0
  72. package/src/select-announce.d.ts +50 -0
  73. package/src/select-announce.js +71 -0
  74. package/src/slider-session.d.ts +43 -0
  75. package/src/slider-session.js +39 -0
  76. package/src/styles.css +96 -0
  77. package/src/tab-strip-layout.d.ts +76 -0
  78. package/src/tab-strip-layout.js +111 -0
  79. package/src/tab-strip.d.ts +73 -0
  80. package/src/tab-strip.js +498 -0
  81. package/src/text-area-view.d.ts +35 -0
  82. package/src/text-area-view.js +142 -0
  83. package/src/text-area.d.ts +38 -0
  84. package/src/text-area.js +51 -0
  85. package/src/theme.css +34 -0
  86. package/src/toast-fit.d.ts +21 -0
  87. package/src/toast-fit.js +30 -0
  88. package/src/toast-tone.d.ts +27 -0
  89. package/src/toast-tone.js +22 -0
  90. package/src/tooltip.d.ts +23 -0
  91. package/src/tooltip.js +18 -0
package/src/effects.js ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Parsing and writing the CSS values the effect editors edit: gradients
3
+ * (`linear-gradient()`, `radial-gradient()` and their `repeating-` forms),
4
+ * `box-shadow` lists and `filter` chains. No DOM.
5
+ *
6
+ * Each parser returns null for a value it cannot represent faithfully (a
7
+ * `var()`, a length in `em`, a color hint…), so an editor can fall back to
8
+ * a plain text field instead of silently rewriting it.
9
+ */
10
+ import { formatLike, toRgba } from "./color.js";
11
+ /* --------------------------------- tokens --------------------------------- */
12
+ /**
13
+ * Splits `text` at top-level separators (outside parentheses): commas, or
14
+ * runs of whitespace. Empty pieces are dropped for whitespace and kept for
15
+ * commas (so `a,,b` can be rejected).
16
+ */
17
+ export function splitTopLevel(text, separator) {
18
+ const parts = [];
19
+ let depth = 0;
20
+ let current = '';
21
+ for (const ch of text) {
22
+ if (ch === '(')
23
+ depth++;
24
+ else if (ch === ')')
25
+ depth = Math.max(0, depth - 1);
26
+ const splits = depth === 0 && (separator === ',' ? ch === ',' : /\s/.test(ch));
27
+ if (splits) {
28
+ if (separator === ',' || current.trim())
29
+ parts.push(current.trim());
30
+ current = '';
31
+ continue;
32
+ }
33
+ current += ch;
34
+ }
35
+ if (separator === ',' || current.trim())
36
+ parts.push(current.trim());
37
+ return parts;
38
+ }
39
+ const LENGTH = /^([+-]?(?:\d+\.?\d*|\.\d+))(px)?$/i;
40
+ /** A px length (or a bare 0), else null. */
41
+ function px(text) {
42
+ const match = LENGTH.exec(text);
43
+ if (!match)
44
+ return null;
45
+ const value = Number(match[1]);
46
+ if (!match[2] && value !== 0)
47
+ return null;
48
+ return value;
49
+ }
50
+ /** Rounds for output, without `-0`. */
51
+ const num = (value, digits = 2) => {
52
+ const out = Math.round(value * 10 ** digits) / 10 ** digits;
53
+ return Object.is(out, -0) ? 0 : out;
54
+ };
55
+ const pxText = (value) => `${num(value)}px`;
56
+ /** True for text that can stand as a color in a shadow or stop (a color, `var()`, `currentcolor`). */
57
+ function isColorToken(text) {
58
+ return toRgba(text) !== null || /^(?:var|color-mix|color|light-dark|hwb|lab|lch|oklab)\(.*\)$/i.test(text) || text.toLowerCase() === 'currentcolor';
59
+ }
60
+ /** A new shadow layer: a soft drop shadow. */
61
+ export const DEFAULT_SHADOW = { x: 0, y: 4, blur: 12, spread: 0, color: 'rgb(0 0 0 / 0.15)', inset: false };
62
+ /** Parses one shadow. `full` allows spread and `inset` (box-shadow). */
63
+ function parseShadow(text, full) {
64
+ const lengths = [];
65
+ const colors = [];
66
+ let inset = false;
67
+ let lengthsDone = false;
68
+ for (const part of splitTopLevel(text, 'space')) {
69
+ const length = px(part);
70
+ if (length !== null) {
71
+ if (lengthsDone)
72
+ return null;
73
+ lengths.push(length);
74
+ continue;
75
+ }
76
+ if (lengths.length)
77
+ lengthsDone = true;
78
+ if (part.toLowerCase() === 'inset') {
79
+ if (!full || inset)
80
+ return null;
81
+ inset = true;
82
+ continue;
83
+ }
84
+ if (!isColorToken(part) || colors.length)
85
+ return null;
86
+ colors.push(part);
87
+ }
88
+ if (lengths.length < 2 || lengths.length > (full ? 4 : 3))
89
+ return null;
90
+ const [x, y, blur = 0, spread = 0] = lengths;
91
+ if (blur < 0)
92
+ return null;
93
+ return { x, y, blur, spread, color: colors[0] ?? 'currentcolor', inset };
94
+ }
95
+ /**
96
+ * Parses a `box-shadow` value into layers (front first). `none` or empty
97
+ * gives `[]`; null when a layer is not `[inset] x y [blur [spread]] [color]`
98
+ * in px.
99
+ */
100
+ export function parseBoxShadow(css) {
101
+ const text = css.trim();
102
+ if (!text || text.toLowerCase() === 'none')
103
+ return [];
104
+ const layers = [];
105
+ for (const part of splitTopLevel(text, ',')) {
106
+ const layer = part ? parseShadow(part, true) : null;
107
+ if (!layer)
108
+ return null;
109
+ layers.push(layer);
110
+ }
111
+ return layers;
112
+ }
113
+ /** Writes one box-shadow layer: `[inset] x y blur spread color`. */
114
+ export function formatShadowLayer(layer) {
115
+ const parts = [pxText(layer.x), pxText(layer.y), pxText(layer.blur), pxText(layer.spread), layer.color];
116
+ return (layer.inset ? ['inset', ...parts] : parts).join(' ');
117
+ }
118
+ /** Writes a `box-shadow` value; `none` for no layers. */
119
+ export function formatBoxShadow(layers) {
120
+ return layers.length ? layers.map(formatShadowLayer).join(', ') : 'none';
121
+ }
122
+ /** Parses the argument of `drop-shadow()` (or one `text-shadow` layer). */
123
+ export function parseDropShadow(text) {
124
+ const layer = parseShadow(text, false);
125
+ return layer ? { x: layer.x, y: layer.y, blur: layer.blur, color: layer.color } : null;
126
+ }
127
+ /** Writes the argument of `drop-shadow()`: `x y blur color`. */
128
+ export function formatDropShadow(shadow) {
129
+ return `${pxText(shadow.x)} ${pxText(shadow.y)} ${pxText(shadow.blur)} ${shadow.color}`;
130
+ }
131
+ /** Field settings of the numeric filters, in menu order. */
132
+ export const FILTER_SPECS = {
133
+ blur: { label: 'Blur', unit: 'px', min: 0, max: 200, step: 1, identity: 0, initial: 4 },
134
+ brightness: { label: 'Brightness', unit: '%', min: 0, max: 500, step: 1, identity: 100, initial: 120 },
135
+ contrast: { label: 'Contrast', unit: '%', min: 0, max: 500, step: 1, identity: 100, initial: 120 },
136
+ grayscale: { label: 'Grayscale', unit: '%', min: 0, max: 100, step: 1, identity: 0, initial: 100 },
137
+ saturate: { label: 'Saturate', unit: '%', min: 0, max: 500, step: 1, identity: 100, initial: 150 },
138
+ 'hue-rotate': { label: 'Hue rotate', unit: 'deg', min: -360, max: 360, step: 1, identity: 0, initial: 90 },
139
+ invert: { label: 'Invert', unit: '%', min: 0, max: 100, step: 1, identity: 0, initial: 100 },
140
+ sepia: { label: 'Sepia', unit: '%', min: 0, max: 100, step: 1, identity: 0, initial: 100 },
141
+ opacity: { label: 'Opacity', unit: '%', min: 0, max: 100, step: 1, identity: 100, initial: 50 },
142
+ };
143
+ /** The drop shadow a newly added `drop-shadow()` starts as. */
144
+ export const DEFAULT_DROP_SHADOW = { x: 0, y: 4, blur: 8, color: 'rgb(0 0 0 / 0.25)' };
145
+ /** A new filter function of `kind` at its initial value. */
146
+ export function newFilter(kind) {
147
+ return kind === 'drop-shadow' ? { kind, shadow: { ...DEFAULT_DROP_SHADOW } } : { kind, value: FILTER_SPECS[kind].initial };
148
+ }
149
+ const ANGLE = /^([+-]?(?:\d+\.?\d*|\.\d+))(deg|grad|rad|turn)?$/i;
150
+ /** Degrees of an angle (a bare 0 allowed). */
151
+ function degrees(text) {
152
+ const match = ANGLE.exec(text);
153
+ if (!match)
154
+ return null;
155
+ const value = Number(match[1]);
156
+ switch ((match[2] ?? '').toLowerCase()) {
157
+ case '':
158
+ return value === 0 ? 0 : null;
159
+ case 'deg':
160
+ return value;
161
+ case 'grad':
162
+ return (value * 360) / 400;
163
+ case 'rad':
164
+ return (value * 180) / Math.PI;
165
+ default:
166
+ return value * 360;
167
+ }
168
+ }
169
+ /** A number-or-percentage amount as a percentage. */
170
+ function percent(text) {
171
+ const match = /^([+-]?(?:\d+\.?\d*|\.\d+))(%)?$/.exec(text);
172
+ if (!match)
173
+ return null;
174
+ const value = Number(match[1]);
175
+ if (value < 0)
176
+ return null;
177
+ return match[2] ? value : value * 100;
178
+ }
179
+ /**
180
+ * Parses a `filter` chain. `none` or empty gives `[]`; null for `url()`,
181
+ * unknown functions or arguments it cannot read.
182
+ */
183
+ export function parseFilter(css) {
184
+ const text = css.trim();
185
+ if (!text || text.toLowerCase() === 'none')
186
+ return [];
187
+ const out = [];
188
+ for (const part of splitTopLevel(text, 'space')) {
189
+ const match = /^([a-z-]+)\(([\s\S]*)\)$/i.exec(part);
190
+ if (!match)
191
+ return null;
192
+ const kind = match[1].toLowerCase();
193
+ const arg = match[2].trim();
194
+ if (kind === 'drop-shadow') {
195
+ const shadow = parseDropShadow(arg);
196
+ if (!shadow)
197
+ return null;
198
+ out.push({ kind, shadow });
199
+ continue;
200
+ }
201
+ if (!(kind in FILTER_SPECS))
202
+ return null;
203
+ const amountKind = kind;
204
+ const spec = FILTER_SPECS[amountKind];
205
+ let value;
206
+ if (!arg)
207
+ value = amountKind === 'blur' || amountKind === 'hue-rotate' ? 0 : 100;
208
+ else if (amountKind === 'blur')
209
+ value = px(arg);
210
+ else if (amountKind === 'hue-rotate')
211
+ value = degrees(arg);
212
+ else
213
+ value = percent(arg);
214
+ if (value === null || (amountKind === 'blur' && value < 0))
215
+ return null;
216
+ // CSS clamps these at 100%.
217
+ if (spec.max === 100 && spec.unit === '%')
218
+ value = Math.min(100, value);
219
+ out.push({ kind: amountKind, value });
220
+ }
221
+ return out;
222
+ }
223
+ /** Writes one filter function. */
224
+ export function formatFilterFunction(fn) {
225
+ if (fn.kind === 'drop-shadow')
226
+ return `drop-shadow(${formatDropShadow(fn.shadow)})`;
227
+ const unit = FILTER_SPECS[fn.kind].unit;
228
+ return `${fn.kind}(${num(fn.value)}${unit})`;
229
+ }
230
+ /** Writes a `filter` value; `none` for an empty chain. */
231
+ export function formatFilter(chain) {
232
+ return chain.length ? chain.map(formatFilterFunction).join(' ') : 'none';
233
+ }
234
+ /** A new gradient: left-to-right, from `from` to `to`. */
235
+ export function defaultGradient(from = '#000000', to = '#ffffff') {
236
+ return { type: 'linear', repeating: false, angle: 90, shape: 'ellipse', stops: [{ color: from, position: 0 }, { color: to, position: 100 }] };
237
+ }
238
+ const SIDE_ANGLES = {
239
+ top: 0,
240
+ right: 90,
241
+ bottom: 180,
242
+ left: 270,
243
+ 'top right': 45,
244
+ 'right top': 45,
245
+ 'bottom right': 135,
246
+ 'right bottom': 135,
247
+ 'bottom left': 225,
248
+ 'left bottom': 225,
249
+ 'top left': 315,
250
+ 'left top': 315,
251
+ };
252
+ const RADIAL_SIZES = new Set(['closest-side', 'closest-corner', 'farthest-side', 'farthest-corner']);
253
+ /** Fills in missing stop positions the way CSS does: ends at 0/100, never backwards, gaps spread evenly. */
254
+ function resolvePositions(raw) {
255
+ const out = [...raw];
256
+ if (out[0] == null)
257
+ out[0] = 0;
258
+ if (out[out.length - 1] == null)
259
+ out[out.length - 1] = Math.max(100, ...out.filter((p) => p != null));
260
+ let max = -Infinity;
261
+ for (let i = 0; i < out.length; i++) {
262
+ if (out[i] != null) {
263
+ max = Math.max(max, out[i]);
264
+ out[i] = max;
265
+ }
266
+ }
267
+ for (let i = 1; i < out.length; i++) {
268
+ if (out[i] != null)
269
+ continue;
270
+ let j = i;
271
+ while (out[j] == null)
272
+ j++;
273
+ const start = out[i - 1];
274
+ const end = out[j];
275
+ for (let k = i; k < j; k++)
276
+ out[k] = start + ((end - start) * (k - i + 1)) / (j - i + 1);
277
+ i = j;
278
+ }
279
+ return out;
280
+ }
281
+ /** Parses the stops; null when one is a color hint or uses a non-% position. */
282
+ function parseStops(parts) {
283
+ const colors = [];
284
+ const positions = [];
285
+ for (const part of parts) {
286
+ const tokens = splitTopLevel(part, 'space');
287
+ const [color, ...rest] = tokens;
288
+ if (!color || !isColorToken(color) || rest.length > 2)
289
+ return null;
290
+ const at = rest.map((token) => {
291
+ const match = /^([+-]?(?:\d+\.?\d*|\.\d+))(%)?$/.exec(token);
292
+ if (!match || (!match[2] && Number(match[1]) !== 0))
293
+ return null;
294
+ return Number(match[1]);
295
+ });
296
+ if (at.some((p) => p === null))
297
+ return null;
298
+ if (at.length === 0) {
299
+ colors.push(color);
300
+ positions.push(null);
301
+ }
302
+ for (const p of at) {
303
+ colors.push(color);
304
+ positions.push(p);
305
+ }
306
+ }
307
+ if (colors.length < 2)
308
+ return null;
309
+ const resolved = resolvePositions(positions);
310
+ return colors.map((color, i) => ({ color, position: num(resolved[i], 4) }));
311
+ }
312
+ /**
313
+ * Parses a `linear-gradient()` / `radial-gradient()` (or `repeating-`) value.
314
+ * Null for other images, color hints, stop positions not in %, or a value
315
+ * with several layers. `to <side>` directions become angles (corners as 45°
316
+ * steps, which matches CSS for square boxes).
317
+ */
318
+ export function parseGradient(css) {
319
+ const match = /^(repeating-)?(linear|radial)-gradient\(([\s\S]*)\)$/i.exec(css.trim());
320
+ if (!match)
321
+ return null;
322
+ // Reject `a-gradient(...), b-gradient(...)`: the body must balance.
323
+ let depth = 0;
324
+ for (const ch of match[3]) {
325
+ if (ch === '(')
326
+ depth++;
327
+ else if (ch === ')' && --depth < 0)
328
+ return null;
329
+ }
330
+ if (depth !== 0)
331
+ return null;
332
+ const type = match[2].toLowerCase();
333
+ const parts = splitTopLevel(match[3], ',');
334
+ if (parts.some((part) => !part))
335
+ return null;
336
+ const gradient = { type, repeating: Boolean(match[1]), angle: 180, shape: 'ellipse', stops: [] };
337
+ const first = parts[0];
338
+ const firstTokens = splitTopLevel(first, 'space');
339
+ let stopParts = parts;
340
+ if (type === 'linear') {
341
+ const angle = firstTokens.length === 1 ? degrees(first) : null;
342
+ if (angle !== null) {
343
+ gradient.angle = num(((angle % 360) + 360) % 360, 4);
344
+ stopParts = parts.slice(1);
345
+ }
346
+ else if (firstTokens[0]?.toLowerCase() === 'to') {
347
+ const side = SIDE_ANGLES[firstTokens.slice(1).join(' ').toLowerCase()];
348
+ if (side === undefined)
349
+ return null;
350
+ gradient.angle = side;
351
+ stopParts = parts.slice(1);
352
+ }
353
+ }
354
+ else if (!isColorToken(firstTokens[0] ?? '')) {
355
+ const at = firstTokens.findIndex((t) => t.toLowerCase() === 'at');
356
+ const head = at < 0 ? firstTokens : firstTokens.slice(0, at);
357
+ const sizes = [];
358
+ for (const t of head) {
359
+ const lower = t.toLowerCase();
360
+ if (lower === 'circle' || lower === 'ellipse')
361
+ gradient.shape = lower;
362
+ else if (RADIAL_SIZES.has(lower) || /^[\d.]+(?:px|%|em|rem|vw|vh)$/.test(lower))
363
+ sizes.push(t);
364
+ else
365
+ return null;
366
+ }
367
+ if (sizes.length && !(sizes.length === 1 && sizes[0].toLowerCase() === 'farthest-corner'))
368
+ gradient.size = sizes.join(' ');
369
+ if (at >= 0) {
370
+ const position = firstTokens.slice(at + 1).join(' ');
371
+ if (!position)
372
+ return null;
373
+ if (position.toLowerCase() !== 'center' && position !== '50% 50%')
374
+ gradient.position = position;
375
+ }
376
+ stopParts = parts.slice(1);
377
+ }
378
+ const stops = parseStops(stopParts);
379
+ if (!stops)
380
+ return null;
381
+ gradient.stops = stops;
382
+ return gradient;
383
+ }
384
+ /** Writes a gradient as CSS; stops are written in position order. */
385
+ export function formatGradient(gradient) {
386
+ const stops = sortStops(gradient.stops).map((stop) => `${stop.color} ${num(stop.position)}%`);
387
+ const name = `${gradient.repeating ? 'repeating-' : ''}${gradient.type}-gradient`;
388
+ if (gradient.type === 'linear')
389
+ return `${name}(${num(gradient.angle)}deg, ${stops.join(', ')})`;
390
+ const head = [gradient.shape === 'circle' ? 'circle' : null, gradient.size ?? null, gradient.position ? `at ${gradient.position}` : null].filter(Boolean);
391
+ return `${name}(${head.length ? `${head.join(' ')}, ` : ''}${stops.join(', ')})`;
392
+ }
393
+ /** Stops sorted by position (stable). */
394
+ export function sortStops(stops) {
395
+ return stops.map((stop, i) => ({ stop, i })).sort((a, b) => a.stop.position - b.stop.position || a.i - b.i).map(({ stop }) => stop);
396
+ }
397
+ const lerp = (a, b, t) => a + (b - a) * t;
398
+ /**
399
+ * The color the gradient shows at `position` (percent), interpolated in
400
+ * premultiplied sRGB like browsers do by default, written like the nearer
401
+ * stop. Stops whose colors cannot be read (a `var()`) are taken as-is.
402
+ */
403
+ export function colorAtPosition(stops, position) {
404
+ const sorted = sortStops(stops);
405
+ if (!sorted.length)
406
+ return '#000000';
407
+ if (position <= sorted[0].position)
408
+ return sorted[0].color;
409
+ const last = sorted[sorted.length - 1];
410
+ if (position >= last.position)
411
+ return last.color;
412
+ const right = sorted.findIndex((stop) => stop.position >= position);
413
+ const a = sorted[right - 1];
414
+ const b = sorted[right];
415
+ const t = b.position === a.position ? 0 : (position - a.position) / (b.position - a.position);
416
+ const ca = toRgba(a.color);
417
+ const cb = toRgba(b.color);
418
+ const near = t < 0.5 ? a : b;
419
+ if (!ca || !cb)
420
+ return near.color;
421
+ const alpha = lerp(ca.a, cb.a, t);
422
+ const channel = (x, y) => (alpha === 0 ? 0 : lerp(x * ca.a, y * cb.a, t) / alpha);
423
+ const mixed = { r: channel(ca.r, cb.r), g: channel(ca.g, cb.g), b: channel(ca.b, cb.b), a: alpha };
424
+ return formatLike(near.color, mixed);
425
+ }
@@ -0,0 +1,53 @@
1
+ /** The parts of a popup element the handoff uses. */
2
+ export interface HandoffPopup {
3
+ hasAttribute(name: string): boolean;
4
+ contains(node: unknown): boolean;
5
+ dispatchEvent(event: unknown): boolean;
6
+ ownerDocument: {
7
+ addEventListener(type: 'keydown', listener: (event: HandoffKey) => void, capture: true): void;
8
+ removeEventListener(type: 'keydown', listener: (event: HandoffKey) => void, capture: true): void;
9
+ defaultView: {
10
+ KeyboardEvent: new (type: 'keydown', init: KeyboardEventInit) => object;
11
+ setTimeout(run: () => void, ms: number): unknown;
12
+ } | null;
13
+ };
14
+ }
15
+ /** The parts of a key event the handoff uses. */
16
+ export interface HandoffKey {
17
+ key: string;
18
+ target: unknown;
19
+ repeat?: boolean;
20
+ isComposing?: boolean;
21
+ keyCode?: number;
22
+ defaultPrevented?: boolean;
23
+ preventDefault?(): void;
24
+ }
25
+ /** What one dialog keeps about the Escapes its popups were meant to get. */
26
+ export interface EscapeHandoff {
27
+ /** The popup each Escape typed outside it was meant for. */
28
+ meantFor: WeakMap<object, HandoffPopup>;
29
+ /** Escapes typed inside one of the popups: theirs to handle. */
30
+ inside: WeakSet<object>;
31
+ /** The Escapes the dialog sent on. */
32
+ sent: WeakSet<object>;
33
+ /** Popups that stayed open after an Escape was handed to them. */
34
+ passedOver: WeakSet<HandoffPopup>;
35
+ }
36
+ export declare function createEscapeHandoff(): EscapeHandoff;
37
+ /** Notes what a key pressed while `popup` is mounted means for the dialog (call in the capture phase, before the dialog sees it). */
38
+ export declare function noteKeyForPopup(handoff: EscapeHandoff, popup: HandoffPopup, event: HandoffKey): void;
39
+ /** What the dialog's open-change reports. */
40
+ export interface DialogCloseDetails {
41
+ reason?: string;
42
+ event?: Event | HandoffKey;
43
+ cancel(): void;
44
+ }
45
+ /**
46
+ * Called first when the dialog would change open state: when the change is an Escape meant for an open popup, sends
47
+ * the Escape to that popup and keeps the dialog open. True when it did (the dialog does nothing more).
48
+ */
49
+ export declare function handEscapeToPopup(handoff: EscapeHandoff, details: DialogCloseDetails): boolean;
50
+ /** The handoff of the modal dialog around a popup; null outside one. */
51
+ export declare const EscapeHandoffContext: import("react").Context<EscapeHandoff | null>;
52
+ /** A ref for a popup's element: inside a modal dialog, the popup gets the Escapes typed outside it while it is open. */
53
+ export declare function useEscapeHandoffRef(): (element: HTMLElement | null) => void;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Escape in a modal dialog that has a menu or popover open in it closes that
3
+ * popup, not the dialog, even when the key was typed outside the popup (the
4
+ * focus left in a field of the dialog, or on the page). The dialog hands the
5
+ * Escape on to the popup; a popup that stays open after that (it does not
6
+ * close on Escape) is passed over by the next Escape, which closes the dialog.
7
+ *
8
+ * The dialog makes an {@link EscapeHandoff} and provides it through
9
+ * {@link EscapeHandoffContext}; each popup inside it notes, through
10
+ * {@link useEscapeHandoffRef}, the Escapes typed outside it while it is open;
11
+ * the dialog's close asks {@link handEscapeToPopup} first.
12
+ */
13
+ import { createContext, useCallback, useContext, useRef } from 'react';
14
+ import { isComposingKey } from "./keys.js";
15
+ export function createEscapeHandoff() {
16
+ return { meantFor: new WeakMap(), inside: new WeakSet(), sent: new WeakSet(), passedOver: new WeakSet() };
17
+ }
18
+ /** A popup is open while it carries Base UI's `data-open`. */
19
+ const isOpen = (popup) => popup.hasAttribute('data-open');
20
+ /** Notes what a key pressed while `popup` is mounted means for the dialog (call in the capture phase, before the dialog sees it). */
21
+ export function noteKeyForPopup(handoff, popup, event) {
22
+ if (!isOpen(popup)) {
23
+ handoff.passedOver.delete(popup);
24
+ return;
25
+ }
26
+ // An Escape that ends an input method's composition is the input method's.
27
+ if (event.key !== 'Escape' || isComposingKey(event))
28
+ return;
29
+ if (popup.contains(event.target))
30
+ handoff.inside.add(event);
31
+ else if (!handoff.passedOver.has(popup))
32
+ handoff.meantFor.set(event, popup);
33
+ }
34
+ /**
35
+ * Called first when the dialog would change open state: when the change is an Escape meant for an open popup, sends
36
+ * the Escape to that popup and keeps the dialog open. True when it did (the dialog does nothing more).
37
+ */
38
+ export function handEscapeToPopup(handoff, details) {
39
+ const event = details.event;
40
+ if (details.reason !== 'escape-key' || !event)
41
+ return false;
42
+ if (handoff.sent.has(event)) {
43
+ details.cancel();
44
+ return true;
45
+ }
46
+ const popup = handoff.meantFor.get(event);
47
+ const view = popup?.ownerDocument.defaultView;
48
+ if (!popup || !view || handoff.inside.has(event) || event.defaultPrevented)
49
+ return false;
50
+ const sent = new view.KeyboardEvent('keydown', { key: 'Escape', code: 'Escape', repeat: event.repeat ?? false, bubbles: true, cancelable: true });
51
+ handoff.sent.add(sent);
52
+ details.cancel();
53
+ event.preventDefault?.();
54
+ popup.dispatchEvent(sent);
55
+ view.setTimeout(() => {
56
+ if (isOpen(popup))
57
+ handoff.passedOver.add(popup);
58
+ }, 0);
59
+ return true;
60
+ }
61
+ /** The handoff of the modal dialog around a popup; null outside one. */
62
+ export const EscapeHandoffContext = createContext(null);
63
+ /** A ref for a popup's element: inside a modal dialog, the popup gets the Escapes typed outside it while it is open. */
64
+ export function useEscapeHandoffRef() {
65
+ const handoff = useContext(EscapeHandoffContext);
66
+ const detach = useRef(null);
67
+ return useCallback((element) => {
68
+ detach.current?.();
69
+ detach.current = null;
70
+ if (!handoff || !element)
71
+ return;
72
+ const popup = element;
73
+ const doc = popup.ownerDocument;
74
+ const listener = (event) => noteKeyForPopup(handoff, popup, event);
75
+ doc.addEventListener('keydown', listener, true);
76
+ detach.current = () => doc.removeEventListener('keydown', listener, true);
77
+ }, [handoff]);
78
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Where a field says what it did with typed text, when the editor does not
3
+ * take that over: a quiet (`polite`) live region, one per host, in the
4
+ * nearest dialog (a modal dialog hides the rest of the page from screen
5
+ * readers) or else the page body, in the page's language. The region is made
6
+ * when a field in that host takes the focus, so it is in place before the
7
+ * first message, and stays with its host.
8
+ */
9
+ import { type AnnounceRegion } from './select-announce.js';
10
+ /** The parts of a region's host the announcer uses. */
11
+ export interface FieldAnnounceHost<R extends AnnounceRegion> {
12
+ appendChild(node: R): unknown;
13
+ }
14
+ /** The parts of a field the announcer uses (an `HTMLElement` has them, with `HTMLSpanElement` regions). */
15
+ export interface FieldAnnounceTarget<R extends AnnounceRegion> {
16
+ ownerDocument: {
17
+ createElement(tag: 'span'): R;
18
+ body: FieldAnnounceHost<R> | null;
19
+ documentElement: {
20
+ lang: string;
21
+ };
22
+ };
23
+ closest(selector: string): FieldAnnounceHost<R> | null;
24
+ }
25
+ /** Makes the region a field will speak into; call when the field takes the focus. */
26
+ export declare function prepareFieldAnnounce<R extends AnnounceRegion>(field: FieldAnnounceTarget<R>): void;
27
+ /** Says `message` from a field. The same message twice in a row is said again. */
28
+ export declare function announceFromField<R extends AnnounceRegion>(field: FieldAnnounceTarget<R>, message: string): void;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Where a field says what it did with typed text, when the editor does not
3
+ * take that over: a quiet (`polite`) live region, one per host, in the
4
+ * nearest dialog (a modal dialog hides the rest of the page from screen
5
+ * readers) or else the page body, in the page's language. The region is made
6
+ * when a field in that host takes the focus, so it is in place before the
7
+ * first message, and stays with its host.
8
+ */
9
+ import { VISUALLY_HIDDEN } from "./select-announce.js";
10
+ const regions = new WeakMap();
11
+ /** The region for a field's host, made the first time. Null when the field has no host to put one in. */
12
+ function regionFor(field) {
13
+ const doc = field.ownerDocument;
14
+ const host = field.closest('[role="dialog"], [role="alertdialog"]') ?? doc.body;
15
+ if (!host)
16
+ return null;
17
+ const known = regions.get(host);
18
+ if (known)
19
+ return known;
20
+ const region = doc.createElement('span');
21
+ region.setAttribute('aria-live', 'polite');
22
+ region.setAttribute('aria-atomic', 'true');
23
+ region.setAttribute('style', VISUALLY_HIDDEN);
24
+ if (doc.documentElement.lang)
25
+ region.setAttribute('lang', doc.documentElement.lang);
26
+ host.appendChild(region);
27
+ regions.set(host, region);
28
+ return region;
29
+ }
30
+ /** Makes the region a field will speak into; call when the field takes the focus. */
31
+ export function prepareFieldAnnounce(field) {
32
+ regionFor(field);
33
+ }
34
+ /** Says `message` from a field. The same message twice in a row is said again. */
35
+ export function announceFromField(field, message) {
36
+ if (!message)
37
+ return;
38
+ const region = regionFor(field);
39
+ if (!region)
40
+ return;
41
+ // A no-break space makes a repeat a change, so it is read again.
42
+ region.textContent = region.textContent === message ? `${message} ` : message;
43
+ }