@huaqiu/dsh-hardware-ui 0.7.22 → 0.7.24

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-hardware-ui",
3
- "version": "0.7.22",
3
+ "version": "0.7.24",
4
4
  "type": "module",
5
5
  "description": "Hardware Engineering product UI for DSH: five-destination engineering navigation, right-panel artifact viewer, CAD installation settings and contextual native-application actions.",
6
6
  "license": "MIT",
@@ -468,6 +468,7 @@ export const COPY = {
468
468
  get 'too-large'(): string { return translateCopy('errors.too-large') },
469
469
  get 'export-timeout'(): string { return translateCopy('errors.export-timeout') },
470
470
  get 'export-failed'(): string { return translateCopy('errors.export-failed') },
471
+ get 'launch-failed'(): string { return translateCopy('errors.launch-failed') },
471
472
  get 'stale-revision'(): string { return translateCopy('errors.stale-revision') },
472
473
  get 'invalid-request'(): string { return translateCopy('errors.invalid-request') },
473
474
  get 'invalid-application'(): string { return translateCopy('errors.invalid-application') },
@@ -491,6 +492,9 @@ export type HardwareCopy = typeof COPY
491
492
  */
492
493
  const KEEPS_DETAIL = new Set([
493
494
  'export-failed',
495
+ // The tail is the OS-level reason a spawn failed (ENOENT, EACCES, bad image),
496
+ // which is the only part of that failure the user can act on.
497
+ 'launch-failed',
494
498
  'order-unreachable',
495
499
  'order-rejected',
496
500
  'invalid-order-url',
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Document body for `.kicad_sch` and `.kicad_pcb`.
2
+ * Document body for `.kicad_sch`, `.kicad_pcb`, `.kicad_sym` and `.kicad_mod`.
3
3
  *
4
- * One component for both kinds, because the differences are exactly three: the
5
- * parser/renderer the mount picks, the interaction hint, and whether a sheet
6
- * hierarchy is disclosed. Splitting it in two would duplicate the whole
7
- * lifecycle to vary three strings.
4
+ * One component for four kinds, because the differences are few: the
5
+ * parser/renderer the mount picks, the label, whether a sheet hierarchy is
6
+ * disclosed, and whether a library needs a symbol picker. Splitting it in four
7
+ * would duplicate the whole lifecycle to vary a handful of strings.
8
8
  *
9
9
  * Lifecycle, in the order the document seat drives it:
10
10
  *
@@ -47,7 +47,7 @@ type SheetStatus = SheetReference & { readonly found: boolean | undefined }
47
47
 
48
48
  type BodyState =
49
49
  | { readonly phase: 'loading' }
50
- | { readonly phase: 'ready'; readonly sheets: readonly SheetStatus[] }
50
+ | { readonly phase: 'ready'; readonly sheets: readonly SheetStatus[]; readonly symbol: number }
51
51
  | { readonly phase: 'error'; readonly message: string }
52
52
 
53
53
  const STAGE: React.CSSProperties = {
@@ -73,14 +73,35 @@ const SHEETS: React.CSSProperties = {
73
73
  display: 'flex', flexDirection: 'column', gap: 2, maxHeight: '40%', overflow: 'auto',
74
74
  }
75
75
  const SHEET_ROW: React.CSSProperties = { display: 'flex', gap: 6, alignItems: 'baseline' }
76
+ const SYMBOL_PICKER: React.CSSProperties = {
77
+ position: 'absolute', left: 8, top: 8, display: 'flex', maxWidth: 'calc(100% - 16px)',
78
+ }
79
+ const SYMBOL_SELECT: React.CSSProperties = {
80
+ padding: '3px 6px', borderRadius: R.sm, border: `1px solid ${C.border}`, background: C.panel,
81
+ color: C.text, fontSize: 10.5, fontFamily: MONO, maxWidth: 220,
82
+ }
83
+
84
+ /**
85
+ * Toolbar/document label per kind.
86
+ *
87
+ * Read through the copy facade at render time, so a language switch follows
88
+ * without the component re-registering anything.
89
+ */
90
+ const VIEWER_TITLE: Readonly<Record<EcadDocumentKind, () => string>> = {
91
+ schematic: () => DOCUMENT_COPY.viewer.schematic,
92
+ pcb: () => DOCUMENT_COPY.viewer.pcb,
93
+ symbol: () => DOCUMENT_COPY.viewer.symbol,
94
+ footprint: () => DOCUMENT_COPY.viewer.footprint,
95
+ }
76
96
 
77
97
  /** Human-readable text for a mount failure, keyed by the reason it carries. */
78
- function failureText(error: unknown): string {
98
+ function failureText(error: unknown, kind: EcadDocumentKind): string {
79
99
  const copy = DOCUMENT_COPY.state
80
100
  if (error instanceof DocumentRenderError) {
81
101
  if (error.reason === 'parse') return copy.parseFailed(error.message)
82
102
  if (error.reason === 'toolarge') return copy.tooLarge('32 MB')
83
103
  if (error.reason === 'aborted') return copy.aborted
104
+ if (error.reason === 'empty') return kind === 'footprint' ? copy.emptyFootprint : copy.emptySymbolLibrary
84
105
  return copy.renderFailed(error.message)
85
106
  }
86
107
  return copy.renderFailed(error instanceof Error ? error.message : String(error))
@@ -102,6 +123,10 @@ export function EcadBody(props: EcadBodyProps): ReactNode {
102
123
  const { tab } = props.useTabInfo()
103
124
  const host = useRef<HTMLDivElement | null>(null)
104
125
  const [state, setState] = useState<BodyState>({ phase: 'loading' })
126
+ // The library's own names, kept across a re-mount so the picker keeps its
127
+ // options while the next symbol draws instead of blinking out of existence.
128
+ const [library, setLibrary] = useState<readonly string[]>([])
129
+ const [selected, setSelected] = useState(0)
105
130
  const data = content.kind === 'bytes' ? content.data : undefined
106
131
  const path = useMemo(() => documentFilePath(resourceAddress)?.path, [resourceAddress])
107
132
 
@@ -116,7 +141,7 @@ export function EcadBody(props: EcadBodyProps): ReactNode {
116
141
  void (async () => {
117
142
  const text = decodeDocumentText(data)
118
143
  let references: readonly SheetReference[] = []
119
- let live: { dispose(): void }
144
+ let live: { dispose(): void; symbols: readonly string[] }
120
145
  if (kind === 'schematic') {
121
146
  // Parsing once for the hierarchy keeps the disclosure and the render
122
147
  // reading the same model: a sheet list that disagreed with the picture
@@ -125,7 +150,10 @@ export function EcadBody(props: EcadBodyProps): ReactNode {
125
150
  references = sheetReferences(parsed, path ?? '')
126
151
  live = await mountEcadDocument({ kind, text, container, signal: lifetime, parsed })
127
152
  } else {
128
- live = await mountEcadDocument({ kind, text, container, signal: lifetime })
153
+ live = await mountEcadDocument({
154
+ kind, text, container, signal: lifetime,
155
+ ...(kind === 'symbol' ? { symbolIndex: selected } : {}),
156
+ })
129
157
  }
130
158
  mounted = live
131
159
  if (lifetime.aborted) {
@@ -135,17 +163,25 @@ export function EcadBody(props: EcadBodyProps): ReactNode {
135
163
  mounted = undefined
136
164
  return
137
165
  }
138
- setState({ phase: 'ready', sheets: references.map(reference => ({ ...reference, found: undefined })) })
166
+ setLibrary(live.symbols)
167
+ // The mount clamps a selection that outlived a smaller library, so the
168
+ // picker reports the symbol actually drawn rather than the one requested.
169
+ setSelected(index => (live.symbols.length === 0 ? 0 : Math.min(index, live.symbols.length - 1)))
170
+ setState({
171
+ phase: 'ready',
172
+ sheets: references.map(reference => ({ ...reference, found: undefined })),
173
+ symbol: live.symbols.length === 0 ? 0 : Math.min(selected, live.symbols.length - 1),
174
+ })
139
175
  })().catch((error: unknown) => {
140
176
  if (lifetime.aborted) return
141
- setState({ phase: 'error', message: failureText(error) })
177
+ setState({ phase: 'error', message: failureText(error, kind) })
142
178
  })
143
179
 
144
180
  return () => {
145
181
  controller.abort()
146
182
  mounted?.dispose()
147
183
  }
148
- }, [data, kind, path, tab.signal])
184
+ }, [data, kind, path, tab.signal, selected])
149
185
 
150
186
  // Child sheets are resolved after the picture is up: existence is a Host read
151
187
  // per reference, and a slow one must not delay the render the user asked for.
@@ -169,7 +205,7 @@ export function EcadBody(props: EcadBodyProps): ReactNode {
169
205
  if (current.phase !== 'ready') return current
170
206
  const byPath = new Map(outcomes.map(outcome => [outcome.resolved, outcome.found]))
171
207
  return {
172
- phase: 'ready',
208
+ ...current,
173
209
  sheets: current.sheets.map(sheet => (sheet.resolved === undefined || !byPath.has(sheet.resolved)
174
210
  ? sheet
175
211
  : { ...sheet, found: byPath.get(sheet.resolved) })),
@@ -188,10 +224,24 @@ export function EcadBody(props: EcadBodyProps): ReactNode {
188
224
  )}
189
225
  {state.phase === 'error' && (
190
226
  <div style={CENTER} role="alert" data-ecad-error>
191
- <p style={ERROR_TITLE}>{kind === 'schematic' ? DOCUMENT_COPY.viewer.schematic : DOCUMENT_COPY.viewer.pcb}</p>
227
+ <p style={ERROR_TITLE}>{VIEWER_TITLE[kind]()}</p>
192
228
  <p style={ERROR_LINE}>{state.message}</p>
193
229
  </div>
194
230
  )}
231
+ {library.length > 1 && state.phase !== 'error' && (
232
+ <div style={SYMBOL_PICKER} data-ecad-symbols>
233
+ <select
234
+ style={SYMBOL_SELECT}
235
+ aria-label={DOCUMENT_COPY.symbols.label}
236
+ value={String(state.phase === 'ready' ? state.symbol : Math.min(selected, library.length - 1))}
237
+ onChange={(event) => { setSelected(Number(event.target.value)) }}
238
+ >
239
+ {library.map((name, index) => (
240
+ <option key={`${index}:${name}`} value={index}>{name}</option>
241
+ ))}
242
+ </select>
243
+ </div>
244
+ )}
195
245
  {state.phase === 'ready' && sheets.length === 0 && (
196
246
  <span style={HINT} data-ecad-hint>{DOCUMENT_COPY.hint.schematic}</span>
197
247
  )}
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Document body for the mesh formats: STL, 3MF, OBJ, glTF/GLB, PLY, AMF.
3
+ *
4
+ * Same shape as `StepBody` — bytes in, picture out, no derived artefact, so a
5
+ * changed file arrives as a new byte array and simply re-runs the effect — with
6
+ * two differences the task asks for:
7
+ *
8
+ * - The status line states what was actually read: the format, the unit and
9
+ * where the unit came from, how many objects and materials, and any companion
10
+ * that could not be loaded. §5.7 forbids presenting a model of unknown units as
11
+ * if its dimensions were authoritative, and the cheapest honest answer is to
12
+ * say "unit unknown" instead of drawing a ruler nobody asked for.
13
+ * - A companion failure is a warning, not a failure. The model still renders and
14
+ * the line says which file was missing (§5.4).
15
+ *
16
+ * Layout and states are shared with the STEP body on purpose: one 3D document
17
+ * looks like another until the status line says otherwise.
18
+ *
19
+ * @module @huaqiu/dsh-hardware-ui/client/document/ModelBody
20
+ */
21
+
22
+ import { useEffect, useRef, useState, type ReactNode } from 'react'
23
+ import { C, MONO, R } from '../theme.js'
24
+ import { DOCUMENT_COPY } from './copy.js'
25
+ import type { DocumentBodyProps } from './contract.js'
26
+ import { DocumentRenderError } from './mount.js'
27
+ import { documentFilePath } from './paths.js'
28
+ import { modelAdapterFor, mountModelDocument } from './model/index.js'
29
+ import type { CompanionReader, ModelMetadata } from './model/types.js'
30
+
31
+ /** Props the registration injects for the mesh kind. */
32
+ export interface ModelBodyInjected {
33
+ /**
34
+ * Reads a companion file — the MTL of an OBJ, the buffers and textures of a
35
+ * glTF — through DSH's own bounded file read.
36
+ *
37
+ * Absent on a Host without a workspace remote, or without the absolute path a
38
+ * companion must resolve against; the adapters treat that as "no companion
39
+ * could be read" rather than as a failure (§5.4).
40
+ */
41
+ readonly readCompanion?: CompanionReader
42
+ }
43
+
44
+ /** Standard document props plus the companion reader. */
45
+ export type ModelBodyProps = DocumentBodyProps & ModelBodyInjected
46
+
47
+ type ModelState =
48
+ | { readonly phase: 'loading' }
49
+ | { readonly phase: 'ready'; readonly metadata: ModelMetadata; readonly format: string }
50
+ | { readonly phase: 'error'; readonly message: string }
51
+
52
+ const STAGE: React.CSSProperties = {
53
+ position: 'relative', width: '100%', height: '100%', minHeight: 0, overflow: 'hidden', background: C.base,
54
+ }
55
+ const HOST: React.CSSProperties = { position: 'absolute', inset: 0 }
56
+ const CENTER: React.CSSProperties = {
57
+ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center',
58
+ justifyContent: 'center', gap: 6, padding: 24, textAlign: 'center', color: C.text3, fontSize: 11, lineHeight: 1.6,
59
+ }
60
+ const ERROR_TITLE: React.CSSProperties = { margin: 0, color: C.text2, fontSize: 12, fontWeight: 600 }
61
+ const ERROR_LINE: React.CSSProperties = { margin: 0, maxWidth: 420, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }
62
+ const HINT: React.CSSProperties = {
63
+ position: 'absolute', right: 8, bottom: 8, padding: '2px 8px', borderRadius: R.pill,
64
+ background: 'rgba(0,0,0,0.55)', color: '#e4e4e7', fontSize: 10, fontFamily: MONO,
65
+ pointerEvents: 'none', maxWidth: 'calc(100% - 16px)',
66
+ }
67
+
68
+ /** Human-readable text for a mesh-format failure. */
69
+ export function modelFailureText(error: unknown, format?: string): string {
70
+ const copy = DOCUMENT_COPY.state
71
+ if (error instanceof DocumentRenderError) {
72
+ if (error.reason === 'parse') return copy.modelInvalid(format ?? DOCUMENT_COPY.viewer.model)
73
+ // The document parsed; a file it points at did not arrive. Saying which file
74
+ // is the whole point (§5.4, §9).
75
+ if (error.reason === 'missing-companion') return copy.modelMissing(format ?? DOCUMENT_COPY.viewer.model, error.message)
76
+ if (error.reason === 'toolarge') return copy.tooLarge('64 MB')
77
+ if (error.reason === 'aborted') return copy.aborted
78
+ if (error.message.includes('webgl')) return copy.noWebgl
79
+ return copy.renderFailed(error.message)
80
+ }
81
+ return copy.renderFailed(error instanceof Error ? error.message : String(error))
82
+ }
83
+
84
+ /**
85
+ * The status line: format, unit honesty, and what loaded.
86
+ *
87
+ * Segments, not one sentence: an STL has no declared unit, so its line reads
88
+ * `STL · 单位未知 · 1 个对象` rather than claiming millimetres, and a model with
89
+ * no materials simply has one segment fewer (§5.7, §5.8).
90
+ * @param metadata - what the adapter reported.
91
+ * @param format - extension-shaped format name.
92
+ * @returns the sentence shown over the model.
93
+ */
94
+ export function modelStatusText(metadata: ModelMetadata, format: string): string {
95
+ const copy = DOCUMENT_COPY.model
96
+ const parts = [
97
+ format.toUpperCase(),
98
+ metadata.units === 'unknown' ? copy.unitUnknown : copy.unit(metadata.units),
99
+ copy.objects(metadata.objectCount),
100
+ ]
101
+ if (metadata.materials > 0) parts.push(copy.materials(metadata.materials))
102
+ if (metadata.warnings.length > 0) parts.push(copy.warnings(metadata.warnings.length))
103
+ return parts.join(copy.separator)
104
+ }
105
+
106
+ /**
107
+ * The tooltip behind the status line.
108
+ *
109
+ * Two facts do not fit on the line: the model's own declared title (3MF's
110
+ * `Title` metadata is the only human name some files carry) and *which*
111
+ * companions failed to load. Both are one hover away instead of absent (§5.4).
112
+ * @param metadata - what the adapter reported.
113
+ * @returns the tooltip text, or undefined when there is nothing to add.
114
+ */
115
+ export function modelHintText(metadata: ModelMetadata): string | undefined {
116
+ const tips: string[] = []
117
+ if (metadata.title !== undefined && metadata.title !== '') tips.push(metadata.title)
118
+ if (metadata.warnings.length > 0) tips.push(DOCUMENT_COPY.model.missing(metadata.warnings.join('、')))
119
+ return tips.length === 0 ? undefined : tips.join('\n')
120
+ }
121
+
122
+ /**
123
+ * Render one mesh document inside its tab.
124
+ * @param props - document bytes, tab lifetime, companion reader.
125
+ * @returns the model, a loading line, or an in-document explanation.
126
+ */
127
+ export function ModelBody(props: ModelBodyProps): ReactNode {
128
+ const { content, resourceAddress } = props
129
+ const { tab } = props.useTabInfo()
130
+ const host = useRef<HTMLDivElement | null>(null)
131
+ const [state, setState] = useState<ModelState>({ phase: 'loading' })
132
+ const data = content.kind === 'bytes' ? content.data : undefined
133
+ // The Host's absolute path is the base for companion files; the address is the
134
+ // fallback, and it is enough because the Host resolves workspace-relative reads.
135
+ const meta = props.useResource?.(resourceAddress)
136
+ const path = meta?.value?.absolutePath ?? documentFilePath(resourceAddress)?.path
137
+ const adapter = modelAdapterFor(path ?? '')
138
+ // Read through a ref, not through the dependency array: the reader is a
139
+ // function of the session, which cannot change within one mount, and an
140
+ // unstable identity here would restart the mount on every render.
141
+ const companionOf = useRef(props.readCompanion)
142
+ companionOf.current = props.readCompanion
143
+ const readCompanion = companionOf.current
144
+
145
+ useEffect(() => {
146
+ const container = host.current
147
+ if (data === undefined || container === null) return
148
+ const controller = new AbortController()
149
+ const lifetime = AbortSignal.any([tab.signal, controller.signal])
150
+ let mounted: { dispose(): void } | undefined
151
+ setState({ phase: 'loading' })
152
+
153
+ void (async () => {
154
+ const live = await mountModelDocument({
155
+ bytes: data,
156
+ ...(path === undefined ? {} : { path }),
157
+ container,
158
+ signal: lifetime,
159
+ ...(readCompanion === undefined ? {} : { readCompanion }),
160
+ })
161
+ mounted = live
162
+ if (lifetime.aborted) {
163
+ live.dispose()
164
+ mounted = undefined
165
+ return
166
+ }
167
+ setState({ phase: 'ready', metadata: live.metadata, format: live.format })
168
+ })().catch((error: unknown) => {
169
+ if (lifetime.aborted) return
170
+ setState({ phase: 'error', message: modelFailureText(error, adapter?.label) })
171
+ })
172
+
173
+ return () => {
174
+ controller.abort()
175
+ mounted?.dispose()
176
+ }
177
+ // `readCompanion` and `adapter` are deliberately absent: both are stable for
178
+ // the life of a mount, and re-running the effect for them would rebuild the
179
+ // scene for no change in the document.
180
+ // eslint-disable-next-line react-hooks/exhaustive-deps
181
+ }, [data, tab.signal, path])
182
+
183
+ return (
184
+ <div data-model-preview style={STAGE}>
185
+ <div ref={host} style={HOST} data-model-host />
186
+ {state.phase === 'loading' && (
187
+ <p style={CENTER} data-model-loading>{DOCUMENT_COPY.state.modelLoading(adapter?.label ?? '3D')}</p>
188
+ )}
189
+ {state.phase === 'error' && (
190
+ <div style={CENTER} role="alert" data-model-error>
191
+ <p style={ERROR_TITLE}>{DOCUMENT_COPY.viewer.model}</p>
192
+ <p style={ERROR_LINE}>{state.message}</p>
193
+ </div>
194
+ )}
195
+ {state.phase === 'ready' && (
196
+ <span style={HINT} data-model-hint title={modelHintText(state.metadata)}>
197
+ {modelStatusText(state.metadata, state.format)}
198
+ </span>
199
+ )}
200
+ </div>
201
+ )
202
+ }