@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,451 @@
1
+ /**
2
+ * Order Placing destination.
3
+ *
4
+ * The panel never prices anything and never keeps its own order backend. It
5
+ * prepares the fabrication package with `kicad-cli` through the host, shows
6
+ * exactly what would be uploaded, and submits only after the user confirms in
7
+ * a dialog. The URL shown afterwards is the backend's own URL, passed through.
8
+ */
9
+ import { createElement, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
10
+ import { isAbortError } from './ecad.js'
11
+ import {
12
+ loadOrderConfig, openOrderUrl, placeOrder, prepareFabrication,
13
+ type FabricationProjection, type OrderConfigInfo, type PlacedOrder,
14
+ } from './transport.js'
15
+ import {
16
+ buttonStyle, C, cardStyle, disabled, dotStyle, MUTED, MONO, MONO_TEXT, pillStyle, R, SECTION_TITLE, SELECT,
17
+ } from './theme.js'
18
+
19
+ export interface OrderPanelProps {
20
+ readonly boardPath: string
21
+ readonly boardTitle: string
22
+ readonly schematicPath?: string
23
+ /**
24
+ * Workspace root of the session showing this panel. It is the authorization
25
+ * base the host re-checks; the project file is not, and never was.
26
+ */
27
+ readonly workspaceRoot?: string
28
+ /** DSH session the panel belongs to; the host authorizes against its workspace. */
29
+ readonly session?: string
30
+ readonly configured: boolean
31
+ }
32
+
33
+ const QUANTITIES = [5, 20, 100] as const
34
+
35
+ function formatBytes(bytes: number): string {
36
+ if (bytes < 1024) return `${String(bytes)} B`
37
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
38
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
39
+ }
40
+
41
+ function describe(error: unknown): string {
42
+ return error instanceof Error ? error.message : String(error)
43
+ }
44
+
45
+ function specRows(facts: FabricationProjection['facts']): { label: string; value: string }[] {
46
+ return [
47
+ { label: 'Layers', value: `${String(facts.layers)} Cu` },
48
+ { label: 'Outline', value: `${facts.widthMm.toFixed(1)} × ${facts.heightMm.toFixed(1)} mm` },
49
+ { label: 'Thickness', value: `${facts.thicknessMm.toFixed(2)} mm` },
50
+ { label: 'Min trace', value: facts.minTrackMm === undefined ? 'default' : `${facts.minTrackMm.toFixed(2)} mm` },
51
+ { label: 'Min drill', value: facts.minViaDrillMm === undefined ? 'default' : `${facts.minViaDrillMm.toFixed(2)} mm` },
52
+ { label: 'Outer Cu', value: `${String(facts.outerOz ?? 1)} oz` },
53
+ ]
54
+ }
55
+
56
+ const SPEC_GRID: CSSProperties = {
57
+ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(88px, 1fr))', gap: 6,
58
+ }
59
+ const SPEC_CELL: CSSProperties = {
60
+ border: `1px solid ${C.borderSoft}`, borderRadius: R.md, background: C.base,
61
+ padding: '5px 7px', display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0,
62
+ }
63
+ const SPEC_LABEL: CSSProperties = { fontSize: 9.5, color: C.text3, letterSpacing: 0.2 }
64
+ const SPEC_VALUE: CSSProperties = { fontSize: 11, ...MONO_TEXT, color: C.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }
65
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0 }
66
+ const SPREAD: CSSProperties = { ...ROW, justifyContent: 'space-between' }
67
+ const TAG: CSSProperties = {
68
+ fontSize: 9.5, fontWeight: 600, letterSpacing: 0.6, padding: '1px 5px', borderRadius: R.sm,
69
+ border: '1px solid currentColor', fontFamily: MONO,
70
+ }
71
+ const LINK: CSSProperties = {
72
+ color: C.info, fontSize: 11, fontFamily: MONO, wordBreak: 'break-all', textDecoration: 'underline',
73
+ textUnderlineOffset: 2,
74
+ }
75
+ const DIALOG_BACKDROP: CSSProperties = {
76
+ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(2px)',
77
+ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 14, zIndex: 20,
78
+ }
79
+ const DIALOG: CSSProperties = {
80
+ width: '100%', maxWidth: 420, maxHeight: '90%', overflow: 'auto', background: C.card,
81
+ border: `1px solid ${C.border}`, borderRadius: R.lg, boxShadow: '0 24px 60px rgba(0,0,0,0.45)',
82
+ padding: 14, display: 'flex', flexDirection: 'column', gap: 10,
83
+ }
84
+
85
+ /** One workflow card: what it will do, what it needs, and its action. */
86
+ function workflowCard(input: {
87
+ readonly tag: string
88
+ readonly tagColor: string
89
+ readonly title: string
90
+ readonly subtitle: string
91
+ readonly details: readonly { label: string; value: string }[]
92
+ readonly action: string
93
+ readonly onAction: () => void
94
+ readonly busy: boolean
95
+ readonly blocked?: string
96
+ }): ReactNode {
97
+ const blocked = input.blocked !== undefined
98
+ return createElement(
99
+ 'div',
100
+ { style: cardStyle({ gap: 9 }), 'data-hardware-order-card': input.tag.toLowerCase() },
101
+ createElement(
102
+ 'div',
103
+ { style: { ...ROW, gap: 7 } },
104
+ createElement('span', { style: { ...TAG, color: input.tagColor } }, input.tag),
105
+ createElement('span', { style: { fontSize: 12, fontWeight: 600, color: C.text, minWidth: 0 } }, input.title),
106
+ ),
107
+ createElement('p', { style: MUTED }, input.subtitle),
108
+ createElement(
109
+ 'div',
110
+ { style: SPEC_GRID },
111
+ ...input.details.map(detail => createElement(
112
+ 'div',
113
+ { key: detail.label, style: SPEC_CELL },
114
+ createElement('span', { style: SPEC_LABEL }, detail.label),
115
+ createElement('span', { style: SPEC_VALUE, title: detail.value }, detail.value),
116
+ )),
117
+ ),
118
+ blocked
119
+ ? createElement('p', { style: { ...MUTED, color: C.warn } }, input.blocked ?? '')
120
+ : null,
121
+ createElement(
122
+ 'button',
123
+ {
124
+ type: 'button', style: { ...buttonStyle('primary'), width: '100%', ...disabled(blocked || input.busy) },
125
+ disabled: blocked || input.busy,
126
+ 'data-hardware-order-action': input.tag.toLowerCase(),
127
+ onClick: input.onAction,
128
+ },
129
+ input.busy ? 'Submitting…' : input.action,
130
+ ),
131
+ )
132
+ }
133
+
134
+ export function OrderPanel(props: OrderPanelProps): ReactNode {
135
+ const { boardPath, boardTitle, schematicPath, workspaceRoot, session, configured } = props
136
+ const [config, setConfig] = useState<OrderConfigInfo>()
137
+ const [prepared, setPrepared] = useState<FabricationProjection>()
138
+ const [preparing, setPreparing] = useState(false)
139
+ const [message, setMessage] = useState<string>()
140
+ const [quantity, setQuantity] = useState<number>(20)
141
+ const [confirming, setConfirming] = useState<'pcb' | 'smt'>()
142
+ const [acknowledged, setAcknowledged] = useState(false)
143
+ const [placing, setPlacing] = useState<'pcb' | 'smt'>()
144
+ const [placed, setPlaced] = useState<PlacedOrder>()
145
+ const [copied, setCopied] = useState(false)
146
+ const [reopening, setReopening] = useState(false)
147
+ const live = useRef(true)
148
+
149
+ useEffect(() => {
150
+ live.current = true
151
+ return () => { live.current = false }
152
+ }, [])
153
+
154
+ useEffect(() => {
155
+ loadOrderConfig()
156
+ .then((value) => { if (live.current) setConfig(value) })
157
+ .catch((error: unknown) => { if (live.current) setMessage(describe(error)) })
158
+ }, [])
159
+
160
+ // Preparing the package is local: gerbers, drill files and CSVs come from the
161
+ // saved board. Nothing leaves the machine until the user confirms an order.
162
+ useEffect(() => {
163
+ if (!configured) {
164
+ setPrepared(undefined)
165
+ return
166
+ }
167
+ const controller = new AbortController()
168
+ setPreparing(true)
169
+ setMessage(undefined)
170
+ setPlaced(undefined)
171
+ prepareFabrication(boardPath, schematicPath, workspaceRoot, controller.signal, session)
172
+ .then((value) => { if (!controller.signal.aborted) setPrepared(value) })
173
+ .catch((error: unknown) => {
174
+ if (controller.signal.aborted || isAbortError(error)) return
175
+ setMessage(describe(error))
176
+ })
177
+ .finally(() => { if (!controller.signal.aborted) setPreparing(false) })
178
+ return () => { controller.abort() }
179
+ }, [boardPath, schematicPath, workspaceRoot, session, configured])
180
+
181
+ const facts = prepared?.facts
182
+ const specs = useMemo(() => (facts === undefined ? [] : specRows(facts)), [facts])
183
+
184
+ const submit = async (kind: 'pcb' | 'smt'): Promise<void> => {
185
+ setPlacing(kind)
186
+ setMessage(undefined)
187
+ try {
188
+ const result = await placeOrder(kind, {
189
+ path: boardPath,
190
+ ...(schematicPath === undefined ? {} : { schematic: schematicPath }),
191
+ ...(workspaceRoot === undefined ? {} : { cwd: workspaceRoot }),
192
+ ...(session === undefined ? {} : { session }),
193
+ quantity,
194
+ confirm: true,
195
+ }, undefined)
196
+ setPlaced(result)
197
+ setConfirming(undefined)
198
+ setAcknowledged(false)
199
+ } catch (error) {
200
+ setMessage(describe(error))
201
+ } finally {
202
+ setPlacing(undefined)
203
+ }
204
+ }
205
+
206
+ const copy = async (): Promise<void> => {
207
+ if (placed === undefined) return
208
+ try {
209
+ await navigator.clipboard.writeText(placed.orderUrl)
210
+ setCopied(true)
211
+ setTimeout(() => { setCopied(false) }, 1600)
212
+ } catch {
213
+ setCopied(false)
214
+ }
215
+ }
216
+
217
+ const reopen = async (): Promise<void> => {
218
+ if (placed === undefined) return
219
+ setReopening(true)
220
+ setMessage(undefined)
221
+ try {
222
+ await openOrderUrl(placed.orderUrl)
223
+ setPlaced({ ...placed, launched: true, status: 'launched' })
224
+ } catch (error) {
225
+ setMessage(describe(error))
226
+ } finally {
227
+ setReopening(false)
228
+ }
229
+ }
230
+
231
+ const zipSize = prepared === undefined ? undefined : formatBytes(prepared.archive.zipBytes)
232
+ const assembly = prepared?.assembly
233
+ const tokenReady = config?.hasToken ?? false
234
+
235
+ const header = createElement(
236
+ 'div',
237
+ { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
238
+ createElement(
239
+ 'div',
240
+ { style: SPREAD },
241
+ createElement(
242
+ 'h3',
243
+ { style: { margin: 0, fontSize: 13, fontWeight: 600, color: C.text, display: 'flex', alignItems: 'center', gap: 6 } },
244
+ createElement('span', { style: dotStyle(C.accent) }),
245
+ 'Fabrication & assembly',
246
+ ),
247
+ preparing
248
+ ? createElement('span', { style: pillStyle('info') }, 'packaging…')
249
+ : prepared !== undefined
250
+ ? createElement('span', { style: pillStyle('ok') }, 'package ready')
251
+ : createElement('span', { style: pillStyle(configured ? 'muted' : 'warn') }, configured ? 'not prepared' : 'KiCad missing'),
252
+ ),
253
+ createElement('p', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10.5 } }, boardTitle),
254
+ )
255
+
256
+ const packageCard = createElement(
257
+ 'div',
258
+ { style: cardStyle() },
259
+ createElement('div', { style: SPREAD },
260
+ createElement('span', { style: SECTION_TITLE }, 'Fabrication package'),
261
+ prepared === undefined
262
+ ? null
263
+ : createElement('span', { style: pillStyle('muted') }, `${String(prepared.archive.files.length)} files · ${zipSize}`),
264
+ ),
265
+ prepared === undefined
266
+ ? createElement('p', { style: MUTED },
267
+ preparing ? 'Running kicad-cli pcb export gerbers and drill…' : 'Not prepared yet.')
268
+ : createElement(
269
+ 'div',
270
+ {
271
+ style: {
272
+ display: 'flex', flexWrap: 'wrap', gap: 4, maxHeight: 74, overflow: 'auto',
273
+ border: `1px solid ${C.borderSoft}`, borderRadius: R.md, padding: 6, background: C.base,
274
+ },
275
+ },
276
+ ...prepared.archive.files.map(file => createElement(
277
+ 'span',
278
+ { key: file.name, style: { ...pillStyle('muted'), fontSize: 9.5, padding: '0 5px' }, title: `${file.name} · ${formatBytes(file.bytes)}` },
279
+ file.name,
280
+ )),
281
+ ),
282
+ )
283
+
284
+ const pcbCard = workflowCard({
285
+ tag: 'PCB',
286
+ tagColor: C.ok,
287
+ title: 'Bare board fabrication',
288
+ subtitle: prepared === undefined
289
+ ? 'Quotes and orders the selected board through the Huaqiu fabrication service.'
290
+ : `${prepared.archive.zipName} · ${String(prepared.archive.files.length)} gerber/drill files · ${zipSize}`,
291
+ details: specs.length === 0
292
+ ? [{ label: 'Board', value: boardTitle }]
293
+ : specs,
294
+ action: 'Submit PCB order',
295
+ onAction: () => { setAcknowledged(false); setConfirming('pcb') },
296
+ busy: placing === 'pcb',
297
+ ...(configured && prepared !== undefined
298
+ ? tokenReady ? {} : { blocked: 'Sign in to Huaqiu to place an order — the order page opens under your account.' }
299
+ : { blocked: configured ? 'Waiting for the fabrication package.' : 'Configure KiCad to package the board files.' }),
300
+ })
301
+
302
+ const smtCard = workflowCard({
303
+ tag: 'PCBA',
304
+ tagColor: C.info,
305
+ title: 'Turnkey assembly',
306
+ subtitle: assembly === undefined
307
+ ? 'Needs the project root schematic for the BOM and component positions.'
308
+ : `${String(assembly.positions)} placements · ${String(assembly.bomLines)} BOM lines · ${formatBytes(assembly.bomBytes + assembly.positionsBytes)}`,
309
+ details: [
310
+ { label: 'Placements', value: assembly === undefined ? '—' : String(assembly.positions) },
311
+ { label: 'BOM lines', value: assembly === undefined ? '—' : String(assembly.bomLines) },
312
+ { label: 'Token', value: tokenReady ? 'Huaqiu login' : 'signed out' },
313
+ ],
314
+ action: 'Submit assembly order',
315
+ onAction: () => { setAcknowledged(false); setConfirming('smt') },
316
+ busy: placing === 'smt',
317
+ ...(assembly === undefined
318
+ ? { blocked: 'Select a root schematic so the BOM and positions can be built.' }
319
+ : tokenReady
320
+ ? {}
321
+ : { blocked: 'Sign in to Huaqiu to order assembly — the page opens under your account.' }),
322
+ })
323
+
324
+ const agentHint = createElement(
325
+ 'div',
326
+ { style: { ...ROW, gap: 4, paddingTop: 2 } },
327
+ createElement('span', { style: { fontSize: 10, color: C.text3 } }, 'Agent entry points'),
328
+ ...['quote_pcb', 'place_pcb_order', 'quote_smt', 'place_smt_order'].map(name => createElement(
329
+ 'span', { key: name, style: { ...pillStyle('muted'), fontSize: 9.5 } }, name,
330
+ )),
331
+ )
332
+
333
+ const resultCard = placed === undefined ? null : createElement(
334
+ 'div',
335
+ { style: cardStyle({ borderColor: 'rgba(52,211,153,0.4)' }), 'data-hardware-order-result': placed.kind },
336
+ createElement('div', { style: SPREAD },
337
+ createElement('span', { style: SECTION_TITLE }, `${placed.kind === 'pcb' ? 'PCB' : 'Assembly'} order created`),
338
+ createElement('span', { style: pillStyle(placed.launched ? 'ok' : 'muted') },
339
+ placed.launched ? 'opened in browser' : 'ready to open'),
340
+ ),
341
+ createElement('p', { style: MUTED }, placed.message),
342
+ createElement('a', {
343
+ style: LINK, href: placed.orderUrl, target: '_blank', rel: 'noreferrer noopener',
344
+ 'data-hardware-order-url': true,
345
+ }, placed.orderUrl),
346
+ createElement('p', { style: { ...MUTED, fontSize: 10 } },
347
+ 'Same page KiCad shows in its order webview, opened in your default browser.'),
348
+ createElement('div', { style: ROW },
349
+ createElement('button', {
350
+ type: 'button',
351
+ style: { ...buttonStyle('primary'), ...disabled(reopening) },
352
+ disabled: reopening,
353
+ 'data-hardware-order-reopen': true,
354
+ onClick: () => { void reopen() },
355
+ }, reopening ? 'Opening…' : 'Open in browser'),
356
+ createElement('button', { type: 'button', style: buttonStyle('secondary'), onClick: () => { void copy() } },
357
+ copied ? 'Copied' : 'Copy URL'),
358
+ createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10 } },
359
+ `${placed.archive.zipName} · ${formatBytes(placed.archive.zipBytes)}`),
360
+ ),
361
+ )
362
+
363
+ const dialog = confirming === undefined ? null : createElement(
364
+ 'div',
365
+ { style: DIALOG_BACKDROP, role: 'dialog', 'aria-modal': true, 'aria-label': 'Confirm order upload', 'data-hardware-order-confirm': confirming },
366
+ createElement(
367
+ 'div',
368
+ { style: DIALOG },
369
+ createElement(
370
+ 'div',
371
+ { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
372
+ createElement('h4', { style: { margin: 0, fontSize: 13, fontWeight: 600 } },
373
+ confirming === 'pcb' ? 'Upload board files and create the PCB order?' : 'Upload the assembly package?'),
374
+ createElement('p', { style: MUTED },
375
+ 'This sends the files below to the Huaqiu order service. The order is created there and its page opens in your default browser; payment still happens on that page.'),
376
+ ),
377
+ createElement(
378
+ 'ul',
379
+ { style: { margin: 0, paddingLeft: 16, fontSize: 11, color: C.text2, lineHeight: 1.7 } },
380
+ createElement('li', null, `${prepared?.archive.zipName ?? 'board.zip'} — gerbers and drill files (${zipSize ?? '—'})`),
381
+ ...(confirming === 'smt'
382
+ ? [
383
+ createElement('li', { key: 'pos' }, `Component positions (${assembly === undefined ? '—' : formatBytes(assembly.positionsBytes)})`),
384
+ createElement('li', { key: 'bom' }, `Assembly BOM (${assembly === undefined ? '—' : formatBytes(assembly.bomBytes)})`),
385
+ ]
386
+ : []),
387
+ createElement('li', { key: 'host' }, createElement('span', { style: MONO_TEXT }, config?.baseUrl ?? 'the configured order service')),
388
+ ),
389
+ createElement(
390
+ 'label',
391
+ { style: { ...ROW, alignItems: 'flex-start', fontSize: 11, color: C.text2, cursor: 'pointer' } },
392
+ createElement('input', {
393
+ type: 'checkbox', checked: acknowledged,
394
+ style: { marginTop: 2, accentColor: C.accent },
395
+ onChange: (event: { currentTarget: HTMLInputElement }) => { setAcknowledged(event.currentTarget.checked) },
396
+ 'data-hardware-order-ack': true,
397
+ }),
398
+ 'I understand these board files leave this machine.',
399
+ ),
400
+ createElement(
401
+ 'div',
402
+ { style: { ...ROW, justifyContent: 'flex-end' } },
403
+ createElement('button', {
404
+ type: 'button', style: buttonStyle('quiet'),
405
+ onClick: () => { setConfirming(undefined); setAcknowledged(false) },
406
+ }, 'Cancel'),
407
+ createElement('button', {
408
+ type: 'button',
409
+ style: { ...buttonStyle('primary'), ...disabled(!acknowledged || placing !== undefined) },
410
+ disabled: !acknowledged || placing !== undefined,
411
+ 'data-hardware-order-confirm-submit': true,
412
+ onClick: () => { void submit(confirming) },
413
+ }, placing === undefined ? 'Upload and open order page' : 'Uploading…'),
414
+ ),
415
+ ),
416
+ )
417
+
418
+ return createElement(
419
+ 'div',
420
+ { style: { position: 'relative', display: 'flex', flexDirection: 'column', gap: 10, minHeight: 0 }, 'data-hardware-order': true },
421
+ header,
422
+ ...(message === undefined ? [] : [createElement('p', {
423
+ key: 'message', role: 'status', style: { ...MUTED, color: C.warn, borderLeft: `2px solid ${C.warn}`, paddingLeft: 8 },
424
+ }, message)]),
425
+ createElement(
426
+ 'div',
427
+ { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 10 } },
428
+ pcbCard,
429
+ smtCard,
430
+ ),
431
+ createElement(
432
+ 'div',
433
+ { style: { ...SPREAD, ...cardStyle({ flexDirection: 'row', alignItems: 'center' }) } },
434
+ createElement('span', { style: { fontSize: 11, color: C.text2 } }, 'Production batch'),
435
+ createElement(
436
+ 'select',
437
+ {
438
+ style: { ...SELECT, width: 'auto' }, value: quantity,
439
+ 'data-hardware-order-quantity': true,
440
+ onChange: (event: { currentTarget: HTMLSelectElement }) => { setQuantity(Number(event.currentTarget.value)) },
441
+ },
442
+ ...QUANTITIES.map(count => createElement('option', { key: count, value: count }, `${String(count)} units`)),
443
+ ),
444
+ createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10 } }, `quote basis · ${String(quantity)} pcs`),
445
+ ),
446
+ packageCard,
447
+ resultCard,
448
+ agentHint,
449
+ dialog,
450
+ )
451
+ }