@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,322 @@
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 { COPY } from './copy.js'
24
+ import { messageOf } from './transport.js'
25
+ import { buttonStyle, C, dotStyle, INPUT, MUTED, MONO_TEXT, pillStyle, R } from './theme.js'
26
+
27
+ const BACKDROP: CSSProperties = {
28
+ position: 'fixed', inset: 0, zIndex: 60, display: 'flex', alignItems: 'center', justifyContent: 'center',
29
+ padding: 16, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(3px)',
30
+ }
31
+ const PANEL: CSSProperties = {
32
+ width: 'min(520px, 100%)', maxHeight: '85vh', overflow: 'auto', borderRadius: R.lg, padding: 16,
33
+ display: 'flex', flexDirection: 'column', gap: 12,
34
+ color: C.text,
35
+ background: C.panel,
36
+ border: `1px solid ${C.border}`,
37
+ boxShadow: '0 28px 70px rgba(0,0,0,0.55)',
38
+ fontSize: 12, lineHeight: 1.5,
39
+ }
40
+ const TITLE: CSSProperties = { margin: 0, fontSize: 15, fontWeight: 600, letterSpacing: 0.1 }
41
+ const LEAD: CSSProperties = { margin: 0, fontSize: 11.5, lineHeight: 1.6, color: C.text2 }
42
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }
43
+ const SPREAD: CSSProperties = { ...ROW, justifyContent: 'space-between' }
44
+ const STEP_LABEL: CSSProperties = { fontSize: 10, color: C.text3 }
45
+ const BRAND_MARK: CSSProperties = {
46
+ width: 26, height: 26, borderRadius: R.sm, display: 'flex', alignItems: 'center', justifyContent: 'center',
47
+ fontSize: 11, fontWeight: 700, color: '#fff', background: C.accent,
48
+ boxShadow: '0 4px 14px rgba(225,27,27,0.35)', flex: '0 0 auto',
49
+ }
50
+ const FIELD_CARD: CSSProperties = {
51
+ border: `1px solid ${C.borderSoft}`, borderRadius: R.md, background: C.base, padding: 10,
52
+ display: 'flex', flexDirection: 'column', gap: 6,
53
+ }
54
+
55
+ /** Step titles, in order (also the dot-strip tooltips and the counter label). */
56
+ const STEPS = COPY.wizard.steps
57
+
58
+ /**
59
+ * Dismissal remembered for the life of this client bundle, not one mount.
60
+ *
61
+ * The navigation seat is remounted by the framework (a conversation switch, a
62
+ * slot refresh), so component state alone lets a just-closed wizard come back
63
+ * for a frame while the host config write is still in flight. A browser refresh
64
+ * reloads the bundle, so the host config stays the only cross-session source of
65
+ * truth and this cannot outlive the tab.
66
+ */
67
+ let dismissedInClient = false
68
+
69
+ /**
70
+ * How the wizard resolves for one render.
71
+ *
72
+ * `waiting` and `no-form` render nothing, exactly like `completed`; they exist
73
+ * so the reason a modal is absent is testable instead of being implicit in an
74
+ * `if` chain.
75
+ */
76
+ export type WizardPhase =
77
+ /** No host config form: there is nowhere to record completion. */
78
+ | 'no-form'
79
+ /** Config sync or the install probe has not answered yet. */
80
+ | 'waiting'
81
+ /** The host already recorded completion or a skip. */
82
+ | 'completed'
83
+ /** KiCad validates now, so first-run setup has nothing left to ask. */
84
+ | 'configured'
85
+ /** Closed in this browser session. */
86
+ | 'dismissed'
87
+ /** Render it. */
88
+ | 'open'
89
+
90
+ /**
91
+ * Decide whether the wizard may mount, without guessing.
92
+ *
93
+ * Order matters: a completed onboarding needs no probe, so it must not wait on
94
+ * one; a `loading` config must not fall through to "not completed", which is the
95
+ * flash this function exists to prevent.
96
+ */
97
+ export function wizardPhase(input: {
98
+ readonly hasForm: boolean
99
+ /** `ConfigFormSnapshot.status`; `loading` until the host answered once. */
100
+ readonly status?: string
101
+ readonly onboardingComplete: boolean
102
+ /** KiCad readiness; `undefined` while the probe is still in flight. */
103
+ readonly kicadConfigured?: boolean | undefined
104
+ readonly dismissed: boolean
105
+ }): WizardPhase {
106
+ if (!input.hasForm) return 'no-form'
107
+ if (input.dismissed) return 'dismissed'
108
+ if (input.status === 'loading') return 'waiting'
109
+ if (input.onboardingComplete) return 'completed'
110
+ if (input.kicadConfigured === undefined) return 'waiting'
111
+ return input.kicadConfigured ? 'configured' : 'open'
112
+ }
113
+
114
+ export function OnboardingWizard(props: HardwareProps): ReactNode {
115
+ const { actions, configForm, saveInstallation, installations, useStore } = props
116
+ const installed = useStore(state => state.installations)
117
+ const form = configForm()
118
+ const empty = useMemo<{ value?: HardwareInstallationConfig; status?: string }>(() => ({}), [])
119
+ const snapshot = useSyncExternalStore<{ value?: HardwareInstallationConfig; status?: string }>(
120
+ form === undefined ? () => () => {} : listener => form.subscribe(listener),
121
+ form === undefined ? () => empty : () => form.getSnapshot(),
122
+ form === undefined ? () => empty : () => form.getSnapshot(),
123
+ )
124
+
125
+ const [step, setStep] = useState(0)
126
+ const [closed, setClosed] = useState(dismissedInClient)
127
+ const [kicadRoot, setKicadRoot] = useState('')
128
+ const [solidcraftRoot, setSolidcraftRoot] = useState('')
129
+ const [message, setMessage] = useState('')
130
+ const [busy, setBusy] = useState(false)
131
+ /**
132
+ * This seat's own install probe: `undefined` while in flight, `null` when it
133
+ * failed (the wizard stays usable, paths can be typed). A result another seat
134
+ * already wrote to the store counts too, so a mounted viewer does not make the
135
+ * navigation row probe twice before deciding.
136
+ */
137
+ const [probe, setProbe] = useState<InstallationsInfo | null>()
138
+
139
+ useEffect(() => {
140
+ let live = true
141
+ installations()
142
+ .then((result) => {
143
+ if (!live) return
144
+ setProbe(result)
145
+ actions.setInstallations(result)
146
+ })
147
+ .catch(() => { if (live) setProbe(null) })
148
+ return () => { live = false }
149
+ }, [actions, installations])
150
+
151
+ const facts = probe ?? installed
152
+ const phase = wizardPhase({
153
+ hasForm: form !== undefined,
154
+ status: snapshot.status,
155
+ onboardingComplete: snapshot.value?.onboardingComplete === true,
156
+ kicadConfigured: probe === undefined && installed === undefined
157
+ ? undefined
158
+ : facts?.kicad?.configured === true,
159
+ dismissed: closed,
160
+ })
161
+
162
+ useEffect(() => {
163
+ if (kicadRoot !== '' || facts?.kicad?.root === undefined) return
164
+ setKicadRoot(facts.kicad.root)
165
+ }, [facts?.kicad?.root, kicadRoot])
166
+
167
+ // `form === undefined` is already `no-form`; repeating it here is what lets
168
+ // TypeScript narrow it for the handlers below.
169
+ if (form === undefined || phase !== 'open') return null
170
+
171
+ const complete = async (): Promise<void> => {
172
+ // Close first: the write is a host round-trip, and the user's click must
173
+ // dismiss the modal whether or not the host accepts it.
174
+ dismissedInClient = true
175
+ setClosed(true)
176
+ try {
177
+ await form.set('onboardingComplete', true)
178
+ } catch {
179
+ // A refused host write must not trap the user in the wizard.
180
+ }
181
+ }
182
+
183
+ const finish = async (): Promise<void> => {
184
+ setBusy(true)
185
+ try {
186
+ if (kicadRoot !== '') await saveInstallation('kicad', kicadRoot)
187
+ if (solidcraftRoot !== '') await saveInstallation('solidcraft', solidcraftRoot)
188
+ } catch (error) {
189
+ setMessage(messageOf(error))
190
+ setBusy(false)
191
+ return
192
+ }
193
+ // Record completion before the probe refresh: a valid KiCad root makes this
194
+ // wizard unmount on the next render, and a write issued after that would
195
+ // rely on an unmounted component finishing its async tail.
196
+ await complete()
197
+ try {
198
+ actions.setInstallations(await installations())
199
+ } catch {
200
+ // The viewer re-probes on its own; nothing here depends on the answer.
201
+ }
202
+ }
203
+
204
+ const next = async (): Promise<void> => {
205
+ if (step < STEPS.length - 1) {
206
+ setStep(step + 1)
207
+ return
208
+ }
209
+ await finish()
210
+ }
211
+
212
+ const stepBody = (): ReactNode => {
213
+ if (step === 0) {
214
+ return createElement(
215
+ 'div',
216
+ { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
217
+ createElement(
218
+ 'div',
219
+ { style: { ...ROW, gap: 10 } },
220
+ createElement('span', { style: BRAND_MARK }, 'H!'),
221
+ createElement(
222
+ 'div',
223
+ { style: { display: 'flex', flexDirection: 'column', gap: 1 } },
224
+ createElement('h2', { style: TITLE }, COPY.wizard.welcomeTitle),
225
+ createElement('span', { style: STEP_LABEL }, COPY.wizard.welcomeKicker),
226
+ ),
227
+ ),
228
+ createElement('p', { style: LEAD }, COPY.wizard.welcomeLead),
229
+ createElement('div',
230
+ { style: FIELD_CARD },
231
+ createElement('span', { style: { fontSize: 11, fontWeight: 600 } }, COPY.wizard.welcomeUsesTitle),
232
+ createElement('p', { style: { ...MUTED, color: C.text3 } }, COPY.wizard.welcomeUses),
233
+ ),
234
+ createElement('p', { style: { ...MUTED, color: C.text3 } }, COPY.wizard.welcomeLocal),
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 }, COPY.wizard.kicadTitle),
245
+ createElement('span', { style: facts?.kicad?.configured === true ? pillStyle('ok') : pillStyle('muted') },
246
+ facts?.kicad?.configured === true ? `v${facts.kicad.version ?? '?'}` : COPY.wizard.kicadOptional),
247
+ ),
248
+ createElement('p', { style: LEAD }, COPY.wizard.kicadLead),
249
+ createElement('input', {
250
+ style: INPUT, value: kicadRoot, autoFocus: true, spellCheck: false,
251
+ placeholder: COPY.wizard.kicadPlaceholder,
252
+ onChange: event => setKicadRoot(event.currentTarget.value),
253
+ }),
254
+ createElement('p', { style: { ...MUTED, color: C.text3 } }, COPY.wizard.kicadSkipHint),
255
+ )
256
+ }
257
+ return createElement(
258
+ 'div',
259
+ { style: { display: 'flex', flexDirection: 'column', gap: 8 } },
260
+ createElement(
261
+ 'div',
262
+ { style: SPREAD },
263
+ createElement('h2', { style: TITLE }, COPY.wizard.solidcraftTitle),
264
+ createElement('span', { style: pillStyle('muted') }, COPY.wizard.kicadOptional),
265
+ ),
266
+ createElement('p', { style: LEAD }, COPY.wizard.solidcraftLead),
267
+ createElement('input', {
268
+ style: INPUT, value: solidcraftRoot, autoFocus: true, spellCheck: false,
269
+ placeholder: COPY.wizard.solidcraftPlaceholder,
270
+ onChange: event => setSolidcraftRoot(event.currentTarget.value),
271
+ }),
272
+ )
273
+ }
274
+
275
+ return createElement(
276
+ 'div',
277
+ { style: BACKDROP, role: 'dialog', 'aria-modal': true, 'aria-label': COPY.wizard.aria, 'data-hardware-wizard': true },
278
+ createElement(
279
+ 'div',
280
+ { style: PANEL },
281
+ createElement(
282
+ 'div',
283
+ { style: SPREAD },
284
+ createElement(
285
+ 'div',
286
+ { style: { ...ROW, gap: 6 } },
287
+ ...STEPS.map((label, index) => createElement('span', {
288
+ key: label,
289
+ style: { ...dotStyle(index === step ? C.accent : index < step ? C.ok : C.text3, 6) },
290
+ title: label,
291
+ })),
292
+ createElement('span', { style: { ...STEP_LABEL, ...MONO_TEXT } }, COPY.wizard.stepCounter(step + 1, STEPS.length, STEPS[step] ?? '')),
293
+ ),
294
+ createElement('button', {
295
+ type: 'button', style: buttonStyle('quiet', { fontSize: 10.5 }),
296
+ onClick: () => { void complete() },
297
+ }, COPY.wizard.skip),
298
+ ),
299
+ stepBody(),
300
+ ...(message === '' ? [] : [createElement('p', { key: 'msg', style: { ...MUTED, color: C.text2 }, role: 'status' }, message)]),
301
+ createElement(
302
+ 'div',
303
+ { style: { ...SPREAD, paddingTop: 6, borderTop: `1px solid ${C.borderSoft}` } },
304
+ createElement('span', { style: { ...MUTED, color: C.text3, fontSize: 10 } }, COPY.wizard.footerNote),
305
+ createElement(
306
+ 'span',
307
+ { style: ROW },
308
+ step > 0
309
+ ? createElement('button', {
310
+ type: 'button', style: buttonStyle('secondary'),
311
+ onClick: () => { setStep(step - 1) },
312
+ }, COPY.wizard.back)
313
+ : null,
314
+ createElement('button', {
315
+ type: 'button', style: buttonStyle('primary'), disabled: busy,
316
+ onClick: () => { void next() },
317
+ }, busy ? COPY.wizard.saving : step === STEPS.length - 1 ? COPY.wizard.finish : COPY.wizard.next),
318
+ ),
319
+ ),
320
+ ),
321
+ )
322
+ }