chore(app): drop @solid-primitives/i18n (#59014)

This commit is contained in:
Kit Langton
2026-10-25 13:19:07 -07:00
committed by GitHub
Unverified
parent 467d61f9d0
commit 2c0dad3428
7 changed files with 69 additions and 16 deletions
-3
View File
@@ -74,7 +74,6 @@
"@sentry/solid": "catalog:",
"@solid-primitives/event-bus": "1.1.2",
"@solid-primitives/event-listener": "catalog:",
"@solid-primitives/i18n": "2.2.1",
"@solid-primitives/keyed": "1.5.3",
"@solid-primitives/media": "catalog:",
"@solid-primitives/resize-observer": "catalog:",
@@ -2666,8 +2665,6 @@
"@solid-primitives/event-listener": ["@solid-primitives/event-listener@2.4.6", "", { "dependencies": { "@solid-primitives/utils": "^6.4.1" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-5I0YJcTVYIWoMmgBSROBZGcz+ymhew/pGTg2dHW74BUjFKsV8Li4bOZYl0YAGP4mHw5o4UBd9/BEesqBci3wxw=="],
"@solid-primitives/i18n": ["@solid-primitives/i18n@2.2.1", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-TnTnE2Ku11MGYZ1JzhJ8pYscwg1fr9MteoYxPwsfxWfh9Jp5K7RRJncJn9BhOHvNLwROjqOHZ46PT7sPHqbcXw=="],
"@solid-primitives/keyed": ["@solid-primitives/keyed@1.5.3", "", { "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-zNadtyYBhJSOjXtogkGHmRxjGdz9KHc8sGGVAGlUABkE8BED2tbIZoxkwSqzOwde8OcUEH0bb5DLZUWIMvyBSA=="],
"@solid-primitives/map": ["@solid-primitives/map@0.4.13", "", { "dependencies": { "@solid-primitives/trigger": "^1.1.0" }, "peerDependencies": { "solid-js": "^1.6.12" } }, "sha512-B1zyFbsiTQvqPr+cuPCXO72sRuczG9Swncqk5P74NCGw1VE8qa/Ry9GlfI1e/VdeQYHjan+XkbE3rO2GW/qKew=="],
-1
View File
@@ -71,7 +71,6 @@
"@sentry/solid": "catalog:",
"@solid-primitives/event-bus": "1.1.2",
"@solid-primitives/event-listener": "catalog:",
"@solid-primitives/i18n": "2.2.1",
"@solid-primitives/keyed": "1.5.3",
"@solid-primitives/media": "catalog:",
"@solid-primitives/resize-observer": "catalog:",
+1 -2
View File
@@ -21,9 +21,8 @@ import {
} from "solid-js"
import { createStore } from "solid-js/store"
import { Predicate } from "effect"
import { resolveTemplate } from "@solid-primitives/i18n"
import { useDialog } from "@opencode/ui/context/dialog"
import { pluralCategory } from "@opencode/ui/context/i18n"
import { pluralCategory, resolveTemplate } from "@opencode/ui/context/i18n"
import {
ExtensionContext,
LifetimeContext,
@@ -1,4 +1,5 @@
import { describe, expect, test } from "bun:test"
import { DESKTOP_NATIVE_LOCALES } from "./desktop-native"
import { localizedListParts, richTemplateParts } from "./language"
describe("rich translations", () => {
@@ -10,6 +11,25 @@ describe("rich translations", () => {
test("keeps list elements intact while localizing punctuation", () => {
const items = [{ id: 1 }, { id: 2 }, { id: 3 }]
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- the check is that no element was stringified
expect(localizedListParts("en", items).filter((part) => typeof part !== "string")).toEqual(items)
})
})
describe("dictionaries", () => {
test("are flat string maps in every locale", async () => {
const modules = await Promise.all(
DESKTOP_NATIVE_LOCALES.flatMap((locale) => [
import(`./${locale}`),
import(`../../../../ui/src/i18n/${locale}`),
]),
)
const nested = modules.flatMap((module) =>
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- the check is that no value is nested
Object.entries<unknown>(module.dict).filter(([, value]) => typeof value !== "string"),
)
expect(nested).toEqual([])
})
})
+19 -8
View File
@@ -1,4 +1,3 @@
import { flatten, resolveTemplate, translator, type Flatten } from "@solid-primitives/i18n"
import { createEffect, createMemo, createResource, type JSX } from "solid-js"
import { createStore } from "solid-js/store"
import { Option, Schema, SchemaGetter } from "effect"
@@ -7,6 +6,7 @@ import {
I18nProvider,
type UiI18n,
pluralCategory,
resolveTemplate,
type UiI18nPluralLookupKey,
type UiI18nPluralKey,
type UiPluralCategory,
@@ -38,7 +38,7 @@ function localeDirection(locale: Locale): Direction {
type RawDictionary = typeof en & typeof dict
type Dictionary = Flatten<RawDictionary>
type Dictionary = RawDictionary
type AppI18nKey = Extract<keyof typeof en, string>
@@ -96,12 +96,13 @@ const StoredLocaleSchema = Schema.Struct({
const INTL = DESKTOP_NATIVE_LOCALE_TAGS
const base = flatten({ ...en, ...dict })
const base: Dictionary = { ...en, ...dict }
const dicts = new Map<Locale, Dictionary>([["en", base]])
const merge = (app: Promise<Source>, ui: Promise<Source>) =>
Promise.all([app, ui]).then(([a, b]) => ({ ...base, ...flatten({ ...a.dict, ...b.dict }) }) as Dictionary)
// SAFETY: a locale module exports a flat string map for the keys of the English dictionaries (`language.test.ts`).
Promise.all([app, ui]).then(([a, b]) => ({ ...base, ...a.dict, ...b.dict }) as Dictionary)
const loaders: Record<Exclude<Locale, "en">, () => Promise<Dictionary>> = {
zh: () => merge(import("@/runtime/i18n/zh"), import("@opencode/ui/i18n/zh")),
@@ -188,6 +189,7 @@ export function loadLocaleDict(locale: Locale) {
}
function detectLocale(): Locale {
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- probing for a browser global
if (typeof navigator !== "object") return "en"
return detectDesktopNativeLocale(navigator.languages?.length ? navigator.languages : [navigator.language])
@@ -202,6 +204,7 @@ export const languageSchema = Persistence.struct({
})
function readStoredLocale() {
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- probing for a browser global
if (typeof localStorage !== "object") return
try {
@@ -241,6 +244,7 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont
const locale = createMemo(() => store.locale)
const intl = createMemo(() => INTL[locale()])
// SAFETY: widens the initial `undefined` so a direction can be stored later.
const [layout, setLayout] = createStore({ direction: undefined as Direction | undefined })
const direction = createMemo(() => layout.direction ?? localeDirection(locale()))
@@ -255,18 +259,22 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont
initialValue: dicts.get(initial) ?? base,
})
const t = translator(() => dictionary() ?? base, resolveTemplate) as <
Key extends Extract<keyof Dictionary, string>,
>(
const t = <Key extends Extract<keyof Dictionary, string>>(
key: TranslationKey<Key>,
params?: Record<string, string | number | boolean>,
) => string
) => {
const template: string | undefined = (dictionary() ?? base)[key]
// A key outside the dictionary translates to nothing, as it did with the package translator.
return template === undefined ? template : resolveTemplate(template, params)
}
const pluralForm = (
key: PluralKey,
category: UiPluralCategory,
params?: Record<string, string | number | boolean>,
) => {
// SAFETY: every dictionary value is a string (`language.test.ts`).
const current = (dictionary.loading ? base : (dictionary() ?? base)) as Record<string, string>
const candidate = `${key}.${category}`
const fallback = `${key}.other`
@@ -287,6 +295,7 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont
key: TranslationKey<Key>,
params: Record<string, JSX.Element>,
) => {
// SAFETY: every dictionary value is a string (`language.test.ts`).
const current = (dictionary.loading ? base : (dictionary() ?? base)) as Record<string, string>
return richTemplateParts(current[key] ?? key, params)
@@ -297,6 +306,7 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont
const label = (value: Locale) => DESKTOP_NATIVE_LABELS[value]
createEffect(() => {
// oxlint-disable-next-line anti-slop/no-runtime-typeof -- probing for a browser global
if (typeof document !== "object") return
const value = locale()
document.documentElement.lang = intl()
@@ -346,6 +356,7 @@ export function UiI18nBridge(props: { children?: JSX.Element }) {
value={{
locale: language.intl,
layoutLocale: language.layoutLocale,
// SAFETY: `t` accepts the UI keys, which are a subset of the app dictionary.
t: language.t as UiI18n["t"],
plural: language.plural,
pluralForm: language.pluralForm,
+25 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test"
import { createUiI18n, localizedListSeparator, pluralCategory, type UiI18nSource } from "./i18n"
import { createUiI18n, localizedListSeparator, pluralCategory, resolveTemplate, type UiI18nSource } from "./i18n"
const i18n = (locale: string, translated: string) => {
const source: UiI18nSource = {
@@ -63,3 +63,27 @@ describe("localizedListSeparator", () => {
expect(i18n("de", "").list(["Lesen", "Suchen"])).toBe("Lesen und Suchen")
})
})
describe("resolveTemplate", () => {
test("fills params with optional inner spacing and repeats", () => {
expect(resolveTemplate("Hello {{name}}, {{ name }} and {{ other }}", { name: "Ada", other: 2 })).toBe(
"Hello Ada, Ada and 2",
)
})
test("stringifies numbers and booleans, including zero and false", () => {
expect(resolveTemplate("{{count}} {{done}}", { count: 0, done: false })).toBe("0 false")
})
test("returns the text untouched without params", () => {
expect(resolveTemplate("Hello {{name}}")).toBe("Hello {{name}}")
})
test("does not treat $ in a value as a replacement pattern", () => {
expect(resolveTemplate("file {{name}}", { name: "a$&b$1" })).toBe("file a$&b$1")
})
test("blanks a placeholder whose param is missing", () => {
expect(resolveTemplate("a {{missing}} b", { other: "x" })).toBe("a b")
})
})
+4 -1
View File
@@ -51,6 +51,7 @@ export function pluralCategory(locale: string, count: number): UiPluralCategory
}
export function pluralKey(key: UiI18nPluralKey, category: UiPluralCategory) {
// SAFETY: `PluralKey` names a base whose `.one`/`.other` forms exist, so `${key}.${category}` is a lookup key.
return `${key}.${category}` as UiI18nPluralLookupKey
}
@@ -73,7 +74,7 @@ export function localizedListSeparator(locale: string, index: number, count: num
.join("")
}
function resolveTemplate(text: string, params?: UiI18nParams) {
export function resolveTemplate(text: string, params?: UiI18nParams) {
if (!params) return text
return text.replace(/{{\s*([^}]+?)\s*}}/g, (_, rawKey) => {
@@ -106,6 +107,7 @@ export function createUiI18n(source: UiI18nSource): UiI18n {
const fallbackSource: UiI18nSource = {
locale: () => "en",
t: (key, params) => {
// SAFETY: the fallback source only translates keys from the UI dictionary; any other key falls back to itself.
const value = en[key as UiI18nKey] ?? String(key)
return resolveTemplate(value, params)
@@ -113,6 +115,7 @@ const fallbackSource: UiI18nSource = {
plural: (key, count, params) =>
fallback.pluralForm!(key, pluralCategory(fallback.locale(), count), { ...params, count }),
pluralForm: (key, category, params) => {
// SAFETY: locale keys are a subset of the dictionary keys, and every value is a string.
const values = en as Partial<Record<UiI18nLocaleKey, string>>
const value = values[pluralKey(key, category)] ?? values[`${key}.other`] ?? `${key}.other`