feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+27
@@ -0,0 +1,27 @@
|
||||
// Bundles the runtime MyGo injects into every page into
|
||||
// internal/bridge/bridge.js, which the Go package embeds, and the script
|
||||
// WebView2's web views in native UI run in an isolated world into
|
||||
// internal/windows/keys.js. The output is committed, so Go users never
|
||||
// need Bun.
|
||||
import { join } from "node:path";
|
||||
|
||||
const outputs: [entry: string, out: string][] = [
|
||||
["src/bridge.ts", "../../internal/bridge/bridge.js"],
|
||||
["src/keys-world.ts", "../../internal/windows/keys.js"],
|
||||
];
|
||||
for (const [entry, file] of outputs) {
|
||||
const out = join(import.meta.dir, file);
|
||||
const result = await Bun.build({
|
||||
entrypoints: [join(import.meta.dir, entry)],
|
||||
format: "iife",
|
||||
target: "browser",
|
||||
minify: true,
|
||||
});
|
||||
if (!result.success) {
|
||||
for (const log of result.logs) console.error(log);
|
||||
process.exit(1);
|
||||
}
|
||||
const code = (await result.outputs[0]!.text()).trim();
|
||||
await Bun.write(out, "// Code generated by `bun run build` from packages/bridge. DO NOT EDIT.\n" + code + "\n");
|
||||
console.log(`wrote ${out} (${code.length} bytes)`);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "mygo-bridge",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "bun run build.ts",
|
||||
"test": "bun test"
|
||||
}
|
||||
}
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
// Entry point of the script MyGo injects at document start into every page.
|
||||
// The Go side wraps the bundle in a function that defines __MYGO_CONFIG__.
|
||||
import { contextTarget } from "./context-menu";
|
||||
import { find, stopFind } from "./find";
|
||||
import { type FitLimits, fitContent } from "./fit-content";
|
||||
import { createRuntime } from "./runtime";
|
||||
import { watchThemeColor } from "./theme-color";
|
||||
import type { BridgeConfig, ThemePreferences } from "./types";
|
||||
import { markWindowActive } from "./window-active";
|
||||
|
||||
declare const __MYGO_CONFIG__: BridgeConfig;
|
||||
|
||||
// Elements that keep receiving clicks inside a drag region.
|
||||
const INTERACTIVE =
|
||||
'input,textarea,select,button,a[href],summary,label,[contenteditable]:not([contenteditable="false"]),video[controls],audio[controls]';
|
||||
|
||||
// MyGo's own style sheet, declared before the bridge starts, which sets it.
|
||||
/** The MyGo CSS variables of :root, kept from every source that sets one. */
|
||||
const rootVars: Record<string, string | null> = {};
|
||||
/** The rule of FitContent, which lays the root out at its content's size. */
|
||||
let fitCSS = "";
|
||||
let rootSheet: CSSStyleSheet | null = null;
|
||||
let rootStyle: HTMLStyleElement | null = null;
|
||||
|
||||
(() => {
|
||||
const w = window as any;
|
||||
if (w.__mygo) return;
|
||||
|
||||
const raw = transport(w);
|
||||
if (!raw) return;
|
||||
// Only this closure knows the secret: the handler is also reachable from
|
||||
// iframes, whose messages Go must ignore.
|
||||
const post = (m: string) => raw.post(__MYGO_CONFIG__.secret + m);
|
||||
|
||||
const { runtime, internal, restored } = createRuntime(__MYGO_CONFIG__, post);
|
||||
Object.defineProperty(w, "mygo", { value: runtime, enumerable: true });
|
||||
Object.defineProperty(w, "__mygo", { value: Object.freeze({ ...internal, find, stopFind }) });
|
||||
|
||||
// A window with a hidden title bar tells its pages the room its window
|
||||
// controls take, from document start on: CSS variables on :root.
|
||||
runtime.on<TitleBar>("mygo:title-bar", (tb) =>
|
||||
setRootVars({
|
||||
"--mygo-titlebar-height": `${tb.height}px`,
|
||||
"--mygo-titlebar-inset-left": `${tb.left}px`,
|
||||
"--mygo-titlebar-inset-right": `${tb.right}px`,
|
||||
"--mygo-titlebar-controls-bottom": `${tb.bottom}px`,
|
||||
}),
|
||||
);
|
||||
|
||||
// The accent color and the size of text the desktop asks for, which the
|
||||
// media queries do not tell a page. From document start on: CSS variables
|
||||
// on :root, with the accent left unset where the desktop has none.
|
||||
runtime.on<ThemePreferences>("mygo:preferences", (p) =>
|
||||
setRootVars({
|
||||
"--mygo-accent": p.accent,
|
||||
"--mygo-text-scale": String(p.textScale),
|
||||
}),
|
||||
);
|
||||
|
||||
// A window that is not the one the user's input goes to marks its pages,
|
||||
// for CSS to draw them as native apps draw such windows:
|
||||
// `:root[data-mygo-window-inactive] .sidebar { … }`.
|
||||
runtime.on<boolean>("mygo:window-active", (active) => markWindowActive(document.documentElement, active));
|
||||
|
||||
const notify = (t: "dom-ready" | "drag" | "dblclick" | "escape") => {
|
||||
try {
|
||||
post(JSON.stringify({ t }));
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
};
|
||||
|
||||
// The page's theme color, for Page.ThemeColor; told before dom-ready, so
|
||||
// that Go knows it once the DOM is.
|
||||
const themeColorReady = watchThemeColor((v) => {
|
||||
try {
|
||||
post(JSON.stringify({ t: "theme-color", v }));
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
});
|
||||
// A window that takes its content's size (FitContent): told before
|
||||
// dom-ready too, so that a window that shows once its DOM is ready shows
|
||||
// at its size.
|
||||
const fit =
|
||||
__MYGO_CONFIG__.fit &&
|
||||
fitContent(__MYGO_CONFIG__.fit, setFitRule, (size) => {
|
||||
try {
|
||||
post(JSON.stringify({ t: "content-size", ...size }));
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
});
|
||||
if (fit) runtime.on<FitLimits>("mygo:fit-content", fit.setLimits);
|
||||
const domReady = () => {
|
||||
themeColorReady();
|
||||
if (fit) fit.start();
|
||||
notify("dom-ready");
|
||||
};
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", domReady, { once: true });
|
||||
} else {
|
||||
domReady();
|
||||
}
|
||||
// A page the web view kept as it was left, and shows again on Back or
|
||||
// Forward, runs no script again and fires no DOMContentLoaded, while Go
|
||||
// took the navigation for a new page: it holds the page's events until
|
||||
// its DOM is ready, and waits for its theme color and its size. So the
|
||||
// page tells them again, whatever it told before.
|
||||
w.addEventListener("pageshow", (e: PageTransitionEvent) => {
|
||||
if (!e.persisted) return;
|
||||
restored();
|
||||
themeColorReady(true);
|
||||
if (fit) fit.again();
|
||||
notify("dom-ready");
|
||||
});
|
||||
// WebKit runs the microtasks that scripts queued once a listener of an
|
||||
// event returns. An eval (Page.Eval) that runs in the page just as a
|
||||
// navigation away commits can leave its continuation queued: with no
|
||||
// listener of pagehide, nothing runs it before WebKit freezes the page
|
||||
// in its back/forward cache, and the eval answers only if Back shows the
|
||||
// page again. Listening has it run as the page is left.
|
||||
w.addEventListener("pagehide", () => {});
|
||||
|
||||
const nativeRegion = typeof CSS !== "undefined" && CSS.supports("-webkit-app-region", "drag");
|
||||
const appRegion = (el: Element): string => {
|
||||
const custom = getComputedStyle(el).getPropertyValue("--app-region").trim();
|
||||
if (custom) return custom;
|
||||
if (!nativeRegion) return "";
|
||||
// The native property is not inherited, so walk up the tree.
|
||||
for (let node: Element | null = el; node; node = node.parentElement) {
|
||||
const value = getComputedStyle(node).getPropertyValue("-webkit-app-region").trim();
|
||||
if (value === "drag" || value === "no-drag") return value;
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
// Files dropped from outside: Go gets their paths next to the page's own
|
||||
// drag and drop, which is left as it is. The platform records the paths
|
||||
// before the page sees the drop, or WebView2 hands them over with the
|
||||
// File objects posted along with the message.
|
||||
let inPage = false; // a drag started in this page: none of our business
|
||||
w.addEventListener("dragstart", () => (inPage = true), true);
|
||||
w.addEventListener("dragend", () => (inPage = false), true);
|
||||
const external = (e: DragEvent) =>
|
||||
!inPage && !!e.dataTransfer && Array.from(e.dataTransfer.types).includes("Files");
|
||||
w.addEventListener(
|
||||
"drop",
|
||||
(e: DragEvent) => {
|
||||
const files = e.dataTransfer?.files;
|
||||
if (inPage || !files?.length) return;
|
||||
const m = __MYGO_CONFIG__.secret + JSON.stringify({ t: "drop", x: Math.round(e.clientX), y: Math.round(e.clientY) });
|
||||
try {
|
||||
raw.postWithFiles ? raw.postWithFiles(m, files) : raw.post(m);
|
||||
} catch {
|
||||
try {
|
||||
raw.post(m); // e.g. File objects not backed by a file
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
}
|
||||
},
|
||||
true,
|
||||
);
|
||||
// Where the page does not handle dragged files, accept them rather than
|
||||
// letting the engine replace the page with the dropped file.
|
||||
const accept = (e: DragEvent) => {
|
||||
if (external(e) && !e.defaultPrevented) e.preventDefault();
|
||||
};
|
||||
w.addEventListener("dragover", accept);
|
||||
w.addEventListener("drop", accept);
|
||||
|
||||
// An Escape the page does not handle (preventDefault) closes a flyout,
|
||||
// as a menu or popover. Handlers run in any order: look once all did.
|
||||
w.addEventListener("keydown", (e: KeyboardEvent) => {
|
||||
if (e.key !== "Escape" || e.isComposing) return;
|
||||
setTimeout(() => {
|
||||
if (!e.defaultPrevented) notify("escape");
|
||||
});
|
||||
});
|
||||
|
||||
// What a context menu opens on (Page.OnContextMenu), told as the event
|
||||
// starts, ahead of the page's own handlers: Go hears it before the web
|
||||
// view asks about its menu, which a handler that cancels the event
|
||||
// keeps from opening. The element is the innermost, inside shadow roots.
|
||||
w.addEventListener(
|
||||
"contextmenu",
|
||||
(e: MouseEvent) => {
|
||||
const el = e.composedPath()[0];
|
||||
const target = contextTarget(el instanceof Element ? el : null, getSelection()?.toString() ?? "");
|
||||
try {
|
||||
post(JSON.stringify({ t: "context-menu", x: e.clientX, y: e.clientY, ...target }));
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
// Frameless windows: `--app-region: drag` (or `-webkit-app-region: drag`
|
||||
// where the engine supports it) turns an element into a window handle.
|
||||
w.addEventListener(
|
||||
"mousedown",
|
||||
(e: MouseEvent) => {
|
||||
if (e.button !== 0 || !(e.target instanceof Element)) return;
|
||||
if (appRegion(e.target) !== "drag" || e.target.closest(INTERACTIVE)) return;
|
||||
e.preventDefault();
|
||||
notify(e.detail === 2 ? "dblclick" : "drag");
|
||||
},
|
||||
true,
|
||||
);
|
||||
})();
|
||||
|
||||
/** The room the window controls take, in CSS pixels. */
|
||||
interface TitleBar {
|
||||
height: number;
|
||||
left: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
/** Sets MyGo's CSS variables of :root, keeping the ones already set. A null
|
||||
* value removes a variable, so a page's `var(--mygo-accent, AccentColor)`
|
||||
* fallback applies. */
|
||||
function setRootVars(vars: Record<string, string | null>): void {
|
||||
Object.assign(rootVars, vars);
|
||||
updateRootStyle();
|
||||
}
|
||||
|
||||
function setFitRule(css: string): void {
|
||||
fitCSS = css;
|
||||
updateRootStyle();
|
||||
}
|
||||
|
||||
function updateRootStyle(): void {
|
||||
const decls = Object.entries(rootVars)
|
||||
.filter(([, v]) => v !== null)
|
||||
.map(([k, v]) => `${k}:${v}`)
|
||||
.join(";");
|
||||
setRootStyle((decls ? `:root{${decls}}` : "") + fitCSS);
|
||||
}
|
||||
|
||||
/** Sets the rules of MyGo's own style sheet, which a Content Security Policy
|
||||
* allows as a constructed sheet. Engines without them get a style element. */
|
||||
function setRootStyle(css: string): void {
|
||||
if ((document as Partial<Document>).adoptedStyleSheets) {
|
||||
if (!rootSheet) {
|
||||
rootSheet = new CSSStyleSheet();
|
||||
document.adoptedStyleSheets = [...document.adoptedStyleSheets, rootSheet];
|
||||
}
|
||||
rootSheet.replaceSync(css);
|
||||
return;
|
||||
}
|
||||
const style = (rootStyle ??= document.createElement("style"));
|
||||
style.textContent = css;
|
||||
const attach = () => {
|
||||
if (!style.isConnected) (document.head ?? document.documentElement)?.append(style);
|
||||
};
|
||||
if (document.documentElement) attach();
|
||||
else document.addEventListener("DOMContentLoaded", attach, { once: true });
|
||||
}
|
||||
|
||||
interface Transport {
|
||||
post(message: string): void;
|
||||
/** Posts File objects along with a message (WebView2). */
|
||||
postWithFiles?(message: string, files: FileList): void;
|
||||
}
|
||||
|
||||
function transport(w: any): Transport | null {
|
||||
const handler = w.webkit?.messageHandlers?.mygo;
|
||||
if (handler) return { post: (m) => handler.postMessage(m) };
|
||||
// Android's web view: the host's JavaScript interface.
|
||||
const android = w.mygoAndroid;
|
||||
if (android) return { post: (m) => android.postMessage(m) };
|
||||
const webview = w.chrome?.webview;
|
||||
if (!webview) return null;
|
||||
return {
|
||||
post: (m) => webview.postMessage(m),
|
||||
postWithFiles: webview.postMessageWithAdditionalObjects
|
||||
? (m, files) => webview.postMessageWithAdditionalObjects(m, files)
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { contextTarget, type TargetElement } from "./context-menu";
|
||||
|
||||
/** An element matching the selectors of its tags, inside parent. */
|
||||
const el = (tags: string[], props: Partial<TargetElement> = {}, parent: TargetElement | null = null): TargetElement => {
|
||||
const self: TargetElement = {
|
||||
...props,
|
||||
closest(selector) {
|
||||
const matches = selector.split(",").some((s) => tags.includes(s.replace(/\[href\]$/, "")) && (!s.endsWith("[href]") || !!props.href));
|
||||
return matches ? self : (parent?.closest(selector) ?? null);
|
||||
},
|
||||
};
|
||||
return self;
|
||||
};
|
||||
|
||||
describe("contextTarget", () => {
|
||||
test("tells a link and its text, from inside it", () => {
|
||||
const a = el(["a"], { href: "https://example.com/", innerText: " Example " });
|
||||
expect(contextTarget(el(["span"], {}, a), "")).toEqual({ l: "https://example.com/", lt: "Example" });
|
||||
expect(contextTarget(el(["a"], { textContent: "No href" }), "")).toEqual({});
|
||||
});
|
||||
|
||||
test("tells an SVG link's href", () => {
|
||||
expect(contextTarget(el(["a"], { href: { baseVal: "/doc" }, textContent: "Doc" }), "")).toEqual({ l: "/doc", lt: "Doc" });
|
||||
});
|
||||
|
||||
test("tells an image in a link", () => {
|
||||
const a = el(["a"], { href: "https://example.com/" });
|
||||
const img = el(["img"], { currentSrc: "", src: "https://example.com/cat.png" }, a);
|
||||
expect(contextTarget(img, "")).toEqual({ l: "https://example.com/", i: "https://example.com/cat.png" });
|
||||
});
|
||||
|
||||
test("tells a video's source", () => {
|
||||
expect(contextTarget(el(["video"], { currentSrc: "https://example.com/a.mp4" }), "")).toEqual({ m: "https://example.com/a.mp4" });
|
||||
});
|
||||
|
||||
test("tells the document's selection", () => {
|
||||
expect(contextTarget(el(["p"]), "Hello")).toEqual({ s: "Hello" });
|
||||
expect(contextTarget(null, "Hello")).toEqual({ s: "Hello" });
|
||||
});
|
||||
|
||||
test("tells a text field's own selection, and that it is editable", () => {
|
||||
const input = el(["input"], { type: "text", value: "Hello world", selectionStart: 6, selectionEnd: 11 });
|
||||
expect(contextTarget(input, "elsewhere")).toEqual({ e: true, s: "world" });
|
||||
const area = el(["textarea"], { value: "abc", selectionStart: 1, selectionEnd: 1 });
|
||||
expect(contextTarget(area, "elsewhere")).toEqual({ e: true, s: "elsewhere" });
|
||||
});
|
||||
|
||||
test("a read-only or disabled field, or a button, is not editable", () => {
|
||||
expect(contextTarget(el(["input"], { type: "text", readOnly: true }), "")).toEqual({});
|
||||
expect(contextTarget(el(["textarea"], { disabled: true }), "")).toEqual({});
|
||||
expect(contextTarget(el(["input"], { type: "checkbox" }), "x")).toEqual({ s: "x" });
|
||||
});
|
||||
|
||||
test("never tells a password", () => {
|
||||
const pw = el(["input"], { type: "password", value: "hunter2", selectionStart: 0, selectionEnd: 7 });
|
||||
expect(contextTarget(pw, "")).toEqual({ e: true });
|
||||
});
|
||||
|
||||
test("editable content", () => {
|
||||
expect(contextTarget(el(["div"], { isContentEditable: true }), "")).toEqual({ e: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// What a context menu opens on, for Page.OnContextMenu in Go. The page's
|
||||
// contextmenu event tells it just before the web view asks Go about its
|
||||
// menu, which WebKit on macOS tells nothing of what was clicked, nor
|
||||
// WebKitGTK of the selection.
|
||||
|
||||
/** The record Go reads: the link and its text, the image, the video or
|
||||
* audio, the selection, and whether the element is editable. Empty parts
|
||||
* are left out. */
|
||||
export interface ContextTarget {
|
||||
l?: string;
|
||||
lt?: string;
|
||||
i?: string;
|
||||
m?: string;
|
||||
s?: string;
|
||||
e?: true;
|
||||
}
|
||||
|
||||
/** The parts of an element a context menu's target is read from: an
|
||||
* Element of the DOM, or what a test makes. */
|
||||
export interface TargetElement {
|
||||
closest(selector: string): TargetElement | null;
|
||||
/** A link's: a string, or an SVG link's animated string. */
|
||||
href?: string | { baseVal: string };
|
||||
/** An image's or a media element's. */
|
||||
currentSrc?: string;
|
||||
src?: string;
|
||||
innerText?: string;
|
||||
textContent?: string | null;
|
||||
isContentEditable?: boolean;
|
||||
/** A text field's. */
|
||||
type?: string;
|
||||
readOnly?: boolean;
|
||||
disabled?: boolean;
|
||||
value?: string;
|
||||
selectionStart?: number | null;
|
||||
selectionEnd?: number | null;
|
||||
}
|
||||
|
||||
// Inputs that take no text, which a context menu offers no editing for.
|
||||
const NOT_TEXT = new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]);
|
||||
|
||||
/** Describes el, the element a context menu opens on, with the text
|
||||
* selected in the document. */
|
||||
export function contextTarget(el: TargetElement | null, selection: string): ContextTarget {
|
||||
const t: ContextTarget = {};
|
||||
const field = el?.closest("input,textarea") ?? null;
|
||||
const text = field && !(field.type && NOT_TEXT.has(field.type.toLowerCase()));
|
||||
if (text && !field.readOnly && !field.disabled) t.e = true;
|
||||
else if (el?.isContentEditable) t.e = true;
|
||||
// A text field's selection is not the document's. A password's is
|
||||
// nobody's business.
|
||||
if (text && field.type?.toLowerCase() !== "password") {
|
||||
const start = field.selectionStart ?? 0;
|
||||
const end = field.selectionEnd ?? 0;
|
||||
if (end > start) selection = (field.value ?? "").slice(start, end);
|
||||
} else if (text) {
|
||||
selection = "";
|
||||
}
|
||||
if (selection) t.s = selection;
|
||||
if (!el) return t;
|
||||
const link = el.closest("a[href],area[href]");
|
||||
if (link) {
|
||||
const href = typeof link.href === "string" ? link.href : (link.href?.baseVal ?? "");
|
||||
if (href) t.l = href;
|
||||
const label = (link.innerText ?? link.textContent ?? "").trim();
|
||||
if (label) t.lt = label;
|
||||
}
|
||||
const img = el.closest("img");
|
||||
if (img) {
|
||||
const src = img.currentSrc || img.src;
|
||||
if (src) t.i = src;
|
||||
}
|
||||
const media = el.closest("video,audio");
|
||||
if (media) {
|
||||
const src = media.currentSrc || media.src;
|
||||
if (src) t.m = src;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// Find in page (Window.FindInPage): matches are marked with the CSS Custom
|
||||
// Highlight API, which leaves the page's DOM and selection alone; engines
|
||||
// without it select the active match instead.
|
||||
|
||||
export interface FindOptions {
|
||||
matchCase?: boolean;
|
||||
backward?: boolean;
|
||||
next?: boolean;
|
||||
}
|
||||
|
||||
export interface FindResult {
|
||||
matches: number;
|
||||
active: number;
|
||||
}
|
||||
|
||||
let state: { text: string; matchCase: boolean; ranges: Range[]; active: number } | null = null;
|
||||
let sheet: CSSStyleSheet | null = null;
|
||||
|
||||
const highlights = () =>
|
||||
typeof CSS !== "undefined" && "highlights" in CSS && typeof Highlight !== "undefined";
|
||||
|
||||
/** Ranges of the visible text matching text, in document order. */
|
||||
function collect(text: string, matchCase: boolean): Range[] {
|
||||
const ranges: Range[] = [];
|
||||
if (!text || !document.body) return ranges;
|
||||
const needle = matchCase ? text : text.toLowerCase();
|
||||
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, {
|
||||
acceptNode(node) {
|
||||
const el = node.parentElement;
|
||||
if (!el || /^(SCRIPT|STYLE|NOSCRIPT|TEMPLATE|TEXTAREA)$/.test(el.tagName)) return NodeFilter.FILTER_REJECT;
|
||||
return el.getClientRects().length ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
|
||||
},
|
||||
});
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
const hay = matchCase ? node.nodeValue! : node.nodeValue!.toLowerCase();
|
||||
for (let i = hay.indexOf(needle); i >= 0; i = hay.indexOf(needle, i + needle.length)) {
|
||||
const r = document.createRange();
|
||||
r.setStart(node, i);
|
||||
r.setEnd(node, i + needle.length);
|
||||
ranges.push(r);
|
||||
}
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
function style() {
|
||||
if (sheet || !("adoptedStyleSheets" in document)) return;
|
||||
// A constructed style sheet, which a Content Security Policy allows.
|
||||
sheet = new CSSStyleSheet();
|
||||
sheet.replaceSync(
|
||||
"::highlight(mygo-find){background-color:#fdeb62;color:#000}" +
|
||||
"::highlight(mygo-find-active){background-color:#ff9632;color:#000}",
|
||||
);
|
||||
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
|
||||
}
|
||||
|
||||
export function find(text: string, opts: FindOptions = {}): FindResult {
|
||||
const matchCase = !!opts.matchCase;
|
||||
if (!opts.next || !state || state.text !== text || state.matchCase !== matchCase) {
|
||||
state = { text, matchCase, ranges: collect(text, matchCase), active: -1 };
|
||||
}
|
||||
const n = state.ranges.length;
|
||||
if (n === 0) {
|
||||
stopFind();
|
||||
return { matches: 0, active: 0 };
|
||||
}
|
||||
state.active =
|
||||
state.active < 0 ? (opts.backward ? n - 1 : 0) : (state.active + (opts.backward ? n - 1 : 1)) % n;
|
||||
const range = state.ranges[state.active]!;
|
||||
if (highlights()) {
|
||||
style();
|
||||
CSS.highlights.set("mygo-find", new Highlight(...state.ranges));
|
||||
CSS.highlights.set("mygo-find-active", new Highlight(range));
|
||||
} else {
|
||||
const sel = getSelection();
|
||||
sel?.removeAllRanges();
|
||||
sel?.addRange(range);
|
||||
}
|
||||
range.startContainer.parentElement?.scrollIntoView({ block: "center", inline: "nearest" });
|
||||
return { matches: n, active: state.active + 1 };
|
||||
}
|
||||
|
||||
export function stopFind() {
|
||||
if (state && !highlights()) getSelection()?.removeAllRanges();
|
||||
state = null;
|
||||
if (highlights()) {
|
||||
CSS.highlights.delete("mygo-find");
|
||||
CSS.highlights.delete("mygo-find-active");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { type ContentSize, fitRule, sizeReporter } from "./fit-content";
|
||||
|
||||
const none = { minWidth: 0, minHeight: 0, maxWidth: 0, maxHeight: 0 };
|
||||
|
||||
describe("fitRule", () => {
|
||||
test("lays out the root at its content's width, without specificity", () => {
|
||||
expect(fitRule(none, 0)).toBe(":where(:root){width:max-content}");
|
||||
});
|
||||
|
||||
test("bounds the width and the minimum height, not the maximum height", () => {
|
||||
expect(fitRule({ minWidth: 100, minHeight: 40, maxWidth: 300, maxHeight: 200 }, 0)).toBe(
|
||||
":where(:root){width:max-content;min-width:100px;max-width:300px;min-height:40px}",
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves a vertical scrollbar's room out of the width", () => {
|
||||
expect(fitRule({ ...none, minWidth: 100, maxWidth: 300 }, 15)).toBe(
|
||||
":where(:root){width:max-content;min-width:85px;max-width:285px}",
|
||||
);
|
||||
expect(fitRule({ ...none, maxWidth: 10 }, 15)).toBe(":where(:root){width:max-content;max-width:0px}");
|
||||
});
|
||||
|
||||
test("takes the fractional CSS pixels of a zoomed page", () => {
|
||||
expect(fitRule({ ...none, maxWidth: 133.5 }, 0)).toBe(":where(:root){width:max-content;max-width:133.5px}");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sizeReporter", () => {
|
||||
test("tells only of changes", () => {
|
||||
const told: ContentSize[] = [];
|
||||
const report = sizeReporter((s) => told.push(s));
|
||||
const size = (w: number, h: number, sw = 0, sh = 0) => ({ w, h, sw, sh });
|
||||
report(size(120, 80));
|
||||
report(size(120, 80));
|
||||
report(size(120.5, 80));
|
||||
report(size(120.5, 90));
|
||||
report(size(120.5, 90));
|
||||
report(size(120.5, 90, 15));
|
||||
report(size(120.5, 90, 15, 15));
|
||||
report(size(120.5, 90, 15, 15));
|
||||
report(size(0, 0));
|
||||
expect(told).toEqual([
|
||||
size(120, 80),
|
||||
size(120.5, 80),
|
||||
size(120.5, 90),
|
||||
size(120.5, 90, 15),
|
||||
size(120.5, 90, 15, 15),
|
||||
size(0, 0),
|
||||
]);
|
||||
});
|
||||
});
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
// A window that takes the size of its page's content (FitContent in Go), as
|
||||
// browsers size the popups of their extensions. The root element is laid out
|
||||
// at the width of its content (max-content), within the window's limits, so
|
||||
// that text wraps at the maximum width, and its height is its content's. A
|
||||
// ResizeObserver on it tells Go the size, and the room of the scrollbars the
|
||||
// page shows, whenever it changes; Go clamps it, turns it into DIPs, decides
|
||||
// whether the scrollbars' room counts, and resizes the window.
|
||||
|
||||
/** The limits of the window's size, in the CSS pixels of the page; 0 is
|
||||
* none. */
|
||||
export interface FitLimits {
|
||||
minWidth: number;
|
||||
minHeight: number;
|
||||
maxWidth: number;
|
||||
maxHeight: number;
|
||||
}
|
||||
|
||||
/** The rule that lays out the root element at its content's size within the
|
||||
* limits, leaving the room of a vertical scrollbar out of the maximum width,
|
||||
* so that the root and the scrollbar fit in it. It has no specificity, so that
|
||||
* a page's own size for html wins. */
|
||||
export function fitRule(l: FitLimits, scrollbar: number): string {
|
||||
const decls = ["width:max-content"];
|
||||
if (l.minWidth > 0) decls.push(`min-width:${Math.max(l.minWidth - scrollbar, 0)}px`);
|
||||
if (l.maxWidth > 0) decls.push(`max-width:${Math.max(l.maxWidth - scrollbar, 0)}px`);
|
||||
if (l.minHeight > 0) decls.push(`min-height:${l.minHeight}px`);
|
||||
return `:where(:root){${decls.join(";")}}`;
|
||||
}
|
||||
|
||||
/** The size of the content in CSS pixels: the root element's, and the room
|
||||
* of the vertical scrollbar the page shows (sw) and of a horizontal one (sh),
|
||||
* which counts only when the content is wider than the root. */
|
||||
export interface ContentSize {
|
||||
w: number;
|
||||
h: number;
|
||||
sw: number;
|
||||
sh: number;
|
||||
}
|
||||
|
||||
/** Returns a function that tells Go of a size only when it changed. */
|
||||
export function sizeReporter(post: (size: ContentSize) => void) {
|
||||
let last: ContentSize | null = null;
|
||||
return (size: ContentSize) => {
|
||||
if (last && last.w === size.w && last.h === size.h && last.sw === size.sw && last.sh === size.sh) return;
|
||||
last = size;
|
||||
post(size);
|
||||
};
|
||||
}
|
||||
|
||||
/** Fits the window to the document's content: the rule applies from now on;
|
||||
* start, once the DOM is ready, measures the content and watches it.
|
||||
* setLimits takes other limits, as the page's zoom changed. again tells
|
||||
* the size whatever was told before, for a page Go took for a new one. */
|
||||
export function fitContent(
|
||||
limits: FitLimits,
|
||||
setRule: (css: string) => void,
|
||||
post: (size: ContentSize) => void,
|
||||
) {
|
||||
let report = sizeReporter(post);
|
||||
let scrollbar = 0; // the vertical scrollbar's width the rule leaves out
|
||||
let started = false;
|
||||
let pending = false;
|
||||
const apply = () => setRule(fitRule(limits, scrollbar));
|
||||
|
||||
// fromObserver: changing the root's size in a ResizeObserver's callback
|
||||
// would end its loop with an error event, which the page would hear; the
|
||||
// rule changes in the next frame then, and the observer tells the size.
|
||||
const measure = (fromObserver: boolean) => {
|
||||
const root = document.documentElement;
|
||||
if (!root) return;
|
||||
const viewport = document.scrollingElement ?? root;
|
||||
const sw = Math.max(innerWidth - viewport.clientWidth, 0);
|
||||
const sh = Math.max(innerHeight - viewport.clientHeight, 0);
|
||||
let r = root.getBoundingClientRect();
|
||||
// A vertical scrollbar shows for a moment whenever the content grows
|
||||
// before the window does, and an engine may keep it while it lays out
|
||||
// (WebKit does): its room is left out of the width only where the
|
||||
// content is taller than the window may be, and Go decides whether it
|
||||
// counts in the window's.
|
||||
const room = limits.maxHeight > 0 && r.height > limits.maxHeight ? sw : 0;
|
||||
if (room !== scrollbar) {
|
||||
scrollbar = room;
|
||||
if (!fromObserver) {
|
||||
apply();
|
||||
r = root.getBoundingClientRect();
|
||||
} else if (!pending) {
|
||||
pending = true;
|
||||
requestAnimationFrame(() => {
|
||||
pending = false;
|
||||
apply();
|
||||
});
|
||||
}
|
||||
}
|
||||
// The content overflows the root only when the root is at its maximum
|
||||
// width.
|
||||
const body = document.body;
|
||||
const wider = !!body && body.scrollWidth > body.clientWidth;
|
||||
report({ w: r.width, h: r.height, sw, sh: wider ? sh : 0 });
|
||||
};
|
||||
|
||||
apply();
|
||||
return {
|
||||
start() {
|
||||
if (started) return;
|
||||
started = true;
|
||||
measure(false);
|
||||
if (typeof ResizeObserver !== "undefined" && document.documentElement) {
|
||||
new ResizeObserver(() => measure(true)).observe(document.documentElement);
|
||||
}
|
||||
// The window's own size changed what scrollbars show.
|
||||
addEventListener("resize", () => measure(false));
|
||||
},
|
||||
setLimits(l: FitLimits) {
|
||||
limits = l;
|
||||
apply();
|
||||
if (started) measure(false);
|
||||
},
|
||||
again() {
|
||||
report = sizeReporter(post);
|
||||
if (started) measure(false);
|
||||
},
|
||||
};
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
// Entry point of the script MyGo's WebView2 backend runs in an isolated
|
||||
// world of every document of a web view in a window of native UI, top
|
||||
// frame and frames alike (DevTools: Page.addScriptToEvaluateOnNewDocument
|
||||
// with a worldName). It sees the page's keydown events, and after the
|
||||
// page's handlers ran, tells Go of those the page left unhandled (keys.ts)
|
||||
// through the binding Runtime.addBinding gives that world alone. The
|
||||
// page's scripts reach neither the world nor the binding, and their
|
||||
// synthetic events are not trusted: they cannot make up a key.
|
||||
import { type Direction, forward, type Target } from "./keys";
|
||||
|
||||
// The binding's name, as internal/windows names it.
|
||||
const BINDING = "mygoUnhandledKey";
|
||||
|
||||
// Inputs that take no text.
|
||||
const NOT_TEXT = new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]);
|
||||
|
||||
// Controls that Enter and Space act on, and those the arrows change too.
|
||||
const CONTROLS = 'a[href],area[href],button,summary,input,[role="button"],[role="link"],[role="checkbox"],[role="tab"]';
|
||||
const ADJUSTABLE = 'input[type="range"],input[type="radio"],audio[controls],video[controls],[role="slider"],[role="radiogroup"]';
|
||||
|
||||
(() => {
|
||||
const w = window as any;
|
||||
if (w[BINDING + "Installed"]) return;
|
||||
w[BINDING + "Installed"] = true;
|
||||
|
||||
// Where the user last pressed, where keys scroll from while nothing has
|
||||
// the focus, as in Chrome.
|
||||
let pressed: Element | null = null;
|
||||
addEventListener("pointerdown", (e) => (pressed = element(e.composedPath()[0])), true);
|
||||
|
||||
addEventListener(
|
||||
"keydown",
|
||||
(e: KeyboardEvent) => {
|
||||
if (!e.isTrusted) return;
|
||||
// What has the focus, inside open shadow roots.
|
||||
let el = element(e.composedPath()[0]);
|
||||
for (let a = el?.shadowRoot?.activeElement; a; a = a.shadowRoot?.activeElement) el = a;
|
||||
if (el === document.body || el === document.documentElement) el = null;
|
||||
const press = {
|
||||
key: e.key,
|
||||
keyCode: e.keyCode,
|
||||
ctrl: e.ctrlKey,
|
||||
alt: e.altKey,
|
||||
shift: e.shiftKey,
|
||||
meta: e.metaKey,
|
||||
altGraph: e.getModifierState("AltGraph"),
|
||||
composing: e.isComposing || e.keyCode === 229,
|
||||
};
|
||||
// Decided as the key comes, before the page scrolls with it.
|
||||
const from = el ?? pressed;
|
||||
if (!forward(press, targetOf(el), (d) => scrolls(from, d), modal())) return;
|
||||
const mods = (e.shiftKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.altKey ? 4 : 0) | (e.metaKey ? 8 : 0);
|
||||
// The page's handlers run in any order: look once all did.
|
||||
setTimeout(() => {
|
||||
if (e.defaultPrevented) return;
|
||||
try {
|
||||
w[BINDING](JSON.stringify({ k: e.keyCode, m: mods, r: e.repeat }));
|
||||
} catch {
|
||||
// No binding: the document is going.
|
||||
}
|
||||
});
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
function element(n: EventTarget | null | undefined): Element | null {
|
||||
return n instanceof Element ? n : null;
|
||||
}
|
||||
|
||||
function targetOf(el: Element | null): Target {
|
||||
if (!el) return "other";
|
||||
if ((el as HTMLElement).isContentEditable || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) return "text";
|
||||
if (el instanceof HTMLInputElement && !NOT_TEXT.has(el.type)) return "text";
|
||||
return el.closest(ADJUSTABLE) ? "adjustable" : el.closest(CONTROLS) ? "control" : "other";
|
||||
}
|
||||
|
||||
// Whether the element or one around it, up to the page, scrolls in the
|
||||
// direction, as the key would.
|
||||
function scrolls(from: Element | null, d: Direction): boolean {
|
||||
const root = document.scrollingElement;
|
||||
for (let n = from; n && n !== root && n !== document.body; ) {
|
||||
const style = getComputedStyle(n);
|
||||
const overflow = d === "up" || d === "down" ? style.overflowY : style.overflowX;
|
||||
if ((overflow === "auto" || overflow === "scroll" || overflow === "overlay") && room(n, d)) return true;
|
||||
n = n.parentElement ?? ((n.getRootNode() as ShadowRoot).host || null);
|
||||
}
|
||||
if (!root || !room(root, d)) return false;
|
||||
const hidden = (el: Element | null) => !!el && getComputedStyle(el)[d === "up" || d === "down" ? "overflowY" : "overflowX"] === "hidden";
|
||||
return !hidden(document.documentElement) && !hidden(document.body);
|
||||
}
|
||||
|
||||
function room(n: Element, d: Direction): boolean {
|
||||
switch (d) {
|
||||
case "up":
|
||||
return n.scrollTop > 0;
|
||||
case "down":
|
||||
return n.scrollTop + n.clientHeight < n.scrollHeight - 1;
|
||||
default:
|
||||
// Either way, whatever the direction of the text.
|
||||
return n.scrollWidth > n.clientWidth + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Whether Escape closes something of the page's own: a modal dialog, full
|
||||
// screen, or a popover.
|
||||
function modal(): boolean {
|
||||
try {
|
||||
return !!document.querySelector(":modal, :popover-open") || !!document.fullscreenElement;
|
||||
} catch {
|
||||
return !!document.fullscreenElement;
|
||||
}
|
||||
}
|
||||
})();
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { type Direction, forward, type KeyPress, scrollDirection } from "./keys";
|
||||
|
||||
/** A key press: key, with its key code, and the modifiers in mods. */
|
||||
const press = (key: string, mods: Partial<KeyPress> = {}): KeyPress => ({
|
||||
key,
|
||||
keyCode: key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
meta: false,
|
||||
altGraph: false,
|
||||
composing: false,
|
||||
...mods,
|
||||
});
|
||||
|
||||
const never = () => false;
|
||||
const always = () => true;
|
||||
|
||||
describe("forward", () => {
|
||||
test("gives the native UI letters and chords the page left", () => {
|
||||
expect(forward(press("j"), "other", never, false)).toBe(true);
|
||||
expect(forward(press("k", { ctrl: true }), "other", never, false)).toBe(true);
|
||||
expect(forward(press("k", { meta: true }), "other", never, false)).toBe(true);
|
||||
expect(forward(press("Enter"), "other", never, false)).toBe(true);
|
||||
expect(forward(press("F5"), "text", never, false)).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps Tab, modifiers on their own and the input method's keys", () => {
|
||||
for (const key of ["Tab", "Shift", "Control", "Alt", "AltGraph", "Meta", "CapsLock", "Dead", "Process"]) {
|
||||
expect(forward(press(key), "other", never, false)).toBe(false);
|
||||
}
|
||||
expect(forward(press("j", { composing: true }), "other", never, false)).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps what AltGr types, outside text fields too", () => {
|
||||
// AltGr+Q types @ on a German layout; Chromium tells neither Ctrl nor
|
||||
// Alt with it, but the key code of Q.
|
||||
const at = press("@", { keyCode: 81, altGraph: true });
|
||||
expect(forward(at, "other", never, false)).toBe(false);
|
||||
expect(forward(at, "text", never, false)).toBe(false);
|
||||
expect(forward(press("q", { ctrl: true, alt: true, altGraph: true }), "other", never, false)).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps what types or edits in a text field, not other chords", () => {
|
||||
for (const k of [press("j"), press("J", { shift: true }), press("Backspace"), press("ArrowLeft"), press(" ")]) {
|
||||
expect(forward(k, "text", never, false)).toBe(false);
|
||||
}
|
||||
for (const key of ["ArrowLeft", "Backspace", "Delete", "Home"]) {
|
||||
expect(forward(press(key, { ctrl: true }), "text", never, false)).toBe(false);
|
||||
}
|
||||
// AltGr, which Windows tells as Ctrl+Alt, types.
|
||||
expect(forward(press("q", { ctrl: true, alt: true }), "text", never, false)).toBe(false);
|
||||
expect(forward(press("k", { ctrl: true }), "text", never, false)).toBe(true);
|
||||
expect(forward(press("Escape"), "text", never, false)).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps the keys of edit commands everywhere", () => {
|
||||
for (const key of ["a", "c", "v", "x", "y", "z"]) {
|
||||
expect(forward(press(key, { ctrl: true }), "other", never, false)).toBe(false);
|
||||
}
|
||||
expect(forward(press("z", { ctrl: true, shift: true }), "other", never, false)).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps what activates or changes a control", () => {
|
||||
expect(forward(press("Enter"), "control", never, false)).toBe(false);
|
||||
expect(forward(press(" "), "control", never, false)).toBe(false);
|
||||
expect(forward(press("Enter", { ctrl: true }), "control", never, false)).toBe(true);
|
||||
// The arrows scroll from a link or a button, and change a slider.
|
||||
expect(forward(press("ArrowDown"), "control", never, false)).toBe(true);
|
||||
expect(forward(press("ArrowDown"), "adjustable", never, false)).toBe(false);
|
||||
expect(forward(press("j"), "adjustable", never, false)).toBe(true);
|
||||
});
|
||||
|
||||
test("keeps the keys that scroll the page, while it can scroll that way", () => {
|
||||
const only = (d: Direction) => (got: Direction) => got === d;
|
||||
expect(forward(press("ArrowDown"), "other", always, false)).toBe(false);
|
||||
expect(forward(press("ArrowDown"), "other", never, false)).toBe(true);
|
||||
expect(forward(press(" "), "other", only("down"), false)).toBe(false);
|
||||
expect(forward(press(" ", { shift: true }), "other", only("down"), false)).toBe(true);
|
||||
expect(forward(press("Home", { ctrl: true }), "other", only("up"), false)).toBe(false);
|
||||
});
|
||||
|
||||
test("keeps Escape while the page shows a dialog, a popover or full screen", () => {
|
||||
expect(forward(press("Escape"), "other", never, true)).toBe(false);
|
||||
expect(forward(press("Escape"), "other", never, false)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scrollDirection", () => {
|
||||
test("tells the way a key scrolls", () => {
|
||||
expect(scrollDirection(press("PageDown"))).toBe("down");
|
||||
expect(scrollDirection(press("ArrowLeft"))).toBe("left");
|
||||
expect(scrollDirection(press(" ", { shift: true }))).toBe("up");
|
||||
expect(scrollDirection(press("End", { ctrl: true }))).toBe("down");
|
||||
expect(scrollDirection(press("ArrowDown", { ctrl: true }))).toBe(null);
|
||||
expect(scrollDirection(press("ArrowDown", { alt: true }))).toBe(null);
|
||||
expect(scrollDirection(press("j"))).toBe(null);
|
||||
});
|
||||
});
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// Keys a page leaves unhandled, which the native UI around a web view gets
|
||||
// as if the web view's element had the focus (platform.WebViewKey). WebKit
|
||||
// tells of them itself, on macOS and Linux; WebView2 does not, so a script
|
||||
// in an isolated world of the page (keys-world.ts) decides with these
|
||||
// rules, which follow what the engine does with a key the page did not
|
||||
// cancel: typing and editing in a text field, activating a control,
|
||||
// scrolling, closing a dialog.
|
||||
|
||||
/** What forward reads of a keydown event. */
|
||||
export interface KeyPress {
|
||||
key: string;
|
||||
keyCode: number;
|
||||
ctrl: boolean;
|
||||
alt: boolean;
|
||||
shift: boolean;
|
||||
meta: boolean;
|
||||
/** AltGr is held (getModifierState("AltGraph")), which types the
|
||||
* layout's third characters, as @ on a German keyboard: Chromium may
|
||||
* tell neither Ctrl nor Alt with it. */
|
||||
altGraph: boolean;
|
||||
/** An input method composes with it (isComposing, or keyCode 229). */
|
||||
composing: boolean;
|
||||
}
|
||||
|
||||
/** What the key went to: a text field, textarea, select or editable
|
||||
* content, which types and edits with keys; a control that Enter and Space
|
||||
* act on (a button, a link, a checkbox); one that the arrows, Home, End and
|
||||
* Page Up and Down change too (a slider, radio buttons, a video with
|
||||
* controls); or anything else. */
|
||||
export type Target = "text" | "control" | "adjustable" | "other";
|
||||
|
||||
/** The way a key scrolls a page. */
|
||||
export type Direction = "up" | "down" | "left" | "right";
|
||||
|
||||
// Keys pressed on their own, which no native UI takes as a key.
|
||||
const MODIFIERS = new Set([
|
||||
"Shift",
|
||||
"Control",
|
||||
"Alt",
|
||||
"AltGraph",
|
||||
"Meta",
|
||||
"OS",
|
||||
"Super",
|
||||
"Hyper",
|
||||
"Fn",
|
||||
"FnLock",
|
||||
"CapsLock",
|
||||
"NumLock",
|
||||
"ScrollLock",
|
||||
"Symbol",
|
||||
"SymbolLock",
|
||||
]);
|
||||
|
||||
// Keys that move the caret or the selection in a text field, or scroll a
|
||||
// page.
|
||||
const MOVES = new Set(["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown"]);
|
||||
|
||||
// The edit commands' keys with Ctrl: select all, copy, cut, paste, undo and
|
||||
// redo, by key code as the engine takes them, whatever the layout types.
|
||||
const EDIT_CODES = new Set([65, 67, 86, 88, 89, 90]);
|
||||
|
||||
/** The way the key scrolls the page, if it does: the arrows, Page Up and
|
||||
* Down, Space (Shift+Space up), and Home and End, with Ctrl too. */
|
||||
export function scrollDirection(k: KeyPress): Direction | null {
|
||||
if (k.alt || k.meta) return null;
|
||||
if (k.ctrl) return k.key === "Home" ? "up" : k.key === "End" ? "down" : null;
|
||||
switch (k.key) {
|
||||
case "ArrowUp":
|
||||
case "PageUp":
|
||||
case "Home":
|
||||
return "up";
|
||||
case "ArrowDown":
|
||||
case "PageDown":
|
||||
case "End":
|
||||
return "down";
|
||||
case "ArrowLeft":
|
||||
return "left";
|
||||
case "ArrowRight":
|
||||
return "right";
|
||||
case " ":
|
||||
return k.shift ? "up" : "down";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* forward reports whether a key the page did not cancel goes to the native
|
||||
* UI. It does not when it is Tab, which moves the focus, a modifier on its
|
||||
* own, a key of the input method's, one typed with AltGr, one that types
|
||||
* or edits in a text field, activates a control or changes it, copies or
|
||||
* selects (Ctrl+C, Ctrl+A), scrolls something that can scroll that way
|
||||
* (scrolls), or Escape while a modal dialog, a popover or full screen is
|
||||
* open (modal), which closes it.
|
||||
*/
|
||||
export function forward(k: KeyPress, target: Target, scrolls: (d: Direction) => boolean, modal: boolean): boolean {
|
||||
if (k.composing || k.altGraph || k.key === "Tab" || k.key === "Dead" || k.key === "Process" || MODIFIERS.has(k.key)) return false;
|
||||
if (k.key === "Escape") return !modal;
|
||||
if (/^F\d+$/.test(k.key)) return true;
|
||||
const chord = (k.ctrl || k.meta) && !(k.ctrl && k.alt); // Ctrl+Alt is AltGr, which types
|
||||
if (chord && EDIT_CODES.has(k.keyCode)) return false;
|
||||
if (target === "text") {
|
||||
return chord && !MOVES.has(k.key) && k.key !== "Backspace" && k.key !== "Delete" && k.key !== "Insert";
|
||||
}
|
||||
if (target !== "other" && !chord && !k.alt && (k.key === "Enter" || k.key === " ")) return false;
|
||||
if (target === "adjustable" && !chord && !k.alt && MOVES.has(k.key)) return false;
|
||||
const d = scrollDirection(k);
|
||||
return !d || !scrolls(d);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { CallError, createRuntime } from "./runtime";
|
||||
import type { Outgoing } from "./types";
|
||||
|
||||
type CallMsg = Extract<Outgoing, { t: "call" }>;
|
||||
|
||||
function setup() {
|
||||
const sent: Outgoing[] = [];
|
||||
const rt = createRuntime(
|
||||
{ platform: "darwin", windowId: 7, version: "0.0.0-test", secret: "s", locale: "en", dir: "ltr" },
|
||||
(m) => sent.push(JSON.parse(m)),
|
||||
);
|
||||
return { sent, ...rt };
|
||||
}
|
||||
|
||||
describe("call", () => {
|
||||
test("resolves with the reply for the current page", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const p = runtime.call("Greeter.Greet", "bun", 1);
|
||||
const msg = sent[0] as CallMsg;
|
||||
expect(msg).toMatchObject({ t: "call", id: 1, m: "Greeter.Greet", a: ["bun", 1] });
|
||||
|
||||
// A reply addressed to another page (stale token) is ignored.
|
||||
internal.receive({ t: "reply", id: 1, k: "stale", ok: true, v: "wrong" });
|
||||
internal.receive({ t: "reply", id: 1, k: msg.k, ok: true, v: "hello bun" });
|
||||
expect(await p).toBe("hello bun");
|
||||
});
|
||||
|
||||
test("rejects with a CallError", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const p = runtime.call("Files.Read", "/nope");
|
||||
const { id, k } = sent[0] as CallMsg;
|
||||
internal.receive([{ t: "reply", id, k, ok: false, e: "file not found" }]);
|
||||
const err = (await p.catch((e) => e)) as CallError;
|
||||
expect(err).toBeInstanceOf(CallError);
|
||||
expect(err.message).toBe("file not found");
|
||||
expect(err.method).toBe("Files.Read");
|
||||
});
|
||||
|
||||
test("concurrent calls resolve independently", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const a = runtime.call("A.Do");
|
||||
const b = runtime.call("B.Do");
|
||||
const [ma, mb] = sent as CallMsg[];
|
||||
internal.receive([
|
||||
{ t: "reply", id: mb!.id, k: mb!.k, ok: true, v: "b" },
|
||||
{ t: "reply", id: ma!.id, k: ma!.k, ok: true, v: "a" },
|
||||
]);
|
||||
expect(await Promise.all([a, b])).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("window controls call built-in methods", () => {
|
||||
const { sent, runtime } = setup();
|
||||
runtime.window.minimize();
|
||||
runtime.window.setTitle("Hi");
|
||||
expect(sent.map((m) => (m as CallMsg).m)).toEqual(["mygo:window.Minimize", "mygo:window.SetTitle"]);
|
||||
expect((sent[1] as CallMsg).a).toEqual(["Hi"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canceling a call", () => {
|
||||
type CancelMsg = Extract<Outgoing, { t: "cancel" }>;
|
||||
|
||||
test("a signal tells Go that the call may be canceled", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const ac = new AbortController();
|
||||
const p = runtime.callWith("Greeter.Greet", ["bun"], { signal: ac.signal });
|
||||
const msg = sent[0] as CallMsg;
|
||||
expect(msg).toMatchObject({ t: "call", id: 1, m: "Greeter.Greet", a: ["bun"], cancel: true });
|
||||
|
||||
internal.receive({ t: "reply", id: msg.id, k: msg.k, ok: true, v: "hello bun" });
|
||||
expect(await p).toBe("hello bun");
|
||||
// A call without a signal is not canceled.
|
||||
runtime.call("Greeter.Greet", "bun");
|
||||
expect((sent[1] as CallMsg).cancel).toBeUndefined();
|
||||
});
|
||||
|
||||
test("aborting tells Go to cancel the call and rejects with the reason", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const ac = new AbortController();
|
||||
const p = runtime.callWith("Greeter.Greet", ["bun"], { signal: ac.signal });
|
||||
const msg = sent[0] as CallMsg;
|
||||
|
||||
ac.abort("no time");
|
||||
const cancel = sent[1] as CancelMsg;
|
||||
expect(cancel).toMatchObject({ t: "cancel", id: msg.id, k: msg.k });
|
||||
expect(await p.catch((e) => e)).toBe("no time");
|
||||
|
||||
// The reply of a canceled call is of no use.
|
||||
internal.receive({ t: "reply", id: msg.id, k: msg.k, ok: true, v: "hello bun" });
|
||||
});
|
||||
|
||||
test("a signal that is aborted already rejects without calling Go", async () => {
|
||||
const { sent, runtime } = setup();
|
||||
const ac = new AbortController();
|
||||
ac.abort();
|
||||
await expect(runtime.callWith("Greeter.Greet", ["bun"], { signal: ac.signal })).rejects.toBeDefined();
|
||||
expect(sent.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("events", () => {
|
||||
test("on / once / unsubscribe", () => {
|
||||
const { runtime, internal } = setup();
|
||||
const seen: unknown[] = [];
|
||||
const off = runtime.on("tick", (v) => seen.push(["on", v]));
|
||||
runtime.once("tick", (v) => seen.push(["once", v]));
|
||||
|
||||
internal.receive({ t: "event", n: "tick", p: 1 });
|
||||
internal.receive({ t: "event", n: "tick", p: 2 });
|
||||
expect(seen).toEqual([
|
||||
["on", 1],
|
||||
["once", 1],
|
||||
["on", 2],
|
||||
]);
|
||||
|
||||
off();
|
||||
internal.receive({ t: "event", n: "tick", p: 3 });
|
||||
expect(seen.length).toBe(3);
|
||||
});
|
||||
|
||||
test("the same listener can subscribe twice", () => {
|
||||
const { runtime, internal } = setup();
|
||||
let n = 0;
|
||||
const fn = () => n++;
|
||||
const off1 = runtime.on("x", fn);
|
||||
runtime.on("x", fn);
|
||||
internal.receive({ t: "event", n: "x" });
|
||||
off1();
|
||||
internal.receive({ t: "event", n: "x" });
|
||||
expect(n).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("channels", () => {
|
||||
type AckMsg = Extract<Outgoing, { t: "chan-ack" }>;
|
||||
type CloseMsg = Extract<Outgoing, { t: "chan-close" }>;
|
||||
|
||||
test("stream values to onmessage, in order, until Go closes them", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const got: unknown[] = [];
|
||||
let closed = 0;
|
||||
const ch = runtime.channel<number>((v) => got.push(v));
|
||||
ch.onclose = () => closed++;
|
||||
const p = runtime.call("Svc.Stream", "x", ch);
|
||||
const { id, k, a } = sent[0] as CallMsg;
|
||||
expect(a).toEqual(["x", 1]); // the channel goes as its id
|
||||
|
||||
internal.receive([
|
||||
{ t: "chan", c: 1, k, p: 1 },
|
||||
{ t: "chan", c: 1, k: "stale", p: 99 },
|
||||
{ t: "chan", c: 1, k, p: 2, a: 1 },
|
||||
]);
|
||||
expect(got).toEqual([1, 2]);
|
||||
expect(sent[1]).toEqual({ t: "chan-ack", c: 1, k, n: 2 } satisfies AckMsg);
|
||||
|
||||
internal.receive([
|
||||
{ t: "chan", c: 1, k, end: true },
|
||||
{ t: "reply", id, k, ok: true },
|
||||
]);
|
||||
await p;
|
||||
expect(ch.closed).toBe(true);
|
||||
expect(closed).toBe(1);
|
||||
internal.receive({ t: "chan", c: 1, k, p: 3 }); // after the end
|
||||
expect(got).toEqual([1, 2]);
|
||||
});
|
||||
|
||||
test("iterate values, including those that arrived first", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const ch = runtime.channel<string>();
|
||||
runtime.call("Svc.Stream", ch);
|
||||
const { k } = sent[0] as CallMsg;
|
||||
internal.receive([
|
||||
{ t: "chan", c: 1, k, p: "a" },
|
||||
{ t: "chan", c: 1, k, p: "b", a: 1 },
|
||||
]);
|
||||
expect(sent.length).toBe(1); // not taken yet: no acknowledgment
|
||||
const got: string[] = [];
|
||||
const loop = (async () => {
|
||||
for await (const v of ch) got.push(v);
|
||||
})();
|
||||
await Promise.resolve();
|
||||
expect(sent[1]).toMatchObject({ t: "chan-ack", n: 2 });
|
||||
internal.receive([
|
||||
{ t: "chan", c: 1, k, p: "c" },
|
||||
{ t: "chan", c: 1, k, end: true },
|
||||
]);
|
||||
await loop;
|
||||
expect(got).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
test("leaving the loop closes the channel", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const ch = runtime.channel<number>();
|
||||
runtime.call("Svc.Stream", ch);
|
||||
const { k } = sent[0] as CallMsg;
|
||||
internal.receive([
|
||||
{ t: "chan", c: 1, k, p: 1 },
|
||||
{ t: "chan", c: 1, k, p: 2 },
|
||||
]);
|
||||
for await (const v of ch) {
|
||||
if (v === 1) break;
|
||||
}
|
||||
expect(ch.closed).toBe(true);
|
||||
expect(sent[1]).toEqual({ t: "chan-close", c: 1, k } satisfies CloseMsg);
|
||||
// A closed channel can not be passed again.
|
||||
await expect(runtime.call("Svc.Stream", ch)).rejects.toThrow("one call");
|
||||
});
|
||||
|
||||
test("onmessage and a waiting iterator both get their due", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const ch = runtime.channel<number>();
|
||||
runtime.call("Svc.Stream", ch);
|
||||
const { k } = sent[0] as CallMsg;
|
||||
const it = ch[Symbol.asyncIterator]();
|
||||
const next = it.next();
|
||||
internal.receive({ t: "chan", c: 1, k, p: 1 });
|
||||
expect(await next).toEqual({ value: 1, done: false });
|
||||
const got: number[] = [];
|
||||
ch.onmessage = (v) => got.push(v);
|
||||
const pending = it.next();
|
||||
internal.receive([
|
||||
{ t: "chan", c: 1, k, p: 2 },
|
||||
{ t: "chan", c: 1, k, end: true },
|
||||
]);
|
||||
expect(got).toEqual([2]);
|
||||
expect(await pending).toEqual({ value: undefined, done: true });
|
||||
});
|
||||
|
||||
for (const failure of ["duplicate", "serialization"]) {
|
||||
test(`a channel can be used after ${failure} rejects before sending`, async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const got: unknown[] = [];
|
||||
const ch = runtime.channel((value) => got.push(value));
|
||||
const bad = failure === "duplicate"
|
||||
? runtime.call("Svc.Stream", ch, ch)
|
||||
: runtime.call("Svc.Stream", ch, 1n);
|
||||
await expect(bad).rejects.toThrow();
|
||||
expect(sent).toHaveLength(0);
|
||||
expect(ch.closed).toBe(false);
|
||||
|
||||
const pending = runtime.call("Svc.Stream", ch);
|
||||
const reply = pending.catch((err) => err);
|
||||
expect(sent).toHaveLength(1);
|
||||
const { id, k, a } = sent[0] as CallMsg;
|
||||
const channelID = a[0] as number;
|
||||
internal.receive([
|
||||
{ t: "chan", c: channelID, k, p: "value" },
|
||||
{ t: "chan", c: channelID, k, end: true },
|
||||
{ t: "reply", id, k, ok: true },
|
||||
]);
|
||||
expect(await reply).toBeUndefined();
|
||||
expect(got).toEqual(["value"]);
|
||||
expect(ch.closed).toBe(true);
|
||||
});
|
||||
}
|
||||
|
||||
test("a failed call ends its channels", async () => {
|
||||
const { sent, runtime, internal } = setup();
|
||||
const ch = runtime.channel();
|
||||
const p = runtime.call("Svc.Missing", ch);
|
||||
const { id, k } = sent[0] as CallMsg;
|
||||
const done = (async () => {
|
||||
for await (const _ of ch);
|
||||
})();
|
||||
internal.receive({ t: "reply", id, k, ok: false, e: "method Svc.Missing is not bound" });
|
||||
await expect(p).rejects.toThrow("not bound");
|
||||
await done;
|
||||
expect(ch.closed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test("a page shown again fails the calls it left unanswered, and ends their channels", async () => {
|
||||
const { sent, runtime, internal, restored } = setup();
|
||||
const ch = runtime.channel();
|
||||
const abort = new AbortController();
|
||||
const a = runtime.call("Svc.Slow", ch);
|
||||
const b = runtime.callWith("Svc.Slow", [], { signal: abort.signal });
|
||||
const [ma, mb] = sent as CallMsg[];
|
||||
restored();
|
||||
const err = (await a.catch((e) => e)) as CallError;
|
||||
expect(err).toBeInstanceOf(CallError);
|
||||
expect(err.method).toBe("Svc.Slow");
|
||||
await expect(b).rejects.toThrow("the page was left");
|
||||
expect(ch.closed).toBe(true);
|
||||
|
||||
// Their late replies, and a signal that aborts, are of no use.
|
||||
internal.receive([
|
||||
{ t: "reply", id: ma!.id, k: ma!.k, ok: true, v: "late" },
|
||||
{ t: "reply", id: mb!.id, k: mb!.k, ok: true, v: "late" },
|
||||
]);
|
||||
abort.abort();
|
||||
expect(sent.length).toBe(2);
|
||||
|
||||
// The page calls again as before.
|
||||
const c = runtime.call("Svc.Fast");
|
||||
const mc = sent[2] as CallMsg;
|
||||
expect(mc.id).toBe(3);
|
||||
internal.receive({ t: "reply", id: mc.id, k: mc.k, ok: true, v: "ok" });
|
||||
expect(await c).toBe("ok");
|
||||
});
|
||||
|
||||
test("runtime object is frozen", () => {
|
||||
const { runtime } = setup();
|
||||
expect(runtime.platform).toBe("darwin");
|
||||
expect(runtime.windowId).toBe(7);
|
||||
expect(Object.isFrozen(runtime)).toBe(true);
|
||||
expect(Object.isFrozen(runtime.window)).toBe(true);
|
||||
});
|
||||
|
||||
test("preferences are the latest Go told, before listeners hear them", () => {
|
||||
const { runtime, internal } = setup();
|
||||
expect(runtime.preferences).toEqual({
|
||||
accent: null,
|
||||
reduceMotion: false,
|
||||
reduceTransparency: false,
|
||||
highContrast: false,
|
||||
textScale: 1,
|
||||
});
|
||||
const p = { accent: "#ff8000", reduceMotion: true, reduceTransparency: true, highContrast: false, textScale: 1.5 };
|
||||
let seen: unknown;
|
||||
runtime.on("mygo:preferences", () => (seen = runtime.preferences));
|
||||
internal.receive({ t: "event", n: "mygo:preferences", p });
|
||||
expect(runtime.preferences).toEqual(p);
|
||||
expect(seen).toEqual(p);
|
||||
});
|
||||
|
||||
describe("locale", () => {
|
||||
test("comes from the configuration, then from the event", () => {
|
||||
const { runtime, internal } = setup();
|
||||
expect(runtime.locale).toBe("en");
|
||||
expect(runtime.dir).toBe("ltr");
|
||||
const seen: unknown[] = [];
|
||||
runtime.on("mygo:locale", (p) => seen.push(p));
|
||||
internal.receive({ t: "event", n: "mygo:locale", p: { locale: "ar", dir: "rtl" } });
|
||||
expect(seen).toEqual([{ locale: "ar", dir: "rtl" }]);
|
||||
expect(runtime.locale).toBe("ar");
|
||||
expect(runtime.dir).toBe("rtl");
|
||||
// A payload that is no language changes nothing.
|
||||
internal.receive({ t: "event", n: "mygo:locale", p: 7 });
|
||||
expect(runtime.locale).toBe("ar");
|
||||
expect(seen.length).toBe(1);
|
||||
});
|
||||
|
||||
test("the language the page has tells no listener", () => {
|
||||
const { runtime, internal } = setup();
|
||||
const seen: string[] = [];
|
||||
runtime.on<{ locale: string }>("mygo:locale", (p) => seen.push(p.locale));
|
||||
// As the page loads, Go tells it the language its configuration has.
|
||||
internal.receive({ t: "event", n: "mygo:locale", p: { locale: "en", dir: "ltr" } });
|
||||
expect(seen).toEqual([]);
|
||||
internal.receive({ t: "event", n: "mygo:locale", p: { locale: "ja", dir: "ltr" } });
|
||||
internal.receive({ t: "event", n: "mygo:locale", p: { locale: "ja", dir: "ltr" } });
|
||||
expect(seen).toEqual(["ja"]);
|
||||
});
|
||||
});
|
||||
+402
@@ -0,0 +1,402 @@
|
||||
import type {
|
||||
BridgeConfig,
|
||||
CallOptions,
|
||||
Channel,
|
||||
Direction,
|
||||
Incoming,
|
||||
LocaleChange,
|
||||
Outgoing,
|
||||
Runtime,
|
||||
ThemePreferences,
|
||||
} from "./types";
|
||||
|
||||
type Pending = {
|
||||
method: string;
|
||||
resolve: (v: any) => void;
|
||||
reject: (e: unknown) => void;
|
||||
channels?: ChannelState[];
|
||||
/** Told when the call is over, to let go of what it holds. */
|
||||
done?: () => void;
|
||||
};
|
||||
type Listener = (payload: any) => void;
|
||||
|
||||
/** The side of a channel that Go messages reach. */
|
||||
interface ChannelState {
|
||||
/** Set when the channel is passed to a call. */
|
||||
id: number;
|
||||
readonly closed: boolean;
|
||||
/** Delivers a value; ask requests an acknowledgment once it is taken. */
|
||||
push(value: unknown, ask: boolean): void;
|
||||
/** Go closed the channel. */
|
||||
end(): void;
|
||||
}
|
||||
|
||||
/** Reports an error thrown by page code without stopping the runtime. */
|
||||
const report = (err: unknown) =>
|
||||
setTimeout(() => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
/** The reason an aborted signal gives: its own, or a plain error. */
|
||||
function abortReason(signal: AbortSignal): unknown {
|
||||
if (signal.reason !== undefined) return signal.reason;
|
||||
return new Error("mygo: the call was aborted");
|
||||
}
|
||||
|
||||
/** Internal API called by the Go side through `window.__mygo`. */
|
||||
export interface Internal {
|
||||
/** Delivers one or more messages from Go. */
|
||||
receive(messages: Incoming | Incoming[]): void;
|
||||
}
|
||||
|
||||
/** Error thrown by `call` when the Go method returns an error. */
|
||||
export class CallError extends Error {
|
||||
constructor(
|
||||
readonly method: string,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "CallError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the renderer runtime. `post` delivers a serialized message to the
|
||||
* Go side. Kept free of DOM access so it can be unit tested.
|
||||
*/
|
||||
export function createRuntime(
|
||||
config: BridgeConfig,
|
||||
post: (message: string) => void,
|
||||
): { runtime: Runtime; internal: Internal; restored: () => void } {
|
||||
// A per-page token keeps replies addressed to a previous page (before a
|
||||
// navigation) from resolving promises of the current one.
|
||||
const token = Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||
const pending = new Map<number, Pending>();
|
||||
const listeners = new Map<string, Set<Listener>>();
|
||||
// The desktop's preferences, which Go tells at document start and on
|
||||
// every change; the defaults stand until then.
|
||||
let preferences: ThemePreferences = {
|
||||
accent: null,
|
||||
reduceMotion: false,
|
||||
reduceTransparency: false,
|
||||
highContrast: false,
|
||||
textScale: 1,
|
||||
};
|
||||
let seq = 0;
|
||||
// Channels passed to calls, by id, and the state of every channel.
|
||||
const channels = new Map<number, ChannelState>();
|
||||
const states = new WeakMap<object, ChannelState>();
|
||||
let channelSeq = 0;
|
||||
// The language the app shows: the configuration tells it at document
|
||||
// start, and the mygo:locale event when it changes.
|
||||
let locale = config.locale || "en";
|
||||
let dir: Direction = config.dir === "rtl" ? "rtl" : "ltr";
|
||||
// Whether the window is drawn as active: pages start active, and the
|
||||
// mygo:window-active event tells otherwise.
|
||||
let windowActive = true;
|
||||
|
||||
const send = (message: Outgoing) => post(JSON.stringify(message));
|
||||
|
||||
const call = <T>(method: string, ...args: unknown[]): Promise<T> => sendCall<T>(method, args);
|
||||
|
||||
// callWith calls a bound Go method, which the page may cancel with the
|
||||
// signal of the options: Go is told to cancel the call, and the promise
|
||||
// rejects with the signal's reason.
|
||||
const callWith = <T>(method: string, args: unknown[], options?: CallOptions): Promise<T> => {
|
||||
const signal = options?.signal;
|
||||
if (!signal) return sendCall<T>(method, args);
|
||||
if (signal.aborted) return Promise.reject(abortReason(signal));
|
||||
return sendCall<T>(method, args, signal);
|
||||
};
|
||||
|
||||
const sendCall = <T>(method: string, args: unknown[], signal?: AbortSignal): Promise<T> => {
|
||||
const id = ++seq;
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
// Channels among the arguments stream values back.
|
||||
let chans: ChannelState[] | undefined;
|
||||
for (const arg of args) {
|
||||
const ch = typeof arg === "object" && arg !== null ? states.get(arg) : undefined;
|
||||
if (!ch) continue;
|
||||
if (ch.id || ch.closed) {
|
||||
chans?.forEach((c) => {
|
||||
channels.delete(c.id);
|
||||
c.id = 0;
|
||||
});
|
||||
reject(new Error("mygo: a channel can be passed to one call, before it is closed"));
|
||||
return;
|
||||
}
|
||||
ch.id = ++channelSeq;
|
||||
channels.set(ch.id, ch);
|
||||
(chans ??= []).push(ch);
|
||||
}
|
||||
// A signal that aborts tells Go to cancel the call, and rejects the
|
||||
// promise here: the reply of a canceled call is of no use.
|
||||
let onAbort: (() => void) | undefined;
|
||||
let done: (() => void) | undefined;
|
||||
if (signal) {
|
||||
onAbort = () => {
|
||||
pending.delete(id);
|
||||
chans?.forEach((c) => {
|
||||
channels.delete(c.id);
|
||||
c.id = 0;
|
||||
});
|
||||
try {
|
||||
send({ t: "cancel", id, k: token });
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
reject(abortReason(signal));
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
done = () => signal.removeEventListener("abort", onAbort!);
|
||||
}
|
||||
pending.set(id, { method, resolve, reject, channels: chans, done });
|
||||
try {
|
||||
send({ t: "call", id, k: token, m: method, a: args, cancel: signal ? true : undefined });
|
||||
} catch (err) {
|
||||
pending.delete(id);
|
||||
if (onAbort) signal?.removeEventListener("abort", onAbort);
|
||||
chans?.forEach((c) => {
|
||||
channels.delete(c.id);
|
||||
c.id = 0;
|
||||
});
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const channel = <T>(onmessage?: (value: T) => void): Channel<T> => {
|
||||
let handler: ((value: T) => void) | null = null;
|
||||
let closed = false;
|
||||
// Values not taken yet, and next() calls waiting for one.
|
||||
let queue: { value: T; n: number; ask: boolean }[] = [];
|
||||
const waiting: ((result: IteratorResult<T>) => void)[] = [];
|
||||
let received = 0;
|
||||
|
||||
// Tells Go the page took the values up to the n-th.
|
||||
const ack = (n: number) => {
|
||||
try {
|
||||
send({ t: "chan-ack", c: state.id, k: token, n });
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
};
|
||||
const handle = (value: T) => {
|
||||
try {
|
||||
handler!(value);
|
||||
} catch (err) {
|
||||
report(err);
|
||||
}
|
||||
};
|
||||
const finish = () => {
|
||||
channels.delete(state.id);
|
||||
if (queue.length === 0) waiting.splice(0).forEach((w) => w({ value: undefined, done: true }));
|
||||
if (ch.onclose) {
|
||||
try {
|
||||
ch.onclose();
|
||||
} catch (err) {
|
||||
report(err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const state: ChannelState = {
|
||||
id: 0,
|
||||
get closed() {
|
||||
return closed;
|
||||
},
|
||||
push(value, ask) {
|
||||
if (closed) return;
|
||||
const n = ++received;
|
||||
if (handler) handle(value as T);
|
||||
else if (waiting.length > 0) waiting.shift()!({ value: value as T, done: false });
|
||||
else return void queue.push({ value: value as T, n, ask });
|
||||
if (ask) ack(n);
|
||||
},
|
||||
end() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
finish(); // values not taken yet can still be iterated
|
||||
},
|
||||
};
|
||||
|
||||
const ch = {
|
||||
get onmessage() {
|
||||
return handler;
|
||||
},
|
||||
set onmessage(fn: ((value: T) => void) | null) {
|
||||
handler = fn;
|
||||
// Values that arrived earlier come first.
|
||||
while (handler && queue.length > 0) {
|
||||
const q = queue.shift()!;
|
||||
handle(q.value);
|
||||
if (q.ask) ack(q.n);
|
||||
}
|
||||
},
|
||||
onclose: null as (() => void) | null,
|
||||
get closed() {
|
||||
return closed;
|
||||
},
|
||||
close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
queue = [];
|
||||
if (state.id) {
|
||||
try {
|
||||
send({ t: "chan-close", c: state.id, k: token });
|
||||
} catch {
|
||||
// The page is being torn down.
|
||||
}
|
||||
}
|
||||
finish();
|
||||
},
|
||||
[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
return {
|
||||
next() {
|
||||
const q = queue.shift();
|
||||
if (q) {
|
||||
if (q.ask) ack(q.n);
|
||||
return Promise.resolve({ value: q.value, done: false });
|
||||
}
|
||||
if (closed) return Promise.resolve({ value: undefined, done: true });
|
||||
return new Promise((resolve) => waiting.push(resolve));
|
||||
},
|
||||
// Leaving a for await loop early stops the stream.
|
||||
return() {
|
||||
ch.close();
|
||||
return Promise.resolve({ value: undefined, done: true });
|
||||
},
|
||||
};
|
||||
},
|
||||
// Goes to Go as its id.
|
||||
toJSON: () => state.id,
|
||||
};
|
||||
states.set(ch, state);
|
||||
if (onmessage) ch.onmessage = onmessage;
|
||||
return ch;
|
||||
};
|
||||
|
||||
const on = (event: string, listener: Listener) => {
|
||||
if (typeof listener !== "function") throw new TypeError("listener must be a function");
|
||||
let set = listeners.get(event);
|
||||
if (!set) listeners.set(event, (set = new Set()));
|
||||
// Wrap so the same function can be subscribed twice and removed once.
|
||||
const entry: Listener = (p) => listener(p);
|
||||
set.add(entry);
|
||||
return () => {
|
||||
set.delete(entry);
|
||||
if (set.size === 0 && listeners.get(event) === set) listeners.delete(event);
|
||||
};
|
||||
};
|
||||
|
||||
const once = (event: string, listener: Listener) => {
|
||||
const off = on(event, (p) => {
|
||||
off();
|
||||
listener(p);
|
||||
});
|
||||
return off;
|
||||
};
|
||||
|
||||
const internal: Internal = {
|
||||
receive(messages) {
|
||||
for (const msg of Array.isArray(messages) ? messages : [messages]) {
|
||||
if (msg.t === "event") {
|
||||
// Before the listeners, which may read it.
|
||||
if (msg.n === "mygo:preferences") preferences = Object.freeze(msg.p as ThemePreferences);
|
||||
if (msg.n === "mygo:window-active") {
|
||||
if (typeof msg.p !== "boolean") continue;
|
||||
// Listeners hear changes only.
|
||||
if (msg.p === windowActive) continue;
|
||||
windowActive = msg.p;
|
||||
}
|
||||
if (msg.n === "mygo:locale") {
|
||||
const p = msg.p as Partial<LocaleChange> | undefined;
|
||||
if (typeof p?.locale !== "string") continue;
|
||||
// Go tells a page the language again as it loads, for one that
|
||||
// started loading as it changed: listeners hear of a language
|
||||
// the page did not have only.
|
||||
if (p.locale === locale) continue;
|
||||
locale = p.locale;
|
||||
dir = p.dir === "rtl" ? "rtl" : "ltr";
|
||||
}
|
||||
const set = listeners.get(msg.n);
|
||||
if (!set) continue;
|
||||
for (const listener of [...set]) {
|
||||
try {
|
||||
listener(msg.p);
|
||||
} catch (err) {
|
||||
// One failing listener must not break the others.
|
||||
report(err);
|
||||
}
|
||||
}
|
||||
} else if (msg.t === "chan") {
|
||||
if (msg.k !== token) continue;
|
||||
const ch = channels.get(msg.c);
|
||||
if (!ch) continue;
|
||||
if (msg.end) ch.end();
|
||||
else ch.push(msg.p, msg.a === 1);
|
||||
} else if (msg.t === "reply") {
|
||||
if (msg.k !== token) continue;
|
||||
const p = pending.get(msg.id);
|
||||
if (!p) continue;
|
||||
pending.delete(msg.id);
|
||||
p.done?.();
|
||||
// Go closed the call's channels before replying, unless the call
|
||||
// failed before they were made.
|
||||
p.channels?.forEach((c) => c.end());
|
||||
if (msg.ok) p.resolve(msg.v);
|
||||
else p.reject(new CallError(p.method, msg.e ?? "unknown error"));
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
// The page shows again from the web view's cache of pages, as going
|
||||
// back to it does: Go canceled the calls it had not answered as the page
|
||||
// left, and their replies went to the page that took its place.
|
||||
const restored = () => {
|
||||
const left = [...pending.values()];
|
||||
pending.clear();
|
||||
for (const p of left) {
|
||||
p.done?.();
|
||||
p.channels?.forEach((c) => c.end());
|
||||
p.reject(new CallError(p.method, "the page was left before the call returned"));
|
||||
}
|
||||
};
|
||||
|
||||
const win = (op: string) => () => call<any>(`mygo:window.${op}`);
|
||||
const runtime: Runtime = Object.freeze({
|
||||
call,
|
||||
callWith,
|
||||
channel,
|
||||
on,
|
||||
once,
|
||||
platform: config.platform,
|
||||
windowId: config.windowId,
|
||||
version: config.version,
|
||||
get preferences() {
|
||||
return preferences;
|
||||
},
|
||||
get locale() {
|
||||
return locale;
|
||||
},
|
||||
get dir() {
|
||||
return dir;
|
||||
},
|
||||
get windowActive() {
|
||||
return windowActive;
|
||||
},
|
||||
window: Object.freeze({
|
||||
minimize: win("Minimize"),
|
||||
maximize: win("Maximize"),
|
||||
unmaximize: win("Unmaximize"),
|
||||
toggleMaximize: win("ToggleMaximize"),
|
||||
isMaximized: win("IsMaximized"),
|
||||
toggleFullScreen: win("ToggleFullScreen"),
|
||||
close: win("Close"),
|
||||
setTitle: (title: string) => call<void>("mygo:window.SetTitle", title),
|
||||
}),
|
||||
});
|
||||
|
||||
return { runtime, internal, restored };
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { fillStyleHex, type Meta, pick, reporter } from "./theme-color";
|
||||
|
||||
const meta = (attrs: Record<string, string>): Meta => ({ getAttribute: (n) => attrs[n] ?? null });
|
||||
// Colors named as the test likes; anything else is not a color.
|
||||
const parse = (v: string) => ({ red: "#ff0000ff", blue: "#0000ffff" })[v.trim()] ?? null;
|
||||
|
||||
describe("pick", () => {
|
||||
const dark = (media: string) => media === "(prefers-color-scheme: dark)";
|
||||
|
||||
test("takes the first meta whose media matches", () => {
|
||||
const metas = [
|
||||
meta({ content: "red", media: "(prefers-color-scheme: light)" }),
|
||||
meta({ content: "blue", media: " (prefers-color-scheme: dark) " }),
|
||||
];
|
||||
expect(pick(metas, dark, parse)).toBe("#0000ffff");
|
||||
expect(pick(metas, (m) => m === "(prefers-color-scheme: light)", parse)).toBe("#ff0000ff");
|
||||
});
|
||||
|
||||
test("an absent or empty media matches", () => {
|
||||
expect(pick([meta({ content: "red" })], () => false, parse)).toBe("#ff0000ff");
|
||||
expect(pick([meta({ content: "red", media: " " })], () => false, parse)).toBe("#ff0000ff");
|
||||
});
|
||||
|
||||
test("skips metas that are not colors", () => {
|
||||
expect(pick([meta({ content: "nope" }), meta({}), meta({ content: " blue " })], dark, parse)).toBe("#0000ffff");
|
||||
expect(pick([meta({ content: "nope" })], dark, parse)).toBeNull();
|
||||
expect(pick([], dark, parse)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("fillStyleHex", () => {
|
||||
test("reads what engines serialize", () => {
|
||||
expect(fillStyleHex("#1E90FF")).toBe("#1e90ffff");
|
||||
expect(fillStyleHex("rgba(255, 0, 0, 0.5)")).toBe("#ff000080");
|
||||
expect(fillStyleHex("rgba(0, 0, 0, 0)")).toBe("#00000000");
|
||||
expect(fillStyleHex("rgb(1 2 3 / 1)")).toBe("#010203ff");
|
||||
expect(fillStyleHex("rgb(1, 2, 3)")).toBe("#010203ff");
|
||||
});
|
||||
|
||||
test("leaves other color spaces to the canvas", () => {
|
||||
expect(fillStyleHex("oklch(0.7 0.1 200)")).toBeNull();
|
||||
expect(fillStyleHex("color(display-p3 1 0 0)")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("reporter", () => {
|
||||
test("tells changes only", () => {
|
||||
const sent: string[] = [];
|
||||
const r = reporter((c) => sent.push(c));
|
||||
r.report("#ff0000ff");
|
||||
r.report("#ff0000ff");
|
||||
r.ready("#ff0000ff");
|
||||
r.report("#0000ffff");
|
||||
r.report(null);
|
||||
r.report(null);
|
||||
expect(sent).toEqual(["#ff0000ff", "#0000ffff", ""]);
|
||||
});
|
||||
|
||||
test("tells of no color once the DOM is ready", () => {
|
||||
const sent: string[] = [];
|
||||
const r = reporter((c) => sent.push(c));
|
||||
r.report(null); // at document start: the previous page's may be the same
|
||||
expect(sent).toEqual([]);
|
||||
r.ready(null);
|
||||
expect(sent).toEqual([""]);
|
||||
});
|
||||
|
||||
test("tells of a color removed before the DOM is ready", () => {
|
||||
const sent: string[] = [];
|
||||
const r = reporter((c) => sent.push(c));
|
||||
r.report("#ff0000ff");
|
||||
r.report(null);
|
||||
r.ready(null);
|
||||
expect(sent).toEqual(["#ff0000ff", ""]);
|
||||
});
|
||||
});
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
// The page's theme color (Page.ThemeColor in Go): the content of the first
|
||||
// <meta name="theme-color"> in the document's head whose media is absent,
|
||||
// empty or matches, and whose content is a color, as browsers pick it. The
|
||||
// engine parses the color, so every CSS color works, and Go hears the color
|
||||
// as #rrggbbaa, or "" for none, whenever it changes.
|
||||
|
||||
/** A meta element, as far as picking a theme color goes. */
|
||||
export interface Meta {
|
||||
getAttribute(name: string): string | null;
|
||||
}
|
||||
|
||||
/** Picks the theme color of the metas named theme-color, in tree order: the
|
||||
* first whose media matches and whose content is a color, as parse returns it,
|
||||
* else null. */
|
||||
export function pick(
|
||||
metas: Iterable<Meta>,
|
||||
matches: (media: string) => boolean,
|
||||
parse: (value: string) => string | null,
|
||||
): string | null {
|
||||
for (const m of metas) {
|
||||
const media = m.getAttribute("media")?.trim();
|
||||
if (media && !matches(media)) continue;
|
||||
const c = parse(m.getAttribute("content") ?? "");
|
||||
if (c !== null) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const hex2 = (n: number) => Math.round(Math.min(Math.max(n, 0), 255)).toString(16).padStart(2, "0");
|
||||
|
||||
/** Returns a canvas's fillStyle as #rrggbbaa: engines serialize sRGB colors as
|
||||
* #rrggbb, or rgba(r, g, b, a) when they are translucent. Other color spaces
|
||||
* (oklch(), color(display-p3 …)) give null. */
|
||||
export function fillStyleHex(s: string): string | null {
|
||||
if (/^#[0-9a-f]{6}$/i.test(s)) return s.toLowerCase() + "ff";
|
||||
const m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+))?\s*\)$/i.exec(s);
|
||||
if (!m) return null;
|
||||
return "#" + hex2(+m[1]!) + hex2(+m[2]!) + hex2(+m[3]!) + hex2(m[4] === undefined ? 255 : +m[4] * 255);
|
||||
}
|
||||
|
||||
/** Tells Go of the theme color when it changes. Before the DOM is ready it
|
||||
* tells only of a color, so that going from a page to another of the same
|
||||
* color tells nothing; once it is ready, of none too. */
|
||||
export function reporter(post: (color: string) => void) {
|
||||
let last: string | null | undefined; // undefined: told nothing yet
|
||||
let ready = false;
|
||||
const report = (c: string | null) => {
|
||||
if (c === last || (c === null && last === undefined && !ready)) return;
|
||||
last = c;
|
||||
post(c ?? "");
|
||||
};
|
||||
return {
|
||||
report,
|
||||
/** The DOM is ready: the color is known, none included. */
|
||||
ready(c: string | null) {
|
||||
ready = true;
|
||||
report(c);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Watches the theme color of the document: its head's metas with a
|
||||
* MutationObserver, and their media with matchMedia, so that a change of the
|
||||
* system's appearance picks the meta for it. Returns the function to call
|
||||
* when the DOM is ready, which tells Go the color it found: again, for a
|
||||
* page Go took for a new one, whatever it told before. */
|
||||
export function watchThemeColor(post: (color: string) => void): (again?: boolean) => void {
|
||||
let r = reporter(post);
|
||||
const queries = new Map<string, MediaQueryList>();
|
||||
const matches = (media: string) => {
|
||||
let q = queries.get(media);
|
||||
if (!q) {
|
||||
q = matchMedia(media);
|
||||
if (q.addEventListener) q.addEventListener("change", update);
|
||||
else q.addListener(update); // WebKit before 14
|
||||
queries.set(media, q);
|
||||
}
|
||||
return q.matches;
|
||||
};
|
||||
const current = () =>
|
||||
document.head ? pick(document.head.querySelectorAll('meta[name="theme-color" i]'), matches, parseColor) : null;
|
||||
function update() {
|
||||
r.report(current());
|
||||
}
|
||||
|
||||
// The head only, rather than the whole document, so that pages changing
|
||||
// their body pay nothing; the document and its root element for a head
|
||||
// that comes, or is replaced, later.
|
||||
const observer = new MutationObserver((records) => {
|
||||
let changed = false;
|
||||
for (const rec of records) {
|
||||
if (rec.target === document || rec.target === document.documentElement) {
|
||||
observe();
|
||||
changed = true;
|
||||
} else if (rec.type === "attributes") {
|
||||
changed ||= isMeta(rec.target);
|
||||
} else {
|
||||
changed ||= hasMeta(rec.addedNodes) || hasMeta(rec.removedNodes);
|
||||
}
|
||||
}
|
||||
if (changed) update();
|
||||
});
|
||||
let head: HTMLHeadElement | null = null;
|
||||
let root: Element | null = null;
|
||||
function observe() {
|
||||
if (document.documentElement !== root && (root = document.documentElement)) {
|
||||
observer.observe(root, { childList: true });
|
||||
}
|
||||
if (document.head !== head && (head = document.head)) {
|
||||
observer.observe(head, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ["name", "content", "media"],
|
||||
});
|
||||
}
|
||||
}
|
||||
observer.observe(document, { childList: true });
|
||||
observe();
|
||||
update();
|
||||
return (again) => {
|
||||
if (again) r = reporter(post);
|
||||
r.ready(current());
|
||||
};
|
||||
}
|
||||
|
||||
const isMeta = (n: Node) => (n as Element).localName === "meta";
|
||||
|
||||
function hasMeta(nodes: NodeList): boolean {
|
||||
for (let i = 0; i < nodes.length; i++) {
|
||||
const n = nodes[i]!;
|
||||
if (n.nodeType === 1 && (isMeta(n) || (n as Element).querySelector("meta"))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let ctx: CanvasRenderingContext2D | null | undefined;
|
||||
|
||||
/** Parses a CSS color as the engine does, with a canvas: its fillStyle keeps
|
||||
* its value when given something else than a color. Colors the engine does not
|
||||
* serialize as sRGB are drawn and read back. */
|
||||
function parseColor(value: string): string | null {
|
||||
value = value.trim();
|
||||
if (!value) return null;
|
||||
if (ctx === undefined) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = canvas.height = 1;
|
||||
ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||||
}
|
||||
if (!ctx) return null;
|
||||
ctx.fillStyle = "#000";
|
||||
ctx.fillStyle = value;
|
||||
if (ctx.fillStyle === "#000000") {
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.fillStyle = value;
|
||||
if (ctx.fillStyle === "#ffffff") return null; // not a color
|
||||
}
|
||||
const hex = fillStyleHex(String(ctx.fillStyle));
|
||||
if (hex) return hex;
|
||||
ctx.clearRect(0, 0, 1, 1);
|
||||
ctx.fillRect(0, 0, 1, 1);
|
||||
const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
|
||||
return "#" + hex2(r!) + hex2(g!) + hex2(b!) + hex2(a!);
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
// The public types are those of the mygo-runtime package.
|
||||
import type { Direction, Platform } from "../../runtime/src/types";
|
||||
import type { ContextTarget } from "./context-menu";
|
||||
import type { FitLimits } from "./fit-content";
|
||||
|
||||
export type {
|
||||
CallOptions,
|
||||
Channel,
|
||||
Direction,
|
||||
LocaleChange,
|
||||
Platform,
|
||||
Runtime,
|
||||
ThemePreferences,
|
||||
WindowControls,
|
||||
} from "../../runtime/src/types";
|
||||
|
||||
/** Configuration injected by the Go side in front of the bridge. */
|
||||
export interface BridgeConfig {
|
||||
platform: Platform;
|
||||
windowId: number;
|
||||
version: string;
|
||||
/** Prefixes every message, so Go can tell ours from other frames'. */
|
||||
secret: string;
|
||||
/** The language the app shows, e.g. "zh-Hans", and its direction. */
|
||||
locale: string;
|
||||
dir: Direction;
|
||||
/** The limits of a window that takes its content's size (FitContent), in
|
||||
* CSS pixels; absent for other windows. */
|
||||
fit?: FitLimits;
|
||||
}
|
||||
|
||||
/** Messages posted from the page to Go. */
|
||||
export type Outgoing =
|
||||
/** A call of the method m, whose reply has the id; cancel tells that
|
||||
* the page may cancel it with a signal. */
|
||||
| { t: "call"; id: number; k: string; m: string; a: unknown[]; cancel?: boolean }
|
||||
/** The page cancels the call with the id. */
|
||||
| { t: "cancel"; id: number; k: string }
|
||||
/** Channel c took the values up to the n-th. */
|
||||
| { t: "chan-ack"; c: number; k: string; n: number }
|
||||
| { t: "chan-close"; c: number; k: string }
|
||||
| { t: "dom-ready" }
|
||||
/** The page's theme color changed: #rrggbbaa, or "" for none. */
|
||||
| { t: "theme-color"; v: string }
|
||||
/** The size of the content of a window that takes it (FitContent), in CSS
|
||||
* pixels, scrollbars included. */
|
||||
| { t: "content-size"; w: number; h: number; sw: number; sh: number }
|
||||
| { t: "drag" }
|
||||
| { t: "dblclick" }
|
||||
/** A context menu opens at x, y, in CSS pixels of the viewport, on what
|
||||
* the rest tells (ContextTarget). */
|
||||
| ({ t: "context-menu"; x: number; y: number } & ContextTarget);
|
||||
|
||||
/** Messages delivered from Go to the page. */
|
||||
export type Incoming =
|
||||
| { t: "event"; n: string; p?: unknown }
|
||||
| { t: "reply"; id: number; k: string; ok: boolean; v?: unknown; e?: string }
|
||||
/** A value p of channel c, which asks for an acknowledgment with a, or its end. */
|
||||
| { t: "chan"; c: number; k: string; p?: unknown; a?: 1; end?: true };
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { createRuntime } from "./runtime";
|
||||
import { INACTIVE_ATTRIBUTE, markWindowActive } from "./window-active";
|
||||
|
||||
/** An element that keeps its attributes as toggleAttribute sets them. */
|
||||
function element() {
|
||||
const attrs = new Set<string>();
|
||||
return {
|
||||
attrs,
|
||||
toggleAttribute(name: string, force?: boolean) {
|
||||
const on = force ?? !attrs.has(name);
|
||||
if (on) attrs.add(name);
|
||||
else attrs.delete(name);
|
||||
return on;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("a page starts active, and its <html> follows the event", () => {
|
||||
const { runtime, internal } = createRuntime(
|
||||
{ platform: "darwin", windowId: 1, version: "0.0.0-test", secret: "s", locale: "en", dir: "ltr" },
|
||||
() => {},
|
||||
);
|
||||
const root = element();
|
||||
const seen: boolean[] = [];
|
||||
runtime.on<boolean>("mygo:window-active", (active) => {
|
||||
seen.push(runtime.windowActive);
|
||||
markWindowActive(root, active);
|
||||
});
|
||||
expect(runtime.windowActive).toBe(true);
|
||||
|
||||
internal.receive({ t: "event", n: "mygo:window-active", p: false });
|
||||
expect(runtime.windowActive).toBe(false);
|
||||
expect(root.attrs.has(INACTIVE_ATTRIBUTE)).toBe(true);
|
||||
// Told again, as a page loads in an inactive window: no listener hears it.
|
||||
internal.receive({ t: "event", n: "mygo:window-active", p: false });
|
||||
// A payload that is no state changes nothing.
|
||||
internal.receive({ t: "event", n: "mygo:window-active", p: "yes" });
|
||||
expect(runtime.windowActive).toBe(false);
|
||||
|
||||
internal.receive({ t: "event", n: "mygo:window-active", p: true });
|
||||
expect(runtime.windowActive).toBe(true);
|
||||
expect(root.attrs.has(INACTIVE_ATTRIBUTE)).toBe(false);
|
||||
// The listeners read the new state.
|
||||
expect(seen).toEqual([false, true]);
|
||||
});
|
||||
|
||||
test("a page without its <html> yet is left alone", () => {
|
||||
expect(() => markWindowActive(null, false)).not.toThrow();
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
/** The attribute of `<html>` that marks a page whose window is not drawn as
|
||||
* active, for CSS: `:root[data-mygo-window-inactive] .sidebar { … }`. */
|
||||
export const INACTIVE_ATTRIBUTE = "data-mygo-window-inactive";
|
||||
|
||||
/** Marks root, a page's `<html>`, as of a window drawn as active or not. */
|
||||
export function markWindowActive(root: Pick<Element, "toggleAttribute"> | null | undefined, active: boolean): void {
|
||||
root?.toggleAttribute(INACTIVE_ATTRIBUTE, !active);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# mygo-cli
|
||||
|
||||
The `mygo` command line tool of [MyGo](https://github.com/egoist/mygo), the
|
||||
desktop app framework for Go whose windows show web pages, in the system
|
||||
webview, or native UI written in Go, as prebuilt binaries for macOS, Linux
|
||||
and Windows (arm64 and x64).
|
||||
|
||||
Create a project, which depends on mygo-cli and runs it from its scripts:
|
||||
|
||||
```sh
|
||||
bunx mygo-cli init my-app # or: npx mygo-cli init my-app
|
||||
cd my-app
|
||||
bun run dev # mygo dev: the app with live reload
|
||||
bun run build # mygo build: the packaged app
|
||||
```
|
||||
|
||||
In a project that depends on mygo-cli, `bunx mygo <command>` runs its
|
||||
`mygo`. Or install it globally with `npm install -g mygo-cli`. The commands
|
||||
are those of the CLI installed with Go
|
||||
(`go install github.com/egoist/mygo/cmd/mygo@latest`): `init`, `dev`,
|
||||
`build`, `generate`, `install-skills`, `keygen` and `doctor`. Building apps
|
||||
still needs [Go](https://go.dev/dl/), which compiles them.
|
||||
|
||||
Outside such a project, run `bunx mygo-cli` or `npx mygo-cli` rather than
|
||||
`bunx mygo`: npm has an unrelated package named mygo.
|
||||
|
||||
## How it works
|
||||
|
||||
Each platform's binary is in a package of its own, such as
|
||||
`@egoist/mygo-cli-darwin-arm64`, which mygo-cli lists as an optional dependency:
|
||||
package managers install only the one that matches the machine. The `mygo`
|
||||
command then runs that binary. Set `MYGO_CLI_BINARY` to the path of another
|
||||
build of the CLI to use it instead.
|
||||
|
||||
## mygo.config.ts
|
||||
|
||||
`defineConfig` types the configuration of a project, `mygo.config.ts`:
|
||||
|
||||
```ts
|
||||
import { defineConfig } from "mygo-cli";
|
||||
|
||||
export default defineConfig({
|
||||
name: "My App",
|
||||
identifier: "com.example.myapp",
|
||||
devUrl: "http://localhost:5173",
|
||||
});
|
||||
```
|
||||
|
||||
## The binary
|
||||
|
||||
From JavaScript, `binaryPath()` returns the path of the binary:
|
||||
|
||||
```ts
|
||||
import { binaryPath } from "mygo-cli";
|
||||
|
||||
Bun.spawnSync([binaryPath(), "generate"]);
|
||||
```
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env node
|
||||
// Runs the mygo binary of this platform with the arguments of this script.
|
||||
import { spawn } from "node:child_process";
|
||||
import { binaryPath } from "../index.js";
|
||||
|
||||
let bin;
|
||||
try {
|
||||
bin = binaryPath();
|
||||
} catch (err) {
|
||||
console.error(err instanceof Error ? err.message : String(err));
|
||||
process.exit(1);
|
||||
}
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
if (process.platform !== "win32" && typeof process.execve === "function") {
|
||||
// Become the binary (Node.js 23.11 and later, Bun), so that signals and
|
||||
// the exit status are its own.
|
||||
process.execve(bin, [bin, ...args]);
|
||||
}
|
||||
|
||||
const child = spawn(bin, args, { stdio: "inherit" });
|
||||
// Ctrl+C reaches the binary from the terminal too: let it decide when to
|
||||
// exit, which mygo dev takes a moment for.
|
||||
process.on("SIGINT", () => {});
|
||||
process.on("SIGTERM", () => child.kill("SIGTERM"));
|
||||
child.on("error", (err) => {
|
||||
console.error(`mygo-cli: cannot run ${bin}: ${err.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
child.on("exit", (code, signal) => {
|
||||
if (signal) {
|
||||
process.removeAllListeners(signal);
|
||||
process.kill(process.pid, signal);
|
||||
} else {
|
||||
process.exit(code ?? 1);
|
||||
}
|
||||
});
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
// Builds the mygo binaries of the platform packages in npm/, for every
|
||||
// platform or for those given as arguments (e.g. `bun run build.ts
|
||||
// darwin-arm64`), and writes the manifests of mygo-cli and its platform
|
||||
// packages with the version of the Go module (mygo.Version), and their
|
||||
// license.
|
||||
import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { platforms } from "./index.js";
|
||||
|
||||
export const dir = import.meta.dir;
|
||||
const root = join(dir, "..", "..");
|
||||
|
||||
/** GOOS and GOARCH of each platform. */
|
||||
export const goTargets: Record<string, [goos: string, goarch: string]> = {
|
||||
"darwin-arm64": ["darwin", "arm64"],
|
||||
"darwin-x64": ["darwin", "amd64"],
|
||||
"linux-arm64": ["linux", "arm64"],
|
||||
"linux-x64": ["linux", "amd64"],
|
||||
"win32-arm64": ["windows", "arm64"],
|
||||
"win32-x64": ["windows", "amd64"],
|
||||
};
|
||||
|
||||
const osNames: Record<string, string> = { darwin: "macOS", linux: "Linux", win32: "Windows" };
|
||||
|
||||
const repository = { type: "git", url: "git+https://github.com/egoist/mygo.git" };
|
||||
|
||||
/** Returns mygo.Version, which every package is released with. */
|
||||
export async function version(): Promise<string> {
|
||||
const source = await readFile(join(root, "mygo.go"), "utf8");
|
||||
const match = source.match(/^const Version = "([^"]+)"$/m);
|
||||
if (!match?.[1]) throw new Error("mygo.go declares no Version");
|
||||
return match[1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of a platform package. Its scope keeps npm from taking
|
||||
* names such as mygo-cli-win32-x64 for spam.
|
||||
*/
|
||||
export function platformName(platform: string): string {
|
||||
return `@egoist/mygo-cli-${platform}`;
|
||||
}
|
||||
|
||||
/** Returns the directory of a platform package. */
|
||||
export function platformDir(platform: string): string {
|
||||
return join(dir, "npm", platform);
|
||||
}
|
||||
|
||||
/** Writes the manifests of mygo-cli and its platform packages. */
|
||||
export async function writeManifests(v: string): Promise<void> {
|
||||
const main = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
|
||||
main.version = v;
|
||||
main.optionalDependencies = Object.fromEntries(platforms.map((p) => [platformName(p), v]));
|
||||
await writeJSON(join(dir, "package.json"), main);
|
||||
for (const platform of platforms) {
|
||||
const [os, cpu] = platform.split("-") as [string, string];
|
||||
const name = platformName(platform);
|
||||
const description = `The ${osNames[os]} ${cpu} binary of mygo-cli`;
|
||||
await mkdir(platformDir(platform), { recursive: true });
|
||||
await writeJSON(join(platformDir(platform), "package.json"), {
|
||||
name,
|
||||
version: v,
|
||||
description,
|
||||
repository: { ...repository, directory: `packages/cli/npm/${platform}` },
|
||||
license: "MIT",
|
||||
os: [os],
|
||||
cpu: [cpu],
|
||||
files: ["bin"],
|
||||
preferUnplugged: true,
|
||||
});
|
||||
await copyFile(join(root, "LICENSE"), join(platformDir(platform), "LICENSE"));
|
||||
await writeFile(
|
||||
join(platformDir(platform), "README.md"),
|
||||
`# ${name}\n\n${description}, the command line tool of MyGo. Install\n` +
|
||||
`[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers\n` +
|
||||
`install the package of the platform they run on.\n`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds the binaries of platforms into their packages. */
|
||||
export async function build(targets: readonly string[] = platforms): Promise<void> {
|
||||
await writeManifests(await version());
|
||||
for (const platform of targets) await buildBinary(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the binary of a platform into its package, whose manifest
|
||||
* writeManifests wrote. It doesn't block the event loop, so that
|
||||
* scripts/publish.ts publishes other packages meanwhile.
|
||||
*/
|
||||
export async function buildBinary(platform: string): Promise<void> {
|
||||
const target = goTargets[platform];
|
||||
if (!target) throw new Error(`unknown platform ${platform}, want one of ${platforms.join(", ")}`);
|
||||
const [goos, goarch] = target;
|
||||
const bin = join(platformDir(platform), "bin", goos === "windows" ? "mygo.exe" : "mygo");
|
||||
console.log(`building ${platform}`);
|
||||
const go = Bun.spawn(["go", "build", "-trimpath", "-ldflags=-s -w", "-o", bin, "./cmd/mygo"], {
|
||||
cwd: root,
|
||||
env: { ...process.env, GOOS: goos, GOARCH: goarch, CGO_ENABLED: "0" },
|
||||
stdout: "inherit",
|
||||
stderr: "inherit",
|
||||
});
|
||||
if ((await go.exited) !== 0) throw new Error(`go build failed for ${platform}`);
|
||||
}
|
||||
|
||||
async function writeJSON(path: string, value: unknown): Promise<void> {
|
||||
await writeFile(path, JSON.stringify(value, null, 2) + "\n");
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
const args = process.argv.slice(2);
|
||||
await build(args.length > 0 ? args : platforms);
|
||||
}
|
||||
+406
@@ -0,0 +1,406 @@
|
||||
/** The platforms with a prebuilt binary, as `${process.platform}-${process.arch}`. */
|
||||
export declare const platforms: readonly string[];
|
||||
|
||||
/**
|
||||
* Returns the name of the package holding the mygo binary of a platform,
|
||||
* by default this one. Throws for platforms without a prebuilt binary.
|
||||
*/
|
||||
export declare function platformPackage(platform?: string, arch?: string): string;
|
||||
|
||||
/**
|
||||
* Returns the path of the mygo binary to run: $MYGO_CLI_BINARY when set,
|
||||
* else the binary of this platform's package. Throws when that package is
|
||||
* not installed.
|
||||
*/
|
||||
export declare function binaryPath(): string;
|
||||
|
||||
/**
|
||||
* Types the configuration of mygo.config.ts, which takes the place of
|
||||
* mygo.json:
|
||||
*
|
||||
* ```ts
|
||||
* import { defineConfig } from "mygo-cli";
|
||||
*
|
||||
* export default defineConfig({
|
||||
* name: "My App",
|
||||
* identifier: "com.example.myapp",
|
||||
* devUrl: "http://localhost:5173",
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* A function gets the command running and returns the configuration, or a
|
||||
* promise of it.
|
||||
*/
|
||||
export declare function defineConfig(config: Config): Config;
|
||||
export declare function defineConfig(config: Promise<Config>): Promise<Config>;
|
||||
export declare function defineConfig(config: ConfigFn): ConfigFn;
|
||||
|
||||
/** A configuration computed for the command running. */
|
||||
export type ConfigFn = (env: ConfigEnv) => Config | Promise<Config>;
|
||||
|
||||
/** What a configuration function gets. */
|
||||
export interface ConfigEnv {
|
||||
/** The mygo command running. */
|
||||
command: "dev" | "build" | "generate" | "init" | "publish";
|
||||
}
|
||||
|
||||
/** The configuration of a MyGo project. Every field is optional. */
|
||||
export interface Config {
|
||||
/** The name users see: the app, its executable, menus and installers (default: the directory's name). */
|
||||
name?: string;
|
||||
/**
|
||||
* The name of the app's files where a name must be plain ASCII: the disk
|
||||
* images of macOS and the installers of Windows, the Linux executable,
|
||||
* desktop entry, icon and Debian package, the update archives of every
|
||||
* platform, and the variables of the install scripts. Lower-case
|
||||
* letters and digits with single hyphens between them (default: the name
|
||||
* in lower case, with hyphens between its words and Chinese, Japanese and
|
||||
* Korean in Latin letters, as `my-app` of "My App" and `yun-yin-le` of
|
||||
* "云音乐").
|
||||
*/
|
||||
slug?: string;
|
||||
/**
|
||||
* A reverse DNS name unique to the app, such as `com.example.myapp`, on
|
||||
* which systems key preferences, permissions and registrations (default:
|
||||
* `com.mygo.` and the name's letters and digits).
|
||||
*/
|
||||
identifier?: string;
|
||||
/** The version of the app, which updates compare (default: `0.1.0`). */
|
||||
version?: string;
|
||||
/** The copyright notice of the app. */
|
||||
copyright?: string;
|
||||
/**
|
||||
* Who makes the app, which Windows lists with the installed app (default:
|
||||
* the copyright notice without its "©" and years).
|
||||
*/
|
||||
publisher?: string;
|
||||
/**
|
||||
* The SPDX license expression of the app, such as `MIT`, which the RPM
|
||||
* package and the PKGBUILD of Arch Linux record (default: `license` in
|
||||
* `package.json`).
|
||||
*/
|
||||
license?: string;
|
||||
/** A square PNG, ideally 1024×1024 (default: `resources/icon.png` when it exists). */
|
||||
icon?: string;
|
||||
/** The Go package of the app, relative to the project (default: `.`). */
|
||||
main?: string;
|
||||
/** Where `mygo build` writes the builds, one directory per platform (default: `dist`). */
|
||||
out?: string;
|
||||
/**
|
||||
* Where `mygo generate` writes the TypeScript client (default:
|
||||
* `src/mygo.ts` when package.json at the project root depends on
|
||||
* mygo-runtime; an app without a frontend gets no client).
|
||||
*/
|
||||
bindings?: string;
|
||||
|
||||
/**
|
||||
* The dev server `mygo dev` points the app at, such as
|
||||
* `http://localhost:5173`: windows load it for URLs without a scheme.
|
||||
*/
|
||||
devUrl?: string;
|
||||
/** Runs in the project while `mygo dev` runs, e.g. the dev server; the app starts once `devUrl` answers. */
|
||||
devCommand?: string;
|
||||
/** Builds the frontend before `mygo build` compiles the app. */
|
||||
buildCommand?: string;
|
||||
/**
|
||||
* The directory of the built frontend, which `mygo build` embeds into the
|
||||
* app; `mygo dev` serves it from disk without `devUrl`.
|
||||
*/
|
||||
frontendDist?: string;
|
||||
|
||||
/**
|
||||
* Files and directories copied into the app of every platform under their
|
||||
* base names, next to the contents of the project's resources directory,
|
||||
* whose directories named after a platform, such as
|
||||
* `resources/linux-amd64`, hold the files of one platform.
|
||||
*/
|
||||
resources?: string[];
|
||||
/**
|
||||
* Files of the project's resources directory left out of the apps:
|
||||
* patterns of their paths there, with slashes, where `*` matches within a
|
||||
* name and `**` any number of directories, as in `design/**`. A directory
|
||||
* that matches is left out with what it holds. Go source files are always
|
||||
* left out; listed `resources` ship whole.
|
||||
*/
|
||||
resourcesExclude?: string[];
|
||||
/** The URL schemes the app opens, such as `myapp` for `myapp://…`, which reach `App.OnOpenURL`. */
|
||||
urlSchemes?: string[];
|
||||
/** The types of files the app opens, which reach `App.OnOpenFile`. */
|
||||
fileAssociations?: FileAssociation[];
|
||||
/**
|
||||
* The catalogs of the app's messages, which make the languages it ships.
|
||||
* Without it, the app ships English only.
|
||||
*/
|
||||
i18n?: I18nConfig;
|
||||
/** Signed updates, which `mygo.Updater` installs. */
|
||||
updates?: UpdatesConfig;
|
||||
/** macOS packaging. */
|
||||
macos?: MacOSConfig;
|
||||
/** Windows packaging. */
|
||||
windows?: WindowsConfig;
|
||||
/** Linux packaging. */
|
||||
linux?: LinuxConfig;
|
||||
/** The iOS app (`mygo build -platform ios`, `ios/simulator`). */
|
||||
ios?: IOSConfig;
|
||||
/** The Android app (`mygo build -platform android`). */
|
||||
android?: AndroidConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalogs of the app's messages: a JSON file per language in `dir`,
|
||||
* named after its BCP 47 tag (`de.json`, `zh-Hant.json`), whose messages
|
||||
* `mygo generate` writes typed Go and TypeScript functions for.
|
||||
*/
|
||||
export interface I18nConfig {
|
||||
/** The directory of the catalogs, a Go package of its own (default `locales`). */
|
||||
dir?: string;
|
||||
/** The language the app is written in, which the others fall back to (default `en`). */
|
||||
source?: string;
|
||||
}
|
||||
|
||||
/** A type of file the app opens. */
|
||||
export interface FileAssociation {
|
||||
/** The file name extensions, without dots, e.g. `["md"]`. */
|
||||
ext: string[];
|
||||
/** What the files are, e.g. `"Markdown Document"`. */
|
||||
name?: string;
|
||||
/** The MIME type of the files, by which Linux identifies them; the app defines an unregistered one (`x-`) (default: `application/x-<app>-<ext>`). */
|
||||
mimeType?: string;
|
||||
/** The app's role for the files on macOS (default: `"Editor"`). */
|
||||
role?: "Editor" | "Viewer";
|
||||
}
|
||||
|
||||
/** Signed updates: `publicKey` and one of `github` and `url` are required. */
|
||||
export interface UpdatesConfig {
|
||||
/** The contents of mygo-update.pub, from `mygo keygen`. */
|
||||
publicKey: string;
|
||||
/** A public GitHub repository, `owner/name`, whose releases hold the updates. */
|
||||
github?: string;
|
||||
/**
|
||||
* What precedes the version in release tags (default: `v`). Another prefix,
|
||||
* such as `desktop-v`, lets the repository hold other releases: apps find
|
||||
* the newest release tagged with it through the GitHub API instead of
|
||||
* reading the latest release.
|
||||
*/
|
||||
tagPrefix?: string;
|
||||
/** Instead of `github`, the HTTPS URL of a directory holding the updates. */
|
||||
url?: string;
|
||||
/** The bucket that serves `url`, which `mygo build -upload` uploads to. */
|
||||
s3?: S3Config;
|
||||
/** The path of mygo-update.key; `MYGO_UPDATER_PRIVATE_KEY`, holding the key, takes precedence. */
|
||||
privateKey?: string;
|
||||
/** A Markdown file whose `## <version>` section becomes the release notes (default: `CHANGELOG.md` when it exists). */
|
||||
changelog?: string;
|
||||
/** How many earlier versions get a delta update, a smaller download of what changed (default: `3`; `0` for none). */
|
||||
deltas?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A bucket of Amazon S3, or of a compatible service such as Cloudflare R2.
|
||||
* The credentials come from `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and
|
||||
* `AWS_SESSION_TOKEN`.
|
||||
*/
|
||||
export interface S3Config {
|
||||
/** The name of the bucket. */
|
||||
bucket: string;
|
||||
/** The directory of the files in the bucket, e.g. `my-app` (default: its root). */
|
||||
prefix?: string;
|
||||
/** The region of the bucket (default: `AWS_REGION`, else `AWS_DEFAULT_REGION`, else `us-east-1`). */
|
||||
region?: string;
|
||||
/** The endpoint of a compatible service, e.g. `https://<account>.r2.cloudflarestorage.com` (default: Amazon S3's). */
|
||||
endpoint?: string;
|
||||
/** Names the bucket in the path of URLs rather than in the host name (default: with `endpoint`, or a bucket name with dots). */
|
||||
pathStyle?: boolean;
|
||||
}
|
||||
|
||||
/** macOS packaging. */
|
||||
export interface MacOSConfig {
|
||||
/**
|
||||
* The icon as an asset catalog: an `Assets.car` compiled with actool (its
|
||||
* app icon named `AppIcon`, unless `infoPlist` sets `CFBundleIconName`), or
|
||||
* an Icon Composer `.icon`, which builds compile on a Mac with Xcode 26 or
|
||||
* later and skip elsewhere. The `.icns` made from `icon` remains the
|
||||
* fallback. Or an `.icns` in place of the one made from `icon`, for an
|
||||
* icon drawn per size.
|
||||
*/
|
||||
icon?: string;
|
||||
/** The oldest macOS the app runs on (default: `12.0`). */
|
||||
minimumSystemVersion?: string;
|
||||
/** The identity that signs the app and its disk image, e.g. `Developer ID Application: Jane Doe (TEAMID)` (default: `-`, ad hoc). */
|
||||
signingIdentity?: string;
|
||||
/** A property list of entitlements to sign the app with. */
|
||||
entitlements?: string;
|
||||
/**
|
||||
* A provisioning profile embedded before signing, for restricted entitlements.
|
||||
* Must match the app's identifier, entitlements and signing identity.
|
||||
* Cannot be used with ad-hoc signing. Paths are relative to the project.
|
||||
*/
|
||||
provisioningProfile?: string;
|
||||
/**
|
||||
* Property lists of entitlements for code among the resources, by its path
|
||||
* there, e.g. `{ "bin/server": "server.entitlements.plist" }` for a helper
|
||||
* that needs `com.apple.security.cs.allow-jit` under the hardened runtime.
|
||||
* Other code keeps the entitlements it is signed with.
|
||||
*/
|
||||
helperEntitlements?: Record<string, string>;
|
||||
/** Keys added to the app's Info.plist, replacing MyGo's, e.g. `NSCameraUsageDescription`. */
|
||||
infoPlist?: Record<string, unknown>;
|
||||
/** The volume name of the disk image (default: the name). */
|
||||
dmgTitle?: string;
|
||||
/** Notarizes the app and the disk image of production builds. */
|
||||
notarize?: NotarizeConfig;
|
||||
}
|
||||
|
||||
/** Credentials of `xcrun notarytool store-credentials <profile>`. */
|
||||
export interface NotarizeConfig {
|
||||
/** The profile holding the credentials. */
|
||||
keychainProfile: string;
|
||||
/** The keychain holding the profile (default: the login keychain). */
|
||||
keychain?: string;
|
||||
}
|
||||
|
||||
/** Windows packaging. */
|
||||
export interface WindowsConfig {
|
||||
/**
|
||||
* The name Windows shows the app by: its shortcuts, its entry in
|
||||
* Settings > Apps, the installer's title and the executable's product
|
||||
* name (default: the name). The executable and the install folder keep
|
||||
* the name's, e.g. `天气助手` for an app named `weather`.
|
||||
*/
|
||||
displayName?: string;
|
||||
/**
|
||||
* The name of the folder the installer installs the app in, in
|
||||
* `%LOCALAPPDATA%\Programs` (default: the name), e.g. an ASCII `ZhiLian`
|
||||
* for an app named `智链`, whose shortcuts and entry in Settings > Apps
|
||||
* keep the name. Changing it moves new installs only.
|
||||
*/
|
||||
installDirName?: string;
|
||||
/** A code signing certificate (.pfx); its password comes from `MYGO_WINDOWS_CERTIFICATE_PASSWORD`. */
|
||||
certificate?: string;
|
||||
/** Instead of `certificate`, a command that signs a file, with `%1` for its path. */
|
||||
signCommand?: string;
|
||||
/** The time stamping server of `certificate` (default: `http://timestamp.digicert.com`). */
|
||||
timestampUrl?: string;
|
||||
/**
|
||||
* An NSIS script that the installer includes, e.g. `build/installer.nsh`:
|
||||
* the macros it defines among `customInit`, `customInstall` and
|
||||
* `customUnInstall` run when the installer starts, at the end of the
|
||||
* install, and in the uninstall before the app's folder is removed.
|
||||
*/
|
||||
installerInclude?: string;
|
||||
}
|
||||
|
||||
/** Linux packaging. */
|
||||
/** The iOS app. */
|
||||
export interface IOSConfig {
|
||||
/** The oldest iOS the app runs on (default: `17.0`). */
|
||||
minimumSystemVersion?: string;
|
||||
/** The ID of the Apple developer team that signs the app for devices. */
|
||||
team?: string;
|
||||
/** The provisioning profile to sign with: its name, UUID or the path of a `.mobileprovision` (default: the installed one that best fits). */
|
||||
provisioningProfile?: string;
|
||||
/** What the build is for (default: `app-store`, TestFlight too). */
|
||||
distribution?: "app-store" | "ad-hoc" | "development" | "enterprise";
|
||||
/** `CFBundleVersion`, which must grow with every upload of a version (default: the version). */
|
||||
/** Lets WindowOptions.OwnScene open windows of the system's own on iPad. */
|
||||
multipleWindows?: boolean;
|
||||
buildNumber?: string;
|
||||
/** The orientations the app turns to on iPhones (default: both); iPads take every one. */
|
||||
orientations?: ("portrait" | "landscape")[];
|
||||
/** Extra keys of Info.plist, which replace MyGo's own, as usage descriptions. */
|
||||
infoPlist?: Record<string, unknown>;
|
||||
/**
|
||||
* The hosts of the app's universal links, which reach `App.OnOpenURL`:
|
||||
* `example.com` signs the app with `applinks:example.com`, and a value with
|
||||
* its own service, as `webcredentials:example.com`, stays as it is. The
|
||||
* provisioning profile needs the capability Associated Domains.
|
||||
*/
|
||||
associatedDomains?: string[];
|
||||
/** What the system shows while the app starts (default: the system background). */
|
||||
launchScreen?: IOSLaunchScreen;
|
||||
/** The app's `UIBackgroundModes`, as `audio`, `fetch` or `remote-notification`, with those its plugins ask for. */
|
||||
backgroundModes?: string[];
|
||||
}
|
||||
|
||||
/** The launch screen of the iOS app: at least one of its fields. */
|
||||
export interface IOSLaunchScreen {
|
||||
/** Its color, as `#102030`. */
|
||||
background?: string;
|
||||
/** A PNG shown centered, at the size of a 3x screen: a logo of 600×600 pixels takes 200×200 points. */
|
||||
image?: string;
|
||||
}
|
||||
|
||||
/** The Android app. */
|
||||
export interface AndroidConfig {
|
||||
/** The oldest Android API level the app runs on (default: `26`, Android 8.0). */
|
||||
minSdk?: number;
|
||||
/** The integer version Google Play orders uploads by (default: from the version, major×10000 + minor×100 + patch). */
|
||||
versionCode?: number;
|
||||
/** Permissions the manifest declares besides INTERNET, as `android.permission.CAMERA` or `CAMERA`. */
|
||||
permissions?: string[];
|
||||
/** The keystore of the upload key that signs release builds; its passwords come from `MYGO_ANDROID_KEYSTORE_PASSWORD` and `MYGO_ANDROID_KEY_PASSWORD`. Without one, builds are signed with the debug key. */
|
||||
keystore?: string;
|
||||
/** The alias of the upload key in the keystore. */
|
||||
keyAlias?: string;
|
||||
/**
|
||||
* The hosts of the app's https deep links, verified by Android, which reach
|
||||
* `App.OnOpenURL`: each serves `/.well-known/assetlinks.json` naming the
|
||||
* app. `*.example.com` takes its subdomains.
|
||||
*/
|
||||
appLinks?: string[];
|
||||
/** The launcher icon of Android 8.0 and later, which the launcher masks and moves. Without it, launchers show `icon` as it is. */
|
||||
adaptiveIcon?: AndroidAdaptiveIcon;
|
||||
/** The color of the screen the system shows while the app starts, as `#102030` (default: the theme's). */
|
||||
splash?: string;
|
||||
}
|
||||
|
||||
/** An icon of two layers. */
|
||||
export interface AndroidAdaptiveIcon {
|
||||
/** A square PNG, ideally 432×432 or more, with transparency around what it shows: launchers crop to the middle 72/108 of it. */
|
||||
foreground: string;
|
||||
/** The color under it, as `#102030`. */
|
||||
background: string;
|
||||
}
|
||||
|
||||
export interface LinuxConfig {
|
||||
/** `Name <email>`, the maintainer of the Debian and RPM packages and of the PKGBUILD (default: `author` in package.json, else the app's name). */
|
||||
maintainer?: string;
|
||||
/** A short description, for the desktop entry and the packages. */
|
||||
comment?: string;
|
||||
/** The categories of the desktop entry (default: `["Utility"]`). */
|
||||
categories?: string[];
|
||||
/** Packages the app needs besides GTK and WebKitGTK, by package format or as Debian packages mapped to Arch Linux and RPM where MyGo knows them. */
|
||||
depends?: string[] | LinuxDepends;
|
||||
/**
|
||||
* `false` for an app that shows no web page, in a window or a `ui.WebView`,
|
||||
* as an app of native UI: its Debian and RPM packages and PKGBUILD depend on GTK alone, and
|
||||
* install.sh and `mygo doctor` do not ask for WebKitGTK (default: `true`).
|
||||
*/
|
||||
webview?: boolean;
|
||||
/**
|
||||
* A command that runs the app, such as `my-app`, or a list of names, such
|
||||
* as `["my-app", "ma"]`, which adds a short one: a link in `/usr/bin` from
|
||||
* the Debian and RPM packages and the PKGBUILD, and in `~/.local/bin` from install.sh, for each,
|
||||
* which says to run the app by the first it links (default: none; the app
|
||||
* opens from the applications menu).
|
||||
*/
|
||||
command?: string | string[];
|
||||
/**
|
||||
* The packages `mygo build` writes (default: all three). The archive with
|
||||
* install.sh is always written, as install.sh updates the app from it and
|
||||
* the PKGBUILD packages it; `[]` writes it alone.
|
||||
*/
|
||||
formats?: ("deb" | "rpm" | "pkgbuild")[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra package dependencies for Linux packages, by package format.
|
||||
*/
|
||||
export interface LinuxDepends {
|
||||
/** Debian packages the app needs besides GTK and WebKitGTK. */
|
||||
deb?: string[];
|
||||
/** RPM package dependencies or library requirements besides GTK and WebKitGTK. */
|
||||
rpm?: string[];
|
||||
/** Arch Linux packages the app needs besides GTK and WebKitGTK. */
|
||||
arch?: string[];
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
// mygo-cli ships the mygo command line tool of MyGo as a prebuilt binary
|
||||
// per platform. Each binary is in a package of its own,
|
||||
// @egoist/mygo-cli-<os>-<cpu>,
|
||||
// which mygo-cli lists as optional dependencies: package managers install
|
||||
// the one matching the machine's os and cpu fields.
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { accessSync, chmodSync, constants, existsSync, readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { basename, dirname, join, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const { version } = require("./package.json");
|
||||
|
||||
/** The platforms with a prebuilt binary, as `${process.platform}-${process.arch}`. */
|
||||
export const platforms = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64", "win32-arm64", "win32-x64"];
|
||||
|
||||
const goInstall = `go install github.com/egoist/mygo/cmd/mygo@v${version}`;
|
||||
|
||||
/**
|
||||
* Returns the name of the package holding the mygo binary of a platform,
|
||||
* by default this one.
|
||||
*/
|
||||
export function platformPackage(platform = process.platform, arch = process.arch) {
|
||||
const target = `${platform}-${arch}`;
|
||||
if (!platforms.includes(target)) {
|
||||
throw new Error(`mygo-cli: there is no prebuilt mygo binary for ${target}; install the CLI with Go instead: ${goInstall}`);
|
||||
}
|
||||
return `@egoist/mygo-cli-${target}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path of the mygo binary to run: $MYGO_CLI_BINARY when set,
|
||||
* else the binary of this platform's package. In a checkout of the MyGo
|
||||
* repository it builds the CLI from its source first.
|
||||
*/
|
||||
export function binaryPath() {
|
||||
if (process.env.MYGO_CLI_BINARY) return process.env.MYGO_CLI_BINARY;
|
||||
const exe = process.platform === "win32" ? "mygo.exe" : "mygo";
|
||||
const pkg = platformPackage();
|
||||
const checkout = join(here, "..", "..");
|
||||
if (isCheckout(checkout)) {
|
||||
// The platform packages hold no binary until they are released: build
|
||||
// the CLI from source, which Go's build cache makes quick.
|
||||
const bin = join(here, "npm", `${process.platform}-${process.arch}`, "bin", exe);
|
||||
execFileSync("go", ["build", "-o", bin, "./cmd/mygo"], { cwd: checkout, stdio: "inherit" });
|
||||
return bin;
|
||||
}
|
||||
let dir;
|
||||
try {
|
||||
dir = dirname(require.resolve(`${pkg}/package.json`));
|
||||
} catch {
|
||||
throw new Error(
|
||||
`mygo-cli: ${pkg}, the package with the mygo binary of this platform, is not installed. ` +
|
||||
`${reinstallHint(pkg)} Or install the CLI with Go: ${goInstall}`,
|
||||
);
|
||||
}
|
||||
const bin = join(dir, "bin", exe);
|
||||
if (process.platform !== "win32") {
|
||||
try {
|
||||
accessSync(bin, constants.X_OK);
|
||||
} catch {
|
||||
// Some package managers drop the executable bit.
|
||||
chmodSync(bin, 0o755);
|
||||
}
|
||||
}
|
||||
return bin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Types the configuration of mygo.config.ts: an object, or a function of the
|
||||
* command running that returns one.
|
||||
*/
|
||||
export function defineConfig(config) {
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Says how to install pkg, the missing package of the mygo binary. Package
|
||||
* managers skip an optional dependency they fail to fetch, as when npm does
|
||||
* not serve it yet, and bun keeps skipping it while bun.lock lacks it, even
|
||||
* with --force.
|
||||
*/
|
||||
function reinstallHint(pkg) {
|
||||
// The directory whose node_modules holds mygo-cli, at any depth.
|
||||
const i = here.indexOf(`${sep}node_modules${sep}`);
|
||||
const root = i < 0 ? here : here.slice(0, i);
|
||||
const runner = basename(root).startsWith("bunx-") ? "bunx" : basename(dirname(root)) === "_npx" ? "npx" : "";
|
||||
if (runner) {
|
||||
return `${runner} installed mygo-cli without it in ${root}: remove that directory, then run ${runner} again.`;
|
||||
}
|
||||
const lockfile = join(root, "bun.lock");
|
||||
let lock = "";
|
||||
try {
|
||||
lock = readFileSync(lockfile, "utf8");
|
||||
} catch {}
|
||||
if (lock && !lock.includes(`"${pkg}": [`)) {
|
||||
return `bun installed mygo-cli without it, and does so again while ${lockfile} lacks it, even with --force: remove that file, then install again.`;
|
||||
}
|
||||
return "Reinstall mygo-cli without omitting optional dependencies.";
|
||||
}
|
||||
|
||||
/** Reports whether dir is a checkout of the MyGo repository. */
|
||||
function isCheckout(dir) {
|
||||
try {
|
||||
return (
|
||||
readFileSync(join(dir, "go.mod"), "utf8").startsWith("module github.com/egoist/mygo\n") &&
|
||||
existsSync(join(dir, "cmd", "mygo", "main.go"))
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import { expect, test } from "bun:test";
|
||||
import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, sep } from "node:path";
|
||||
import { build, dir, goTargets, platformDir, platformName, version } from "./build.ts";
|
||||
import { defineConfig, platformPackage, platforms } from "./index.js";
|
||||
|
||||
const host = `${process.platform}-${process.arch}`;
|
||||
const exe = process.platform === "win32" ? "mygo.exe" : "mygo";
|
||||
const readJSON = (path: string) => JSON.parse(readFileSync(path, "utf8"));
|
||||
|
||||
test("platformPackage names the package of each platform", () => {
|
||||
expect(platformPackage("darwin", "arm64")).toBe("@egoist/mygo-cli-darwin-arm64");
|
||||
expect(platformPackage("win32", "x64")).toBe("@egoist/mygo-cli-win32-x64");
|
||||
expect(platformName("linux-x64")).toBe(platformPackage("linux", "x64"));
|
||||
expect(() => platformPackage("freebsd", "x64")).toThrow(/go install github.com\/egoist\/mygo\/cmd\/mygo@v/);
|
||||
expect(Object.keys(goTargets).sort()).toEqual([...platforms].sort());
|
||||
});
|
||||
|
||||
test("the packages have the version of the Go module", async () => {
|
||||
const v = await version();
|
||||
const main = readJSON(join(dir, "package.json"));
|
||||
expect(main.version).toBe(v);
|
||||
expect(main.optionalDependencies).toEqual(Object.fromEntries(platforms.map((p) => [platformName(p), v])));
|
||||
for (const platform of platforms) {
|
||||
const pkg = readJSON(join(platformDir(platform), "package.json"));
|
||||
const [os, cpu] = platform.split("-");
|
||||
expect(pkg).toMatchObject({ name: platformName(platform), version: v, os: [os], cpu: [cpu], license: "MIT" });
|
||||
}
|
||||
});
|
||||
|
||||
test("the published packages carry the license", () => {
|
||||
const license = readFileSync(join(dir, "..", "..", "LICENSE"), "utf8");
|
||||
for (const pkg of [join(dir, "..", "runtime"), dir, ...platforms.map(platformDir)]) {
|
||||
expect(readJSON(join(pkg, "package.json")).license).toBe("MIT");
|
||||
expect(readFileSync(join(pkg, "LICENSE"), "utf8")).toBe(license);
|
||||
}
|
||||
});
|
||||
|
||||
// install lays out mygo-cli in node_modules as a package manager would, with
|
||||
// or without the package of this platform, and returns the binary's path.
|
||||
function install(root: string, withPlatform: boolean) {
|
||||
const cli = join(root, "node_modules", "mygo-cli");
|
||||
mkdirSync(join(cli, "bin"), { recursive: true });
|
||||
for (const file of ["package.json", "index.js", "bin/mygo.js"]) cpSync(join(dir, file), join(cli, file));
|
||||
if (withPlatform) {
|
||||
const pkg = join(root, "node_modules", platformName(host));
|
||||
cpSync(platformDir(host), pkg, { recursive: true });
|
||||
return join(pkg, "bin", exe);
|
||||
}
|
||||
}
|
||||
|
||||
function run(runtime: string, root: string, args: string[], env: Record<string, string> = {}) {
|
||||
const r = Bun.spawnSync([runtime, join(root, "node_modules", "mygo-cli", "bin", "mygo.js"), ...args], {
|
||||
env: { ...process.env, MYGO_CLI_BINARY: "", ...env },
|
||||
});
|
||||
return { code: r.exitCode, out: r.stdout.toString(), err: r.stderr.toString() };
|
||||
}
|
||||
|
||||
const runtimes = ["node", "bun"].filter((r) => Bun.which(r));
|
||||
|
||||
test.skipIf(!platforms.includes(host))(
|
||||
"mygo runs the binary of the platform's package",
|
||||
async () => {
|
||||
await build([host]);
|
||||
const v = await version();
|
||||
const root = mkdtempSync(join(tmpdir(), "mygo-cli-"));
|
||||
try {
|
||||
const bin = install(root, true)!;
|
||||
if (process.platform !== "win32") chmodSync(bin, 0o644); // a package manager dropped the executable bit
|
||||
for (const runtime of runtimes) {
|
||||
expect(run(runtime, root, ["version"])).toMatchObject({ code: 0, out: `mygo ${v}\n` });
|
||||
expect(run(runtime, root, ["no-such-command"]).code).toBe(2);
|
||||
}
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
120_000,
|
||||
);
|
||||
|
||||
// bunLock returns a bun.lock of a project depending on mygo-cli, which
|
||||
// resolved the package of this platform or, when bun could not fetch it,
|
||||
// did not.
|
||||
function bunLock(withPlatform: boolean) {
|
||||
const pkg = platformName(host);
|
||||
const resolved = withPlatform ? `\n "${pkg}": ["${pkg}@0.1.1", "", {}, "sha512-"],` : "";
|
||||
return `{
|
||||
"lockfileVersion": 2,
|
||||
"workspaces": { "": { "dependencies": { "mygo-cli": "^0.1.1" } } },
|
||||
"packages": {
|
||||
"mygo-cli": ["mygo-cli@0.1.1", "", { "optionalDependencies": { "${pkg}": "0.1.1" } }, "sha512-"],${resolved}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
test("mygo explains a missing platform package", () => {
|
||||
const base = mkdtempSync(join(tmpdir(), "mygo-cli-"));
|
||||
const missing = `${platformName(host)}, the package with the mygo binary of this platform, is not installed`;
|
||||
const omitted = "Reinstall mygo-cli without omitting optional dependencies";
|
||||
try {
|
||||
const project = join(base, "project");
|
||||
install(project, false);
|
||||
const bunx = join(base, "bunx-501-mygo-cli@latest");
|
||||
install(bunx, false);
|
||||
const npx = join(base, "_npx", "0123456789abcdef");
|
||||
install(npx, false);
|
||||
for (const runtime of runtimes) {
|
||||
rmSync(join(project, "bun.lock"), { force: true });
|
||||
let r = run(runtime, project, ["version"]);
|
||||
expect(r.code).toBe(1);
|
||||
expect(r.err).toContain(missing);
|
||||
expect(r.err).toContain(omitted);
|
||||
// bun keeps out what its lockfile lacks. The messages name the real
|
||||
// paths, which can differ from ours, as in 8.3 names on Windows.
|
||||
writeFileSync(join(project, "bun.lock"), bunLock(false));
|
||||
r = run(runtime, project, ["version"]);
|
||||
expect(r.err).toContain(missing);
|
||||
expect(r.err).toContain(`${sep}project${sep}bun.lock lacks it, even with --force: remove that file`);
|
||||
writeFileSync(join(project, "bun.lock"), bunLock(true));
|
||||
expect(run(runtime, project, ["version"]).err).toContain(omitted);
|
||||
// bunx and npx run the install they made again.
|
||||
r = run(runtime, bunx, ["version"]);
|
||||
expect(r.err).toContain(missing);
|
||||
expect(r.err).toContain("bunx installed mygo-cli without it in ");
|
||||
expect(r.err).toContain(`${sep}bunx-501-mygo-cli@latest: remove that directory, then run bunx again`);
|
||||
r = run(runtime, npx, ["version"]);
|
||||
expect(r.err).toContain("npx installed mygo-cli without it in ");
|
||||
expect(r.err).toContain(`${sep}_npx${sep}0123456789abcdef: remove that directory, then run npx again`);
|
||||
// MYGO_CLI_BINARY points at a binary of one's own instead.
|
||||
const own = run(runtime, project, ["--version"], { MYGO_CLI_BINARY: process.execPath });
|
||||
expect(own.code).toBe(0);
|
||||
}
|
||||
} finally {
|
||||
rmSync(base, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("defineConfig returns the configuration", async () => {
|
||||
const config = defineConfig({
|
||||
name: "My App",
|
||||
fileAssociations: [{ ext: ["md"], role: "Viewer" }],
|
||||
macos: { infoPlist: { NSCameraUsageDescription: "Scan documents." } },
|
||||
});
|
||||
expect(config.name).toBe("My App");
|
||||
const fn = defineConfig(({ command }) => ({ devUrl: command === "dev" ? "http://localhost:5173" : undefined }));
|
||||
expect(await fn({ command: "dev" })).toEqual({ devUrl: "http://localhost:5173" });
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
# @egoist/mygo-cli-darwin-arm64
|
||||
|
||||
The macOS arm64 binary of mygo-cli, the command line tool of MyGo. Install
|
||||
[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers
|
||||
install the package of the platform they run on.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@egoist/mygo-cli-darwin-arm64",
|
||||
"version": "0.10.0",
|
||||
"description": "The macOS arm64 binary of mygo-cli",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli/npm/darwin-arm64"
|
||||
},
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"files": [
|
||||
"bin"
|
||||
],
|
||||
"preferUnplugged": true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
# @egoist/mygo-cli-darwin-x64
|
||||
|
||||
The macOS x64 binary of mygo-cli, the command line tool of MyGo. Install
|
||||
[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers
|
||||
install the package of the platform they run on.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@egoist/mygo-cli-darwin-x64",
|
||||
"version": "0.10.0",
|
||||
"description": "The macOS x64 binary of mygo-cli",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli/npm/darwin-x64"
|
||||
},
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"files": [
|
||||
"bin"
|
||||
],
|
||||
"preferUnplugged": true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
# @egoist/mygo-cli-linux-arm64
|
||||
|
||||
The Linux arm64 binary of mygo-cli, the command line tool of MyGo. Install
|
||||
[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers
|
||||
install the package of the platform they run on.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@egoist/mygo-cli-linux-arm64",
|
||||
"version": "0.10.0",
|
||||
"description": "The Linux arm64 binary of mygo-cli",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli/npm/linux-arm64"
|
||||
},
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"files": [
|
||||
"bin"
|
||||
],
|
||||
"preferUnplugged": true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
# @egoist/mygo-cli-linux-x64
|
||||
|
||||
The Linux x64 binary of mygo-cli, the command line tool of MyGo. Install
|
||||
[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers
|
||||
install the package of the platform they run on.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@egoist/mygo-cli-linux-x64",
|
||||
"version": "0.10.0",
|
||||
"description": "The Linux x64 binary of mygo-cli",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli/npm/linux-x64"
|
||||
},
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"files": [
|
||||
"bin"
|
||||
],
|
||||
"preferUnplugged": true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
# @egoist/mygo-cli-win32-arm64
|
||||
|
||||
The Windows arm64 binary of mygo-cli, the command line tool of MyGo. Install
|
||||
[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers
|
||||
install the package of the platform they run on.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@egoist/mygo-cli-win32-arm64",
|
||||
"version": "0.10.0",
|
||||
"description": "The Windows arm64 binary of mygo-cli",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli/npm/win32-arm64"
|
||||
},
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"files": [
|
||||
"bin"
|
||||
],
|
||||
"preferUnplugged": true
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,5 @@
|
||||
# @egoist/mygo-cli-win32-x64
|
||||
|
||||
The Windows x64 binary of mygo-cli, the command line tool of MyGo. Install
|
||||
[mygo-cli](https://www.npmjs.com/package/mygo-cli) instead: package managers
|
||||
install the package of the platform they run on.
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@egoist/mygo-cli-win32-x64",
|
||||
"version": "0.10.0",
|
||||
"description": "The Windows x64 binary of mygo-cli",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli/npm/win32-x64"
|
||||
},
|
||||
"license": "MIT",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"files": [
|
||||
"bin"
|
||||
],
|
||||
"preferUnplugged": true
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "mygo-cli",
|
||||
"version": "0.10.0",
|
||||
"description": "The mygo command line tool: create, develop and package MyGo desktop apps",
|
||||
"keywords": [
|
||||
"mygo",
|
||||
"desktop",
|
||||
"webview",
|
||||
"go",
|
||||
"cli"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/cli"
|
||||
},
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"mygo": "bin/mygo.js"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"default": "./index.js"
|
||||
}
|
||||
},
|
||||
"types": "./index.d.ts",
|
||||
"files": [
|
||||
"bin",
|
||||
"index.js",
|
||||
"index.d.ts",
|
||||
"README.md"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"scripts": {
|
||||
"binaries": "bun run build.ts",
|
||||
"test": "bun test"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@egoist/mygo-cli-darwin-arm64": "0.10.0",
|
||||
"@egoist/mygo-cli-darwin-x64": "0.10.0",
|
||||
"@egoist/mygo-cli-linux-arm64": "0.10.0",
|
||||
"@egoist/mygo-cli-linux-x64": "0.10.0",
|
||||
"@egoist/mygo-cli-win32-arm64": "0.10.0",
|
||||
"@egoist/mygo-cli-win32-x64": "0.10.0"
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 MyGo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
# mygo-runtime
|
||||
|
||||
Typed access to the runtime of [MyGo](https://github.com/egoist/mygo) apps,
|
||||
for their web frontends.
|
||||
|
||||
MyGo injects its runtime into every page of an app as `window.mygo`. This
|
||||
package gives it types and imports. The client that `mygo generate` writes
|
||||
for your bound Go services is built on it, so you mostly use that:
|
||||
|
||||
```ts
|
||||
import { Greeter, events } from "./mygo"; // generated
|
||||
|
||||
const greeting = await Greeter.greet("Ada");
|
||||
events.tick.on((time) => console.log(time));
|
||||
```
|
||||
|
||||
Use the package directly for the window and the platform:
|
||||
|
||||
```ts
|
||||
import { currentWindow, isCallError, isMyGo, runtime } from "mygo-runtime";
|
||||
|
||||
if (isMyGo() && runtime().platform === "darwin") {
|
||||
document.body.classList.add("mac");
|
||||
}
|
||||
await currentWindow.toggleMaximize();
|
||||
```
|
||||
|
||||
A Go method that streams values through a `*mygo.Channel[T]` parameter takes
|
||||
a `Channel` in its place:
|
||||
|
||||
```ts
|
||||
import { Channel } from "mygo-runtime";
|
||||
|
||||
const lines = new Channel<string>();
|
||||
const done = Shell.tail("ls -R", lines);
|
||||
for await (const line of lines) console.log(line);
|
||||
await done;
|
||||
```
|
||||
|
||||
A Go method returning an error rejects with a `CallError` (see
|
||||
`isCallError`). Outside a MyGo window, e.g. when the dev server is opened in a
|
||||
browser, calls reject and `isMyGo()` is false.
|
||||
|
||||
`mygo-runtime/i18n` formats the messages of the app's catalogs in its pages,
|
||||
as package `i18n` does in Go: messages of ICU MessageFormat, with the plural
|
||||
rules, numbers and dates of `Intl`. `mygo generate` writes a typed module of
|
||||
the catalogs next to the client (`locales.ts`) on top of it:
|
||||
|
||||
```ts
|
||||
import { messages } from "./locales"; // generated
|
||||
|
||||
status.textContent = messages.filesSelected(3); // "3 files selected"
|
||||
```
|
||||
|
||||
`formatMessage(locale, message, args)` formats a message of your own.
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
// Builds dist/ of the mygo-runtime package: an ES module and its type
|
||||
// declarations. dist/ is not committed: `bun run build` at the root builds
|
||||
// it, as CI and releases do.
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
const dir = import.meta.dir;
|
||||
await rm(join(dir, "dist"), { recursive: true, force: true });
|
||||
const result = await Bun.build({
|
||||
entrypoints: [join(dir, "src/index.ts"), join(dir, "src/i18n.ts")],
|
||||
outdir: join(dir, "dist"),
|
||||
format: "esm",
|
||||
target: "browser",
|
||||
});
|
||||
if (!result.success) {
|
||||
for (const log of result.logs) console.error(log);
|
||||
process.exit(1);
|
||||
}
|
||||
const tsc = Bun.spawnSync(["tsc", "-p", join(dir, "tsconfig.json")], { stdout: "inherit", stderr: "inherit" });
|
||||
if (tsc.exitCode !== 0) process.exit(1);
|
||||
console.log(`wrote ${join(dir, "dist")}`);
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "mygo-runtime",
|
||||
"version": "0.10.0",
|
||||
"description": "Typed access to the MyGo runtime in the pages of MyGo desktop apps",
|
||||
"keywords": [
|
||||
"mygo",
|
||||
"desktop",
|
||||
"webview",
|
||||
"go"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/egoist/mygo.git",
|
||||
"directory": "packages/runtime"
|
||||
},
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"./i18n": {
|
||||
"types": "./dist/i18n.d.ts",
|
||||
"default": "./dist/i18n.js"
|
||||
}
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "bun run build.ts",
|
||||
"test": "bun test"
|
||||
}
|
||||
}
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
import { afterAll, afterEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
createCatalog,
|
||||
currentLocale,
|
||||
formatMessage,
|
||||
isPseudoLocale,
|
||||
MessageSyntaxError,
|
||||
parseMessage,
|
||||
skeletonOptions,
|
||||
type CatalogData,
|
||||
} from "./i18n";
|
||||
|
||||
// The cases package i18n checks too (i18n/testdata/messages.json), so that
|
||||
// Go and pages say the same.
|
||||
const fixtures = JSON.parse(readFileSync(join(import.meta.dir, "../../../i18n/testdata/messages.json"), "utf8")) as {
|
||||
format: { message: string; locale?: string; args?: Record<string, unknown>; want: string }[];
|
||||
errors: string[];
|
||||
pseudo: { message: string; locale: string; args?: Record<string, unknown>; want: string }[];
|
||||
};
|
||||
|
||||
describe("formatMessage", () => {
|
||||
test("has the fixtures", () => {
|
||||
expect(fixtures.format.length).toBeGreaterThan(50);
|
||||
expect(fixtures.errors.length).toBeGreaterThan(20);
|
||||
});
|
||||
for (const c of [...fixtures.format, ...fixtures.pseudo]) {
|
||||
test(`${c.message} in ${c.locale ?? "en"} with ${JSON.stringify(c.args ?? {})}`, () => {
|
||||
expect(formatMessage(c.locale ?? "en", c.message, c.args)).toBe(c.want);
|
||||
});
|
||||
}
|
||||
for (const s of fixtures.errors) {
|
||||
test(`${JSON.stringify(s)} does not parse`, () => {
|
||||
expect(() => parseMessage(s)).toThrow(MessageSyntaxError);
|
||||
});
|
||||
}
|
||||
|
||||
test("formats numbers and dates with Intl", () => {
|
||||
expect(formatMessage("en", "{n}", { n: 1234.5 })).toBe("1,234.5");
|
||||
expect(formatMessage("de", "{n}", { n: 1234.5 })).toBe("1.234,5");
|
||||
expect(formatMessage("de", "{n, plural, one {# Datei} other {# Dateien}}", { n: 1000 })).toBe("1.000 Dateien");
|
||||
expect(formatMessage("en", "{n, number, ::currency/EUR}", { n: 3 })).toBe("€3.00");
|
||||
const day = new Date(Date.UTC(2026, 0, 2, 15, 4));
|
||||
expect(formatMessage("en", "{d, date, short}", { d: day })).toBe(
|
||||
new Intl.DateTimeFormat("en", { dateStyle: "short" }).format(day),
|
||||
);
|
||||
expect(formatMessage("en", "{d, time, short}", { d: day })).toBe(
|
||||
new Intl.DateTimeFormat("en", { timeStyle: "short" }).format(day),
|
||||
);
|
||||
expect(formatMessage("en", "{d}", { d: day })).toBe(
|
||||
new Intl.DateTimeFormat("en", { dateStyle: "short", timeStyle: "short" }).format(day),
|
||||
);
|
||||
expect(formatMessage("en", "{d, date}", { d: "tomorrow" })).toBe("tomorrow");
|
||||
});
|
||||
|
||||
test("writes other values", () => {
|
||||
expect(formatMessage("en", "{e}", { e: new Error("boom") })).toBe("boom");
|
||||
expect(formatMessage("en", "{v}", { v: null })).toBe("");
|
||||
expect(formatMessage("en", "{n, plural, one {#} other {# x}}", { n: 2n })).toBe("2 x");
|
||||
});
|
||||
|
||||
test("reports where a message does not parse", () => {
|
||||
try {
|
||||
parseMessage("Hello {name");
|
||||
throw new Error("parsed");
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(MessageSyntaxError);
|
||||
expect((err as MessageSyntaxError).offset).toBe(11);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const data: CatalogData = {
|
||||
source: "en",
|
||||
languages: ["en", "de", "en-001", "pt", "pt-PT", "zh-Hans", "zh-Hant"],
|
||||
fallbacks: {
|
||||
en: ["en"],
|
||||
de: ["de", "en"],
|
||||
"en-001": ["en-001", "en"],
|
||||
pt: ["pt", "en"],
|
||||
"pt-PT": ["pt-PT", "pt", "en"],
|
||||
"zh-Hans": ["zh-Hans", "en"],
|
||||
"zh-Hant": ["zh-Hant", "en"],
|
||||
},
|
||||
params: { hello: ["name"], color: [], files: ["n"], broken: [] },
|
||||
messages: {
|
||||
en: {
|
||||
hello: "Hello, {name}!",
|
||||
color: "Color",
|
||||
files: "{n, plural, one {# file} other {# files}}",
|
||||
broken: "Fine in English",
|
||||
},
|
||||
"en-001": { color: "Colour" },
|
||||
de: { hello: "Hallo, {name}!", files: "{n, plural, one {# Datei} other {# Dateien}}", broken: "{kaputt" },
|
||||
"zh-Hans": { hello: "你好,{name}!" },
|
||||
"zh-Hant": { hello: "你好,{name}!", color: "顏色" },
|
||||
pt: { color: "Cor" },
|
||||
"pt-PT": { hello: "Olá, {name}!" },
|
||||
},
|
||||
};
|
||||
|
||||
interface Messages {
|
||||
hello(name: string): string;
|
||||
color(): string;
|
||||
files(n: number): string;
|
||||
broken(): string;
|
||||
}
|
||||
|
||||
describe("createCatalog", () => {
|
||||
const catalog = createCatalog<Messages>(data);
|
||||
const g = globalThis as { mygo?: unknown };
|
||||
afterEach(() => {
|
||||
delete g.mygo;
|
||||
});
|
||||
|
||||
test("falls back along the languages", () => {
|
||||
const cases: [string, string, Record<string, unknown>, string][] = [
|
||||
["en", "hello", { name: "Ada" }, "Hello, Ada!"],
|
||||
["de", "hello", { name: "Ada" }, "Hallo, Ada!"],
|
||||
["de-CH", "hello", { name: "Ada" }, "Hallo, Ada!"],
|
||||
["de", "color", {}, "Color"],
|
||||
["de", "broken", {}, "broken"],
|
||||
["en-001", "color", {}, "Colour"],
|
||||
["zh-TW", "color", {}, "顏色"],
|
||||
["zh-Hant-HK", "color", {}, "顏色"],
|
||||
["zh-CN", "color", {}, "Color"],
|
||||
["pt-PT", "color", {}, "Cor"],
|
||||
["fr", "hello", { name: "Ada" }, "Hello, Ada!"],
|
||||
["de", "missing", {}, "missing"],
|
||||
// Properties every object has are no messages.
|
||||
["de", "toString", {}, "toString"],
|
||||
["de", "constructor", {}, "constructor"],
|
||||
["de", "files", { n: 1 }, "1 Datei"],
|
||||
// English's plural rules for an English message: French says one for 0.
|
||||
["fr", "files", { n: 0 }, "0 files"],
|
||||
["en-XA", "color", {}, "[Çöļöŕ one]"],
|
||||
["ar-XB", "color", {}, "\u200f\u202eColor\u202c\u200f"],
|
||||
["", "color", {}, "Color"],
|
||||
];
|
||||
for (const [locale, key, args, want] of cases) {
|
||||
expect(catalog.format(locale, key, args), `${locale} ${key}`).toBe(want);
|
||||
}
|
||||
expect(catalog.resolve("zh-TW")).toBe("zh-Hant");
|
||||
expect(catalog.resolve("en-AU")).toBe("en");
|
||||
expect(catalog.resolve("xx")).toBe("en");
|
||||
});
|
||||
|
||||
test("binds the messages to the language the page shows", () => {
|
||||
const messages = catalog.messages();
|
||||
g.mygo = { locale: "de" };
|
||||
expect(currentLocale()).toBe("de");
|
||||
expect(messages.files(3)).toBe("3 Dateien");
|
||||
g.mygo = { locale: "zh-Hant" };
|
||||
expect(messages.hello("Ada")).toBe("你好,Ada!");
|
||||
expect(catalog.messagesIn("en").files(1)).toBe("1 file");
|
||||
expect(catalog.languages).toEqual(data.languages);
|
||||
});
|
||||
|
||||
test("reads the browser's language outside MyGo", () => {
|
||||
delete g.mygo;
|
||||
expect(currentLocale()).toBe(navigator.languages?.[0] ?? navigator.language ?? "");
|
||||
});
|
||||
});
|
||||
|
||||
test("isPseudoLocale", () => {
|
||||
expect(isPseudoLocale("en-XA")).toBe(true);
|
||||
expect(isPseudoLocale("ar-xb")).toBe(true);
|
||||
expect(isPseudoLocale("en")).toBe(false);
|
||||
expect(isPseudoLocale("not a tag")).toBe(false);
|
||||
});
|
||||
|
||||
// The module of internal/i18ngen's golden catalog, as mygo generate writes
|
||||
// it, importing this package's source in place of mygo-runtime/i18n: it
|
||||
// type-checks, and says its messages.
|
||||
describe("the module mygo generate writes", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "mygo-locales-"));
|
||||
const file = join(dir, "locales.ts");
|
||||
const source = readFileSync(join(import.meta.dir, "../../../internal/i18ngen/testdata/app/locales.ts"), "utf8");
|
||||
expect(source).toContain(`from "mygo-runtime/i18n"`);
|
||||
writeFileSync(file, source.replace(`from "mygo-runtime/i18n"`, `from ${JSON.stringify(join(import.meta.dir, "i18n.ts"))}`));
|
||||
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
test("type-checks", () => {
|
||||
const tsc = Bun.spawnSync(
|
||||
[
|
||||
"tsc", "--noEmit", "--strict", "--noUncheckedIndexedAccess", "--target", "ES2022", "--module", "ESNext",
|
||||
"--moduleResolution", "bundler", "--allowImportingTsExtensions", "--lib", "ES2022,DOM", "--skipLibCheck", file,
|
||||
],
|
||||
{ cwd: dir },
|
||||
);
|
||||
expect(tsc.stdout.toString() + tsc.stderr.toString()).toBe("");
|
||||
expect(tsc.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
test("says the messages", async () => {
|
||||
const locales = await import(file);
|
||||
expect(locales.languages).toEqual(["en", "de", "en-GB", "zh-Hant"]);
|
||||
const de = locales.messagesIn("de");
|
||||
expect(de.title()).toBe("Notizen");
|
||||
expect(de.filesSelected(0)).toBe("Keine Dateien ausgewählt");
|
||||
expect(de.filesSelected(1)).toBe("1 Datei ausgewählt");
|
||||
expect(de.progress(0.5)).toBe("50\u00a0% done");
|
||||
expect(locales.messagesIn("en-GB").progress(0.5)).toBe("50% complete");
|
||||
expect(locales.messagesIn("zh-TW").filesSelected(2)).toBe("已選取 2 個檔案");
|
||||
expect(locales.messagesIn("en").guests("Ada", 3)).toBe("Ada and 2 others");
|
||||
expect(locales.messagesIn("en").place(22)).toBe("You came 22nd");
|
||||
expect(locales.messagesIn("en").positional("a", "b")).toBe("a of b");
|
||||
expect(locales.messagesIn("en").keyword("x", "y", "z", "w", "p")).toBe("x y z w p");
|
||||
expect(locales.messagesIn("en-XA").title()).toBe("[Ñöţéš one]");
|
||||
const g = globalThis as { mygo?: unknown };
|
||||
g.mygo = { locale: "de" };
|
||||
try {
|
||||
expect(locales.messages.greeting("Ada")).toBe("Hallo, Ada!");
|
||||
expect(locales.messages.keyword("x", "y", "z", "w", "p")).toBe("x y z w p");
|
||||
} finally {
|
||||
delete g.mygo;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("skeletons and number stems", () => {
|
||||
const day = new Date(Date.UTC(2026, 0, 2, 15, 4));
|
||||
test("formats a date of a skeleton as Intl's options", () => {
|
||||
expect(skeletonOptions("yMMMd")).toEqual({ year: "numeric", month: "short", day: "numeric" });
|
||||
expect(skeletonOptions("jm")).toEqual({ hour: "numeric", minute: "numeric" });
|
||||
expect(skeletonOptions("Hmm")).toEqual({ hour: "numeric", hourCycle: "h23", minute: "2-digit" });
|
||||
expect(skeletonOptions("EEEEd")).toEqual({ weekday: "long", day: "numeric" });
|
||||
expect(skeletonOptions("Kms")).toEqual({ hour: "numeric", hourCycle: "h11", minute: "numeric", second: "numeric" });
|
||||
expect(formatMessage("en", "{d, date, ::yMMMM}", { d: day })).toBe(
|
||||
new Intl.DateTimeFormat("en", { year: "numeric", month: "long" }).format(day),
|
||||
);
|
||||
});
|
||||
});
|
||||
+738
@@ -0,0 +1,738 @@
|
||||
/**
|
||||
* Formats the messages of a MyGo app's catalogs in its pages: messages of
|
||||
* ICU MessageFormat, as package i18n formats them in Go, with the plural
|
||||
* rules, numbers and dates of the browser's `Intl`. The module
|
||||
* `mygo generate` writes next to the TypeScript client (`locales.ts`) is
|
||||
* built on it:
|
||||
*
|
||||
* ```ts
|
||||
* import { messages } from "./locales";
|
||||
*
|
||||
* status.textContent = messages.filesSelected(3); // "3 files selected"
|
||||
* ```
|
||||
*
|
||||
* Use {@link formatMessage} directly to format a message of your own.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
/** A part of a parsed message. */
|
||||
export type MessagePart =
|
||||
| string
|
||||
| { type: "pound" }
|
||||
| { type: "arg"; name: string }
|
||||
| { type: "number" | "date" | "time"; name: string; style: string }
|
||||
| {
|
||||
type: "plural" | "selectordinal" | "select";
|
||||
name: string;
|
||||
offset: number;
|
||||
cases: { key: string; parts: MessagePart[] }[];
|
||||
};
|
||||
|
||||
/** The error of a message that does not parse. */
|
||||
export class MessageSyntaxError extends Error {
|
||||
constructor(
|
||||
/** The message. */
|
||||
readonly source: string,
|
||||
/** Where in it the error is, in UTF-16 code units. */
|
||||
readonly offset: number,
|
||||
reason: string,
|
||||
) {
|
||||
super(`${reason} at offset ${offset} of ${JSON.stringify(source)}`);
|
||||
this.name = "MessageSyntaxError";
|
||||
}
|
||||
}
|
||||
|
||||
const pluralKeywords = ["zero", "one", "two", "few", "many", "other"];
|
||||
|
||||
function isPatternSpace(c: string): boolean {
|
||||
return /^[\t\n\v\f\r \u0085\u200e\u200f\u2028\u2029]$/.test(c);
|
||||
}
|
||||
|
||||
function isPatternSyntax(c: string): boolean {
|
||||
const r = c.codePointAt(0)!;
|
||||
if (r < 0x80) {
|
||||
return (r >= 0x21 && r <= 0x2f) || (r >= 0x3a && r <= 0x40) || (r >= 0x5b && r <= 0x5e) || r === 0x60 || (r >= 0x7b && r <= 0x7e);
|
||||
}
|
||||
return (
|
||||
(r >= 0xa1 && r <= 0xa7) || r === 0xa9 || r === 0xab || r === 0xac || r === 0xae || r === 0xb0 || r === 0xb1 ||
|
||||
r === 0xb6 || r === 0xbb || r === 0xbf || r === 0xd7 || r === 0xf7 ||
|
||||
(r >= 0x2010 && r <= 0x2027) || (r >= 0x2030 && r <= 0x203e) || (r >= 0x2041 && r <= 0x2053) ||
|
||||
(r >= 0x2055 && r <= 0x205e) || (r >= 0x2190 && r <= 0x245f) || (r >= 0x2500 && r <= 0x2775) ||
|
||||
(r >= 0x2794 && r <= 0x2bff) || (r >= 0x2e00 && r <= 0x2e7f) || (r >= 0x3001 && r <= 0x3003) ||
|
||||
(r >= 0x3008 && r <= 0x3020) || r === 0x3030 || r === 0xfd3e || r === 0xfd3f || r === 0xfe45 || r === 0xfe46
|
||||
);
|
||||
}
|
||||
|
||||
const decimalRe = /^-?\d+(\.\d+)?$/;
|
||||
|
||||
/**
|
||||
* Parses a message of ICU MessageFormat, as package i18n's ParseMessage
|
||||
* does: the same messages parse, and fail, in Go and in pages.
|
||||
*/
|
||||
export function parseMessage(source: string): MessagePart[] {
|
||||
let i = 0;
|
||||
const s = source;
|
||||
const fail = (reason: string): never => {
|
||||
throw new MessageSyntaxError(source, i, reason);
|
||||
};
|
||||
const space = () => {
|
||||
while (i < s.length && isPatternSpace(s[i]!)) i++;
|
||||
};
|
||||
const word = (): string => {
|
||||
const start = i;
|
||||
while (i < s.length) {
|
||||
const c = String.fromCodePoint(s.codePointAt(i)!);
|
||||
if (isPatternSpace(c) || isPatternSyntax(c)) break;
|
||||
i += c.length;
|
||||
}
|
||||
return s.slice(start, i);
|
||||
};
|
||||
const validName = (name: string): boolean =>
|
||||
/^\d/.test(name) ? /^(0|[1-9]\d*)$/.test(name) : /^[\p{L}_]/u.test(name);
|
||||
|
||||
const message = (depth: number, inPlural: boolean): MessagePart[] => {
|
||||
if (depth > 32) fail("arguments nest too deep");
|
||||
const parts: MessagePart[] = [];
|
||||
let text = "";
|
||||
const flush = () => {
|
||||
if (text !== "") parts.push(text);
|
||||
text = "";
|
||||
};
|
||||
while (i < s.length) {
|
||||
const c = s[i]!;
|
||||
if (c === "'") {
|
||||
i++;
|
||||
if (s[i] === "'") {
|
||||
text += "'";
|
||||
i++;
|
||||
} else if (i < s.length && (s[i] === "{" || s[i] === "}" || (s[i] === "#" && inPlural))) {
|
||||
while (i < s.length) {
|
||||
if (s[i] === "'") {
|
||||
if (s[i + 1] === "'") {
|
||||
text += "'";
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
text += s[i];
|
||||
i++;
|
||||
}
|
||||
} else {
|
||||
text += "'";
|
||||
}
|
||||
} else if (c === "{") {
|
||||
flush();
|
||||
parts.push(argument(depth));
|
||||
} else if (c === "}") {
|
||||
break;
|
||||
} else if (c === "#" && inPlural) {
|
||||
flush();
|
||||
parts.push({ type: "pound" });
|
||||
i++;
|
||||
} else {
|
||||
text += c;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return parts;
|
||||
};
|
||||
|
||||
const argument = (depth: number): MessagePart => {
|
||||
i++; // {
|
||||
space();
|
||||
const name = word();
|
||||
if (name === "") fail("an argument has no name");
|
||||
if (!validName(name)) fail(`${JSON.stringify(name)} is not an argument name`);
|
||||
space();
|
||||
if (i >= s.length) fail(`unclosed argument {${name}`);
|
||||
if (s[i] === "}") {
|
||||
i++;
|
||||
return { type: "arg", name };
|
||||
}
|
||||
if (s[i] !== ",") fail(`expected , or } after the argument name ${JSON.stringify(name)}`);
|
||||
i++;
|
||||
space();
|
||||
const type = word();
|
||||
space();
|
||||
if (type === "number" || type === "date" || type === "time") {
|
||||
let style = "";
|
||||
if (s[i] === ",") {
|
||||
i++;
|
||||
const start = i;
|
||||
let nest = 0;
|
||||
for (;;) {
|
||||
if (i >= s.length) fail("unclosed style");
|
||||
const c = s[i];
|
||||
if (c === "'") {
|
||||
const end = s.indexOf("'", i + 1);
|
||||
if (end < 0) fail("unclosed quote in a style");
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (c === "{") nest++;
|
||||
if (c === "}") {
|
||||
if (nest === 0) break;
|
||||
nest--;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
style = s.slice(start, i).replace(/^[\s\u0085\u200e\u200f]+|[\s\u0085\u200e\u200f]+$/g, "");
|
||||
if (style === "") fail(`the ${type} argument ${JSON.stringify(name)} has an empty style`);
|
||||
}
|
||||
if (s[i] !== "}") fail(`unclosed argument {${name}, ${type}`);
|
||||
i++;
|
||||
return { type, name, style };
|
||||
}
|
||||
if (type === "") fail(`the argument ${JSON.stringify(name)} has no type`);
|
||||
if (type !== "plural" && type !== "selectordinal" && type !== "select") {
|
||||
fail(`unknown argument type ${JSON.stringify(type)} (want number, date, time, plural, selectordinal or select)`);
|
||||
}
|
||||
if (s[i] !== ",") fail(`expected , after ${type}`);
|
||||
i++;
|
||||
const plural = type !== "select";
|
||||
let offset = 0;
|
||||
space();
|
||||
if (plural && s.startsWith("offset:", i)) {
|
||||
i += "offset:".length;
|
||||
space();
|
||||
const start = i;
|
||||
while (i < s.length && s[i]! >= "0" && s[i]! <= "9") i++;
|
||||
if (start === i || i - start > 15) fail("offset: needs a number");
|
||||
offset = Number(s.slice(start, i));
|
||||
}
|
||||
const cases: { key: string; parts: MessagePart[] }[] = [];
|
||||
for (;;) {
|
||||
space();
|
||||
if (i >= s.length) fail(`unclosed ${type} argument ${JSON.stringify(name)}`);
|
||||
if (s[i] === "}") {
|
||||
i++;
|
||||
break;
|
||||
}
|
||||
let key: string;
|
||||
if (plural && s[i] === "=") {
|
||||
i++;
|
||||
const start = i;
|
||||
while (i < s.length && /[0-9.]/.test(s[i]!)) i++;
|
||||
const value = s.slice(start, i);
|
||||
if (!/^\d+(\.\d+)?$/.test(value)) fail(`=${value} is not a number`);
|
||||
key = "=" + value;
|
||||
} else {
|
||||
key = word();
|
||||
if (key === "") fail(`expected a case of the ${type} argument ${JSON.stringify(name)}`);
|
||||
if (plural && !pluralKeywords.includes(key)) {
|
||||
fail(`${JSON.stringify(key)} is not a plural category (zero, one, two, few, many, other)`);
|
||||
}
|
||||
}
|
||||
if (cases.some((c) => c.key === key)) fail(`the ${type} argument ${JSON.stringify(name)} has the case ${key} twice`);
|
||||
space();
|
||||
if (s[i] !== "{") fail(`expected { after the case ${key}`);
|
||||
i++;
|
||||
const parts = message(depth + 1, plural);
|
||||
if (i >= s.length) fail(`unclosed case ${key}`);
|
||||
i++; // }
|
||||
cases.push({ key, parts });
|
||||
}
|
||||
if (!cases.some((c) => c.key === "other")) fail(`the ${type} argument ${JSON.stringify(name)} has no other case`);
|
||||
return { type: type as "plural" | "selectordinal" | "select", name, offset, cases };
|
||||
};
|
||||
|
||||
const parts = message(0, false);
|
||||
if (i < s.length) fail("unmatched }");
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** A number as a page formats it: its value, and its visible fraction digits. */
|
||||
interface Num {
|
||||
value: number;
|
||||
/** The fraction digits a string of a decimal number shows, as 2 for "1.50". */
|
||||
digits?: number;
|
||||
/** The decimal number as written, for the cases of exact values. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
function toNum(v: unknown): Num | undefined {
|
||||
if (typeof v === "number") return Number.isFinite(v) ? { value: v, text: String(v) } : undefined;
|
||||
if (typeof v === "bigint") return { value: Number(v), text: v.toString() };
|
||||
if (typeof v === "string") {
|
||||
const t = v.trim();
|
||||
if (!decimalRe.test(t)) return undefined;
|
||||
return { value: Number(t), digits: t.includes(".") ? t.split(".")[1]!.length : 0, text: t };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Writes n less offset, with the fraction digits of n. */
|
||||
function minus(n: Num, offset: number): Num {
|
||||
if (offset === 0) return n;
|
||||
const value = n.value - offset;
|
||||
if (n.digits !== undefined) return { value, digits: n.digits, text: value.toFixed(n.digits) };
|
||||
return { value, text: String(value) };
|
||||
}
|
||||
|
||||
/** Whether a number written as text equals an exact case, "=1" for 1.0. */
|
||||
function exactEquals(text: string, exact: string): boolean {
|
||||
if (text.startsWith("-")) return false;
|
||||
const norm = (s: string) => {
|
||||
let [i, f = ""] = s.split(".");
|
||||
i = i!.replace(/^0+(?=\d)/, "");
|
||||
f = f.replace(/0+$/, "");
|
||||
return f === "" ? i : `${i}.${f}`;
|
||||
};
|
||||
return /^\d+(\.\d+)?$/.test(text) && norm(text) === norm(exact);
|
||||
}
|
||||
|
||||
const caches = new Map<string, Intl.PluralRules | Intl.NumberFormat | Intl.DateTimeFormat>();
|
||||
|
||||
function cached<T extends Intl.PluralRules | Intl.NumberFormat | Intl.DateTimeFormat>(key: string, make: () => T): T {
|
||||
let v = caches.get(key) as T | undefined;
|
||||
if (!v) {
|
||||
v = make();
|
||||
if (caches.size > 256) caches.clear();
|
||||
caches.set(key, v);
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
function safeLocale(locale: string): string | undefined {
|
||||
try {
|
||||
return Intl.getCanonicalLocales(locale)[0];
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function pluralCategory(locale: string, n: Num, type: "cardinal" | "ordinal"): string {
|
||||
const digits = n.digits;
|
||||
const pr = cached(`p|${locale}|${type}|${digits ?? ""}`, () =>
|
||||
new Intl.PluralRules(safeLocale(locale), digits === undefined ? { type } : { type, minimumFractionDigits: digits, maximumFractionDigits: digits }),
|
||||
);
|
||||
return (pr as Intl.PluralRules).select(Math.abs(n.value));
|
||||
}
|
||||
|
||||
/** The hooks that write numbers and dates, which tests and apps may replace. */
|
||||
export const formatters = {
|
||||
/**
|
||||
* Writes a number in an ICU number style: "" (the default), "integer",
|
||||
* "percent", or a skeleton ("::percent .00"), of which this formatter
|
||||
* reads percent, integer, precision-integer, the precision of fraction
|
||||
* digits (.00, .0#, .##), group-off and currency/, and writes the rest
|
||||
* as the default. Package i18n reads the same.
|
||||
*/
|
||||
number(locale: string, n: number, style: string, digits?: number): string {
|
||||
const options: Intl.NumberFormatOptions & { roundingMode?: string } = {};
|
||||
const stems = style.startsWith("::") ? style.slice(2).trim().split(/\s+/) : [style];
|
||||
let fraction = false;
|
||||
for (const stem of stems) {
|
||||
if (stem === "integer" || stem === "precision-integer") {
|
||||
options.maximumFractionDigits = 0;
|
||||
options.roundingMode = "halfEven";
|
||||
} else if (stem === "percent") {
|
||||
options.style = "percent";
|
||||
options.roundingMode = "halfEven";
|
||||
} else if (stem === "group-off") {
|
||||
options.useGrouping = false;
|
||||
} else if (/^\.[0#]+$/.test(stem)) {
|
||||
options.minimumFractionDigits = stem.split("0").length - 1;
|
||||
options.maximumFractionDigits = stem.length - 1;
|
||||
fraction = true;
|
||||
} else if (stem.startsWith("currency/")) {
|
||||
options.style = "currency";
|
||||
options.currency = stem.slice("currency/".length);
|
||||
}
|
||||
}
|
||||
if (digits !== undefined && !fraction && options.style === undefined && options.maximumFractionDigits === undefined) {
|
||||
options.minimumFractionDigits = options.maximumFractionDigits = Math.min(digits, 100);
|
||||
}
|
||||
const nf = cached(`n|${locale}|${JSON.stringify(options)}`, () => new Intl.NumberFormat(safeLocale(locale), options));
|
||||
return (nf as Intl.NumberFormat).format(n);
|
||||
},
|
||||
/**
|
||||
* Writes a time: its date, its time or both ("datetime"), in an ICU
|
||||
* style, "short", "medium" (the default), "long" or "full", or a
|
||||
* skeleton of CLDR ("::yMMMd"), which Intl finds the locale's pattern
|
||||
* of as package i18n does.
|
||||
*/
|
||||
date(locale: string, d: Date, kind: "date" | "time" | "datetime", style: string): string {
|
||||
const s = (["short", "medium", "long", "full"].includes(style) ? style : "medium") as "short" | "medium" | "long" | "full";
|
||||
const options: Intl.DateTimeFormatOptions = style.startsWith("::")
|
||||
? skeletonOptions(style.slice(2).trim())
|
||||
: kind === "date"
|
||||
? { dateStyle: s }
|
||||
: kind === "time"
|
||||
? { timeStyle: s }
|
||||
: { dateStyle: "short", timeStyle: "short" };
|
||||
const df = cached(`d|${locale}|${JSON.stringify(options)}`, () => new Intl.DateTimeFormat(safeLocale(locale), options));
|
||||
return (df as Intl.DateTimeFormat).format(d);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The options of Intl.DateTimeFormat of a skeleton of CLDR, "yMMMd" or
|
||||
* "jm": V8 makes the skeleton back of them, and finds its pattern with
|
||||
* ICU's DateTimePatternGenerator. An hour letter other than j is an
|
||||
* hourCycle, as in package i18n. EEEEEE, CLDR's short weekday ("Mo"),
|
||||
* has no option of Intl: it is the abbreviated one ("Mon"), where package
|
||||
* i18n writes the short one.
|
||||
*/
|
||||
export function skeletonOptions(skeleton: string): Intl.DateTimeFormatOptions {
|
||||
const o: Intl.DateTimeFormatOptions = {};
|
||||
for (const [field] of skeleton.matchAll(/([A-Za-z])\1*/g)) {
|
||||
const n = field.length;
|
||||
switch (field[0]) {
|
||||
case "y":
|
||||
o.year = n === 2 ? "2-digit" : "numeric";
|
||||
break;
|
||||
case "M":
|
||||
case "L":
|
||||
o.month = n === 1 ? "numeric" : n === 2 ? "2-digit" : n === 3 ? "short" : n === 4 ? "long" : "narrow";
|
||||
break;
|
||||
case "d":
|
||||
o.day = n === 2 ? "2-digit" : "numeric";
|
||||
break;
|
||||
case "E":
|
||||
case "c":
|
||||
o.weekday = n === 4 ? "long" : n === 5 ? "narrow" : "short";
|
||||
break;
|
||||
case "j":
|
||||
case "h":
|
||||
case "H":
|
||||
case "K":
|
||||
case "k":
|
||||
o.hour = n === 2 ? "2-digit" : "numeric";
|
||||
if (field[0] === "h") o.hourCycle = "h12";
|
||||
if (field[0] === "H") o.hourCycle = "h23";
|
||||
if (field[0] === "K") o.hourCycle = "h11";
|
||||
if (field[0] === "k") o.hourCycle = "h24";
|
||||
break;
|
||||
case "m":
|
||||
o.minute = n === 2 ? "2-digit" : "numeric";
|
||||
break;
|
||||
case "s":
|
||||
o.second = n === 2 ? "2-digit" : "numeric";
|
||||
break;
|
||||
case "z":
|
||||
case "v":
|
||||
o.timeZoneName = n >= 4 ? "long" : "short";
|
||||
break;
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
function valueString(locale: string, v: unknown): string {
|
||||
if (typeof v === "string") return v;
|
||||
if (v instanceof Date) return formatters.date(locale, v, "datetime", "short");
|
||||
if (v === null || v === undefined) return "";
|
||||
if (typeof v === "number" || typeof v === "bigint") {
|
||||
const n = toNum(v);
|
||||
return n ? formatters.number(locale, n.value, "", n.digits) : String(v);
|
||||
}
|
||||
if (v instanceof Error) return v.message;
|
||||
return String(v);
|
||||
}
|
||||
|
||||
/** Transforms the text of a message for a pseudo locale. */
|
||||
interface Pseudo {
|
||||
text(s: string): string;
|
||||
placeholder(s: string): string;
|
||||
wrap(s: string): string;
|
||||
}
|
||||
|
||||
const accented: Record<string, string> = {
|
||||
a: "å", b: "ƀ", c: "ç", d: "ð", e: "é", f: "ƒ", g: "ĝ", h: "ĥ", i: "î", j: "ĵ", k: "ķ", l: "ļ", m: "ɱ",
|
||||
n: "ñ", o: "ö", p: "þ", q: "ǫ", r: "ŕ", s: "š", t: "ţ", u: "û", v: "ṽ", w: "ŵ", x: "ẋ", y: "ý", z: "ž",
|
||||
A: "Å", B: "Ɓ", C: "Ç", D: "Ð", E: "É", F: "Ƒ", G: "Ĝ", H: "Ĥ", I: "Î", J: "Ĵ", K: "Ķ", L: "Ļ", M: "Ṁ",
|
||||
N: "Ñ", O: "Ö", P: "Þ", Q: "Ǫ", R: "Ŕ", S: "Š", T: "Ţ", U: "Û", V: "Ṽ", W: "Ŵ", X: "Ẋ", Y: "Ý", Z: "Ž",
|
||||
};
|
||||
|
||||
const padWords = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty".split(" ");
|
||||
|
||||
const RLM = "\u200f";
|
||||
const RLO = "\u202e";
|
||||
const PDF = "\u202c";
|
||||
|
||||
/** The pseudo locales, which test layouts without translations. */
|
||||
export const pseudoLocales = ["en-XA", "ar-XB"] as const;
|
||||
|
||||
function canonical(tag: string): string {
|
||||
return safeLocale(tag.replace(/_/g, "-").split(/[.@]/)[0]!) ?? "";
|
||||
}
|
||||
|
||||
/** Strips the extensions of a canonical tag, as "-u-ca-buddhist". */
|
||||
function stripExtensions(tag: string): string {
|
||||
const parts = tag.split("-");
|
||||
const i = parts.findIndex((p, i) => i > 0 && p.length === 1);
|
||||
return i < 0 ? tag : parts.slice(0, i).join("-");
|
||||
}
|
||||
|
||||
/** Reports whether tag is a pseudo locale: en-XA or ar-XB. */
|
||||
export function isPseudoLocale(tag: string): boolean {
|
||||
return (pseudoLocales as readonly string[]).includes(stripExtensions(canonical(tag)));
|
||||
}
|
||||
|
||||
function pseudoFor(locale: string): Pseudo | undefined {
|
||||
switch (stripExtensions(canonical(locale))) {
|
||||
case "en-XA": {
|
||||
let length = 0;
|
||||
return {
|
||||
text(s) {
|
||||
let out = "";
|
||||
for (const c of s) {
|
||||
out += accented[c] ?? c;
|
||||
length++;
|
||||
}
|
||||
return out;
|
||||
},
|
||||
placeholder: (s) => s,
|
||||
wrap(s) {
|
||||
const pad = Math.floor((length * 2 + 4) / 5);
|
||||
let out = "[" + s;
|
||||
for (let i = 0, n = 0; n < pad; i++) {
|
||||
const w = padWords[i % padWords.length]!;
|
||||
out += " " + w;
|
||||
n += 1 + w.length;
|
||||
}
|
||||
return out + "]";
|
||||
},
|
||||
};
|
||||
}
|
||||
case "ar-XB":
|
||||
return {
|
||||
text: (s) => s.replace(/[^\s]+/gu, (w) => RLM + RLO + w + PDF + RLM),
|
||||
placeholder: (s) => RLM + s + RLM,
|
||||
wrap: (s) => s,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function formatParts(
|
||||
parts: MessagePart[],
|
||||
locale: string,
|
||||
pluralLocale: string,
|
||||
args: Record<string, unknown>,
|
||||
pseudo: Pseudo | undefined,
|
||||
pound: { num?: Num; raw?: unknown } | undefined,
|
||||
): string {
|
||||
let out = "";
|
||||
const placeholder = (s: string) => (pseudo ? pseudo.placeholder(s) : s);
|
||||
for (const part of parts) {
|
||||
if (typeof part === "string") {
|
||||
out += pseudo ? pseudo.text(part) : part;
|
||||
continue;
|
||||
}
|
||||
if (part.type === "pound") {
|
||||
if (!pound) {
|
||||
out += "#";
|
||||
} else if (pound.num) {
|
||||
out += placeholder(formatters.number(locale, pound.num.value, "", pound.num.digits));
|
||||
} else {
|
||||
out += placeholder(valueString(locale, pound.raw));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(args, part.name)) {
|
||||
out += `{${part.name}}`;
|
||||
continue;
|
||||
}
|
||||
const v = args[part.name];
|
||||
switch (part.type) {
|
||||
case "arg":
|
||||
out += placeholder(valueString(locale, v));
|
||||
break;
|
||||
case "number": {
|
||||
const n = toNum(v);
|
||||
out += placeholder(n ? formatters.number(locale, n.value, part.style, n.digits) : valueString(locale, v));
|
||||
break;
|
||||
}
|
||||
case "date":
|
||||
case "time":
|
||||
out += placeholder(v instanceof Date ? formatters.date(locale, v, part.type, part.style) : valueString(locale, v));
|
||||
break;
|
||||
case "select": {
|
||||
const key = typeof v === "string" ? v : typeof v === "number" ? (toNum(v)?.text ?? String(v)) : String(v);
|
||||
const c = part.cases.find((c) => c.key === key) ?? part.cases.find((c) => c.key === "other")!;
|
||||
out += formatParts(c.parts, locale, pluralLocale, args, pseudo, pound);
|
||||
break;
|
||||
}
|
||||
case "plural":
|
||||
case "selectordinal": {
|
||||
const n = toNum(v);
|
||||
const other = part.cases.find((c) => c.key === "other")!;
|
||||
if (!n) {
|
||||
out += formatParts(other.parts, locale, pluralLocale, args, pseudo, { raw: v });
|
||||
break;
|
||||
}
|
||||
let chosen = part.cases.find((c) => c.key.startsWith("=") && exactEquals(n.text, c.key.slice(1)));
|
||||
const shown = minus(n, part.offset);
|
||||
if (!chosen) {
|
||||
const cat = pluralCategory(pluralLocale, shown, part.type === "plural" ? "cardinal" : "ordinal");
|
||||
chosen = part.cases.find((c) => c.key === cat) ?? other;
|
||||
}
|
||||
out += formatParts(chosen.parts, locale, pluralLocale, args, pseudo, { num: shown });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const parsedCache = new Map<string, MessagePart[]>();
|
||||
|
||||
function parsed(message: string): MessagePart[] {
|
||||
let parts = parsedCache.get(message);
|
||||
if (!parts) {
|
||||
parts = parseMessage(message);
|
||||
parsedCache.set(message, parts);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a message of ICU MessageFormat with the values of its arguments
|
||||
* for locale, as package i18n's Message.Format does: its plural rules
|
||||
* pick the cases, its conventions write numbers and dates, and the pseudo
|
||||
* locales en-XA and ar-XB transform the message. An argument args lacks is
|
||||
* written as it is, `{name}`. Throws a {@link MessageSyntaxError} for a
|
||||
* message that does not parse.
|
||||
*/
|
||||
export function formatMessage(locale: string, message: string, args: Record<string, unknown> = {}): string {
|
||||
const pseudo = pseudoFor(locale);
|
||||
return format(parsed(message), pseudo ? "en" : locale, pseudo ? "en" : locale, args, pseudo);
|
||||
}
|
||||
|
||||
function format(parts: MessagePart[], locale: string, pluralLocale: string, args: Record<string, unknown>, pseudo: Pseudo | undefined): string {
|
||||
const out = formatParts(parts, locale, pluralLocale, args, pseudo, undefined);
|
||||
return pseudo ? pseudo.wrap(out) : out;
|
||||
}
|
||||
|
||||
/** The data of a catalog, as the module `mygo generate` writes has it. */
|
||||
export interface CatalogData {
|
||||
/** The source language, which every message falls back to. */
|
||||
source: string;
|
||||
/** The languages of the catalog: the source, then the others. */
|
||||
languages: string[];
|
||||
/** For each language, the languages it falls back along: itself, its parents, the source. */
|
||||
fallbacks: Record<string, string[]>;
|
||||
/** The names of the arguments of each key, in the order its function takes them. */
|
||||
params: Record<string, string[]>;
|
||||
/** The messages of each language by key. */
|
||||
messages: Record<string, Record<string, string>>;
|
||||
}
|
||||
|
||||
/** A catalog of messages in a page, which {@link createCatalog} returns. */
|
||||
export interface Catalog<M> {
|
||||
/** The languages of the catalog: the source, then the others. */
|
||||
readonly languages: readonly string[];
|
||||
/** Formats the message of key in locale, or returns key without one. */
|
||||
format(locale: string, key: string, args?: Record<string, unknown>): string;
|
||||
/** Returns the language of the catalog whose messages locale says. */
|
||||
resolve(locale: string): string;
|
||||
/** The messages in the language the page shows, read at each call. */
|
||||
messages(): M;
|
||||
/** The messages in the language of locale. */
|
||||
messagesIn(locale: string): M;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the language the page shows: the app's, which the MyGo runtime
|
||||
* holds (`window.mygo.locale`, set before the page's scripts run), else
|
||||
* the browser's first preferred language.
|
||||
*/
|
||||
export function currentLocale(): string {
|
||||
const rt = (globalThis as { mygo?: { locale?: unknown } }).mygo;
|
||||
const locale = typeof rt?.locale === "function" ? (rt.locale as () => unknown)() : rt?.locale;
|
||||
if (typeof locale === "string" && locale !== "") return locale;
|
||||
if (typeof navigator !== "undefined") return navigator.languages?.[0] ?? navigator.language ?? "";
|
||||
return "";
|
||||
}
|
||||
|
||||
/** Creates the catalog of a module `mygo generate` wrote. */
|
||||
export function createCatalog<M>(data: CatalogData): Catalog<M> {
|
||||
const resolved = new Map<string, string>();
|
||||
const resolve = (locale: string): string => {
|
||||
let r = resolved.get(locale);
|
||||
if (r !== undefined) return r;
|
||||
r = data.source;
|
||||
const tag = stripExtensions(canonical(locale));
|
||||
if (data.languages.includes(tag)) {
|
||||
r = tag;
|
||||
} else if (tag !== "" && !isPseudoLocale(tag)) {
|
||||
// The tag without its last subtags, then a language written in the
|
||||
// same script, as zh-Hant for zh-TW.
|
||||
const found = truncations(tag).find((t) => data.languages.includes(t)) ?? sameScript(tag, data.languages);
|
||||
if (found) r = found;
|
||||
}
|
||||
resolved.set(locale, r);
|
||||
return r;
|
||||
};
|
||||
const has = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const lookup = (locale: string, key: string): [string, string] | undefined => {
|
||||
const lang = isPseudoLocale(locale) ? data.source : resolve(locale);
|
||||
for (const t of data.fallbacks[lang] ?? [data.source]) {
|
||||
// Own keys only: a key named as a property of every object, as
|
||||
// "toString", is a message only where the catalog has it.
|
||||
const messages = has(data.messages, t) ? data.messages[t] : undefined;
|
||||
const m = messages && has(messages, key) ? messages[key] : undefined;
|
||||
if (m !== undefined) return [m, t];
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const formatKey = (locale: string, key: string, args: Record<string, unknown> = {}): string => {
|
||||
const found = lookup(locale, key);
|
||||
if (!found) return key;
|
||||
const [message, lang] = found;
|
||||
let parts: MessagePart[];
|
||||
try {
|
||||
parts = parsed(message);
|
||||
} catch {
|
||||
return key;
|
||||
}
|
||||
const pseudo = pseudoFor(locale);
|
||||
const numbers = pseudo || locale === "" ? lang : locale;
|
||||
return format(parts, numbers, lang, args, pseudo);
|
||||
};
|
||||
const bind = (locale: () => string): M => {
|
||||
const out: Record<string, (...values: unknown[]) => string> = {};
|
||||
for (const [key, names] of Object.entries(data.params)) {
|
||||
out[key] = (...values: unknown[]) => {
|
||||
const args: Record<string, unknown> = Object.create(null);
|
||||
names.forEach((name, i) => (args[name] = values[i]));
|
||||
return formatKey(locale(), key, args);
|
||||
};
|
||||
}
|
||||
return out as M;
|
||||
};
|
||||
return {
|
||||
languages: data.languages,
|
||||
format: formatKey,
|
||||
resolve,
|
||||
messages: () => bind(currentLocale),
|
||||
messagesIn: (locale) => bind(() => locale),
|
||||
};
|
||||
}
|
||||
|
||||
function truncations(tag: string): string[] {
|
||||
const parts = tag.split("-");
|
||||
const out: string[] = [];
|
||||
for (let n = parts.length; n > 0; n--) out.push(parts.slice(0, n).join("-"));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The first of langs in the language and script of tag. */
|
||||
function sameScript(tag: string, langs: string[]): string | undefined {
|
||||
try {
|
||||
const want = new Intl.Locale(tag).maximize();
|
||||
const same = langs.filter((l) => {
|
||||
const have = new Intl.Locale(l).maximize();
|
||||
return have.language === want.language && have.script === want.script;
|
||||
});
|
||||
return same.find((l) => new Intl.Locale(l).maximize().region === want.region) ?? same[0];
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import {
|
||||
Channel,
|
||||
bind,
|
||||
call,
|
||||
currentWindow,
|
||||
direction,
|
||||
event,
|
||||
isCallError,
|
||||
isMyGo,
|
||||
locale,
|
||||
on,
|
||||
onDocumentReload,
|
||||
onDocumentState,
|
||||
onFileDrop,
|
||||
onLocaleChange,
|
||||
onPreferences,
|
||||
onWindowActive,
|
||||
preferences,
|
||||
runtime,
|
||||
windowActive,
|
||||
type DocumentState,
|
||||
type FileDrop,
|
||||
type Runtime,
|
||||
type ThemePreferences,
|
||||
} from "./index";
|
||||
import type { CallOptions } from "./types";
|
||||
|
||||
const calls: [string, unknown[]][] = [];
|
||||
const listeners = new Map<string, (payload: unknown) => void>();
|
||||
|
||||
const fake: Runtime = {
|
||||
call: async <T>(method: string, ...args: unknown[]) => {
|
||||
calls.push([method, args]);
|
||||
if (method === "Svc.Fail") {
|
||||
const err = new Error("boom") as Error & { method: string };
|
||||
err.name = "CallError";
|
||||
err.method = method;
|
||||
throw err;
|
||||
}
|
||||
return method as T;
|
||||
},
|
||||
callWith: async <T>(method: string, args: unknown[], options?: CallOptions) => {
|
||||
calls.push([method, args]);
|
||||
if (options?.signal?.aborted) throw options.signal.reason;
|
||||
return method as T;
|
||||
},
|
||||
channel: <T>(onmessage?: (value: T) => void) =>
|
||||
({ onmessage, onclose: null, closed: false, close() {}, [Symbol.asyncIterator]: () => ({}) }) as unknown as Channel<T>,
|
||||
on: (name, listener) => {
|
||||
listeners.set(name, listener as (payload: unknown) => void);
|
||||
return () => listeners.delete(name);
|
||||
},
|
||||
once: (name, listener) => {
|
||||
listeners.set(name, listener as (payload: unknown) => void);
|
||||
return () => listeners.delete(name);
|
||||
},
|
||||
platform: "darwin",
|
||||
windowId: 1,
|
||||
version: "0.1.0",
|
||||
preferences: { accent: null, reduceMotion: false, reduceTransparency: true, highContrast: false, textScale: 1 },
|
||||
locale: "en",
|
||||
dir: "ltr",
|
||||
windowActive: false,
|
||||
window: {
|
||||
minimize: () => fake.call("mygo:window.Minimize"),
|
||||
maximize: () => fake.call("mygo:window.Maximize"),
|
||||
unmaximize: () => fake.call("mygo:window.Unmaximize"),
|
||||
toggleMaximize: () => fake.call("mygo:window.ToggleMaximize"),
|
||||
isMaximized: () => fake.call("mygo:window.IsMaximized"),
|
||||
toggleFullScreen: () => fake.call("mygo:window.ToggleFullScreen"),
|
||||
close: () => fake.call("mygo:window.Close"),
|
||||
setTitle: (title) => fake.call("mygo:window.SetTitle", title),
|
||||
},
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
delete (globalThis as { mygo?: Runtime }).mygo;
|
||||
calls.length = 0;
|
||||
listeners.clear();
|
||||
});
|
||||
|
||||
test("outside MyGo", async () => {
|
||||
expect(isMyGo()).toBe(false);
|
||||
expect(() => runtime()).toThrow("runtime not found");
|
||||
await expect(call("Svc.Method")).rejects.toThrow("runtime not found");
|
||||
});
|
||||
|
||||
test("delegates to window.mygo", async () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
expect(isMyGo()).toBe(true);
|
||||
expect(await call<string>("Svc.Method", 1, "a")).toBe("Svc.Method");
|
||||
expect(calls).toEqual([["Svc.Method", [1, "a"]]]);
|
||||
|
||||
const got: unknown[] = [];
|
||||
const off = event<{ n: number }>("tick").on((p) => got.push(p.n));
|
||||
listeners.get("tick")?.({ n: 7 });
|
||||
off();
|
||||
expect(got).toEqual([7]);
|
||||
expect(listeners.has("tick")).toBe(false);
|
||||
|
||||
on("other", () => {});
|
||||
expect(listeners.has("other")).toBe(true);
|
||||
|
||||
await currentWindow.setTitle("Hi");
|
||||
expect(calls.at(-1)).toEqual(["mygo:window.SetTitle", ["Hi"]]);
|
||||
|
||||
const err = await call("Svc.Fail").catch((e: unknown) => e);
|
||||
expect(isCallError(err)).toBe(true);
|
||||
expect(isCallError(new Error("other"))).toBe(false);
|
||||
});
|
||||
|
||||
test("bind and with", async () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
const greet = bind<[string], string>("Greeter.Greet", (name: string) => [name]);
|
||||
expect(await greet("Ada")).toBe("Greeter.Greet");
|
||||
expect(calls).toEqual([["Greeter.Greet", ["Ada"]]]);
|
||||
|
||||
// The options of the call go with the arguments.
|
||||
const ac = new AbortController();
|
||||
expect(await greet.with({ signal: ac.signal })("Ada")).toBe("Greeter.Greet");
|
||||
expect(calls.at(-1)).toEqual(["Greeter.Greet", ["Ada"]]);
|
||||
|
||||
// A signal that is aborted already rejects the call.
|
||||
const aborted = new AbortController();
|
||||
aborted.abort("no time");
|
||||
await expect(greet.with({ signal: aborted.signal })("Ada")).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
test("Channel", () => {
|
||||
expect(() => new Channel()).toThrow("runtime not found");
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
const fn = (n: number) => n;
|
||||
const ch = new Channel<number>(fn);
|
||||
expect(ch.onmessage).toBe(fn);
|
||||
expect(ch.closed).toBe(false);
|
||||
});
|
||||
|
||||
test("onFileDrop", () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
const got: FileDrop[] = [];
|
||||
const off = onFileDrop((d) => got.push(d));
|
||||
listeners.get("mygo:file-drop")?.({ paths: ["/tmp/a.txt"], x: 10, y: 20 });
|
||||
expect(got).toEqual([{ paths: ["/tmp/a.txt"], x: 10, y: 20 }]);
|
||||
off();
|
||||
expect(listeners.has("mygo:file-drop")).toBe(false);
|
||||
});
|
||||
|
||||
test("onDocumentState and onDocumentReload", () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
const states: DocumentState[] = [];
|
||||
let reloads = 0;
|
||||
const off = onDocumentState((s) => states.push(s));
|
||||
const offReload = onDocumentReload(() => reloads++);
|
||||
const state = { name: "a.md", path: "/tmp/a.md", edited: true, readOnly: false, conflict: false, deleted: false };
|
||||
listeners.get("mygo:document-state")?.(state);
|
||||
listeners.get("mygo:document-reload")?.({});
|
||||
expect(states).toEqual([state]);
|
||||
expect(reloads).toBe(1);
|
||||
off();
|
||||
offReload();
|
||||
expect(listeners.has("mygo:document-state")).toBe(false);
|
||||
expect(listeners.has("mygo:document-reload")).toBe(false);
|
||||
});
|
||||
|
||||
test("preferences and onPreferences", () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
expect(preferences()).toEqual(fake.preferences);
|
||||
const got: ThemePreferences[] = [];
|
||||
const off = onPreferences((p) => got.push(p));
|
||||
const changed = { accent: "#ff8000", reduceMotion: true, reduceTransparency: false, highContrast: false, textScale: 1.25 };
|
||||
listeners.get("mygo:preferences")?.(changed);
|
||||
expect(got).toEqual([changed]);
|
||||
off();
|
||||
expect(listeners.has("mygo:preferences")).toBe(false);
|
||||
});
|
||||
|
||||
test("windowActive and onWindowActive", () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
expect(windowActive()).toBe(false);
|
||||
const got: boolean[] = [];
|
||||
const off = onWindowActive((a) => got.push(a));
|
||||
listeners.get("mygo:window-active")?.(true);
|
||||
expect(got).toEqual([true]);
|
||||
off();
|
||||
expect(listeners.has("mygo:window-active")).toBe(false);
|
||||
});
|
||||
|
||||
test("locale, direction and onLocaleChange", () => {
|
||||
(globalThis as { mygo?: Runtime }).mygo = fake;
|
||||
expect(locale()).toBe("en");
|
||||
expect(direction()).toBe("ltr");
|
||||
const got: [string, string][] = [];
|
||||
const off = onLocaleChange((tag, dir) => got.push([tag, dir]));
|
||||
listeners.get("mygo:locale")?.({ locale: "ar", dir: "rtl" });
|
||||
expect(got).toEqual([["ar", "rtl"]]);
|
||||
off();
|
||||
expect(listeners.has("mygo:locale")).toBe(false);
|
||||
});
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Typed access to the MyGo runtime, which MyGo injects into every page of
|
||||
* an app as `window.mygo`. The client that `mygo generate` writes for your Go
|
||||
* services is built on it; use it directly for window controls and the
|
||||
* platform:
|
||||
*
|
||||
* ```ts
|
||||
* import { currentWindow, runtime } from "mygo-runtime";
|
||||
*
|
||||
* if (runtime().platform === "darwin") document.body.classList.add("mac");
|
||||
* await currentWindow.toggleMaximize();
|
||||
* ```
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type {
|
||||
CallOptions,
|
||||
Channel as ChannelType,
|
||||
Direction,
|
||||
LocaleChange,
|
||||
Runtime,
|
||||
ThemePreferences,
|
||||
WindowControls,
|
||||
} from "./types";
|
||||
|
||||
export type { CallOptions, Direction, LocaleChange, Platform, Runtime, ThemePreferences, WindowControls } from "./types";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
/** The MyGo runtime; missing outside MyGo windows. */
|
||||
mygo?: Runtime;
|
||||
}
|
||||
}
|
||||
|
||||
/** Reports whether the page runs inside a MyGo window. */
|
||||
export function isMyGo(): boolean {
|
||||
return typeof globalThis === "object" && (globalThis as { mygo?: Runtime }).mygo !== undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the MyGo runtime. Throws when the page is not running inside a
|
||||
* MyGo window, e.g. when the dev server is opened in a regular browser.
|
||||
*/
|
||||
export function runtime(): Runtime {
|
||||
const rt = (globalThis as { mygo?: Runtime }).mygo;
|
||||
if (!rt) throw new Error("mygo: runtime not found; is this page running inside a MyGo window?");
|
||||
return rt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a bound Go method by name, e.g. `call("Greeter.Greet", "Ada")`.
|
||||
* Prefer the typed client generated by `mygo generate`. A Go error rejects
|
||||
* with a {@link CallError}.
|
||||
*/
|
||||
export function call<T = unknown>(method: string, ...args: unknown[]): Promise<T> {
|
||||
try {
|
||||
return runtime().call<T>(method, ...args);
|
||||
} catch (err) {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls a bound Go method by name, with the options of the call: a signal
|
||||
* that cancels it, as `fetch` does.
|
||||
*
|
||||
* ```ts
|
||||
* await callWith("Capture.Region", [rect], { signal: AbortSignal.timeout(5000) });
|
||||
* ```
|
||||
*
|
||||
* Aborting cancels the Go method's context, and rejects the promise with
|
||||
* the signal's reason. A method that takes no context runs to its end, and
|
||||
* its reply is of no use.
|
||||
*/
|
||||
export function callWith<T = unknown>(method: string, args: unknown[], options?: CallOptions): Promise<T> {
|
||||
try {
|
||||
return runtime().callWith<T>(method, args, options);
|
||||
} catch (err) {
|
||||
return Promise.reject(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A bound Go method, which a call may cancel.
|
||||
*/
|
||||
export interface Cancellable<A extends unknown[], R> {
|
||||
(...args: A): Promise<R>;
|
||||
/**
|
||||
* Returns the method with the options of its calls, e.g. a signal that
|
||||
* cancels them:
|
||||
*
|
||||
* ```ts
|
||||
* await Todos.list.with({ signal: AbortSignal.timeout(1000) })("todo");
|
||||
* ```
|
||||
*/
|
||||
with(options: CallOptions): (...args: A) => Promise<R>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds a bound Go method by name, for the client that `mygo generate`
|
||||
* writes. The arguments are built at the call, so that the options of the
|
||||
* call can be given with them.
|
||||
*/
|
||||
export function bind<A extends unknown[], R>(method: string, args: (...a: A) => unknown[]): Cancellable<A, R> {
|
||||
const bound = ((...a: A) => callWith<R>(method, args(...a))) as Cancellable<A, R>;
|
||||
bound.with = (options: CallOptions) => (...a: A) => callWith<R>(method, args(...a), options);
|
||||
return bound;
|
||||
}
|
||||
|
||||
/**
|
||||
* A stream of values from a Go method that takes a `*mygo.Channel[T]`.
|
||||
* Create one, pass it to the call in place of that parameter, and iterate
|
||||
* it or handle its values with `onmessage`:
|
||||
*
|
||||
* ```ts
|
||||
* const lines = new Channel<string>();
|
||||
* const done = Shell.tail("ping -c 3 example.com", lines);
|
||||
* for await (const line of lines) output.append(line + "\n");
|
||||
* await done;
|
||||
* ```
|
||||
*
|
||||
* It closes when the method returns; `close()`, or breaking out of the
|
||||
* loop, stops the method. A channel serves one call.
|
||||
*/
|
||||
export type Channel<T = unknown> = ChannelType<T>;
|
||||
|
||||
/** Creates a {@link Channel}, optionally with its `onmessage` handler. */
|
||||
export const Channel = function <T>(onmessage?: (value: T) => void): Channel<T> {
|
||||
return runtime().channel<T>(onmessage);
|
||||
} as unknown as new <T = unknown>(onmessage?: (value: T) => void) => Channel<T>;
|
||||
|
||||
/** Subscribes to a Go event by name. Returns a function that unsubscribes. */
|
||||
export function on<T = unknown>(name: string, listener: (payload: T) => void): () => void {
|
||||
return runtime().on<T>(name, listener);
|
||||
}
|
||||
|
||||
/** Like {@link on}, but unsubscribes after the first event. */
|
||||
export function once<T = unknown>(name: string, listener: (payload: T) => void): () => void {
|
||||
return runtime().once<T>(name, listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* The language the app shows, a BCP 47 tag such as "en" or "zh-Hans"
|
||||
* (`App.Locale`): the page has it from document start, so its first paint
|
||||
* can be in it.
|
||||
*
|
||||
* ```ts
|
||||
* document.documentElement.lang = locale();
|
||||
* document.documentElement.dir = direction();
|
||||
* ```
|
||||
*/
|
||||
export function locale(): string {
|
||||
return runtime().locale;
|
||||
}
|
||||
|
||||
/** The direction the language the app shows is written in: "ltr" or "rtl". */
|
||||
export function direction(): Direction {
|
||||
return runtime().dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to changes of the language the app shows, as `App.SetLocale`
|
||||
* makes them, or the user's languages while the app follows them. The
|
||||
* listener hears only of a language the page did not have: a page loaded
|
||||
* after a change starts with the new one. Returns a function that
|
||||
* unsubscribes.
|
||||
*
|
||||
* ```ts
|
||||
* onLocaleChange((tag, dir) => {
|
||||
* document.documentElement.lang = tag;
|
||||
* document.documentElement.dir = dir;
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function onLocaleChange(listener: (locale: string, dir: Direction) => void): () => void {
|
||||
return on<LocaleChange>("mygo:locale", (p) => listener(p.locale, p.dir));
|
||||
}
|
||||
|
||||
/** A typed event sent by the Go side, declared with `mygo.NewEvent`. */
|
||||
export interface GoEvent<T> {
|
||||
readonly name: string;
|
||||
/** Subscribes to the event and returns a function that unsubscribes. */
|
||||
on(listener: (payload: T) => void): () => void;
|
||||
/** Like on, but unsubscribes after the first event. */
|
||||
once(listener: (payload: T) => void): () => void;
|
||||
}
|
||||
|
||||
/** Returns the typed event `name`; the generated client declares them. */
|
||||
export function event<T>(name: string): GoEvent<T> {
|
||||
return {
|
||||
name,
|
||||
on: (listener) => on<T>(name, listener),
|
||||
once: (listener) => once<T>(name, listener),
|
||||
};
|
||||
}
|
||||
|
||||
/** The error of a call whose Go method returned an error. */
|
||||
export interface CallError extends Error {
|
||||
readonly name: "CallError";
|
||||
/** The method that failed, e.g. "Greeter.Greet". */
|
||||
readonly method: string;
|
||||
}
|
||||
|
||||
/** Reports whether err comes from a Go method that returned an error. */
|
||||
export function isCallError(err: unknown): err is CallError {
|
||||
return err instanceof Error && err.name === "CallError";
|
||||
}
|
||||
|
||||
/** Files dropped on the window, e.g. from Finder or Explorer. */
|
||||
export interface FileDrop {
|
||||
/** Absolute paths of the dropped files and directories. */
|
||||
paths: string[];
|
||||
/** Where they were dropped, in CSS pixels, like `clientX`. */
|
||||
x: number;
|
||||
/** Where they were dropped, in CSS pixels, like `clientY`. */
|
||||
y: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to files dropped on the window, with their paths, which DOM
|
||||
* drop events do not tell. Only the app's own pages get them. Returns a
|
||||
* function that unsubscribes.
|
||||
*
|
||||
* ```ts
|
||||
* onFileDrop(({ paths, x, y }) => {
|
||||
* const target = document.elementFromPoint(x, y);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function onFileDrop(listener: (drop: FileDrop) => void): () => void {
|
||||
return on<FileDrop>("mygo:file-drop", listener);
|
||||
}
|
||||
|
||||
/** The document a window shows (mygo.NewDocuments), as Go describes it. */
|
||||
export interface DocumentState {
|
||||
/** The file name, or a name such as "Untitled 2" while untitled. */
|
||||
name: string;
|
||||
/** The file, "" while the document is untitled. */
|
||||
path: string;
|
||||
/** Whether the document has unsaved changes. */
|
||||
edited: boolean;
|
||||
/** Whether its file can't be written: saving asks for another. */
|
||||
readOnly: boolean;
|
||||
/** Whether another app changed its file while it had unsaved changes. */
|
||||
conflict: boolean;
|
||||
/** Whether its file was deleted: saving writes it again. */
|
||||
deleted: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to the state of the window's document: edited, saved,
|
||||
* renamed, moved, changed by another app. Only the app's own pages get it.
|
||||
* Returns a function that unsubscribes.
|
||||
*
|
||||
* ```ts
|
||||
* onDocumentState(({ name, edited }) => {
|
||||
* heading.textContent = edited ? `${name} (edited)` : name;
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function onDocumentState(listener: (state: DocumentState) => void): () => void {
|
||||
return on<DocumentState>("mygo:document-state", listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to the window's document being read from its file again:
|
||||
* reverted, or changed by another app while it had no unsaved changes.
|
||||
* Fetch its content again, with the service bound to
|
||||
* `Documents.Service()`. Returns a function that unsubscribes.
|
||||
*/
|
||||
export function onDocumentReload(listener: () => void): () => void {
|
||||
return on<unknown>("mygo:document-reload", () => listener());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the accent color and the accessibility settings of the desktop
|
||||
* (`mygo.Theme.Preferences()` in Go), current from document start on.
|
||||
* Throws outside MyGo, as {@link runtime} does.
|
||||
*
|
||||
* ```ts
|
||||
* const { accent, reduceTransparency } = preferences();
|
||||
* ```
|
||||
*
|
||||
* CSS gets the accent and the text scale from the `--mygo-accent` and
|
||||
* `--mygo-text-scale` variables of `:root`.
|
||||
*/
|
||||
export function preferences(): ThemePreferences {
|
||||
return runtime().preferences;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to changes of the desktop's preferences, which
|
||||
* {@link preferences} returns; the listener gets the new ones. Returns a
|
||||
* function that unsubscribes.
|
||||
*
|
||||
* ```ts
|
||||
* const apply = (p: ThemePreferences) => root.classList.toggle("opaque", p.reduceTransparency);
|
||||
* apply(preferences());
|
||||
* onPreferences(apply);
|
||||
* ```
|
||||
*/
|
||||
export function onPreferences(listener: (preferences: ThemePreferences) => void): () => void {
|
||||
return on<ThemePreferences>("mygo:preferences", listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the window hosting the page is drawn as active: the
|
||||
* window the user's input goes to, while it or one of its flyouts has the
|
||||
* keyboard, as native apps tell which of their windows has it. Not DOM
|
||||
* focus, which a click into a flyout or the window's menus takes away.
|
||||
* Throws outside MyGo, as {@link runtime} does.
|
||||
*
|
||||
* CSS gets it from `<html>`, which has the `data-mygo-window-inactive`
|
||||
* attribute while the window is not active:
|
||||
*
|
||||
* ```css
|
||||
* :root[data-mygo-window-inactive] .sidebar .selected { background: #0000001a; color: inherit; }
|
||||
* ```
|
||||
*/
|
||||
export function windowActive(): boolean {
|
||||
return runtime().windowActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to changes of whether the window is drawn as active, which
|
||||
* {@link windowActive} returns. Returns a function that unsubscribes.
|
||||
*/
|
||||
export function onWindowActive(listener: (active: boolean) => void): () => void {
|
||||
return on<boolean>("mygo:window-active", listener);
|
||||
}
|
||||
|
||||
/** The window hosting the page, e.g. for a custom title bar. */
|
||||
export const currentWindow: WindowControls = {
|
||||
minimize: async () => runtime().window.minimize(),
|
||||
maximize: async () => runtime().window.maximize(),
|
||||
unmaximize: async () => runtime().window.unmaximize(),
|
||||
toggleMaximize: async () => runtime().window.toggleMaximize(),
|
||||
isMaximized: async () => runtime().window.isMaximized(),
|
||||
toggleFullScreen: async () => runtime().window.toggleFullScreen(),
|
||||
close: async () => runtime().window.close(),
|
||||
setTitle: async (title) => runtime().window.setTitle(title),
|
||||
};
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/** The operating system, using Node.js' `process.platform` names. */
|
||||
export type Platform = "darwin" | "linux" | "win32";
|
||||
|
||||
/** The direction a language is written in: left to right, or right to left. */
|
||||
export type Direction = "ltr" | "rtl";
|
||||
|
||||
/** The payload of the `mygo:locale` event. */
|
||||
export interface LocaleChange {
|
||||
/** The language the app shows now, e.g. "zh-Hans". */
|
||||
locale: string;
|
||||
/** The direction it is written in. */
|
||||
dir: Direction;
|
||||
}
|
||||
|
||||
/** Controls for the window hosting the page, handy for custom title bars. */
|
||||
export interface WindowControls {
|
||||
minimize(): Promise<void>;
|
||||
maximize(): Promise<void>;
|
||||
unmaximize(): Promise<void>;
|
||||
toggleMaximize(): Promise<void>;
|
||||
isMaximized(): Promise<boolean>;
|
||||
toggleFullScreen(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
setTitle(title: string): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A stream of values from a Go method that takes a `*mygo.Channel[T]`,
|
||||
* passed to the call in its place. Iterate it, or handle the values with
|
||||
* `onmessage`: values that arrive before either wait for it. The channel
|
||||
* closes when the method returns, or calls `Close`, once its values are
|
||||
* taken; `close()` stops the method.
|
||||
*/
|
||||
export interface Channel<T = unknown> extends AsyncIterable<T> {
|
||||
/** Called with each value, instead of iterating. */
|
||||
onmessage: ((value: T) => void) | null;
|
||||
/** Called when the channel closes. */
|
||||
onclose: (() => void) | null;
|
||||
/** Whether the channel is closed. */
|
||||
readonly closed: boolean;
|
||||
/**
|
||||
* Closes the channel, dropping values not taken yet: the Go method's
|
||||
* `Send` fails and its context is canceled. Breaking out of a
|
||||
* `for await` loop over the channel closes it too.
|
||||
*/
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The accent color and the accessibility settings of the desktop, as
|
||||
* `mygo.ThemePreferences` encodes them.
|
||||
*/
|
||||
export interface ThemePreferences {
|
||||
/** The accent color of the desktop's controls as "#rrggbb", or null where the desktop has none. */
|
||||
accent: string | null;
|
||||
/** Whether the desktop asks for less motion; `prefers-reduced-motion` tells it too. */
|
||||
reduceMotion: boolean;
|
||||
/**
|
||||
* Whether the desktop asks for opaque surfaces in place of translucent
|
||||
* ones: macOS's Reduce Transparency, Windows's transparency effects
|
||||
* turned off. Linux desktops have no such setting.
|
||||
*/
|
||||
reduceTransparency: boolean;
|
||||
/** Whether the desktop asks for more contrast; `prefers-contrast` tells it too. */
|
||||
highContrast: boolean;
|
||||
/** How many times larger than usual text should be; 1 is usual. */
|
||||
textScale: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The options of a call.
|
||||
*/
|
||||
export interface CallOptions {
|
||||
/**
|
||||
* Cancels the call when it is aborted: the Go method's context is
|
||||
* canceled, and the promise rejects with the signal's reason, as
|
||||
* `fetch` does. A method that takes no context runs to its end, and
|
||||
* its reply is of no use.
|
||||
*/
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/** The runtime MyGo injects into every page as `window.mygo`. */
|
||||
export interface Runtime {
|
||||
/** Calls a bound Go method, e.g. `call("Greeter.Greet", "Ada")`. */
|
||||
call<T = unknown>(method: string, ...args: unknown[]): Promise<T>;
|
||||
/**
|
||||
* Calls a bound Go method, with the options of the call: a signal that
|
||||
* cancels it.
|
||||
*/
|
||||
callWith<T = unknown>(method: string, args: unknown[], options?: CallOptions): Promise<T>;
|
||||
/**
|
||||
* Creates a channel to pass to a call of a Go method that streams values
|
||||
* through a `*mygo.Channel[T]` parameter. A channel serves one call.
|
||||
*/
|
||||
channel<T = unknown>(onmessage?: (value: T) => void): Channel<T>;
|
||||
/** Subscribes to a Go event. Returns a function that unsubscribes. */
|
||||
on<T = unknown>(event: string, listener: (payload: T) => void): () => void;
|
||||
/** Like `on`, but unsubscribes after the first event. */
|
||||
once<T = unknown>(event: string, listener: (payload: T) => void): () => void;
|
||||
/** The operating system. */
|
||||
readonly platform: Platform;
|
||||
/** Id of the Go `*mygo.Window` hosting this page. */
|
||||
readonly windowId: number;
|
||||
/** MyGo version. */
|
||||
readonly version: string;
|
||||
/**
|
||||
* The desktop's preferences, current from document start on; the
|
||||
* `mygo:preferences` event tells their changes.
|
||||
*/
|
||||
readonly preferences: ThemePreferences;
|
||||
/**
|
||||
* The language the app shows, a BCP 47 tag such as "en" or "zh-Hans"
|
||||
* (`App.Locale`): of the languages the app is written in, the one the
|
||||
* user reads best, or the one `App.SetLocale` chose. A page has it from
|
||||
* document start, and the `mygo:locale` event tells of changes.
|
||||
*/
|
||||
readonly locale: string;
|
||||
/** The direction `locale` is written in, for `<html dir>`. */
|
||||
readonly dir: Direction;
|
||||
/**
|
||||
* Whether the window is drawn as active: the window the user's input
|
||||
* goes to, while it or one of its flyouts has the keyboard, as native
|
||||
* apps tell which of their windows has it. The `mygo:window-active`
|
||||
* event tells its changes, and `<html data-mygo-window-inactive>` marks
|
||||
* a page whose window is not, for CSS.
|
||||
*/
|
||||
readonly windowActive: boolean;
|
||||
/** The window hosting this page. */
|
||||
readonly window: WindowControls;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user