@silkui/core 0.1.1 → 0.1.3

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.
package/README.md CHANGED
@@ -115,10 +115,40 @@ through the tree.
115
115
  | `layout` | `bounds`: where layout put the node, in window pixels |
116
116
  | `transitionrun`, `transitionstart`, `transitionend`, `transitioncancel` | `propertyName`, `elapsedTime` |
117
117
  | `animationstart`, `animationiteration`, `animationend`, `animationcancel` | `animationName`, `elapsedTime` |
118
+ | `dragenter`, `dragover`, `dragleave`, `drop` | `clientX`, `clientY`, `dataTransfer` (files dragged in from other apps) |
118
119
 
119
120
  A listener that throws does not stop the dispatch. `setErrorHandler(handler)` receives the
120
121
  exception; without one the host reports it.
121
122
 
123
+ ### The desktop
124
+
125
+ Files dragged in from other apps fire `dragenter`, `dragover`, `dragleave` and `drop` on the
126
+ node under them, and bubble, as on the web. `event.dataTransfer.types` is `["Files"]` while
127
+ they are over the window, and `drop` lists them in `dataTransfer.files`, each with its `name`
128
+ and its `path` on disk.
129
+
130
+ ```ts
131
+ zone.addEventListener("drop", (event) => open(event.dataTransfer.files[0].path));
132
+ ```
133
+
134
+ `Notification` is the web's: `new Notification("Built", { body: "In 2 s" })`, with `onclick`.
135
+ Permission is always granted. Two things the web has no API for come from the package:
136
+
137
+ ```ts
138
+ import { setTray, registerShortcut } from "@silkui/core";
139
+
140
+ setTray({
141
+ icon: { width: 32, height: 32, data: pixels }, // RGBA, as an ImageData
142
+ tooltip: "Builds",
143
+ menu: [{ label: "Build now", click: build }, { type: "separator" }, { label: "Quit", click: quit }],
144
+ });
145
+ registerShortcut("Mod+Shift+B", build); // Mod is Command on macOS, Control elsewhere
146
+ ```
147
+
148
+ `setTray` and `registerShortcut` resolve to whether the system took them. A shortcut works
149
+ whichever app has focus; another app may hold it, and Wayland has none. `removeTray()` and
150
+ `unregisterShortcut(accelerator)` undo them.
151
+
122
152
  ### Attributes and accessibility
123
153
 
124
154
  `setAttribute(name, value)` sets the tree's attributes: `tabIndex`, `disabled`, `label`,
@@ -178,3 +208,38 @@ The package ships its types. Every node class, event and style property is typed
178
208
  - [Templates](https://github.com/silk-lang/examples) and
179
209
  [Get started](https://silk-ui-docs.juliaortiz-js.workers.dev/start/).
180
210
  - [Source](https://github.com/silk-lang/SilkUI/tree/main/modules/js/packages/core). MIT license.
211
+
212
+
213
+ ## Stylesheets
214
+
215
+ CSS imports built with `@silkui/vite` are adopted before the first frame and replaced in
216
+ place during development. For application-managed themes, adopt constructed sheets on the
217
+ node passed to `mount`:
218
+
219
+ ```js
220
+ import { CSSStyleSheet, createBox, mount } from "@silkui/core";
221
+
222
+ const theme = new CSSStyleSheet();
223
+ theme.replaceSync(".card { padding: 12px; color: rebeccapurple }");
224
+ const app = createBox();
225
+ app.className = "card";
226
+ app.adoptedStyleSheets = [theme];
227
+ mount(app);
228
+ await theme.replace(".card { padding: 18px; color: teal }");
229
+ ```
230
+
231
+ JavaScript development hosts include the text compiler. Release hosts require
232
+ `App.runtimeStylesheets()` in their Silk task pipeline. Without that option they accept
233
+ compiled sheets and reject text compilation. The compiler is linked only when enabled.
234
+
235
+ `adoptedStyleSheets` is an ordered mutable array. Assignment, `push`, `splice`, reordering,
236
+ and shrinking `length` update the active root. Entries must be constructed `CSSStyleSheet`
237
+ objects; deleting an indexed property or creating holes is invalid. The same sheet can
238
+ appear multiple times, and replacing it updates each adoption. Invalid compiled bytes leave
239
+ the current sheet intact. Replacing the mounted root switches to that node's adopted list.
240
+
241
+ `CSSStyleSheet.fromCompiled(bytes)` creates a sheet from `Uint8Array`, `ArrayBuffer`, or
242
+ Base64-encoded compiled bytes; `sheet.replaceCompiled(bytes)` updates it. The format is
243
+ versioned and must match the host. Build-time sheets come first, followed by imported CSS
244
+ and the root's constructed sheets. There is no `document`, `<style>`, or `<link>` node;
245
+ `cssRules`, `insertRule`, and `deleteRule` are not part of this API.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkui/core",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "The node and event API of a Silk UI tree for JavaScript applications that run on the embedded SilkJS engine",
5
5
  "repository": {
6
6
  "type": "git",
package/src/index.d.ts CHANGED
@@ -1,3 +1,13 @@
1
+ /** A constructed stylesheet. Text loading requires runtime stylesheet compilation in the host. */
2
+ export class CSSStyleSheet {
3
+ static fromCompiled(bytes: Uint8Array | ArrayBuffer | string): CSSStyleSheet;
4
+ replaceCompiled(bytes: Uint8Array | ArrayBuffer | string): void;
5
+ replaceSync(text: string): void;
6
+ replace(text: string): Promise<CSSStyleSheet>;
7
+ }
8
+ /** Used by build tools to replace or remove a compiled CSS import without restarting the app. */
9
+ export function updateStyleSheet(id: string, compiled: Uint8Array | ArrayBuffer | string | null): void;
10
+
1
11
  import type * as CSS from "csstype";
2
12
 
3
13
  /** The node kinds of the tree. `richinput` is an `input` with marks and atoms. */
@@ -29,11 +39,34 @@ export interface Look {
29
39
  export type Listener<E extends Event = Event> = ((this: Node, event: E) => void) | { handleEvent(event: E): void };
30
40
  export type ListenerOptions = boolean | { capture?: boolean; once?: boolean };
31
41
 
42
+ /** Live tokens in a node's class attribute. */
43
+ export class ClassList implements Iterable<string> {
44
+ constructor(node: Node);
45
+ value: string;
46
+ readonly length: number;
47
+ item(index: number): string | null;
48
+ contains(token: string): boolean;
49
+ add(...tokens: string[]): void;
50
+ remove(...tokens: string[]): void;
51
+ toggle(token: string, force?: boolean): boolean;
52
+ replace(oldToken: string, newToken: string): boolean;
53
+ values(): IterableIterator<string>;
54
+ keys(): IterableIterator<number>;
55
+ entries(): IterableIterator<[number, string]>;
56
+ forEach(callback: (value: string, index: number, list: ClassList) => void, thisArg?: unknown): void;
57
+ [Symbol.iterator](): IterableIterator<string>;
58
+ toString(): string;
59
+ }
60
+
32
61
  /** A node of the tree. Make one with `createBox`, `createText`, `createInput` or `createNode`. */
33
62
  export class Node {
34
63
  constructor(kind: NodeKind);
35
- /** The tree's number for the node (not the DOM `id`: that is `setAttribute("id", ...)`). */
36
- readonly id: number;
64
+ /** Stable protocol identifier, independent of the CSS id attribute. */
65
+ readonly nodeId: number;
66
+ id: string;
67
+ className: string;
68
+ adoptedStyleSheets: CSSStyleSheet[];
69
+ readonly classList: ClassList;
37
70
  readonly kind: NodeKind;
38
71
  readonly parentNode: Node | null;
39
72
  readonly childNodes: readonly Node[];
@@ -61,9 +94,13 @@ export class Node {
61
94
  /**
62
95
  * Sets a tree attribute (`tabIndex`, `disabled`, `label`, `testId`, `placeholder`, `href`,
63
96
  * `cursor`, `multiline`, `readOnly`, `inert`, `focusTrap`, `transition`), `id`, `role`, or
64
- * an ARIA attribute spelled `aria-checked` or `ariaChecked`.
97
+ * an ARIA attribute spelled `aria-checked` or `ariaChecked`, or a `data-*` attribute.
98
+ * `null` and `undefined` remove an attribute.
65
99
  */
66
100
  setAttribute(name: string, value: unknown): void;
101
+ getAttribute(name: string): string | null;
102
+ hasAttribute(name: string): boolean;
103
+ removeAttribute(name: string): void;
67
104
  set tabIndex(value: number);
68
105
  set disabled(value: boolean);
69
106
  focus(): void;
@@ -261,6 +298,10 @@ export interface EventMap {
261
298
  animationiteration: AnimationEvent;
262
299
  animationend: AnimationEvent;
263
300
  animationcancel: AnimationEvent;
301
+ dragenter: DragEvent;
302
+ dragover: DragEvent;
303
+ dragleave: DragEvent;
304
+ drop: DragEvent;
264
305
  }
265
306
 
266
307
  export function createNode(kind: "text"): Text;
@@ -317,3 +358,80 @@ export function parseMarkdown(text: string, options?: MarkdownOptions): import("
317
358
 
318
359
  /** What happens to an exception a listener throws. Without a handler, the host reports it. */
319
360
  export function setErrorHandler(handler: ((error: unknown) => void) | null): void;
361
+
362
+ /** A file dragged in from the desktop, as the web's `File`, with its `path` on disk. */
363
+ export class DroppedFile {
364
+ readonly name: string;
365
+ readonly path: string;
366
+ readonly type: string;
367
+ }
368
+
369
+ /** What a file drag carries. `files` is filled in `drop`, as on the web. */
370
+ export class DataTransfer {
371
+ readonly files: DroppedFile[];
372
+ readonly items: { kind: "file"; type: string; getAsFile(): DroppedFile }[];
373
+ readonly types: string[];
374
+ dropEffect: string;
375
+ effectAllowed: string;
376
+ getData(format: string): string;
377
+ }
378
+
379
+ /** Files dragged from another app over the window (`dragenter`, `dragover`, `dragleave`, `drop`). */
380
+ export interface DragEvent extends Event {
381
+ clientX: number;
382
+ clientY: number;
383
+ x: number;
384
+ y: number;
385
+ dataTransfer: DataTransfer;
386
+ }
387
+
388
+ export interface NotificationOptions {
389
+ body?: string;
390
+ tag?: string;
391
+ data?: unknown;
392
+ }
393
+
394
+ /** A desktop notification, as the web's. Permission is always granted. */
395
+ export class Notification {
396
+ static readonly permission: "granted";
397
+ static requestPermission(callback?: (permission: "granted") => void): Promise<"granted">;
398
+ constructor(title: string, options?: NotificationOptions);
399
+ readonly title: string;
400
+ readonly body: string;
401
+ readonly tag: string;
402
+ readonly data: unknown;
403
+ onclick: ((event: { type: "click"; target: Notification }) => void) | null;
404
+ onshow: ((event: { type: "show"; target: Notification }) => void) | null;
405
+ onerror: ((event: { type: "error"; target: Notification }) => void) | null;
406
+ onclose: ((event: { type: "close"; target: Notification }) => void) | null;
407
+ close(): void;
408
+ addEventListener(type: "click" | "show" | "error" | "close", listener: (event: { type: string; target: Notification }) => void): void;
409
+ removeEventListener(type: "click" | "show" | "error" | "close", listener: (event: { type: string; target: Notification }) => void): void;
410
+ }
411
+
412
+ export type TrayMenuItem =
413
+ | { label: string; click?: () => void; enabled?: boolean; checked?: boolean }
414
+ | { type: "separator" }
415
+ | { label: string; submenu: TrayMenuItem[] };
416
+
417
+ export interface TrayOptions {
418
+ /** RGBA pixels, as an `ImageData`. 32 by 32 looks right everywhere. */
419
+ icon: { width: number; height: number; data: ArrayLike<number> };
420
+ tooltip?: string;
421
+ /** macOS draws the icon from its alpha, in the menu bar's colours. */
422
+ template?: boolean;
423
+ menu?: TrayMenuItem[];
424
+ /** Runs on a click when there is no menu. `button` is `MouseEvent.button`'s. */
425
+ onClick?: (event: { button: number }) => void;
426
+ }
427
+
428
+ /** Shows an icon in the system tray; calling it again replaces it. Resolves to whether it shows. */
429
+ export function setTray(options: TrayOptions): Promise<boolean>;
430
+ export function removeTray(): void;
431
+
432
+ /**
433
+ * Runs `callback` when `accelerator` (`"Mod+Shift+K"`; `Mod` is Command on macOS, Control
434
+ * elsewhere) is pressed, whichever app has focus. Resolves to whether the system took it.
435
+ */
436
+ export function registerShortcut(accelerator: string, callback: () => void): Promise<boolean>;
437
+ export function unregisterShortcut(accelerator: string): void;
package/src/index.js CHANGED
@@ -26,13 +26,15 @@ const CLICK = KIND_OF.get("click");
26
26
  // As on the web: these reach the target alone.
27
27
  const NO_BUBBLE = new Set(["pointerenter", "pointerleave", "focus", "blur", "scroll", "layout", "load", "error"]);
28
28
  // The tree has a default action to skip for these.
29
- const CANCELABLE = new Set(["pointerdown", "pointerup", "click", "wheel", "keydown", "keyup"]);
29
+ const CANCELABLE = new Set(["pointerdown", "pointerup", "click", "wheel", "keydown", "keyup", "dragenter", "dragover", "drop"]);
30
+ // Files dragged from the desktop: the host dispatches these itself, so nodes need no flag.
31
+ const DRAG_TYPES = new Set(["dragenter", "dragover", "dragleave", "drop"]);
30
32
 
31
33
  // Properties whose numbers are not lengths. Every other number is CSS pixels.
32
34
  const UNITLESS = new Set([
33
35
  "opacity", "flexGrow", "flexShrink", "flex", "order", "zIndex", "fontWeight", "lineHeight",
34
36
  "aspectRatio", "tabSize", "scale", "animationIterationCount", "gridRow", "gridRowStart", "gridRowEnd",
35
- "gridColumn", "gridColumnStart", "gridColumnEnd", "gridArea",
37
+ "gridColumn", "gridColumnStart", "gridColumnEnd", "gridArea", "columnCount", "columns", "orphans", "widows",
36
38
  ]);
37
39
 
38
40
  const nodes = new Map();
@@ -43,6 +45,7 @@ let nextId = 0;
43
45
  const CSS_NAMES = new Map();
44
46
 
45
47
  function cssName(name) {
48
+ if (name.startsWith("--")) return name;
46
49
  let css = CSS_NAMES.get(name);
47
50
  if (css === undefined) {
48
51
  css = name.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase());
@@ -68,20 +71,11 @@ function familyOf(names) {
68
71
  }
69
72
 
70
73
  function cssValue(name, value) {
74
+ if (name.startsWith("--")) return String(value);
71
75
  if (name === "fontFamily") return familyOf(String(value));
72
76
  return typeof value === "number" && !UNITLESS.has(name) ? value + "px" : String(value);
73
77
  }
74
78
 
75
- // ARIA states with a tree attribute of their own, by the name after `aria-`. The host takes
76
- // the other ARIA names as they are; one it does not know is ignored, with one warning.
77
- const ARIA_STATES = { checked: "checked", selected: "selected", expanded: "expanded" };
78
- const ARIA_RANGE = { valuemin: 0, valuemax: 1, valuenow: 2 };
79
- // ARIA attributes that name other elements by their ids. The tree takes node numbers, so a
80
- // relation is sent again whenever an id it names comes, goes or moves to another node.
81
- const ARIA_RELATIONS = new Set(["labelledby", "describedby", "controls", "activedescendant"]);
82
- // Nodes by their `id`, and the nodes whose relations name each id.
83
- const byId = new Map();
84
- const naming = new Map();
85
79
  const warned = new Set();
86
80
 
87
81
  function warnOnce(message) {
@@ -135,15 +129,15 @@ class Look {
135
129
  if (removed) {
136
130
  // The tree sets declarations over earlier ones, so taking one out means starting the
137
131
  // look again.
138
- native.clearStyle(this.#node.id, this.#state);
132
+ native.clearStyle(this.#node.nodeId, this.#state);
139
133
  css = this.cssText;
140
134
  }
141
- if (css) native.style(this.#node.id, css, this.#state);
135
+ if (css) native.style(this.#node.nodeId, css, this.#state);
142
136
  }
143
137
 
144
138
  /** Replaces the whole look. */
145
139
  replace(properties) {
146
- native.clearStyle(this.#node.id, this.#state);
140
+ native.clearStyle(this.#node.nodeId, this.#state);
147
141
  this.#values = Object.create(null);
148
142
  this.set(properties);
149
143
  }
@@ -159,6 +153,220 @@ class Look {
159
153
  }
160
154
  }
161
155
 
156
+ const CLASS_SPACE = /[\t\n\f\r ]/;
157
+ function classToken(value) {
158
+ const token = String(value);
159
+ if (!token || CLASS_SPACE.test(token)) {
160
+ const error = new Error(!token ? "A class token cannot be empty" : "A class token cannot contain whitespace");
161
+ error.name = !token ? "SyntaxError" : "InvalidCharacterError";
162
+ throw error;
163
+ }
164
+ return token;
165
+ }
166
+
167
+ /** A live token list backed by the node's class attribute. */
168
+ export class ClassList {
169
+ #node;
170
+ constructor(node) { this.#node = node; }
171
+ #tokens() { return [...new Set(this.value.split(/[\t\n\f\r ]+/).filter(Boolean))]; }
172
+ #write(tokens) { this.#node.className = tokens.join(" "); }
173
+ get value() { return this.#node.className; }
174
+ set value(value) { this.#node.className = value; }
175
+ get length() { return this.#tokens().length; }
176
+ item(index) { return this.#tokens()[Number(index) >>> 0] ?? null; }
177
+ contains(token) { return this.#tokens().includes(classToken(token)); }
178
+ add(...values) {
179
+ const tokens = values.map(classToken);
180
+ this.#write([...new Set([...this.#tokens(), ...tokens])]);
181
+ }
182
+ remove(...values) {
183
+ const tokens = values.map(classToken);
184
+ this.#write(this.#tokens().filter((token) => !tokens.includes(token)));
185
+ }
186
+ toggle(value, force) {
187
+ const token = classToken(value);
188
+ const present = this.contains(token);
189
+ const wanted = force === undefined ? !present : !!force;
190
+ if (wanted && !present) this.add(token);
191
+ else if (!wanted && present) this.remove(token);
192
+ return wanted;
193
+ }
194
+ replace(oldValue, newValue) {
195
+ const oldToken = classToken(oldValue), newToken = classToken(newValue);
196
+ const tokens = this.#tokens(), index = tokens.indexOf(oldToken);
197
+ if (index === -1) return false;
198
+ if (oldToken !== newToken) {
199
+ if (tokens.includes(newToken)) tokens.splice(index, 1);
200
+ else tokens[index] = newToken;
201
+ }
202
+ this.#write(tokens);
203
+ return true;
204
+ }
205
+ values() { return this.#tokens().values(); }
206
+ keys() { return this.#tokens().keys(); }
207
+ entries() { return this.#tokens().entries(); }
208
+ forEach(callback, thisArg) { this.#tokens().forEach((value, index) => callback.call(thisArg, value, index, this)); }
209
+ [Symbol.iterator]() { return this.values(); }
210
+ toString() { return this.value; }
211
+ }
212
+
213
+ const sheetData = new WeakMap();
214
+ const adoptedLists = new WeakMap();
215
+ const importedSheets = new Map();
216
+ let installedSheets = [];
217
+ let nextSheet = 1;
218
+
219
+ function sheetError(message) {
220
+ const error = new Error(message);
221
+ error.name = "NotAllowedError";
222
+ return error;
223
+ }
224
+
225
+ function base64Bytes(value) {
226
+ if (typeof value === "string") return value;
227
+ const bytes = value instanceof ArrayBuffer ? new Uint8Array(value) : value;
228
+ if (!(bytes instanceof Uint8Array)) throw new TypeError("Expected compiled stylesheet bytes");
229
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
230
+ let encoded = "";
231
+ for (let i = 0; i < bytes.length; i += 3) {
232
+ const bits = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
233
+ encoded += alphabet[bits >>> 18] + alphabet[(bits >>> 12) & 63]
234
+ + (i + 1 < bytes.length ? alphabet[(bits >>> 6) & 63] : "=")
235
+ + (i + 2 < bytes.length ? alphabet[bits & 63] : "=");
236
+ }
237
+ return encoded;
238
+ }
239
+
240
+ function replaceSheet(sheet, bytes) {
241
+ native.styleSheet(0, 0, bytes);
242
+ const state = sheetData.get(sheet);
243
+ state.bytes = bytes;
244
+ for (const entry of installedSheets) {
245
+ if (entry.sheet !== sheet) continue;
246
+ native.styleSheet(entry.live ? 2 : 1, entry.id, bytes);
247
+ entry.live = true;
248
+ }
249
+ }
250
+
251
+ /** A constructed stylesheet, adopted on an application's root. */
252
+ export class CSSStyleSheet {
253
+ constructor() { sheetData.set(this, { bytes: null, replacing: false }); }
254
+
255
+ static fromCompiled(bytes) {
256
+ const sheet = new CSSStyleSheet();
257
+ replaceSheet(sheet, base64Bytes(bytes));
258
+ return sheet;
259
+ }
260
+
261
+ replaceCompiled(bytes) {
262
+ if (sheetData.get(this).replacing) throw sheetError("A stylesheet replacement is already pending");
263
+ replaceSheet(this, base64Bytes(bytes));
264
+ }
265
+
266
+ replaceSync(text) {
267
+ if (sheetData.get(this).replacing) throw sheetError("A stylesheet replacement is already pending");
268
+ if (!native.compileStyleSheet) throw sheetError("Runtime CSS compilation is disabled in this host");
269
+ replaceSheet(this, native.compileStyleSheet(String(text)));
270
+ }
271
+
272
+ replace(text) {
273
+ const state = sheetData.get(this);
274
+ if (state.replacing) return Promise.reject(sheetError("A stylesheet replacement is already pending"));
275
+ const source = String(text);
276
+ state.replacing = true;
277
+ return Promise.resolve().then(() => {
278
+ if (!native.compileStyleSheet) throw sheetError("Runtime CSS compilation is disabled in this host");
279
+ replaceSheet(this, native.compileStyleSheet(source));
280
+ return this;
281
+ }).finally(() => { state.replacing = false; });
282
+ }
283
+ }
284
+
285
+ function clearAdoptedSheets() {
286
+ for (const entry of installedSheets) if (entry.live) native.styleSheet(3, entry.id, "");
287
+ installedSheets = [];
288
+ }
289
+
290
+ function syncAdoptedSheets() {
291
+ if (!rootNode) return;
292
+ clearAdoptedSheets();
293
+ const sheets = [...importedSheets.values(), ...(adoptedLists.get(rootNode)?.values ?? [])];
294
+ for (const sheet of sheets) {
295
+ if (nextSheet >= 0x80000000) throw new RangeError("Too many stylesheet adoptions");
296
+ const entry = { sheet, id: nextSheet++, live: false };
297
+ installedSheets.push(entry);
298
+ const bytes = sheetData.get(sheet).bytes;
299
+ if (bytes !== null) { native.styleSheet(1, entry.id, bytes); entry.live = true; }
300
+ }
301
+ }
302
+
303
+ function validateSheets(values) {
304
+ for (const sheet of values) if (!sheetData.has(sheet)) throw new TypeError("adoptedStyleSheets accepts constructed CSSStyleSheet objects");
305
+ return values;
306
+ }
307
+
308
+ const sheetMutators = new Set(["copyWithin", "fill", "pop", "push", "reverse", "shift", "sort", "splice", "unshift"]);
309
+ function adoptedList(node) {
310
+ let list = adoptedLists.get(node);
311
+ if (list) return list;
312
+ const values = [];
313
+ const assign = next => {
314
+ validateSheets(next);
315
+ values.splice(0, values.length, ...next);
316
+ if (rootNode === node) syncAdoptedSheets();
317
+ };
318
+ const numeric = key => typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key);
319
+ const proxy = new Proxy(values, {
320
+ get(target, key, receiver) {
321
+ if (!sheetMutators.has(key)) return Reflect.get(target, key, receiver);
322
+ return (...args) => {
323
+ const next = values.slice();
324
+ const result = Array.prototype[key].apply(next, args);
325
+ assign(next);
326
+ return result === next ? proxy : result;
327
+ };
328
+ },
329
+ set(target, key, value) {
330
+ if (key !== "length" && !numeric(key)) return Reflect.set(target, key, value);
331
+ const next = values.slice();
332
+ Reflect.set(next, key, value);
333
+ assign(next);
334
+ return true;
335
+ },
336
+ defineProperty(target, key, descriptor) {
337
+ if (key !== "length" && !numeric(key)) return Reflect.defineProperty(target, key, descriptor);
338
+ if (!Object.hasOwn(descriptor, "value") || descriptor.get || descriptor.set || descriptor.configurable === false || descriptor.writable === false) {
339
+ throw new TypeError("adoptedStyleSheets entries must remain mutable values");
340
+ }
341
+ const next = values.slice();
342
+ Reflect.set(next, key, descriptor.value);
343
+ assign(next);
344
+ return true;
345
+ },
346
+ deleteProperty(target, key) {
347
+ if (!numeric(key)) return Reflect.deleteProperty(target, key);
348
+ return Number(key) >= values.length;
349
+ },
350
+ });
351
+ list = { values, proxy, assign };
352
+ adoptedLists.set(node, list);
353
+ return list;
354
+ }
355
+
356
+ /** Installs or replaces a CSS import compiled by the development build tool. */
357
+ export function updateStyleSheet(id, compiled) {
358
+ const key = String(id);
359
+ const previous = importedSheets.get(key);
360
+ if (compiled === null) {
361
+ if (importedSheets.delete(key)) syncAdoptedSheets();
362
+ } else if (previous) {
363
+ previous.replaceCompiled(compiled);
364
+ } else {
365
+ importedSheets.set(key, CSSStyleSheet.fromCompiled(compiled));
366
+ syncAdoptedSheets();
367
+ }
368
+ }
369
+
162
370
  /** A node of the tree. Make one with `createBox`, `createText`, `createInput` or `createNode`. */
163
371
  export class Node {
164
372
  #listeners = null;
@@ -166,19 +374,22 @@ export class Node {
166
374
  #base = null;
167
375
  #looks = null;
168
376
  #flags = 0;
169
- // aria-valuemin, aria-valuemax and aria-valuenow, which the tree takes as one range.
170
- #range = null;
377
+ #attributes = null;
378
+ #classList = null;
171
379
 
172
380
  constructor(kind) {
173
- this.id = ++nextId;
381
+ Object.defineProperty(this, "nodeId", { value: ++nextId, enumerable: true });
174
382
  this.kind = kind;
175
383
  this.parentNode = null;
176
384
  // A text leaf has no children: they all share one empty list.
177
385
  this.childNodes = kind === "text" ? NO_CHILDREN : [];
178
- nodes.set(this.id, this);
179
- native.create(this.id, KINDS[kind]);
386
+ nodes.set(this.nodeId, this);
387
+ native.create(this.nodeId, KINDS[kind]);
180
388
  }
181
389
 
390
+ get adoptedStyleSheets() { return adoptedList(this).proxy; }
391
+ set adoptedStyleSheets(value) { adoptedList(this).assign(Array.from(value)); }
392
+
182
393
  get firstChild() {
183
394
  return this.childNodes[0] ?? null;
184
395
  }
@@ -213,10 +424,10 @@ export class Node {
213
424
  child.parentNode = this;
214
425
  if (before) {
215
426
  this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
216
- native.insertBefore(this.id, child.id, before.id);
427
+ native.insertBefore(this.nodeId, child.nodeId, before.nodeId);
217
428
  } else {
218
429
  this.childNodes.push(child);
219
- native.append(this.id, child.id);
430
+ native.append(this.nodeId, child.nodeId);
220
431
  }
221
432
  return child;
222
433
  }
@@ -235,7 +446,7 @@ export class Node {
235
446
  if (child.parentNode !== this) throw new Error("the node to remove is not a child of this node");
236
447
  this.childNodes.splice(this.childNodes.indexOf(child), 1);
237
448
  child.parentNode = null;
238
- native.remove(child.id);
449
+ native.remove(child.nodeId);
239
450
  return child;
240
451
  }
241
452
 
@@ -245,12 +456,13 @@ export class Node {
245
456
 
246
457
  /** Detaches and frees this node and its subtree. They cannot be used again. */
247
458
  destroy() {
459
+ if (rootNode && this.contains(rootNode)) { clearAdoptedSheets(); rootNode = null; }
248
460
  const parent = this.parentNode;
249
461
  if (parent) {
250
462
  parent.childNodes.splice(parent.childNodes.indexOf(this), 1);
251
463
  this.parentNode = null;
252
464
  }
253
- native.destroy(this.id);
465
+ native.destroy(this.nodeId);
254
466
  forget(this);
255
467
  }
256
468
 
@@ -281,88 +493,54 @@ export class Node {
281
493
  * the address with `open`, as a click on an `<a>` follows it.
282
494
  *
283
495
  * `role` and `aria-*` work as in the DOM, spelled `aria-checked` or `ariaChecked`. A role
284
- * or ARIA name the tree does not know is ignored with a warning.
496
+ * the tree does not know is ignored with a warning. Literal ARIA and data attributes
497
+ * remain available to selectors even when they have no native accessibility mapping.
285
498
  */
499
+ get id() { return this._elementId ?? ""; }
500
+ set id(value) { this.setAttribute("id", String(value)); }
501
+ get className() { return this.getAttribute("class") ?? ""; }
502
+ set className(value) { this.setAttribute("class", String(value)); }
503
+ get classList() { return this.#classList ??= new ClassList(this); }
504
+
505
+ getAttribute(name) {
506
+ name = String(name);
507
+ const aria = ariaName(name);
508
+ name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
509
+ return this.#attributes?.get(name) ?? null;
510
+ }
511
+
512
+ hasAttribute(name) { return this.getAttribute(name) !== null; }
513
+ removeAttribute(name) { this.setAttribute(name, null); }
514
+
286
515
  setAttribute(name, value) {
287
- if (name === "role") {
288
- const words = value == null ? "" : String(value);
289
- if (!native.attribute(this.id, "role", words)) warnOnce("the tree has no role '" + words + "': it is ignored");
290
- return;
291
- }
292
- if (name === "id") {
293
- this.#identify(value == null ? "" : String(value));
294
- return;
295
- }
516
+ name = String(name);
296
517
  const aria = ariaName(name);
297
- if (aria !== null) {
298
- this.#aria(aria, value);
299
- return;
300
- }
301
- if (name === "href") {
302
- this._href = value ? String(value) : null;
303
- this.#want(KIND_OF.get("click"));
304
- }
305
- native.attribute(this.id, name, value);
306
- }
307
-
308
- #aria(name, value) {
309
- if (name === "label") {
310
- native.attribute(this.id, "label", value == null ? "" : String(value));
311
- } else if (name in ARIA_STATES) {
312
- // ARIA states are the words "true" and "false"; anything else is false.
313
- if (name === "checked") native.attribute(this.id, "indeterminate", value === "mixed");
314
- native.attribute(this.id, ARIA_STATES[name], value === true || value === "true");
315
- } else if (ARIA_RELATIONS.has(name)) {
316
- this.#relate(name, value == null ? [] : String(value).split(/\s+/).filter(Boolean));
317
- } else if (name in ARIA_RANGE) {
318
- const range = (this.#range ??= [undefined, undefined, undefined]);
319
- range[ARIA_RANGE[name]] = value == null || value === "" ? undefined : Number(value);
320
- const [min = 0, max = 100, now] = range;
321
- if (now === undefined || Number.isNaN(now)) native.attribute(this.id, "valueRange");
322
- else native.attribute(this.id, "valueRange", min, max, now);
323
- } else if (!native.attribute(this.id, "aria-" + name, value == null ? "" : String(value))) {
324
- warnOnce("the tree has no 'aria-" + name + "' yet: it is ignored");
518
+ name = aria === null ? name === "className" ? "class" : name : "aria-" + aria;
519
+ const text = value == null ? null : String(value);
520
+ if (name === "role") {
521
+ if (!native.attribute(this.nodeId, "role", text ?? "")) warnOnce("the tree has no role '" + text + "': it is ignored");
522
+ } else if (name === "id") {
523
+ this.#identify(text);
524
+ } else if (aria !== null) {
525
+ native.attribute(this.nodeId, name, text);
526
+ } else {
527
+ if (name === "href") {
528
+ this._href = text || null;
529
+ this.#want(KIND_OF.get("click"));
530
+ }
531
+ native.attribute(this.nodeId, name,
532
+ name === "class" || name === "lang" || name === "dir" || name.startsWith("data-") ? text : value);
325
533
  }
534
+ if (text === null) this.#attributes?.delete(name);
535
+ else (this.#attributes ??= new Map()).set(name, text);
326
536
  }
327
537
 
328
538
  // The `id` other nodes' relations name this node by.
329
539
  #identify(id) {
330
540
  const old = this._elementId ?? "";
331
- if (old === id) return;
332
- if (old && byId.get(old) === this) {
333
- byId.delete(old);
334
- resolveNaming(old);
335
- }
541
+ if (old === (id ?? "") && this.getAttribute("id") === id) return;
336
542
  this._elementId = id || undefined;
337
- native.attribute(this.id, "id", id);
338
- if (id) {
339
- byId.set(id, this);
340
- resolveNaming(id);
341
- }
342
- }
343
-
344
- // Sets relation `name` (`labelledby`) to the nodes with ids `refs`, as they are now and
345
- // as they change.
346
- #relate(name, refs) {
347
- const relations = (this._relations ??= new Map());
348
- for (const ref of relations.get(name) ?? []) naming.get(ref)?.delete(this);
349
- if (refs.length) relations.set(name, refs);
350
- else relations.delete(name);
351
- for (const ref of refs) {
352
- let sources = naming.get(ref);
353
- if (!sources) naming.set(ref, (sources = new Set()));
354
- sources.add(this);
355
- }
356
- this._sendRelation(name);
357
- }
358
-
359
- _sendRelation(name) {
360
- const numbers = [];
361
- for (const ref of this._relations?.get(name) ?? []) {
362
- const target = byId.get(ref);
363
- if (target) numbers.push(target.id);
364
- }
365
- native.attribute(this.id, "aria-" + name, numbers.join(" "));
543
+ native.attribute(this.nodeId, "id", id);
366
544
  }
367
545
 
368
546
  // Tells the tree which events this node wants: its listeners', and clicks on a link.
@@ -370,23 +548,23 @@ export class Node {
370
548
  const list = this.#listeners?.get(TYPES[kind]);
371
549
  const wanted = (list && list.length > 0) || (kind === CLICK && this._href);
372
550
  const flags = wanted ? this.#flags | (1 << kind) : this.#flags & ~(1 << kind);
373
- if (flags !== this.#flags) native.listen(this.id, (this.#flags = flags));
551
+ if (flags !== this.#flags) native.listen(this.nodeId, (this.#flags = flags));
374
552
  }
375
553
 
376
554
  set tabIndex(value) {
377
- native.attribute(this.id, "tabIndex", value);
555
+ native.attribute(this.nodeId, "tabIndex", value);
378
556
  }
379
557
 
380
558
  set disabled(value) {
381
- native.attribute(this.id, "disabled", value);
559
+ native.attribute(this.nodeId, "disabled", value);
382
560
  }
383
561
 
384
562
  focus() {
385
- native.focus(this.id);
563
+ native.focus(this.nodeId);
386
564
  }
387
565
 
388
566
  scrollTo(x, y) {
389
- native.scrollTo(this.id, x, y);
567
+ native.scrollTo(this.nodeId, x, y);
390
568
  }
391
569
 
392
570
  /**
@@ -395,14 +573,14 @@ export class Node {
395
573
  */
396
574
  addEventListener(type, listener, options) {
397
575
  const kind = KIND_OF.get(type);
398
- if (kind === undefined) throw new TypeError("the tree has no event '" + type + "'");
576
+ if (kind === undefined && !DRAG_TYPES.has(type)) throw new TypeError("the tree has no event '" + type + "'");
399
577
  const capture = options === true || !!options?.capture;
400
578
  this.#listeners ??= new Map();
401
579
  let list = this.#listeners.get(type);
402
580
  if (!list) this.#listeners.set(type, (list = []));
403
581
  if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
404
582
  list.push({ listener, capture, once: !!options?.once });
405
- this.#want(kind);
583
+ if (kind !== undefined) this.#want(kind);
406
584
  }
407
585
 
408
586
  removeEventListener(type, listener, options) {
@@ -412,7 +590,8 @@ export class Node {
412
590
  const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
413
591
  if (index < 0) return;
414
592
  list.splice(index, 1);
415
- this.#want(KIND_OF.get(type));
593
+ const kind = KIND_OF.get(type);
594
+ if (kind !== undefined) this.#want(kind);
416
595
  }
417
596
 
418
597
  /** Runs the capture or the bubble listeners of `event.type`. Used by the dispatcher. */
@@ -450,7 +629,7 @@ export class Text extends Node {
450
629
  value = String(value);
451
630
  if (value === this.#data && value !== "") return;
452
631
  this.#data = value;
453
- native.setText(this.id, value);
632
+ native.setText(this.nodeId, value);
454
633
  }
455
634
 
456
635
  get textContent() {
@@ -478,12 +657,12 @@ export class Input extends Node {
478
657
 
479
658
  set value(value) {
480
659
  this.#value = String(value);
481
- native.setText(this.id, this.#value);
660
+ native.setText(this.nodeId, this.#value);
482
661
  }
483
662
 
484
663
  /** Selects from `anchor` to `focus`, as UTF-8 byte offsets in the value. */
485
664
  setSelectionRange(anchor, focus) {
486
- native.select(this.id, anchor, focus);
665
+ native.select(this.nodeId, anchor, focus);
487
666
  }
488
667
 
489
668
  _changed(value, anchor, focus) {
@@ -545,7 +724,7 @@ export class Icon extends Node {
545
724
  if (markup === this.#svg) return;
546
725
  if (this.#svg) dropIcon(this.#svg);
547
726
  this.#svg = markup;
548
- native.source(this.id, markup ? holdIcon(markup) : 0);
727
+ native.source(this.nodeId, markup ? holdIcon(markup) : 0);
549
728
  }
550
729
 
551
730
  _forget() {
@@ -653,12 +832,12 @@ export class RichInput extends Input {
653
832
 
654
833
  /** What text with mark `name` looks like: properties as `style.set` takes them. */
655
834
  defineMark(name, style) {
656
- native.mark(this.id, this.#bit(name), cssTextOf(style));
835
+ native.mark(this.nodeId, this.#bit(name), cssTextOf(style));
657
836
  }
658
837
 
659
838
  /** What atoms of `kind` look like: the inline block holding the label. */
660
839
  defineAtom(kind, style) {
661
- native.atomStyle(this.id, this.#kind(kind), cssTextOf(style));
840
+ native.atomStyle(this.nodeId, this.#kind(kind), cssTextOf(style));
662
841
  }
663
842
 
664
843
  get document() {
@@ -679,7 +858,7 @@ export class RichInput extends Input {
679
858
  }
680
859
  let packedAtoms = "";
681
860
  for (const atom of atoms) packedAtoms += this.#packAtom(atom);
682
- native.richText(this.id, text, packedMarks, packedAtoms);
861
+ native.richText(this.nodeId, text, packedMarks, packedAtoms);
683
862
  super._changed(text, text.length, text.length);
684
863
  }
685
864
 
@@ -689,7 +868,7 @@ export class RichInput extends Input {
689
868
 
690
869
  /** Turns mark `name` on or off over the selection, or for the text typed next. */
691
870
  format(name, on = true) {
692
- native.format(this.id, this.#bit(name), !!on);
871
+ native.format(this.nodeId, this.#bit(name), !!on);
693
872
  }
694
873
 
695
874
  /** Turns mark `name` off where the caret's text has it, on where it does not. */
@@ -700,12 +879,12 @@ export class RichInput extends Input {
700
879
  /** Replaces the text from `start` to `end` with `atom` (`{ kind, label, data }`). */
701
880
  insertAtom(start, end, atom) {
702
881
  const text = this.#document.text;
703
- native.insertAtom(this.id, byteOf(text, start), byteOf(text, end), this.#packAtom(atom));
882
+ native.insertAtom(this.nodeId, byteOf(text, start), byteOf(text, end), this.#packAtom(atom));
704
883
  }
705
884
 
706
885
  setSelectionRange(anchor, focus) {
707
886
  const text = this.#document.text;
708
- native.select(this.id, byteOf(text, anchor), byteOf(text, focus));
887
+ native.select(this.nodeId, byteOf(text, anchor), byteOf(text, focus));
709
888
  }
710
889
 
711
890
  _changed(value, anchor, focus, marks, atoms, active) {
@@ -740,22 +919,8 @@ export function createRichInput(style) {
740
919
  return input;
741
920
  }
742
921
 
743
- // Sends again the relations that name `ref`, after the node with that id changed.
744
- function resolveNaming(ref) {
745
- for (const source of naming.get(ref) ?? []) {
746
- for (const [name, refs] of source._relations) if (refs.includes(ref)) source._sendRelation(name);
747
- }
748
- }
749
-
750
922
  function forget(node) {
751
- nodes.delete(node.id);
752
- if (node._relations) {
753
- for (const refs of node._relations.values()) for (const ref of refs) naming.get(ref)?.delete(node);
754
- }
755
- if (node._elementId && byId.get(node._elementId) === node) {
756
- byId.delete(node._elementId);
757
- resolveNaming(node._elementId);
758
- }
923
+ nodes.delete(node.nodeId);
759
924
  node._forget?.();
760
925
  for (const child of node.childNodes) {
761
926
  child.parentNode = null;
@@ -826,8 +991,10 @@ export function defineKeyframes(name, frames) {
826
991
  }
827
992
 
828
993
  export function mount(node) {
994
+ if (rootNode) clearAdoptedSheets();
829
995
  rootNode = node;
830
- native.root(node.id);
996
+ native.root(node.nodeId);
997
+ syncAdoptedSheets();
831
998
  return node;
832
999
  }
833
1000
 
@@ -989,7 +1156,7 @@ function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth)
989
1156
  } else if (kind >= 19 && kind <= 22) {
990
1157
  event.propertyName = first;
991
1158
  event.elapsedTime = a;
992
- event.pseudoElement = "";
1159
+ event.pseudoElement = second ?? "";
993
1160
  } else if (kind === 27) {
994
1161
  event.target._selected?.(a, b, d);
995
1162
  event.selectionStart = event.target.selectionStart;
@@ -997,7 +1164,7 @@ function fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth)
997
1164
  } else if (kind >= 23) {
998
1165
  event.animationName = first;
999
1166
  event.elapsedTime = a;
1000
- event.pseudoElement = "";
1167
+ event.pseudoElement = second ?? "";
1001
1168
  }
1002
1169
  }
1003
1170
 
@@ -1059,7 +1226,8 @@ function follow(target) {
1059
1226
  // The host calls this before it replaces the realm, on a reload: every node goes, so the
1060
1227
  // next realm starts on an empty tree.
1061
1228
  native.unload = function () {
1062
- for (const node of [...nodes.values()]) if (!node.parentNode && nodes.has(node.id)) node.destroy();
1229
+ importedSheets.clear();
1230
+ for (const node of [...nodes.values()]) if (!node.parentNode && nodes.has(node.nodeId)) node.destroy();
1063
1231
  rootNode = null;
1064
1232
  };
1065
1233
 
@@ -1070,3 +1238,273 @@ native.takeError = function () {
1070
1238
  pendingError = null;
1071
1239
  throw error;
1072
1240
  };
1241
+
1242
+ // The desktop around the window: files dragged in from other apps, notifications, the tray
1243
+ // and global shortcuts. The host serves `__ui.shell` calls after the code that made them has
1244
+ // run and answers through `__ui.shellAnswer`; desktop events arrive through `__ui.shellEvent`.
1245
+
1246
+ const shellCalls = new Map();
1247
+ let nextShellCall = 0;
1248
+
1249
+ function shellCall(op, fields) {
1250
+ const call = ++nextShellCall;
1251
+ return new Promise((resolve) => {
1252
+ shellCalls.set(call, resolve);
1253
+ native.shell(call, op, fields.join("\x1f"));
1254
+ });
1255
+ }
1256
+
1257
+ native.shellAnswer = function (call, value) {
1258
+ const resolve = shellCalls.get(call);
1259
+ if (!resolve) return;
1260
+ shellCalls.delete(call);
1261
+ resolve(value);
1262
+ };
1263
+
1264
+ /** A file dragged in from the desktop, as the web's `File`, with its `path` on disk. */
1265
+ export class DroppedFile {
1266
+ constructor(path) {
1267
+ this.path = path;
1268
+ this.name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
1269
+ this.type = "";
1270
+ }
1271
+ }
1272
+
1273
+ /**
1274
+ * What a file drag carries, as the web's `DataTransfer`: `types` is `["Files"]` while files
1275
+ * are over the window, and `files` lists them in `drop`, as on the web.
1276
+ */
1277
+ export class DataTransfer {
1278
+ constructor(paths) {
1279
+ this.files = paths.map((path) => new DroppedFile(path));
1280
+ this.items = this.files.map((file) => ({ kind: "file", type: "", getAsFile: () => file }));
1281
+ this.types = ["Files"];
1282
+ this.dropEffect = "copy";
1283
+ this.effectAllowed = "copy";
1284
+ }
1285
+
1286
+ getData() {
1287
+ return "";
1288
+ }
1289
+ }
1290
+
1291
+ let dragTarget = null;
1292
+
1293
+ function dragEvent(type, target, x, y, paths) {
1294
+ const event = new Event(type, target);
1295
+ event.clientX = event.x = x;
1296
+ event.clientY = event.y = y;
1297
+ event.dataTransfer = new DataTransfer(paths);
1298
+ dispatchEvent(event);
1299
+ }
1300
+
1301
+ // As the web: `dragenter` on the node now under the files, `dragleave` on the one before,
1302
+ // then `dragover` on the current one.
1303
+ function dragTo(target, x, y) {
1304
+ if (target !== dragTarget) {
1305
+ const before = dragTarget;
1306
+ dragTarget = target;
1307
+ if (target) dragEvent("dragenter", target, x, y, []);
1308
+ if (before) dragEvent("dragleave", before, x, y, []);
1309
+ }
1310
+ if (target) dragEvent("dragover", target, x, y, []);
1311
+ }
1312
+
1313
+ let trayMenu = new Map();
1314
+ let trayClick = null;
1315
+ const shortcuts = new Map();
1316
+ const shortcutIds = new Map();
1317
+ let nextShortcut = 0;
1318
+ const notifications = new Map();
1319
+
1320
+ native.shellEvent = function (kind, a, x, y, text) {
1321
+ if (kind <= 3) {
1322
+ const target = nodes.get(a) ?? rootNode;
1323
+ if (kind === 2) {
1324
+ const before = dragTarget;
1325
+ dragTarget = null;
1326
+ if (before) dragEvent("dragleave", before, x, y, []);
1327
+ } else if (kind === 3) {
1328
+ if (target !== dragTarget) dragTo(target, x, y);
1329
+ dragTarget = null;
1330
+ if (target) dragEvent("drop", target, x, y, text ? text.split("\n") : []);
1331
+ } else {
1332
+ dragTo(target, x, y);
1333
+ }
1334
+ } else if (kind === 4) {
1335
+ shortcuts.get(a)?.();
1336
+ } else if (kind === 5) {
1337
+ trayClick?.({ button: a });
1338
+ } else if (kind === 6) {
1339
+ trayMenu.get(a)?.();
1340
+ } else if (kind === 7) {
1341
+ const notification = notifications.get(a);
1342
+ if (!notification) return;
1343
+ notifications.delete(a);
1344
+ notification._fire("click");
1345
+ }
1346
+ };
1347
+
1348
+ // Notifications nobody clicked are forgotten after this many newer ones.
1349
+ const NOTIFICATIONS_KEPT = 64;
1350
+
1351
+ /**
1352
+ * A desktop notification, as the web's: `new Notification(title, { body })`, with `onclick`
1353
+ * or a `click` listener. Permission is always granted.
1354
+ */
1355
+ export class Notification {
1356
+ static permission = "granted";
1357
+
1358
+ static requestPermission(callback) {
1359
+ callback?.("granted");
1360
+ return Promise.resolve("granted");
1361
+ }
1362
+
1363
+ #listeners = new Map();
1364
+
1365
+ constructor(title, options = {}) {
1366
+ this.title = String(title);
1367
+ this.body = String(options.body ?? "");
1368
+ this.tag = String(options.tag ?? "");
1369
+ this.data = options.data ?? null;
1370
+ this.onclick = this.onshow = this.onerror = this.onclose = null;
1371
+ shellCall(0, [this.title, this.body]).then((id) => {
1372
+ if (!id) return this._fire("error");
1373
+ notifications.set(id, this);
1374
+ if (notifications.size > NOTIFICATIONS_KEPT) notifications.delete(notifications.keys().next().value);
1375
+ this._fire("show");
1376
+ });
1377
+ }
1378
+
1379
+ /** The system keeps the notification until the user dismisses it. */
1380
+ close() {}
1381
+
1382
+ addEventListener(type, listener) {
1383
+ let list = this.#listeners.get(type);
1384
+ if (!list) this.#listeners.set(type, (list = []));
1385
+ if (!list.includes(listener)) list.push(listener);
1386
+ }
1387
+
1388
+ removeEventListener(type, listener) {
1389
+ const list = this.#listeners.get(type);
1390
+ const index = list ? list.indexOf(listener) : -1;
1391
+ if (index >= 0) list.splice(index, 1);
1392
+ }
1393
+
1394
+ _fire(type) {
1395
+ const event = { type, target: this, currentTarget: this };
1396
+ const handler = this["on" + type];
1397
+ try {
1398
+ if (typeof handler === "function") handler.call(this, event);
1399
+ for (const listener of (this.#listeners.get(type) ?? []).slice()) listener.call(this, event);
1400
+ } catch (error) {
1401
+ reportError(error);
1402
+ }
1403
+ }
1404
+ }
1405
+
1406
+ globalThis.Notification ??= Notification;
1407
+
1408
+ function hex(bytes) {
1409
+ let text = "";
1410
+ for (let i = 0; i < bytes.length; i++) text += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
1411
+ return text;
1412
+ }
1413
+
1414
+ function packMenu(items, lines) {
1415
+ for (const item of items) {
1416
+ if (item.type === "separator") lines.push("S");
1417
+ else if (item.submenu) {
1418
+ lines.push("B" + String(item.label ?? "").replace(/\n/g, " "));
1419
+ packMenu(item.submenu, lines);
1420
+ lines.push("E");
1421
+ } else {
1422
+ const action = trayMenu.size + 1;
1423
+ trayMenu.set(action, typeof item.click === "function" ? item.click : () => {});
1424
+ const label = String(item.label ?? "").replace(/\n/g, " ");
1425
+ lines.push("A" + action + "," + (item.enabled === false ? 0 : 1) + "," + (item.checked ? 1 : 0) + "," + label);
1426
+ }
1427
+ }
1428
+ }
1429
+
1430
+ /**
1431
+ * Shows an icon in the system tray (the macOS menu bar, the Windows notification area, a
1432
+ * StatusNotifierItem on Linux). `icon` is RGBA pixels, as an `ImageData`: `{ width, height,
1433
+ * data }`; macOS draws a `template` icon from its alpha in the menu bar's colours. `menu`
1434
+ * items are `{ label, click, enabled, checked }`, `{ type: "separator" }` or `{ label,
1435
+ * submenu }`. With no menu, `onClick({ button })` runs when the icon is clicked. Calling it
1436
+ * again replaces the tray. Resolves to whether the system shows it.
1437
+ */
1438
+ export function setTray({ icon, tooltip = "", template = false, menu = [], onClick = null }) {
1439
+ if (!icon || !(icon.width > 0) || !(icon.height > 0) || icon.data?.length !== icon.width * icon.height * 4) {
1440
+ throw new TypeError("setTray needs an icon of RGBA pixels: { width, height, data }");
1441
+ }
1442
+ trayMenu = new Map();
1443
+ trayClick = typeof onClick === "function" ? onClick : null;
1444
+ const lines = [];
1445
+ packMenu(menu, lines);
1446
+ const fields = [String(tooltip), icon.width, icon.height, template ? 1 : 0, hex(icon.data), lines.join("\n")];
1447
+ return shellCall(1, fields).then((shown) => shown === 1);
1448
+ }
1449
+
1450
+ /** Takes the tray icon away. */
1451
+ export function removeTray() {
1452
+ trayMenu = new Map();
1453
+ trayClick = null;
1454
+ shellCall(2, []);
1455
+ }
1456
+
1457
+ const MODIFIERS = { shift: 1, ctrl: 2, control: 2, alt: 4, option: 4, meta: 8, cmd: 8, command: 8, super: 8, mod: 16, cmdorctrl: 16, commandorcontrol: 16 };
1458
+ const KEY_NAMES = {
1459
+ up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", esc: "Escape", return: "Enter",
1460
+ space: " ", plus: "Equal", "=": "Equal", "-": "Minus", ",": "Comma", ".": "Period", "/": "Slash",
1461
+ ";": "Semicolon", "'": "Quote", "[": "BracketLeft", "]": "BracketRight", "\\": "Backslash", "`": "Backquote",
1462
+ };
1463
+
1464
+ // "Mod+Shift+K" as the UI Events `code` of the key and the modifier bits; `Mod` (also
1465
+ // `CmdOrCtrl`) is Command on macOS and Control elsewhere.
1466
+ function parseShortcut(accelerator) {
1467
+ const parts = String(accelerator).split("+").map((part) => part.trim()).filter(Boolean);
1468
+ let bits = 0;
1469
+ let code = "";
1470
+ for (const part of parts) {
1471
+ const modifier = MODIFIERS[part.toLowerCase()];
1472
+ if (modifier !== undefined) {
1473
+ bits |= modifier;
1474
+ continue;
1475
+ }
1476
+ const named = KEY_NAMES[part.toLowerCase()] ?? part;
1477
+ if (named === " ") code = "Space";
1478
+ else if (/^[a-z]$/i.test(named)) code = "Key" + named.toUpperCase();
1479
+ else if (/^[0-9]$/.test(named)) code = "Digit" + named;
1480
+ else code = named[0].toUpperCase() + named.slice(1);
1481
+ }
1482
+ if (!code) throw new TypeError("'" + accelerator + "' names no key");
1483
+ return { code, bits };
1484
+ }
1485
+
1486
+ /**
1487
+ * Runs `callback` when the keys of `accelerator` are pressed, whichever app has focus:
1488
+ * `"Mod+Shift+K"`, where `Mod` is Command on macOS and Control elsewhere, and the key is a
1489
+ * letter, a digit, a UI Events `code` (`"F5"`, `"ArrowUp"`, `"Slash"`) or a name such as
1490
+ * `Space` or `Esc`. Registering it again replaces the callback. Resolves to whether the
1491
+ * system took it: another app may hold it, and Wayland has no global shortcuts.
1492
+ */
1493
+ export function registerShortcut(accelerator, callback) {
1494
+ const { code, bits } = parseShortcut(accelerator);
1495
+ const key = code + "+" + bits;
1496
+ let id = shortcutIds.get(key);
1497
+ if (id === undefined) shortcutIds.set(key, (id = ++nextShortcut));
1498
+ shortcuts.set(id, callback);
1499
+ return shellCall(3, [id, code, bits]).then((held) => held === 1);
1500
+ }
1501
+
1502
+ /** Stops the shortcut of `accelerator`. */
1503
+ export function unregisterShortcut(accelerator) {
1504
+ const { code, bits } = parseShortcut(accelerator);
1505
+ const id = shortcutIds.get(code + "+" + bits);
1506
+ if (id === undefined) return;
1507
+ shortcutIds.delete(code + "+" + bits);
1508
+ shortcuts.delete(id);
1509
+ shellCall(4, [id]);
1510
+ }