@huaqiu/dsh-hardware-ui 0.7.13 → 0.7.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ /**
2
+ * zh_CN copy for every user-visible string of the Hardware Engineering product
3
+ * UI (browser half).
4
+ *
5
+ * Why one module instead of strings at the call sites: the same sentence is
6
+ * rendered from up to three seats (navigation row, viewer body, settings
7
+ * section), and a literal that drifts between them reads as two different
8
+ * products. One dictionary also makes "is this text translated?" a mechanical
9
+ * question — grep for a Chinese character outside this file and the answer is
10
+ * no.
11
+ *
12
+ * Why not DSH's own locale service: `ctx.locale.register(ns, { zh, en })` plus a
13
+ * `locale: 'ns'` slot registration would put a typed, reactive `t` seat on the
14
+ * component props, and it is the right answer for a bilingual plugin. It cannot
15
+ * express zh-only: the typed overload takes
16
+ * `Record<BuiltInLocaleId, LocaleDictOf<N>>` — both baseline locales are
17
+ * required — and the untyped single-locale arm leaves an en-active host falling
18
+ * back to the raw key (`FALLBACK_LOCALE = 'en'`, and a namespace registered only
19
+ * for `zh` is not in `en`'s chain). The sibling packages hit the same wall and
20
+ * self-contained for the same reason (`dsh-auth/src/client/i18n.ts`,
21
+ * `dsh-tool-plugin-update/src/client/copy.ts`).
22
+ *
23
+ * Why one module instead of strings at the call sites: the same sentence is
24
+ * rendered from up to three seats (navigation row, viewer body, settings
25
+ * section), and a literal that drifts between them reads as two different
26
+ * products. One dictionary also makes "is this text translated?" a mechanical
27
+ * question — grep for a Chinese character outside this file and the answer is
28
+ * no.
29
+ *
30
+ * Adding a language later is mechanical: turn `COPY` into `{ zh, en }` with
31
+ * `en: Record<CopyKeys, string>` (the `dsh-auth` shape, so a missing key is a
32
+ * COMPILE error), pick by `<html lang>`, and — if the second language is real —
33
+ * move the dictionary into `ctx.locale.register` and declare `locale:` on the
34
+ * slots to get the framework's reactive `t` seat instead. Nothing that renders
35
+ * would move, because every render site already reads through this module.
36
+ *
37
+ * Wording rules that hold across the file:
38
+ * - Commands, file names, extension names, and host paths are NOT translated
39
+ * (`kicad-cli`, `.kicad_pcb`, `Settings → Hardware Engineering` becomes
40
+ * 「设置 → 硬件工程」 only because the host section label is translated too).
41
+ * - Host-origin text is never re-spelled here: {@link describeHostError} maps
42
+ * a stable host `code` to a sentence and appends the host detail where it
43
+ * is technical output (kicad-cli stderr) rather than prose.
44
+ * - Interpolation is a function, not `{placeholder}` templates: a function
45
+ * cannot be rendered with its placeholders unfilled by accident.
46
+ *
47
+ * @module
48
+ */
49
+
50
+ /** The only locale this bundle ships. See the module note above. */
51
+ export const LOCALE = 'zh_CN' as const
52
+
53
+ export const COPY = {
54
+ /** Product name — tab title, settings section label, wizard title. */
55
+ product: {
56
+ name: '硬件工程',
57
+ },
58
+
59
+ /** The five persistent destinations, in `DESTINATIONS` order. */
60
+ destinations: {
61
+ schematic: '原理图',
62
+ pcb: 'PCB',
63
+ bom: 'BOM',
64
+ '3d': '3D 模型',
65
+ order: '下单',
66
+ },
67
+
68
+ /** Navigation row + viewer strip. */
69
+ viewer: {
70
+ discoveryFailed: (detail: string) => `产物扫描失败:${detail}`,
71
+ installationFailed: (detail: string) => `安装检查失败:${detail}`,
72
+ noArtifact: '未选择产物',
73
+ kicadMissing: '未找到 KiCad',
74
+ kicadVersion: (version: string) => `KiCad ${version}`,
75
+ openInKicad: '用 KiCad 打开',
76
+ openInKicadTitle: (path: string) => `在 KiCad 中打开 ${path}`,
77
+ selectArtifactFirst: '请先选择一个产物',
78
+ configureKicad: '请在「设置 → 硬件工程」中配置 KiCad',
79
+ nothingToShow: '暂无可显示内容',
80
+ selectProject: '选择工程…',
81
+ // aria labels / titles (screen-reader text is visible text too)
82
+ projectField: '工程',
83
+ schematicSheetField: '原理图页',
84
+ boardField: '板文件',
85
+ },
86
+
87
+ /**
88
+ * Discovery outcomes. These are the panel's OWN sentences for a host state —
89
+ * the host also sends a `message`, but re-deriving it here keeps the copy in
90
+ * one place and lets the count/cwd be woven in. {@link issueText} bridges the
91
+ * two: known codes get translated, unknown ones fall back to the host text.
92
+ */
93
+ discovery: {
94
+ selectionRequiredCount: (count: number) => `发现 ${count} 个硬件工程,请明确选择一个。`,
95
+ selectionRequiredArtifact: '该工程包含多个可选产物,请明确选择一个。',
96
+ noProjectSelected: '尚未选择硬件工程。请打开或选择一个硬件工程。',
97
+ noSchematic: '该工程没有可用的根原理图。',
98
+ noBoard: '该工程没有可用的 .kicad_pcb 板文件。',
99
+ noBoardToOrder: '请先选择板文件,再报价或下单制板。',
100
+ // Host `issue.code` vocabulary.
101
+ noProject: (cwd: string) => (cwd === '' ? '未找到 .kicad_pro 工程文件' : `${cwd} 下未找到 .kicad_pro 工程文件`),
102
+ missingProject: (path: string) => `工程文件不存在:${path}`,
103
+ badManifest: (detail: string) => `配置文件 .hardware-engineering.json 无效:${detail}`,
104
+ },
105
+
106
+ /** schematic / pcb / 3d / bom stages. */
107
+ preview: {
108
+ loading: '正在加载已保存的产物…',
109
+ unavailable: '不可用',
110
+ kindSchematic: '原理图',
111
+ kindBoard: 'PCB',
112
+ revision: (revision: string) => `版本 ${revision}`,
113
+ ecadHint: '仅预览已保存的文件;文件必须存在且可解析。',
114
+ ecadKindMismatch: (expected: string, actual: string) =>
115
+ `宿主返回的产物类型(${actual})与预览类型(${expected})不一致。`,
116
+ ecadOverlay: '已保存文件 · 滚轮缩放,拖拽平移',
117
+ kicadNotConfigured: 'KiCad 尚未配置。',
118
+ glbExporting: '正在用 kicad-cli 导出 PCB 的 GLB…',
119
+ glbLoading: '正在加载 3D 模型…',
120
+ glbCached: '缓存',
121
+ glbGenerated: '已生成',
122
+ glbOverlay: '拖拽旋转 · 滚轮缩放',
123
+ bomHint: 'BOM 行来自 kicad-cli sch export bom。请在「设置 → 硬件工程」中配置 KiCad。',
124
+ bomTitle: (lines: number) => `物料清单 · ${String(lines)} 行`,
125
+ bomPlacements: (count: number) => `${String(count)} 个元件位`,
126
+ bomColumns: ['位号', '数量', '值', '封装', '备注'] as const,
127
+ },
128
+
129
+ /** Order Placing destination. */
130
+ order: {
131
+ title: '制板与贴片',
132
+ packaging: '打包中…',
133
+ packageReady: '打包完成',
134
+ packagePending: '尚未打包',
135
+ packageRunning: '正在运行 kicad-cli 导出 Gerber 与钻孔…',
136
+ packageNotPrepared: '尚未打包。',
137
+ packageCard: '制板文件包',
138
+ packageFiles: (files: number, size: string) => `${String(files)} 个文件 · ${size}`,
139
+
140
+ pcbTitle: '裸板制板',
141
+ pcbSubtitle: '通过华秋制板服务对选中的板文件报价并下单。',
142
+ pcbSummary: (zip: string, files: number, size: string) =>
143
+ `${zip} · ${String(files)} 个 Gerber/钻孔文件 · ${size}`,
144
+ pcbAction: '提交 PCB 订单',
145
+
146
+ smtTitle: '整包贴片',
147
+ smtSubtitle: '需要工程根原理图以生成 BOM 与元件坐标。',
148
+ smtSummary: (placements: number, lines: number, size: string) =>
149
+ `${String(placements)} 个贴片点位 · ${String(lines)} 行 BOM · ${size}`,
150
+ smtAction: '提交贴片订单',
151
+
152
+ boardFile: '板文件',
153
+ placements: '贴片点位',
154
+ bomLines: 'BOM 行数',
155
+ credential: '登录凭据',
156
+ signedIn: '华秋登录',
157
+ signedOut: '未登录',
158
+
159
+ signInToOrder: '请先登录华秋账号再下单——订单页将以你的账号打开。',
160
+ signInToOrderSmt: '请先登录华秋账号再下单贴片——订单页将以你的账号打开。',
161
+ waitingForPackage: '正在等待制板文件包。',
162
+ configureToPackage: '请配置 KiCad 以打包板文件。',
163
+ selectRootSchematic: '请选择根原理图,以便生成 BOM 与坐标。',
164
+
165
+ // Board facts (values keep their units, which are not prose).
166
+ layers: '层数',
167
+ layersValue: (layers: number) => `${String(layers)} 层`,
168
+ outline: '外形尺寸',
169
+ thickness: '板厚',
170
+ minTrace: '最小线宽',
171
+ minDrill: '最小钻孔',
172
+ outerCopper: '外层铜厚',
173
+ defaultValue: '默认',
174
+ copperValue: (oz: number | string) => `${String(oz)} oz`,
175
+
176
+ agentEntryPoints: 'Agent 入口',
177
+ submitting: '提交中…',
178
+
179
+ resultTitlePcb: 'PCB 订单已创建',
180
+ resultTitleSmt: '贴片订单已创建',
181
+ resultLaunched: '已在浏览器打开',
182
+ resultReady: '待打开',
183
+ resultNote: '与 KiCad 在下单窗口中展示的是同一个页面,已在你的默认浏览器中打开。',
184
+ resultLaunchedMessage: (kind: string) => `已在默认浏览器中打开「${kind}」订单页。`,
185
+ resultReadyMessage: (kind: string) => `「${kind}」订单页已就绪,打开链接即可继续。`,
186
+ openInBrowser: '在浏览器打开',
187
+ opening: '正在打开…',
188
+ copyUrl: '复制链接',
189
+ copied: '已复制',
190
+
191
+ confirmAria: '确认下单上传',
192
+ confirmTitlePcb: '上传板文件并创建 PCB 订单?',
193
+ confirmTitleSmt: '上传贴片文件包?',
194
+ confirmBody: '以下文件将发送到华秋下单服务。订单在那里创建,其页面会在你的默认浏览器中打开;付款仍在该页面完成。',
195
+ confirmZip: (zip: string, size: string) => `${zip} — Gerber 与钻孔文件(${size})`,
196
+ confirmPositions: (size: string) => `元件坐标(${size})`,
197
+ confirmBom: (size: string) => `贴片 BOM(${size})`,
198
+ confirmHost: (baseUrl: string | undefined) => baseUrl ?? '已配置的下单服务',
199
+ confirmAck: '我了解这些板文件将离开本机。',
200
+ cancel: '取消',
201
+ uploadAndOpen: '上传并打开订单页',
202
+ uploading: '正在上传…',
203
+
204
+ batch: '生产数量',
205
+ batchUnits: (count: number) => `${String(count)} 片`,
206
+ quoteBasis: (count: number) => `报价基准 · ${String(count)} 片`,
207
+ },
208
+
209
+ /** First-run setup wizard. */
210
+ wizard: {
211
+ steps: ['欢迎', 'KiCad', 'SolidCraft'] as const,
212
+ stepCounter: (index: number, total: number, label: string) =>
213
+ `${String(index)}/${String(total)} · ${label}`,
214
+ aria: '硬件工程初始化',
215
+
216
+ welcomeTitle: '配置你的硬件工具链',
217
+ welcomeKicker: '仅需一次 · 可跳过',
218
+ welcomeLead: '硬件工程可预览 KiCad 工程、导出 PCB 三维模型、打包制板文件并调用本地程序打开文件。只需指定一次本地安装位置。',
219
+ welcomeUsesTitle: '使用到的组件',
220
+ welcomeUses: 'kicad-cli 负责预览、BOM、GLB 与 Gerber/钻孔打包。SolidCraft 仅作为环境上下文提供给 Agent。',
221
+ welcomeLocal: '只使用本机的可执行文件。不会上传任何内容,也不会替你安装任何东西。',
222
+
223
+ kicadTitle: 'KiCad 安装位置',
224
+ kicadOptional: '可选',
225
+ kicadLead: '填写 KiCad 安装目录或 kicad-cli 路径。它用于 .kicad_sch / .kicad_pcb 预览、PCB 的 GLB 导出、制板文件打包,以及「用 KiCad 打开」。',
226
+ kicadPlaceholder: 'C:\\Program Files\\KiCad\\8.0\\ 或 /usr/bin/kicad-cli',
227
+ kicadSkipHint: '留空即跳过。之后可在「设置 → 硬件工程」中配置。',
228
+
229
+ solidcraftTitle: 'SolidCraft 安装位置',
230
+ solidcraftLead: '本 POC 中 SolidCraft 仅作为环境上下文提供给 Agent——不启动本地程序,也不做结构预览。',
231
+ solidcraftPlaceholder: 'C:\\Program Files\\SolidCraft\\bin\\SolidCraft.exe',
232
+
233
+ skip: '跳过设置',
234
+ back: '上一步',
235
+ next: '下一步',
236
+ finish: '完成',
237
+ saving: '保存中…',
238
+ footerNote: '随时可在「设置 → 硬件工程」中修改。',
239
+ },
240
+
241
+ /** Settings section (the two CAD installation roots). */
242
+ settings: {
243
+ title: '硬件工程',
244
+ lead: '用于预览、制板打包、一键调用本地程序以及 Agent 环境上下文的本地 EDA / MCAD 可执行文件。',
245
+ kicadTitle: 'KiCad EDA 套件',
246
+ kicadBlurb: '可填 KiCad 安装目录或 kicad-cli 路径。用于 .kicad_sch / .kicad_pcb 预览、GLB 导出、BOM、Gerber 打包与本地打开。',
247
+ kicadPlaceholder: 'C:\\Program Files\\KiCad\\8.0\\ 或 /usr/bin/kicad-cli',
248
+ solidcraftTitle: 'SolidCraft 三维 CAD',
249
+ solidcraftBlurb: '本 POC 中仅用于 Agent 环境上下文。不启动本地程序,也不做结构预览;「3D 模型」页签渲染的是所选 PCB。',
250
+ solidcraftPlaceholder: 'C:\\Program Files\\SolidCraft\\bin\\SolidCraft.exe',
251
+ pathField: (title: string) => `${title}路径`,
252
+ validate: '校验并保存',
253
+ validating: '校验中…',
254
+ configured: '已配置',
255
+ notConfigured: '未配置',
256
+ notDetected: '未检测到',
257
+ savedAndValidated: (application: string) => `${application} 校验通过并已保存。`,
258
+ savedButInvalid: (application: string, detail: string) => `${application} 已保存,但校验失败:${detail}`,
259
+ hostSettingsUnavailable: '宿主未提供设置服务,无法保存。',
260
+ hostRejected: (application: string) => `宿主拒绝了${application}的设置。`,
261
+ },
262
+
263
+ /**
264
+ * Host error sentences, keyed by the stable `code` in the route envelope
265
+ * (`packages/hardware-artifacts/src/routes.ts`). A code missing here is not a
266
+ * bug in the UI: the host detail is then shown verbatim, which is the right
267
+ * answer for an unmodelled failure.
268
+ */
269
+ errors: {
270
+ unauthorized: '没有权限访问该产物:它不在当前会话的工作区授权范围内。',
271
+ forbidden: '没有权限执行该操作。',
272
+ 'missing-artifact': '该产物不存在。',
273
+ 'unsupported-artifact': '不支持该产物类型。',
274
+ 'invalid-identity': '产物路径无效。',
275
+ 'missing-executable': '已配置的 KiCad 中没有可打开该产物的程序。',
276
+ 'not-configured': '尚未配置 KiCad。请在「设置 → 硬件工程」中填写安装位置。',
277
+ 'too-large': '产物超过可预览的大小上限。',
278
+ 'export-timeout': 'kicad-cli 执行超时。',
279
+ 'export-failed': 'kicad-cli 导出失败。',
280
+ 'stale-revision': '文件已变化,请刷新后重试。',
281
+ 'invalid-request': '请求参数不完整。',
282
+ 'invalid-application': '不支持该本地程序。',
283
+ 'confirmation-required': '下单需要先在上传确认框中确认。',
284
+ 'invalid-order-url': '订单链接无效,已拒绝打开。',
285
+ 'order-unreachable': '无法连接下单服务。',
286
+ 'order-rejected': '下单服务未能返回可用的订单页。',
287
+ 'not-found': '未找到该接口。',
288
+ internal: '服务内部错误。',
289
+ },
290
+ } as const
291
+
292
+ export type HardwareCopy = typeof COPY
293
+
294
+ /**
295
+ * Codes whose host detail is a technical tail worth keeping next to the
296
+ * translated sentence: kicad-cli stderr, an HTTP failure, a backend payload.
297
+ * For the rest the detail merely restates the sentence in English.
298
+ */
299
+ const KEEPS_DETAIL = new Set([
300
+ 'export-failed',
301
+ 'order-unreachable',
302
+ 'order-rejected',
303
+ 'invalid-order-url',
304
+ 'internal',
305
+ ])
306
+
307
+ /**
308
+ * One host error → one zh_CN sentence.
309
+ *
310
+ * `detail` is the host's own message. Unknown codes keep it untouched, so an
311
+ * unmodelled failure still says something specific instead of collapsing into
312
+ * a generic "出错了".
313
+ */
314
+ export function describeHostError(code: string | undefined, detail: string): string {
315
+ if (code === undefined) return detail
316
+ const sentence = (COPY.errors as Record<string, string | undefined>)[code]
317
+ if (sentence === undefined) return detail
318
+ return KEEPS_DETAIL.has(code) && detail !== '' ? `${sentence}(${detail})` : sentence
319
+ }
320
+
321
+ /**
322
+ * Translate one discovery `issue` without losing the host's specifics.
323
+ *
324
+ * The count and the workspace come from the discovery result, not from the
325
+ * host sentence, so the wording does not depend on how the host phrased it.
326
+ */
327
+ export function issueText(
328
+ issue: { readonly code: string; readonly message: string },
329
+ context: { readonly cwd?: string; readonly count?: number } = {},
330
+ ): string {
331
+ switch (issue.code) {
332
+ case 'selection-required':
333
+ return context.count !== undefined && context.count > 1
334
+ ? COPY.discovery.selectionRequiredCount(context.count)
335
+ : COPY.discovery.selectionRequiredArtifact
336
+ case 'no-project':
337
+ return COPY.discovery.noProject(context.cwd ?? '')
338
+ case 'missing-project':
339
+ // Host text is `${path} does not exist`; the path is the useful half.
340
+ return COPY.discovery.missingProject(issue.message.replace(/\s+does not exist\s*$/u, ''))
341
+ case 'bad-manifest':
342
+ return COPY.discovery.badManifest(issue.message.replace(/^invalid \.hardware-engineering\.json:\s*/u, ''))
343
+ default:
344
+ return issue.message
345
+ }
346
+ }
@@ -9,6 +9,7 @@
9
9
  import { BoardParser, SchematicParser } from '@huaqiu/kicad-sexpr-parser'
10
10
  import { renderPcb, renderSchematic } from '@huaqiu/ecad-renderer'
11
11
  import { loadArtifactSource, type ArtifactSource } from './transport.js'
12
+ import { COPY } from './copy.js'
12
13
 
13
14
  export type EcadKind = 'schematic' | 'pcb'
14
15
  export interface MountedEcad {
@@ -37,28 +38,56 @@ export async function mountEcad(
37
38
  kind: EcadKind,
38
39
  artifactPath: string,
39
40
  container: HTMLElement,
40
- options: { readonly signal: AbortSignal; readonly revision?: string },
41
+ options: { readonly signal: AbortSignal; readonly revision?: string; readonly session?: string },
41
42
  ): Promise<MountedEcad> {
42
- const source = await loadArtifactSource(artifactPath, options.signal, options.revision)
43
+ const source = await loadArtifactSource(artifactPath, {
44
+ signal: options.signal,
45
+ ...(options.revision === undefined ? {} : { expectedRevision: options.revision }),
46
+ ...(options.session === undefined ? {} : { session: options.session }),
47
+ })
43
48
  if (options.signal.aborted) throw aborted(options.signal)
44
49
  if (source.kind !== undefined && source.kind !== kind) {
45
- throw new Error(`host returned a ${source.kind} artifact for a ${kind} preview`)
50
+ throw new Error(COPY.preview.ecadKindMismatch(kind, source.kind))
46
51
  }
47
52
 
53
+ // The renderer owns the backing resolution but not the CSS size, and it fits
54
+ // the view to the canvas during `load()`. Supplying our own already-sized
55
+ // canvas is therefore the only way the first fit matches the panel instead of
56
+ // the renderer's 300x150 default.
57
+ const canvas = document.createElement('canvas')
58
+ canvas.style.cssText = 'position:absolute;inset:0;display:block;width:100%;height:100%;outline:none'
59
+ container.append(canvas)
60
+
48
61
  let rendered
49
62
  if (kind === 'schematic') {
50
- rendered = await renderSchematic(new SchematicParser().parse(source.text), { container, interactive: true })
63
+ rendered = await renderSchematic(new SchematicParser().parse(source.text), { canvas, container, interactive: true })
51
64
  } else {
52
- rendered = await renderPcb(new BoardParser().parse(source.text), { container, interactive: true })
65
+ rendered = await renderPcb(new BoardParser().parse(source.text), { canvas, container, interactive: true })
53
66
  }
54
67
 
55
68
  if (options.signal.aborted) {
56
69
  rendered.dispose()
70
+ canvas.remove()
57
71
  throw aborted(options.signal)
58
72
  }
59
73
 
74
+ // The viewer fits once during `load()`, before React has finished laying the
75
+ // viewer tab out. Re-fit on the next painted frame so the first view matches
76
+ // the panel it is actually in rather than the pre-layout canvas. Only at
77
+ // mount: a later resize must not undo the user's own pan/zoom.
78
+ const viewer = rendered.viewer as { zoom_fit_top_item?: () => void }
79
+ if (typeof viewer.zoom_fit_top_item === 'function') {
80
+ await new Promise<void>((resolve) => {
81
+ requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) })
82
+ })
83
+ if (!options.signal.aborted) viewer.zoom_fit_top_item()
84
+ }
85
+
60
86
  return {
61
- dispose: () => { rendered.dispose() },
87
+ dispose: () => {
88
+ rendered.dispose()
89
+ canvas.remove()
90
+ },
62
91
  sourceRevision: source.revision,
63
92
  source,
64
93
  }
@@ -5,13 +5,21 @@
5
5
  * `keepMounted` right-panel tab body, and one settings section. Native open
6
6
  * lives inside the viewer with the resolved artifact in scope, so no
7
7
  * conversation-level action is registered.
8
+ *
9
+ * Two store handles, not one: DSH pins a handle to a single slot scope, and
10
+ * `conversation.header.leading`/`settings.section` are `root` while
11
+ * `sidebar.right.pane.tab` is `session`. Mounting one handle in both scopes is
12
+ * rejected at load time ("one handle, one scope"). The two halves therefore
13
+ * coordinate the only way the slot contract allows — through the tab
14
+ * parameters and their navigation revision.
8
15
  */
9
16
  import { EngineeringNav, HardwareSettingsSection, HardwareViewerBody } from './components.js'
10
17
  import type {
11
- ConfigFormLike, HardwareActions, HardwareDestination, HardwareInjected,
12
- HardwareInstallationConfig, NativeApplication,
18
+ ConfigFormLike, HardwareController, HardwareDestination, HardwareInstallationConfig,
19
+ ViewerNavigationParams,
13
20
  } from './model.js'
14
21
  import { createHardwareStore } from './store.js'
22
+ import { COPY } from './copy.js'
15
23
  import { loadInstallations, loadProjects, openArtifact } from './transport.js'
16
24
 
17
25
  /** Real Cordis service names this browser plugin waits for. */
@@ -20,6 +28,8 @@ export const inject = ['slots', 'sidebarRight', 'sidebarRightTabs', 'configForms
20
28
  export const HARDWARE_SETTINGS_ID = 'hardware-engineering'
21
29
  export const HARDWARE_TAB_ID = '@huaqiu/dsh-hardware-ui'
22
30
  export const HARDWARE_TAB_KIND = 'hardware-engineering'
31
+ /** Host plugin row id whose volatile config backs the product settings page. */
32
+ export const HARDWARE_CONFIG_ENTRY = 'hardware-artifacts'
23
33
 
24
34
  interface SlotSpec {
25
35
  name: string
@@ -73,84 +83,55 @@ function nativeKindFor(destination: HardwareDestination, path: string): string {
73
83
 
74
84
  /** Install all product UI contributions on a DSH client context. */
75
85
  export function apply(ctx: ClientContext): void {
76
- const store = createHardwareStore()
77
- let actions: HardwareActions | undefined
78
- let revision = 0
86
+ // Root scope: product chrome (navigation + settings) shares one instance.
87
+ const rootStore = createHardwareStore()
88
+ // Session scope: each viewer owns its own selection/discovery state.
89
+ const viewerStore = createHardwareStore()
90
+ let navigation = 0
79
91
  const effect = (fn: () => (() => void) | void, label: string): void => {
80
92
  if (ctx.effect !== undefined) ctx.effect(fn, label)
81
93
  else fn()
82
94
  }
83
95
 
84
- const captureActions = (...args: unknown[]): { hooks: HardwareInjected } => {
85
- for (const candidate of args) {
86
- if (candidate !== null && typeof candidate === 'object'
87
- && typeof (candidate as HardwareActions).setActive === 'function') {
88
- actions = candidate as HardwareActions
89
- }
90
- }
91
- return { hooks: injected }
92
- }
93
-
94
- const injected: HardwareInjected = {
95
- async refreshDiscovery(cwd, project) {
96
- try {
97
- const result = await loadProjects(cwd, project)
98
- actions?.setDiscovery(result)
99
- if (result.issue?.code === 'bad-manifest') actions?.setNotice(result.issue.message)
100
- } catch (error) {
101
- actions?.setNotice(`Artifact discovery failed: ${String(error)}`)
102
- }
96
+ const controller: HardwareController = {
97
+ discover(cwd, project, session) {
98
+ return loadProjects(cwd, project, session)
103
99
  },
104
- openDestination(destination: HardwareDestination, path) {
105
- revision += 1
106
- const kind = path === undefined ? undefined : kindForPath(path)
107
- try {
108
- ctx.sidebarRight?.openTab(HARDWARE_TAB_KIND, {
109
- params: {
110
- destination,
111
- ...(path === undefined ? {} : { path }),
112
- ...(kind === undefined ? {} : { kind }),
113
- navigationRevision: revision,
114
- },
115
- revealIfOpened: true,
116
- })
117
- } catch (error) {
118
- actions?.setNotice(`Open viewer failed: ${String(error)}`)
119
- }
120
- },
121
- async openNative(application?: NativeApplication, artifactPath?: string) {
122
- if (artifactPath === undefined || artifactPath === '') {
123
- actions?.setNotice('Select an artifact before opening it in KiCad.')
124
- return
125
- }
126
- const destination = store.create().getSnapshot().activeDestination
127
- try {
128
- await openArtifact({
129
- application: application ?? 'kicad',
130
- artifactPath,
131
- kind: nativeKindFor(destination, artifactPath),
132
- })
133
- } catch (error) {
134
- actions?.setNotice(`Native launch failed: ${String(error)}`)
135
- throw error
136
- }
100
+ installations() {
101
+ return loadInstallations()
137
102
  },
138
103
  async saveInstallation(application, root) {
139
- const form = ctx.configForms?.get<HardwareInstallationConfig>('hardware-artifacts')
140
- if (form === undefined) throw new Error('host settings are unavailable')
104
+ const form = ctx.configForms?.get<HardwareInstallationConfig>(HARDWARE_CONFIG_ENTRY)
105
+ if (form === undefined) throw new Error(COPY.settings.hostSettingsUnavailable)
141
106
  const field = application === 'kicad' ? 'kicadRoot' : 'solidcraftRoot'
142
107
  const accepted = await form.set(field, root)
143
- if (!accepted) throw new Error(`the host rejected the ${field} setting`)
108
+ if (!accepted) {
109
+ throw new Error(COPY.settings.hostRejected(application === 'kicad' ? 'KiCad' : 'SolidCraft'))
110
+ }
111
+ },
112
+ configForm() {
113
+ return ctx.configForms?.get<HardwareInstallationConfig>(HARDWARE_CONFIG_ENTRY)
144
114
  },
145
- async fetchInstallations() {
146
- try {
147
- actions?.setInstallations(await loadInstallations())
148
- } catch (error) {
149
- actions?.setNotice(`Installation check failed: ${String(error)}`)
115
+ openDestination(destination, path) {
116
+ navigation += 1
117
+ const kind = path === undefined ? undefined : kindForPath(path)
118
+ const params: ViewerNavigationParams = {
119
+ destination,
120
+ ...(path === undefined ? {} : { path }),
121
+ ...(kind === undefined ? {} : { kind }),
122
+ navigationRevision: navigation,
150
123
  }
124
+ ctx.sidebarRight?.openTab(HARDWARE_TAB_KIND, {
125
+ params: params as unknown as Readonly<Record<string, unknown>>,
126
+ revealIfOpened: true,
127
+ })
151
128
  },
152
- useConfigForm() {
153
- return ctx.configForms?.get<HardwareInstallationConfig>('hardware-artifacts')
129
+ async openNative(request) {
130
+ await openArtifact({
131
+ application: request.application,
132
+ artifactPath: request.artifactPath,
133
+ kind: request.kind,
134
+ })
154
135
  },
155
136
  }
156
137
 
@@ -158,7 +139,7 @@ export function apply(ctx: ClientContext): void {
158
139
  id: HARDWARE_TAB_ID,
159
140
  kind: HARDWARE_TAB_KIND,
160
141
  keepMounted: true,
161
- title: () => 'Hardware Engineering',
142
+ title: () => COPY.product.name,
162
143
  }) ?? (() => {}), 'hardware-ui: right-panel tab type')
163
144
 
164
145
  const slots = ctx.slots
@@ -166,23 +147,23 @@ export function apply(ctx: ClientContext): void {
166
147
 
167
148
  effect(() => slots.inject('conversation.header.leading', () => slots.register({
168
149
  name: 'conversation.header.leading',
169
- store,
170
- inject: captureActions,
150
+ store: rootStore,
151
+ inject: () => controller,
171
152
  }, EngineeringNav)), 'hardware-ui: five-destination navigation')
172
153
 
173
154
  effect(() => slots.inject('sidebar.right.pane.tab', () => slots.register({
174
155
  name: 'sidebar.right.pane.tab',
175
156
  key: HARDWARE_TAB_ID,
176
- store,
177
- inject: captureActions,
157
+ store: viewerStore,
158
+ inject: () => controller,
178
159
  }, HardwareViewerBody)), 'hardware-ui: viewer body')
179
160
 
180
161
  effect(() => slots.inject('settings.section', () => slots.register({
181
162
  name: 'settings.section',
182
163
  id: HARDWARE_SETTINGS_ID,
183
164
  order: 85,
184
- label: () => 'Hardware Engineering',
185
- store,
186
- inject: captureActions,
165
+ label: () => COPY.product.name,
166
+ store: rootStore,
167
+ inject: () => controller,
187
168
  }, HardwareSettingsSection)), 'hardware-ui: CAD installation settings')
188
169
  }