@silkui/core 0.1.10 → 0.1.11

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
@@ -171,6 +171,42 @@ registerShortcut("Mod+Shift+B", build); // Mod is Command on macOS, Control else
171
171
  whichever app has focus; another app may hold it, and Wayland has none. `removeTray()` and
172
172
  `unregisterShortcut(accelerator)` undo them.
173
173
 
174
+ The rest of a desktop app's shell is direct calls too, shaped like Electron's so a desktop app
175
+ moves over without an IPC layer. Everything runs in the app's own process.
176
+
177
+ ```ts
178
+ import { setApplicationMenu, showContextMenu, showOpenDialog, appWindow } from "@silkui/core";
179
+
180
+ setApplicationMenu([
181
+ { role: "appMenu" },
182
+ { label: "File", submenu: [{ label: "Open…", accelerator: "Mod+O", click: open }] },
183
+ { role: "editMenu" },
184
+ { role: "viewMenu" },
185
+ { role: "windowMenu" },
186
+ ]);
187
+ node.addEventListener("contextmenu", (event) =>
188
+ showContextMenu([{ label: "Rename", click: rename }, { type: "separator" }, { label: "Delete", click: remove }], {
189
+ x: event.clientX,
190
+ y: event.clientY,
191
+ }),
192
+ );
193
+ const { canceled, filePaths } = await showOpenDialog({ properties: ["openDirectory"] });
194
+ appWindow.addEventListener("fullscreenchange", ({ fullScreen }) => setInset(fullScreen ? 0 : 80));
195
+ ```
196
+
197
+ | Call | Does |
198
+ | --- | --- |
199
+ | `setApplicationMenu(template)` | The menu bar. `role`s are the system's items (`quit`, `copy`, `togglefullscreen`, `front`), `zoomIn`/`zoomOut`/`resetZoom` zoom the page, `appMenu`, `editMenu`, `viewMenu`, `windowMenu` are whole menus |
200
+ | `showContextMenu(template, { x, y })` | A native context menu; resolves to `true` when it closes, or at once to `false` where the system has none (Linux, the browser) |
201
+ | `showOpenDialog({ properties, filters, defaultPath })`, `showSaveDialog(...)` | File and folder pickers; resolve to `{ canceled, filePaths }` and `{ canceled, filePath }` |
202
+ | `openExternal(url)`, `showItemInFolder(path)` | The default browser (or mail app), and Finder or Explorer with the item selected |
203
+ | `startFileDrag(paths)` | From a `pointerdown` or `pointermove`, drags the files out to other apps (macOS, Windows) |
204
+ | `setBadge(text)`, `setProgress(fraction)` | The dock or taskbar icon's badge and progress |
205
+ | `appWindow` | `setFullScreen`, `isFullScreen`, `minimize`, `focus`, `show`, `hide`, `setTitle`, `setZoomFactor`, `getZoomFactor`, and `fullscreenchange` and `zoomchange` events |
206
+
207
+ A hidden title bar with the window controls inset is the app's configuration, not a call:
208
+ `.titleBar(TitleBar.transparent(height).buttons(left, top))` in its `tasks.silk`.
209
+
174
210
  `memoryUsage()` is the app's memory as the system shows it to users, to put next to an
175
211
  Electron app's in Activity Monitor or Task Manager. It is synchronous and allocates almost
176
212
  nothing, so it can run every second.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@silkui/core",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
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
@@ -851,6 +851,96 @@ export function removeTray(): void;
851
851
  export function registerShortcut(accelerator: string, callback: () => void): Promise<boolean>;
852
852
  export function unregisterShortcut(accelerator: string): void;
853
853
 
854
+ /** An item of `setApplicationMenu` or `showContextMenu`, as Electron's menu templates. */
855
+ export interface MenuItem {
856
+ label?: string;
857
+ click?: (item: MenuItem) => void;
858
+ /** `"Mod+Shift+K"`, `"CmdOrCtrl+O"`, `"F5"`: `Mod` is Command on macOS, Control elsewhere. */
859
+ accelerator?: string;
860
+ enabled?: boolean;
861
+ checked?: boolean;
862
+ visible?: boolean;
863
+ type?: "normal" | "separator" | "checkbox" | "radio" | "submenu";
864
+ /**
865
+ * The system's own items (`about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`,
866
+ * `close`, `minimize`, `zoom`, `togglefullscreen`, `front`, `undo`, `redo`, `cut`, `copy`,
867
+ * `paste`, `selectAll`), the page zoom (`zoomIn`, `zoomOut`, `resetZoom`), or a whole menu
868
+ * (`appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `windowMenu`).
869
+ */
870
+ role?: string;
871
+ submenu?: MenuItem[];
872
+ }
873
+
874
+ /** Replaces the app's menu bar. On macOS the first menu is the app menu. */
875
+ export function setApplicationMenu(template: MenuItem[]): Promise<void>;
876
+
877
+ /**
878
+ * Opens a native context menu at `x`, `y` (CSS pixels in the window). Resolves to `true` when
879
+ * it closes, or at once to `false` where the system has none and the app draws its own.
880
+ */
881
+ export function showContextMenu(template: MenuItem[], position?: { x?: number; y?: number }): Promise<boolean>;
882
+
883
+ export interface FileFilter {
884
+ name?: string;
885
+ /** Without dots; `"*"` for every file. */
886
+ extensions: string[];
887
+ }
888
+
889
+ export interface OpenDialogOptions {
890
+ title?: string;
891
+ defaultPath?: string;
892
+ filters?: FileFilter[];
893
+ properties?: Array<"openFile" | "openDirectory" | "multiSelections" | "createDirectory" | "showHiddenFiles">;
894
+ }
895
+
896
+ export interface SaveDialogOptions {
897
+ title?: string;
898
+ /** A folder, a file name, or a path to a file. */
899
+ defaultPath?: string;
900
+ filters?: FileFilter[];
901
+ }
902
+
903
+ export function showOpenDialog(options?: OpenDialogOptions): Promise<{ canceled: boolean; filePaths: string[] }>;
904
+ export function showSaveDialog(options?: SaveDialogOptions): Promise<{ canceled: boolean; filePath: string }>;
905
+
906
+ /** Puts `text` on the dock or taskbar icon; `""` takes it off. Resolves to whether it shows. */
907
+ export function setBadge(text: string): Promise<boolean>;
908
+ /** Progress from 0 to 1 on the dock or taskbar icon; negative takes it off. */
909
+ export function setProgress(fraction: number): Promise<boolean>;
910
+ /** Opens `url` with the system's handler (the default browser for a web page). */
911
+ export function openExternal(url: string): Promise<boolean>;
912
+ /** Shows the file or folder at `path` selected in Finder, Explorer or the file manager. */
913
+ export function showItemInFolder(path: string): Promise<boolean>;
914
+ /**
915
+ * Drags the files at `paths` out to other apps; call it from `pointerdown` or `pointermove`
916
+ * while the button is down. Resolves to whether it started (macOS and Windows).
917
+ */
918
+ export function startFileDrag(paths: string | string[]): Promise<boolean>;
919
+
920
+ /** The window the app runs in. */
921
+ export interface AppWindow {
922
+ readonly fullScreen: boolean;
923
+ /** The page zoom, 1 at 100%. */
924
+ readonly zoomFactor: number;
925
+ setFullScreen(on: boolean): void;
926
+ toggleFullScreen(): void;
927
+ isFullScreen(): boolean;
928
+ minimize(): void;
929
+ /** Shows the window and brings it to the front with keyboard focus. */
930
+ focus(): void;
931
+ show(): void;
932
+ hide(): void;
933
+ setTitle(title: string): void;
934
+ /** From 0.25 to 5; resolves to the zoom now. */
935
+ setZoomFactor(zoom: number): Promise<number>;
936
+ getZoomFactor(): number;
937
+ addEventListener(type: "fullscreenchange", listener: (event: { type: "fullscreenchange"; fullScreen: boolean }) => void): void;
938
+ addEventListener(type: "zoomchange", listener: (event: { type: "zoomchange"; zoomFactor: number }) => void): void;
939
+ removeEventListener(type: "fullscreenchange" | "zoomchange", listener: (event: never) => void): void;
940
+ }
941
+
942
+ export const appWindow: AppWindow;
943
+
854
944
  /** The app's memory: `footprint` in bytes over `processes` processes. */
855
945
  export interface MemoryUsage {
856
946
  footprint: number;
package/src/index.js CHANGED
@@ -37,6 +37,8 @@ function eachLiveRange(update) {
37
37
  }
38
38
 
39
39
  const CLICK = KIND_OF.get("click");
40
+ const FOCUS = KIND_OF.get("focus");
41
+ const BLUR = KIND_OF.get("blur");
40
42
  const SELECTION_CHANGE = KIND_OF.get("selectionchange");
41
43
  const TOUCH_START = KIND_OF.get("touchstart");
42
44
  const COPY = KIND_OF.get("copy");
@@ -78,6 +80,10 @@ const UNITLESS = new Set([
78
80
  ]);
79
81
 
80
82
  const nodes = new Map();
83
+ // HTML boolean attributes that are also the tree's own.
84
+ const BOOLEAN_TREE_ATTRIBUTES = new Set(["disabled", "checked", "selected", "inert", "readonly", "multiline"]);
85
+ // The tag stylesheets match a tree node by, by its kind (see ui-tree's `SelectorTree`).
86
+ const LOCAL_NAMES = { box: "div", input: "input", image: "img", canvas: "canvas", svg: "svg", text: "#text" };
81
87
  const NO_CHILDREN = Object.freeze([]);
82
88
  let nextId = 0;
83
89
 
@@ -94,6 +100,68 @@ function cssName(name) {
94
100
  return css;
95
101
  }
96
102
 
103
+ // A CSS name as the camel case name looks take: `background-color` is `backgroundColor`,
104
+ // `-webkit-line-clamp` is `WebkitLineClamp`; custom properties stay as they are.
105
+ function camelName(name) {
106
+ if (name.startsWith("--") || !name.includes("-")) return name;
107
+ return name.replace(/^-ms-/, "ms-").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
108
+ }
109
+
110
+ // `color: red; --gap: 4px` as camel case properties. Semicolons inside parentheses or
111
+ // quotes (`url("a;b")`) stay in their value.
112
+ function parseDeclarations(text) {
113
+ const properties = {};
114
+ let depth = 0;
115
+ let quote = "";
116
+ let start = 0;
117
+ const take = (end) => {
118
+ const part = text.slice(start, end);
119
+ const colon = part.indexOf(":");
120
+ if (colon > 0) {
121
+ const name = part.slice(0, colon).trim();
122
+ const value = part.slice(colon + 1).trim();
123
+ if (name && value) properties[camelName(name.startsWith("--") ? name : name.toLowerCase())] = value;
124
+ }
125
+ start = end + 1;
126
+ };
127
+ for (let i = 0; i < text.length; i++) {
128
+ const c = text[i];
129
+ if (quote) {
130
+ if (c === "\\") i++;
131
+ else if (c === quote) quote = "";
132
+ } else if (c === '"' || c === "'") quote = c;
133
+ else if (c === "(") depth++;
134
+ else if (c === ")") depth--;
135
+ else if (c === ";" && depth <= 0) take(i);
136
+ }
137
+ take(text.length);
138
+ return properties;
139
+ }
140
+
141
+ // `element.style` of an HTML element: the base look, whose CSS properties also read and write
142
+ // as fields (`style.height = "10px"`), as a CSSStyleDeclaration's do.
143
+ const styleProxies = new WeakMap();
144
+ function styleProxy(look) {
145
+ let proxy = styleProxies.get(look);
146
+ if (proxy) return proxy;
147
+ proxy = new Proxy(look, {
148
+ get(target, key) {
149
+ if (typeof key !== "string" || key in target) {
150
+ const value = Reflect.get(target, key, target);
151
+ return typeof value === "function" ? value.bind(target) : value;
152
+ }
153
+ return target.get(key) ?? "";
154
+ },
155
+ set(target, key, value) {
156
+ if (typeof key !== "string" || key in target) return Reflect.set(target, key, value, target);
157
+ target.set({ [key]: value });
158
+ return true;
159
+ },
160
+ });
161
+ styleProxies.set(look, proxy);
162
+ return proxy;
163
+ }
164
+
97
165
  // The tree names font family lists by number: each `fontFamily` text is defined once, as a
98
166
  // list of its own. The numbers start high, clear of the lists a host defines, and stay
99
167
  // small enough to be exact in the 32-bit float a style value is.
@@ -195,6 +263,41 @@ class Look {
195
263
  return css;
196
264
  }
197
265
 
266
+ /** Replaces the look with declarations in CSS text, as `element.style.cssText`. */
267
+ set cssText(text) {
268
+ this.replace(parseDeclarations(String(text ?? "")));
269
+ }
270
+
271
+ get length() {
272
+ return Object.keys(this.#values).length;
273
+ }
274
+
275
+ item(index) {
276
+ const name = Object.keys(this.#values)[index];
277
+ return name === undefined ? "" : cssName(name);
278
+ }
279
+
280
+ // CSSStyleDeclaration's methods, which take CSS names (`background-color`, `--gap`).
281
+ setProperty(name, value, priority) {
282
+ const text = value === null || value === undefined ? "" : String(value) + (priority === "important" ? " !important" : "");
283
+ this.set({ [camelName(String(name))]: text });
284
+ }
285
+
286
+ removeProperty(name) {
287
+ const camel = camelName(String(name));
288
+ const old = this.get(camel) ?? "";
289
+ this.set({ [camel]: null });
290
+ return old;
291
+ }
292
+
293
+ getPropertyValue(name) {
294
+ return this.get(camelName(String(name))) ?? "";
295
+ }
296
+
297
+ getPropertyPriority() {
298
+ return "";
299
+ }
300
+
198
301
  _copyTo(look) {
199
302
  look.#values = Object.assign(Object.create(null), this.#values);
200
303
  const css = this.cssText;
@@ -486,6 +589,30 @@ export class Node {
486
589
  return 1;
487
590
  }
488
591
 
592
+ /**
593
+ * The element's tag: the HTML tag it was made with (see `createElement`), or for a tree
594
+ * node the tag stylesheets match it by (`div` for a box).
595
+ */
596
+ get localName() {
597
+ return this._tag ?? LOCAL_NAMES[this.kind] ?? "div";
598
+ }
599
+
600
+ set localName(value) {
601
+ this._tag = String(value);
602
+ }
603
+
604
+ /** The tag in upper case for HTML elements, as in the DOM. */
605
+ get tagName() {
606
+ const name = this.localName;
607
+ return this.namespaceURI === undefined ? name.toUpperCase() : name;
608
+ }
609
+
610
+ set tagName(_value) {}
611
+
612
+ get nodeName() {
613
+ return this.tagName;
614
+ }
615
+
489
616
  hasChildNodes() {
490
617
  return this.childNodes.length > 0;
491
618
  }
@@ -628,11 +755,12 @@ export class Node {
628
755
  * `node.style = { ... }` replaces the look.
629
756
  */
630
757
  get style() {
631
- return this.look("base");
758
+ return this._tag === undefined ? this.look("base") : styleProxy(this.look("base"));
632
759
  }
633
760
 
634
761
  set style(properties) {
635
- this.look("base").replace(properties);
762
+ if (typeof properties === "string") this.look("base").cssText = properties;
763
+ else this.look("base").replace(properties);
636
764
  }
637
765
 
638
766
  /** The look the tree lays over the base in `state`: hover, active, focus, focusVisible, or
@@ -668,11 +796,33 @@ export class Node {
668
796
  }
669
797
 
670
798
  hasAttribute(name) { return this.getAttribute(name) !== null; }
799
+
800
+ getAttributeNames() {
801
+ const names = this.#className === null ? [] : ["class"];
802
+ for (const name of this.#rare?.attributes?.keys() ?? []) names.push(name);
803
+ return names;
804
+ }
805
+
806
+ /** The children as HTML; setting it replaces them with nodes parsed from HTML. */
807
+ get innerHTML() {
808
+ let html = "";
809
+ for (const child of this.childNodes) html += markupOf(child);
810
+ return html;
811
+ }
812
+
813
+ set innerHTML(html) {
814
+ for (const child of this.childNodes.slice()) child.destroy();
815
+ parseHTML(String(html ?? ""), this);
816
+ }
817
+
818
+ get outerHTML() {
819
+ return markupOf(this);
820
+ }
671
821
  removeAttribute(name) { this.setAttribute(name, null); }
672
822
 
673
823
  setAttribute(name, value) {
674
824
  name = String(name);
675
- const text = value == null ? null : String(value);
825
+ let text = value == null ? null : String(value);
676
826
  if (name === "className" || name === "class") {
677
827
  native.attribute(this.nodeId, "class", text);
678
828
  this.#className = text;
@@ -692,6 +842,20 @@ export class Node {
692
842
  else warnOnce("only an image has a src: it is ignored");
693
843
  } else if (name === "alt") {
694
844
  native.attribute(this.nodeId, "label", text ?? "");
845
+ } else if (this._tag !== undefined && (name === "tabindex" || name === "tabIndex")) {
846
+ this._keep("focus", "blur");
847
+ native.attribute(this.nodeId, "tabIndex", text === null ? -2147483648 : Number(text));
848
+ } else if (this._tag !== undefined && name === "style") {
849
+ this.style.cssText = text ?? "";
850
+ } else if (this._tag !== undefined && BOOLEAN_TREE_ATTRIBUTES.has(name)) {
851
+ // An HTML boolean attribute is on whatever its text, `disabled=""` included.
852
+ const on = value !== null && value !== undefined && value !== false;
853
+ text = on ? "" : null;
854
+ if (name === "checked" && "checked" in this) this.checked = on;
855
+ else native.attribute(this.nodeId, name === "readonly" ? "readOnly" : name, on);
856
+ } else if (this._tag !== undefined && name !== "href" && name !== "placeholder" && name !== "label") {
857
+ // Any other HTML attribute is text the tree keeps for selectors (`[type=checkbox]`).
858
+ native.attribute(this.nodeId, name, text);
695
859
  } else {
696
860
  if (name === "href") {
697
861
  this._href = text || null;
@@ -727,7 +891,7 @@ export class Node {
727
891
  const has = (type) => (listeners?.get(type)?.length ?? 0) > 0;
728
892
  if (kind >= TOUCH_START) return [KINDS_OF_BIT(bitOf(kind)).some((each) => has(TYPES[each])), (1 << bitOf(kind)) >>> 0];
729
893
  const type = TYPES[kind];
730
- const wanted = has(type) || (MOUSE_OF.has(type) && has(MOUSE_OF.get(type))) || (kind === CLICK && this._href)
894
+ const wanted = has(type) || (MOUSE_OF.has(type) && has(MOUSE_OF.get(type))) || (kind === CLICK && (this._href || this._activate))
731
895
  || (kind === SELECTION_CHANGE && has("selectstart"));
732
896
  return [wanted, 1 << kind];
733
897
  }
@@ -946,6 +1110,10 @@ export class Text extends Node {
946
1110
  return 3;
947
1111
  }
948
1112
 
1113
+ get nodeName() {
1114
+ return "#text";
1115
+ }
1116
+
949
1117
  get nodeValue() {
950
1118
  return this.#data;
951
1119
  }
@@ -1820,8 +1988,6 @@ export class Svg extends Node {
1820
1988
  // The tree's node for drawn SVG markup is an icon; to code it is an `svg`.
1821
1989
  super("icon");
1822
1990
  this.kind = "svg";
1823
- this.localName = "svg";
1824
- this.tagName = "svg";
1825
1991
  this.namespaceURI = SVG_NAMESPACE;
1826
1992
  svgChanged(this);
1827
1993
  }
@@ -2324,6 +2490,278 @@ export function createNode(kind) {
2324
2490
  return new Node(kind);
2325
2491
  }
2326
2492
 
2493
+ // `<input>` types that are not a text field.
2494
+ const BOX_INPUTS = new Set(["checkbox", "radio", "range", "color", "file", "hidden", "submit", "button", "reset", "image"]);
2495
+ // Tags that take focus without a tabindex, as on the web.
2496
+ const FOCUSABLE_TAGS = new Set(["button", "select", "summary", "iframe"]);
2497
+
2498
+ /**
2499
+ * `<input type="checkbox">` and `type="radio"`: a box a click checks, as on the web. It fires
2500
+ * `input` and `change` when the click changes it.
2501
+ */
2502
+ export class CheckInput extends Node {
2503
+ #checked = false;
2504
+
2505
+ constructor(type = "checkbox") {
2506
+ super("box");
2507
+ this._tag = "input";
2508
+ this.type = type;
2509
+ this.value = "on";
2510
+ this.defaultChecked = false;
2511
+ native.attribute(this.nodeId, "element", "input");
2512
+ native.attribute(this.nodeId, "type", type);
2513
+ native.attribute(this.nodeId, "role", type === "radio" ? "radio" : "checkbox");
2514
+ native.attribute(this.nodeId, "tabIndex", 0);
2515
+ this._keep("focus", "blur");
2516
+ this._relisten();
2517
+ }
2518
+
2519
+ _shallowClone() {
2520
+ const copy = new CheckInput(this.type);
2521
+ copy.checked = this.#checked;
2522
+ return copy;
2523
+ }
2524
+
2525
+ get name() {
2526
+ return this.getAttribute("name") ?? "";
2527
+ }
2528
+
2529
+ get checked() {
2530
+ return this.#checked;
2531
+ }
2532
+
2533
+ set checked(value) {
2534
+ value = !!value;
2535
+ if (value === this.#checked) return;
2536
+ this.#checked = value;
2537
+ native.attribute(this.nodeId, "checked", value);
2538
+ if (value && this.type === "radio" && this.name) {
2539
+ let top = this;
2540
+ while (top.parentNode) top = top.parentNode;
2541
+ eachDescendant(top, (node) => {
2542
+ if (node !== this && node instanceof CheckInput && node.type === "radio" && node.name === this.name) node.checked = false;
2543
+ });
2544
+ }
2545
+ }
2546
+
2547
+ _activate() {
2548
+ if (this.hasAttribute("disabled")) return true;
2549
+ if (this.type === "radio" && this.#checked) return true;
2550
+ this.checked = this.type === "radio" ? true : !this.#checked;
2551
+ const input = new Event("input", this);
2552
+ input.bubbles = true;
2553
+ dispatchEvent(input);
2554
+ const change = new Event("change", this);
2555
+ change.bubbles = true;
2556
+ dispatchEvent(change);
2557
+ return true;
2558
+ }
2559
+ }
2560
+
2561
+ function eachDescendant(node, visit) {
2562
+ for (const child of node.childNodes) {
2563
+ visit(child);
2564
+ if (child.childNodes.length) eachDescendant(child, visit);
2565
+ }
2566
+ }
2567
+
2568
+ function findById(id) {
2569
+ for (const node of nodes.values()) if (node._elementId === id && (node.parentNode || node === rootNode)) return node;
2570
+ return null;
2571
+ }
2572
+
2573
+ // What a click on a label, summary or submit button does (see `activate`).
2574
+ function labelActivate() {
2575
+ const id = this.getAttribute("for");
2576
+ let control = id ? findById(id) : null;
2577
+ if (!control) eachDescendant(this, (node) => {
2578
+ if (!control && (node instanceof Input || node instanceof CheckInput)) control = node;
2579
+ });
2580
+ if (!control) return false;
2581
+ if (control instanceof CheckInput) control._activate();
2582
+ else control.focus();
2583
+ return true;
2584
+ }
2585
+
2586
+ function summaryActivate() {
2587
+ const details = this.parentNode;
2588
+ if (details?.localName !== "details") return false;
2589
+ details.setAttribute("open", details.hasAttribute("open") ? null : "");
2590
+ const toggle = new Event("toggle", details);
2591
+ dispatchEvent(toggle);
2592
+ return true;
2593
+ }
2594
+
2595
+ function buttonActivate() {
2596
+ if (this.hasAttribute("disabled")) return true;
2597
+ const type = this.getAttribute("type") ?? "submit";
2598
+ if (type !== "submit" && type !== "reset") return false;
2599
+ let form = this.parentNode;
2600
+ while (form && form.localName !== "form") form = form.parentNode;
2601
+ if (!form) return false;
2602
+ const event = new Event(type, form);
2603
+ event.bubbles = true;
2604
+ event.cancelable = true;
2605
+ event.submitter = this;
2606
+ dispatchEvent(event);
2607
+ return true;
2608
+ }
2609
+
2610
+ /**
2611
+ * The node for HTML element `tag`, as `document.createElement` makes it: `<input>` and
2612
+ * `<textarea>` are text fields (an `<input>` whose `type` is not a text field's is a box),
2613
+ * `<img>` an image, `<canvas>` a canvas, `<svg>` inline SVG, and every other tag a box the
2614
+ * tree knows by its tag, for selectors, its implicit role and the default stylesheet of
2615
+ * `@silkui/react`. `localName` and `tagName` give the tag.
2616
+ */
2617
+ export function createElement(tag, options) {
2618
+ tag = String(tag).toLowerCase();
2619
+ const type = String(options?.type ?? "text").toLowerCase();
2620
+ let node;
2621
+ if (tag === "svg") return new Svg();
2622
+ if (tag === "input" && (type === "checkbox" || type === "radio")) return new CheckInput(type);
2623
+ if (tag === "input" && !BOX_INPUTS.has(type)) node = new Input();
2624
+ else if (tag === "textarea") node = new Input();
2625
+ else if (tag === "img") node = new Image();
2626
+ else if (tag === "canvas") node = new Canvas();
2627
+ else node = new Node("box");
2628
+ node._tag = tag;
2629
+ native.attribute(node.nodeId, "element", tag);
2630
+ if (tag === "textarea") native.attribute(node.nodeId, "multiline", true);
2631
+ if (tag === "input" && type !== "text") native.attribute(node.nodeId, "type", type);
2632
+ if (node instanceof Input || FOCUSABLE_TAGS.has(tag)) {
2633
+ if (!(node instanceof Input)) native.attribute(node.nodeId, "tabIndex", 0);
2634
+ node._keep("focus", "blur");
2635
+ }
2636
+ if (tag === "label") node._activate = labelActivate;
2637
+ else if (tag === "summary") node._activate = summaryActivate;
2638
+ else if (tag === "button") node._activate = buttonActivate;
2639
+ if (node._activate) node._relisten();
2640
+ return node;
2641
+ }
2642
+
2643
+ const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
2644
+ // Elements whose content is not markup. Scripts and styles in parsed HTML are left out.
2645
+ const RAW_TAGS = new Set(["script", "style", "textarea", "title"]);
2646
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", copy: "©", reg: "®", hellip: "…", mdash: "—", ndash: "–", laquo: "«", raquo: "»", times: "×", middot: "·", bull: "•" };
2647
+ const ATTRIBUTE = /\s*([^\s"'>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/y;
2648
+
2649
+ function decodeEntities(text) {
2650
+ if (!text.includes("&")) return text;
2651
+ return text.replace(/&(#[xX][0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);/g, (whole, name) => {
2652
+ if (name[0] === "#") {
2653
+ const code = name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
2654
+ return Number.isFinite(code) ? String.fromCodePoint(code) : whole;
2655
+ }
2656
+ return ENTITIES[name] ?? whole;
2657
+ });
2658
+ }
2659
+
2660
+ const escapeText = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;");
2661
+ const escapeAttribute = (text) => text.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
2662
+
2663
+ function markupOf(node) {
2664
+ if (node.nodeType === 3) return escapeText(node.data);
2665
+ if (node instanceof Svg || node instanceof SvgElement) return node.outerHTML ?? node._markup();
2666
+ if (node.nodeType === 11) return node.innerHTML;
2667
+ const tag = node.localName;
2668
+ let html = "<" + tag;
2669
+ for (const name of node.getAttributeNames()) if (name !== "style") html += " " + name + '="' + escapeAttribute(node.getAttribute(name)) + '"';
2670
+ const css = node.look("base").cssText;
2671
+ if (css) html += ' style="' + escapeAttribute(css) + '"';
2672
+ html += ">";
2673
+ if (VOID_TAGS.has(tag)) return html;
2674
+ if (node instanceof Input) html += escapeText(node.value);
2675
+ else html += node.innerHTML;
2676
+ return html + "</" + tag + ">";
2677
+ }
2678
+
2679
+ /**
2680
+ * Parses `html` and appends its nodes to `parent`, as `innerHTML` does: elements, text with
2681
+ * character references, and `<svg>` markup. Comments, scripts and styles are left out.
2682
+ */
2683
+ export function parseHTML(html, parent) {
2684
+ const stack = [parent];
2685
+ const top = () => stack[stack.length - 1];
2686
+ const inSvg = () => top() instanceof Svg || top() instanceof SvgElement;
2687
+ let i = 0;
2688
+ const text = (data) => {
2689
+ if (!data) return;
2690
+ const value = decodeEntities(data);
2691
+ top().appendChild(inSvg() ? new SvgText(value) : createText(value));
2692
+ };
2693
+ while (i < html.length) {
2694
+ const open = html.indexOf("<", i);
2695
+ if (open < 0) {
2696
+ text(html.slice(i));
2697
+ break;
2698
+ }
2699
+ text(html.slice(i, open));
2700
+ if (html.startsWith("<!--", open)) {
2701
+ const end = html.indexOf("-->", open + 4);
2702
+ i = end < 0 ? html.length : end + 3;
2703
+ continue;
2704
+ }
2705
+ if (html[open + 1] === "!" || html[open + 1] === "?") {
2706
+ const end = html.indexOf(">", open);
2707
+ i = end < 0 ? html.length : end + 1;
2708
+ continue;
2709
+ }
2710
+ if (html[open + 1] === "/") {
2711
+ const end = html.indexOf(">", open);
2712
+ const name = html.slice(open + 2, end < 0 ? html.length : end).trim().toLowerCase();
2713
+ i = end < 0 ? html.length : end + 1;
2714
+ for (let at = stack.length - 1; at > 0; at--) {
2715
+ if (stack[at].localName.toLowerCase() === name) {
2716
+ stack.length = at;
2717
+ break;
2718
+ }
2719
+ }
2720
+ continue;
2721
+ }
2722
+ const nameMatch = /^[a-zA-Z][^\s\/>]*/.exec(html.slice(open + 1, open + 64));
2723
+ if (!nameMatch) {
2724
+ text("<");
2725
+ i = open + 1;
2726
+ continue;
2727
+ }
2728
+ const written = nameMatch[0];
2729
+ const tag = inSvg() ? written : written.toLowerCase();
2730
+ let at = open + 1 + written.length;
2731
+ const attributes = [];
2732
+ ATTRIBUTE.lastIndex = at;
2733
+ for (let match; (match = ATTRIBUTE.exec(html)); ATTRIBUTE.lastIndex = at) {
2734
+ at = ATTRIBUTE.lastIndex;
2735
+ attributes.push([match[1], decodeEntities(match[2] ?? match[3] ?? match[4] ?? "")]);
2736
+ }
2737
+ while (at < html.length && html[at] !== ">") at++;
2738
+ const selfClosing = html[at - 1] === "/";
2739
+ i = at + 1;
2740
+ if (RAW_TAGS.has(tag)) {
2741
+ const close = html.toLowerCase().indexOf("</" + tag, i);
2742
+ const content = html.slice(i, close < 0 ? html.length : close);
2743
+ const end = close < 0 ? html.length : html.indexOf(">", close);
2744
+ i = end < 0 ? html.length : end + 1;
2745
+ if (tag === "script" || tag === "style") continue;
2746
+ const node = createElement(tag);
2747
+ for (const [name, value] of attributes) node.setAttribute(name, value);
2748
+ if (tag === "textarea") node.value = decodeEntities(content);
2749
+ else node.appendChild(createText(decodeEntities(content)));
2750
+ top().appendChild(node);
2751
+ continue;
2752
+ }
2753
+ const svg = inSvg() || tag === "svg";
2754
+ const type = attributes.find(([name]) => name.toLowerCase() === "type")?.[1];
2755
+ const node = svg ? createSvgElement(tag) : createElement(tag, { type });
2756
+ for (const [name, value] of attributes) {
2757
+ if (!svg && name.toLowerCase() === "value" && node instanceof Input) node.value = value;
2758
+ else node.setAttribute(svg ? name : name.toLowerCase(), value);
2759
+ }
2760
+ top().appendChild(node);
2761
+ if (!selfClosing && !(VOID_TAGS.has(tag) && !svg)) stack.push(node);
2762
+ }
2763
+ }
2764
+
2327
2765
  /** A box with `style` as its base look and `children` appended. */
2328
2766
  export function createBox(style, ...children) {
2329
2767
  const box = new Node("box");
@@ -3614,8 +4052,10 @@ native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, thir
3614
4052
  if (!target) return false;
3615
4053
  if (kind >= COPY) return dispatchEditing(kind, target, first, second, third);
3616
4054
  if (kind === SELECTION_CHANGE && !(target instanceof Input)) return selectionRecord(target, a);
4055
+ if (kind === FOCUS) focusing(target);
3617
4056
  const event = new Event(TYPES[kind], target);
3618
4057
  fill(event, kind, a, b, modifiers, d, e, first, second, third, fourth);
4058
+ if (kind === FOCUS || kind === BLUR) event.relatedTarget = kind === FOCUS ? blurredNode : null;
3619
4059
  const live = target instanceof Svg && target._live && isPointerKind(kind);
3620
4060
  if (kind === CLICK && event.pointerType === "touch" && event.isPrimary) compatTap(event, target);
3621
4061
  // A live svg sends pointer records on to the element under the pointer.
@@ -3625,7 +4065,12 @@ native.dispatch = function (kind, id, a, b, modifiers, d, e, first, second, thir
3625
4065
  dispatchEvent(event);
3626
4066
  prevented = event.defaultPrevented;
3627
4067
  }
3628
- if (kind === CLICK && !prevented) follow(target);
4068
+ if (kind === FOCUS) {
4069
+ focusEvent("focusin", target, blurredNode);
4070
+ blurredNode = null;
4071
+ }
4072
+ else if (kind === BLUR) blurring(target);
4073
+ if (kind === CLICK && !prevented && !activate(target)) follow(target);
3629
4074
  if (kind !== CLICK && isPointerKind(kind)) {
3630
4075
  if (event.pointerType !== "touch") compatMouse(kind, event, live && event.target instanceof SvgElement ? event.target : target);
3631
4076
  // A finger's defaults (pan, focus, the tap's click) follow its touch events, not its
@@ -3684,6 +4129,57 @@ function writeClipboard(data) {
3684
4129
  Promise.resolve(written).catch(reportError);
3685
4130
  }
3686
4131
 
4132
+ // The focused node, as far as focus and blur records tell (HTML elements that can take focus
4133
+ // listen for both: see `createElement`).
4134
+ let focusedNode = null;
4135
+ // The node a blur record left, until the focus record that follows it.
4136
+ let blurredNode = null;
4137
+ let pendingFocusOut = null;
4138
+
4139
+ /** The focused node, or null. */
4140
+ export function activeElement() {
4141
+ return focusedNode?.parentNode || focusedNode === rootNode ? focusedNode : null;
4142
+ }
4143
+
4144
+ function focusEvent(type, target, relatedTarget) {
4145
+ const event = new Event(type, target);
4146
+ event.bubbles = true;
4147
+ event.relatedTarget = relatedTarget;
4148
+ dispatchEvent(event);
4149
+ }
4150
+
4151
+ // `focusout` waits for the focus record that follows a blur, so its `relatedTarget` is where
4152
+ // focus went, as on the web; with none, it goes out on its own.
4153
+ function blurring(target) {
4154
+ if (focusedNode === target) focusedNode = null;
4155
+ blurredNode = target;
4156
+ pendingFocusOut = target;
4157
+ queueMicrotask(() => {
4158
+ if (pendingFocusOut !== target) return;
4159
+ pendingFocusOut = null;
4160
+ blurredNode = null;
4161
+ focusEvent("focusout", target, null);
4162
+ });
4163
+ }
4164
+
4165
+ function focusing(target) {
4166
+ focusedNode = target;
4167
+ const left = pendingFocusOut;
4168
+ pendingFocusOut = null;
4169
+ if (left) focusEvent("focusout", left, target);
4170
+ else blurredNode = null;
4171
+ }
4172
+
4173
+ // HTML defaults of a click: a checkbox or radio checks, a label passes the click on to its
4174
+ // control, a summary opens its details, a submit button submits its form. True when one ran.
4175
+ function activate(target) {
4176
+ for (let node = target; node; node = node.parentNode) {
4177
+ if (node._activate) return node._activate() !== false;
4178
+ if (node._href) return false;
4179
+ }
4180
+ return false;
4181
+ }
4182
+
3687
4183
  // The default action of a click: the nearest link around the target opens.
3688
4184
  function follow(target) {
3689
4185
  for (let node = target; node; node = node.parentNode) {
@@ -3980,7 +4476,11 @@ function dragTo(target, x, y) {
3980
4476
  if (target) dragEvent("dragover", target, x, y, []);
3981
4477
  }
3982
4478
 
3983
- let trayMenu = new Map();
4479
+ // Menu item callbacks by action id. Each menu (the tray's, the app's, a context menu) owns
4480
+ // the ids it packed, and drops them when it is replaced or closes.
4481
+ const menuActions = new Map();
4482
+ const menuOwners = { tray: [], app: [], context: [] };
4483
+ let nextMenuAction = 0;
3984
4484
  let trayClick = null;
3985
4485
  const shortcuts = new Map();
3986
4486
  const shortcutIds = new Map();
@@ -4006,12 +4506,30 @@ native.shellEvent = function (kind, a, x, y, text) {
4006
4506
  } else if (kind === 5) {
4007
4507
  trayClick?.({ button: a });
4008
4508
  } else if (kind === 6) {
4009
- trayMenu.get(a)?.();
4509
+ const run = menuActions.get(a);
4510
+ if (menuOwners.context.includes(a)) closeContextMenu();
4511
+ run?.();
4010
4512
  } else if (kind === 7) {
4011
4513
  const notification = notifications.get(a);
4012
4514
  if (!notification) return;
4013
4515
  notifications.delete(a);
4014
4516
  notification._fire("click");
4517
+ } else if (kind === 8) {
4518
+ const resolve = dialogs.get(a);
4519
+ if (!resolve) return;
4520
+ dialogs.delete(a);
4521
+ resolve(text ? text.split("\n") : []);
4522
+ } else if (kind === 9) {
4523
+ closeContextMenu();
4524
+ } else if (kind === 10) {
4525
+ const fullScreen = a === 1;
4526
+ if (fullScreen === appWindow.fullScreen) return;
4527
+ appWindow.fullScreen = fullScreen;
4528
+ appWindow._fire("fullscreenchange", { fullScreen });
4529
+ } else if (kind === 11) {
4530
+ if (a === appWindow.zoomFactor) return;
4531
+ appWindow.zoomFactor = a;
4532
+ appWindow._fire("zoomchange", { zoomFactor: a });
4015
4533
  }
4016
4534
  };
4017
4535
 
@@ -4085,22 +4603,88 @@ function hex(bytes) {
4085
4603
  return text;
4086
4604
  }
4087
4605
 
4088
- function packMenu(items, lines) {
4606
+ // The roles the system implements, by `SystemItem` index; `about` and the others the
4607
+ // platform has no counterpart for are left out there.
4608
+ const SYSTEM_ROLES = {
4609
+ about: 0, services: 1, hide: 2, hideothers: 3, unhide: 4, quit: 5, close: 6, minimize: 7, zoom: 8,
4610
+ togglefullscreen: 9, front: 10, undo: 11, redo: 12, cut: 13, copy: 14, paste: 15, selectall: 16,
4611
+ };
4612
+
4613
+ // Roles JavaScript does itself, with their usual labels and shortcuts.
4614
+ const SCRIPT_ROLES = {
4615
+ resetzoom: { label: "Actual Size", accelerator: "Mod+0", click: () => appWindow.setZoomFactor(1) },
4616
+ zoomin: { label: "Zoom In", accelerator: "Mod+Plus", click: () => appWindow.setZoomFactor(zoomStep(1)) },
4617
+ zoomout: { label: "Zoom Out", accelerator: "Mod+-", click: () => appWindow.setZoomFactor(zoomStep(-1)) },
4618
+ };
4619
+
4620
+ // Roles that stand for a whole menu, as Electron's.
4621
+ const MENU_ROLES = {
4622
+ appmenu: () => [{ role: "about" }, { type: "separator" }, { role: "services" }, { type: "separator" }, { role: "hide" }, { role: "hideOthers" }, { role: "unhide" }, { type: "separator" }, { role: "quit" }],
4623
+ filemenu: () => [{ role: IS_MAC ? "close" : "quit" }],
4624
+ editmenu: () => [{ role: "undo" }, { role: "redo" }, { type: "separator" }, { role: "cut" }, { role: "copy" }, { role: "paste" }, { role: "selectAll" }],
4625
+ viewmenu: () => [{ role: "resetZoom" }, { role: "zoomIn" }, { role: "zoomOut" }, { type: "separator" }, { role: "togglefullscreen" }],
4626
+ windowmenu: () => [{ role: "minimize" }, { role: "zoom" }, ...(IS_MAC ? [{ type: "separator" }, { role: "front" }] : [{ role: "close" }])],
4627
+ };
4628
+
4629
+ const IS_MAC = /mac/i.test(globalThis.navigator?.platform ?? "") || globalThis.process?.platform === "darwin";
4630
+
4631
+ // A menu shortcut as the host reads it: "" for none, else the key (`c` and a character, `n`
4632
+ // and a key name) and the modifier bits.
4633
+ function packAccelerator(accelerator) {
4634
+ if (!accelerator) return ",0";
4635
+ const parts = String(accelerator).split("+").map((part) => part.trim());
4636
+ // "Mod+Plus" and "Mod++" both name the plus key.
4637
+ if (parts.at(-1) === "" && parts.at(-2) === "") parts.splice(-2, 2, "+");
4638
+ let bits = 0;
4639
+ let key = "";
4640
+ for (const part of parts) {
4641
+ const modifier = MODIFIERS[part.toLowerCase()];
4642
+ if (modifier !== undefined) bits |= modifier;
4643
+ else if (part) key = part;
4644
+ }
4645
+ const lower = key.toLowerCase();
4646
+ const named = { up: "ArrowUp", down: "ArrowDown", left: "ArrowLeft", right: "ArrowRight", esc: "Escape", escape: "Escape", return: "Enter", enter: "Enter", tab: "Tab", backspace: "Backspace", delete: "Delete", home: "Home", end: "End", pageup: "PageUp", pagedown: "PageDown" }[lower];
4647
+ if (named) return "n" + named + "," + bits;
4648
+ if (/^f([1-9]|1[0-9]|2[0-4])$/.test(lower)) return "nF" + lower.slice(1) + "," + bits;
4649
+ if (lower === "plus") return "c+," + bits;
4650
+ if (lower === "space") return "c ," + bits;
4651
+ if ([...key].length === 1) return "c" + lower + "," + bits;
4652
+ return "," + bits;
4653
+ }
4654
+
4655
+ // `items` as the host's menu lines, with their callbacks kept under `owner`.
4656
+ function packMenu(items, lines, owner) {
4089
4657
  for (const item of items) {
4658
+ if (!item || item.visible === false) continue;
4659
+ const role = String(item.role ?? "").toLowerCase();
4090
4660
  if (item.type === "separator") lines.push("S");
4091
- else if (item.submenu) {
4661
+ else if (MENU_ROLES[role] && !item.submenu) {
4662
+ lines.push("B" + String(item.label ?? role.replace(/menu$/, "").replace(/^./, (c) => c.toUpperCase())).replace(/\n/g, " "));
4663
+ packMenu(MENU_ROLES[role](), lines, owner);
4664
+ lines.push("E");
4665
+ } else if (item.submenu) {
4092
4666
  lines.push("B" + String(item.label ?? "").replace(/\n/g, " "));
4093
- packMenu(item.submenu, lines);
4667
+ packMenu(item.submenu, lines, owner);
4094
4668
  lines.push("E");
4669
+ } else if (SYSTEM_ROLES[role] !== undefined && !item.click) {
4670
+ lines.push("R" + SYSTEM_ROLES[role]);
4095
4671
  } else {
4096
- const action = trayMenu.size + 1;
4097
- trayMenu.set(action, typeof item.click === "function" ? item.click : () => {});
4098
- const label = String(item.label ?? "").replace(/\n/g, " ");
4099
- lines.push("A" + action + "," + (item.enabled === false ? 0 : 1) + "," + (item.checked ? 1 : 0) + "," + label);
4672
+ const known = SCRIPT_ROLES[role] ?? {};
4673
+ const action = ++nextMenuAction;
4674
+ const click = item.click ?? known.click;
4675
+ menuActions.set(action, typeof click === "function" ? () => click(item) : () => {});
4676
+ menuOwners[owner].push(action);
4677
+ const label = String(item.label ?? known.label ?? "").replace(/\n/g, " ");
4678
+ lines.push("A" + action + "," + (item.enabled === false ? 0 : 1) + "," + (item.checked ? 1 : 0) + "," + packAccelerator(item.accelerator ?? known.accelerator) + "," + label);
4100
4679
  }
4101
4680
  }
4102
4681
  }
4103
4682
 
4683
+ function dropMenu(owner) {
4684
+ for (const action of menuOwners[owner]) menuActions.delete(action);
4685
+ menuOwners[owner] = [];
4686
+ }
4687
+
4104
4688
  /**
4105
4689
  * Shows an icon in the system tray (the macOS menu bar, the Windows notification area, a
4106
4690
  * StatusNotifierItem on Linux). `icon` is RGBA pixels, as an `ImageData`: `{ width, height,
@@ -4113,17 +4697,17 @@ export function setTray({ icon, tooltip = "", template = false, menu = [], onCli
4113
4697
  if (!icon || !(icon.width > 0) || !(icon.height > 0) || icon.data?.length !== icon.width * icon.height * 4) {
4114
4698
  throw new TypeError("setTray needs an icon of RGBA pixels: { width, height, data }");
4115
4699
  }
4116
- trayMenu = new Map();
4700
+ dropMenu("tray");
4117
4701
  trayClick = typeof onClick === "function" ? onClick : null;
4118
4702
  const lines = [];
4119
- packMenu(menu, lines);
4703
+ packMenu(menu, lines, "tray");
4120
4704
  const fields = [String(tooltip), icon.width, icon.height, template ? 1 : 0, hex(icon.data), lines.join("\n")];
4121
4705
  return shellCall(1, fields).then((shown) => shown === 1);
4122
4706
  }
4123
4707
 
4124
4708
  /** Takes the tray icon away. */
4125
4709
  export function removeTray() {
4126
- trayMenu = new Map();
4710
+ dropMenu("tray");
4127
4711
  trayClick = null;
4128
4712
  shellCall(2, []);
4129
4713
  }
@@ -4183,6 +4767,226 @@ export function unregisterShortcut(accelerator) {
4183
4767
  shellCall(4, [id]);
4184
4768
  }
4185
4769
 
4770
+ // File dialogs waiting for `DialogClosed`, by dialog id.
4771
+ const dialogs = new Map();
4772
+
4773
+ function extensionsOf(filters) {
4774
+ const all = [];
4775
+ for (const filter of filters ?? []) {
4776
+ for (const extension of filter.extensions ?? []) {
4777
+ if (extension === "*") return "";
4778
+ all.push(String(extension).replace(/^\./, ""));
4779
+ }
4780
+ }
4781
+ return all.join(",");
4782
+ }
4783
+
4784
+ function dialog(op, fields) {
4785
+ return shellCall(op, fields).then((id) => (id ? new Promise((resolve) => dialogs.set(id, resolve)) : []));
4786
+ }
4787
+
4788
+ /**
4789
+ * Opens the system's file dialog, as Electron's `dialog.showOpenDialog`: `properties` takes
4790
+ * `openFile`, `openDirectory` and `multiSelections`; `filters` are `{ name, extensions }`
4791
+ * without dots (`"*"` for every file). It attaches to the window as a sheet on macOS and never
4792
+ * blocks. Resolves to `{ canceled, filePaths }`.
4793
+ */
4794
+ export function showOpenDialog(options = {}) {
4795
+ const properties = options.properties ?? ["openFile"];
4796
+ const directories = properties.includes("openDirectory");
4797
+ const files = properties.includes("openFile") || !directories;
4798
+ const flags = (files ? 1 : 0) | (directories ? 2 : 0) | (properties.includes("multiSelections") ? 4 : 0);
4799
+ return dialog(5, [String(options.title ?? ""), String(options.defaultPath ?? ""), flags, extensionsOf(options.filters)]).then(
4800
+ (filePaths) => ({ canceled: filePaths.length === 0, filePaths }),
4801
+ );
4802
+ }
4803
+
4804
+ /**
4805
+ * Opens the system's save dialog, as Electron's `dialog.showSaveDialog`. `defaultPath` may
4806
+ * name a folder, a file, or both. Resolves to `{ canceled, filePath }`.
4807
+ */
4808
+ export function showSaveDialog(options = {}) {
4809
+ const path = String(options.defaultPath ?? "");
4810
+ const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
4811
+ const looksLikeFolder = slash === path.length - 1 || !/\.[^./\\]+$/.test(path.slice(slash + 1));
4812
+ const directory = looksLikeFolder ? path : path.slice(0, Math.max(slash, 0));
4813
+ const name = looksLikeFolder ? "" : path.slice(slash + 1);
4814
+ return dialog(6, [String(options.title ?? ""), directory, name, extensionsOf(options.filters)]).then((paths) => ({
4815
+ canceled: paths.length === 0,
4816
+ filePath: paths[0] ?? "",
4817
+ }));
4818
+ }
4819
+
4820
+ /**
4821
+ * Replaces the app's menu bar, as Electron's `Menu.setApplicationMenu(Menu.buildFromTemplate(t))`.
4822
+ * Items are `{ label, click, accelerator, enabled, checked, type, role, submenu, visible }`.
4823
+ * `accelerator` is `"Mod+Shift+K"` (`Mod`, `CmdOrCtrl`: Command on macOS, Control elsewhere).
4824
+ * The system roles (`about`, `quit`, `undo`, `copy`, `togglefullscreen`, `minimize`, `front`
4825
+ * and so on) are the system's own items; `zoomIn`, `zoomOut` and `resetZoom` zoom the page;
4826
+ * `appMenu`, `fileMenu`, `editMenu`, `viewMenu` and `windowMenu` are whole menus. On macOS
4827
+ * the first menu is the app menu. Edit shortcuts reach the focused node as keys first.
4828
+ */
4829
+ export function setApplicationMenu(template) {
4830
+ dropMenu("app");
4831
+ const lines = [];
4832
+ packMenu(template ?? [], lines, "app");
4833
+ return shellCall(7, [lines.join("\n")]).then(() => undefined);
4834
+ }
4835
+
4836
+ let contextMenuClosed = null;
4837
+
4838
+ function closeContextMenu() {
4839
+ dropMenu("context");
4840
+ const closed = contextMenuClosed;
4841
+ contextMenuClosed = null;
4842
+ closed?.();
4843
+ }
4844
+
4845
+ /**
4846
+ * Opens a native context menu at `x`, `y` (CSS pixels in the window, a `MouseEvent`'s
4847
+ * `clientX`/`clientY`), as Electron's `menu.popup()`. Items are as `setApplicationMenu`'s.
4848
+ * Resolves when the menu closes, with or without a choice, to `true`; or at once to `false`
4849
+ * when the system draws no context menus (Linux, the browser) and the app should draw its own.
4850
+ */
4851
+ export function showContextMenu(template, { x = 0, y = 0 } = {}) {
4852
+ closeContextMenu();
4853
+ const lines = [];
4854
+ packMenu(template ?? [], lines, "context");
4855
+ const zoom = appWindow.zoomFactor || 1;
4856
+ return shellCall(8, [x * zoom, y * zoom, lines.join("\n")]).then((shown) => {
4857
+ if (shown !== 1) {
4858
+ dropMenu("context");
4859
+ return false;
4860
+ }
4861
+ return new Promise((resolve) => (contextMenuClosed = () => resolve(true)));
4862
+ });
4863
+ }
4864
+
4865
+ /** Puts `text` on the app's dock or taskbar icon (an unread count); `""` takes it off. */
4866
+ export function setBadge(text) {
4867
+ return shellCall(9, [String(text ?? "")]).then((shown) => shown === 1);
4868
+ }
4869
+
4870
+ /** Shows progress from 0 to 1 on the app's dock or taskbar icon; a negative number takes it off. */
4871
+ export function setProgress(fraction) {
4872
+ return shellCall(10, [Number(fraction)]).then((shown) => shown === 1);
4873
+ }
4874
+
4875
+ /** Opens `url` with the system's handler: a web page in the default browser, `mailto:` in the mail app. */
4876
+ export function openExternal(url) {
4877
+ return shellCall(11, [String(url)]).then((opened) => opened === 1);
4878
+ }
4879
+
4880
+ /** Shows the file or folder at `path` selected in Finder, Explorer or the file manager. */
4881
+ export function showItemInFolder(path) {
4882
+ return shellCall(12, [String(path)]).then((shown) => shown === 1);
4883
+ }
4884
+
4885
+ /**
4886
+ * Drags the files at `paths` out of the window, as Electron's `webContents.startDrag`, so
4887
+ * Finder, a mail draft or a terminal can take them. Call it from a `pointerdown` or
4888
+ * `pointermove` listener while the button is down. Resolves to whether the drag started
4889
+ * (macOS and Windows drag files out; Linux and the browser do not).
4890
+ */
4891
+ export function startFileDrag(paths) {
4892
+ const list = (Array.isArray(paths) ? paths : [paths]).map(String).filter(Boolean);
4893
+ return shellCall(13, [list.join("\n")]).then((started) => started === 1);
4894
+ }
4895
+
4896
+ const ZOOM_STEPS = [0.25, 0.33, 0.5, 0.67, 0.75, 0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5];
4897
+
4898
+ function zoomStep(direction) {
4899
+ const now = appWindow.zoomFactor;
4900
+ if (direction > 0) return ZOOM_STEPS.find((step) => step > now + 0.001) ?? now;
4901
+ return ZOOM_STEPS.findLast((step) => step < now - 0.001) ?? now;
4902
+ }
4903
+
4904
+ /**
4905
+ * The window the app runs in. `fullScreen` and `zoomFactor` (the page zoom, as Electron's
4906
+ * `webFrame.getZoomFactor()`; Mod with `=`, `-` and `0` change it too) are current, and
4907
+ * `fullscreenchange` and `zoomchange` say when they change. The title bar is the app's
4908
+ * configuration: a transparent one, with the window controls placed in it, comes from
4909
+ * `TitleBar.transparent` in its `tasks.silk`.
4910
+ */
4911
+ class AppWindow {
4912
+ fullScreen = false;
4913
+ zoomFactor = 1;
4914
+ #listeners = new Map();
4915
+
4916
+ setFullScreen(on) {
4917
+ if (!!on !== this.fullScreen) shellCall(14, [0]);
4918
+ }
4919
+
4920
+ toggleFullScreen() {
4921
+ shellCall(14, [0]);
4922
+ }
4923
+
4924
+ minimize() {
4925
+ shellCall(14, [1]);
4926
+ }
4927
+
4928
+ /** Shows the window and brings it to the front with keyboard focus. */
4929
+ focus() {
4930
+ shellCall(14, [2]);
4931
+ }
4932
+
4933
+ show() {
4934
+ shellCall(14, [2]);
4935
+ }
4936
+
4937
+ hide() {
4938
+ shellCall(14, [3]);
4939
+ }
4940
+
4941
+ setTitle(title) {
4942
+ shellCall(14, [4, String(title)]);
4943
+ }
4944
+
4945
+ /** Zooms the page, from 0.25 to 5. Resolves to the zoom now. */
4946
+ setZoomFactor(zoom) {
4947
+ return shellCall(15, [Math.min(5, Math.max(0.25, Number(zoom) || 1))]).then((now) => {
4948
+ if (now !== this.zoomFactor) {
4949
+ this.zoomFactor = now;
4950
+ this._fire("zoomchange", { zoomFactor: now });
4951
+ }
4952
+ return now;
4953
+ });
4954
+ }
4955
+
4956
+ getZoomFactor() {
4957
+ return this.zoomFactor;
4958
+ }
4959
+
4960
+ isFullScreen() {
4961
+ return this.fullScreen;
4962
+ }
4963
+
4964
+ addEventListener(type, listener) {
4965
+ let list = this.#listeners.get(type);
4966
+ if (!list) this.#listeners.set(type, (list = []));
4967
+ if (!list.includes(listener)) list.push(listener);
4968
+ }
4969
+
4970
+ removeEventListener(type, listener) {
4971
+ const list = this.#listeners.get(type);
4972
+ const index = list ? list.indexOf(listener) : -1;
4973
+ if (index >= 0) list.splice(index, 1);
4974
+ }
4975
+
4976
+ _fire(type, detail) {
4977
+ const event = { type, target: this, ...detail };
4978
+ for (const listener of (this.#listeners.get(type) ?? []).slice()) {
4979
+ try {
4980
+ listener.call(this, event);
4981
+ } catch (error) {
4982
+ reportError(error);
4983
+ }
4984
+ }
4985
+ }
4986
+ }
4987
+
4988
+ export const appWindow = new AppWindow();
4989
+
4186
4990
  /**
4187
4991
  * The app's memory in bytes, as the system shows it to users: `phys_footprint` on macOS
4188
4992
  * (Activity Monitor's "Memory"), `Pss` on Linux and `PrivateUsage` on Windows. `processes` is