refactor(i18n): ship only the official host languages, drop the better-locale override

Dictionaries now follow the host's own locale list: zh/en static, ja/de/es/fr/pt/ru
in the lazy locale chunk (new es dictionary). t() reads the host's active locale
directly (exact id, base language, then en); attachBetterLocale and the optional
@huanlin/dsh-plugin-better-locale peer are removed along with the 14 non-official
dictionaries.
This commit is contained in:
Menghuan1918 committed 2026-11-24 16:43:27 +08:00
1 parent 30a73d38f5
commit efbc21d65c
30 files changed
+1350 -17715

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@
- **构建纯度**:client bundle 禁止 value-import `@dsh-external/*` 或非白名单 `@deepseek-ai/*`(tsdown.config.ts 拦截);跨插件交互走 `ctx.betterSidebar`。
- **懒加载 chunk**:重依赖只在 `lib/client-<name>.js`,经 `/sidebar/bundle` 下发;核心 bundle 禁止静态 import `src/client/chunks/*`;`CHUNK_NAMES` 的 5 处镜像要同步。
- **i18n**:新增 zh key 必须同步 locales-ja.ts 与其余词典(tests/locales.spec.ts 守护)。
- **i18n**:只维护宿主官方语言(zh/en 内置,ja/de/es/fr/pt/ru 懒加载);新增 zh key 必须同步 en 与其余词典(tests/locales.spec.ts 守护)。
- **保存语义**:写盘前按磁盘现状还原编码与行尾;客户端只发送 LF。
- **皮肤**:视觉值只用 `--dsw-alias-*` / `--dsw-font-*` / `--ds-*`,零硬编码颜色,插件没有任何豁免面。
- **图标**:宿主 `Icon*` 默认 16px,要 14px 显式传 `size={14}`;设置页导航图标走 `settings.section.icon` 插槽,不要用「标记行 + CSS 遮盖」。
+1 -1
View File
@@ -32,7 +32,7 @@ chunk 名的真源是 `CHUNK_NAMES`(src/bundle-route.ts),另有 5 处镜
### i18n
- 词典在 betterSidebar 命名空间;**新增 zh key 必须同步 src/client/locales-ja.ts**(否则 ja 下回退 en),其余词典的 key 集由 tests/locales.spec.ts 守护。
- 词典在 betterSidebar 命名空间;词典只覆盖宿主官方语言:zh / en 内置,ja / de / es / fr / pt / ru 在 src/client/locales-*.ts(懒加载 chunk)。**新增 zh key 必须同步 en 与这 6 份词典**,key 集与占位符由 tests/locales.spec.ts 守护。
- 渲染 MarkdownText 一律经 `markdownTextProps()`(src/client/markdown-labels.tsx),它负责必填的 labels 嵌套结构;漏传会回退硬编码中文。
### 皮肤契约
+2 -2
View File
@@ -1382,8 +1382,8 @@ interface SettingsDescriptor {
| **家族右面板互斥(v0.13.0+)** | `aionui-panel` 设置的 `rightPanel` 解析为 `'aionui-panel'` 时整个侧边栏不挂载(`settings.get` 返回 `externalDisable: true`,挂载门 + 接管停用)。**DSH 0.1.7 起 `settings/updated` 事件已删除**,保留的 `settings/document-updated` 是在 **settings 服务自己的 context 上 emit 的、插件 fiber 监听不到**(见 §8.2 第 4 条)——所以实时性由「每次重新读取时重新求值 + 客户端经 `remote` 镜像重新拉取」提供,不要写成 `ctx.on('settings/document-updated')` |
| **设置持久化位置(0.1.7 起)** | 偏好不再写 `~/.dsh/settings.yaml`,而是落在 **profile 的 cordis patch 文档**里,按插件 Loader 行的 entry id 组织(本插件默认 `better-sidebar`)。0.1.6 线的 `dsh-better-sidebar` 段由插件在**首次启动时一次性回迁**(只在该行用户层仍为空时执行,且只迁移当前 `Config` 仍声明的字段),所以用户设置不会丢。排障时先看 profile patch,而不是旧的 `settings.yaml`(服务已把它改名为 `settings.yaml.imported`) |
| **i18n 跟随** | 文案跟随 DSH `ctx.locale`(词典在 `betterSidebar` 命名空间;Host-backed `locale.preference` 优先于浏览器语言并实时切换;缺失回退浏览器)。消费插件**不要**依赖内部 `t()`——标题传字符串或 `() => string` |
| **第三语言覆盖(ja 等)** | 可选 peer `@huanlin/dsh-plugin-better-locale`(optional)提供 ja/ko 覆盖,**借用 DSH 英文槽位**(仅 DSH=en 时生效,zh 下惰性)。经 `ctx.get('betterLocale')` 注入 `t()`;未安装整段 no-op |
| **懒加载 chunk** | 重依赖(CodeMirror / mermaid / 19 份第三语言词典)在独立 bundle(`lib/client-<name>.js`,现存 `editor` / `mermaid` / `locale` 三个),经 `/sidebar/bundle` 按需下发;factory 赋到 `globalThis.__dshChunks__[<name>]`,由 `src/client/chunk-loader.ts` 物化,**不经** `__ModuleLoader__`。对消费插件透明 |
| **官方语言词典(zh/en 之外)** | 与宿主 `@deepseek-ai/dsh-client-locale` 的官方语言对齐:zh / en 静态内置,ja / de / es / fr / pt / ru 走懒加载 `locale` chunk,宿主切到该语言时才拉取并注册到 `betterSidebar` 命名空间;缺 key 回落 en。不再借用 better-locale 的英文槽位,也没有 `ctx.get('betterLocale')` 集成 |
| **懒加载 chunk** | 重依赖(CodeMirror / mermaid / 6 份官方语言词典)在独立 bundle(`lib/client-<name>.js`,现存 `editor` / `mermaid` / `locale` 三个),经 `/sidebar/bundle` 按需下发;factory 赋到 `globalThis.__dshChunks__[<name>]`,由 `src/client/chunk-loader.ts` 物化,**不经** `__ModuleLoader__`。对消费插件透明 |
| **聊天文件打开漏斗(0.1.5 宿主)** | 聊天里一切文件打开(工具行 / 产物行 / 正文提及 / 行内代码路径)统一走 DSH 原生右侧栏的 `ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path))`(`packages/client/ui-chat/src/client/apply.ts` 是唯一调用点);`remote.session.openWorkspacePath` 在 0.1.5 客户端**已无调用者**,better-sidebar 的 openpath 拦截随之删除。你的插件若要观测/旁路聊天文件打开,注册原生 tab 类型认领 `dsh-resource://file/**`(见本文 §4 的原生 tab 类型);不要假设 `ctx.workspaces.openPath`(已删除)或旧 `remote.session` 漏斗存在 |
| **会话地址的基准是会话 header cwd(#947 / #950 的根因)** | `dsh-resource://file/session/<sid>/<path>` 里的路径总是相对**会话存储的 header cwd**:宿主构造端(`ui-chat` 的 `openFile` → `fileAddressFor(sessionId, sessions.list.byId[sid].cwd, path)`)与解析端(`api-workspace-files` 的 `resolve()` → `sessions.get(sid).header.cwd`)用的就是同一个值。本插件的 fs 路由自 #802 起跟随**活动 worktree 根**,两者在「会话 header cwd 是主检出、agent 在 linked worktree 里干活」时不同,于是地址里的相对路径被活动根**再拼一次**:路径翻倍 → ENOENT(#947),或在两个检出都存在同名文件时**静默**读到另一份(#950,可保存写回)。所以**构造端**(`native/surface.ts` 的 `fileAddress`、`sidebar-file.ts` 的 `openClaimedNativeFile`)与**消费端**(`native/index.ts` 的 `fileParamsOf(info, base)`)都经 `src/client/address-base.ts` 的 `addressBaseOf(ctx, sessionId)` 取基准,并在边界处把地址路径解析成**绝对路径**(绝对路径在任何基准下都一样,下游再无可重定基的余地);只有用户/插件**意图**的相对路径(文件树、编辑器路径输入框、文档内相对链接)才走活根(`useSessionRoot`)。你的插件若自己解析文件地址,请照同一条规则做 |
| **原生 tab 体的高度契约** | 你的 tab 组件被挂在**全高列 flex 宿主**里:native 适配层给每个 tab 体(含 orphaned 回退)包一层 `height:100%` 的 `sidebar.module.css` `.nativeTabHost`(带 `data-dsh-native-tab-host`)——根用 `flex: 1` / `height: 100%` 并加 `min-height: 0` 填满面板。宿主的面板体 `.paneBody`(`dsh-client-ui-dockkit`)是**有确定高度的块级滚动容器,不是 flex 容器**,因此只靠外层 flex 容器支撑的根会塌成内容高度(sidechat 的输入框就贴不到面板底);DSH 自己的 tab 体(`ui-sidebar-documentpreview` 的文档预览、`ui-sidebar-files` 的 FilesBody)正是因此在根上声明 `height: 100%` |
-5
View File
@@ -111,14 +111,10 @@
"@deepseek-ai/dsh-settings": "^0.2.2-rc.2",
"@deepseek-ai/dsh-subagent": "^0.2.2-rc.2",
"@deepseek-ai/dsh-tools": "^0.2.2-rc.2",
"@huanlin/dsh-plugin-better-locale": "^0.1.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"peerDependenciesMeta": {
"@huanlin/dsh-plugin-better-locale": {
"optional": true
},
"@deepseek-ai/dsh-client-ui-sidebar-right": {
"optional": true
}
@@ -185,7 +181,6 @@
"@deepseek-ai/dsh-working-directory": "0.2.2-rc.2",
"@eslint/js": "^10.0.1",
"@formkit/auto-animate": "^0.10.0",
"@huanlin/dsh-plugin-better-locale": "^0.1.0",
"@lezer/highlight": "^1.2.3",
"@playwright/test": "^1.62.1",
"@shikijs/langs": "^4.3.1",
-45
View File
@@ -192,9 +192,6 @@ importers:
'@formkit/auto-animate':
specifier: ^0.10.0
version: 0.10.0
'@huanlin/dsh-plugin-better-locale':
specifier: ^0.1.0
version: 0.1.0(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-client-locale@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-client-ui-primitives@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-client-ui-settings@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-client-ui-slots@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@lezer/highlight':
specifier: ^1.2.3
version: 1.2.5
@@ -996,37 +993,6 @@ packages:
'@formkit/auto-animate@0.10.0':
resolution: {integrity: sha512-KGomRttjUfORuPUaR/ZGQw+6xfMrTM+sxnILv7JAd9AmabU9rg9i6gF/iC0Ih+QpKCubJpCA/1DX9UHKE8cX+A==}
'@huanlin/dsh-plugin-better-locale@0.1.0':
resolution: {integrity: sha512-fGXDgVq1R3gVTi2M9TMn2x5ROqiaYkhEsFJqYF5xiVUFfs9KjwIpOF0ZbhUyK6vFBOeYP4uetc/ZVknQb38WrQ==}
engines: {node: '>=22.0.0'}
peerDependencies:
'@deepseek-ai/cordis': ^4.0.1-rc.1
'@deepseek-ai/dsh-client-locale': ^0.1.0-rc.8
'@deepseek-ai/dsh-client-runtime': ^0.1.0-rc.8
'@deepseek-ai/dsh-client-ui-primitives': ^0.1.0-rc.8
'@deepseek-ai/dsh-client-ui-settings': ^0.1.0-rc.8
'@deepseek-ai/dsh-client-ui-slots': ^0.1.0-rc.8
'@deepseek-ai/dsh-invariants': ^0.1.0-rc.8
react: ^18.2.0
react-dom: ^18.2.0
peerDependenciesMeta:
'@deepseek-ai/dsh-client-locale':
optional: true
'@deepseek-ai/dsh-client-runtime':
optional: true
'@deepseek-ai/dsh-client-ui-primitives':
optional: true
'@deepseek-ai/dsh-client-ui-settings':
optional: true
'@deepseek-ai/dsh-client-ui-slots':
optional: true
'@deepseek-ai/dsh-invariants':
optional: true
react:
optional: true
react-dom:
optional: true
'@humanfs/core@0.19.2':
resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}
engines: {node: '>=18.18.0'}
@@ -4279,17 +4245,6 @@ snapshots:
'@formkit/auto-animate@0.10.0': {}
'@huanlin/dsh-plugin-better-locale@0.1.0(@deepseek-ai/cordis@4.1.0)(@deepseek-ai/dsh-client-locale@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-client-ui-primitives@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-client-ui-settings@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(@deepseek-ai/dsh-client-ui-slots@0.2.2-rc.2(@deepseek-ai/cordis@4.1.0))(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
dependencies:
'@deepseek-ai/cordis': 4.1.0(@deepseek-ai/cordis-plugin-include@1.1.0)(@deepseek-ai/cordis-plugin-loader@1.1.0)
optionalDependencies:
'@deepseek-ai/dsh-client-locale': 0.2.2-rc.2(@deepseek-ai/cordis@4.1.0)
'@deepseek-ai/dsh-client-ui-primitives': 0.2.2-rc.2(@deepseek-ai/cordis@4.1.0)
'@deepseek-ai/dsh-client-ui-settings': 0.2.2-rc.2(@deepseek-ai/cordis@4.1.0)
'@deepseek-ai/dsh-client-ui-slots': 0.2.2-rc.2(@deepseek-ai/cordis@4.1.0)
react: 18.2.0
react-dom: 18.2.0(react@18.2.0)
'@humanfs/core@0.19.2':
dependencies:
'@humanfs/types': 0.15.0
+4 -37
View File
@@ -50,7 +50,7 @@ import { useCenterColumn } from './sidebar/use-center-column.ts'
import { useHostFeeds } from './sidebar/use-host-feeds.ts'
import { mountedSessions } from './native/surface.ts'
import type { TabDragPayload } from './TabBar.tsx'
import { t } from './locales.ts'
import { localeSignature, t } from './locales.ts'
import { useSessionRoot } from './use-session-root.ts'
import { useSessionScope } from './session-scope.ts'
import { IconButton } from './ui/index.ts'
@@ -101,49 +101,16 @@ function injectUserCss(attr: string, id: string, cssText: string): HTMLStyleElem
export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
const { ctx, store } = props
// Copy freshness: re-render the whole tree when the DSH locale switches.
// Copy freshness: re-render the whole tree when the DSH locale switches or
// a lazily loaded dictionary registers (both bump the snapshot revision).
// The module-level t() reads the active locale at call time, so a root
// re-render alone re-localizes every panel (no memo barriers below).
const localeRevision = useSyncExternalStore(
useMemo(() => (callback: () => void) => ctx.locale.subscribe(callback), [ctx]),
useCallback(() => ctx.locale.getSnapshot().active, [ctx]),
useCallback(() => `${ctx.locale.getSnapshot().active}:${localeSignature()}`, [ctx]),
)
void localeRevision
// better-locale override freshness: when @huanlin/dsh-plugin-better-locale
// is installed and the user picks an override language (e.g. ja), the
// store's `active` changes but the DSH locale's `active` does NOT —
// better-locale keeps the dsh active value (zh/en) unchanged and only
// patches `LocaleRuntime.prototype.lookup`. The localeRevision uSES
// above reads `getSnapshot().active`, so it sees no change and skips
// re-render. This second uSES reads the better-locale store's `active`
// directly, so an override switch fires a full re-render and t() picks
// up the new override text. Optional: ctx.get returns undefined when
// better-locale is absent (or when ctx is a minimal test mock without
// a `get` method), in which case this is a no-op uSES.
type BetterLocaleStore = {
readonly active: string | undefined
subscribe(listener: () => void): () => void
}
const betterLocaleStore = typeof ctx.get === 'function'
? (ctx as unknown as {
get(name: 'betterLocale'): BetterLocaleStore | undefined
}).get('betterLocale')
: undefined
const betterLocaleActive = useSyncExternalStore(
useMemo(() => {
const store = betterLocaleStore
if (store === undefined) return (_cb: () => void) => () => {}
return (callback: () => void) => store.subscribe(callback)
}, [betterLocaleStore]),
useMemo(() => {
const store = betterLocaleStore
if (store === undefined) return () => undefined
return () => store.active
}, [betterLocaleStore]),
)
void betterLocaleActive
// Tab-registry revision: TabContent memo cells must pick up a descriptor
// a plugin registers/disposes after mount (the + menu / icons already read
// the registry at render). Rare events (plugin (un)mount), so one full
+5 -16
View File
@@ -197,9 +197,9 @@ export function TextEditor(props: FileViewerProps & TextEditorSelectionProps) {
/** The uncommitted-change gutter compartment (issue #212; reconfigured on a
* setting flip instead of rebuilding the view). */
const gitCompRef = useRef<CmGitGutterCompartment | null>(null)
/** The effective UI language (DSH locale id + better-locale override id).
/** The effective UI language (DSH locale id + loaded dictionary count).
* Read during render and subscribed below: the tab-cell memo only
* compares the DSH locale revision, so a better-locale override switch
* compares the DSH locale revision, so a lazily loaded dictionary
* would otherwise never reach this component. */
const [localeSig, setLocaleSig] = useState(() => localeSignature())
/** The app's resolved color scheme; the editor re-themes in place on flips. */
@@ -331,25 +331,14 @@ export function TextEditor(props: FileViewerProps & TextEditorSelectionProps) {
useEffect(() => subscribeColorScheme(() => { setDark(isDarkScheme()) }), [])
// Keep `localeSig` fresh from BOTH language sources: the DSH locale service
// and (when @huanlin/dsh-plugin-better-locale is installed) the override
// store. The sidebar root re-renders the tree on a DSH locale switch, but
// an override switch is not part of the tab-cell memo key, so this
// Keep `localeSig` fresh from the DSH locale service. A language switch or a
// lazily registered dictionary is not part of the tab-cell memo key, so this
// component subscribes directly instead of relying on a parent render.
useEffect(() => {
const sync = (): void => { setLocaleSig(localeSignature()) }
sync()
const locale = ctx.locale as { subscribe?: (cb: () => void) => () => void } | undefined
type BetterLocaleStore = { subscribe?(listener: () => void): () => void }
const betterLocale = typeof ctx.get === 'function'
? (ctx as unknown as { get(name: 'betterLocale'): BetterLocaleStore | undefined }).get('betterLocale')
: undefined
const offLocale = locale?.subscribe?.(sync)
const offOverride = betterLocale?.subscribe?.(sync)
return () => {
offLocale?.()
offOverride?.()
}
return locale?.subscribe?.(sync)
}, [ctx])
// A new file (tab switch) starts clean: fresh preview mode, no draft.
+7 -42
View File
@@ -1,60 +1,25 @@
/**
* Lazy chunk entry: the 19 non-zh/en dictionaries (ja/de/fr/…/zh-HK/MO/TW —
* ~640KB of source). The sidebar's own `t()` only ever consults zh/en plus
* the better-locale override store, so these dicts are needed ONLY when
* @huanlin/dsh-plugin-better-locale is installed: they register into its
* override store from there (see the client apply's better-locale
* integration). Built as `lib/client-locale.js` and fetched from the
* plugin's /sidebar/bundle route on first need — never import this module
* from the core bundle: it would drag every language back into the startup
* path (see docs/plans/2026-08-31-perf-optimization.md).
* Lazy chunk entry: the official host languages beyond zh/en. Built as
* `lib/client-locale.js` and fetched from /sidebar/bundle only when the host
* is on one of them — never import this module from the core bundle.
*/
import { ja } from '../locales-ja.ts'
import { de } from '../locales-de.ts'
import { es } from '../locales-es.ts'
import { fr } from '../locales-fr.ts'
import { pt } from '../locales-pt.ts'
import { ko } from '../locales-ko.ts'
import { ar } from '../locales-ar.ts'
import { hi } from '../locales-hi.ts'
import { id } from '../locales-id.ts'
import { tr } from '../locales-tr.ts'
import { vi } from '../locales-vi.ts'
import { th } from '../locales-th.ts'
import { ru } from '../locales-ru.ts'
import { it } from '../locales-it.ts'
import { nl } from '../locales-nl.ts'
import { sv } from '../locales-sv.ts'
import { pl } from '../locales-pl.ts'
import { zhHK } from '../locales-zh-HK.ts'
import { zhTW } from '../locales-zh-TW.ts'
import { zhMO } from '../locales-zh-MO.ts'
import type { CopyKey } from '../locales.ts'
/** Key-set check against zh (type-only import — erased before bundling, so
* this adds no runtime tie to the core bundle): a dictionary missing or
* adding a key fails the build instead of silently falling back to en. */
/** Key-set check against zh (type-only, erased before bundling). */
const checked = (dict: Record<CopyKey, string>): Record<string, string> => dict
/** Every non-zh/en dictionary keyed by its override id, ready for the
* better-locale store's `register(ns, dicts)`. */
/** Every lazily loaded dictionary, keyed by host locale id. */
export const localeDicts: Record<string, Record<string, string>> = {
ja: checked(ja),
de: checked(de),
es: checked(es),
fr: checked(fr),
pt: checked(pt),
ko: checked(ko),
ar: checked(ar),
hi: checked(hi),
id: checked(id),
tr: checked(tr),
vi: checked(vi),
th: checked(th),
ru: checked(ru),
it: checked(it),
nl: checked(nl),
sv: checked(sv),
pl: checked(pl),
'zh-HK': checked(zhHK),
'zh-TW': checked(zhTW),
'zh-MO': checked(zhMO),
}
+30 -56
View File
@@ -39,8 +39,11 @@ import { parkSidechatReopen } from './SideChatView.tsx'
import { setClueSelectionActionContext, setClueSelectionActionStarter } from './clues/selection-actions.tsx'
import { createClueActionRefreshWatcher, type ClueActionDraftStatus, type ClueActionRefreshResult } from './clues/action-refresh.ts'
import { invalidateClueAgentSave, type ClueClientResourceInput } from './clues/api.ts'
import { LOCALE_NS, attachLocale, attachBetterLocale, t, zh, en } from './locales.ts'
import { LOCALE_NS, attachLocale, attachLocaleDicts, t, zh, en } from './locales.ts'
import { loadChunk } from './chunk-loader.ts'
/** Official host languages whose dictionaries ride the lazy `locale` chunk. */
const LAZY_LOCALES = new Set(['ja', 'de', 'es', 'fr', 'pt', 'ru'])
import { registerGithubSourceClient } from './clues/sources/github/index.tsx'
import { registerFeishuSourceClient } from './clues/sources/feishu/index.tsx'
import { appDateTime } from './clues/sources/feishu/time.ts'
@@ -93,69 +96,40 @@ export function apply(ctx: Context): void {
return () => { offZh(); offEn() }
}, 'dsh-better-sidebar: dictionaries')
// Opt-in third-language support through @huanlin/dsh-plugin-better-locale.
// When that plugin is installed, it publishes `ctx.betterLocale` (the
// override store) and patches LocaleRuntime.prototype.lookup to consult
// it. We mirror the same override awareness into the sidebar's own `t()`:
// attachBetterLocale() makes t() consult the store's getOverride first,
// so the sidebar's chrome (which bypasses ctx.locale and calls t()
// directly) also switches to the override language. We also register
// the ja dict with the better-locale store so external callers of
// ctx.locale.lookup('betterSidebar', key) get the override text too.
//
// Activation-order-safe: ctx.get('betterLocale') is a non-reactive read
// (cordis only re-evaluates declared `inject` deps). If better-locale
// activates after better-sidebar, the initial read returns undefined.
// We subscribe to the locale revision — better-locale bumps it on
// activation (when a persisted override exists) and on every override
// switch — and re-check ctx.get on each bump, attaching + registering
// the ja dict once the store becomes available.
// The official host languages beyond zh/en ride the lazy `locale` chunk:
// fetched the first time the host is on one of them, then registered into
// the shared registry (so `ctx.locale.bind('betterSidebar')` resolves too)
// and handed to `t()`. Registration bumps the locale revision, which
// re-renders the sidebar root once the dictionaries land.
ctx.effect(() => {
let dispose: (() => void) | undefined
// Guards the async chunk registration below: a sync() re-run (or fiber
// disposal) that lands while the chunk is still in flight must render
// that registration moot.
let generation = 0
let disposed = false
let offDicts: (() => void) | undefined
const sync = (): void => {
generation += 1
dispose?.()
dispose = undefined
const store = ctx.get('betterLocale') as
| {
readonly active: string | undefined
getOverride(dshActive: string, ns: string, key: string): string | undefined
isOverrideActive(dshActive: string): boolean
register(ns: string, dicts: Record<string, Record<string, string>>): () => void
subscribe(listener: () => void): () => void
}
| undefined
attachBetterLocale(store)
if (store !== undefined) {
// The 19 override dictionaries ride the lazy `locale` chunk: until
// it lands, the store has no betterSidebar entries and t() keeps
// the zh/en chain; the store's own revision bump on register
// re-renders the chrome once the dicts arrive.
const myGeneration = generation
void loadChunk('locale')
.then(mod => {
if (myGeneration !== generation) return
dispose = store.register(LOCALE_NS, mod.localeDicts as Record<string, Record<string, string>>)
})
.catch(() => { /* the dicts stay unregistered; the zh/en chain runs */ })
}
if (offDicts !== undefined || disposed) return
const active = ctx.locale.getSnapshot().active.toLowerCase().split('-')[0]!
if (!LAZY_LOCALES.has(active)) return
offDicts = () => {}
void loadChunk('locale')
.then(mod => {
if (disposed) return
// Attach before registering: register() notifies subscribers, and the
// sidebar's revision snapshot must already see the new dictionaries.
const dicts = mod.localeDicts as Record<string, Record<string, string>>
attachLocaleDicts(dicts)
const offs = Object.entries(dicts).map(([id, dict]) => ctx.locale.register(LOCALE_NS, id, dict))
offDicts = () => { for (const off of offs) off() }
})
.catch(() => { offDicts = undefined })
}
// Initial check (picks up the store if better-locale activated first).
sync()
// Re-check on every locale revision bump (better-locale bumps when it
// activates with a persisted override, and when the user switches).
const unsubscribe = ctx.locale.subscribe(sync)
return () => {
generation += 1
disposed = true
unsubscribe()
dispose?.()
attachBetterLocale(undefined)
offDicts?.()
attachLocaleDicts({})
}
}, 'dsh-better-sidebar: better-locale lazy integration')
}, 'dsh-better-sidebar: lazy locale dictionaries')
// A failure anywhere in the client lifecycle must never take the app down
// silently: log with the plugin prefix and pin a visible diagnostic strip
// to the page so a blank panel is never the only symptom. This strip is
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2 -3
View File
@@ -2,9 +2,8 @@
* French translation of the better-sidebar copy.
*
* Mirrors the key set of the zh dictionary in `locales.ts` (enforced by
* the `Record<keyof typeof zh, string>` type annotation). The better-locale
* override store registers this dict under the `betterSidebar` namespace,
* so it takes effect when the user has selected the `fr` override.
* the `Record<keyof typeof zh, string>` type annotation). Delivered by the
* lazy `locale` chunk and read by `t()` when the host locale is `fr`.
*/
/** fr dictionary for the `betterSidebar` namespace. */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3 -4
View File
@@ -1,10 +1,9 @@
/**
* The ja (Japanese) dictionary for the betterSidebar namespace.
*
* Mirrors the key set of `zh` in `locales.ts`. The sidebar's `t()`
* consults this dict when `attachBetterLocale(store)` has been called
* with an active better-locale store whose `active` is `'ja'`; absent
* that, the existing zh/en chain runs unchanged.
* Mirrors the key set of `zh` in `locales.ts`. The sidebar's `t()` reads
* it when the host's active locale is `ja` (delivered by the lazy `locale`
* chunk); missing keys fall back to `en`.
*
* Translation conventions:
* - Common dev-tool loanwords stay in katakana (ターミナル, ブラウザー, サンドボックス).
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+30 -100
View File
@@ -1,24 +1,15 @@
/**
* Minimal zh/en/ja copy for the sidebar. The copy follows the DSH i18n system:
* the client apply attaches the locale service (`ctx.locale`, provided by
* `@deepseek-ai/dsh-client-locale`) through {@link attachLocale}, and
* `t()`/`isZh()` resolve the active locale from it — the Host-backed
* `locale.preference` wins over the raw browser language and switches live.
* Without an attached service (standalone/test compositions) the browser
* language is used, matching the previous behavior. The dictionaries are
* also registered into the DSH locale registry under {@link LOCALE_NS}.
* Sidebar copy, following the DSH i18n system: the client apply attaches the
* locale service (`ctx.locale`) through {@link attachLocale}, and
* `t()`/`isZh()` resolve the host's active locale from it. Without an
* attached service (standalone/test compositions) the browser language is
* used.
*
* ja (Japanese) is opt-in through `@huanlin/dsh-plugin-better-locale`: when
* that plugin is installed, the client apply also calls
* {@link attachBetterLocale} with the override store. `t()` then consults
* the store's active override id first; if it is `'ja'` (or any id whose
* dict has the requested key) the ja text wins, otherwise the existing
* zh/en chain runs unchanged. better-locale itself patches
* `LocaleRuntime.prototype.lookup` so DSH's own translate chain also
* returns ja where the `betterSidebar` namespace has a ja entry — that
* path covers external callers of `ctx.locale.bind('betterSidebar')`,
* while the override-aware `t()` here covers better-sidebar's own
* components (which bypass `ctx.locale` and call `t()` directly).
* zh and en ship in the core bundle. The other official host languages ride
* the lazy `locale` chunk: the client apply loads it only when the host is
* on one of them, registers the dictionaries into `ctx.locale` and hands
* them to {@link attachLocaleDicts}. Any key a language lacks falls back to
* English, exactly like the host's own chain.
*/
/** The zh dictionary (also registered into the DSH locale registry under {@link LOCALE_NS}). */
@@ -2481,13 +2472,6 @@ export const en: Record<keyof typeof zh, string> = {
*/
export const LOCALE_NS = 'betterSidebar'
// The 19 non-zh/en dictionaries live in the LAZY `locale` chunk
// (src/client/chunks/locale.tsx → lib/client-locale.js): `t()` only ever
// consults zh/en plus the better-locale override store, so those dicts are
// needed only when better-locale is installed — the client apply fetches the
// chunk there and registers its `localeDicts` into the override store. They
// used to sit statically in the core bundle (≈ half its weight) for a code
// path most sessions never enter.
/** The DSH locale service attached by the client apply (absent → browser detection). */
let localeService: {
@@ -2502,23 +2486,8 @@ let localeService: {
bind?(ns: string): (key: string, params?: Record<string, string | number>) => string
} | undefined
/**
* The better-locale override store attached by the client apply
* (absent → no override; the zh/en chain runs). The store's `active`
* field holds the user's chosen override id (e.g. `'ja'`); `undefined`
* means "no override, use DSH native zh/en".
*
* The override only takes effect when DSH's active locale is `'en'`
* (it borrows DSH's English slot to render a third language). While
* DSH is on `'zh'` the override is inert — `getOverride` returns
* `undefined` and `isOverrideActive` returns `false` — so `t()` and
* `isZh()` fall through to the native zh/en chain unchanged.
*/
let betterLocaleStore: {
readonly active: string | undefined
getOverride(dshActive: string, ns: string, key: string): string | undefined
isOverrideActive(dshActive: string): boolean
} | undefined
/** Lazily loaded non-zh/en dictionaries, keyed by host locale id. */
let localeDicts: Readonly<Record<string, Readonly<Record<string, string>>>> = {}
/**
* Attach (or detach, with undefined) the DSH locale service. The sidebar
@@ -2586,26 +2555,14 @@ export function hostT(ns: string, key: string, params?: Record<string, string |
}
}
/**
* Attach (or detach, with undefined) the better-locale override store.
* When attached with an active override, `t()` consults the store's
* `getOverride(active, LOCALE_NS, key)` first; if it returns a string,
* that text wins over the zh/en chain. Detaching (or the store's active
* being `undefined`) restores the zh/en chain unchanged.
*
* The Sidebar root subscribes to the store separately (see Sidebar.tsx)
* so an override change re-renders the whole tree — the locale service's
* own revision bump (which better-locale triggers via `publish(active, true)`)
* does NOT fire the existing `localeRevision` uSES because that snapshot
* reads `getSnapshot().active` (unchanged) rather than `revision`.
*/
export function attachBetterLocale(store: typeof betterLocaleStore): void {
betterLocaleStore = store
/** Install (or clear, with `{}`) the lazily loaded non-zh/en dictionaries. */
export function attachLocaleDicts(dicts: Readonly<Record<string, Readonly<Record<string, string>>>>): void {
localeDicts = dicts
}
/**
* The active locale id ('zh' | 'en'): the DSH locale service's snapshot when
* attached, else the browser language.
* The active locale id: the DSH locale service's snapshot when attached, else
* the browser language.
*/
function activeLocale(): string {
return localeService?.getSnapshot().active
@@ -2613,30 +2570,12 @@ function activeLocale(): string {
?? 'en'
}
/** Translate a copy key in the active locale (zh → zh, else en). */
/** One copy key; zh is the source of truth for the key set. */
export type CopyKey = keyof typeof zh
/** Translate a copy key; `{name}` placeholders interpolate from `params`. */
export function t(key: CopyKey, params?: Record<string, string | number>): string {
// 1. better-locale override (e.g. ja) wins when an override is active,
// DSH's active locale is 'en' (the override borrows the en slot),
// and the store has a translation for this (ns, key). The store's
// getOverride returns undefined otherwise (no override, DSH on zh,
// or missing key) and the zh/en chain runs.
const dshActive = localeService?.getSnapshot().active ?? ''
const override = betterLocaleStore?.getOverride(dshActive, LOCALE_NS, key)
let text: string | undefined = override
// 2. Fall back to the zh/en chain when no override matched.
if (text === undefined) {
const dict = activeLocale().toLowerCase().startsWith('zh') ? zh : en
text = dict[key]
}
if (text === undefined) {
// Key missing from every dict (should not happen — zh is the source of
// truth and en/ja are checked against it). Return the key itself so the
// UI shows something identifiable rather than `undefined`.
text = key
}
let text: string = dictFor(activeLocale())[key] ?? en[key] ?? key
if (params !== undefined) {
for (const [name, value] of Object.entries(params)) {
text = text.replaceAll(`{${name}}`, String(value))
@@ -2645,34 +2584,25 @@ export function t(key: CopyKey, params?: Record<string, string | number>): strin
return text
}
/** The dictionary of one locale id: exact id, then its base language, else en. */
function dictFor(locale: string): Readonly<Record<string, string>> {
const id = locale.toLowerCase()
if (id.startsWith('zh')) return zh
return localeDicts[id] ?? localeDicts[id.split('-')[0]!] ?? en
}
/** Whether the active locale is Chinese (used for selectors). */
export function isZh(): boolean {
// An override is only "effectively active" when DSH is on 'en' (the
// override borrows the en slot). While DSH is on 'zh' the override is
// inert — the user sees native zh, so isZh() returns true. When an
// override is effectively active, the rendered text is neither zh nor
// en (it's ja/ko/...), so isZh() returns false to route selectors to
// the non-zh branch (e.g. date format, pluralization).
const dshActive = localeService?.getSnapshot().active ?? ''
if (betterLocaleStore?.isOverrideActive(dshActive) === true) return false
return activeLocale().toLowerCase().startsWith('zh')
}
/**
* A signature of the effective UI language: the DSH locale service's active
* id plus the better-locale override id when one is actually in force (the
* override only borrows DSH's `en` slot, so it is inert while DSH is on
* `zh`). `t()` resolves copy from exactly these two inputs, so a component
* that caches localized text OUTSIDE React state — e.g. CodeMirror's
* `phrases` facet, which is baked into an EditorState — can use this string
* as an effect dependency to know when to re-resolve it.
* A signature of the effective UI language: the active locale id plus how many
* lazy dictionaries are loaded. Components that cache localized text OUTSIDE
* React state (CodeMirror's `phrases` facet) use it as an effect dependency.
*/
export function localeSignature(): string {
const dshActive = localeService?.getSnapshot().active ?? ''
const override = betterLocaleStore?.isOverrideActive(dshActive) === true
? betterLocaleStore.active ?? ''
: ''
return `${dshActive}:${override}`
return `${activeLocale()}:${Object.keys(localeDicts).length}`
}
/** Format an ISO 8601 author date relative to now (刚刚 / N 分钟前 / N 小时前 / 昨天 / date). */
+1 -1
View File
@@ -45,7 +45,7 @@ export interface MarkdownCopyLabels {
type HostMarkdownLabels = ComponentProps<typeof MarkdownText>['labels']
/**
* How many distinct label sets the identity cache keeps. The plugin renders
* one label set per locale revision (zh/en plus the better-locale override,
* one label set per locale revision (one per official host language,
* and one per mounted view), so this is far above the real cardinality; the
* bound only keeps a pathological caller from growing the map forever.
*/
+3 -3
View File
@@ -1,6 +1,6 @@
/**
* S8 copy parity: the grouped settings/source/install/authorization copy must
* exist in EVERY shipped dictionary (zh + en + the 19 lazy-chunk languages).
* exist in EVERY shipped dictionary (zh + en + the 6 lazy-chunk languages).
*
* The global locales spec already enforces key-set equality against `zh`; this
* spec pins the S8 surface specifically so a future key addition cannot ship
@@ -77,9 +77,9 @@ function dictionaries(): Record<string, Record<string, string>> {
}
describe('S8 copy across every shipped locale', () => {
it('carries every S8 key in zh, en and all 19 lazy dictionaries', () => {
it('carries every S8 key in zh, en and all 6 lazy dictionaries', () => {
const dictionariesByLang = dictionaries()
expect(Object.keys(dictionariesByLang)).toHaveLength(21)
expect(Object.keys(dictionariesByLang)).toHaveLength(8)
for (const [lang, dict] of Object.entries(dictionariesByLang)) {
for (const key of S8_KEYS) {
expect(dict[key], `${lang}:${key}`).toBeTypeOf('string')
+45 -124
View File
@@ -6,7 +6,7 @@
* interpolation.
*/
import { afterEach, describe, expect, it } from 'vitest'
import { LOCALE_NS, attachBetterLocale, attachLocale, chatT, en, isZh, relativeTime, t, zh } from '../src/client/locales.ts'
import { LOCALE_NS, attachLocale, attachLocaleDicts, chatT, en, isZh, localeSignature, relativeTime, t, zh } from '../src/client/locales.ts'
import { localeDicts } from '../src/client/chunks/locale.tsx'
/** Minimal structural fake of the DSH LocaleService face the sidebar uses. */
@@ -36,7 +36,7 @@ function stubNavigatorLanguage(lang: string | undefined): void {
afterEach(() => {
attachLocale(undefined)
attachBetterLocale(undefined)
attachLocaleDicts({})
stubNavigatorLanguage(undefined)
})
@@ -117,15 +117,14 @@ describe('locales (DSH i18n following)', () => {
expect(Object.keys(en).sort()).toEqual(Object.keys(zh).sort())
})
it('keeps every shipped third-language dictionary key-set-equal to zh', () => {
// The third-language dicts live in the lazy locale chunk typed as plain
it('keeps every lazily loaded dictionary key-set-equal to zh', () => {
// The lazy dicts live in the lazy locale chunk typed as plain
// records (the chunk boundary has no key-set type tie to zh). This test
// catches missing/extra keys introduced when a zh key is added without
// updating every language — a missing key silently falls back to en.
for (const [lang, dict] of Object.entries(localeDicts)) {
expect(Object.keys(dict).sort(), lang).toEqual(Object.keys(zh).sort())
}
expect(Object.keys(localeDicts), 'every shipped third language rides the locale chunk').toContain('ja')
})
})
@@ -179,136 +178,58 @@ describe('locales (host chat namespace bridge)', () => {
})
})
/** Minimal fake of the better-locale override store (the subset t()/isZh() read). */
class FakeBetterLocale {
active: string | undefined = undefined
private readonly dict: Record<string, Record<string, Record<string, string>>>
constructor(dict: Record<string, Record<string, Record<string, string>>>) {
this.dict = dict
}
getOverride(dshActive: string, ns: string, key: string): string | undefined {
if (this.active === undefined) return undefined
if (dshActive !== 'en') return undefined
return this.dict[ns]?.[this.active]?.[key]
}
isOverrideActive(dshActive: string): boolean {
return this.active !== undefined && dshActive === 'en'
}
subscribe(_listener: () => void): () => void {
return () => {}
}
}
describe('locales (better-locale override)', () => {
it('returns the override text when an override is active and the key exists', () => {
describe('locales (official-language dictionaries)', () => {
it('follows the host locale into a loaded dictionary and falls back to en for a missing key', () => {
const locale = new FakeLocale()
locale.switchTo('en')
attachLocale(locale)
attachLocaleDicts({ ja: { explorer: 'エクスプローラー', timeMinutesAgo: '{n} 分前' } })
const betterLocale = new FakeBetterLocale({
[LOCALE_NS]: { ja: { explorer: 'エクスプローラー' } },
})
betterLocale.active = 'ja'
attachBetterLocale(betterLocale)
locale.switchTo('ja')
expect(t('explorer')).toBe('エクスプローラー')
expect(isZh()).toBe(false)
})
it('falls back to the zh/en chain when override is active but the key is missing', () => {
const locale = new FakeLocale()
locale.switchTo('en')
attachLocale(locale)
const betterLocale = new FakeBetterLocale({
[LOCALE_NS]: { ja: { explorer: 'エクスプローラー' } },
})
betterLocale.active = 'ja'
attachBetterLocale(betterLocale)
// 'changes' has no ja entry in this fake; should fall back to the en text.
expect(t('changes')).toBe('Git')
})
it('falls back to the zh/en chain when no override is active', () => {
const locale = new FakeLocale()
locale.switchTo('zh')
attachLocale(locale)
const betterLocale = new FakeBetterLocale({
[LOCALE_NS]: { ja: { explorer: 'エクスプローラー' } },
})
// active is undefined — no override.
attachBetterLocale(betterLocale)
expect(t('explorer')).toBe('资源管理器')
expect(isZh()).toBe(true)
})
it('override is inert while DSH is on zh (override borrows the en slot)', () => {
const locale = new FakeLocale()
locale.switchTo('zh')
attachLocale(locale)
const betterLocale = new FakeBetterLocale({
[LOCALE_NS]: { ja: { explorer: 'エクスプローラー' } },
})
betterLocale.active = 'ja'
attachBetterLocale(betterLocale)
// Override is set to 'ja' but DSH is on zh — override is inert,
// native zh text wins. The user must switch DSH to en to see ja.
expect(t('explorer')).toBe('资源管理器')
expect(isZh()).toBe(true)
})
it('returns to the zh/en chain after detaching the override store', () => {
const locale = new FakeLocale()
locale.switchTo('en')
attachLocale(locale)
const betterLocale = new FakeBetterLocale({
[LOCALE_NS]: { ja: { explorer: 'エクスプローラー' } },
})
betterLocale.active = 'ja'
attachBetterLocale(betterLocale)
expect(t('explorer')).toBe('エクスプローラー')
attachBetterLocale(undefined)
expect(t('explorer')).toBe('Explorer')
expect(isZh()).toBe(false)
})
it('interpolates {name} placeholders in the override text', () => {
const locale = new FakeLocale()
locale.switchTo('en')
attachLocale(locale)
const betterLocale = new FakeBetterLocale({
[LOCALE_NS]: { ja: { timeMinutesAgo: '{n} 分前' } },
})
betterLocale.active = 'ja'
attachBetterLocale(betterLocale)
expect(t('timeMinutesAgo', { n: 5 })).toBe('5 分前')
expect(t('terminal')).toBe('Terminal')
expect(isZh()).toBe(false)
locale.switchTo('ja-JP')
expect(t('explorer')).toBe('エクスプローラー')
})
it('ships a ja dictionary whose every key resolves to a non-empty string', () => {
// Smoke-check the shipped ja dict: every key in zh must have a non-empty
// ja entry. This catches copy-paste mistakes where a key was added to zh
// but its ja translation was left blank or missing.
it('serves en until the dictionary lands and again once it is detached', () => {
const locale = new FakeLocale()
locale.switchTo('en')
attachLocale(locale)
locale.switchTo('ja')
expect(t('explorer')).toBe('Explorer')
const betterLocale = new FakeBetterLocale({ [LOCALE_NS]: { ja: localeDicts.ja! } })
betterLocale.active = 'ja'
attachBetterLocale(betterLocale)
attachLocaleDicts({ ja: { explorer: 'エクスプローラー' } })
expect(t('explorer')).toBe('エクスプローラー')
for (const key of Object.keys(zh) as (keyof typeof zh)[]) {
const text = t(key)
expect(text, `ja translation for "${key}"`).toBeTruthy()
expect(text, `ja translation for "${key}"`).not.toBe(key)
attachLocaleDicts({})
expect(t('explorer')).toBe('Explorer')
})
it('bumps the locale signature when a dictionary attaches or the locale switches', () => {
const locale = new FakeLocale()
attachLocale(locale)
const before = localeSignature()
attachLocaleDicts({ ja: {} })
expect(localeSignature()).not.toBe(before)
const loaded = localeSignature()
locale.switchTo('ja')
expect(localeSignature()).not.toBe(loaded)
})
it('ships exactly the official host languages beyond zh/en', () => {
expect(Object.keys(localeDicts).sort()).toEqual(['de', 'es', 'fr', 'ja', 'pt', 'ru'])
})
it('keeps every shipped dictionary non-empty and placeholder-equal to en', () => {
const placeholders = (text: string): string => (text.match(/\{\w+\}/g) ?? []).sort().join(',')
for (const [lang, dict] of Object.entries(localeDicts)) {
for (const key of Object.keys(en) as (keyof typeof en)[]) {
const text = dict[key]
expect(text, `${lang}.${key}`).toBeTruthy()
expect(placeholders(text!), `${lang}.${key} placeholders`).toBe(placeholders(en[key]))
}
}
})
})