@huaqiu/dsh-hardware-ui 0.7.13 → 0.7.14

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,158 @@
1
+ /**
2
+ * Design tokens for the Hardware Engineering surfaces.
3
+ *
4
+ * Structure and geometry follow the product prototype (layered dark panels,
5
+ * 12px cards, 11px type, mono numerals, a red primary action); the colours are
6
+ * DSH alias tokens with the prototype values as fallbacks, so the panel stays
7
+ * legible in the light theme instead of hard-coding a dark palette.
8
+ */
9
+ import type { CSSProperties } from 'react'
10
+
11
+ export const MONO = 'ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, monospace'
12
+
13
+ export const C = {
14
+ base: 'var(--dsw-alias-bg-base, #161618)',
15
+ panel: 'var(--dsw-alias-bg-layer-1, #1d1d20)',
16
+ card: 'var(--dsw-alias-bg-layer-2, #202024)',
17
+ raised: 'var(--dsw-alias-bg-layer-3, #2a2a2e)',
18
+ border: 'var(--dsw-alias-border-l2, rgba(127,127,127,0.24))',
19
+ borderSoft: 'var(--dsw-alias-border-l1, rgba(127,127,127,0.14))',
20
+ text: 'var(--dsw-alias-label-primary, #ececee)',
21
+ text2: 'var(--dsw-alias-label-secondary, #a1a1aa)',
22
+ text3: 'var(--dsw-alias-label-tertiary, #71717a)',
23
+ accent: '#e1251b',
24
+ accentHover: '#c41e15',
25
+ accentSoft: 'rgba(225, 37, 27, 0.15)',
26
+ ok: '#34d399',
27
+ okSoft: 'rgba(52, 211, 153, 0.14)',
28
+ warn: '#fbbf24',
29
+ warnSoft: 'rgba(251, 191, 36, 0.14)',
30
+ info: '#38bdf8',
31
+ infoSoft: 'rgba(56, 189, 248, 0.14)',
32
+ violet: '#a78bfa',
33
+ pink: '#f472b6',
34
+ } as const
35
+
36
+ export const R = { sm: 6, md: 8, lg: 12, pill: 999 } as const
37
+
38
+ export const DOT_COLORS = {
39
+ schematic: C.info,
40
+ pcb: C.ok,
41
+ bom: C.pink,
42
+ '3d': C.warn,
43
+ order: C.accent,
44
+ } as const
45
+
46
+ export function cardStyle(extra?: CSSProperties): CSSProperties {
47
+ return {
48
+ border: `1px solid ${C.border}`,
49
+ borderRadius: R.lg,
50
+ background: C.card,
51
+ padding: 12,
52
+ display: 'flex',
53
+ flexDirection: 'column',
54
+ gap: 8,
55
+ minWidth: 0,
56
+ ...extra,
57
+ }
58
+ }
59
+
60
+ export const SECTION_TITLE: CSSProperties = {
61
+ margin: 0,
62
+ fontSize: 11,
63
+ fontWeight: 600,
64
+ letterSpacing: 0.2,
65
+ color: C.text2,
66
+ textTransform: 'uppercase',
67
+ }
68
+
69
+ export const MUTED: CSSProperties = { margin: 0, fontSize: 11, lineHeight: 1.55, color: C.text3 }
70
+
71
+ export const MONO_TEXT: CSSProperties = { fontFamily: MONO, fontVariantNumeric: 'tabular-nums' }
72
+
73
+ export function dotStyle(color: string, size = 7): CSSProperties {
74
+ return { width: size, height: size, borderRadius: R.pill, background: color, flex: '0 0 auto' }
75
+ }
76
+
77
+ export function pillStyle(tone: 'ok' | 'warn' | 'info' | 'muted' | 'accent' = 'muted', extra?: CSSProperties): CSSProperties {
78
+ const tones = {
79
+ ok: { color: C.ok, background: C.okSoft, border: 'rgba(52, 211, 153, 0.28)' },
80
+ warn: { color: C.warn, background: C.warnSoft, border: 'rgba(251, 191, 36, 0.28)' },
81
+ info: { color: C.info, background: C.infoSoft, border: 'rgba(56, 189, 248, 0.28)' },
82
+ accent: { color: C.accent, background: C.accentSoft, border: 'rgba(225, 37, 27, 0.32)' },
83
+ muted: { color: C.text3, background: 'transparent', border: C.border },
84
+ } as const
85
+ const tone_ = tones[tone]
86
+ return {
87
+ display: 'inline-flex',
88
+ alignItems: 'center',
89
+ gap: 4,
90
+ padding: '1px 7px',
91
+ borderRadius: R.pill,
92
+ border: `1px solid ${tone_.border}`,
93
+ background: tone_.background,
94
+ color: tone_.color,
95
+ fontSize: 10,
96
+ lineHeight: 1.6,
97
+ whiteSpace: 'nowrap',
98
+ fontFamily: MONO,
99
+ ...extra,
100
+ }
101
+ }
102
+
103
+ export function buttonStyle(kind: 'primary' | 'secondary' | 'quiet' = 'secondary', extra?: CSSProperties): CSSProperties {
104
+ const base: CSSProperties = {
105
+ display: 'inline-flex',
106
+ alignItems: 'center',
107
+ justifyContent: 'center',
108
+ gap: 6,
109
+ padding: '5px 10px',
110
+ borderRadius: R.md,
111
+ font: 'inherit',
112
+ fontSize: 11,
113
+ fontWeight: 500,
114
+ lineHeight: 1.4,
115
+ cursor: 'pointer',
116
+ whiteSpace: 'nowrap',
117
+ transition: 'background 120ms ease, border-color 120ms ease, opacity 120ms ease',
118
+ }
119
+ if (kind === 'primary') {
120
+ return {
121
+ ...base,
122
+ border: '1px solid transparent',
123
+ background: C.accent,
124
+ color: '#fff',
125
+ boxShadow: '0 6px 16px rgba(225, 37, 27, 0.22)',
126
+ ...extra,
127
+ }
128
+ }
129
+ if (kind === 'quiet') {
130
+ return { ...base, border: '1px solid transparent', background: 'transparent', color: C.text2, ...extra }
131
+ }
132
+ return {
133
+ ...base,
134
+ border: `1px solid ${C.border}`,
135
+ background: C.raised,
136
+ color: C.text,
137
+ ...extra,
138
+ }
139
+ }
140
+
141
+ export const INPUT: CSSProperties = {
142
+ width: '100%',
143
+ boxSizing: 'border-box',
144
+ padding: '5px 8px',
145
+ borderRadius: R.md,
146
+ border: `1px solid ${C.border}`,
147
+ background: C.base,
148
+ color: C.text,
149
+ font: 'inherit',
150
+ fontSize: 11,
151
+ fontFamily: MONO,
152
+ }
153
+
154
+ export const SELECT: CSSProperties = { ...INPUT, cursor: 'pointer' }
155
+
156
+ export function disabled(active: boolean): CSSProperties {
157
+ return active ? { opacity: 0.45, cursor: 'not-allowed', boxShadow: 'none' } : {}
158
+ }
@@ -22,16 +22,17 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
22
22
  return body as T
23
23
  }
24
24
 
25
- function query(cwd: string | undefined, project?: string): string {
25
+ function query(cwd: string | undefined, project?: string, session?: string): string {
26
26
  const params = new URLSearchParams()
27
27
  if (cwd !== undefined && cwd !== '') params.set('cwd', cwd)
28
28
  if (project !== undefined && project !== '') params.set('project', project)
29
+ if (session !== undefined && session !== '') params.set('session', session)
29
30
  const text = params.toString()
30
31
  return text === '' ? '' : `?${text}`
31
32
  }
32
33
 
33
- export async function loadProjects(cwd?: string, project?: string): Promise<DiscoveryInfo> {
34
- const body = await request<DiscoveryInfo>(`/projects${query(cwd, project)}`)
34
+ export async function loadProjects(cwd?: string, project?: string, session?: string): Promise<DiscoveryInfo> {
35
+ const body = await request<DiscoveryInfo>(`/projects${query(cwd, project, session)}`)
35
36
  const fallback: DiscoveryInfo = {
36
37
  cwd: body.cwd,
37
38
  projects: Array.isArray(body.projects) ? body.projects : [],
@@ -54,6 +55,7 @@ export async function openArtifact(requestBody: {
54
55
  artifactPath: string
55
56
  kind: string
56
57
  projectPath?: string
58
+ session?: string
57
59
  }): Promise<void> {
58
60
  await request('/open', {
59
61
  method: 'POST',
@@ -74,12 +76,21 @@ export interface ArtifactSource {
74
76
 
75
77
  export async function loadArtifactSource(
76
78
  artifactPath: string,
77
- signal?: AbortSignal,
78
- expectedRevision?: string,
79
+ options: {
80
+ readonly signal?: AbortSignal
81
+ readonly expectedRevision?: string
82
+ readonly session?: string
83
+ /** Workspace root the panel already discovered; the host adds it to the session's own. */
84
+ readonly cwd?: string
85
+ } = {},
79
86
  ): Promise<ArtifactSource> {
80
87
  const params = new URLSearchParams({ path: artifactPath })
81
- if (expectedRevision !== undefined && expectedRevision !== '') params.set('revision', expectedRevision)
82
- return request<ArtifactSource>(`/source?${params.toString()}`, { signal })
88
+ if (options.expectedRevision !== undefined && options.expectedRevision !== '') {
89
+ params.set('revision', options.expectedRevision)
90
+ }
91
+ if (options.session !== undefined && options.session !== '') params.set('session', options.session)
92
+ if (options.cwd !== undefined && options.cwd !== '') params.set('cwd', options.cwd)
93
+ return request<ArtifactSource>(`/source?${params.toString()}`, options.signal === undefined ? {} : { signal: options.signal })
83
94
  }
84
95
 
85
96
  /** Generated PCB GLB for one authorized `.kicad_pcb`. */
@@ -111,12 +122,19 @@ export interface BomProjection {
111
122
  readonly source: string
112
123
  }
113
124
 
114
- export async function loadBom(artifactPath: string, signal?: AbortSignal): Promise<BomProjection> {
125
+ export async function loadBom(
126
+ artifactPath: string,
127
+ options: { readonly session?: string; readonly cwd?: string; readonly signal?: AbortSignal } = {},
128
+ ): Promise<BomProjection> {
115
129
  return request<BomProjection>('/bom', {
116
130
  method: 'POST',
117
131
  headers: { 'content-type': 'application/json' },
118
- body: JSON.stringify({ path: artifactPath }),
119
- signal,
132
+ body: JSON.stringify({
133
+ path: artifactPath,
134
+ ...(options.session === undefined ? {} : { session: options.session }),
135
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
136
+ }),
137
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
120
138
  })
121
139
  }
122
140
 
@@ -125,11 +143,133 @@ export async function prepareBoardGlb(
125
143
  artifactPath: string,
126
144
  cwd?: string,
127
145
  signal?: AbortSignal,
146
+ session?: string,
128
147
  ): Promise<GlbArtifact & { readonly url: string }> {
129
148
  return request<GlbArtifact & { readonly url: string }>('/glb', {
130
149
  method: 'POST',
131
150
  headers: { 'content-type': 'application/json' },
132
- body: JSON.stringify({ path: artifactPath, ...(cwd === undefined ? {} : { cwd }) }),
133
- signal,
151
+ body: JSON.stringify({
152
+ path: artifactPath,
153
+ ...(cwd === undefined ? {} : { cwd }),
154
+ ...(session === undefined ? {} : { session }),
155
+ }),
156
+ ...(signal === undefined ? {} : { signal }),
157
+ })
158
+ }
159
+
160
+ /** What the Order destination may do, as the host sees it. */
161
+ export interface OrderConfigInfo {
162
+ readonly configured: boolean
163
+ readonly baseUrl: string
164
+ /** A signed-in Huaqiu session or an explicitly configured token. */
165
+ readonly hasToken: boolean
166
+ readonly provider: string
167
+ }
168
+
169
+ export async function loadOrderConfig(): Promise<OrderConfigInfo> {
170
+ return request<OrderConfigInfo>('/order')
171
+ }
172
+
173
+ export interface BoardFactsInfo {
174
+ readonly layers: number
175
+ readonly widthMm: number
176
+ readonly heightMm: number
177
+ readonly thicknessMm: number
178
+ readonly minTrackMm?: number
179
+ readonly minViaDrillMm?: number
180
+ readonly outerOz?: number
181
+ readonly innerOz?: number
182
+ }
183
+
184
+ export interface PackageInfo {
185
+ readonly zipName: string
186
+ readonly zipBytes: number
187
+ readonly files: readonly { readonly name: string; readonly bytes: number }[]
188
+ }
189
+
190
+ /** A fabrication package prepared on the host; nothing has been uploaded. */
191
+ export interface FabricationProjection {
192
+ readonly boardPath: string
193
+ readonly revision: string
194
+ readonly generatedAt: string
195
+ readonly facts: BoardFactsInfo
196
+ readonly archive: PackageInfo
197
+ readonly assembly?: {
198
+ readonly positions: number
199
+ readonly bomLines: number
200
+ readonly positionsBytes: number
201
+ readonly bomBytes: number
202
+ }
203
+ }
204
+
205
+ export async function prepareFabrication(
206
+ boardPath: string,
207
+ schematicPath?: string,
208
+ cwd?: string,
209
+ signal?: AbortSignal,
210
+ session?: string,
211
+ ): Promise<FabricationProjection> {
212
+ return request<FabricationProjection>('/fabrication', {
213
+ method: 'POST',
214
+ headers: { 'content-type': 'application/json' },
215
+ body: JSON.stringify({
216
+ path: boardPath,
217
+ ...(schematicPath === undefined ? {} : { schematic: schematicPath }),
218
+ ...(cwd === undefined ? {} : { cwd }),
219
+ ...(session === undefined ? {} : { session }),
220
+ }),
221
+ ...(signal === undefined ? {} : { signal }),
222
+ })
223
+ }
224
+
225
+ /** One placed order, as returned by the host after the backend answered. */
226
+ export interface PlacedOrder {
227
+ readonly kind: 'pcb' | 'smt'
228
+ /** The exact URL KiCad's own action loads in its order webview. */
229
+ readonly orderUrl: string
230
+ /** The backend's raw URL, before KiCad's query parameters were added. */
231
+ readonly responseUrl: string
232
+ readonly launched: boolean
233
+ readonly launcher?: string
234
+ readonly status: 'launched' | 'ready'
235
+ readonly message: string
236
+ readonly endpoint: string
237
+ readonly archive: PackageInfo
238
+ readonly assembly?: FabricationProjection['assembly']
239
+ }
240
+
241
+ /**
242
+ * Submit one order. `confirm` is what the host requires; the panel sets it only
243
+ * after the user confirms the upload in the dialog. The host opens the order
244
+ * page in the default browser unless `launch` is false.
245
+ */
246
+ export async function placeOrder(
247
+ kind: 'pcb' | 'smt',
248
+ requestBody: {
249
+ path: string
250
+ schematic?: string
251
+ /** Workspace root, never the project file; the host authorizes against it. */
252
+ cwd?: string
253
+ session?: string
254
+ quantity?: number
255
+ confirm: boolean
256
+ launch?: boolean
257
+ },
258
+ signal?: AbortSignal,
259
+ ): Promise<PlacedOrder> {
260
+ return request<PlacedOrder>(`/order/${kind}`, {
261
+ method: 'POST',
262
+ headers: { 'content-type': 'application/json' },
263
+ body: JSON.stringify(requestBody),
264
+ ...(signal === undefined ? {} : { signal }),
265
+ })
266
+ }
267
+
268
+ /** Hand an already-created order page back to the OS default browser. */
269
+ export async function openOrderUrl(url: string): Promise<{ readonly launched: boolean; readonly command: string }> {
270
+ return request<{ readonly launched: boolean; readonly command: string }>('/order/open', {
271
+ method: 'POST',
272
+ headers: { 'content-type': 'application/json' },
273
+ body: JSON.stringify({ url }),
134
274
  })
135
275
  }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * First-run setup wizard.
3
+ *
4
+ * Rendered from the root navigation seat so it can appear before any session
5
+ * exists. It only guides the user towards a local KiCad/SolidCraft executable:
6
+ * everything on it is skippable, and completion is recorded in the host-backed
7
+ * product config (`onboardingComplete`) rather than in browser storage.
8
+ *
9
+ * It is a full-screen modal, so it must never mount on a guess. Both facts it
10
+ * depends on arrive asynchronously — the host's synced config (is onboarding
11
+ * recorded?) and one local install probe (is KiCad already usable?) — and
12
+ * {@link wizardPhase} refuses to decide until they are known. Deciding on the
13
+ * initial `loading`/`undefined` values is what made the wizard flash on first
14
+ * launch and on every browser refresh: it mounted, then unmounted a frame later
15
+ * when the real answer landed.
16
+ */
17
+ import {
18
+ createElement, useEffect, useMemo, useState, useSyncExternalStore,
19
+ type CSSProperties, type ReactNode,
20
+ } from 'react'
21
+ import type { HardwareInstallationConfig, InstallationsInfo } from './model.js'
22
+ import type { HardwareProps } from './components.js'
23
+ import { buttonStyle, C, dotStyle, INPUT, MUTED, MONO_TEXT, pillStyle, R } from './theme.js'
24
+
25
+ const BACKDROP: CSSProperties = {
26
+ position: 'fixed', inset: 0, zIndex: 60, display: 'flex', alignItems: 'center', justifyContent: 'center',
27
+ padding: 16, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(3px)',
28
+ }
29
+ const PANEL: CSSProperties = {
30
+ width: 'min(520px, 100%)', maxHeight: '85vh', overflow: 'auto', borderRadius: R.lg, padding: 16,
31
+ display: 'flex', flexDirection: 'column', gap: 12,
32
+ color: C.text,
33
+ background: C.panel,
34
+ border: `1px solid ${C.border}`,
35
+ boxShadow: '0 28px 70px rgba(0,0,0,0.55)',
36
+ fontSize: 12, lineHeight: 1.5,
37
+ }
38
+ const TITLE: CSSProperties = { margin: 0, fontSize: 15, fontWeight: 600, letterSpacing: 0.1 }
39
+ const LEAD: CSSProperties = { margin: 0, fontSize: 11.5, lineHeight: 1.6, color: C.text2 }
40
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }
41
+ const SPREAD: CSSProperties = { ...ROW, justifyContent: 'space-between' }
42
+ const STEP_LABEL: CSSProperties = { fontSize: 10, color: C.text3 }
43
+ const BRAND_MARK: CSSProperties = {
44
+ width: 26, height: 26, borderRadius: R.sm, display: 'flex', alignItems: 'center', justifyContent: 'center',
45
+ fontSize: 11, fontWeight: 700, color: '#fff', background: C.accent,
46
+ boxShadow: '0 4px 14px rgba(225,27,27,0.35)', flex: '0 0 auto',
47
+ }
48
+ const FIELD_CARD: CSSProperties = {
49
+ border: `1px solid ${C.borderSoft}`, borderRadius: R.md, background: C.base, padding: 10,
50
+ display: 'flex', flexDirection: 'column', gap: 6,
51
+ }
52
+
53
+ const STEPS = ['Welcome', 'KiCad', 'SolidCraft'] as const
54
+
55
+ /**
56
+ * Dismissal remembered for the life of this client bundle, not one mount.
57
+ *
58
+ * The navigation seat is remounted by the framework (a conversation switch, a
59
+ * slot refresh), so component state alone lets a just-closed wizard come back
60
+ * for a frame while the host config write is still in flight. A browser refresh
61
+ * reloads the bundle, so the host config stays the only cross-session source of
62
+ * truth and this cannot outlive the tab.
63
+ */
64
+ let dismissedInClient = false
65
+
66
+ /**
67
+ * How the wizard resolves for one render.
68
+ *
69
+ * `waiting` and `no-form` render nothing, exactly like `completed`; they exist
70
+ * so the reason a modal is absent is testable instead of being implicit in an
71
+ * `if` chain.
72
+ */
73
+ export type WizardPhase =
74
+ /** No host config form: there is nowhere to record completion. */
75
+ | 'no-form'
76
+ /** Config sync or the install probe has not answered yet. */
77
+ | 'waiting'
78
+ /** The host already recorded completion or a skip. */
79
+ | 'completed'
80
+ /** KiCad validates now, so first-run setup has nothing left to ask. */
81
+ | 'configured'
82
+ /** Closed in this browser session. */
83
+ | 'dismissed'
84
+ /** Render it. */
85
+ | 'open'
86
+
87
+ /**
88
+ * Decide whether the wizard may mount, without guessing.
89
+ *
90
+ * Order matters: a completed onboarding needs no probe, so it must not wait on
91
+ * one; a `loading` config must not fall through to "not completed", which is the
92
+ * flash this function exists to prevent.
93
+ */
94
+ export function wizardPhase(input: {
95
+ readonly hasForm: boolean
96
+ /** `ConfigFormSnapshot.status`; `loading` until the host answered once. */
97
+ readonly status?: string
98
+ readonly onboardingComplete: boolean
99
+ /** KiCad readiness; `undefined` while the probe is still in flight. */
100
+ readonly kicadConfigured?: boolean | undefined
101
+ readonly dismissed: boolean
102
+ }): WizardPhase {
103
+ if (!input.hasForm) return 'no-form'
104
+ if (input.dismissed) return 'dismissed'
105
+ if (input.status === 'loading') return 'waiting'
106
+ if (input.onboardingComplete) return 'completed'
107
+ if (input.kicadConfigured === undefined) return 'waiting'
108
+ return input.kicadConfigured ? 'configured' : 'open'
109
+ }
110
+
111
+ export function OnboardingWizard(props: HardwareProps): ReactNode {
112
+ const { actions, configForm, saveInstallation, installations, useStore } = props
113
+ const installed = useStore(state => state.installations)
114
+ const form = configForm()
115
+ const empty = useMemo<{ value?: HardwareInstallationConfig; status?: string }>(() => ({}), [])
116
+ const snapshot = useSyncExternalStore<{ value?: HardwareInstallationConfig; status?: string }>(
117
+ form === undefined ? () => () => {} : listener => form.subscribe(listener),
118
+ form === undefined ? () => empty : () => form.getSnapshot(),
119
+ form === undefined ? () => empty : () => form.getSnapshot(),
120
+ )
121
+
122
+ const [step, setStep] = useState(0)
123
+ const [closed, setClosed] = useState(dismissedInClient)
124
+ const [kicadRoot, setKicadRoot] = useState('')
125
+ const [solidcraftRoot, setSolidcraftRoot] = useState('')
126
+ const [message, setMessage] = useState('')
127
+ const [busy, setBusy] = useState(false)
128
+ /**
129
+ * This seat's own install probe: `undefined` while in flight, `null` when it
130
+ * failed (the wizard stays usable, paths can be typed). A result another seat
131
+ * already wrote to the store counts too, so a mounted viewer does not make the
132
+ * navigation row probe twice before deciding.
133
+ */
134
+ const [probe, setProbe] = useState<InstallationsInfo | null>()
135
+
136
+ useEffect(() => {
137
+ let live = true
138
+ installations()
139
+ .then((result) => {
140
+ if (!live) return
141
+ setProbe(result)
142
+ actions.setInstallations(result)
143
+ })
144
+ .catch(() => { if (live) setProbe(null) })
145
+ return () => { live = false }
146
+ }, [actions, installations])
147
+
148
+ const facts = probe ?? installed
149
+ const phase = wizardPhase({
150
+ hasForm: form !== undefined,
151
+ status: snapshot.status,
152
+ onboardingComplete: snapshot.value?.onboardingComplete === true,
153
+ kicadConfigured: probe === undefined && installed === undefined
154
+ ? undefined
155
+ : facts?.kicad?.configured === true,
156
+ dismissed: closed,
157
+ })
158
+
159
+ useEffect(() => {
160
+ if (kicadRoot !== '' || facts?.kicad?.root === undefined) return
161
+ setKicadRoot(facts.kicad.root)
162
+ }, [facts?.kicad?.root, kicadRoot])
163
+
164
+ // `form === undefined` is already `no-form`; repeating it here is what lets
165
+ // TypeScript narrow it for the handlers below.
166
+ if (form === undefined || phase !== 'open') return null
167
+
168
+ const complete = async (): Promise<void> => {
169
+ // Close first: the write is a host round-trip, and the user's click must
170
+ // dismiss the modal whether or not the host accepts it.
171
+ dismissedInClient = true
172
+ setClosed(true)
173
+ try {
174
+ await form.set('onboardingComplete', true)
175
+ } catch {
176
+ // A refused host write must not trap the user in the wizard.
177
+ }
178
+ }
179
+
180
+ const finish = async (): Promise<void> => {
181
+ setBusy(true)
182
+ try {
183
+ if (kicadRoot !== '') await saveInstallation('kicad', kicadRoot)
184
+ if (solidcraftRoot !== '') await saveInstallation('solidcraft', solidcraftRoot)
185
+ } catch (error) {
186
+ setMessage(String(error))
187
+ setBusy(false)
188
+ return
189
+ }
190
+ // Record completion before the probe refresh: a valid KiCad root makes this
191
+ // wizard unmount on the next render, and a write issued after that would
192
+ // rely on an unmounted component finishing its async tail.
193
+ await complete()
194
+ try {
195
+ actions.setInstallations(await installations())
196
+ } catch {
197
+ // The viewer re-probes on its own; nothing here depends on the answer.
198
+ }
199
+ }
200
+
201
+ const next = async (): Promise<void> => {
202
+ if (step < STEPS.length - 1) {
203
+ setStep(step + 1)
204
+ return
205
+ }
206
+ await finish()
207
+ }
208
+
209
+ const stepBody = (): ReactNode => {
210
+ if (step === 0) {
211
+ return createElement(
212
+ 'div',
213
+ { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
214
+ createElement(
215
+ 'div',
216
+ { style: { ...ROW, gap: 10 } },
217
+ createElement('span', { style: BRAND_MARK }, 'H!'),
218
+ createElement(
219
+ 'div',
220
+ { style: { display: 'flex', flexDirection: 'column', gap: 1 } },
221
+ createElement('h2', { style: TITLE }, 'Set up your hardware toolchain'),
222
+ createElement('span', { style: STEP_LABEL }, 'one-time · skippable'),
223
+ ),
224
+ ),
225
+ createElement('p', { style: LEAD },
226
+ 'Hardware Engineering previews KiCad projects, exports PCB 3D models, packages fabrication files and opens native files. Point it at your local installations once.'),
227
+ createElement('div',
228
+ { style: FIELD_CARD },
229
+ createElement('span', { style: { fontSize: 11, fontWeight: 600 } }, 'What it uses'),
230
+ createElement('p', { style: { ...MUTED, color: C.text3 } },
231
+ 'kicad-cli for previews, BOM, GLB and gerber/drill packaging. SolidCraft is shared with the agent as environment context only.'),
232
+ ),
233
+ createElement('p', { style: { ...MUTED, color: C.text3 } },
234
+ 'Only local executables are used. Nothing is uploaded, and nothing is installed for you.'),
235
+ )
236
+ }
237
+ if (step === 1) {
238
+ return createElement(
239
+ 'div',
240
+ { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
241
+ createElement(
242
+ 'div',
243
+ { style: SPREAD },
244
+ createElement('h2', { style: TITLE }, 'KiCad installation'),
245
+ createElement('span', { style: facts?.kicad?.configured === true ? pillStyle('ok') : pillStyle('muted') },
246
+ facts?.kicad?.configured === true ? `v${facts.kicad.version ?? '?'}` : 'optional'),
247
+ ),
248
+ createElement('p', { style: LEAD },
249
+ 'Enter a KiCad installation folder or a kicad-cli path. It is used for .kicad_sch / .kicad_pcb previews, PCB GLB export, fabrication packaging, and “Open in KiCad”.'),
250
+ createElement('input', {
251
+ style: INPUT, value: kicadRoot, autoFocus: true, spellCheck: false,
252
+ placeholder: 'C:\\Program Files\\KiCad\\8.0\\ or /usr/bin/kicad-cli',
253
+ onChange: event => setKicadRoot(event.currentTarget.value),
254
+ }),
255
+ createElement('p', { style: { ...MUTED, color: C.text3 } },
256
+ 'Leave it empty to skip. You can configure it later in Settings → Hardware Engineering.'),
257
+ )
258
+ }
259
+ return createElement(
260
+ 'div',
261
+ { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
262
+ createElement(
263
+ 'div',
264
+ { style: SPREAD },
265
+ createElement('h2', { style: TITLE }, 'SolidCraft installation'),
266
+ createElement('span', { style: pillStyle('muted') }, 'optional'),
267
+ ),
268
+ createElement('p', { style: LEAD },
269
+ 'SolidCraft is shared with the agent as environment context only in this POC — no native launch, no mechanical preview.'),
270
+ createElement('input', {
271
+ style: INPUT, value: solidcraftRoot, autoFocus: true, spellCheck: false,
272
+ placeholder: 'C:\\Program Files\\SolidCraft\\bin\\SolidCraft.exe',
273
+ onChange: event => setSolidcraftRoot(event.currentTarget.value),
274
+ }),
275
+ )
276
+ }
277
+
278
+ return createElement(
279
+ 'div',
280
+ { style: BACKDROP, role: 'dialog', 'aria-modal': true, 'aria-label': 'Hardware Engineering setup', 'data-hardware-wizard': true },
281
+ createElement(
282
+ 'div',
283
+ { style: PANEL },
284
+ createElement(
285
+ 'div',
286
+ { style: SPREAD },
287
+ createElement(
288
+ 'div',
289
+ { style: { ...ROW, gap: 6 } },
290
+ ...STEPS.map((label, index) => createElement('span', {
291
+ key: label,
292
+ style: { ...dotStyle(index === step ? C.accent : index < step ? C.ok : C.text3, 6) },
293
+ title: label,
294
+ })),
295
+ createElement('span', { style: { ...STEP_LABEL, ...MONO_TEXT } }, `${String(step + 1)}/${String(STEPS.length)} · ${STEPS[step]}`),
296
+ ),
297
+ createElement('button', {
298
+ type: 'button', style: buttonStyle('quiet', { fontSize: 10.5 }),
299
+ onClick: () => { void complete() },
300
+ }, 'Skip setup'),
301
+ ),
302
+ stepBody(),
303
+ ...(message === '' ? [] : [createElement('p', { key: 'msg', style: { ...MUTED, color: C.text2 }, role: 'status' }, message)]),
304
+ createElement(
305
+ 'div',
306
+ { style: { ...SPREAD, paddingTop: 6, borderTop: `1px solid ${C.borderSoft}` } },
307
+ createElement('span', { style: { ...MUTED, color: C.text3, fontSize: 10 } },
308
+ 'You can change this any time in Settings → Hardware Engineering.'),
309
+ createElement(
310
+ 'span',
311
+ { style: ROW },
312
+ step > 0
313
+ ? createElement('button', {
314
+ type: 'button', style: buttonStyle('secondary'),
315
+ onClick: () => { setStep(step - 1) },
316
+ }, 'Back')
317
+ : null,
318
+ createElement('button', {
319
+ type: 'button', style: buttonStyle('primary'), disabled: busy,
320
+ onClick: () => { void next() },
321
+ }, busy ? 'Saving…' : step === STEPS.length - 1 ? 'Finish' : 'Next'),
322
+ ),
323
+ ),
324
+ ),
325
+ )
326
+ }