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:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+283
View File
@@ -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 });
});
});
+79
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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);
}
+356
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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();
});
+8
View File
@@ -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);
}