@huaqiu/dsh-hardware-ui 0.7.19 → 0.7.21

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,453 +1,423 @@
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 { COPY } from './copy.js'
12
- import {
13
- loadOrderConfig, messageOf, placeOrder, prepareFabrication,
14
- type FabricationProjection, type OrderConfigInfo, type PlacedOrder,
15
- } from './transport.js'
16
- import { openOrderPage } from './order-page.js'
17
- import {
18
- buttonStyle, C, cardStyle, disabled, dotStyle, MUTED, MONO, MONO_TEXT, pillStyle, R, SECTION_TITLE, SELECT,
19
- } from './theme.js'
20
-
21
- export interface OrderPanelProps {
22
- readonly boardPath: string
23
- readonly boardTitle: string
24
- readonly schematicPath?: string
25
- /** Workspace root of the session showing this panel; the base for relative paths. */
26
- readonly workspaceRoot?: string
27
- /** DSH session the panel belongs to, used to scope host-side discovery. */
28
- readonly session?: string
29
- readonly configured: boolean
30
- }
31
-
32
- const QUANTITIES = [5, 20, 100] as const
33
-
34
- function formatBytes(bytes: number): string {
35
- if (bytes < 1024) return `${String(bytes)} B`
36
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
37
- return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
38
- }
39
-
40
- function specRows(facts: FabricationProjection['facts']): { label: string; value: string }[] {
41
- return [
42
- { label: COPY.order.layers, value: COPY.order.layersValue(facts.layers) },
43
- { label: COPY.order.outline, value: `${facts.widthMm.toFixed(1)} × ${facts.heightMm.toFixed(1)} mm` },
44
- { label: COPY.order.thickness, value: `${facts.thicknessMm.toFixed(2)} mm` },
45
- { label: COPY.order.minTrace, value: facts.minTrackMm === undefined ? COPY.order.defaultValue : `${facts.minTrackMm.toFixed(2)} mm` },
46
- { label: COPY.order.minDrill, value: facts.minViaDrillMm === undefined ? COPY.order.defaultValue : `${facts.minViaDrillMm.toFixed(2)} mm` },
47
- { label: COPY.order.outerCopper, value: COPY.order.copperValue(facts.outerOz ?? 1) },
48
- ]
49
- }
50
-
51
- const SPEC_GRID: CSSProperties = {
52
- display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(88px, 1fr))', gap: 6,
53
- }
54
- const SPEC_CELL: CSSProperties = {
55
- border: `1px solid ${C.borderSoft}`, borderRadius: R.md, background: C.base,
56
- padding: '5px 7px', display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0,
57
- }
58
- const SPEC_LABEL: CSSProperties = { fontSize: 9.5, color: C.text3, letterSpacing: 0.2 }
59
- const SPEC_VALUE: CSSProperties = { fontSize: 11, ...MONO_TEXT, color: C.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }
60
- const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0 }
61
- const SPREAD: CSSProperties = { ...ROW, justifyContent: 'space-between' }
62
- const TAG: CSSProperties = {
63
- fontSize: 9.5, fontWeight: 600, letterSpacing: 0.6, padding: '1px 5px', borderRadius: R.sm,
64
- border: '1px solid currentColor', fontFamily: MONO,
65
- }
66
- const LINK: CSSProperties = {
67
- color: C.info, fontSize: 11, fontFamily: MONO, wordBreak: 'break-all', textDecoration: 'underline',
68
- textUnderlineOffset: 2,
69
- }
70
- const DIALOG_BACKDROP: CSSProperties = {
71
- position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(2px)',
72
- display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 14, zIndex: 20,
73
- }
74
- const DIALOG: CSSProperties = {
75
- width: '100%', maxWidth: 420, maxHeight: '90%', overflow: 'auto', background: C.card,
76
- border: `1px solid ${C.border}`, borderRadius: R.lg, boxShadow: '0 24px 60px rgba(0,0,0,0.45)',
77
- padding: 14, display: 'flex', flexDirection: 'column', gap: 10,
78
- }
79
-
80
- /** One workflow card: what it will do, what it needs, and its action. */
81
- function workflowCard(input: {
82
- readonly tag: string
83
- readonly tagColor: string
84
- readonly title: string
85
- readonly subtitle: string
86
- readonly details: readonly { label: string; value: string }[]
87
- readonly action: string
88
- readonly onAction: () => void
89
- readonly busy: boolean
90
- readonly blocked?: string
91
- }): ReactNode {
92
- const blocked = input.blocked !== undefined
93
- return createElement(
94
- 'div',
95
- { style: cardStyle({ gap: 9 }), 'data-hardware-order-card': input.tag.toLowerCase() },
96
- createElement(
97
- 'div',
98
- { style: { ...ROW, gap: 7 } },
99
- createElement('span', { style: { ...TAG, color: input.tagColor } }, input.tag),
100
- createElement('span', { style: { fontSize: 12, fontWeight: 600, color: C.text, minWidth: 0 } }, input.title),
101
- ),
102
- createElement('p', { style: MUTED }, input.subtitle),
103
- createElement(
104
- 'div',
105
- { style: SPEC_GRID },
106
- ...input.details.map(detail => createElement(
107
- 'div',
108
- { key: detail.label, style: SPEC_CELL },
109
- createElement('span', { style: SPEC_LABEL }, detail.label),
110
- createElement('span', { style: SPEC_VALUE, title: detail.value }, detail.value),
111
- )),
112
- ),
113
- blocked
114
- ? createElement('p', { style: { ...MUTED, color: C.warn } }, input.blocked ?? '')
115
- : null,
116
- createElement(
117
- 'button',
118
- {
119
- type: 'button', style: { ...buttonStyle('primary'), width: '100%', ...disabled(blocked || input.busy) },
120
- disabled: blocked || input.busy,
121
- 'data-hardware-order-action': input.tag.toLowerCase(),
122
- onClick: input.onAction,
123
- },
124
- input.busy ? COPY.order.submitting : input.action,
125
- ),
126
- )
127
- }
128
-
129
- export function OrderPanel(props: OrderPanelProps): ReactNode {
130
- const { boardPath, boardTitle, schematicPath, workspaceRoot, session, configured } = props
131
- const [config, setConfig] = useState<OrderConfigInfo>()
132
- const [prepared, setPrepared] = useState<FabricationProjection>()
133
- const [preparing, setPreparing] = useState(false)
134
- const [message, setMessage] = useState<string>()
135
- const [quantity, setQuantity] = useState<number>(20)
136
- const [confirming, setConfirming] = useState<'pcb' | 'smt'>()
137
- const [acknowledged, setAcknowledged] = useState(false)
138
- const [placing, setPlacing] = useState<'pcb' | 'smt'>()
139
- const [placed, setPlaced] = useState<PlacedOrder>()
140
- const [copied, setCopied] = useState(false)
141
- const [reopening, setReopening] = useState(false)
142
- const live = useRef(true)
143
-
144
- useEffect(() => {
145
- live.current = true
146
- return () => { live.current = false }
147
- }, [])
148
-
149
- useEffect(() => {
150
- loadOrderConfig()
151
- .then((value) => { if (live.current) setConfig(value) })
152
- .catch((error: unknown) => { if (live.current) setMessage(messageOf(error)) })
153
- }, [])
154
-
155
- // Preparing the package is local: gerbers, drill files and CSVs come from the
156
- // saved board. Nothing leaves the machine until the user confirms an order.
157
- useEffect(() => {
158
- if (!configured) {
159
- setPrepared(undefined)
160
- return
161
- }
162
- const controller = new AbortController()
163
- setPreparing(true)
164
- setMessage(undefined)
165
- setPlaced(undefined)
166
- prepareFabrication(boardPath, schematicPath, workspaceRoot, controller.signal, session)
167
- .then((value) => { if (!controller.signal.aborted) setPrepared(value) })
168
- .catch((error: unknown) => {
169
- if (controller.signal.aborted || isAbortError(error)) return
170
- setMessage(messageOf(error))
171
- })
172
- .finally(() => { if (!controller.signal.aborted) setPreparing(false) })
173
- return () => { controller.abort() }
174
- }, [boardPath, schematicPath, workspaceRoot, session, configured])
175
-
176
- const facts = prepared?.facts
177
- const specs = useMemo(() => (facts === undefined ? [] : specRows(facts)), [facts])
178
-
179
- const submit = async (kind: 'pcb' | 'smt'): Promise<void> => {
180
- setPlacing(kind)
181
- setMessage(undefined)
182
- try {
183
- const result = await placeOrder(kind, {
184
- path: boardPath,
185
- ...(schematicPath === undefined ? {} : { schematic: schematicPath }),
186
- ...(workspaceRoot === undefined ? {} : { cwd: workspaceRoot }),
187
- ...(session === undefined ? {} : { session }),
188
- quantity,
189
- confirm: true,
190
- }, undefined)
191
- setPlaced(result)
192
- setConfirming(undefined)
193
- setAcknowledged(false)
194
- // The order exists from here on; show it where the user is working.
195
- openOrderPage(result.orderUrl)
196
- } catch (error) {
197
- setMessage(messageOf(error))
198
- } finally {
199
- setPlacing(undefined)
200
- }
201
- }
202
-
203
- const copy = async (): Promise<void> => {
204
- if (placed === undefined) return
205
- try {
206
- await navigator.clipboard.writeText(placed.orderUrl)
207
- setCopied(true)
208
- setTimeout(() => { setCopied(false) }, 1600)
209
- } catch {
210
- setCopied(false)
211
- }
212
- }
213
-
214
- const reopen = async (): Promise<void> => {
215
- if (placed === undefined) return
216
- setReopening(true)
217
- setMessage(undefined)
218
- try {
219
- openOrderPage(placed.orderUrl)
220
- setPlaced({ ...placed, launched: true, status: 'launched' })
221
- } catch (error) {
222
- setMessage(messageOf(error))
223
- } finally {
224
- setReopening(false)
225
- }
226
- }
227
-
228
- const zipSize = prepared === undefined ? undefined : formatBytes(prepared.archive.zipBytes)
229
- const assembly = prepared?.assembly
230
- const tokenReady = config?.hasToken ?? false
231
-
232
- const header = createElement(
233
- 'div',
234
- { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
235
- createElement(
236
- 'div',
237
- { style: SPREAD },
238
- createElement(
239
- 'h3',
240
- { style: { margin: 0, fontSize: 13, fontWeight: 600, color: C.text, display: 'flex', alignItems: 'center', gap: 6 } },
241
- createElement('span', { style: dotStyle(C.accent) }),
242
- COPY.order.title,
243
- ),
244
- preparing
245
- ? createElement('span', { style: pillStyle('info') }, COPY.order.packaging)
246
- : prepared !== undefined
247
- ? createElement('span', { style: pillStyle('ok') }, COPY.order.packageReady)
248
- : createElement('span', { style: pillStyle(configured ? 'muted' : 'warn') }, configured ? COPY.order.packagePending : COPY.viewer.kicadMissing),
249
- ),
250
- createElement('p', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10.5 } }, boardTitle),
251
- )
252
-
253
- const packageCard = createElement(
254
- 'div',
255
- { style: cardStyle() },
256
- createElement('div', { style: SPREAD },
257
- createElement('span', { style: SECTION_TITLE }, COPY.order.packageCard),
258
- prepared === undefined
259
- ? null
260
- : createElement('span', { style: pillStyle('muted') }, COPY.order.packageFiles(prepared.archive.files.length, zipSize ?? '')),
261
- ),
262
- prepared === undefined
263
- ? createElement('p', { style: MUTED },
264
- preparing ? COPY.order.packageRunning : COPY.order.packageNotPrepared)
265
- : createElement(
266
- 'div',
267
- {
268
- style: {
269
- display: 'flex', flexWrap: 'wrap', gap: 4, maxHeight: 74, overflow: 'auto',
270
- border: `1px solid ${C.borderSoft}`, borderRadius: R.md, padding: 6, background: C.base,
271
- },
272
- },
273
- ...prepared.archive.files.map(file => createElement(
274
- 'span',
275
- { key: file.name, style: { ...pillStyle('muted'), fontSize: 9.5, padding: '0 5px' }, title: `${file.name} · ${formatBytes(file.bytes)}` },
276
- file.name,
277
- )),
278
- ),
279
- )
280
-
281
- const pcbCard = workflowCard({
282
- tag: 'PCB',
283
- tagColor: C.ok,
284
- title: COPY.order.pcbTitle,
285
- subtitle: prepared === undefined
286
- ? COPY.order.pcbSubtitle
287
- : COPY.order.pcbSummary(prepared.archive.zipName, prepared.archive.files.length, zipSize ?? ''),
288
- details: specs.length === 0
289
- ? [{ label: COPY.order.boardFile, value: boardTitle }]
290
- : specs,
291
- action: COPY.order.pcbAction,
292
- onAction: () => { setAcknowledged(false); setConfirming('pcb') },
293
- busy: placing === 'pcb',
294
- ...(configured && prepared !== undefined
295
- ? tokenReady ? {} : { blocked: COPY.order.signInToOrder }
296
- : { blocked: configured ? COPY.order.waitingForPackage : COPY.order.configureToPackage }),
297
- })
298
-
299
- const smtCard = workflowCard({
300
- tag: 'PCBA',
301
- tagColor: C.info,
302
- title: COPY.order.smtTitle,
303
- subtitle: assembly === undefined
304
- ? COPY.order.smtSubtitle
305
- : COPY.order.smtSummary(assembly.positions, assembly.bomLines, formatBytes(assembly.bomBytes + assembly.positionsBytes)),
306
- details: [
307
- { label: COPY.order.placements, value: assembly === undefined ? '—' : String(assembly.positions) },
308
- { label: COPY.order.bomLines, value: assembly === undefined ? '—' : String(assembly.bomLines) },
309
- { label: COPY.order.credential, value: tokenReady ? COPY.order.signedIn : COPY.order.signedOut },
310
- ],
311
- action: COPY.order.smtAction,
312
- onAction: () => { setAcknowledged(false); setConfirming('smt') },
313
- busy: placing === 'smt',
314
- ...(assembly === undefined
315
- ? { blocked: COPY.order.selectRootSchematic }
316
- : tokenReady
317
- ? {}
318
- : { blocked: COPY.order.signInToOrderSmt }),
319
- })
320
-
321
- const agentHint = createElement(
322
- 'div',
323
- { style: { ...ROW, gap: 4, paddingTop: 2 } },
324
- createElement('span', { style: { fontSize: 10, color: C.text3 } }, COPY.order.agentEntryPoints),
325
- ...['quote_pcb', 'place_pcb_order', 'quote_smt', 'place_smt_order'].map(name => createElement(
326
- 'span', { key: name, style: { ...pillStyle('muted'), fontSize: 9.5 } }, name,
327
- )),
328
- )
329
-
330
- const resultCard = placed === undefined ? null : createElement(
331
- 'div',
332
- { style: cardStyle({ borderColor: 'rgba(52,211,153,0.4)' }), 'data-hardware-order-result': placed.kind },
333
- createElement('div', { style: SPREAD },
334
- createElement('span', { style: SECTION_TITLE },
335
- placed.kind === 'pcb' ? COPY.order.resultTitlePcb : COPY.order.resultTitleSmt),
336
- createElement('span', { style: pillStyle(placed.launched ? 'ok' : 'muted') },
337
- placed.launched ? COPY.order.resultLaunched : COPY.order.resultReady),
338
- ),
339
- // The host sends its own English sentence in `placed.message`; the visible
340
- // copy is derived here so the panel speaks one language. The host string is
341
- // kept on the object for tooling, not rendered.
342
- createElement('p', { style: MUTED },
343
- placed.launched
344
- ? COPY.order.resultLaunchedMessage(placed.kind === 'pcb' ? 'PCB' : COPY.order.smtShort)
345
- : COPY.order.resultReadyMessage(placed.kind === 'pcb' ? 'PCB' : COPY.order.smtShort)),
346
- createElement('a', {
347
- style: LINK, href: placed.orderUrl, target: '_blank', rel: 'noreferrer noopener',
348
- 'data-hardware-order-url': true,
349
- }, placed.orderUrl),
350
- createElement('p', { style: { ...MUTED, fontSize: 10 } }, COPY.order.resultNote),
351
- createElement('div', { style: ROW },
352
- createElement('button', {
353
- type: 'button',
354
- style: { ...buttonStyle('primary'), ...disabled(reopening) },
355
- disabled: reopening,
356
- 'data-hardware-order-reopen': true,
357
- onClick: () => { void reopen() },
358
- }, reopening ? COPY.order.opening : COPY.order.openInBrowser),
359
- createElement('button', { type: 'button', style: buttonStyle('secondary'), onClick: () => { void copy() } },
360
- copied ? COPY.order.copied : COPY.order.copyUrl),
361
- createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10 } },
362
- `${placed.archive.zipName} · ${formatBytes(placed.archive.zipBytes)}`),
363
- ),
364
- )
365
-
366
- const dialog = confirming === undefined ? null : createElement(
367
- 'div',
368
- { style: DIALOG_BACKDROP, role: 'dialog', 'aria-modal': true, 'aria-label': COPY.order.confirmAria, 'data-hardware-order-confirm': confirming },
369
- createElement(
370
- 'div',
371
- { style: DIALOG },
372
- createElement(
373
- 'div',
374
- { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
375
- createElement('h4', { style: { margin: 0, fontSize: 13, fontWeight: 600 } },
376
- confirming === 'pcb' ? COPY.order.confirmTitlePcb : COPY.order.confirmTitleSmt),
377
- createElement('p', { style: MUTED }, COPY.order.confirmBody),
378
- ),
379
- createElement(
380
- 'ul',
381
- { style: { margin: 0, paddingLeft: 16, fontSize: 11, color: C.text2, lineHeight: 1.7 } },
382
- createElement('li', null, COPY.order.confirmZip(prepared?.archive.zipName ?? 'board.zip', zipSize ?? '—')),
383
- ...(confirming === 'smt'
384
- ? [
385
- createElement('li', { key: 'pos' }, COPY.order.confirmPositions(assembly === undefined ? '—' : formatBytes(assembly.positionsBytes))),
386
- createElement('li', { key: 'bom' }, COPY.order.confirmBom(assembly === undefined ? '—' : formatBytes(assembly.bomBytes))),
387
- ]
388
- : []),
389
- createElement('li', { key: 'host' }, createElement('span', { style: MONO_TEXT }, COPY.order.confirmHost(config?.baseUrl))),
390
- ),
391
- createElement(
392
- 'label',
393
- { style: { ...ROW, alignItems: 'flex-start', fontSize: 11, color: C.text2, cursor: 'pointer' } },
394
- createElement('input', {
395
- type: 'checkbox', checked: acknowledged,
396
- style: { marginTop: 2, accentColor: C.accent },
397
- onChange: (event: { currentTarget: HTMLInputElement }) => { setAcknowledged(event.currentTarget.checked) },
398
- 'data-hardware-order-ack': true,
399
- }),
400
- COPY.order.confirmAck,
401
- ),
402
- createElement(
403
- 'div',
404
- { style: { ...ROW, justifyContent: 'flex-end' } },
405
- createElement('button', {
406
- type: 'button', style: buttonStyle('quiet'),
407
- onClick: () => { setConfirming(undefined); setAcknowledged(false) },
408
- }, COPY.order.cancel),
409
- createElement('button', {
410
- type: 'button',
411
- style: { ...buttonStyle('primary'), ...disabled(!acknowledged || placing !== undefined) },
412
- disabled: !acknowledged || placing !== undefined,
413
- 'data-hardware-order-confirm-submit': true,
414
- onClick: () => { void submit(confirming) },
415
- }, placing === undefined ? COPY.order.uploadAndOpen : COPY.order.uploading),
416
- ),
417
- ),
418
- )
419
-
420
- return createElement(
421
- 'div',
422
- { style: { position: 'relative', display: 'flex', flexDirection: 'column', gap: 10, minHeight: 0 }, 'data-hardware-order': true },
423
- header,
424
- ...(message === undefined ? [] : [createElement('p', {
425
- key: 'message', role: 'status', style: { ...MUTED, color: C.warn, borderLeft: `2px solid ${C.warn}`, paddingLeft: 8 },
426
- }, message)]),
427
- createElement(
428
- 'div',
429
- { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 10 } },
430
- pcbCard,
431
- smtCard,
432
- ),
433
- createElement(
434
- 'div',
435
- { style: { ...SPREAD, ...cardStyle({ flexDirection: 'row', alignItems: 'center' }) } },
436
- createElement('span', { style: { fontSize: 11, color: C.text2 } }, COPY.order.batch),
437
- createElement(
438
- 'select',
439
- {
440
- style: { ...SELECT, width: 'auto' }, value: quantity,
441
- 'data-hardware-order-quantity': true,
442
- onChange: (event: { currentTarget: HTMLSelectElement }) => { setQuantity(Number(event.currentTarget.value)) },
443
- },
444
- ...QUANTITIES.map(count => createElement('option', { key: count, value: count }, COPY.order.batchUnits(count))),
445
- ),
446
- createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10 } }, COPY.order.quoteBasis(quantity)),
447
- ),
448
- packageCard,
449
- resultCard,
450
- agentHint,
451
- dialog,
452
- )
453
- }
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 which files and which board facts the upload carries, and then
7
+ * uploads on the click itself — one click, one real order. The URL shown
8
+ * afterwards is the backend's own URL, passed through.
9
+ */
10
+ import { createElement, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
11
+ import { isAbortError } from './ecad.js'
12
+ import { COPY } from './copy.js'
13
+ import {
14
+ loadOrderConfig, messageOf, placeOrder, prepareFabrication,
15
+ type FabricationProjection, type OrderConfigInfo, type PlacedOrder,
16
+ } from './transport.js'
17
+ import { openOrderPage } from './order-page.js'
18
+ import {
19
+ buttonStyle, C, cardStyle, disabled, dotStyle, MUTED, MONO, MONO_TEXT, pillStyle, R, SECTION_TITLE, SELECT,
20
+ } from './theme.js'
21
+
22
+ export interface OrderPanelProps {
23
+ readonly boardPath: string
24
+ readonly boardTitle: string
25
+ readonly schematicPath?: string
26
+ /** Workspace root of the session showing this panel; the base for relative paths. */
27
+ readonly workspaceRoot?: string
28
+ /** DSH session the panel belongs to, used to scope host-side discovery. */
29
+ readonly session?: string
30
+ readonly configured: boolean
31
+ /**
32
+ * Operation the user already chose (Place Order view).
33
+ *
34
+ * It places that order as soon as the package and the account are ready,
35
+ * because choosing the operation *is* the click there. The card stays visible
36
+ * and its button reads busy while the upload runs.
37
+ */
38
+ readonly focus?: 'pcb' | 'smt'
39
+ }
40
+
41
+ const QUANTITIES = [5, 20, 100] as const
42
+
43
+ function formatBytes(bytes: number): string {
44
+ if (bytes < 1024) return `${String(bytes)} B`
45
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
46
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
47
+ }
48
+
49
+ function specRows(facts: FabricationProjection['facts']): { label: string; value: string }[] {
50
+ return [
51
+ { label: COPY.order.layers, value: COPY.order.layersValue(facts.layers) },
52
+ { label: COPY.order.outline, value: `${facts.widthMm.toFixed(1)} × ${facts.heightMm.toFixed(1)} mm` },
53
+ { label: COPY.order.thickness, value: `${facts.thicknessMm.toFixed(2)} mm` },
54
+ { label: COPY.order.minTrace, value: facts.minTrackMm === undefined ? COPY.order.defaultValue : `${facts.minTrackMm.toFixed(2)} mm` },
55
+ { label: COPY.order.minDrill, value: facts.minViaDrillMm === undefined ? COPY.order.defaultValue : `${facts.minViaDrillMm.toFixed(2)} mm` },
56
+ { label: COPY.order.outerCopper, value: COPY.order.copperValue(facts.outerOz ?? 1) },
57
+ ]
58
+ }
59
+
60
+ const SPEC_GRID: CSSProperties = {
61
+ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(88px, 1fr))', gap: 6,
62
+ }
63
+ const SPEC_CELL: CSSProperties = {
64
+ border: `1px solid ${C.borderSoft}`, borderRadius: R.md, background: C.base,
65
+ padding: '5px 7px', display: 'flex', flexDirection: 'column', gap: 1, minWidth: 0,
66
+ }
67
+ const SPEC_LABEL: CSSProperties = { fontSize: 9.5, color: C.text3, letterSpacing: 0.2 }
68
+ const SPEC_VALUE: CSSProperties = { fontSize: 11, ...MONO_TEXT, color: C.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }
69
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', minWidth: 0 }
70
+ const SPREAD: CSSProperties = { ...ROW, justifyContent: 'space-between' }
71
+ const TAG: CSSProperties = {
72
+ fontSize: 9.5, fontWeight: 600, letterSpacing: 0.6, padding: '1px 5px', borderRadius: R.sm,
73
+ border: '1px solid currentColor', fontFamily: MONO,
74
+ }
75
+ const LINK: CSSProperties = {
76
+ color: C.info, fontSize: 11, fontFamily: MONO, wordBreak: 'break-all', textDecoration: 'underline',
77
+ textUnderlineOffset: 2,
78
+ }
79
+
80
+ /** One workflow card: what it will do, what it needs, and its action. */
81
+ function workflowCard(input: {
82
+ readonly tag: string
83
+ readonly tagColor: string
84
+ readonly title: string
85
+ readonly subtitle: string
86
+ readonly details: readonly { label: string; value: string }[]
87
+ readonly action: string
88
+ readonly onAction: () => void
89
+ readonly busy: boolean
90
+ /** Another order is in flight: both cards wait, not just the pressed one. */
91
+ readonly locked?: boolean
92
+ readonly blocked?: string
93
+ }): ReactNode {
94
+ const blocked = input.blocked !== undefined
95
+ const off = blocked || input.busy || input.locked === true
96
+ return createElement(
97
+ 'div',
98
+ { style: cardStyle({ gap: 9 }), 'data-hardware-order-card': input.tag.toLowerCase() },
99
+ createElement(
100
+ 'div',
101
+ { style: { ...ROW, gap: 7 } },
102
+ createElement('span', { style: { ...TAG, color: input.tagColor } }, input.tag),
103
+ createElement('span', { style: { fontSize: 12, fontWeight: 600, color: C.text, minWidth: 0 } }, input.title),
104
+ ),
105
+ createElement('p', { style: MUTED }, input.subtitle),
106
+ createElement(
107
+ 'div',
108
+ { style: SPEC_GRID },
109
+ ...input.details.map(detail => createElement(
110
+ 'div',
111
+ { key: detail.label, style: SPEC_CELL },
112
+ createElement('span', { style: SPEC_LABEL }, detail.label),
113
+ createElement('span', { style: SPEC_VALUE, title: detail.value }, detail.value),
114
+ )),
115
+ ),
116
+ blocked
117
+ ? createElement('p', { style: { ...MUTED, color: C.warn } }, input.blocked ?? '')
118
+ : null,
119
+ createElement(
120
+ 'button',
121
+ {
122
+ type: 'button', style: { ...buttonStyle('primary'), width: '100%', ...disabled(off) },
123
+ disabled: off,
124
+ 'data-hardware-order-action': input.tag.toLowerCase(),
125
+ onClick: input.onAction,
126
+ },
127
+ input.busy ? COPY.order.submitting : input.action,
128
+ ),
129
+ )
130
+ }
131
+
132
+ export function OrderPanel(props: OrderPanelProps): ReactNode {
133
+ const { boardPath, boardTitle, schematicPath, workspaceRoot, session, configured, focus } = props
134
+ const [config, setConfig] = useState<OrderConfigInfo>()
135
+ const [prepared, setPrepared] = useState<FabricationProjection>()
136
+ const [preparing, setPreparing] = useState(false)
137
+ const [message, setMessage] = useState<string>()
138
+ const [quantity, setQuantity] = useState<number>(20)
139
+ const [placing, setPlacing] = useState<'pcb' | 'smt'>()
140
+ const [placed, setPlaced] = useState<PlacedOrder>()
141
+ const [copied, setCopied] = useState(false)
142
+ const [reopening, setReopening] = useState(false)
143
+ const live = useRef(true)
144
+ /** One in-flight upload at a time, checked before React can re-render. */
145
+ const uploading = useRef(false)
146
+ /** `${boardPath}:${kind}` already auto-placed, so a requote cannot upload twice. */
147
+ const autoPlaced = useRef<string>()
148
+
149
+ useEffect(() => {
150
+ live.current = true
151
+ return () => { live.current = false }
152
+ }, [])
153
+
154
+ const submit = async (kind: 'pcb' | 'smt'): Promise<void> => {
155
+ // One upload at a time: a double click must not create two orders, and the
156
+ // guard is a ref so it holds before React re-renders the disabled card.
157
+ if (uploading.current) return
158
+ uploading.current = true
159
+ setPlacing(kind)
160
+ setMessage(undefined)
161
+ try {
162
+ const result = await placeOrder(kind, {
163
+ path: boardPath,
164
+ ...(schematicPath === undefined ? {} : { schematic: schematicPath }),
165
+ ...(workspaceRoot === undefined ? {} : { cwd: workspaceRoot }),
166
+ ...(session === undefined ? {} : { session }),
167
+ quantity,
168
+ }, undefined)
169
+ setPlaced(result)
170
+ // The order exists from here on; show it where the user is working.
171
+ openOrderPage(result.orderUrl)
172
+ } catch (error) {
173
+ setMessage(messageOf(error))
174
+ } finally {
175
+ uploading.current = false
176
+ setPlacing(undefined)
177
+ }
178
+ }
179
+
180
+ // A user who picked PCBA in the Place Order view has already made the choice:
181
+ // the order is placed as soon as the package and the account are ready, with
182
+ // the same single upload path the card uses. The key keeps a second render
183
+ // (or a requote) from uploading twice for one visit.
184
+ useEffect(() => {
185
+ if (focus === undefined || prepared === undefined || !live.current) return
186
+ if (config?.hasToken !== true || placing !== undefined) return
187
+ const key = `${boardPath}:${focus}`
188
+ if (autoPlaced.current === key) return
189
+ autoPlaced.current = key
190
+ void submit(focus)
191
+ }, [focus, prepared, config, boardPath, placing])
192
+
193
+ useEffect(() => {
194
+ loadOrderConfig()
195
+ .then((value) => { if (live.current) setConfig(value) })
196
+ .catch((error: unknown) => { if (live.current) setMessage(messageOf(error)) })
197
+ }, [])
198
+
199
+ // Preparing the package is local: gerbers, drill files and CSVs come from the
200
+ // saved board. Nothing leaves the machine until the user clicks an order card.
201
+ useEffect(() => {
202
+ if (!configured) {
203
+ setPrepared(undefined)
204
+ return
205
+ }
206
+ const controller = new AbortController()
207
+ setPreparing(true)
208
+ setMessage(undefined)
209
+ setPlaced(undefined)
210
+ prepareFabrication(boardPath, schematicPath, workspaceRoot, controller.signal, session)
211
+ .then((value) => { if (!controller.signal.aborted) setPrepared(value) })
212
+ .catch((error: unknown) => {
213
+ if (controller.signal.aborted || isAbortError(error)) return
214
+ setMessage(messageOf(error))
215
+ })
216
+ .finally(() => { if (!controller.signal.aborted) setPreparing(false) })
217
+ return () => { controller.abort() }
218
+ }, [boardPath, schematicPath, workspaceRoot, session, configured])
219
+
220
+ const facts = prepared?.facts
221
+ const specs = useMemo(() => (facts === undefined ? [] : specRows(facts)), [facts])
222
+
223
+ const copy = async (): Promise<void> => {
224
+ if (placed === undefined) return
225
+ try {
226
+ await navigator.clipboard.writeText(placed.orderUrl)
227
+ setCopied(true)
228
+ setTimeout(() => { setCopied(false) }, 1600)
229
+ } catch {
230
+ setCopied(false)
231
+ }
232
+ }
233
+
234
+ const reopen = async (): Promise<void> => {
235
+ if (placed === undefined) return
236
+ setReopening(true)
237
+ setMessage(undefined)
238
+ try {
239
+ openOrderPage(placed.orderUrl)
240
+ setPlaced({ ...placed, launched: true, status: 'launched' })
241
+ } catch (error) {
242
+ setMessage(messageOf(error))
243
+ } finally {
244
+ setReopening(false)
245
+ }
246
+ }
247
+
248
+ const zipSize = prepared === undefined ? undefined : formatBytes(prepared.archive.zipBytes)
249
+ const assembly = prepared?.assembly
250
+ const tokenReady = config?.hasToken ?? false
251
+
252
+ const header = createElement(
253
+ 'div',
254
+ { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
255
+ createElement(
256
+ 'div',
257
+ { style: SPREAD },
258
+ createElement(
259
+ 'h3',
260
+ { style: { margin: 0, fontSize: 13, fontWeight: 600, color: C.text, display: 'flex', alignItems: 'center', gap: 6 } },
261
+ createElement('span', { style: dotStyle(C.accent) }),
262
+ COPY.order.title,
263
+ ),
264
+ preparing
265
+ ? createElement('span', { style: pillStyle('info') }, COPY.order.packaging)
266
+ : prepared !== undefined
267
+ ? createElement('span', { style: pillStyle('ok') }, COPY.order.packageReady)
268
+ : createElement('span', { style: pillStyle(configured ? 'muted' : 'warn') }, configured ? COPY.order.packagePending : COPY.viewer.kicadMissing),
269
+ ),
270
+ createElement('p', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10.5 } }, boardTitle),
271
+ )
272
+
273
+ const packageCard = createElement(
274
+ 'div',
275
+ { style: cardStyle() },
276
+ createElement('div', { style: SPREAD },
277
+ createElement('span', { style: SECTION_TITLE }, COPY.order.packageCard),
278
+ prepared === undefined
279
+ ? null
280
+ : createElement('span', { style: pillStyle('muted') }, COPY.order.packageFiles(prepared.archive.files.length, zipSize ?? '')),
281
+ ),
282
+ prepared === undefined
283
+ ? createElement('p', { style: MUTED },
284
+ preparing ? COPY.order.packageRunning : COPY.order.packageNotPrepared)
285
+ : createElement(
286
+ 'div',
287
+ {
288
+ style: {
289
+ display: 'flex', flexWrap: 'wrap', gap: 4, maxHeight: 74, overflow: 'auto',
290
+ border: `1px solid ${C.borderSoft}`, borderRadius: R.md, padding: 6, background: C.base,
291
+ },
292
+ },
293
+ ...prepared.archive.files.map(file => createElement(
294
+ 'span',
295
+ { key: file.name, style: { ...pillStyle('muted'), fontSize: 9.5, padding: '0 5px' }, title: `${file.name} · ${formatBytes(file.bytes)}` },
296
+ file.name,
297
+ )),
298
+ ),
299
+ )
300
+
301
+ const pcbCard = workflowCard({
302
+ tag: 'PCB',
303
+ tagColor: C.ok,
304
+ title: COPY.order.pcbTitle,
305
+ subtitle: prepared === undefined
306
+ ? COPY.order.pcbSubtitle
307
+ : COPY.order.pcbSummary(prepared.archive.zipName, prepared.archive.files.length, zipSize ?? ''),
308
+ details: specs.length === 0
309
+ ? [{ label: COPY.order.boardFile, value: boardTitle }]
310
+ : specs,
311
+ action: COPY.order.pcbAction,
312
+ onAction: () => { void submit('pcb') },
313
+ busy: placing === 'pcb',
314
+ locked: placing !== undefined && placing !== 'pcb',
315
+ ...(configured && prepared !== undefined
316
+ ? tokenReady ? {} : { blocked: COPY.order.signInToOrder }
317
+ : { blocked: configured ? COPY.order.waitingForPackage : COPY.order.configureToPackage }),
318
+ })
319
+
320
+ const smtCard = workflowCard({
321
+ tag: 'PCBA',
322
+ tagColor: C.info,
323
+ title: COPY.order.smtTitle,
324
+ subtitle: assembly === undefined
325
+ ? COPY.order.smtSubtitle
326
+ : COPY.order.smtSummary(assembly.positions, assembly.bomLines, formatBytes(assembly.bomBytes + assembly.positionsBytes)),
327
+ details: [
328
+ { label: COPY.order.placements, value: assembly === undefined ? '—' : String(assembly.positions) },
329
+ { label: COPY.order.bomLines, value: assembly === undefined ? '—' : String(assembly.bomLines) },
330
+ { label: COPY.order.credential, value: tokenReady ? COPY.order.signedIn : COPY.order.signedOut },
331
+ ],
332
+ action: COPY.order.smtAction,
333
+ onAction: () => { void submit('smt') },
334
+ busy: placing === 'smt',
335
+ locked: placing !== undefined && placing !== 'smt',
336
+ ...(assembly === undefined
337
+ ? { blocked: COPY.order.selectRootSchematic }
338
+ : tokenReady
339
+ ? {}
340
+ : { blocked: COPY.order.signInToOrderSmt }),
341
+ })
342
+
343
+ const agentHint = createElement(
344
+ 'div',
345
+ { style: { ...ROW, gap: 4, paddingTop: 2 } },
346
+ createElement('span', { style: { fontSize: 10, color: C.text3 } }, COPY.order.agentEntryPoints),
347
+ ...['quote_pcb', 'place_pcb_order', 'quote_smt', 'place_smt_order'].map(name => createElement(
348
+ 'span', { key: name, style: { ...pillStyle('muted'), fontSize: 9.5 } }, name,
349
+ )),
350
+ )
351
+
352
+ const resultCard = placed === undefined ? null : createElement(
353
+ 'div',
354
+ { style: cardStyle({ borderColor: 'rgba(52,211,153,0.4)' }), 'data-hardware-order-result': placed.kind },
355
+ createElement('div', { style: SPREAD },
356
+ createElement('span', { style: SECTION_TITLE },
357
+ placed.kind === 'pcb' ? COPY.order.resultTitlePcb : COPY.order.resultTitleSmt),
358
+ createElement('span', { style: pillStyle(placed.launched ? 'ok' : 'muted') },
359
+ placed.launched ? COPY.order.resultLaunched : COPY.order.resultReady),
360
+ ),
361
+ // The host sends its own English sentence in `placed.message`; the visible
362
+ // copy is derived here so the panel speaks one language. The host string is
363
+ // kept on the object for tooling, not rendered.
364
+ createElement('p', { style: MUTED },
365
+ placed.launched
366
+ ? COPY.order.resultLaunchedMessage(placed.kind === 'pcb' ? 'PCB' : COPY.order.smtShort)
367
+ : COPY.order.resultReadyMessage(placed.kind === 'pcb' ? 'PCB' : COPY.order.smtShort)),
368
+ createElement('a', {
369
+ style: LINK, href: placed.orderUrl, target: '_blank', rel: 'noreferrer noopener',
370
+ 'data-hardware-order-url': true,
371
+ }, placed.orderUrl),
372
+ createElement('p', { style: { ...MUTED, fontSize: 10 } }, COPY.order.resultNote),
373
+ createElement('div', { style: ROW },
374
+ createElement('button', {
375
+ type: 'button',
376
+ style: { ...buttonStyle('primary'), ...disabled(reopening) },
377
+ disabled: reopening,
378
+ 'data-hardware-order-reopen': true,
379
+ onClick: () => { void reopen() },
380
+ }, reopening ? COPY.order.opening : COPY.order.openInBrowser),
381
+ createElement('button', { type: 'button', style: buttonStyle('secondary'), onClick: () => { void copy() } },
382
+ copied ? COPY.order.copied : COPY.order.copyUrl),
383
+ createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10 } },
384
+ `${placed.archive.zipName} · ${formatBytes(placed.archive.zipBytes)}`),
385
+ ),
386
+ )
387
+
388
+
389
+ return createElement(
390
+ 'div',
391
+ { style: { position: 'relative', display: 'flex', flexDirection: 'column', gap: 10, minHeight: 0 }, 'data-hardware-order': true },
392
+ header,
393
+ ...(message === undefined ? [] : [createElement('p', {
394
+ key: 'message', role: 'status', style: { ...MUTED, color: C.warn, borderLeft: `2px solid ${C.warn}`, paddingLeft: 8 },
395
+ }, message)]),
396
+ createElement(
397
+ 'div',
398
+ { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))', gap: 10 } },
399
+ pcbCard,
400
+ smtCard,
401
+ ),
402
+ createElement(
403
+ 'div',
404
+ { style: { ...SPREAD, ...cardStyle({ flexDirection: 'row', alignItems: 'center' }) } },
405
+ createElement('span', { style: { fontSize: 11, color: C.text2 } }, COPY.order.batch),
406
+ createElement(
407
+ 'select',
408
+ {
409
+ style: { ...SELECT, width: 'auto' }, value: quantity,
410
+ 'data-hardware-order-quantity': true,
411
+ onChange: (event: { currentTarget: HTMLSelectElement }) => { setQuantity(Number(event.currentTarget.value)) },
412
+ },
413
+ ...QUANTITIES.map(count => createElement('option', { key: count, value: count }, COPY.order.batchUnits(count))),
414
+ ),
415
+ createElement('span', { style: { ...MUTED, ...MONO_TEXT, fontSize: 10 } }, COPY.order.quoteBasis(quantity)),
416
+ ),
417
+ packageCard,
418
+ resultCard,
419
+ // One click uploads: say so where the click happens, not in a dialog after it.
420
+ createElement('p', { style: { ...MUTED, fontSize: 10 }, 'data-hardware-order-hint': true }, COPY.order.uploadHint),
421
+ agentHint,
422
+ )
423
+ }