@silkui/core 0.1.10 → 0.1.12
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 +36 -0
- package/package.json +1 -1
- package/src/index.d.ts +180 -0
- package/src/index.js +1133 -19
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").
|
|
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
|
-
|
|
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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/ /g, " ");
|
|
2661
|
+
const escapeAttribute = (text) => text.replace(/&/g, "&").replace(/"/g, """);
|
|
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 ===
|
|
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
|
-
|
|
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,32 @@ 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
|
-
|
|
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 });
|
|
4533
|
+
} else if (kind === WEB_VIEW_EVENT) {
|
|
4534
|
+
webViewEvent(a, x, text);
|
|
4015
4535
|
}
|
|
4016
4536
|
};
|
|
4017
4537
|
|
|
@@ -4085,22 +4605,88 @@ function hex(bytes) {
|
|
|
4085
4605
|
return text;
|
|
4086
4606
|
}
|
|
4087
4607
|
|
|
4088
|
-
|
|
4608
|
+
// The roles the system implements, by `SystemItem` index; `about` and the others the
|
|
4609
|
+
// platform has no counterpart for are left out there.
|
|
4610
|
+
const SYSTEM_ROLES = {
|
|
4611
|
+
about: 0, services: 1, hide: 2, hideothers: 3, unhide: 4, quit: 5, close: 6, minimize: 7, zoom: 8,
|
|
4612
|
+
togglefullscreen: 9, front: 10, undo: 11, redo: 12, cut: 13, copy: 14, paste: 15, selectall: 16,
|
|
4613
|
+
};
|
|
4614
|
+
|
|
4615
|
+
// Roles JavaScript does itself, with their usual labels and shortcuts.
|
|
4616
|
+
const SCRIPT_ROLES = {
|
|
4617
|
+
resetzoom: { label: "Actual Size", accelerator: "Mod+0", click: () => appWindow.setZoomFactor(1) },
|
|
4618
|
+
zoomin: { label: "Zoom In", accelerator: "Mod+Plus", click: () => appWindow.setZoomFactor(zoomStep(1)) },
|
|
4619
|
+
zoomout: { label: "Zoom Out", accelerator: "Mod+-", click: () => appWindow.setZoomFactor(zoomStep(-1)) },
|
|
4620
|
+
};
|
|
4621
|
+
|
|
4622
|
+
// Roles that stand for a whole menu, as Electron's.
|
|
4623
|
+
const MENU_ROLES = {
|
|
4624
|
+
appmenu: () => [{ role: "about" }, { type: "separator" }, { role: "services" }, { type: "separator" }, { role: "hide" }, { role: "hideOthers" }, { role: "unhide" }, { type: "separator" }, { role: "quit" }],
|
|
4625
|
+
filemenu: () => [{ role: IS_MAC ? "close" : "quit" }],
|
|
4626
|
+
editmenu: () => [{ role: "undo" }, { role: "redo" }, { type: "separator" }, { role: "cut" }, { role: "copy" }, { role: "paste" }, { role: "selectAll" }],
|
|
4627
|
+
viewmenu: () => [{ role: "resetZoom" }, { role: "zoomIn" }, { role: "zoomOut" }, { type: "separator" }, { role: "togglefullscreen" }],
|
|
4628
|
+
windowmenu: () => [{ role: "minimize" }, { role: "zoom" }, ...(IS_MAC ? [{ type: "separator" }, { role: "front" }] : [{ role: "close" }])],
|
|
4629
|
+
};
|
|
4630
|
+
|
|
4631
|
+
const IS_MAC = /mac/i.test(globalThis.navigator?.platform ?? "") || globalThis.process?.platform === "darwin";
|
|
4632
|
+
|
|
4633
|
+
// A menu shortcut as the host reads it: "" for none, else the key (`c` and a character, `n`
|
|
4634
|
+
// and a key name) and the modifier bits.
|
|
4635
|
+
function packAccelerator(accelerator) {
|
|
4636
|
+
if (!accelerator) return ",0";
|
|
4637
|
+
const parts = String(accelerator).split("+").map((part) => part.trim());
|
|
4638
|
+
// "Mod+Plus" and "Mod++" both name the plus key.
|
|
4639
|
+
if (parts.at(-1) === "" && parts.at(-2) === "") parts.splice(-2, 2, "+");
|
|
4640
|
+
let bits = 0;
|
|
4641
|
+
let key = "";
|
|
4642
|
+
for (const part of parts) {
|
|
4643
|
+
const modifier = MODIFIERS[part.toLowerCase()];
|
|
4644
|
+
if (modifier !== undefined) bits |= modifier;
|
|
4645
|
+
else if (part) key = part;
|
|
4646
|
+
}
|
|
4647
|
+
const lower = key.toLowerCase();
|
|
4648
|
+
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];
|
|
4649
|
+
if (named) return "n" + named + "," + bits;
|
|
4650
|
+
if (/^f([1-9]|1[0-9]|2[0-4])$/.test(lower)) return "nF" + lower.slice(1) + "," + bits;
|
|
4651
|
+
if (lower === "plus") return "c+," + bits;
|
|
4652
|
+
if (lower === "space") return "c ," + bits;
|
|
4653
|
+
if ([...key].length === 1) return "c" + lower + "," + bits;
|
|
4654
|
+
return "," + bits;
|
|
4655
|
+
}
|
|
4656
|
+
|
|
4657
|
+
// `items` as the host's menu lines, with their callbacks kept under `owner`.
|
|
4658
|
+
function packMenu(items, lines, owner) {
|
|
4089
4659
|
for (const item of items) {
|
|
4660
|
+
if (!item || item.visible === false) continue;
|
|
4661
|
+
const role = String(item.role ?? "").toLowerCase();
|
|
4090
4662
|
if (item.type === "separator") lines.push("S");
|
|
4091
|
-
else if (item.submenu) {
|
|
4663
|
+
else if (MENU_ROLES[role] && !item.submenu) {
|
|
4664
|
+
lines.push("B" + String(item.label ?? role.replace(/menu$/, "").replace(/^./, (c) => c.toUpperCase())).replace(/\n/g, " "));
|
|
4665
|
+
packMenu(MENU_ROLES[role](), lines, owner);
|
|
4666
|
+
lines.push("E");
|
|
4667
|
+
} else if (item.submenu) {
|
|
4092
4668
|
lines.push("B" + String(item.label ?? "").replace(/\n/g, " "));
|
|
4093
|
-
packMenu(item.submenu, lines);
|
|
4669
|
+
packMenu(item.submenu, lines, owner);
|
|
4094
4670
|
lines.push("E");
|
|
4671
|
+
} else if (SYSTEM_ROLES[role] !== undefined && !item.click) {
|
|
4672
|
+
lines.push("R" + SYSTEM_ROLES[role]);
|
|
4095
4673
|
} else {
|
|
4096
|
-
const
|
|
4097
|
-
|
|
4098
|
-
const
|
|
4099
|
-
|
|
4674
|
+
const known = SCRIPT_ROLES[role] ?? {};
|
|
4675
|
+
const action = ++nextMenuAction;
|
|
4676
|
+
const click = item.click ?? known.click;
|
|
4677
|
+
menuActions.set(action, typeof click === "function" ? () => click(item) : () => {});
|
|
4678
|
+
menuOwners[owner].push(action);
|
|
4679
|
+
const label = String(item.label ?? known.label ?? "").replace(/\n/g, " ");
|
|
4680
|
+
lines.push("A" + action + "," + (item.enabled === false ? 0 : 1) + "," + (item.checked ? 1 : 0) + "," + packAccelerator(item.accelerator ?? known.accelerator) + "," + label);
|
|
4100
4681
|
}
|
|
4101
4682
|
}
|
|
4102
4683
|
}
|
|
4103
4684
|
|
|
4685
|
+
function dropMenu(owner) {
|
|
4686
|
+
for (const action of menuOwners[owner]) menuActions.delete(action);
|
|
4687
|
+
menuOwners[owner] = [];
|
|
4688
|
+
}
|
|
4689
|
+
|
|
4104
4690
|
/**
|
|
4105
4691
|
* Shows an icon in the system tray (the macOS menu bar, the Windows notification area, a
|
|
4106
4692
|
* StatusNotifierItem on Linux). `icon` is RGBA pixels, as an `ImageData`: `{ width, height,
|
|
@@ -4113,17 +4699,17 @@ export function setTray({ icon, tooltip = "", template = false, menu = [], onCli
|
|
|
4113
4699
|
if (!icon || !(icon.width > 0) || !(icon.height > 0) || icon.data?.length !== icon.width * icon.height * 4) {
|
|
4114
4700
|
throw new TypeError("setTray needs an icon of RGBA pixels: { width, height, data }");
|
|
4115
4701
|
}
|
|
4116
|
-
|
|
4702
|
+
dropMenu("tray");
|
|
4117
4703
|
trayClick = typeof onClick === "function" ? onClick : null;
|
|
4118
4704
|
const lines = [];
|
|
4119
|
-
packMenu(menu, lines);
|
|
4705
|
+
packMenu(menu, lines, "tray");
|
|
4120
4706
|
const fields = [String(tooltip), icon.width, icon.height, template ? 1 : 0, hex(icon.data), lines.join("\n")];
|
|
4121
4707
|
return shellCall(1, fields).then((shown) => shown === 1);
|
|
4122
4708
|
}
|
|
4123
4709
|
|
|
4124
4710
|
/** Takes the tray icon away. */
|
|
4125
4711
|
export function removeTray() {
|
|
4126
|
-
|
|
4712
|
+
dropMenu("tray");
|
|
4127
4713
|
trayClick = null;
|
|
4128
4714
|
shellCall(2, []);
|
|
4129
4715
|
}
|
|
@@ -4173,7 +4759,315 @@ export function registerShortcut(accelerator, callback) {
|
|
|
4173
4759
|
return shellCall(3, [id, code, bits]).then((held) => held === 1);
|
|
4174
4760
|
}
|
|
4175
4761
|
|
|
4762
|
+
// Web views: a real browser page (WKWebView on macOS) shown over a node, which a person and
|
|
4763
|
+
// an agent can both use. The views live on the platform thread; calls go through `__ui.shell`
|
|
4764
|
+
// (ops 10 to 14) and their events come back through `__ui.shellEvent` kind 20, with the view,
|
|
4765
|
+
// an event code and the fields separated by U+001F (ui-webview's wire.silk).
|
|
4766
|
+
|
|
4767
|
+
const WEB_VIEW_EVENT = 20;
|
|
4768
|
+
const webViews = new Map();
|
|
4769
|
+
let nextWebView = 0;
|
|
4770
|
+
let nextWebRequest = 0;
|
|
4771
|
+
const webRequests = new Map();
|
|
4772
|
+
const dataClears = new Map();
|
|
4773
|
+
|
|
4774
|
+
const thousandths = (value) => String(Math.round(Number(value) * 1000));
|
|
4775
|
+
|
|
4776
|
+
function webRequest(resolve, reject) {
|
|
4777
|
+
const request = ++nextWebRequest;
|
|
4778
|
+
webRequests.set(request, { resolve, reject });
|
|
4779
|
+
return request;
|
|
4780
|
+
}
|
|
4781
|
+
|
|
4782
|
+
function settleWebRequest(request, ok, value, error) {
|
|
4783
|
+
const waiting = webRequests.get(request);
|
|
4784
|
+
if (!waiting) return;
|
|
4785
|
+
webRequests.delete(request);
|
|
4786
|
+
if (ok) waiting.resolve(value);
|
|
4787
|
+
else waiting.reject(error instanceof Error ? error : new Error(String(error)));
|
|
4788
|
+
}
|
|
4789
|
+
|
|
4790
|
+
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
4791
|
+
const BASE64_VALUES = new Uint8Array(128);
|
|
4792
|
+
for (let i = 0; i < BASE64.length; i++) BASE64_VALUES[BASE64.charCodeAt(i)] = i;
|
|
4793
|
+
|
|
4794
|
+
function decodeBase64(text) {
|
|
4795
|
+
const clean = text.replace(/=+$/, "");
|
|
4796
|
+
const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
|
|
4797
|
+
let bits = 0;
|
|
4798
|
+
let count = 0;
|
|
4799
|
+
let at = 0;
|
|
4800
|
+
for (let i = 0; i < clean.length; i++) {
|
|
4801
|
+
bits = (bits << 6) | BASE64_VALUES[clean.charCodeAt(i)];
|
|
4802
|
+
count += 6;
|
|
4803
|
+
if (count >= 8) {
|
|
4804
|
+
count -= 8;
|
|
4805
|
+
out[at++] = (bits >> count) & 255;
|
|
4806
|
+
}
|
|
4807
|
+
}
|
|
4808
|
+
return out;
|
|
4809
|
+
}
|
|
4810
|
+
|
|
4811
|
+
const CONSOLE_LEVELS = ["debug", "log", "info", "warning", "error"];
|
|
4812
|
+
|
|
4813
|
+
/** An event of a {@link WebView}: its `type` and the fields of what happened. */
|
|
4814
|
+
export class WebViewEvent {
|
|
4815
|
+
constructor(type, fields) {
|
|
4816
|
+
this.type = type;
|
|
4817
|
+
Object.assign(this, fields);
|
|
4818
|
+
}
|
|
4819
|
+
}
|
|
4820
|
+
|
|
4821
|
+
/**
|
|
4822
|
+
* A web view: a real browser page shown over a node. The page draws over the node's box
|
|
4823
|
+
* (a native view of the system's engine), follows it as layout moves it, and hides when the
|
|
4824
|
+
* node is not shown. Make one with {@link createWebView}.
|
|
4825
|
+
*
|
|
4826
|
+
* The view keeps the page's state as it reports it: `url`, `title`, `favicon`, `loading`,
|
|
4827
|
+
* `progress`, `canGoBack`, `canGoForward`, `focused`. Listen with `addEventListener(type,
|
|
4828
|
+
* listener)` for `loadstart`, `loadprogress`, `loadend` (`ok`, `error`, `errorCode`, a Chromium net error), `urlchange`,
|
|
4829
|
+
* `titlechange`, `faviconchange`, `historychange`, `navigationrequest` (answer it with
|
|
4830
|
+
* `answerNavigation`), `newwindow`, `focuschange`, `console` (`level`, `message`),
|
|
4831
|
+
* `unsupported` (`command`), `crashed` and `closed`.
|
|
4832
|
+
*/
|
|
4833
|
+
export class WebView {
|
|
4834
|
+
#listeners = new Map();
|
|
4835
|
+
#closed = false;
|
|
4836
|
+
|
|
4837
|
+
constructor(node, options) {
|
|
4838
|
+
this.id = ++nextWebView;
|
|
4839
|
+
this.node = node;
|
|
4840
|
+
this.url = options.url ?? "";
|
|
4841
|
+
this.title = "";
|
|
4842
|
+
this.favicon = "";
|
|
4843
|
+
this.loading = false;
|
|
4844
|
+
this.progress = 0;
|
|
4845
|
+
this.canGoBack = false;
|
|
4846
|
+
this.canGoForward = false;
|
|
4847
|
+
this.focused = false;
|
|
4848
|
+
webViews.set(this.id, this);
|
|
4849
|
+
const flags = (options.inspectable === false ? 0 : 1) | (options.askBeforeNavigating ? 2 : 0) | (options.transparent ? 4 : 0);
|
|
4850
|
+
/** Resolves to whether the view opened: there are web views only in a desktop window. */
|
|
4851
|
+
this.opened = shellCall(40, [this.id, node.nodeId, this.url, options.profile ?? "", flags]).then((value) => {
|
|
4852
|
+
if (value !== 1) webViews.delete(this.id);
|
|
4853
|
+
return value === 1;
|
|
4854
|
+
});
|
|
4855
|
+
}
|
|
4856
|
+
|
|
4857
|
+
addEventListener(type, listener) {
|
|
4858
|
+
let list = this.#listeners.get(type);
|
|
4859
|
+
if (!list) this.#listeners.set(type, (list = new Set()));
|
|
4860
|
+
list.add(listener);
|
|
4861
|
+
}
|
|
4862
|
+
|
|
4863
|
+
removeEventListener(type, listener) {
|
|
4864
|
+
this.#listeners.get(type)?.delete(listener);
|
|
4865
|
+
}
|
|
4866
|
+
|
|
4867
|
+
_fire(type, fields = {}) {
|
|
4868
|
+
const event = new WebViewEvent(type, fields);
|
|
4869
|
+
const handler = this["on" + type];
|
|
4870
|
+
if (typeof handler === "function") handler.call(this, event);
|
|
4871
|
+
for (const listener of this.#listeners.get(type) ?? []) listener.call(this, event);
|
|
4872
|
+
}
|
|
4873
|
+
|
|
4874
|
+
#command(name, ...fields) {
|
|
4875
|
+
if (this.#closed) return;
|
|
4876
|
+
shellCall(42, [this.id, name, ...fields]);
|
|
4877
|
+
}
|
|
4878
|
+
|
|
4879
|
+
#ask(name, ...fields) {
|
|
4880
|
+
if (this.#closed) return Promise.reject(new Error("the web view is closed"));
|
|
4881
|
+
return new Promise((resolve, reject) => {
|
|
4882
|
+
const request = webRequest(resolve, reject);
|
|
4883
|
+
this.#command(name, request, ...fields);
|
|
4884
|
+
});
|
|
4885
|
+
}
|
|
4886
|
+
|
|
4887
|
+
navigate(url) { this.url = String(url); this.#command("navigate", this.url); }
|
|
4888
|
+
/** Shows `html` as if loaded from `baseUrl`. */
|
|
4889
|
+
loadHtml(html, baseUrl = "") { this.#command("loadHtml", baseUrl, html); }
|
|
4890
|
+
back() { this.#command("back"); }
|
|
4891
|
+
forward() { this.#command("forward"); }
|
|
4892
|
+
reload() { this.#command("reload"); }
|
|
4893
|
+
/** Reloads bypassing the cache. */
|
|
4894
|
+
hardReload() { this.#command("hardReload"); }
|
|
4895
|
+
stop() { this.#command("stop"); }
|
|
4896
|
+
/** Page zoom, 1 for 100%. */
|
|
4897
|
+
setZoom(factor) { this.#command("zoom", thousandths(factor)); }
|
|
4898
|
+
/** Gives the page keyboard focus. */
|
|
4899
|
+
focus() { this.#command("focus"); }
|
|
4900
|
+
/** Opens the engine's developer tools (Web Inspector on macOS). */
|
|
4901
|
+
openDevTools() { this.#command("devtools"); }
|
|
4902
|
+
setAudioMuted(muted) { this.#command("mute", muted ? 1 : 0); }
|
|
4903
|
+
/** The color scheme the page sees: `"system"`, `"light"` or `"dark"`. */
|
|
4904
|
+
setColorScheme(scheme) { this.#command("scheme", scheme === "light" || scheme === "dark" ? scheme : "system"); }
|
|
4905
|
+
/** Shows or hides the view; a hidden view keeps its page. */
|
|
4906
|
+
setShown(shown) { if (!this.#closed) shellCall(44, [this.id, shown ? 1 : 0]); }
|
|
4907
|
+
|
|
4908
|
+
/** Runs `script` in the page; resolves to its value (a promise is awaited), JSON-cloned. */
|
|
4909
|
+
evaluate(script) {
|
|
4910
|
+
return this.#ask("evaluate", String(script)).then((json) => (json === "" ? undefined : JSON.parse(json)));
|
|
4911
|
+
}
|
|
4912
|
+
|
|
4913
|
+
/** A text outline of what the page shows, with refs (`[ref=e12]`) on what an agent can act on. */
|
|
4914
|
+
snapshot() { return this.#ask("snapshot"); }
|
|
4915
|
+
|
|
4916
|
+
/** The page's pixels: `{ width, height, data }`, RGBA rows top first, in device pixels. */
|
|
4917
|
+
screenshot() { return this.#ask("screenshot"); }
|
|
4918
|
+
|
|
4919
|
+
/** Scrolls element `ref` (a snapshot ref) into view and clicks it with real input. */
|
|
4920
|
+
clickElement(ref) { return this.#ask("click", String(ref)); }
|
|
4921
|
+
|
|
4922
|
+
/** Focuses element `ref`, selects its value and types `text` over it with real input. */
|
|
4923
|
+
fillElement(ref, text) { return this.#ask("fill", String(ref), String(text)); }
|
|
4924
|
+
|
|
4925
|
+
/** A click at a point of the page's viewport, in CSS pixels. */
|
|
4926
|
+
clickAt(x, y, { button = 0, clickCount = 1, modifiers = 0 } = {}) {
|
|
4927
|
+
this.#command("clickAt", thousandths(x), thousandths(y), button, clickCount, modifiers);
|
|
4928
|
+
}
|
|
4929
|
+
|
|
4930
|
+
movePointer(x, y, { modifiers = 0 } = {}) { this.#command("move", thousandths(x), thousandths(y), modifiers); }
|
|
4931
|
+
|
|
4932
|
+
/** A wheel turn over a point, deltas in CSS pixels. */
|
|
4933
|
+
scroll(x, y, deltaX, deltaY, { modifiers = 0 } = {}) {
|
|
4934
|
+
this.#command("scroll", thousandths(x), thousandths(y), thousandths(deltaX), thousandths(deltaY), modifiers);
|
|
4935
|
+
}
|
|
4936
|
+
|
|
4937
|
+
/** Types `text` into whatever has focus in the page. */
|
|
4938
|
+
typeText(text) { this.#command("type", String(text)); }
|
|
4939
|
+
|
|
4940
|
+
/** Presses one key, by its DOM `key` value (`"Enter"`, `"a"`); modifiers shift 1, control 2, alt 4, meta 8. */
|
|
4941
|
+
pressKey(key, modifiers = 0) { this.#command("key", modifiers, String(key)); }
|
|
4942
|
+
|
|
4943
|
+
/** Answers a `navigationrequest` event. */
|
|
4944
|
+
answerNavigation(request, allow) { this.#command("answer", request, allow ? 1 : 0); }
|
|
4945
|
+
|
|
4946
|
+
/**
|
|
4947
|
+
* Finds `text` in the page (case insensitive) and highlights the next match, or the previous
|
|
4948
|
+
* one when `forward` is false; resolves to `{ matches, activeMatchOrdinal }`.
|
|
4949
|
+
*/
|
|
4950
|
+
findInPage(text, { forward = true, newSession = false } = {}) {
|
|
4951
|
+
return this.#ask("find", forward ? 1 : 0, newSession ? 1 : 0, String(text));
|
|
4952
|
+
}
|
|
4953
|
+
|
|
4954
|
+
stopFindInPage() { this.#command("stopFind"); }
|
|
4955
|
+
|
|
4956
|
+
/** Closes the view; its page goes. */
|
|
4957
|
+
close() {
|
|
4958
|
+
if (this.#closed) return;
|
|
4959
|
+
this.#closed = true;
|
|
4960
|
+
shellCall(41, [this.id]);
|
|
4961
|
+
}
|
|
4962
|
+
}
|
|
4963
|
+
|
|
4964
|
+
/**
|
|
4965
|
+
* Shows a web view over `node` (any node: the page covers its border box). Options: `url`,
|
|
4966
|
+
* `profile` (a name keeps cookies and storage between runs; empty forgets them),
|
|
4967
|
+
* `inspectable` (default true), `askBeforeNavigating`, `transparent`.
|
|
4968
|
+
*/
|
|
4969
|
+
export function createWebView(node, options = {}) {
|
|
4970
|
+
return new WebView(node, options);
|
|
4971
|
+
}
|
|
4972
|
+
|
|
4973
|
+
/**
|
|
4974
|
+
* Clears what the pages of profile `profile` stored (an empty name: the views opened without
|
|
4975
|
+
* one): `cookies` (cookies and site storage) and `cache`.
|
|
4976
|
+
*/
|
|
4977
|
+
export function clearWebViewData({ profile = "", cookies = true, cache = true } = {}) {
|
|
4978
|
+
return new Promise((resolve) => {
|
|
4979
|
+
const request = ++nextWebRequest;
|
|
4980
|
+
dataClears.set(request, resolve);
|
|
4981
|
+
shellCall(43, [request, cookies ? 1 : 0, cache ? 1 : 0, profile]);
|
|
4982
|
+
});
|
|
4983
|
+
}
|
|
4984
|
+
|
|
4985
|
+
function webViewEvent(id, code, text) {
|
|
4986
|
+
const parts = text === "" ? [] : text.split("\x1f");
|
|
4987
|
+
// The last field of each event may hold the separator itself.
|
|
4988
|
+
const rest = (from) => parts.slice(from).join("\x1f");
|
|
4989
|
+
if (code === 21) {
|
|
4990
|
+
const request = Number(parts[0]);
|
|
4991
|
+
const resolve = dataClears.get(request);
|
|
4992
|
+
dataClears.delete(request);
|
|
4993
|
+
resolve?.();
|
|
4994
|
+
return;
|
|
4995
|
+
}
|
|
4996
|
+
const view = webViews.get(id);
|
|
4997
|
+
if (!view) return;
|
|
4998
|
+
switch (code) {
|
|
4999
|
+
case 1: view._fire("created"); break;
|
|
5000
|
+
case 2:
|
|
5001
|
+
webViews.delete(id);
|
|
5002
|
+
view._fire("closed");
|
|
5003
|
+
break;
|
|
5004
|
+
case 3:
|
|
5005
|
+
view.loading = true;
|
|
5006
|
+
view._fire("loadstart", { url: rest(0) });
|
|
5007
|
+
break;
|
|
5008
|
+
case 4:
|
|
5009
|
+
view.progress = Number(parts[0]) / 1000;
|
|
5010
|
+
view._fire("loadprogress", { progress: view.progress });
|
|
5011
|
+
break;
|
|
5012
|
+
case 5:
|
|
5013
|
+
view.loading = false;
|
|
5014
|
+
view._fire("loadend", { ok: parts[0] === "1", errorCode: -Number(parts[1] ?? 0), url: parts[2] ?? "", error: rest(3) });
|
|
5015
|
+
break;
|
|
5016
|
+
case 6:
|
|
5017
|
+
view.url = rest(0);
|
|
5018
|
+
view._fire("urlchange", { url: view.url });
|
|
5019
|
+
break;
|
|
5020
|
+
case 7:
|
|
5021
|
+
view.title = rest(0);
|
|
5022
|
+
view._fire("titlechange", { title: view.title });
|
|
5023
|
+
break;
|
|
5024
|
+
case 8:
|
|
5025
|
+
view.canGoBack = parts[0] === "1";
|
|
5026
|
+
view.canGoForward = parts[1] === "1";
|
|
5027
|
+
view._fire("historychange", { canGoBack: view.canGoBack, canGoForward: view.canGoForward });
|
|
5028
|
+
break;
|
|
5029
|
+
case 9:
|
|
5030
|
+
view._fire("navigationrequest", { request: Number(parts[0]), userInitiated: parts[1] === "1", url: rest(2) });
|
|
5031
|
+
break;
|
|
5032
|
+
case 10: view._fire("newwindow", { url: rest(0) }); break;
|
|
5033
|
+
case 11:
|
|
5034
|
+
view.focused = parts[0] === "1";
|
|
5035
|
+
view._fire("focuschange", { focused: view.focused });
|
|
5036
|
+
break;
|
|
5037
|
+
case 12: settleWebRequest(Number(parts[0]), parts[1] === "1", rest(2), rest(2)); break;
|
|
5038
|
+
case 13: settleWebRequest(Number(parts[0]), true, rest(1)); break;
|
|
5039
|
+
case 14:
|
|
5040
|
+
settleWebRequest(Number(parts[0]), true, {
|
|
5041
|
+
width: Number(parts[1]),
|
|
5042
|
+
height: Number(parts[2]),
|
|
5043
|
+
data: decodeBase64(parts[3] ?? ""),
|
|
5044
|
+
});
|
|
5045
|
+
break;
|
|
5046
|
+
case 15: settleWebRequest(Number(parts[0]), parts[1] === "1", undefined, rest(2) || "the action failed"); break;
|
|
5047
|
+
case 16: view._fire("console", { level: CONSOLE_LEVELS[Number(parts[0])] ?? "log", message: rest(1) }); break;
|
|
5048
|
+
case 17: {
|
|
5049
|
+
const command = rest(1);
|
|
5050
|
+
if (Number(parts[0])) settleWebRequest(Number(parts[0]), false, undefined, command + " is not supported here");
|
|
5051
|
+
view._fire("unsupported", { command });
|
|
5052
|
+
break;
|
|
5053
|
+
}
|
|
5054
|
+
case 18: view._fire("crashed", { reason: rest(0) }); break;
|
|
5055
|
+
case 19:
|
|
5056
|
+
view.favicon = rest(0);
|
|
5057
|
+
view._fire("faviconchange", { url: view.favicon });
|
|
5058
|
+
break;
|
|
5059
|
+
case 20:
|
|
5060
|
+
settleWebRequest(Number(parts[0]), true, { matches: Number(parts[1]), activeMatchOrdinal: Number(parts[2]) });
|
|
5061
|
+
break;
|
|
5062
|
+
}
|
|
5063
|
+
}
|
|
5064
|
+
|
|
4176
5065
|
/** Stops the shortcut of `accelerator`. */
|
|
5066
|
+
/** Ends the app with an exit code once the current turn finishes. */
|
|
5067
|
+
export function quit(code = 0) {
|
|
5068
|
+
shellCall(45, [String(code)]);
|
|
5069
|
+
}
|
|
5070
|
+
|
|
4177
5071
|
export function unregisterShortcut(accelerator) {
|
|
4178
5072
|
const { code, bits } = parseShortcut(accelerator);
|
|
4179
5073
|
const id = shortcutIds.get(code + "+" + bits);
|
|
@@ -4183,6 +5077,226 @@ export function unregisterShortcut(accelerator) {
|
|
|
4183
5077
|
shellCall(4, [id]);
|
|
4184
5078
|
}
|
|
4185
5079
|
|
|
5080
|
+
// File dialogs waiting for `DialogClosed`, by dialog id.
|
|
5081
|
+
const dialogs = new Map();
|
|
5082
|
+
|
|
5083
|
+
function extensionsOf(filters) {
|
|
5084
|
+
const all = [];
|
|
5085
|
+
for (const filter of filters ?? []) {
|
|
5086
|
+
for (const extension of filter.extensions ?? []) {
|
|
5087
|
+
if (extension === "*") return "";
|
|
5088
|
+
all.push(String(extension).replace(/^\./, ""));
|
|
5089
|
+
}
|
|
5090
|
+
}
|
|
5091
|
+
return all.join(",");
|
|
5092
|
+
}
|
|
5093
|
+
|
|
5094
|
+
function dialog(op, fields) {
|
|
5095
|
+
return shellCall(op, fields).then((id) => (id ? new Promise((resolve) => dialogs.set(id, resolve)) : []));
|
|
5096
|
+
}
|
|
5097
|
+
|
|
5098
|
+
/**
|
|
5099
|
+
* Opens the system's file dialog, as Electron's `dialog.showOpenDialog`: `properties` takes
|
|
5100
|
+
* `openFile`, `openDirectory` and `multiSelections`; `filters` are `{ name, extensions }`
|
|
5101
|
+
* without dots (`"*"` for every file). It attaches to the window as a sheet on macOS and never
|
|
5102
|
+
* blocks. Resolves to `{ canceled, filePaths }`.
|
|
5103
|
+
*/
|
|
5104
|
+
export function showOpenDialog(options = {}) {
|
|
5105
|
+
const properties = options.properties ?? ["openFile"];
|
|
5106
|
+
const directories = properties.includes("openDirectory");
|
|
5107
|
+
const files = properties.includes("openFile") || !directories;
|
|
5108
|
+
const flags = (files ? 1 : 0) | (directories ? 2 : 0) | (properties.includes("multiSelections") ? 4 : 0);
|
|
5109
|
+
return dialog(5, [String(options.title ?? ""), String(options.defaultPath ?? ""), flags, extensionsOf(options.filters)]).then(
|
|
5110
|
+
(filePaths) => ({ canceled: filePaths.length === 0, filePaths }),
|
|
5111
|
+
);
|
|
5112
|
+
}
|
|
5113
|
+
|
|
5114
|
+
/**
|
|
5115
|
+
* Opens the system's save dialog, as Electron's `dialog.showSaveDialog`. `defaultPath` may
|
|
5116
|
+
* name a folder, a file, or both. Resolves to `{ canceled, filePath }`.
|
|
5117
|
+
*/
|
|
5118
|
+
export function showSaveDialog(options = {}) {
|
|
5119
|
+
const path = String(options.defaultPath ?? "");
|
|
5120
|
+
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
|
|
5121
|
+
const looksLikeFolder = slash === path.length - 1 || !/\.[^./\\]+$/.test(path.slice(slash + 1));
|
|
5122
|
+
const directory = looksLikeFolder ? path : path.slice(0, Math.max(slash, 0));
|
|
5123
|
+
const name = looksLikeFolder ? "" : path.slice(slash + 1);
|
|
5124
|
+
return dialog(6, [String(options.title ?? ""), directory, name, extensionsOf(options.filters)]).then((paths) => ({
|
|
5125
|
+
canceled: paths.length === 0,
|
|
5126
|
+
filePath: paths[0] ?? "",
|
|
5127
|
+
}));
|
|
5128
|
+
}
|
|
5129
|
+
|
|
5130
|
+
/**
|
|
5131
|
+
* Replaces the app's menu bar, as Electron's `Menu.setApplicationMenu(Menu.buildFromTemplate(t))`.
|
|
5132
|
+
* Items are `{ label, click, accelerator, enabled, checked, type, role, submenu, visible }`.
|
|
5133
|
+
* `accelerator` is `"Mod+Shift+K"` (`Mod`, `CmdOrCtrl`: Command on macOS, Control elsewhere).
|
|
5134
|
+
* The system roles (`about`, `quit`, `undo`, `copy`, `togglefullscreen`, `minimize`, `front`
|
|
5135
|
+
* and so on) are the system's own items; `zoomIn`, `zoomOut` and `resetZoom` zoom the page;
|
|
5136
|
+
* `appMenu`, `fileMenu`, `editMenu`, `viewMenu` and `windowMenu` are whole menus. On macOS
|
|
5137
|
+
* the first menu is the app menu. Edit shortcuts reach the focused node as keys first.
|
|
5138
|
+
*/
|
|
5139
|
+
export function setApplicationMenu(template) {
|
|
5140
|
+
dropMenu("app");
|
|
5141
|
+
const lines = [];
|
|
5142
|
+
packMenu(template ?? [], lines, "app");
|
|
5143
|
+
return shellCall(7, [lines.join("\n")]).then(() => undefined);
|
|
5144
|
+
}
|
|
5145
|
+
|
|
5146
|
+
let contextMenuClosed = null;
|
|
5147
|
+
|
|
5148
|
+
function closeContextMenu() {
|
|
5149
|
+
dropMenu("context");
|
|
5150
|
+
const closed = contextMenuClosed;
|
|
5151
|
+
contextMenuClosed = null;
|
|
5152
|
+
closed?.();
|
|
5153
|
+
}
|
|
5154
|
+
|
|
5155
|
+
/**
|
|
5156
|
+
* Opens a native context menu at `x`, `y` (CSS pixels in the window, a `MouseEvent`'s
|
|
5157
|
+
* `clientX`/`clientY`), as Electron's `menu.popup()`. Items are as `setApplicationMenu`'s.
|
|
5158
|
+
* Resolves when the menu closes, with or without a choice, to `true`; or at once to `false`
|
|
5159
|
+
* when the system draws no context menus (Linux, the browser) and the app should draw its own.
|
|
5160
|
+
*/
|
|
5161
|
+
export function showContextMenu(template, { x = 0, y = 0 } = {}) {
|
|
5162
|
+
closeContextMenu();
|
|
5163
|
+
const lines = [];
|
|
5164
|
+
packMenu(template ?? [], lines, "context");
|
|
5165
|
+
const zoom = appWindow.zoomFactor || 1;
|
|
5166
|
+
return shellCall(8, [x * zoom, y * zoom, lines.join("\n")]).then((shown) => {
|
|
5167
|
+
if (shown !== 1) {
|
|
5168
|
+
dropMenu("context");
|
|
5169
|
+
return false;
|
|
5170
|
+
}
|
|
5171
|
+
return new Promise((resolve) => (contextMenuClosed = () => resolve(true)));
|
|
5172
|
+
});
|
|
5173
|
+
}
|
|
5174
|
+
|
|
5175
|
+
/** Puts `text` on the app's dock or taskbar icon (an unread count); `""` takes it off. */
|
|
5176
|
+
export function setBadge(text) {
|
|
5177
|
+
return shellCall(9, [String(text ?? "")]).then((shown) => shown === 1);
|
|
5178
|
+
}
|
|
5179
|
+
|
|
5180
|
+
/** Shows progress from 0 to 1 on the app's dock or taskbar icon; a negative number takes it off. */
|
|
5181
|
+
export function setProgress(fraction) {
|
|
5182
|
+
return shellCall(10, [Number(fraction)]).then((shown) => shown === 1);
|
|
5183
|
+
}
|
|
5184
|
+
|
|
5185
|
+
/** Opens `url` with the system's handler: a web page in the default browser, `mailto:` in the mail app. */
|
|
5186
|
+
export function openExternal(url) {
|
|
5187
|
+
return shellCall(11, [String(url)]).then((opened) => opened === 1);
|
|
5188
|
+
}
|
|
5189
|
+
|
|
5190
|
+
/** Shows the file or folder at `path` selected in Finder, Explorer or the file manager. */
|
|
5191
|
+
export function showItemInFolder(path) {
|
|
5192
|
+
return shellCall(12, [String(path)]).then((shown) => shown === 1);
|
|
5193
|
+
}
|
|
5194
|
+
|
|
5195
|
+
/**
|
|
5196
|
+
* Drags the files at `paths` out of the window, as Electron's `webContents.startDrag`, so
|
|
5197
|
+
* Finder, a mail draft or a terminal can take them. Call it from a `pointerdown` or
|
|
5198
|
+
* `pointermove` listener while the button is down. Resolves to whether the drag started
|
|
5199
|
+
* (macOS and Windows drag files out; Linux and the browser do not).
|
|
5200
|
+
*/
|
|
5201
|
+
export function startFileDrag(paths) {
|
|
5202
|
+
const list = (Array.isArray(paths) ? paths : [paths]).map(String).filter(Boolean);
|
|
5203
|
+
return shellCall(13, [list.join("\n")]).then((started) => started === 1);
|
|
5204
|
+
}
|
|
5205
|
+
|
|
5206
|
+
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];
|
|
5207
|
+
|
|
5208
|
+
function zoomStep(direction) {
|
|
5209
|
+
const now = appWindow.zoomFactor;
|
|
5210
|
+
if (direction > 0) return ZOOM_STEPS.find((step) => step > now + 0.001) ?? now;
|
|
5211
|
+
return ZOOM_STEPS.findLast((step) => step < now - 0.001) ?? now;
|
|
5212
|
+
}
|
|
5213
|
+
|
|
5214
|
+
/**
|
|
5215
|
+
* The window the app runs in. `fullScreen` and `zoomFactor` (the page zoom, as Electron's
|
|
5216
|
+
* `webFrame.getZoomFactor()`; Mod with `=`, `-` and `0` change it too) are current, and
|
|
5217
|
+
* `fullscreenchange` and `zoomchange` say when they change. The title bar is the app's
|
|
5218
|
+
* configuration: a transparent one, with the window controls placed in it, comes from
|
|
5219
|
+
* `TitleBar.transparent` in its `tasks.silk`.
|
|
5220
|
+
*/
|
|
5221
|
+
class AppWindow {
|
|
5222
|
+
fullScreen = false;
|
|
5223
|
+
zoomFactor = 1;
|
|
5224
|
+
#listeners = new Map();
|
|
5225
|
+
|
|
5226
|
+
setFullScreen(on) {
|
|
5227
|
+
if (!!on !== this.fullScreen) shellCall(14, [0]);
|
|
5228
|
+
}
|
|
5229
|
+
|
|
5230
|
+
toggleFullScreen() {
|
|
5231
|
+
shellCall(14, [0]);
|
|
5232
|
+
}
|
|
5233
|
+
|
|
5234
|
+
minimize() {
|
|
5235
|
+
shellCall(14, [1]);
|
|
5236
|
+
}
|
|
5237
|
+
|
|
5238
|
+
/** Shows the window and brings it to the front with keyboard focus. */
|
|
5239
|
+
focus() {
|
|
5240
|
+
shellCall(14, [2]);
|
|
5241
|
+
}
|
|
5242
|
+
|
|
5243
|
+
show() {
|
|
5244
|
+
shellCall(14, [2]);
|
|
5245
|
+
}
|
|
5246
|
+
|
|
5247
|
+
hide() {
|
|
5248
|
+
shellCall(14, [3]);
|
|
5249
|
+
}
|
|
5250
|
+
|
|
5251
|
+
setTitle(title) {
|
|
5252
|
+
shellCall(14, [4, String(title)]);
|
|
5253
|
+
}
|
|
5254
|
+
|
|
5255
|
+
/** Zooms the page, from 0.25 to 5. Resolves to the zoom now. */
|
|
5256
|
+
setZoomFactor(zoom) {
|
|
5257
|
+
return shellCall(15, [Math.min(5, Math.max(0.25, Number(zoom) || 1))]).then((now) => {
|
|
5258
|
+
if (now !== this.zoomFactor) {
|
|
5259
|
+
this.zoomFactor = now;
|
|
5260
|
+
this._fire("zoomchange", { zoomFactor: now });
|
|
5261
|
+
}
|
|
5262
|
+
return now;
|
|
5263
|
+
});
|
|
5264
|
+
}
|
|
5265
|
+
|
|
5266
|
+
getZoomFactor() {
|
|
5267
|
+
return this.zoomFactor;
|
|
5268
|
+
}
|
|
5269
|
+
|
|
5270
|
+
isFullScreen() {
|
|
5271
|
+
return this.fullScreen;
|
|
5272
|
+
}
|
|
5273
|
+
|
|
5274
|
+
addEventListener(type, listener) {
|
|
5275
|
+
let list = this.#listeners.get(type);
|
|
5276
|
+
if (!list) this.#listeners.set(type, (list = []));
|
|
5277
|
+
if (!list.includes(listener)) list.push(listener);
|
|
5278
|
+
}
|
|
5279
|
+
|
|
5280
|
+
removeEventListener(type, listener) {
|
|
5281
|
+
const list = this.#listeners.get(type);
|
|
5282
|
+
const index = list ? list.indexOf(listener) : -1;
|
|
5283
|
+
if (index >= 0) list.splice(index, 1);
|
|
5284
|
+
}
|
|
5285
|
+
|
|
5286
|
+
_fire(type, detail) {
|
|
5287
|
+
const event = { type, target: this, ...detail };
|
|
5288
|
+
for (const listener of (this.#listeners.get(type) ?? []).slice()) {
|
|
5289
|
+
try {
|
|
5290
|
+
listener.call(this, event);
|
|
5291
|
+
} catch (error) {
|
|
5292
|
+
reportError(error);
|
|
5293
|
+
}
|
|
5294
|
+
}
|
|
5295
|
+
}
|
|
5296
|
+
}
|
|
5297
|
+
|
|
5298
|
+
export const appWindow = new AppWindow();
|
|
5299
|
+
|
|
4186
5300
|
/**
|
|
4187
5301
|
* The app's memory in bytes, as the system shows it to users: `phys_footprint` on macOS
|
|
4188
5302
|
* (Activity Monitor's "Memory"), `Pss` on Linux and `PrivateUsage` on Windows. `processes` is
|