@huaqiu/dsh-hardware-ui 0.7.23 → 0.7.25

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,313 @@
1
+ /**
2
+ * `Open in KiCad` / `Open in SolidCraft` — one document action, two targets.
3
+ *
4
+ * Both actions are the same component with a different `application` in its
5
+ * injected face, registered twice on DSH's own
6
+ * `sidebar.right.tab.document.actions` list. That list is rendered by the
7
+ * document owner in the preview header *once the file's Host path is known* and
8
+ * not at all otherwise, which is why nothing here invents, guesses or validates
9
+ * a path: the owner hands over an absolute path or does not render the slot.
10
+ *
11
+ * The split of responsibility is the point of §4 of the toolchain-aware
12
+ * open-in-app task:
13
+ *
14
+ * 1. *Which application?* The Host answers with a verified format list per
15
+ * application (`inputFormats`). A suffix nobody claims renders nothing —
16
+ * the mapping is capability evidence, never a table of guesses.
17
+ * 2. *Can it be launched?* The Host's installation report answers, and for
18
+ * KiCad it answers per document type: the action is offered only when the
19
+ * editor that owns this suffix resolved (`eeschema` / `pcbnew` / `kicad`),
20
+ * because that is the executable the launch will actually use. A validated
21
+ * `kicad-cli` never enables a document hand-off, and a GUI-only KiCad is
22
+ * still usable even though the toolchain verdict calls it unconfigured.
23
+ * 3. *Did it launch?* The `/open` route resolves only after the child process
24
+ * actually spawned, so what is reported is the Host's confirmation rather
25
+ * than the click.
26
+ *
27
+ * An unavailable action is drawn muted with its reason in the tooltip *and* in
28
+ * the existing notice channel on click, pointing at Settings → Hardware
29
+ * Engineering instead of a second onboarding flow (§5).
30
+ *
31
+ * The MDI tab is untouched: this hands a file to an external editor, it does
32
+ * not navigate, close, save or replace the document being previewed. The
33
+ * external process is detached by the Host, so closing the tab never terminates
34
+ * it (§6).
35
+ *
36
+ * *Saving before launch* has nothing to call: DSH's workspace-files service
37
+ * exposes read operations only, and a document tab carries no dirty flag, so
38
+ * there is no unsaved buffer this action could flush — the bodies this product
39
+ * registers are read-only renderers of what is already on disk. What remains
40
+ * implementable is the other half of §6, and the Host does it: it canonicalizes
41
+ * the path and re-checks that the file still exists immediately before spawning,
42
+ * so a document deleted or replaced between the click and the launch is refused
43
+ * instead of opened.
44
+ *
45
+ * @module @huaqiu/dsh-hardware-ui/client/document/OpenInApplicationAction
46
+ */
47
+
48
+ import { useEffect, useRef, useState, type ReactNode } from 'react'
49
+ import { C, R, buttonStyle } from '../theme.js'
50
+ import { DOCUMENT_COPY } from './copy.js'
51
+ import type { DocumentActionOwner } from './contract.js'
52
+ import { displayName } from './paths.js'
53
+ import { messageOf } from '../transport.js'
54
+ import type { InstallationsInfo, NativeApplication } from '../model.js'
55
+
56
+ /** The applications this action can hand a document to, in routing order. */
57
+ export const APPLICATIONS: readonly NativeApplication[] = Object.freeze(['kicad', 'solidcraft'])
58
+
59
+ /**
60
+ * The product's own name, used as `{app}` in every sentence this action says.
61
+ *
62
+ * A proper noun is not translated, so it lives here rather than in the locale
63
+ * dictionaries; what changes with the language is the sentence around it.
64
+ * @param application - the target application.
65
+ * @returns `KiCad` or `SolidCraft`.
66
+ */
67
+ export function applicationName(application: NativeApplication): string {
68
+ return application === 'kicad' ? 'KiCad' : 'SolidCraft'
69
+ }
70
+
71
+ /** What the action needs from the Host half of the product. */
72
+ export interface ApplicationActionInjected {
73
+ /** The one application this registration speaks for. */
74
+ application: NativeApplication
75
+ /** Current installation report; read on mount and again when it changes. */
76
+ installations: () => Promise<InstallationsInfo>
77
+ /** Launch the configured GUI with this path; resolves after spawn. */
78
+ open: (absolutePath: string) => Promise<void>
79
+ /** The product's existing transient notice channel — no second toast system. */
80
+ notify: (tone: 'ok' | 'warn' | 'error' | 'info', text: string) => void
81
+ /**
82
+ * Called when the Host's toolchain configuration changes while DSH is
83
+ * running, so availability and the executable behind it are re-derived from
84
+ * the new installation rather than a stale report (§5).
85
+ */
86
+ subscribe?: (listener: () => void) => () => void
87
+ }
88
+
89
+ /** Standard header-action props plus the Host face. */
90
+ export type ApplicationActionProps = DocumentActionOwner & ApplicationActionInjected
91
+
92
+ /**
93
+ * What the action can do right now.
94
+ *
95
+ * `checking` and `unsupported` both render nothing: the first because a guess
96
+ * would flash, the second because a button that can never work — or that this
97
+ * application cannot serve — is noise the document header does not need.
98
+ */
99
+ export type Gate =
100
+ | { readonly phase: 'checking' }
101
+ | { readonly phase: 'supported' }
102
+ | { readonly phase: 'unsupported' }
103
+ | { readonly phase: 'unavailable'; readonly reason: string }
104
+
105
+ const BUTTON: React.CSSProperties = {
106
+ ...buttonStyle('quiet', { padding: '2px 8px', fontSize: 11, borderRadius: R.pill }),
107
+ whiteSpace: 'nowrap',
108
+ }
109
+ const MUTED: React.CSSProperties = { ...BUTTON, color: C.text3, cursor: 'not-allowed' }
110
+
111
+ /** Lower-case extension including the dot, or `''` for a name with none. */
112
+ export function extensionOf(path: string): string {
113
+ const name = displayName(path)
114
+ const dot = name.lastIndexOf('.')
115
+ return dot <= 0 ? '' : name.slice(dot).toLowerCase()
116
+ }
117
+
118
+ /**
119
+ * Which KiCad editor owns a document suffix.
120
+ *
121
+ * Kept next to the gate because it is the evidence the gate needs: KiCad is one
122
+ * application with three editors, and the launch resolves a different
123
+ * executable per suffix. A suffix the Host lists but this map does not know is
124
+ * withheld rather than guessed — the failure mode is a missing button, never a
125
+ * document opened by the wrong editor.
126
+ */
127
+ const KICAD_EDITORS: Readonly<Record<string, 'schematicEditor' | 'pcbEditor' | 'projectManager'>> = Object.freeze({
128
+ '.kicad_sch': 'schematicEditor',
129
+ '.kicad_pcb': 'pcbEditor',
130
+ '.kicad_pro': 'projectManager',
131
+ })
132
+
133
+ /** The configuration facts either gate reads, for one application. */
134
+ type Formats = readonly string[] | undefined
135
+
136
+ /** Does a Host format list claim this suffix? Case-insensitive both ways. */
137
+ function claims(formats: Formats, extension: string): boolean {
138
+ return extension !== '' && formats !== undefined
139
+ && formats.some(format => format.toLowerCase() === extension)
140
+ }
141
+
142
+ /**
143
+ * Decide what the header should offer this document for one application.
144
+ *
145
+ * Exported because the decision is the part worth testing: it is a pure function
146
+ * of the Host's report and the document's own suffix, and every rule above
147
+ * (verified formats, per-format editors, independent GUI/CLI) lives here.
148
+ * @param application - the application this registration speaks for.
149
+ * @param absolutePath - the document the header is showing, as the Host named it.
150
+ * @param installed - the Host's installation report.
151
+ * @returns the gate this document falls into.
152
+ */
153
+ export function applicationGate(
154
+ application: NativeApplication,
155
+ absolutePath: string,
156
+ installed: InstallationsInfo,
157
+ ): Gate {
158
+ const extension = extensionOf(absolutePath)
159
+ const name = applicationName(application)
160
+
161
+ if (application === 'solidcraft') {
162
+ const solidcraft = installed.solidcraft
163
+ // Without the Host's verified list there is nothing this action may claim,
164
+ // so it offers nothing — the list is capability evidence, not a default.
165
+ if (solidcraft === undefined || !claims(solidcraft.inputFormats, extension)) {
166
+ return { phase: 'unsupported' }
167
+ }
168
+ // A configured CLI proves nothing about the GUI (§6.2 of the 3D/SolidCraft
169
+ // task), so the two are read separately and only the GUI enables a launch.
170
+ if (solidcraft.configured !== true) {
171
+ return { phase: 'unavailable', reason: DOCUMENT_COPY.action.notConfigured(name) }
172
+ }
173
+ if (solidcraft.guiAvailable !== true) {
174
+ return { phase: 'unavailable', reason: DOCUMENT_COPY.action.noGui(name) }
175
+ }
176
+ return { phase: 'supported' }
177
+ }
178
+
179
+ const kicad = installed.kicad
180
+ if (kicad === undefined || !claims(kicad.inputFormats, extension)) return { phase: 'unsupported' }
181
+ // The editor for *this* suffix is the evidence. `configured` is the
182
+ // toolchain's CLI-anchored verdict, so it cannot decide a document hand-off:
183
+ // a GUI-only install has editors and no verdict, and a CLI-only one has the
184
+ // reverse. Ask about the executable the launch will actually use.
185
+ const field = KICAD_EDITORS[extension]
186
+ if (field === undefined) {
187
+ // The Host lists a suffix this action has no editor route for. Withholding
188
+ // it is the only safe answer: offering it would open the wrong window.
189
+ return { phase: 'unavailable', reason: DOCUMENT_COPY.action.noEditor(name, extension) }
190
+ }
191
+ if (kicad[field] !== undefined) return { phase: 'supported' }
192
+ if (kicad.guiAvailable !== true && kicad.configured !== true) {
193
+ return { phase: 'unavailable', reason: DOCUMENT_COPY.action.notConfigured(name) }
194
+ }
195
+ return { phase: 'unavailable', reason: DOCUMENT_COPY.action.noEditor(name, extension) }
196
+ }
197
+
198
+ /** The application that claims a document, and what it can do with it. */
199
+ export interface DocumentRoute {
200
+ readonly application: NativeApplication
201
+ readonly gate: Gate
202
+ }
203
+
204
+ /**
205
+ * Route one document to the application that verifiably opens it.
206
+ *
207
+ * The two Host lists are disjoint today (a KiCad project file is not a SolidCraft
208
+ * input), so the first match is the only match; if they ever overlapped, the
209
+ * first entry of {@link APPLICATIONS} wins deterministically rather than the
210
+ * document offering two different editors for one suffix.
211
+ * @param absolutePath - the previewed document.
212
+ * @param installed - the Host's installation report.
213
+ * @returns the claiming application and its gate, or undefined for no route.
214
+ */
215
+ export function routeDocument(absolutePath: string, installed: InstallationsInfo): DocumentRoute | undefined {
216
+ for (const application of APPLICATIONS) {
217
+ const gate = applicationGate(application, absolutePath, installed)
218
+ if (gate.phase !== 'unsupported') return { application, gate }
219
+ }
220
+ return undefined
221
+ }
222
+
223
+ /**
224
+ * Render the header action for the previewed document.
225
+ * @param props - the document's absolute path, the target application, and the Host face.
226
+ * @returns the button, or null when this document has no hand-off to that application.
227
+ */
228
+ export function OpenInApplicationAction(props: ApplicationActionProps): ReactNode {
229
+ const { absolutePath, application, installations, open, notify, subscribe } = props
230
+ const [gate, setGate] = useState<Gate>({ phase: 'checking' })
231
+ const [busy, setBusy] = useState(false)
232
+ const [launched, setLaunched] = useState(false)
233
+ const name = displayName(absolutePath)
234
+ /** The path the current gate was computed for; a new document re-checks. */
235
+ const gatedFor = useRef<string | undefined>(undefined)
236
+ const app = applicationName(application)
237
+
238
+ useEffect(() => {
239
+ let live = true
240
+ const read = (): void => {
241
+ void installations()
242
+ .then((installed) => {
243
+ if (live) setGate(applicationGate(application, absolutePath, installed))
244
+ })
245
+ .catch(() => {
246
+ // Without a readable installation report the honest answer is "cannot
247
+ // offer", not "available" — a launch would only fail later.
248
+ if (live) setGate({ phase: 'unsupported' })
249
+ })
250
+ }
251
+ // A different document is a different question; the same document is not,
252
+ // so a configuration change re-reads without blanking the header first.
253
+ if (gatedFor.current !== absolutePath) {
254
+ gatedFor.current = absolutePath
255
+ setGate({ phase: 'checking' })
256
+ }
257
+ read()
258
+ // The Host's configuration is live: a settings write re-reads the report
259
+ // here instead of needing a DSH restart (§5).
260
+ const stop = subscribe?.(read)
261
+ return () => {
262
+ live = false
263
+ stop?.()
264
+ }
265
+ }, [absolutePath, application, installations, subscribe])
266
+
267
+ if (gate.phase === 'checking' || gate.phase === 'unsupported') return null
268
+
269
+ const launch = (): void => {
270
+ if (gate.phase === 'unavailable') {
271
+ notify('warn', gate.reason)
272
+ return
273
+ }
274
+ if (busy) return
275
+ setBusy(true)
276
+ setLaunched(false)
277
+ void open(absolutePath)
278
+ .then(() => {
279
+ setLaunched(true)
280
+ notify('ok', DOCUMENT_COPY.action.launched(app, name))
281
+ })
282
+ .catch((error: unknown) => {
283
+ // The Host's own sentence for a spawn failure keeps the OS reason
284
+ // (`transport.request` maps `launch-failed`), and the frame around it
285
+ // says which action failed, not which route did.
286
+ notify('error', DOCUMENT_COPY.action.failed(app, messageOf(error)))
287
+ })
288
+ .finally(() => { setBusy(false) })
289
+ }
290
+
291
+ const label = busy ? DOCUMENT_COPY.action.opening(app) : DOCUMENT_COPY.action.open(app)
292
+ const title = gate.phase === 'unavailable'
293
+ ? gate.reason
294
+ : DOCUMENT_COPY.action.title(app, name)
295
+
296
+ return (
297
+ <button
298
+ type="button"
299
+ // Not the `disabled` attribute: a disabled control does not raise the
300
+ // tooltip that explains *why*, and that explanation is the point (§5).
301
+ aria-disabled={gate.phase === 'unavailable' || busy}
302
+ aria-busy={busy || undefined}
303
+ title={title}
304
+ onClick={launch}
305
+ style={gate.phase === 'unavailable' ? MUTED : BUTTON}
306
+ data-open-in={application}
307
+ data-open-in-state={gate.phase === 'unavailable' ? 'unavailable' : 'ready'}
308
+ data-open-in-launched={launched ? 'true' : undefined}
309
+ >
310
+ {label}
311
+ </button>
312
+ )
313
+ }
@@ -89,16 +89,45 @@ export interface DocumentTabInfo {
89
89
  }
90
90
  }
91
91
 
92
+ /** File metadata one `file` resource read exposes, as far as a body needs it. */
93
+ export interface DocumentResourceMeta {
94
+ /** Host-resolved absolute path; the base for a document's companion files. */
95
+ readonly value?: { readonly absolutePath?: string }
96
+ }
97
+
92
98
  /** Standard props of a `sidebar.right.tab.document` body. */
93
99
  export interface DocumentBodyProps extends DocumentBodyOwner {
94
100
  readonly sessionId: string
95
101
  readonly useTabInfo: () => DocumentTabInfo
102
+ /**
103
+ * The owner's own `file` resource reader (`useResource<'file'>(address)`).
104
+ *
105
+ * Supplied by the framework to every body — the Markdown body reads its image
106
+ * directory through it — but declared optional here because this package's
107
+ * structural contract is also exercised by tests that mount a body without it.
108
+ * A body must keep working when it is absent, falling back to the address.
109
+ */
110
+ readonly useResource?: (address: string) => DocumentResourceMeta
96
111
  }
97
112
 
98
- /** The slice of the slot registry this package registers through. */
113
+ /**
114
+ * The slice of the slot registry this package registers through.
115
+ *
116
+ * Two seat shapes matter here. A *keyed* slot takes `key` (the document body
117
+ * slot keys its entries by renderer id); a *list* slot takes `id` plus `order`
118
+ * (the document action list draws its entries sorted by `order`). Registering a
119
+ * list entry with a `key` instead of an `id` type-checks nowhere and silently
120
+ * does nothing at runtime, which is why both spellings are declared.
121
+ */
99
122
  export interface SlotSpec {
100
123
  readonly name: string
101
- readonly key: string
124
+ /** Keyed-slot entry key; the definition id for a document body. */
125
+ readonly key?: string
126
+ /** List-slot entry id. */
127
+ readonly id?: string
128
+ /** Position within a list slot; lower draws first. */
129
+ readonly order?: number
130
+ readonly label?: () => string
102
131
  readonly locale?: string
103
132
  readonly store?: unknown
104
133
  readonly inject?: (...args: unknown[]) => object
@@ -154,3 +183,21 @@ export interface DocumentClientContext {
154
183
 
155
184
  /** The document seat every body registers into. */
156
185
  export const DOCUMENT_BODY_SLOT = 'sidebar.right.tab.document'
186
+
187
+ /**
188
+ * The document header's action list — the seat a contextual action contributes to.
189
+ *
190
+ * Transcribed from `…/document/contract.ts:66-85` in
191
+ * `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`: a `list` slot at session
192
+ * scope whose only owner prop is the previewed file's absolute path, rendered in
193
+ * the header "once the file's Host path is known". That last clause is the reason
194
+ * the path needs no validation of its own here: an absent path means the slot is
195
+ * not rendered at all.
196
+ */
197
+ export const DOCUMENT_ACTION_SLOT = 'sidebar.right.tab.document.actions'
198
+
199
+ /** What a document action receives from the owner. */
200
+ export interface DocumentActionOwner {
201
+ /** Absolute path of the previewed file in the Host's filesystem. */
202
+ readonly absolutePath: string
203
+ }
@@ -19,6 +19,8 @@ export const DOCUMENT_COPY = {
19
19
  viewer: {
20
20
  get schematic(): string { return translateCopy('document.viewer.schematic') },
21
21
  get pcb(): string { return translateCopy('document.viewer.pcb') },
22
+ get symbol(): string { return translateCopy('document.viewer.symbol') },
23
+ get footprint(): string { return translateCopy('document.viewer.footprint') },
22
24
  get model(): string { return translateCopy('document.viewer.model') },
23
25
  },
24
26
  /** Progress and state lines. */
@@ -29,16 +31,60 @@ export const DOCUMENT_COPY = {
29
31
  parseFailed: (message: string): string => translateCopy('document.state.parseFailed', { message }),
30
32
  renderFailed: (message: string): string => translateCopy('document.state.renderFailed', { message }),
31
33
  get aborted(): string { return translateCopy('document.state.aborted') },
34
+ /** A well-formed library that holds nothing to draw. */
35
+ get emptySymbolLibrary(): string { return translateCopy('document.state.emptySymbolLibrary') },
36
+ get emptyFootprint(): string { return translateCopy('document.state.emptyFootprint') },
32
37
  /** Shown when the WebGL canvas cannot be created (no GPU, blocklisted driver). */
33
38
  get noWebgl(): string { return translateCopy('document.state.noWebgl') },
34
39
  get stepInvalid(): string { return translateCopy('document.state.stepInvalid') },
35
40
  get wasmFailed(): string { return translateCopy('document.state.wasmFailed') },
41
+ /** `format` is a format name (`STL`, `3MF`), never a file name. */
42
+ modelLoading: (format: string): string => translateCopy('document.state.modelLoading', { format }),
43
+ modelInvalid: (format: string): string => translateCopy('document.state.modelInvalid', { format }),
44
+ /** `name` is the reference the document declared, not a resolved path. */
45
+ modelMissing: (format: string, name: string): string =>
46
+ translateCopy('document.state.modelMissing', { format, name }),
36
47
  },
37
48
  /** Interaction hints overlaid on a rendered document. */
38
49
  hint: {
39
50
  get schematic(): string { return translateCopy('document.hint.schematic') },
40
51
  get model(): string { return translateCopy('document.hint.model') },
41
52
  },
53
+ /**
54
+ * The mesh-format status line.
55
+ *
56
+ * Composed from segments rather than one template so nothing has to render a
57
+ * placeholder it has no value for: a model with no materials simply has one
58
+ * segment fewer, instead of "0 种材质" pretending to be information.
59
+ */
60
+ model: {
61
+ get separator(): string { return translateCopy('document.model.separator') },
62
+ get unitUnknown(): string { return translateCopy('document.model.unitUnknown') },
63
+ unit: (unit: string): string => translateCopy('document.model.unit', { unit }),
64
+ objects: (count: number): string => translateCopy('document.model.objects', { count }),
65
+ materials: (count: number): string => translateCopy('document.model.materials', { count }),
66
+ warnings: (count: number): string => translateCopy('document.model.warnings', { count }),
67
+ /** The tooltip listing the companions that could not be read. */
68
+ missing: (list: string): string => translateCopy('document.model.missing', { list }),
69
+ },
70
+ /**
71
+ * The contextual document-header action, for both applications.
72
+ *
73
+ * One group, not one per tool: `app` is the product's own name (`KiCad`,
74
+ * `SolidCraft`), which is never translated, and the sentence around it is.
75
+ * Both registrations read these, so the two buttons cannot drift into two
76
+ * slightly different experiences (§4 of the toolchain-aware task).
77
+ */
78
+ action: {
79
+ open: (app: string): string => translateCopy('document.actions.openIn', { app }),
80
+ title: (app: string, name: string): string => translateCopy('document.actions.openInTitle', { app, name }),
81
+ opening: (app: string): string => translateCopy('document.actions.opening', { app }),
82
+ notConfigured: (app: string): string => translateCopy('document.actions.notConfigured', { app }),
83
+ noGui: (app: string): string => translateCopy('document.actions.noGui', { app }),
84
+ noEditor: (app: string, ext: string): string => translateCopy('document.actions.noEditor', { app, ext }),
85
+ launched: (app: string, name: string): string => translateCopy('document.actions.launched', { app, name }),
86
+ failed: (app: string, detail: string): string => translateCopy('document.actions.failed', { app, detail }),
87
+ },
42
88
  /** Child-sheet disclosure under a schematic. */
43
89
  sheets: {
44
90
  title: (count: number): string => translateCopy('document.sheets.title', { count }),
@@ -46,4 +92,14 @@ export const DOCUMENT_COPY = {
46
92
  found: (label: string): string => translateCopy('document.sheets.found', { label }),
47
93
  get hint(): string { return translateCopy('document.sheets.hint') },
48
94
  },
95
+ /**
96
+ * The symbol picker over a library.
97
+ *
98
+ * A `.kicad_sym` holds many symbols and the renderer draws one, so the choice
99
+ * has to be visible: the label names the control, and the options are the
100
+ * symbols' own names, which are never translated.
101
+ */
102
+ symbols: {
103
+ get label(): string { return translateCopy('document.symbols.label') },
104
+ },
49
105
  }
@@ -1,13 +1,20 @@
1
1
  /**
2
2
  * Registration of the Hardware Engineering document renderers.
3
3
  *
4
- * The whole point of this module is how little it does: four file extensions
5
- * become four entries in DSH's existing document-preview registry, and the
4
+ * The whole point of this module is how little it does: a handful of file
5
+ * extensions become entries in DSH's existing document-preview registry, and the
6
6
  * existing `text` tab type — which already claims every workspace file — renders
7
7
  * our bodies through the keyed `sidebar.right.tab.document` seat. No second tab
8
8
  * system, no second explorer, no document identity of our own, and no change to
9
9
  * the panel layout: the MDI decides *when* a document opens, we only decide
10
- * *how* these four types are drawn.
10
+ * *how* these types are drawn.
11
+ *
12
+ * One body per *kind*, not per format: schematic, PCB, symbol library,
13
+ * footprint, STEP and "any other 3D model". The two library kinds share the
14
+ * ECAD body because they share its lifecycle; the mesh formats share a body
15
+ * because they share a scene, a camera rig and a disposal path (§3.3 of the
16
+ * 3D/SolidCraft task). Adding STL or 3MF means adding an adapter under
17
+ * `./model/adapters/`, not another registration.
11
18
  *
12
19
  * Priority is `'extension'` (a plugin implementation) rather than `'builtin'`,
13
20
  * which is what makes the ECAD viewer, not the plain-text view, the default for
@@ -23,20 +30,40 @@ import { DOCUMENT_BODY_SLOT, type DocumentClientContext, type DocumentPreviewDef
23
30
  import { HARDWARE_UI_NS } from '../copy.js'
24
31
  import { DOCUMENT_COPY } from './copy.js'
25
32
  import { EcadBody, type EcadBodyInjected } from './EcadBody.js'
33
+ import type { EcadDocumentKind } from './mount.js'
34
+ import { ModelBody, type ModelBodyInjected } from './ModelBody.js'
26
35
  import { StepBody, type StepBodyInjected } from './StepBody.js'
36
+ import { MODEL_EXTENSIONS } from './model/index.js'
37
+ import type { CompanionReader } from './model/types.js'
27
38
  import type { ProbeSheetFile } from './EcadBody.js'
28
39
 
29
40
  /** Implementation identity of the schematic body; also its document slot key. */
30
41
  export const SCHEMATIC_BODY_ID = '@huaqiu/dsh-hardware-ui/document/schematic'
31
42
  /** Implementation identity of the PCB body; also its document slot key. */
32
43
  export const PCB_BODY_ID = '@huaqiu/dsh-hardware-ui/document/pcb'
44
+ /** Implementation identity of the symbol-library body; also its document slot key. */
45
+ export const SYMBOL_BODY_ID = '@huaqiu/dsh-hardware-ui/document/symbol'
46
+ /** Implementation identity of the footprint body; also its document slot key. */
47
+ export const FOOTPRINT_BODY_ID = '@huaqiu/dsh-hardware-ui/document/footprint'
33
48
  /** Implementation identity of the 3D model body; also its document slot key. */
34
49
  export const STEP_BODY_ID = '@huaqiu/dsh-hardware-ui/document/step'
50
+ /** Implementation identity of the mesh-format body (STL, 3MF, OBJ, glTF, PLY, AMF). */
51
+ export const MODEL_BODY_ID = '@huaqiu/dsh-hardware-ui/document/model'
35
52
 
36
53
  /** Suffixes each registration claims. Matching is case-insensitive in the registry. */
37
54
  export const SCHEMATIC_EXTENSIONS = ['kicad_sch'] as const
38
55
  export const PCB_EXTENSIONS = ['kicad_pcb'] as const
56
+ export const SYMBOL_EXTENSIONS = ['kicad_sym'] as const
57
+ export const FOOTPRINT_EXTENSIONS = ['kicad_mod'] as const
39
58
  export const STEP_EXTENSIONS = ['step', 'stp'] as const
59
+ /**
60
+ * Suffixes the mesh body claims, derived from its adapters.
61
+ *
62
+ * Derived rather than restated so the registry and the adapter table cannot
63
+ * disagree: a format that gains an adapter is previewable on the next load, and
64
+ * a format whose adapter is removed stops claiming its files.
65
+ */
66
+ export const MESH_EXTENSIONS: readonly string[] = MODEL_EXTENSIONS
40
67
 
41
68
  /**
42
69
  * The four registrations, in the order they are installed.
@@ -63,6 +90,26 @@ export function documentPreviewDefinitions(): readonly DocumentPreviewDefinition
63
90
  loading: 'bytes-complete',
64
91
  wrap: false,
65
92
  },
93
+ {
94
+ // A library file is one document per *file*: the symbols inside are its
95
+ // content, not sibling documents. That is why this is a definition of its
96
+ // own rather than a longer schematic list — a `.kicad_sym` cannot be
97
+ // handed to the sheet parser.
98
+ id: SYMBOL_BODY_ID,
99
+ extensions: SYMBOL_EXTENSIONS,
100
+ priority: 'extension',
101
+ title: () => DOCUMENT_COPY.viewer.symbol,
102
+ loading: 'bytes-complete',
103
+ wrap: false,
104
+ },
105
+ {
106
+ id: FOOTPRINT_BODY_ID,
107
+ extensions: FOOTPRINT_EXTENSIONS,
108
+ priority: 'extension',
109
+ title: () => DOCUMENT_COPY.viewer.footprint,
110
+ loading: 'bytes-complete',
111
+ wrap: false,
112
+ },
66
113
  {
67
114
  id: STEP_BODY_ID,
68
115
  extensions: STEP_EXTENSIONS,
@@ -71,6 +118,18 @@ export function documentPreviewDefinitions(): readonly DocumentPreviewDefinition
71
118
  loading: 'bytes-complete',
72
119
  wrap: false,
73
120
  },
121
+ {
122
+ // A separate id, not a longer STEP list: STEP keeps its OCCT reader and its
123
+ // own body untouched (§3.2), and the mesh formats share one body, one
124
+ // scene and one disposal path (§3.3). The toolbar therefore shows "3D
125
+ // model" for both, which is what the user sees either way.
126
+ id: MODEL_BODY_ID,
127
+ extensions: MESH_EXTENSIONS,
128
+ priority: 'extension',
129
+ title: () => DOCUMENT_COPY.viewer.model,
130
+ loading: 'bytes-complete',
131
+ wrap: false,
132
+ },
74
133
  ]
75
134
  }
76
135
 
@@ -84,6 +143,15 @@ export interface DocumentPreviewOptions {
84
143
  readonly probeSheet?: (sessionId: string) => ProbeSheetFile | undefined
85
144
  /** Same-origin URL of the packaged STEP reader; defaults to the host route. */
86
145
  readonly stepWasmUrl?: string
146
+ /**
147
+ * Build the companion reader for one session, or return undefined when the
148
+ * workspace remote is unavailable.
149
+ *
150
+ * Backed by DSH's own bounded file read, so the plugin runs no filesystem
151
+ * access of its own: the Host applies its regular-file and size gates, and a
152
+ * companion it cannot read is a warning on a model that still renders.
153
+ */
154
+ readonly readCompanion?: (sessionId: string) => CompanionReader | undefined
87
155
  }
88
156
 
89
157
  /**
@@ -109,7 +177,7 @@ export function installDocumentPreviews(ctx: DocumentClientContext, options: Doc
109
177
  effect(() => previews.register(definition), `hardware-ui: document ${definition.id}`)
110
178
  }
111
179
 
112
- const ecad = (kind: 'schematic' | 'pcb', id: string): void => {
180
+ const ecad = (kind: EcadDocumentKind, id: string): void => {
113
181
  effect(() => slots.inject(DOCUMENT_BODY_SLOT, () => slots.register({
114
182
  name: DOCUMENT_BODY_SLOT,
115
183
  key: id,
@@ -124,6 +192,11 @@ export function installDocumentPreviews(ctx: DocumentClientContext, options: Doc
124
192
  }
125
193
  ecad('schematic', SCHEMATIC_BODY_ID)
126
194
  ecad('pcb', PCB_BODY_ID)
195
+ // One body for four kinds: the differences are the parser/renderer pair and
196
+ // whether a library needs a picker, not four lifecycles (§3 of the 3D task
197
+ // keeps the same rule for the mesh formats).
198
+ ecad('symbol', SYMBOL_BODY_ID)
199
+ ecad('footprint', FOOTPRINT_BODY_ID)
127
200
 
128
201
  effect(() => slots.inject(DOCUMENT_BODY_SLOT, () => slots.register({
129
202
  name: DOCUMENT_BODY_SLOT,
@@ -131,4 +204,16 @@ export function installDocumentPreviews(ctx: DocumentClientContext, options: Doc
131
204
  locale: HARDWARE_UI_NS,
132
205
  inject: (): StepBodyInjected => (options.stepWasmUrl === undefined ? {} : { wasmUrl: options.stepWasmUrl }),
133
206
  }, StepBody)), `hardware-ui: document body ${STEP_BODY_ID}`)
207
+
208
+ effect(() => slots.inject(DOCUMENT_BODY_SLOT, () => slots.register({
209
+ name: DOCUMENT_BODY_SLOT,
210
+ key: MODEL_BODY_ID,
211
+ locale: HARDWARE_UI_NS,
212
+ inject: (sessionId: unknown): ModelBodyInjected => {
213
+ // The session arrives here, once, with the enclosing tab; the document's
214
+ // own path arrives at render time and resolves the references locally.
215
+ const read = options.readCompanion?.(String(sessionId))
216
+ return read === undefined ? {} : { readCompanion: read }
217
+ },
218
+ }, ModelBody)), `hardware-ui: document body ${MODEL_BODY_ID}`)
134
219
  }