@vestra-player/sdk - v1.11.3
    Preparing search index...

    Add settings and translations

    Goal: the plugin has a page in the player's Options window whose choices survive a restart, and it shows its menus, windows, settings and messages in the user's interface language, while its code holds only English source text and no translation code: the player translates.

    The languages, file formats, template rules and limits are in Reference: translations.

    A settings page is a Slint file that exports a global (the bridge the plugin talks to) and a component (the layout):

    // ui/settings.slint
    import { CheckBox } from "std-widgets.slint";
    import { Theme } from "@vestra/theme.slint";
    
    export global HelloSettings {
        in-out property <bool> show-duration;
        callback show-duration-toggled(bool);
    }
    
    export component HelloSettingsPage inherits Rectangle {
        VerticalLayout {
            padding: Theme.dialog-padding;
            alignment: start;
            CheckBox {
                text: @tr("Show the duration");
                checked <=> HelloSettings.show-duration;
                toggled => { HelloSettings.show-duration-toggled(self.checked); }
            }
        }
    }
    

    Keep the value in a JSON store, so it survives a restart, and bind the page to it:

    type Settings = { showDuration: boolean };
    const settings = plugin.storage.json<Settings>("settings", {
    defaults: { showDuration: true },
    validate: (v): v is Settings =>
    typeof (v as Settings)?.showDuration === "boolean",
    });
    const page = plugin.settings.page("ui/settings.slint", {
    id: "hello",
    category: "plugins",
    title: "Hello",
    });
    page.bind(() => ({ showDuration: settings.value.showDuration }));
    page.on("showDurationToggled", (on: boolean) =>
    settings.save({ ...settings.value, showDuration: on }),
    );

    The page appears in the Options window under Plugins ▸ Hello. Where else a plugin can keep data is in Store a plugin's data.

    What the plugin declares, the player shows translated: command titles and paths, settings page titles, panel titles, command reasons, and the manifest's name, punchline, description and tags. Menus of different plugins merge by the English words, so write a shared submenu the same way the other plugins do.

    declare const counterWindow: Window;
    // ---cut---
    plugin.commands.add({
    id: "counter",
    path: ["Tools", "Counter…"], // English: menus merge by these words
    run: () => counterWindow.show(),
    });

    A window's texts belong in its .slint file. TypeScript passes data (count, step), never finished sentences.

    title: @tr("Counter");
    Text { text: @tr("{n} click" | "{n} clicks" % root.count); }
    Button { text: @tr("Add {}", root.step); }
    

    osd.show, OsdPanel.set and dialogs.confirm take a template and its arguments. Never build the sentence in TypeScript (`Speed ${rate}×`): a translator can only translate a whole template, and word order differs between languages.

    declare const rate: number;
    declare const count: number;
    // ---cut---
    await plugin.osd.show("Speed {}×", [rate]);
    await plugin.dialogs.confirm({
    message: "Delete {} bookmarks?",
    confirm: "Delete",
    args: [count],
    });

    For what is not text (a date), use the run's language: date.toLocaleDateString(plugin.i18n.locale).

    For a menu item "Track 2 (opus)", a list whose first item is "No Audio" and the rest track names, or a message whose argument is a sentence of its own, make a text value with plugin.i18n.text(source, args) and pass it where a string would go. Write the source as a literal, never text(`Track ${n}`).

    declare const n: number;
    declare const codec: string;
    declare const picker: View;
    declare const tracks: { id: number; title: string }[];
    declare const missing: string[];
    // ---cut---
    const { text, list } = plugin.i18n;

    // A menu item with data (the menu merges by the English "Track 2 (opus)").
    plugin.commands.add({
    id: `track-${n}`,
    path: ["@audio", "Audio Track", text("Track {} ({})", [n, codec])],
    run: () => {},
    });

    // A [string] model: fixed words and data in one list.
    picker.set({
    labels: [
    text("No Audio"),
    ...tracks.map((t) => text("Track {} · {}", [t.id, t.title])),
    ],
    });

    // An argument that is a sentence of its own.
    await plugin.osd.show("Download failed: {}", [text("Connection timed out")]);

    // Items joined the language's way: "a.glsl, b.glsl", "a.glsl、b.glsl".
    await plugin.osd.show("Removed missing shaders: {}", [list(missing)]);

    Where a text value is accepted is in Reference: translations. For text that leaves the player (the clipboard, a file), plugin.i18n.resolve(value) returns the translated string.

    A comment that starts with TRANSLATORS: right before a text is copied into the files:

    const REASONS = {
    // TRANSLATORS: the download took longer than 30 seconds.
    timeout: "Connection timed out",
    dns: "Server not found",
    } as const;

    Extract the texts, start a language, translate it in any .po editor (Poedit, Lokalize, Weblate, a text editor), and check:

    vestra-plugin i18n extract                     # locales/messages.pot, update every .po
    vestra-plugin i18n extract --locale zh-Hans # start a new language
    vestra-plugin i18n check # coverage; fails on stale catalogs

    Fill in each msgstr and keep every {} of the English:

    msgid "{} s of {} s"
    msgstr "{} 秒 / 共 {} 秒"
    

    Commit locales/ with the code, and run extract again after every text change, so i18n check (in CI) does not fail on a stale messages.pot. vestra-plugin build compiles the .po files into dist/locales/; with --plugin <dir> the player reads them directly (Files).

    When a machine or a language model translated an entry, flag it x-machine in the entry's #, line, and note a review of the whole file in a comment before the header. A person who knows the language checks each entry and deletes its x-machine; grep -c x-machine locales/zh-Hans.po counts what is left (Machine translations and review).

    Start the plugin with locale and assert on what a user of that language sees. Without locale the plugin's texts show in English.

    import assert from "node:assert/strict";
    import test from "node:test";
    import { startPlugin } from "@vestra-player/sdk/testing";
    import activate from "../main.ts";

    test("speaks Chinese", async () => {
    const { host, plugin, stop } = await startPlugin(activate, {
    directory: new URL("..", import.meta.url),
    locale: "zh-Hans",
    });
    assert.equal(plugin.i18n.locale, "zh-Hans");
    await host.command("counter").run();
    await stop();
    });

    To try it in the player, set the language with the Language commands of the command palette (Ctrl+Shift+P) and start the player again.

    The Counter example: a window with one button, its texts in Slint, a template on the OSD and an English menu path, translated into Simplified Chinese by locales/zh-Hans.po.

    /**
    * Counter: Tools ▸ Counter… opens a window with one button that counts
    * clicks, in the player's language. The texts are English; the player
    * translates them with locales/<lang>.po. Walkthrough: docs/examples/i18n.md.
    */
    // #region activate
    import type { Plugin } from "@vestra-player/sdk";

    export default function activate(plugin: Plugin) {
    let count = 0;
    // #endregion activate

    // #region window
    // The window's texts are in its Slint file (@tr); TypeScript passes data.
    const counterWindow = plugin.windows.create("ui/counter.slint");
    counterWindow.bind(() => ({ count }));
    counterWindow.on("add", () => {
    count += 1;
    // A template and its arguments, never a sentence built in TypeScript.
    return plugin.osd.show("Count: {}", [count]);
    });
    // #endregion window

    // #region command
    // Declared texts are English; the player shows them translated.
    plugin.commands.add({
    id: "counter",
    path: ["Tools", "Counter…"],
    run: () => counterWindow.show(),
    });
    // #endregion command
    }