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
+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