@silkui/core 0.1.9 → 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
@@ -74,7 +74,19 @@ An `Svg` is one node whose markup its `SvgElement` and text children make, as an
74
74
  `fill`, `width` and every other attribute are markup, and React's spellings (`strokeWidth`)
75
75
  work too. Changes are drawn once, before the host applies the batch (`flushSvg()` draws them
76
76
  now). Without a CSS size it takes the `<svg>`'s `width` and `height`, else a square of the
77
- font size. Elements inside it hear no events: listen on the `Svg`.
77
+ font size. Listeners on its elements hear pointer events on their shapes, with
78
+ `pointerover`, `pointerout`, `pointerenter` and `pointerleave` as the pointer moves between
79
+ them; `pointer-events`, `visibility`, `display` and clip paths decide hits as on the web.
80
+ `getBBox()`, `getTotalLength()` and `getPointAtLength()` measure elements from their markup.
81
+
82
+ Once an `Svg` has drawn, later changes go to the tree element by element, and only the shapes
83
+ whose geometry changed rasterize again: a script can animate it every frame. Listeners on its
84
+ elements make it live from its first draw. The tree draws
85
+ `g`, `path`, `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`, `clipPath` and linear
86
+ and radial gradients this way; anything else (text, masks, filters, `use`...) puts the `Svg`
87
+ back to drawing its markup whole, which is right but slower. Browser libraries that build SVG
88
+ with `document`, such as lottie-web, run after `import "@silkui/core/globals"`, which adds a
89
+ minimal `window` and `document` where the realm has none.
78
90
 
79
91
  A node has `append`, `appendChild`, `insertBefore`, `removeChild`, `remove`, `contains`,
80
92
  `parentNode`, `childNodes`, `firstChild`, `lastChild` and the sibling getters, as in the DOM.
@@ -159,6 +171,42 @@ registerShortcut("Mod+Shift+B", build); // Mod is Command on macOS, Control else
159
171
  whichever app has focus; another app may hold it, and Wayland has none. `removeTray()` and
160
172
  `unregisterShortcut(accelerator)` undo them.
161
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
+
162
210
  `memoryUsage()` is the app's memory as the system shows it to users, to put next to an
163
211
  Electron app's in Activity Monitor or Task Manager. It is synchronous and allocates almost
164
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.9",
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",
@@ -12,6 +12,10 @@
12
12
  ".": {
13
13
  "types": "./src/index.d.ts",
14
14
  "default": "./src/index.js"
15
+ },
16
+ "./globals": {
17
+ "types": "./src/globals.d.ts",
18
+ "default": "./src/globals.js"
15
19
  }
16
20
  },
17
21
  "files": [
@@ -0,0 +1,3 @@
1
+ // Installs a minimal `window`, `navigator.userAgent` and `document` for browser libraries that
2
+ // build SVG with the DOM. It exports nothing.
3
+ export {};
package/src/globals.js ADDED
@@ -0,0 +1,38 @@
1
+ // A minimal `window` and `document` for libraries written for the browser that build SVG with
2
+ // the DOM, such as lottie-web. Import it before them; globals the realm has stay as they are.
3
+ import { createNode, createSvgElement, createText } from "./index.js";
4
+
5
+ const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
6
+ const KIND_OF_TAG = { div: "box", span: "box", p: "box", a: "box", img: "image", input: "input", svg: "svg" };
7
+
8
+ // A `<canvas>` here draws nothing: libraries such as lottie-web make one at load to probe.
9
+ const inert = new Proxy({}, { get: (target, name) => (name in target ? target[name] : () => {}) });
10
+
11
+ function createElement(tag) {
12
+ tag = String(tag).toLowerCase();
13
+ if (tag === "canvas") return { localName: tag, width: 300, height: 150, style: {}, getContext: () => inert };
14
+ const node = createNode(KIND_OF_TAG[tag] ?? "box");
15
+ node.localName ??= tag;
16
+ return node;
17
+ }
18
+
19
+ const none = () => [];
20
+
21
+ globalThis.window ??= globalThis;
22
+ if (typeof globalThis.navigator !== "object" || globalThis.navigator === null) globalThis.navigator = {};
23
+ if (globalThis.navigator.userAgent === undefined) {
24
+ Object.defineProperty(globalThis.navigator, "userAgent", { value: "SilkUI", enumerable: true, configurable: true });
25
+ }
26
+ globalThis.document ??= {
27
+ readyState: "complete",
28
+ createElement,
29
+ createElementNS: (namespace, tag) => (namespace === SVG_NAMESPACE ? createSvgElement(tag) : createElement(tag)),
30
+ createTextNode: (data) => createText(data),
31
+ getElementsByTagName: none,
32
+ getElementsByClassName: none,
33
+ querySelectorAll: none,
34
+ querySelector: () => null,
35
+ getElementById: () => null,
36
+ addEventListener() {},
37
+ removeEventListener() {},
38
+ };
package/src/index.d.ts CHANGED
@@ -368,6 +368,19 @@ export class Image extends Node {
368
368
  src: string;
369
369
  }
370
370
 
371
+ /**
372
+ * A canvas the application draws with WebGPU, as a `<canvas>`: `width` and `height` are the
373
+ * drawing's size in pixels and `getContext("webgpu")` gives its `GPUCanvasContext` (the types
374
+ * of `@webgpu/types` describe it). Drawing runs on a GPU device of the application's own.
375
+ */
376
+ export class Canvas extends Node {
377
+ constructor();
378
+ width: number;
379
+ height: number;
380
+ getContext(kind: "webgpu"): unknown | null;
381
+ getContext(kind: string): unknown | null;
382
+ }
383
+
371
384
  /** Text inside an `<svg>`. */
372
385
  export class SvgText {
373
386
  constructor(data?: string);
@@ -378,7 +391,10 @@ export class SvgText {
378
391
  destroy(): void;
379
392
  }
380
393
 
381
- /** An element inside an `<svg>` (`path`, `g`, `circle`...): markup its root draws, no node. */
394
+ /**
395
+ * An element inside an `<svg>` (`path`, `g`, `circle`...): markup its root draws, no node.
396
+ * Once the root has drawn, a change to its elements updates them one at a time.
397
+ */
382
398
  export class SvgElement {
383
399
  constructor(tag: string);
384
400
  readonly localName: string;
@@ -392,6 +408,26 @@ export class SvgElement {
392
408
  /** SVG's names, or React's spellings (`strokeWidth`, `xlinkHref`). */
393
409
  setAttribute(name: string, value: unknown): void;
394
410
  removeAttribute(name: string): void;
411
+ setAttributeNS(namespace: string | null, name: string, value: unknown): void;
412
+ getAttributeNS(namespace: string | null, name: string): string | null;
413
+ removeAttributeNS(namespace: string | null, name: string): void;
414
+ /** The `style` attribute as declarations: `element.style.display = "none"`. */
415
+ readonly style: Record<string, string>;
416
+ /**
417
+ * Hears pointer events (`click`, `pointerdown`, `pointerenter`...) on its shapes, as on the
418
+ * web; its `<svg>` turns live so the tree can tell which shape is under the pointer.
419
+ */
420
+ addEventListener<K extends keyof EventMap>(type: K, listener: Listener<EventMap[K]>, options?: ListenerOptions): void;
421
+ addEventListener(type: string, listener: (event: globalThis.Event) => void, options?: ListenerOptions): void;
422
+ removeEventListener<K extends keyof EventMap>(type: K, listener: Listener<EventMap[K]>, options?: ListenerOptions): void;
423
+ removeEventListener(type: string, listener: (event: globalThis.Event) => void, options?: ListenerOptions): void;
424
+ dispatchEvent(event: globalThis.Event): boolean;
425
+ /** The box of its geometry in its own user space: a shape's fill, a group's children. */
426
+ getBBox(): { x: number; y: number; width: number; height: number };
427
+ /** The length of a shape's outline in user units. */
428
+ getTotalLength(): number;
429
+ /** The point `distance` along a shape's outline, clamped to its ends. */
430
+ getPointAtLength(distance: number): { x: number; y: number };
395
431
  insertBefore<T extends SvgElement | SvgText | Text>(child: T, before?: SvgElement | SvgText | Text | null): T;
396
432
  appendChild<T extends SvgElement | SvgText | Text>(child: T): T;
397
433
  append(...children: (SvgElement | SvgText | Text | string)[]): void;
@@ -404,11 +440,16 @@ export class SvgElement {
404
440
  * An inline `<svg>`: one node drawing the markup its `SvgElement` children make, at its CSS
405
441
  * size (else its `width` and `height`, else a square of the font size), with its `color` as
406
442
  * `currentColor`. Class, look, events and ARIA are the node's; `viewBox`, `fill`, `width`
407
- * and the rest are markup.
443
+ * and the rest are markup. After its first draw, changes go to the tree element by element
444
+ * and only the shapes that changed redraw, so scripts can animate it (lottie-web and the like).
408
445
  */
409
446
  export class Svg extends Node {
410
447
  constructor();
411
448
  readonly outerHTML: string;
449
+ setAttributeNS(namespace: string | null, name: string, value: unknown): void;
450
+ getAttributeNS(namespace: string | null, name: string): string | null;
451
+ /** The box of what it draws, in its user space (inside `viewBox`). */
452
+ getBBox(): { x: number; y: number; width: number; height: number };
412
453
  textContent: string;
413
454
  }
414
455
 
@@ -541,6 +582,17 @@ export interface SelectionEvent<T extends Node = Input> extends Event {
541
582
  readonly selectionEnd: number;
542
583
  }
543
584
 
585
+ /** An edit about to change an input (`beforeinput`), as the web's `InputEvent`. Preventing it cancels the edit. */
586
+ export interface BeforeInputEvent<T extends Node = Input> extends Event {
587
+ readonly target: FieldOf<T>;
588
+ readonly inputType: string;
589
+ /** The text the edit inserts. */
590
+ readonly data: string | null;
591
+ readonly dataTransfer: DataTransfer | null;
592
+ readonly isComposing: boolean;
593
+ getTargetRanges(): never[];
594
+ }
595
+
544
596
  export interface ScrollEvent extends Event {
545
597
  readonly scrollLeft: number;
546
598
  readonly scrollTop: number;
@@ -592,6 +644,10 @@ export interface EventMap {
592
644
  blur: Event;
593
645
  input: InputEvent;
594
646
  selectionchange: SelectionEvent;
647
+ copy: ClipboardEvent;
648
+ cut: ClipboardEvent;
649
+ paste: ClipboardEvent;
650
+ beforeinput: BeforeInputEvent;
595
651
  scroll: ScrollEvent;
596
652
  layout: LayoutEvent;
597
653
  gotpointercapture: Event;
@@ -616,6 +672,7 @@ export function createNode(kind: "text"): Text;
616
672
  export function createNode(kind: "input"): Input;
617
673
  export function createNode(kind: "richinput"): RichInput;
618
674
  export function createNode(kind: "image" | "img"): Image;
675
+ export function createNode(kind: "canvas"): Canvas;
619
676
  export function createNode(kind: "svg"): Svg;
620
677
  export function createNode(kind: NodeKind): Node;
621
678
 
@@ -680,14 +737,58 @@ export class DroppedFile {
680
737
  readonly type: string;
681
738
  }
682
739
 
683
- /** What a file drag carries. `files` is filled in `drop`, as on the web. */
740
+ /** A file in a `DataTransfer` that is no file on disk, such as a pasted image: the runtime's `File`. */
741
+ export interface DataFile {
742
+ readonly name: string;
743
+ readonly type: string;
744
+ readonly size: number;
745
+ arrayBuffer(): Promise<ArrayBuffer>;
746
+ text(): Promise<string>;
747
+ }
748
+
749
+ /** One entry of a `DataTransfer`. */
750
+ export interface DataTransferItem {
751
+ readonly kind: "string" | "file";
752
+ readonly type: string;
753
+ getAsString(callback: (value: string) => void): void;
754
+ getAsFile(): DataFile | DroppedFile | null;
755
+ }
756
+
757
+ export interface DataTransferItemList extends Iterable<DataTransferItem> {
758
+ readonly length: number;
759
+ readonly [index: number]: DataTransferItem;
760
+ add(data: string, type: string): DataTransferItem;
761
+ add(file: DataFile | DroppedFile): DataTransferItem;
762
+ remove(index: number): void;
763
+ clear(): void;
764
+ }
765
+
766
+ /**
767
+ * What a copy, cut, paste or file drag carries, as the web's. `new DataTransfer()` is empty
768
+ * and writable; a paste's is read-only, and after its event none can be read.
769
+ */
684
770
  export class DataTransfer {
685
- readonly files: DroppedFile[];
686
- readonly items: { kind: "file"; type: string; getAsFile(): DroppedFile }[];
687
- readonly types: string[];
771
+ constructor();
772
+ readonly files: readonly (DataFile | DroppedFile)[];
773
+ readonly items: DataTransferItemList;
774
+ readonly types: readonly string[];
688
775
  dropEffect: string;
689
776
  effectAllowed: string;
690
777
  getData(format: string): string;
778
+ setData(format: string, data: string): void;
779
+ clearData(format?: string): void;
780
+ setDragImage(image: unknown, x: number, y: number): void;
781
+ }
782
+
783
+ /**
784
+ * A copy, cut or paste at the focused node, as the web's. A `copy` or `cut` listener that sets
785
+ * data on `clipboardData` and prevents the default puts that data on the clipboard; a `paste`
786
+ * listener reads what it holds (`text/plain`, `text/html`, a pasted PNG in `files`), and
787
+ * preventing it keeps the paste out of the input.
788
+ */
789
+ export class ClipboardEvent extends Event {
790
+ constructor(type: string, init?: { bubbles?: boolean; cancelable?: boolean; composed?: boolean; clipboardData?: DataTransfer | null });
791
+ readonly clipboardData: DataTransfer | null;
691
792
  }
692
793
 
693
794
  /** Files dragged from another app over the window (`dragenter`, `dragover`, `dragleave`, `drop`). */
@@ -750,6 +851,96 @@ export function removeTray(): void;
750
851
  export function registerShortcut(accelerator: string, callback: () => void): Promise<boolean>;
751
852
  export function unregisterShortcut(accelerator: string): void;
752
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
+
753
944
  /** The app's memory: `footprint` in bytes over `processes` processes. */
754
945
  export interface MemoryUsage {
755
946
  footprint: number;