@silkui/core 0.1.2 → 0.1.4

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
@@ -61,11 +61,20 @@ mount(createBox({ position: "absolute", inset: 0, display: "flex", alignItems: "
61
61
  | `createText(data?)` | A text node. It takes its look from its parent |
62
62
  | `createInput(style?)` | An editable text field. `value`, `selectionStart`, `selectionEnd` and `setSelectionRange` work as on an `<input>` |
63
63
  | `createRichInput(style?)` | A text field with marks and inline atoms (see below) |
64
- | `createIcon(svg, style?)` | SVG markup drawn at the node's size, with its `color` as `currentColor` |
65
- | `createNode(kind)` | A node of any kind: `"box"`, `"text"`, `"input"`, `"richinput"`, `"image"`, `"icon"`, `"canvas"` |
64
+ | `createImage(src, style?)` | An image, as an `<img>`: `src` is a `data:` URL, a file or an `http(s):` address. An SVG file draws as an inline `<svg>` |
65
+ | `createIcon(svg, style?)` | SVG markup drawn at the node's size, with its `color` as `currentColor`. `icon.src` takes an SVG address instead |
66
+ | `createSvgElement(tag)` | `document.createElementNS` for SVG: an `Svg` root for `"svg"`, else an `SvgElement` (`path`, `g`, ...) to append inside one |
67
+ | `createNode(kind)` | A node of any kind: `"box"`, `"text"`, `"input"`, `"richinput"`, `"image"` (or `"img"`), `"icon"`, `"canvas"`, `"svg"` |
66
68
  | `mount(node)` / `root()` | Makes a node the root of the window's tree, or returns it |
67
69
  | `nodeById(id)` | The node with a tree id, for hosts and tools |
68
70
 
71
+ An `Svg` is one icon node whose markup its `SvgElement` and text children make, as an inline
72
+ `<svg>` is on a page. Class, look, events and ARIA attributes are the node's; `viewBox`,
73
+ `fill`, `width` and every other attribute are markup, and React's spellings (`strokeWidth`)
74
+ work too. Changes are drawn once, before the host applies the batch (`flushSvg()` draws them
75
+ now). Without a CSS size it takes the `<svg>`'s `width` and `height`, else a square of the
76
+ font size. Elements inside it hear no events: listen on the `Svg`.
77
+
69
78
  A node has `append`, `appendChild`, `insertBefore`, `removeChild`, `remove`, `contains`,
70
79
  `parentNode`, `childNodes`, `firstChild`, `lastChild` and the sibling getters, as in the DOM.
71
80
  A removed node keeps its state and can be inserted again. `destroy()` frees a node and its
@@ -115,10 +124,40 @@ through the tree.
115
124
  | `layout` | `bounds`: where layout put the node, in window pixels |
116
125
  | `transitionrun`, `transitionstart`, `transitionend`, `transitioncancel` | `propertyName`, `elapsedTime` |
117
126
  | `animationstart`, `animationiteration`, `animationend`, `animationcancel` | `animationName`, `elapsedTime` |
127
+ | `dragenter`, `dragover`, `dragleave`, `drop` | `clientX`, `clientY`, `dataTransfer` (files dragged in from other apps) |
118
128
 
119
129
  A listener that throws does not stop the dispatch. `setErrorHandler(handler)` receives the
120
130
  exception; without one the host reports it.
121
131
 
132
+ ### The desktop
133
+
134
+ Files dragged in from other apps fire `dragenter`, `dragover`, `dragleave` and `drop` on the
135
+ node under them, and bubble, as on the web. `event.dataTransfer.types` is `["Files"]` while
136
+ they are over the window, and `drop` lists them in `dataTransfer.files`, each with its `name`
137
+ and its `path` on disk.
138
+
139
+ ```ts
140
+ zone.addEventListener("drop", (event) => open(event.dataTransfer.files[0].path));
141
+ ```
142
+
143
+ `Notification` is the web's: `new Notification("Built", { body: "In 2 s" })`, with `onclick`.
144
+ Permission is always granted. Two things the web has no API for come from the package:
145
+
146
+ ```ts
147
+ import { setTray, registerShortcut } from "@silkui/core";
148
+
149
+ setTray({
150
+ icon: { width: 32, height: 32, data: pixels }, // RGBA, as an ImageData
151
+ tooltip: "Builds",
152
+ menu: [{ label: "Build now", click: build }, { type: "separator" }, { label: "Quit", click: quit }],
153
+ });
154
+ registerShortcut("Mod+Shift+B", build); // Mod is Command on macOS, Control elsewhere
155
+ ```
156
+
157
+ `setTray` and `registerShortcut` resolve to whether the system took them. A shortcut works
158
+ whichever app has focus; another app may hold it, and Wayland has none. `removeTray()` and
159
+ `unregisterShortcut(accelerator)` undo them.
160
+
122
161
  ### Attributes and accessibility
123
162
 
124
163
  `setAttribute(name, value)` sets the tree's attributes: `tabIndex`, `disabled`, `label`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkui/core",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
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
@@ -173,10 +173,66 @@ export class RichInput extends Input {
173
173
  setSelectionRange(anchor: number, focus: number): void;
174
174
  }
175
175
 
176
- /** An icon: SVG markup drawn at the node's CSS size, with its `color` as `currentColor`. */
176
+ /**
177
+ * An image, as an `<img>`: `src` is a `data:` URL, a file or `http(s):` address. An SVG
178
+ * file draws as an inline `<svg>` does. It hears `load` and `error`.
179
+ */
180
+ export class Image extends Node {
181
+ constructor(src?: string);
182
+ src: string;
183
+ }
184
+
185
+ /**
186
+ * An icon: SVG drawn at the node's CSS size, with its `color` as `currentColor`. Without a
187
+ * CSS size it takes the `<svg>`'s `width` and `height`, else a square of the font size.
188
+ * `svg` is markup and `src` the address of an SVG file; setting one clears the other.
189
+ */
177
190
  export class Icon extends Node {
178
191
  constructor(svg?: string);
179
192
  svg: string;
193
+ src: string;
194
+ }
195
+
196
+ /** Text inside an `<svg>`. */
197
+ export class SvgText {
198
+ constructor(data?: string);
199
+ data: string;
200
+ textContent: string;
201
+ readonly parentNode: SvgElement | Svg | null;
202
+ remove(): void;
203
+ destroy(): void;
204
+ }
205
+
206
+ /** An element inside an `<svg>` (`path`, `g`, `circle`...): markup its root draws, no node. */
207
+ export class SvgElement {
208
+ constructor(tag: string);
209
+ readonly localName: string;
210
+ readonly tagName: string;
211
+ readonly namespaceURI: string;
212
+ readonly parentNode: SvgElement | Svg | null;
213
+ readonly childNodes: (SvgElement | SvgText | Text)[];
214
+ textContent: string;
215
+ getAttribute(name: string): string | null;
216
+ hasAttribute(name: string): boolean;
217
+ /** SVG's names, or React's spellings (`strokeWidth`, `xlinkHref`). */
218
+ setAttribute(name: string, value: unknown): void;
219
+ removeAttribute(name: string): void;
220
+ insertBefore<T extends SvgElement | SvgText | Text>(child: T, before?: SvgElement | SvgText | Text | null): T;
221
+ appendChild<T extends SvgElement | SvgText | Text>(child: T): T;
222
+ append(...children: (SvgElement | SvgText | Text | string)[]): void;
223
+ removeChild<T extends SvgElement | SvgText | Text>(child: T): T;
224
+ remove(): void;
225
+ destroy(): void;
226
+ }
227
+
228
+ /**
229
+ * An inline `<svg>`: an icon node whose markup its `SvgElement` children make. Class, look,
230
+ * events and ARIA are the node's; `viewBox`, `fill`, `width` and the rest are markup.
231
+ */
232
+ export class Svg extends Icon {
233
+ constructor();
234
+ readonly outerHTML: string;
235
+ textContent: string;
180
236
  }
181
237
 
182
238
  /** An event of the tree, with the members of the DOM event it corresponds to. */
@@ -298,12 +354,18 @@ export interface EventMap {
298
354
  animationiteration: AnimationEvent;
299
355
  animationend: AnimationEvent;
300
356
  animationcancel: AnimationEvent;
357
+ dragenter: DragEvent;
358
+ dragover: DragEvent;
359
+ dragleave: DragEvent;
360
+ drop: DragEvent;
301
361
  }
302
362
 
303
363
  export function createNode(kind: "text"): Text;
304
364
  export function createNode(kind: "input"): Input;
305
365
  export function createNode(kind: "richinput"): RichInput;
306
366
  export function createNode(kind: "icon"): Icon;
367
+ export function createNode(kind: "image" | "img"): Image;
368
+ export function createNode(kind: "svg"): Svg;
307
369
  export function createNode(kind: NodeKind): Node;
308
370
 
309
371
  /** A box with `style` as its base look and `children` appended. */
@@ -313,6 +375,13 @@ export function createInput(style?: Style | null): Input;
313
375
  export function createRichInput(style?: Style | null): RichInput;
314
376
  /** An icon showing `svg` markup, with `style` as its base look. */
315
377
  export function createIcon(svg: string, style?: Style | null): Icon;
378
+ /** An image showing `src`, with `style` as its base look. */
379
+ export function createImage(src: string, style?: Style | null): Image;
380
+ /** `document.createElementNS` in the SVG namespace: an `Svg` for `svg`, else an `SvgElement`. */
381
+ export function createSvgElement(tag: "svg"): Svg;
382
+ export function createSvgElement(tag: string): SvgElement;
383
+ /** Draws the `<svg>`s that changed now, rather than before the host applies the batch. */
384
+ export function flushSvg(): void;
316
385
 
317
386
  /**
318
387
  * Defines `@keyframes name`: `{ from: { opacity: 0 }, "50%": { ... }, to: { ... } }`.
@@ -354,3 +423,80 @@ export function parseMarkdown(text: string, options?: MarkdownOptions): import("
354
423
 
355
424
  /** What happens to an exception a listener throws. Without a handler, the host reports it. */
356
425
  export function setErrorHandler(handler: ((error: unknown) => void) | null): void;
426
+
427
+ /** A file dragged in from the desktop, as the web's `File`, with its `path` on disk. */
428
+ export class DroppedFile {
429
+ readonly name: string;
430
+ readonly path: string;
431
+ readonly type: string;
432
+ }
433
+
434
+ /** What a file drag carries. `files` is filled in `drop`, as on the web. */
435
+ export class DataTransfer {
436
+ readonly files: DroppedFile[];
437
+ readonly items: { kind: "file"; type: string; getAsFile(): DroppedFile }[];
438
+ readonly types: string[];
439
+ dropEffect: string;
440
+ effectAllowed: string;
441
+ getData(format: string): string;
442
+ }
443
+
444
+ /** Files dragged from another app over the window (`dragenter`, `dragover`, `dragleave`, `drop`). */
445
+ export interface DragEvent extends Event {
446
+ clientX: number;
447
+ clientY: number;
448
+ x: number;
449
+ y: number;
450
+ dataTransfer: DataTransfer;
451
+ }
452
+
453
+ export interface NotificationOptions {
454
+ body?: string;
455
+ tag?: string;
456
+ data?: unknown;
457
+ }
458
+
459
+ /** A desktop notification, as the web's. Permission is always granted. */
460
+ export class Notification {
461
+ static readonly permission: "granted";
462
+ static requestPermission(callback?: (permission: "granted") => void): Promise<"granted">;
463
+ constructor(title: string, options?: NotificationOptions);
464
+ readonly title: string;
465
+ readonly body: string;
466
+ readonly tag: string;
467
+ readonly data: unknown;
468
+ onclick: ((event: { type: "click"; target: Notification }) => void) | null;
469
+ onshow: ((event: { type: "show"; target: Notification }) => void) | null;
470
+ onerror: ((event: { type: "error"; target: Notification }) => void) | null;
471
+ onclose: ((event: { type: "close"; target: Notification }) => void) | null;
472
+ close(): void;
473
+ addEventListener(type: "click" | "show" | "error" | "close", listener: (event: { type: string; target: Notification }) => void): void;
474
+ removeEventListener(type: "click" | "show" | "error" | "close", listener: (event: { type: string; target: Notification }) => void): void;
475
+ }
476
+
477
+ export type TrayMenuItem =
478
+ | { label: string; click?: () => void; enabled?: boolean; checked?: boolean }
479
+ | { type: "separator" }
480
+ | { label: string; submenu: TrayMenuItem[] };
481
+
482
+ export interface TrayOptions {
483
+ /** RGBA pixels, as an `ImageData`. 32 by 32 looks right everywhere. */
484
+ icon: { width: number; height: number; data: ArrayLike<number> };
485
+ tooltip?: string;
486
+ /** macOS draws the icon from its alpha, in the menu bar's colours. */
487
+ template?: boolean;
488
+ menu?: TrayMenuItem[];
489
+ /** Runs on a click when there is no menu. `button` is `MouseEvent.button`'s. */
490
+ onClick?: (event: { button: number }) => void;
491
+ }
492
+
493
+ /** Shows an icon in the system tray; calling it again replaces it. Resolves to whether it shows. */
494
+ export function setTray(options: TrayOptions): Promise<boolean>;
495
+ export function removeTray(): void;
496
+
497
+ /**
498
+ * Runs `callback` when `accelerator` (`"Mod+Shift+K"`; `Mod` is Command on macOS, Control
499
+ * elsewhere) is pressed, whichever app has focus. Resolves to whether the system took it.
500
+ */
501
+ export function registerShortcut(accelerator: string, callback: () => void): Promise<boolean>;
502
+ 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();
@@ -521,6 +523,12 @@ export class Node {
521
523
  this.#identify(text);
522
524
  } else if (aria !== null) {
523
525
  native.attribute(this.nodeId, name, text);
526
+ } else if (name === "src") {
527
+ // An image's or icon's address, as `<img src>`.
528
+ if ("src" in this) this.src = text ?? "";
529
+ else warnOnce("only an image or an icon has a src: it is ignored");
530
+ } else if (name === "alt") {
531
+ native.attribute(this.nodeId, "label", text ?? "");
524
532
  } else {
525
533
  if (name === "href") {
526
534
  this._href = text || null;
@@ -571,14 +579,14 @@ export class Node {
571
579
  */
572
580
  addEventListener(type, listener, options) {
573
581
  const kind = KIND_OF.get(type);
574
- if (kind === undefined) throw new TypeError("the tree has no event '" + type + "'");
582
+ if (kind === undefined && !DRAG_TYPES.has(type)) throw new TypeError("the tree has no event '" + type + "'");
575
583
  const capture = options === true || !!options?.capture;
576
584
  this.#listeners ??= new Map();
577
585
  let list = this.#listeners.get(type);
578
586
  if (!list) this.#listeners.set(type, (list = []));
579
587
  if (list.some((entry) => entry.listener === listener && entry.capture === capture)) return;
580
588
  list.push({ listener, capture, once: !!options?.once });
581
- this.#want(kind);
589
+ if (kind !== undefined) this.#want(kind);
582
590
  }
583
591
 
584
592
  removeEventListener(type, listener, options) {
@@ -588,7 +596,8 @@ export class Node {
588
596
  const index = list.findIndex((entry) => entry.listener === listener && entry.capture === capture);
589
597
  if (index < 0) return;
590
598
  list.splice(index, 1);
591
- this.#want(KIND_OF.get(type));
599
+ const kind = KIND_OF.get(type);
600
+ if (kind !== undefined) this.#want(kind);
592
601
  }
593
602
 
594
603
  /** Runs the capture or the bubble listeners of `event.type`. Used by the dispatcher. */
@@ -627,6 +636,7 @@ export class Text extends Node {
627
636
  if (value === this.#data && value !== "") return;
628
637
  this.#data = value;
629
638
  native.setText(this.nodeId, value);
639
+ if (this._svgText) svgChanged(this);
630
640
  }
631
641
 
632
642
  get textContent() {
@@ -698,16 +708,78 @@ function dropIcon(markup) {
698
708
  }
699
709
  }
700
710
 
711
+ // Addresses as image and icon resources, shared and freed as markup is. The tree keeps a load
712
+ // state per number, so these count from 1.
713
+ const ADDRESSES = new Map();
714
+ let nextAddress = 1;
715
+
716
+ function holdAddress(url, icon) {
717
+ const key = (icon ? "icon " : "image ") + url;
718
+ let entry = ADDRESSES.get(key);
719
+ if (!entry) {
720
+ entry = { id: nextAddress++, count: 0 };
721
+ ADDRESSES.set(key, entry);
722
+ native.load(entry.id, url, icon);
723
+ }
724
+ entry.count++;
725
+ return entry.id;
726
+ }
727
+
728
+ function dropAddress(url, icon) {
729
+ const key = (icon ? "icon " : "image ") + url;
730
+ const entry = ADDRESSES.get(key);
731
+ if (entry && --entry.count === 0) {
732
+ ADDRESSES.delete(key);
733
+ native.release(entry.id);
734
+ }
735
+ }
736
+
737
+ /**
738
+ * An image, as an `<img>`: `src` is its address, a `data:` URL (base64 or percent-encoded),
739
+ * a file or `http(s):`. An SVG file draws as an inline `<svg>` does. It hears `load` and
740
+ * `error` when the address loads or fails.
741
+ */
742
+ export class Image extends Node {
743
+ #src = "";
744
+
745
+ constructor(src = "") {
746
+ super("image");
747
+ this.src = src;
748
+ }
749
+
750
+ get src() {
751
+ return this.#src;
752
+ }
753
+
754
+ set src(url) {
755
+ url = url == null ? "" : String(url);
756
+ if (url === this.#src) return;
757
+ if (this.#src) dropAddress(this.#src, false);
758
+ this.#src = url;
759
+ native.source(this.nodeId, url ? holdAddress(url, false) : 0);
760
+ }
761
+
762
+ _forget() {
763
+ if (this.#src) dropAddress(this.#src, false);
764
+ this.#src = "";
765
+ }
766
+ }
767
+
701
768
  /**
702
769
  * An icon: SVG drawn at the node's CSS size, as an inline `<svg>` is. Its `currentColor` is
703
770
  * the node's `color`, so an icon that paints only with it (Lucide's, for example) takes the
704
- * text color, and any other keeps its own colors.
771
+ * text color, and any other keeps its own colors. Without a CSS size it takes the `width`
772
+ * and `height` of its `<svg>`, else a square of the font size.
773
+ *
774
+ * `svg` is its markup; `src` is the address of an SVG file instead (a `data:image/svg+xml`
775
+ * URL too). Setting one clears the other.
705
776
  */
706
777
  export class Icon extends Node {
707
778
  #svg = "";
779
+ #src = "";
708
780
 
709
- constructor(svg = "") {
710
- super("icon");
781
+ constructor(svg = "", kind = "icon") {
782
+ super(kind);
711
783
  this.svg = svg;
712
784
  }
713
785
 
@@ -719,15 +791,377 @@ export class Icon extends Node {
719
791
  set svg(markup) {
720
792
  markup = markup == null ? "" : String(markup);
721
793
  if (markup === this.#svg) return;
722
- if (this.#svg) dropIcon(this.#svg);
794
+ this.#release();
723
795
  this.#svg = markup;
724
796
  native.source(this.nodeId, markup ? holdIcon(markup) : 0);
725
797
  }
726
798
 
727
- _forget() {
799
+ get src() {
800
+ return this.#src;
801
+ }
802
+
803
+ set src(url) {
804
+ url = url == null ? "" : String(url);
805
+ if (url === this.#src) return;
806
+ this.#release();
807
+ this.#src = url;
808
+ native.source(this.nodeId, url ? holdAddress(url, true) : 0);
809
+ }
810
+
811
+ #release() {
728
812
  if (this.#svg) dropIcon(this.#svg);
813
+ if (this.#src) dropAddress(this.#src, true);
729
814
  this.#svg = "";
815
+ this.#src = "";
816
+ }
817
+
818
+ _forget() {
819
+ this.#release();
820
+ }
821
+ }
822
+
823
+ const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
824
+
825
+ // SVG attribute names that are camel case in SVG itself. Any other name with a capital letter
826
+ // is a React-style spelling of a hyphenated one (`strokeWidth` for `stroke-width`).
827
+ const SVG_CAMEL = new Set([
828
+ "viewBox", "preserveAspectRatio", "gradientUnits", "gradientTransform", "patternUnits",
829
+ "patternContentUnits", "patternTransform", "clipPathUnits", "maskUnits", "maskContentUnits",
830
+ "markerUnits", "markerWidth", "markerHeight", "refX", "refY", "spreadMethod", "stdDeviation",
831
+ "textLength", "lengthAdjust", "startOffset", "pathLength", "baseFrequency", "numOctaves",
832
+ "filterUnits", "primitiveUnits", "kernelMatrix", "kernelUnitLength", "tableValues",
833
+ "surfaceScale", "specularConstant", "specularExponent", "diffuseConstant", "limitingConeAngle",
834
+ "pointsAtX", "pointsAtY", "pointsAtZ", "edgeMode", "targetX", "targetY", "xChannelSelector",
835
+ "yChannelSelector", "attributeName", "attributeType", "calcMode", "keyTimes", "keySplines",
836
+ "keyPoints", "repeatCount", "repeatDur", "systemLanguage", "requiredFeatures", "zoomAndPan",
837
+ "glyphRef", "stitchTiles", "viewTarget", "contentScriptType", "contentStyleType",
838
+ ]);
839
+ const SVG_NAMES = new Map([
840
+ ["className", "class"], ["htmlFor", "for"], ["xlinkHref", "xlink:href"], ["xlinkTitle", "xlink:title"],
841
+ ["xmlSpace", "xml:space"], ["xmlLang", "xml:lang"], ["xmlnsXlink", "xmlns:xlink"],
842
+ ]);
843
+
844
+ function svgName(name) {
845
+ name = String(name);
846
+ const named = SVG_NAMES.get(name);
847
+ if (named) return named;
848
+ if (SVG_CAMEL.has(name) || !/[A-Z]/.test(name)) return name;
849
+ return name.replace(/[A-Z]/g, (letter) => "-" + letter.toLowerCase());
850
+ }
851
+
852
+ function escaped(text, attribute) {
853
+ text = String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;");
854
+ return attribute ? text.replace(/"/g, "&quot;") : text;
855
+ }
856
+
857
+ // The svg roots whose markup changed, drawn again once, before the host applies the mutations.
858
+ const changedSvgs = new Set();
859
+
860
+ function drawSvgs() {
861
+ for (const svg of changedSvgs) svg._draw();
862
+ changedSvgs.clear();
863
+ }
864
+
865
+ /** The element of `node` in an `<svg>` subtree: its text, or its element. */
866
+ function svgOwner(node) {
867
+ for (let at = node; at; at = at.parentNode) if (at instanceof Svg) return at;
868
+ return null;
869
+ }
870
+
871
+ function svgChanged(node) {
872
+ const svg = svgOwner(node);
873
+ if (!svg || changedSvgs.has(svg)) return;
874
+ if (changedSvgs.size === 0) queueMicrotask(drawSvgs);
875
+ changedSvgs.add(svg);
876
+ }
877
+
878
+ function svgStyle(value) {
879
+ if (typeof value !== "object" || value === null) return String(value);
880
+ let css = "";
881
+ for (const name of Object.keys(value)) {
882
+ const part = value[name];
883
+ if (part === null || part === undefined || part === "") continue;
884
+ css += cssName(name) + ":" + (typeof part === "number" && !UNITLESS.has(name) ? part + "px" : part) + ";";
885
+ }
886
+ return css;
887
+ }
888
+
889
+ // The children of an element of an `<svg>`: the markup they write, and how they move.
890
+ const svgChildren = {
891
+ insertBefore(child, before = null) {
892
+ if (before && before.parentNode !== this) throw new Error("the node to insert before is not a child of this node");
893
+ if (before === child) return child;
894
+ for (let at = this; at; at = at.parentNode) if (at === child) throw new Error("a node cannot be inserted into itself or its own subtree");
895
+ const old = child.parentNode;
896
+ if (old) {
897
+ svgChanged(old);
898
+ old.childNodes.splice(old.childNodes.indexOf(child), 1);
899
+ }
900
+ child.parentNode = this;
901
+ if (before) this.childNodes.splice(this.childNodes.indexOf(before), 0, child);
902
+ else this.childNodes.push(child);
903
+ if (child instanceof Text) child._svgText = true;
904
+ svgChanged(this);
905
+ return child;
906
+ },
907
+ appendChild(child) {
908
+ return this.insertBefore(child, null);
909
+ },
910
+ append(...children) {
911
+ for (const child of children) this.insertBefore(typeof child === "string" ? new SvgText(child) : child, null);
912
+ },
913
+ removeChild(child) {
914
+ if (child.parentNode !== this) throw new Error("the node to remove is not a child of this node");
915
+ svgChanged(this);
916
+ this.childNodes.splice(this.childNodes.indexOf(child), 1);
917
+ child.parentNode = null;
918
+ return child;
919
+ },
920
+ get textContent() {
921
+ let text = "";
922
+ for (const child of this.childNodes) text += child.textContent ?? child.data ?? "";
923
+ return text;
924
+ },
925
+ set textContent(value) {
926
+ for (const child of this.childNodes.slice()) this.removeChild(child);
927
+ if (value !== null && value !== undefined && value !== "") this.insertBefore(new SvgText(String(value)), null);
928
+ },
929
+ _markupOf(children) {
930
+ let markup = "";
931
+ for (const child of children) {
932
+ if (child instanceof SvgElement) markup += child._markup();
933
+ else markup += escaped(child.data ?? "", false);
934
+ }
935
+ return markup;
936
+ },
937
+ };
938
+
939
+ /** Text in an `<svg>`: its `<text>` and `<title>` contents. */
940
+ export class SvgText {
941
+ #data;
942
+
943
+ constructor(data = "") {
944
+ this.#data = String(data);
945
+ this.parentNode = null;
946
+ this.childNodes = NO_CHILDREN;
947
+ }
948
+
949
+ get data() {
950
+ return this.#data;
951
+ }
952
+
953
+ set data(value) {
954
+ value = String(value);
955
+ if (value === this.#data) return;
956
+ this.#data = value;
957
+ svgChanged(this);
958
+ }
959
+
960
+ get textContent() {
961
+ return this.#data;
962
+ }
963
+
964
+ set textContent(value) {
965
+ this.data = value;
966
+ }
967
+
968
+ get nextSibling() {
969
+ const siblings = this.parentNode?.childNodes;
970
+ return siblings ? siblings[siblings.indexOf(this) + 1] ?? null : null;
971
+ }
972
+
973
+ get previousSibling() {
974
+ const siblings = this.parentNode?.childNodes;
975
+ return siblings ? siblings[siblings.indexOf(this) - 1] ?? null : null;
976
+ }
977
+
978
+ contains(other) {
979
+ for (let node = other; node; node = node.parentNode) if (node === this) return true;
980
+ return false;
981
+ }
982
+
983
+ remove() {
984
+ this.parentNode?.removeChild(this);
985
+ }
986
+
987
+ destroy() {
988
+ this.remove();
989
+ }
990
+ }
991
+
992
+ /**
993
+ * An element inside an `<svg>`: `path`, `circle`, `g`, `linearGradient` and the rest. It is
994
+ * no node of the tree: it is markup its `Svg` root draws. Its attributes take SVG's names or
995
+ * React's spellings (`strokeWidth`, `xlinkHref`).
996
+ */
997
+ export class SvgElement {
998
+ #attributes = new Map();
999
+
1000
+ constructor(tag) {
1001
+ this.localName = String(tag);
1002
+ this.tagName = this.localName;
1003
+ this.namespaceURI = SVG_NAMESPACE;
1004
+ this.parentNode = null;
1005
+ this.childNodes = [];
1006
+ }
1007
+
1008
+ getAttribute(name) {
1009
+ return this.#attributes.get(svgName(name)) ?? null;
1010
+ }
1011
+
1012
+ hasAttribute(name) {
1013
+ return this.#attributes.has(svgName(name));
1014
+ }
1015
+
1016
+ setAttribute(name, value) {
1017
+ name = svgName(name);
1018
+ if (value === null || value === undefined || value === false) {
1019
+ this.removeAttribute(name);
1020
+ return;
1021
+ }
1022
+ const text = name === "style" ? svgStyle(value) : String(value);
1023
+ if (this.#attributes.get(name) === text) return;
1024
+ this.#attributes.set(name, text);
1025
+ svgChanged(this);
1026
+ }
1027
+
1028
+ removeAttribute(name) {
1029
+ if (this.#attributes.delete(svgName(name))) svgChanged(this);
1030
+ }
1031
+
1032
+ get firstChild() {
1033
+ return this.childNodes[0] ?? null;
730
1034
  }
1035
+
1036
+ get lastChild() {
1037
+ return this.childNodes[this.childNodes.length - 1] ?? null;
1038
+ }
1039
+
1040
+ get nextSibling() {
1041
+ const siblings = this.parentNode?.childNodes;
1042
+ return siblings ? siblings[siblings.indexOf(this) + 1] ?? null : null;
1043
+ }
1044
+
1045
+ get previousSibling() {
1046
+ const siblings = this.parentNode?.childNodes;
1047
+ return siblings ? siblings[siblings.indexOf(this) - 1] ?? null : null;
1048
+ }
1049
+
1050
+ contains(other) {
1051
+ for (let node = other; node; node = node.parentNode) if (node === this) return true;
1052
+ return false;
1053
+ }
1054
+
1055
+ remove() {
1056
+ this.parentNode?.removeChild(this);
1057
+ }
1058
+
1059
+ /** Takes the element out of its `<svg>`. It is plain markup, so nothing else is freed. */
1060
+ destroy() {
1061
+ this.remove();
1062
+ }
1063
+
1064
+ addEventListener(type) {
1065
+ warnOnce("an element inside an <svg> hears no events: listen on the <svg> ('" + type + "')");
1066
+ }
1067
+
1068
+ removeEventListener() {}
1069
+
1070
+ _markup() {
1071
+ let markup = "<" + this.localName;
1072
+ for (const [name, value] of this.#attributes) markup += " " + name + '="' + escaped(value, true) + '"';
1073
+ if (this.childNodes.length === 0) return markup + "/>";
1074
+ return markup + ">" + svgChildren._markupOf(this.childNodes) + "</" + this.localName + ">";
1075
+ }
1076
+ }
1077
+
1078
+ for (const name of ["insertBefore", "appendChild", "append", "removeChild"]) SvgElement.prototype[name] = svgChildren[name];
1079
+ Object.defineProperty(SvgElement.prototype, "textContent", Object.getOwnPropertyDescriptor(svgChildren, "textContent"));
1080
+
1081
+ // Attributes of an `<svg>` root the tree has: they go to its node. Every other one is markup.
1082
+ function treeAttribute(name) {
1083
+ return name === "class" || name === "className" || name === "id" || name === "role" || name === "tabIndex"
1084
+ || name === "tabindex" || name === "testId" || name === "label" || name === "cursor" || name === "transition"
1085
+ || name === "inert" || name === "disabled" || name === "element" || name === "lang" || name === "dir"
1086
+ || name.startsWith("data-") || ariaName(name) !== null;
1087
+ }
1088
+
1089
+ /**
1090
+ * An inline `<svg>`, as the web has it: its children are `SvgElement`s and `SvgText`s, and
1091
+ * the tree draws the markup they make as an icon. Its look, class, events and accessibility
1092
+ * are the node's; `viewBox`, `fill`, `width` and the other SVG attributes are markup.
1093
+ * Changes are drawn once, before the host applies the batch.
1094
+ */
1095
+ export class Svg extends Icon {
1096
+ #attributes = new Map();
1097
+
1098
+ constructor() {
1099
+ super("", "icon");
1100
+ this.localName = "svg";
1101
+ this.tagName = "svg";
1102
+ this.namespaceURI = SVG_NAMESPACE;
1103
+ svgChanged(this);
1104
+ }
1105
+
1106
+ getAttribute(name) {
1107
+ return treeAttribute(String(name)) ? super.getAttribute(name) : this.#attributes.get(svgName(name)) ?? null;
1108
+ }
1109
+
1110
+ setAttribute(name, value) {
1111
+ name = String(name);
1112
+ if (treeAttribute(name)) {
1113
+ super.setAttribute(name === "tabindex" ? "tabIndex" : name, value);
1114
+ return;
1115
+ }
1116
+ name = svgName(name);
1117
+ if (name === "xmlns") return;
1118
+ if (value === null || value === undefined || value === false || value === "") {
1119
+ this.removeAttribute(name);
1120
+ return;
1121
+ }
1122
+ const text = name === "style" ? svgStyle(value) : String(value);
1123
+ if (this.#attributes.get(name) === text) return;
1124
+ this.#attributes.set(name, text);
1125
+ svgChanged(this);
1126
+ }
1127
+
1128
+ removeAttribute(name) {
1129
+ name = String(name);
1130
+ if (treeAttribute(name)) super.removeAttribute(name);
1131
+ else if (this.#attributes.delete(svgName(name))) svgChanged(this);
1132
+ }
1133
+
1134
+ /** The markup the tree draws, as `outerHTML` gives it. */
1135
+ get outerHTML() {
1136
+ let markup = '<svg xmlns="' + SVG_NAMESPACE + '"';
1137
+ const children = svgChildren._markupOf(this.childNodes);
1138
+ let xlink = this.#attributes.has("xmlns:xlink");
1139
+ for (const [name, value] of this.#attributes) {
1140
+ markup += " " + name + '="' + escaped(value, true) + '"';
1141
+ }
1142
+ if (!xlink && children.includes("xlink:")) markup += ' xmlns:xlink="http://www.w3.org/1999/xlink"';
1143
+ return markup + ">" + children + "</svg>";
1144
+ }
1145
+
1146
+ _draw() {
1147
+ if (nodes.has(this.nodeId)) this.svg = this.outerHTML;
1148
+ }
1149
+ }
1150
+
1151
+ for (const name of ["insertBefore", "appendChild", "append", "removeChild"]) Svg.prototype[name] = svgChildren[name];
1152
+ Object.defineProperty(Svg.prototype, "textContent", Object.getOwnPropertyDescriptor(svgChildren, "textContent"));
1153
+
1154
+ /**
1155
+ * An element of tag `tag` in the SVG namespace: an `Svg` root for `svg`, an `SvgElement`
1156
+ * inside one for anything else. `document.createElementNS` with the SVG namespace, as it were.
1157
+ */
1158
+ export function createSvgElement(tag) {
1159
+ return tag === "svg" ? new Svg() : new SvgElement(tag);
1160
+ }
1161
+
1162
+ /** Draws the `<svg>` roots that changed now, instead of before the host applies the batch. */
1163
+ export function flushSvg() {
1164
+ drawSvgs();
731
1165
  }
732
1166
 
733
1167
  // Offsets cross the bridge as UTF-8 bytes; a rich input speaks JavaScript string indices.
@@ -928,10 +1362,13 @@ function forget(node) {
928
1362
 
929
1363
  export function createNode(kind) {
930
1364
  if (kind === "richinput") return new RichInput();
1365
+ if (kind === "svg") return new Svg();
1366
+ if (kind === "img") kind = "image";
931
1367
  if (!(kind in KINDS)) throw new TypeError("the tree has no node kind '" + kind + "'");
932
1368
  if (kind === "text") return new Text();
933
1369
  if (kind === "input") return new Input();
934
1370
  if (kind === "icon") return new Icon();
1371
+ if (kind === "image") return new Image();
935
1372
  return new Node(kind);
936
1373
  }
937
1374
 
@@ -954,6 +1391,13 @@ export function createIcon(svg, style) {
954
1391
  return icon;
955
1392
  }
956
1393
 
1394
+ /** An image showing `src` (see `Image`), with `style` as its base look. */
1395
+ export function createImage(src, style) {
1396
+ const image = new Image(src);
1397
+ if (style) image.style.set(style);
1398
+ return image;
1399
+ }
1400
+
957
1401
  export function createInput(style) {
958
1402
  const input = new Input();
959
1403
  if (style) input.style.set(style);
@@ -1235,3 +1679,273 @@ native.takeError = function () {
1235
1679
  pendingError = null;
1236
1680
  throw error;
1237
1681
  };
1682
+
1683
+ // The desktop around the window: files dragged in from other apps, notifications, the tray
1684
+ // and global shortcuts. The host serves `__ui.shell` calls after the code that made them has
1685
+ // run and answers through `__ui.shellAnswer`; desktop events arrive through `__ui.shellEvent`.
1686
+
1687
+ const shellCalls = new Map();
1688
+ let nextShellCall = 0;
1689
+
1690
+ function shellCall(op, fields) {
1691
+ const call = ++nextShellCall;
1692
+ return new Promise((resolve) => {
1693
+ shellCalls.set(call, resolve);
1694
+ native.shell(call, op, fields.join("\x1f"));
1695
+ });
1696
+ }
1697
+
1698
+ native.shellAnswer = function (call, value) {
1699
+ const resolve = shellCalls.get(call);
1700
+ if (!resolve) return;
1701
+ shellCalls.delete(call);
1702
+ resolve(value);
1703
+ };
1704
+
1705
+ /** A file dragged in from the desktop, as the web's `File`, with its `path` on disk. */
1706
+ export class DroppedFile {
1707
+ constructor(path) {
1708
+ this.path = path;
1709
+ this.name = path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1);
1710
+ this.type = "";
1711
+ }
1712
+ }
1713
+
1714
+ /**
1715
+ * What a file drag carries, as the web's `DataTransfer`: `types` is `["Files"]` while files
1716
+ * are over the window, and `files` lists them in `drop`, as on the web.
1717
+ */
1718
+ export class DataTransfer {
1719
+ constructor(paths) {
1720
+ this.files = paths.map((path) => new DroppedFile(path));
1721
+ this.items = this.files.map((file) => ({ kind: "file", type: "", getAsFile: () => file }));
1722
+ this.types = ["Files"];
1723
+ this.dropEffect = "copy";
1724
+ this.effectAllowed = "copy";
1725
+ }
1726
+
1727
+ getData() {
1728
+ return "";
1729
+ }
1730
+ }
1731
+
1732
+ let dragTarget = null;
1733
+
1734
+ function dragEvent(type, target, x, y, paths) {
1735
+ const event = new Event(type, target);
1736
+ event.clientX = event.x = x;
1737
+ event.clientY = event.y = y;
1738
+ event.dataTransfer = new DataTransfer(paths);
1739
+ dispatchEvent(event);
1740
+ }
1741
+
1742
+ // As the web: `dragenter` on the node now under the files, `dragleave` on the one before,
1743
+ // then `dragover` on the current one.
1744
+ function dragTo(target, x, y) {
1745
+ if (target !== dragTarget) {
1746
+ const before = dragTarget;
1747
+ dragTarget = target;
1748
+ if (target) dragEvent("dragenter", target, x, y, []);
1749
+ if (before) dragEvent("dragleave", before, x, y, []);
1750
+ }
1751
+ if (target) dragEvent("dragover", target, x, y, []);
1752
+ }
1753
+
1754
+ let trayMenu = new Map();
1755
+ let trayClick = null;
1756
+ const shortcuts = new Map();
1757
+ const shortcutIds = new Map();
1758
+ let nextShortcut = 0;
1759
+ const notifications = new Map();
1760
+
1761
+ native.shellEvent = function (kind, a, x, y, text) {
1762
+ if (kind <= 3) {
1763
+ const target = nodes.get(a) ?? rootNode;
1764
+ if (kind === 2) {
1765
+ const before = dragTarget;
1766
+ dragTarget = null;
1767
+ if (before) dragEvent("dragleave", before, x, y, []);
1768
+ } else if (kind === 3) {
1769
+ if (target !== dragTarget) dragTo(target, x, y);
1770
+ dragTarget = null;
1771
+ if (target) dragEvent("drop", target, x, y, text ? text.split("\n") : []);
1772
+ } else {
1773
+ dragTo(target, x, y);
1774
+ }
1775
+ } else if (kind === 4) {
1776
+ shortcuts.get(a)?.();
1777
+ } else if (kind === 5) {
1778
+ trayClick?.({ button: a });
1779
+ } else if (kind === 6) {
1780
+ trayMenu.get(a)?.();
1781
+ } else if (kind === 7) {
1782
+ const notification = notifications.get(a);
1783
+ if (!notification) return;
1784
+ notifications.delete(a);
1785
+ notification._fire("click");
1786
+ }
1787
+ };
1788
+
1789
+ // Notifications nobody clicked are forgotten after this many newer ones.
1790
+ const NOTIFICATIONS_KEPT = 64;
1791
+
1792
+ /**
1793
+ * A desktop notification, as the web's: `new Notification(title, { body })`, with `onclick`
1794
+ * or a `click` listener. Permission is always granted.
1795
+ */
1796
+ export class Notification {
1797
+ static permission = "granted";
1798
+
1799
+ static requestPermission(callback) {
1800
+ callback?.("granted");
1801
+ return Promise.resolve("granted");
1802
+ }
1803
+
1804
+ #listeners = new Map();
1805
+
1806
+ constructor(title, options = {}) {
1807
+ this.title = String(title);
1808
+ this.body = String(options.body ?? "");
1809
+ this.tag = String(options.tag ?? "");
1810
+ this.data = options.data ?? null;
1811
+ this.onclick = this.onshow = this.onerror = this.onclose = null;
1812
+ shellCall(0, [this.title, this.body]).then((id) => {
1813
+ if (!id) return this._fire("error");
1814
+ notifications.set(id, this);
1815
+ if (notifications.size > NOTIFICATIONS_KEPT) notifications.delete(notifications.keys().next().value);
1816
+ this._fire("show");
1817
+ });
1818
+ }
1819
+
1820
+ /** The system keeps the notification until the user dismisses it. */
1821
+ close() {}
1822
+
1823
+ addEventListener(type, listener) {
1824
+ let list = this.#listeners.get(type);
1825
+ if (!list) this.#listeners.set(type, (list = []));
1826
+ if (!list.includes(listener)) list.push(listener);
1827
+ }
1828
+
1829
+ removeEventListener(type, listener) {
1830
+ const list = this.#listeners.get(type);
1831
+ const index = list ? list.indexOf(listener) : -1;
1832
+ if (index >= 0) list.splice(index, 1);
1833
+ }
1834
+
1835
+ _fire(type) {
1836
+ const event = { type, target: this, currentTarget: this };
1837
+ const handler = this["on" + type];
1838
+ try {
1839
+ if (typeof handler === "function") handler.call(this, event);
1840
+ for (const listener of (this.#listeners.get(type) ?? []).slice()) listener.call(this, event);
1841
+ } catch (error) {
1842
+ reportError(error);
1843
+ }
1844
+ }
1845
+ }
1846
+
1847
+ globalThis.Notification ??= Notification;
1848
+
1849
+ function hex(bytes) {
1850
+ let text = "";
1851
+ for (let i = 0; i < bytes.length; i++) text += (bytes[i] < 16 ? "0" : "") + bytes[i].toString(16);
1852
+ return text;
1853
+ }
1854
+
1855
+ function packMenu(items, lines) {
1856
+ for (const item of items) {
1857
+ if (item.type === "separator") lines.push("S");
1858
+ else if (item.submenu) {
1859
+ lines.push("B" + String(item.label ?? "").replace(/\n/g, " "));
1860
+ packMenu(item.submenu, lines);
1861
+ lines.push("E");
1862
+ } else {
1863
+ const action = trayMenu.size + 1;
1864
+ trayMenu.set(action, typeof item.click === "function" ? item.click : () => {});
1865
+ const label = String(item.label ?? "").replace(/\n/g, " ");
1866
+ lines.push("A" + action + "," + (item.enabled === false ? 0 : 1) + "," + (item.checked ? 1 : 0) + "," + label);
1867
+ }
1868
+ }
1869
+ }
1870
+
1871
+ /**
1872
+ * Shows an icon in the system tray (the macOS menu bar, the Windows notification area, a
1873
+ * StatusNotifierItem on Linux). `icon` is RGBA pixels, as an `ImageData`: `{ width, height,
1874
+ * data }`; macOS draws a `template` icon from its alpha in the menu bar's colours. `menu`
1875
+ * items are `{ label, click, enabled, checked }`, `{ type: "separator" }` or `{ label,
1876
+ * submenu }`. With no menu, `onClick({ button })` runs when the icon is clicked. Calling it
1877
+ * again replaces the tray. Resolves to whether the system shows it.
1878
+ */
1879
+ export function setTray({ icon, tooltip = "", template = false, menu = [], onClick = null }) {
1880
+ if (!icon || !(icon.width > 0) || !(icon.height > 0) || icon.data?.length !== icon.width * icon.height * 4) {
1881
+ throw new TypeError("setTray needs an icon of RGBA pixels: { width, height, data }");
1882
+ }
1883
+ trayMenu = new Map();
1884
+ trayClick = typeof onClick === "function" ? onClick : null;
1885
+ const lines = [];
1886
+ packMenu(menu, lines);
1887
+ const fields = [String(tooltip), icon.width, icon.height, template ? 1 : 0, hex(icon.data), lines.join("\n")];
1888
+ return shellCall(1, fields).then((shown) => shown === 1);
1889
+ }
1890
+
1891
+ /** Takes the tray icon away. */
1892
+ export function removeTray() {
1893
+ trayMenu = new Map();
1894
+ trayClick = null;
1895
+ shellCall(2, []);
1896
+ }
1897
+
1898
+ 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 };
1899
+ const KEY_NAMES = {
1900
+ up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", esc: "Escape", return: "Enter",
1901
+ space: " ", plus: "Equal", "=": "Equal", "-": "Minus", ",": "Comma", ".": "Period", "/": "Slash",
1902
+ ";": "Semicolon", "'": "Quote", "[": "BracketLeft", "]": "BracketRight", "\\": "Backslash", "`": "Backquote",
1903
+ };
1904
+
1905
+ // "Mod+Shift+K" as the UI Events `code` of the key and the modifier bits; `Mod` (also
1906
+ // `CmdOrCtrl`) is Command on macOS and Control elsewhere.
1907
+ function parseShortcut(accelerator) {
1908
+ const parts = String(accelerator).split("+").map((part) => part.trim()).filter(Boolean);
1909
+ let bits = 0;
1910
+ let code = "";
1911
+ for (const part of parts) {
1912
+ const modifier = MODIFIERS[part.toLowerCase()];
1913
+ if (modifier !== undefined) {
1914
+ bits |= modifier;
1915
+ continue;
1916
+ }
1917
+ const named = KEY_NAMES[part.toLowerCase()] ?? part;
1918
+ if (named === " ") code = "Space";
1919
+ else if (/^[a-z]$/i.test(named)) code = "Key" + named.toUpperCase();
1920
+ else if (/^[0-9]$/.test(named)) code = "Digit" + named;
1921
+ else code = named[0].toUpperCase() + named.slice(1);
1922
+ }
1923
+ if (!code) throw new TypeError("'" + accelerator + "' names no key");
1924
+ return { code, bits };
1925
+ }
1926
+
1927
+ /**
1928
+ * Runs `callback` when the keys of `accelerator` are pressed, whichever app has focus:
1929
+ * `"Mod+Shift+K"`, where `Mod` is Command on macOS and Control elsewhere, and the key is a
1930
+ * letter, a digit, a UI Events `code` (`"F5"`, `"ArrowUp"`, `"Slash"`) or a name such as
1931
+ * `Space` or `Esc`. Registering it again replaces the callback. Resolves to whether the
1932
+ * system took it: another app may hold it, and Wayland has no global shortcuts.
1933
+ */
1934
+ export function registerShortcut(accelerator, callback) {
1935
+ const { code, bits } = parseShortcut(accelerator);
1936
+ const key = code + "+" + bits;
1937
+ let id = shortcutIds.get(key);
1938
+ if (id === undefined) shortcutIds.set(key, (id = ++nextShortcut));
1939
+ shortcuts.set(id, callback);
1940
+ return shellCall(3, [id, code, bits]).then((held) => held === 1);
1941
+ }
1942
+
1943
+ /** Stops the shortcut of `accelerator`. */
1944
+ export function unregisterShortcut(accelerator) {
1945
+ const { code, bits } = parseShortcut(accelerator);
1946
+ const id = shortcutIds.get(code + "+" + bits);
1947
+ if (id === undefined) return;
1948
+ shortcutIds.delete(code + "+" + bits);
1949
+ shortcuts.delete(id);
1950
+ shellCall(4, [id]);
1951
+ }