@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.
@@ -1,7 +1,14 @@
1
1
  /**
2
- * Hardware Engineering UI components. All state reaches them through the
3
- * standard slot props (`useStore`, `actions`) and one injected hook bundle;
4
- * nothing here imports Node APIs or reaches into another plugin's singleton.
2
+ * Hardware Engineering UI components.
3
+ *
4
+ * Props come from three declared sources and nothing else:
5
+ * - the slot store seat (`useStore`, `actions`),
6
+ * - the registrant's inject face (the {@link HardwareController} members,
7
+ * delivered verbatim — never through a `hooks` compartment),
8
+ * - the framework standard kit (`sessionId`, `useSessions`, `useTabInfo`).
9
+ *
10
+ * Importing nothing from Node keeps the client bundle loadable by the DSH
11
+ * ModuleLoader; every host read goes through `./transport.ts`.
5
12
  */
6
13
  import {
7
14
  createElement, useEffect, useMemo, useState, useSyncExternalStore,
@@ -9,79 +16,151 @@ import {
9
16
  } from 'react'
10
17
  import {
11
18
  applicationFor, DESTINATIONS, DESTINATION_LABELS,
12
- type HardwareActions, type HardwareArtifactInfo, type HardwareDestination,
13
- type HardwareInjected, type HardwareInstallationConfig, type HardwareState,
19
+ type ConfigFormLike, type HardwareActions, type HardwareArtifactInfo, type HardwareController,
20
+ type HardwareDestination, type HardwareInstallationConfig, type HardwareState,
21
+ type ViewerNavigationParams,
14
22
  } from './model.js'
15
23
  import { HardwarePreview } from './preview.js'
24
+ import { OnboardingWizard } from './wizard.js'
25
+ import { COPY, issueText } from './copy.js'
26
+ import { messageOf } from './transport.js'
27
+ import {
28
+ buttonStyle, C, cardStyle, disabled, DOT_COLORS, dotStyle, INPUT, MUTED, MONO, MONO_TEXT,
29
+ pillStyle, R, SECTION_TITLE,
30
+ } from './theme.js'
16
31
 
17
32
  type UseStore = <S>(selector: (state: HardwareState) => S) => S
18
33
 
19
- interface SlotProps {
34
+ /** Tab information the `sidebar.right.pane.tab` seat supplies as `useTabInfo`. */
35
+ export interface TabInfo {
36
+ readonly tab: {
37
+ readonly id: string
38
+ readonly navigation: {
39
+ readonly params?: Readonly<Record<string, unknown>>
40
+ readonly revision?: number
41
+ }
42
+ readonly signal?: AbortSignal
43
+ readonly visible?: boolean
44
+ }
45
+ }
46
+
47
+ export interface SlotProps {
20
48
  readonly useStore: UseStore
21
49
  readonly actions: HardwareActions
22
- readonly hooks: HardwareInjected
50
+ /** Slot-delivered hook; absent only in non-DSH test harnesses. */
51
+ readonly useTabInfo?: () => TabInfo
52
+ readonly sessionId?: string
53
+ readonly useSessions?: (selector: (state: {
54
+ readonly ids: readonly string[]
55
+ readonly byId: Readonly<Record<string, { readonly cwd?: string }>>
56
+ }) => string | undefined) => string | undefined
23
57
  readonly t?: (key: string) => string
24
58
  }
25
59
 
26
- const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }
27
- const NAV: CSSProperties = { ...ROW, minWidth: 0, fontSize: 12 }
28
- const TAB: CSSProperties = {
29
- border: '1px solid var(--dsw-alias-border-default, rgba(127,127,127,0.3))',
30
- borderRadius: 6, background: 'transparent', color: 'var(--dsw-alias-label-secondary)',
31
- padding: '3px 8px', cursor: 'pointer', font: 'inherit', whiteSpace: 'nowrap',
60
+ /** Full component props: slot props plus the controller's verbatim members. */
61
+ export type HardwareProps = SlotProps & HardwareController
62
+
63
+ const EMPTY_TAB: TabInfo = { tab: { id: '', navigation: {} } }
64
+ const useEmptyTab = (): TabInfo => EMPTY_TAB
65
+
66
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap', minWidth: 0 }
67
+
68
+ const NAV: CSSProperties = {
69
+ display: 'flex', alignItems: 'center', gap: 3, minWidth: 0, fontSize: 12,
70
+ position: 'relative', flexWrap: 'nowrap',
71
+ }
72
+ const NAV_ITEM: CSSProperties = {
73
+ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '3px 8px', borderRadius: R.md,
74
+ border: '1px solid transparent', background: 'transparent', color: C.text2,
75
+ cursor: 'pointer', font: 'inherit', fontSize: 11.5, whiteSpace: 'nowrap', flex: '0 0 auto',
76
+ transition: 'background 120ms ease, color 120ms ease, border-color 120ms ease',
77
+ }
78
+ const NAV_ITEM_ACTIVE: CSSProperties = {
79
+ ...NAV_ITEM,
80
+ color: C.text,
81
+ background: C.card,
82
+ border: `1px solid ${C.border}`,
32
83
  }
33
- const ACTIVE: CSSProperties = {
34
- ...TAB, color: 'var(--dsw-alias-label-primary)', borderColor: 'var(--dsw-alias-brand-primary, currentColor)',
35
- background: 'color-mix(in srgb, var(--dsw-alias-brand-primary, currentColor) 10%, transparent)',
84
+ const BRAND: CSSProperties = {
85
+ display: 'flex', alignItems: 'center', gap: 6, paddingRight: 8, flex: '0 0 auto',
86
+ borderRight: `1px solid ${C.border}`, marginRight: 3,
36
87
  }
37
- const PATH: CSSProperties = {
38
- minWidth: 0, maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
39
- color: 'var(--dsw-alias-label-tertiary)', fontSize: 11,
88
+ const BRAND_MARK: CSSProperties = {
89
+ width: 19, height: 19, borderRadius: R.sm, display: 'flex', alignItems: 'center', justifyContent: 'center',
90
+ fontSize: 9.5, fontWeight: 700, color: '#fff', background: C.accent,
91
+ boxShadow: '0 2px 8px rgba(225,37,27,0.35)',
40
92
  }
41
- const ROOT: CSSProperties = {
42
- display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0,
43
- boxSizing: 'border-box', padding: 12, gap: 10,
44
- color: 'var(--dsw-alias-label-primary)', overflow: 'auto',
93
+ const BRAND_NAME: CSSProperties = { fontSize: 10.5, fontWeight: 600, whiteSpace: 'nowrap', color: C.text }
94
+ const CHIP: CSSProperties = {
95
+ minWidth: 0, maxWidth: 168, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
96
+ color: C.text3, fontSize: 10, fontFamily: MONO, flex: '0 1 auto',
45
97
  }
46
- const HEADER: CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }
47
- const TITLE: CSSProperties = { margin: 0, fontSize: 14, fontWeight: 600 }
48
- const BUTTON: CSSProperties = {
49
- ...TAB, padding: '5px 10px', color: 'var(--dsw-alias-label-primary)',
98
+ const PANEL_ROOT: CSSProperties = {
99
+ display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0, minWidth: 0,
100
+ boxSizing: 'border-box', background: C.base, color: C.text,
50
101
  }
51
- const FIELD: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12 }
52
- const INPUT: CSSProperties = {
53
- width: '100%', boxSizing: 'border-box', padding: '6px 8px', borderRadius: 6,
54
- border: '1px solid var(--dsw-alias-border-default, rgba(127,127,127,0.3))',
55
- background: 'transparent', color: 'inherit', font: 'inherit',
102
+ const STRIP: CSSProperties = {
103
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6,
104
+ padding: '5px 8px', background: C.panel, borderBottom: `1px solid ${C.border}`,
105
+ flex: '0 0 auto', minWidth: 0,
56
106
  }
57
- const MUTED: CSSProperties = { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12, margin: 0 }
58
- const SELECT: CSSProperties = { ...INPUT, cursor: 'pointer' }
107
+ const STRIP_GROUP: CSSProperties = { ...ROW, gap: 2, flexWrap: 'nowrap', overflowX: 'auto', minWidth: 0 }
108
+ const META: CSSProperties = {
109
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
110
+ padding: '4px 10px', background: C.base, borderBottom: `1px solid ${C.borderSoft}`,
111
+ flex: '0 0 auto', minWidth: 0, fontSize: 10, color: C.text3,
112
+ }
113
+ const META_PATH: CSSProperties = {
114
+ ...MONO_TEXT, fontSize: 10, color: C.text2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
115
+ minWidth: 0,
116
+ }
117
+ const BODY: CSSProperties = { flex: '1 1 0', minHeight: 0, display: 'flex', flexDirection: 'column', padding: 10, gap: 8 }
59
118
 
60
- function option(value: string, label: string, selected: boolean): ReactNode {
61
- return createElement('option', { key: value, value, selected }, label)
119
+ function option(value: string, label: string): ReactNode {
120
+ return createElement('option', { key: value, value }, label)
62
121
  }
63
122
 
64
- function artworkOptions(artifacts: readonly HardwareArtifactInfo[] | undefined, kind: string): ReactNode[] {
65
- return (artifacts ?? []).filter(artifact => artifact.kind === kind)
66
- .map(artifact => option(artifact.path, artifact.title || artifact.path, false))
123
+ function basename(path: string): string {
124
+ const parts = path.split(/[\\/]/u)
125
+ return parts[parts.length - 1] ?? path
67
126
  }
68
127
 
69
- /** Five persistent destinations in the conversation header's leading seat. */
70
- export function EngineeringNav({
71
- useStore, actions, hooks, useSessions,
72
- }: SlotProps & {
73
- useSessions?: (selector: (state: {
74
- readonly ids: readonly string[]
75
- readonly byId: Readonly<Record<string, { readonly cwd?: string }>>
76
- }) => string | undefined) => string | undefined
77
- }): ReactNode {
128
+ /** Read the viewer navigation params carried by one `openTab` call. */
129
+ export function navigationParams(info: TabInfo | undefined): ViewerNavigationParams | undefined {
130
+ const params = info?.tab.navigation.params
131
+ if (params === undefined || typeof params.destination !== 'string') return undefined
132
+ if (!(DESTINATIONS as readonly string[]).includes(params.destination)) return undefined
133
+ return params as unknown as ViewerNavigationParams
134
+ }
135
+
136
+ /**
137
+ * One product navigation row: brand, the five persistent destinations, and the
138
+ * selected project. The first-run wizard renders from this root-scope seat
139
+ * because it must be able to run before any session exists.
140
+ */
141
+ export function EngineeringNav(props: HardwareProps): ReactNode {
142
+ const { useStore, actions, useSessions, discover, openDestination } = props
78
143
  const active = useStore(state => state.activeDestination)
79
144
  const projectPath = useStore(state => state.projectPath)
145
+ const selected = useStore(state => state.discovery?.selected)
146
+ // The navigation row is a `root` seat, so it has no session of its own; the
147
+ // first listed session stands in for "the workspace this product is showing".
148
+ const sessionId = useSessions?.(state => state.ids[0])
80
149
  const cwd = useSessions?.(state => {
81
150
  const id = state.ids[0]
82
151
  return id === undefined ? undefined : state.byId[id]?.cwd
83
152
  })
84
- useEffect(() => { void hooks.refreshDiscovery(cwd) }, [cwd, hooks])
153
+
154
+ useEffect(() => {
155
+ let live = true
156
+ discover(cwd, undefined, sessionId)
157
+ .then((discovery) => { if (live) actions.setDiscovery(discovery) })
158
+ .catch((error: unknown) => { if (live) actions.setNotice(COPY.viewer.discoveryFailed(messageOf(error))) })
159
+ return () => { live = false }
160
+ }, [cwd, sessionId, discover, actions])
161
+
162
+ const projectName = selected?.name ?? (projectPath === undefined ? undefined : basename(projectPath))
163
+
85
164
  return createElement(
86
165
  'div',
87
166
  { style: NAV, 'data-hardware-nav': true },
@@ -89,17 +168,24 @@ export function EngineeringNav({
89
168
  'button',
90
169
  {
91
170
  key: destination, type: 'button',
92
- style: destination === active ? ACTIVE : TAB,
171
+ style: destination === active ? NAV_ITEM_ACTIVE : NAV_ITEM,
93
172
  'aria-pressed': destination === active,
94
173
  'data-destination': destination,
174
+ title: DESTINATION_LABELS[destination],
95
175
  onClick: () => {
96
176
  actions.setActive(destination)
97
- hooks.openDestination(destination)
177
+ openDestination(destination)
98
178
  },
99
179
  },
180
+ createElement('span', { style: dotStyle(DOT_COLORS[destination], 6) }),
100
181
  DESTINATION_LABELS[destination],
101
182
  )),
102
- ...(projectPath === undefined ? [] : [createElement('span', { key: 'path', style: PATH, title: projectPath }, projectPath)]),
183
+ ...(projectName === undefined
184
+ ? []
185
+ : [createElement('span', {
186
+ key: 'project', style: { ...CHIP, paddingLeft: 4 }, title: projectPath ?? projectName,
187
+ }, projectName)]),
188
+ createElement(OnboardingWizard, props),
103
189
  )
104
190
  }
105
191
 
@@ -108,210 +194,404 @@ export function selectedArtifact(state: HardwareState, destination: HardwareDest
108
194
  const project = state.discovery?.selected
109
195
  const schematic: HardwareArtifactInfo | undefined = state.schematicPath === undefined
110
196
  ? project?.schematic
111
- : { id: `schematic:${state.schematicPath}`, kind: 'schematic', path: state.schematicPath, title: state.schematicPath.split(/[\\/]/u).pop() ?? state.schematicPath }
197
+ : { id: `schematic:${state.schematicPath}`, kind: 'schematic', path: state.schematicPath, title: basename(state.schematicPath) }
112
198
  const board: HardwareArtifactInfo | undefined = state.pcbPath === undefined
113
199
  ? project?.boards?.find(candidate => candidate.path === project?.defaultBoard) ?? project?.boards?.[0]
114
- : { id: `pcb:${state.pcbPath}`, kind: 'pcb', path: state.pcbPath, title: state.pcbPath.split(/[\\/]/u).pop() ?? state.pcbPath }
200
+ : { id: `pcb:${state.pcbPath}`, kind: 'pcb', path: state.pcbPath, title: basename(state.pcbPath) }
115
201
  if (destination === 'schematic' || destination === 'bom') return schematic
116
- if (destination === 'pcb' || destination === '3d') return board
117
202
  return board
118
203
  }
119
204
 
120
205
  function missingReason(state: HardwareState, destination: HardwareDestination): string | undefined {
121
206
  const discovery = state.discovery
122
207
  if (discovery === undefined) return undefined
123
- if (discovery.issue?.code === 'selection-required' && discovery.projects !== undefined && discovery.projects.length > 1) {
124
- return `${discovery.projects.length} projects found; choose one explicitly.`
208
+ if (discovery.issue?.code === 'selection-required' && (discovery.projects?.length ?? 0) > 1) {
209
+ return COPY.discovery.selectionRequiredCount(discovery.projects?.length ?? 0)
125
210
  }
126
- if (discovery.selected === undefined) return 'No hardware project selected. Open or select a hardware project.'
211
+ if (discovery.selected === undefined) return COPY.discovery.noProjectSelected
127
212
  if (destination === 'schematic' || destination === 'bom') {
128
- if (discovery.selected.schematic === undefined) return 'This project has no discoverable root schematic.'
213
+ if (discovery.selected.schematic === undefined) return COPY.discovery.noSchematic
129
214
  }
130
215
  if (destination === 'pcb' || destination === '3d') {
131
- if ((discovery.selected.boards?.length ?? 0) === 0) return 'This project has no discoverable .kicad_pcb board.'
216
+ if ((discovery.selected.boards?.length ?? 0) === 0) return COPY.discovery.noBoard
132
217
  }
133
218
  if (destination === 'order') {
134
- if ((discovery.selected.boards?.length ?? 0) === 0) return 'Select a board before quoting or ordering fabrication.'
219
+ if ((discovery.selected.boards?.length ?? 0) === 0) return COPY.discovery.noBoardToOrder
135
220
  }
136
221
  return undefined
137
222
  }
138
223
 
139
- /** Right-panel body: one destination at a time, with explicit selectors. */
140
- export function HardwareViewerBody({
141
- useStore, actions, hooks, tab,
142
- }: SlotProps & {
143
- tab?: {
144
- readonly navigation?: {
145
- readonly params?: Readonly<Record<string, unknown>>
146
- readonly revision?: number
147
- }
148
- }
149
- }): ReactNode {
224
+ /** Native-open affordance for the artifact currently on screen. */
225
+ function nativeAction(
226
+ active: HardwareDestination,
227
+ artifact: HardwareArtifactInfo | undefined,
228
+ configured: boolean,
229
+ notice: (message: string) => void,
230
+ openNative: HardwareController['openNative'],
231
+ ): ReactNode {
232
+ const application = applicationFor(active)
233
+ if (application === undefined) return null
234
+ const canOpen = configured && artifact !== undefined
235
+ return createElement(
236
+ 'button',
237
+ {
238
+ type: 'button',
239
+ style: { ...buttonStyle(canOpen ? 'secondary' : 'quiet'), fontSize: 10.5, padding: '2px 7px', ...disabled(!canOpen) },
240
+ disabled: !canOpen,
241
+ 'data-hardware-native-open': true,
242
+ title: canOpen
243
+ ? COPY.viewer.openInKicadTitle(artifact.path)
244
+ : configured ? COPY.viewer.selectArtifactFirst : COPY.viewer.configureKicad,
245
+ onClick: () => {
246
+ if (artifact === undefined) return
247
+ openNative({
248
+ application,
249
+ artifactPath: artifact.path,
250
+ kind: active === '3d' ? 'pcb-3d' : active === 'bom' ? 'bom' : artifact.kind,
251
+ }).catch((error: unknown) => { notice(messageOf(error)) })
252
+ },
253
+ },
254
+ createElement('span', { style: dotStyle(configured ? C.ok : C.text3, 6) }),
255
+ COPY.viewer.openInKicad,
256
+ )
257
+ }
258
+
259
+ /** Keyframes the stages reference; rendered once per panel. */
260
+ const PANEL_STYLE = `
261
+ @keyframes dsh-hw-spin { to { transform: rotate(360deg) } }
262
+ `
263
+
264
+ /**
265
+ * Right-panel body: one destination at a time, driven by the tab's navigation
266
+ * params so a navigation with unchanged params still refreshes (the revision
267
+ * changes), and so the viewer never depends on a remount.
268
+ */
269
+ export function HardwareViewerBody(props: HardwareProps): ReactNode {
270
+ const {
271
+ useStore, actions, useTabInfo, sessionId, useSessions, discover, installations,
272
+ openDestination, openNative,
273
+ } = props
274
+ const info = (useTabInfo ?? useEmptyTab)()
275
+ const navigation = info.tab.navigation
276
+ const params = useMemo(() => navigationParams(info), [navigation.params, navigation.revision])
277
+ const navRevision = navigation.revision ?? 0
278
+
150
279
  const active = useStore(state => state.activeDestination)
151
280
  const discovery = useStore(state => state.discovery)
152
281
  const projectPath = useStore(state => state.projectPath)
153
282
  const schematicPath = useStore(state => state.schematicPath)
154
283
  const pcbPath = useStore(state => state.pcbPath)
155
- const notice = useStore(state => state.notice)
156
- const installations = useStore(state => state.installations)
157
- const revision = tab?.navigation?.revision ?? 0
158
- const selectedProject = discovery?.selected
159
-
160
- useEffect(() => { void hooks.fetchInstallations() }, [hooks])
161
-
284
+ const noticeText = useStore(state => state.notice)
285
+ const installed = useStore(state => state.installations)
162
286
  const artifact = useStore(state => selectedArtifact(state, active))
163
287
  const reason = useStore(state => missingReason(state, active))
164
- const application = applicationFor(active)
165
- const kicadConfigured = installations?.kicad?.configured ?? false
166
- const nativeLabel = application === 'kicad' ? 'Open in KiCad' : 'No native action'
167
- const canOpenNative = application !== undefined && kicadConfigured && artifact !== undefined && active !== 'order'
288
+ const workspaceRoot = useStore(state => state.workspaceRoot)
289
+ const cwd = useSessions?.(state => {
290
+ if (sessionId === undefined) return undefined
291
+ return state.byId[sessionId]?.cwd
292
+ })
293
+
294
+ // Adopt the navigation, then refresh discovery without clobbering it.
295
+ useEffect(() => {
296
+ if (params !== undefined) actions.applyNavigation(params)
297
+ }, [navRevision, params, actions])
298
+
299
+ useEffect(() => {
300
+ let live = true
301
+ discover(cwd, params?.projectPath, sessionId)
302
+ .then((result) => { if (live) actions.setDiscovery(result, params?.path !== undefined) })
303
+ .catch((error: unknown) => { if (live) actions.setNotice(COPY.viewer.discoveryFailed(messageOf(error))) })
304
+ return () => { live = false }
305
+ }, [cwd, sessionId, params?.projectPath, actions, discover])
306
+
307
+ useEffect(() => {
308
+ let live = true
309
+ installations()
310
+ .then((result) => { if (live) actions.setInstallations(result) })
311
+ .catch((error: unknown) => { if (live) actions.setNotice(COPY.viewer.installationFailed(messageOf(error))) })
312
+ return () => { live = false }
313
+ }, [actions, installations])
314
+
315
+ const selectedProject = discovery?.selected
316
+ const kicadConfigured = installed?.kicad?.configured ?? false
317
+ const notice = (message: string): void => { actions.setNotice(message) }
318
+ const go = (destination: HardwareDestination): void => {
319
+ actions.setActive(destination)
320
+ openDestination(destination, destination === 'schematic' || destination === 'bom' ? schematicPath : pcbPath)
321
+ }
168
322
 
169
- const header = createElement(
323
+ const strip = createElement(
170
324
  'div',
171
- { style: HEADER },
172
- createElement('h2', { style: TITLE }, DESTINATION_LABELS[active]),
173
- ...(application === undefined ? [] : [createElement(
174
- 'button',
175
- {
176
- key: 'native', type: 'button', style: BUTTON, disabled: !canOpenNative,
177
- title: canOpenNative
178
- ? `${nativeLabel}: ${artifact?.path ?? ''}`
179
- : kicadConfigured
180
- ? 'Select an artifact before opening it in KiCad.'
181
- : 'Configure KiCad in Settings → Hardware Engineering.',
182
- 'data-hardware-native-open': true,
183
- onClick: () => { void hooks.openNative(application, artifact?.path).catch(error => actions.setNotice(String(error))) },
184
- },
185
- nativeLabel,
186
- )]),
325
+ { style: STRIP, 'data-hardware-destinations': true },
326
+ createElement(
327
+ 'div',
328
+ { style: STRIP_GROUP },
329
+ ...DESTINATIONS.map(destination => createElement(
330
+ 'button',
331
+ {
332
+ key: destination, type: 'button',
333
+ style: destination === active ? { ...NAV_ITEM_ACTIVE, fontSize: 11 } : { ...NAV_ITEM, fontSize: 11 },
334
+ 'aria-pressed': destination === active,
335
+ onClick: () => { go(destination) },
336
+ },
337
+ createElement('span', { style: dotStyle(DOT_COLORS[destination], 6) }),
338
+ DESTINATION_LABELS[destination],
339
+ )),
340
+ ),
341
+ nativeAction(active, artifact, kicadConfigured, notice, openNative),
342
+ )
343
+
344
+ const meta = createElement(
345
+ 'div',
346
+ { style: META },
347
+ createElement('span', { style: META_PATH, title: artifact?.path ?? '' },
348
+ artifact === undefined ? COPY.viewer.noArtifact : artifact.path),
349
+ createElement(
350
+ 'span',
351
+ { style: { display: 'flex', alignItems: 'center', gap: 4, flex: '0 0 auto' } },
352
+ ...(selectedProject === undefined ? [] : [createElement('span', { key: 'project', style: pillStyle('muted') }, selectedProject.name)]),
353
+ ...(kicadConfigured
354
+ ? [createElement('span', { key: 'kicad', style: pillStyle('ok') }, COPY.viewer.kicadVersion(installed?.kicad?.version ?? '').trim())]
355
+ : [createElement('span', { key: 'kicad', style: pillStyle('warn'), title: installed?.kicad?.error ?? '' }, COPY.viewer.kicadMissing)]),
356
+ ),
187
357
  )
188
358
 
189
359
  const selectors: ReactNode[] = []
190
- if (discovery !== undefined && (discovery.projects?.length ?? 0) > 0) {
360
+ const selectStyle: CSSProperties = { ...INPUT, width: 'auto', maxWidth: 220, fontSize: 10.5 }
361
+ if ((discovery?.projects?.length ?? 0) > 1 || discovery?.issue?.code === 'selection-required') {
191
362
  selectors.push(createElement(
192
- 'label',
193
- { key: 'project', style: FIELD },
194
- 'Project',
195
- createElement('select', {
196
- style: SELECT, value: projectPath ?? '',
363
+ 'select',
364
+ {
365
+ key: 'project', style: selectStyle, value: projectPath ?? '', 'aria-label': COPY.viewer.projectField,
197
366
  onChange: (event: ChangeEvent<HTMLSelectElement>) => {
198
- actions.selectProject(event.currentTarget.value)
199
- void hooks.refreshDiscovery(undefined, event.currentTarget.value)
367
+ const path = event.currentTarget.value
368
+ actions.selectProject(path)
369
+ discover(cwd, path, sessionId)
370
+ .then(result => actions.setDiscovery(result))
371
+ .catch((error: unknown) => actions.setNotice(messageOf(error)))
200
372
  },
201
373
  },
202
- option('', 'Select a project…', projectPath === undefined),
203
- ...(discovery?.projects ?? []).map(project => option(project.path, project.name, project.path === projectPath))),
374
+ option('', COPY.viewer.selectProject),
375
+ ...(discovery?.projects ?? []).map(project => option(project.path, project.name)),
204
376
  ))
205
377
  }
206
378
  if ((active === 'schematic' || active === 'bom') && selectedProject !== undefined) {
207
379
  const candidates: HardwareArtifactInfo[] = [selectedProject.schematic, ...(selectedProject.sheets ?? [])]
208
380
  .filter((candidate): candidate is HardwareArtifactInfo => candidate !== undefined)
209
- selectors.push(createElement(
210
- 'label',
211
- { key: 'sheet', style: FIELD },
212
- 'Schematic / sheet',
213
- createElement('select', {
214
- style: SELECT, value: schematicPath ?? '',
215
- onChange: (event: ChangeEvent<HTMLSelectElement>) => {
216
- actions.selectArtifact(event.currentTarget.value, 'schematic')
217
- hooks.openDestination(active, event.currentTarget.value)
381
+ if (candidates.length > 1) {
382
+ selectors.push(createElement(
383
+ 'select',
384
+ {
385
+ key: 'sheet', style: selectStyle, value: schematicPath ?? '', 'aria-label': COPY.viewer.schematicSheetField,
386
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
387
+ const path = event.currentTarget.value
388
+ actions.selectArtifact(path, 'schematic')
389
+ openDestination(active, path)
390
+ },
218
391
  },
219
- },
220
- option('', 'Select a schematic…', schematicPath === undefined),
221
- ...candidates.map(candidate => option(candidate.path, candidate.title, false))),
222
- ))
392
+ ...candidates.map(candidate => option(candidate.path, candidate.title)),
393
+ ))
394
+ }
223
395
  }
224
396
  if ((active === 'pcb' || active === '3d' || active === 'order') && selectedProject !== undefined) {
225
- selectors.push(createElement(
226
- 'label',
227
- { key: 'board', style: FIELD },
228
- 'Board',
229
- createElement('select', {
230
- style: SELECT, value: pcbPath ?? '',
231
- onChange: (event: ChangeEvent<HTMLSelectElement>) => {
232
- actions.selectArtifact(event.currentTarget.value, 'pcb')
233
- hooks.openDestination(active, event.currentTarget.value)
397
+ if ((selectedProject.boards?.length ?? 0) > 1) {
398
+ selectors.push(createElement(
399
+ 'select',
400
+ {
401
+ key: 'board', style: selectStyle, value: pcbPath ?? '', 'aria-label': COPY.viewer.boardField,
402
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
403
+ const path = event.currentTarget.value
404
+ actions.selectArtifact(path, 'pcb')
405
+ openDestination(active, path)
406
+ },
234
407
  },
235
- },
236
- option('', 'Select a board…', pcbPath === undefined),
237
- ...artworkOptions(selectedProject.boards, 'pcb')),
238
- ))
408
+ ...(selectedProject.boards ?? []).map(board => option(board.path, board.title || board.path)),
409
+ ))
410
+ }
239
411
  }
240
412
 
241
- return createElement(
413
+ const banner = createElement(
242
414
  'div',
243
- { style: ROOT, 'data-hardware-destination': active },
244
- header,
245
- ...(notice === undefined ? [] : [createElement('p', { key: 'notice', style: MUTED, role: 'status' }, notice)]),
246
- ...(discovery?.issue === undefined || discovery.issue.code === 'selection-required' && (discovery.projects?.length ?? 0) <= 1
247
- ? []
248
- : [createElement('p', { key: 'issue', style: MUTED, role: 'status' }, discovery.issue.message)]),
249
- createElement('p', { key: 'project-path', style: MUTED },
250
- projectPath === undefined ? 'No canonical KiCad project selected.' : `Project: ${projectPath}`),
415
+ { style: { ...ROW, gap: 6, padding: '0 2px', flex: '0 0 auto' } },
251
416
  ...selectors,
252
- ...(reason === undefined
253
- ? [createElement(HardwarePreview, {
254
- key: `preview:${revision}`,
255
- destination: active,
256
- artifact,
257
- projectPath,
258
- revision: revision,
259
- notice,
260
- })]
261
- : [createElement('p', { key: 'reason', style: MUTED, role: 'status', 'data-hardware-state': 'missing' }, reason)]),
262
- ...(application === undefined || kicadConfigured ? [] : [createElement('p', {
263
- key: 'unconfigured', style: MUTED,
264
- }, 'Configure KiCad in Settings → Hardware Engineering to enable previews and native open.')]),
265
- ...(artifact === undefined || reason !== undefined ? [] : [createElement('p', {
266
- key: 'identity', style: MUTED, 'data-hardware-identity': true,
267
- }, `Selected: ${artifact.path}`)]),
417
+ ...(noticeText === undefined
418
+ ? []
419
+ : [createElement('span', { key: 'notice', role: 'status', style: { ...MUTED, color: C.warn } }, noticeText)]),
420
+ ...(discovery?.issue === undefined || discovery.issue.code === 'selection-required'
421
+ ? []
422
+ : [createElement('span', { key: 'issue', role: 'status', style: MUTED },
423
+ issueText(discovery.issue, {
424
+ ...(discovery.cwd === undefined ? {} : { cwd: discovery.cwd }),
425
+ ...(discovery.projects === undefined ? {} : { count: discovery.projects.length }),
426
+ }))]),
427
+ )
428
+
429
+ return createElement(
430
+ 'div',
431
+ { style: PANEL_ROOT, 'data-hardware-destination': active },
432
+ createElement('style', null, PANEL_STYLE),
433
+ strip,
434
+ meta,
435
+ selectors.length === 0 && noticeText === undefined && (discovery?.issue === undefined || discovery.issue.code === 'selection-required')
436
+ ? null
437
+ : createElement('div', { style: { padding: '6px 10px 0' } }, banner),
438
+ createElement(
439
+ 'div',
440
+ { style: { ...BODY, overflow: active === 'order' || active === 'bom' ? 'auto' : 'hidden' } },
441
+ ...(reason === undefined
442
+ ? [createElement(HardwarePreview, {
443
+ key: `preview:${info.tab.id}:${String(navRevision)}:${active}:${artifact?.path ?? ''}`,
444
+ destination: active,
445
+ artifact,
446
+ ...(schematicPath === undefined ? {} : { schematicPath }),
447
+ ...(workspaceRoot === undefined ? {} : { workspaceRoot }),
448
+ ...(sessionId === undefined ? {} : { session: sessionId }),
449
+ revision: navRevision,
450
+ configured: kicadConfigured,
451
+ })]
452
+ : [createElement('div', {
453
+ key: 'reason',
454
+ style: cardStyle({ alignItems: 'center', justifyContent: 'center', flex: '1 1 0', gap: 6 }),
455
+ 'data-hardware-state': 'missing',
456
+ },
457
+ createElement('span', { style: pillStyle('warn') }, COPY.viewer.nothingToShow),
458
+ createElement('p', { role: 'status', style: { ...MUTED, textAlign: 'center', maxWidth: 320 } }, reason))]),
459
+ ),
268
460
  )
269
461
  }
270
462
 
271
- /** Settings section for the two CAD installation roots. */
272
- export function HardwareSettingsSection({ hooks }: { readonly hooks: HardwareInjected }): ReactNode {
273
- const form = hooks.useConfigForm?.()
274
- const emptySnapshot: { value?: HardwareInstallationConfig } = {}
463
+ /** Settings section: the two CAD installation roots, host-validated. */
464
+ export function HardwareSettingsSection(props: HardwareProps): ReactNode {
465
+ const { useStore, actions, configForm, saveInstallation, installations } = props
466
+ const installed = useStore(state => state.installations)
467
+ const form = configForm()
468
+ const empty = useMemo<{ value?: HardwareInstallationConfig }>(() => ({}), [])
275
469
  const snapshot = useSyncExternalStore<{ value?: HardwareInstallationConfig }>(
276
- form?.subscribe.bind(form) ?? (() => () => {}),
277
- form?.getSnapshot.bind(form) ?? (() => emptySnapshot),
278
- form?.getSnapshot.bind(form) ?? (() => emptySnapshot),
470
+ form === undefined ? () => () => {} : listener => form.subscribe(listener),
471
+ form === undefined ? () => empty : () => form.getSnapshot(),
472
+ form === undefined ? () => empty : () => form.getSnapshot(),
279
473
  )
280
- const value = snapshot.value
281
- const [kicadRoot, setKicadRoot] = useState(value?.kicadRoot ?? '')
282
- const [solidcraftRoot, setSolidcraftRoot] = useState(value?.solidcraftRoot ?? '')
474
+ const [kicadRoot, setKicadRoot] = useState(snapshot.value?.kicadRoot ?? '')
475
+ const [solidcraftRoot, setSolidcraftRoot] = useState(snapshot.value?.solidcraftRoot ?? '')
283
476
  const [message, setMessage] = useState('')
477
+ const [busy, setBusy] = useState<'kicad' | 'solidcraft' | undefined>()
478
+
479
+ useEffect(() => { setKicadRoot(snapshot.value?.kicadRoot ?? '') }, [snapshot.value?.kicadRoot])
480
+ useEffect(() => { setSolidcraftRoot(snapshot.value?.solidcraftRoot ?? '') }, [snapshot.value?.solidcraftRoot])
481
+
284
482
  useEffect(() => {
285
- setKicadRoot(value?.kicadRoot ?? '')
286
- setSolidcraftRoot(value?.solidcraftRoot ?? '')
287
- }, [value?.kicadRoot, value?.solidcraftRoot])
483
+ let live = true
484
+ installations()
485
+ .then((result) => { if (live) actions.setInstallations(result) })
486
+ .catch(() => { /* the wizard and viewer surface the same failure */ })
487
+ return () => { live = false }
488
+ }, [actions, installations])
288
489
 
289
490
  const save = async (application: 'kicad' | 'solidcraft', root: string): Promise<void> => {
491
+ setBusy(application)
290
492
  try {
291
- await hooks.saveInstallation(application, root)
292
- await hooks.fetchInstallations()
293
- setMessage(`${application === 'kicad' ? 'KiCad' : 'SolidCraft'} installation saved and validated.`)
493
+ await saveInstallation(application, root)
494
+ const refreshed = await installations()
495
+ actions.setInstallations(refreshed)
496
+ const state = application === 'kicad' ? refreshed.kicad : refreshed.solidcraft
497
+ const applicationName = application === 'kicad' ? 'KiCad' : 'SolidCraft'
498
+ setMessage(state?.configured === true
499
+ ? COPY.settings.savedAndValidated(applicationName)
500
+ : COPY.settings.savedButInvalid(applicationName, state?.error ?? COPY.settings.notDetected))
294
501
  } catch (error) {
295
- setMessage(String(error))
502
+ setMessage(messageOf(error))
503
+ } finally {
504
+ setBusy(undefined)
296
505
  }
297
506
  }
298
507
 
299
- return createElement(
508
+ const kicad = installed?.kicad
509
+ const solidcraft = installed?.solidcraft
510
+
511
+ const installationCard = (input: {
512
+ key: 'kicad' | 'solidcraft'
513
+ letter: string
514
+ color: string
515
+ title: string
516
+ blurb: string
517
+ value: string
518
+ placeholder: string
519
+ ok: boolean
520
+ status: string
521
+ detail?: string
522
+ onChange: (value: string) => void
523
+ }): ReactNode => createElement(
300
524
  'div',
301
- { style: { ...ROOT, height: 'auto' }, 'data-hardware-settings': true },
302
- createElement('h2', { style: TITLE }, 'Hardware Engineering'),
303
- createElement('label', { style: FIELD }, 'KiCad installation root or kicad-cli path',
304
- createElement('input', { style: INPUT, value: kicadRoot, onChange: event => setKicadRoot(event.currentTarget.value) }),
525
+ { key: input.key, style: cardStyle() },
526
+ createElement(
527
+ 'div',
528
+ { style: { ...ROW, justifyContent: 'space-between', gap: 8 } },
529
+ createElement(
530
+ 'div',
531
+ { style: { ...ROW, gap: 7 } },
532
+ createElement('span', {
533
+ style: {
534
+ width: 22, height: 22, borderRadius: R.sm, display: 'flex', alignItems: 'center',
535
+ justifyContent: 'center', fontSize: 10, fontWeight: 700, fontFamily: MONO,
536
+ color: input.color, background: `color-mix(in srgb, ${input.color} 18%, transparent)`,
537
+ border: `1px solid color-mix(in srgb, ${input.color} 40%, transparent)`,
538
+ },
539
+ }, input.letter),
540
+ createElement('span', { style: { fontSize: 12, fontWeight: 600 } }, input.title),
541
+ ),
542
+ createElement('span', { style: pillStyle(input.ok ? 'ok' : 'warn') }, input.status),
305
543
  ),
306
- createElement('button', { type: 'button', style: BUTTON, onClick: () => { void save('kicad', kicadRoot) } }, 'Validate / Save KiCad'),
307
- createElement('p', { style: MUTED },
308
- 'Used for PCB GLB export, native artifact opening, and the agent environment context.'),
309
- createElement('label', { style: FIELD }, 'SolidCraft installation root or executable path',
310
- createElement('input', { style: INPUT, value: solidcraftRoot, onChange: event => setSolidcraftRoot(event.currentTarget.value) }),
544
+ createElement('p', { style: MUTED }, input.blurb),
545
+ createElement('input', {
546
+ style: INPUT, value: input.value, placeholder: input.placeholder, spellCheck: false,
547
+ 'aria-label': COPY.settings.pathField(input.title),
548
+ onChange: (event: ChangeEvent<HTMLInputElement>) => input.onChange(event.currentTarget.value),
549
+ }),
550
+ createElement(
551
+ 'div',
552
+ { style: { ...ROW, justifyContent: 'space-between' } },
553
+ createElement('button', {
554
+ type: 'button', style: { ...buttonStyle('secondary'), ...disabled(busy !== undefined) },
555
+ disabled: busy !== undefined,
556
+ onClick: () => { void save(input.key, input.value) },
557
+ }, busy === input.key ? COPY.settings.validating : COPY.settings.validate),
558
+ input.detail === undefined
559
+ ? null
560
+ : createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10, maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, input.detail),
311
561
  ),
312
- createElement('button', { type: 'button', style: BUTTON, onClick: () => { void save('solidcraft', solidcraftRoot) } }, 'Validate / Save SolidCraft'),
313
- createElement('p', { style: MUTED },
314
- 'SolidCraft is agent environment context only in this POC; it has no native open action.'),
315
- ...(message === '' ? [] : [createElement('p', { style: MUTED, role: 'status' }, message)]),
562
+ )
563
+
564
+ return createElement(
565
+ 'div',
566
+ { style: { display: 'flex', flexDirection: 'column', gap: 10 }, 'data-hardware-settings': true },
567
+ createElement('h2', { style: { margin: 0, fontSize: 15, fontWeight: 600 } }, COPY.settings.title),
568
+ createElement('p', { style: MUTED }, COPY.settings.lead),
569
+ installationCard({
570
+ key: 'kicad',
571
+ letter: 'Ki',
572
+ color: C.info,
573
+ title: COPY.settings.kicadTitle,
574
+ blurb: COPY.settings.kicadBlurb,
575
+ value: kicadRoot,
576
+ placeholder: COPY.settings.kicadPlaceholder,
577
+ ok: kicad?.configured === true,
578
+ status: kicad?.configured ? `v${kicad.version ?? '?'}` : COPY.settings.notConfigured,
579
+ ...(kicad?.cli === undefined ? {} : { detail: kicad.cli }),
580
+ onChange: setKicadRoot,
581
+ }),
582
+ installationCard({
583
+ key: 'solidcraft',
584
+ letter: 'Sc',
585
+ color: C.warn,
586
+ title: COPY.settings.solidcraftTitle,
587
+ blurb: COPY.settings.solidcraftBlurb,
588
+ value: solidcraftRoot,
589
+ placeholder: COPY.settings.solidcraftPlaceholder,
590
+ ok: solidcraft?.configured === true,
591
+ status: solidcraft?.configured ? COPY.settings.configured : COPY.settings.notConfigured,
592
+ ...(solidcraft?.executable === undefined ? {} : { detail: solidcraft.executable }),
593
+ onChange: setSolidcraftRoot,
594
+ }),
595
+ ...(message === '' ? [] : [createElement('p', { role: 'status', style: { ...MUTED, color: C.text2 } }, message)]),
316
596
  )
317
597
  }