@huaqiu/dsh-hardware-ui 0.7.17 → 0.7.19

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,212 @@
1
+ /**
2
+ * Document body for `.kicad_sch` and `.kicad_pcb`.
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.
8
+ *
9
+ * Lifecycle, in the order the document seat drives it:
10
+ *
11
+ * 1. **Content arrives** as complete bytes (`loading: 'bytes-complete'`), so the
12
+ * body never reads the file itself and never sees a partial document.
13
+ * 2. **A revision change replaces the content object**, so the effect re-runs,
14
+ * aborts the previous mount and rebuilds — a renderer never shows the
15
+ * previous revision's pixels under the new revision's text.
16
+ * 3. **The tab ends**, aborting `tab.signal`; the mount is disposed and the
17
+ * canvas removed. The body is not `keepMounted`, so this also runs on a tab
18
+ * switch.
19
+ *
20
+ * Every failure is rendered *inside* the document: the MDI shell, the
21
+ * conversation and the other tabs are unaffected by a malformed board.
22
+ *
23
+ * @module @huaqiu/dsh-hardware-ui/client/document/EcadBody
24
+ */
25
+
26
+ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
27
+ import { C, MONO, R } from '../theme.js'
28
+ import { DOCUMENT_COPY } from './copy.js'
29
+ import type { DocumentBodyProps } from './contract.js'
30
+ import { DocumentRenderError, mountEcadDocument, parseEcadSource, type EcadDocumentKind } from './mount.js'
31
+ import { documentFilePath } from './paths.js'
32
+ import { sheetReferences, type SheetReference } from './sheets.js'
33
+
34
+ /** Resolve one declared child sheet to "readable" or not, through the Host's own workspace read. */
35
+ export type ProbeSheetFile = (path: string, signal: AbortSignal) => Promise<boolean>
36
+
37
+ /** Props the registration injects for one kind. */
38
+ export interface EcadBodyInjected {
39
+ readonly kind: EcadDocumentKind
40
+ readonly probeSheet?: ProbeSheetFile
41
+ }
42
+
43
+ /** Standard document props plus the kind this registration renders. */
44
+ export type EcadBodyProps = DocumentBodyProps & EcadBodyInjected
45
+
46
+ type SheetStatus = SheetReference & { readonly found: boolean | undefined }
47
+
48
+ type BodyState =
49
+ | { readonly phase: 'loading' }
50
+ | { readonly phase: 'ready'; readonly sheets: readonly SheetStatus[] }
51
+ | { readonly phase: 'error'; readonly message: string }
52
+
53
+ const STAGE: React.CSSProperties = {
54
+ position: 'relative', width: '100%', height: '100%', minHeight: 0, overflow: 'hidden',
55
+ background: C.base,
56
+ }
57
+ const HOST: React.CSSProperties = { position: 'absolute', inset: 0 }
58
+ const CENTER: React.CSSProperties = {
59
+ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
60
+ alignItems: 'center', justifyContent: 'center', gap: 6, padding: 24, textAlign: 'center',
61
+ color: C.text3, fontSize: 11, lineHeight: 1.6,
62
+ }
63
+ const ERROR_TITLE: React.CSSProperties = { margin: 0, color: C.text2, fontSize: 12, fontWeight: 600 }
64
+ const ERROR_LINE: React.CSSProperties = { margin: 0, maxWidth: 420, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }
65
+ const HINT: React.CSSProperties = {
66
+ position: 'absolute', right: 8, bottom: 8, padding: '2px 8px', borderRadius: R.pill,
67
+ background: 'rgba(0,0,0,0.55)', color: '#e4e4e7', fontSize: 10, fontFamily: MONO,
68
+ pointerEvents: 'none', maxWidth: 'calc(100% - 16px)',
69
+ }
70
+ const SHEETS: React.CSSProperties = {
71
+ position: 'absolute', left: 8, right: 8, bottom: 8, padding: '6px 8px', borderRadius: R.md,
72
+ background: 'rgba(0,0,0,0.62)', color: '#e4e4e7', fontSize: 10, fontFamily: MONO,
73
+ display: 'flex', flexDirection: 'column', gap: 2, maxHeight: '40%', overflow: 'auto',
74
+ }
75
+ const SHEET_ROW: React.CSSProperties = { display: 'flex', gap: 6, alignItems: 'baseline' }
76
+
77
+ /** Human-readable text for a mount failure, keyed by the reason it carries. */
78
+ function failureText(error: unknown): string {
79
+ const copy = DOCUMENT_COPY.state
80
+ if (error instanceof DocumentRenderError) {
81
+ if (error.reason === 'parse') return copy.parseFailed(error.message)
82
+ if (error.reason === 'toolarge') return copy.tooLarge('32 MB')
83
+ if (error.reason === 'aborted') return copy.aborted
84
+ return copy.renderFailed(error.message)
85
+ }
86
+ return copy.renderFailed(error instanceof Error ? error.message : String(error))
87
+ }
88
+
89
+ /** Decode document bytes as UTF-8, dropping a BOM KiCad never writes but editors add. */
90
+ export function decodeDocumentText(data: Uint8Array): string {
91
+ const text = new TextDecoder('utf-8').decode(data)
92
+ return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text
93
+ }
94
+
95
+ /**
96
+ * Render one ECAD document inside its tab.
97
+ * @param props - document content, resource identity, tab lifetime and kind.
98
+ * @returns the rendered document, a loading line, or an in-document failure.
99
+ */
100
+ export function EcadBody(props: EcadBodyProps): ReactNode {
101
+ const { content, kind, resourceAddress } = props
102
+ const { tab } = props.useTabInfo()
103
+ const host = useRef<HTMLDivElement | null>(null)
104
+ const [state, setState] = useState<BodyState>({ phase: 'loading' })
105
+ const data = content.kind === 'bytes' ? content.data : undefined
106
+ const path = useMemo(() => documentFilePath(resourceAddress)?.path, [resourceAddress])
107
+
108
+ useEffect(() => {
109
+ const container = host.current
110
+ if (data === undefined || container === null) return
111
+ const controller = new AbortController()
112
+ const lifetime = AbortSignal.any([tab.signal, controller.signal])
113
+ let mounted: { dispose(): void } | undefined
114
+ setState({ phase: 'loading' })
115
+
116
+ void (async () => {
117
+ const text = decodeDocumentText(data)
118
+ let references: readonly SheetReference[] = []
119
+ let live: { dispose(): void }
120
+ if (kind === 'schematic') {
121
+ // Parsing once for the hierarchy keeps the disclosure and the render
122
+ // reading the same model: a sheet list that disagreed with the picture
123
+ // would be worse than no list.
124
+ const parsed = parseEcadSource('schematic', text)
125
+ references = sheetReferences(parsed, path ?? '')
126
+ live = await mountEcadDocument({ kind, text, container, signal: lifetime, parsed })
127
+ } else {
128
+ live = await mountEcadDocument({ kind, text, container, signal: lifetime })
129
+ }
130
+ mounted = live
131
+ if (lifetime.aborted) {
132
+ // The tab or the revision ended while the viewer was fitting; the mount
133
+ // is live and nothing else holds it.
134
+ live.dispose()
135
+ mounted = undefined
136
+ return
137
+ }
138
+ setState({ phase: 'ready', sheets: references.map(reference => ({ ...reference, found: undefined })) })
139
+ })().catch((error: unknown) => {
140
+ if (lifetime.aborted) return
141
+ setState({ phase: 'error', message: failureText(error) })
142
+ })
143
+
144
+ return () => {
145
+ controller.abort()
146
+ mounted?.dispose()
147
+ }
148
+ }, [data, kind, path, tab.signal])
149
+
150
+ // Child sheets are resolved after the picture is up: existence is a Host read
151
+ // per reference, and a slow one must not delay the render the user asked for.
152
+ const probe = props.probeSheet
153
+ useEffect(() => {
154
+ if (state.phase !== 'ready' || probe === undefined) return
155
+ const pending = state.sheets.filter(sheet => sheet.resolved !== undefined && sheet.found === undefined)
156
+ if (pending.length === 0) return
157
+ const controller = new AbortController()
158
+ const lifetime = AbortSignal.any([tab.signal, controller.signal])
159
+ void (async () => {
160
+ const outcomes = await Promise.all(pending.map(async (sheet) => {
161
+ try {
162
+ return { resolved: sheet.resolved as string, found: await probe(sheet.resolved as string, lifetime) }
163
+ } catch {
164
+ return { resolved: sheet.resolved as string, found: false }
165
+ }
166
+ }))
167
+ if (lifetime.aborted) return
168
+ setState((current) => {
169
+ if (current.phase !== 'ready') return current
170
+ const byPath = new Map(outcomes.map(outcome => [outcome.resolved, outcome.found]))
171
+ return {
172
+ phase: 'ready',
173
+ sheets: current.sheets.map(sheet => (sheet.resolved === undefined || !byPath.has(sheet.resolved)
174
+ ? sheet
175
+ : { ...sheet, found: byPath.get(sheet.resolved) })),
176
+ }
177
+ })
178
+ })()
179
+ return () => { controller.abort() }
180
+ }, [state, probe, tab.signal])
181
+
182
+ const sheets = state.phase === 'ready' ? state.sheets : []
183
+ return (
184
+ <div data-ecad-preview data-ecad-kind={kind} style={STAGE}>
185
+ <div ref={host} style={HOST} data-ecad-host />
186
+ {state.phase === 'loading' && (
187
+ <p style={CENTER} data-ecad-loading>{DOCUMENT_COPY.state.loading}</p>
188
+ )}
189
+ {state.phase === 'error' && (
190
+ <div style={CENTER} role="alert" data-ecad-error>
191
+ <p style={ERROR_TITLE}>{kind === 'schematic' ? DOCUMENT_COPY.viewer.schematic : DOCUMENT_COPY.viewer.pcb}</p>
192
+ <p style={ERROR_LINE}>{state.message}</p>
193
+ </div>
194
+ )}
195
+ {state.phase === 'ready' && sheets.length === 0 && (
196
+ <span style={HINT} data-ecad-hint>{DOCUMENT_COPY.hint.schematic}</span>
197
+ )}
198
+ {state.phase === 'ready' && sheets.length > 0 && (
199
+ <div style={SHEETS} data-ecad-sheets>
200
+ <span>{DOCUMENT_COPY.sheets.title(sheets.length)}</span>
201
+ {sheets.map(sheet => (
202
+ <span key={sheet.resolved ?? sheet.declared} style={SHEET_ROW} data-ecad-sheet={sheet.found === false ? 'missing' : 'present'}>
203
+ <span>{sheet.found === false ? '!' : '·'}</span>
204
+ <span>{sheet.found === false ? DOCUMENT_COPY.sheets.missing(sheet.label) : DOCUMENT_COPY.sheets.found(sheet.label)}</span>
205
+ </span>
206
+ ))}
207
+ <span style={{ opacity: 0.7 }}>{DOCUMENT_COPY.sheets.hint}</span>
208
+ </div>
209
+ )}
210
+ </div>
211
+ )
212
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Document body for `.step` and `.stp`.
3
+ *
4
+ * Bytes in, picture out. The source model is never written back and no derived
5
+ * artefact is produced, so there is no cache to invalidate: a changed file
6
+ * arrives as a new byte array, which re-runs this effect and replaces the model.
7
+ *
8
+ * The mount owns a WebGL context. A document tab is closed and reopened
9
+ * constantly, and browsers cap live contexts (Chrome drops the oldest at ~16),
10
+ * so disposal is not optional housekeeping here — it is what keeps the *other*
11
+ * tabs' 3D views alive.
12
+ *
13
+ * @module @huaqiu/dsh-hardware-ui/client/document/StepBody
14
+ */
15
+
16
+ import { useEffect, useRef, useState, type ReactNode } from 'react'
17
+ import { C, MONO, R } from '../theme.js'
18
+ import { OCCT_WASM_ROUTE } from '../../shared/occt-asset.js'
19
+ import { DOCUMENT_COPY } from './copy.js'
20
+ import type { DocumentBodyProps } from './contract.js'
21
+ import { DocumentRenderError } from './mount.js'
22
+ import { mountStepDocument } from './step.js'
23
+
24
+ /** Props the registration injects for the model kind. */
25
+ export interface StepBodyInjected {
26
+ /** Same-origin URL of the packaged reader wasm; injected so tests can point elsewhere. */
27
+ readonly wasmUrl?: string
28
+ }
29
+
30
+ /** Standard document props plus the reader location. */
31
+ export type StepBodyProps = DocumentBodyProps & StepBodyInjected
32
+
33
+ type StepState =
34
+ | { readonly phase: 'loading' }
35
+ | { readonly phase: 'ready' }
36
+ | { readonly phase: 'error'; readonly message: string }
37
+
38
+ const STAGE: React.CSSProperties = {
39
+ position: 'relative', width: '100%', height: '100%', minHeight: 0, overflow: 'hidden', background: C.base,
40
+ }
41
+ const HOST: React.CSSProperties = { position: 'absolute', inset: 0 }
42
+ const CENTER: React.CSSProperties = {
43
+ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center',
44
+ justifyContent: 'center', gap: 6, padding: 24, textAlign: 'center', color: C.text3, fontSize: 11, lineHeight: 1.6,
45
+ }
46
+ const ERROR_TITLE: React.CSSProperties = { margin: 0, color: C.text2, fontSize: 12, fontWeight: 600 }
47
+ const ERROR_LINE: React.CSSProperties = { margin: 0, maxWidth: 420, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }
48
+ const HINT: React.CSSProperties = {
49
+ position: 'absolute', right: 8, bottom: 8, padding: '2px 8px', borderRadius: R.pill,
50
+ background: 'rgba(0,0,0,0.55)', color: '#e4e4e7', fontSize: 10, fontFamily: MONO,
51
+ pointerEvents: 'none', maxWidth: 'calc(100% - 16px)',
52
+ }
53
+
54
+ /** Human-readable text for a STEP failure. */
55
+ export function stepFailureText(error: unknown): string {
56
+ const copy = DOCUMENT_COPY.state
57
+ if (error instanceof DocumentRenderError) {
58
+ if (error.reason === 'parse') return copy.stepInvalid
59
+ if (error.reason === 'toolarge') return copy.tooLarge('32 MB')
60
+ if (error.reason === 'aborted') return copy.aborted
61
+ if (error.message.includes('webgl')) return copy.noWebgl
62
+ if (error.message.includes('wasm')) return copy.wasmFailed
63
+ return copy.renderFailed(error.message)
64
+ }
65
+ return copy.renderFailed(error instanceof Error ? error.message : String(error))
66
+ }
67
+
68
+ /**
69
+ * Render one STEP/STP document inside its tab.
70
+ * @param props - document bytes, tab lifetime, reader location.
71
+ * @returns the model, a loading line, or an in-document failure.
72
+ */
73
+ export function StepBody(props: StepBodyProps): ReactNode {
74
+ const { content } = props
75
+ const { tab } = props.useTabInfo()
76
+ const host = useRef<HTMLDivElement | null>(null)
77
+ const [state, setState] = useState<StepState>({ phase: 'loading' })
78
+ const data = content.kind === 'bytes' ? content.data : undefined
79
+ const wasmUrl = props.wasmUrl ?? OCCT_WASM_ROUTE
80
+
81
+ useEffect(() => {
82
+ const container = host.current
83
+ if (data === undefined || container === null) return
84
+ const controller = new AbortController()
85
+ const lifetime = AbortSignal.any([tab.signal, controller.signal])
86
+ let mounted: { dispose(): void } | undefined
87
+ setState({ phase: 'loading' })
88
+
89
+ void (async () => {
90
+ const live = await mountStepDocument({ bytes: data, container, signal: lifetime, wasmUrl })
91
+ mounted = live
92
+ if (lifetime.aborted) {
93
+ live.dispose()
94
+ mounted = undefined
95
+ return
96
+ }
97
+ setState({ phase: 'ready' })
98
+ })().catch((error: unknown) => {
99
+ if (lifetime.aborted) return
100
+ setState({ phase: 'error', message: stepFailureText(error) })
101
+ })
102
+
103
+ return () => {
104
+ controller.abort()
105
+ mounted?.dispose()
106
+ }
107
+ }, [data, tab.signal, wasmUrl])
108
+
109
+ return (
110
+ <div data-step-preview style={STAGE}>
111
+ <div ref={host} style={HOST} data-step-host />
112
+ {state.phase === 'loading' && (
113
+ <p style={CENTER} data-step-loading>{DOCUMENT_COPY.state.stepLoading}</p>
114
+ )}
115
+ {state.phase === 'error' && (
116
+ <div style={CENTER} role="alert" data-step-error>
117
+ <p style={ERROR_TITLE}>{DOCUMENT_COPY.viewer.model}</p>
118
+ <p style={ERROR_LINE}>{state.message}</p>
119
+ </div>
120
+ )}
121
+ {state.phase === 'ready' && <span style={HINT} data-step-hint>{DOCUMENT_COPY.hint.model}</span>}
122
+ </div>
123
+ )
124
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * Structural view of the DSH document-preview seats this package extends.
3
+ *
4
+ * Why structural and not imported: the DSH client packages are not installed in
5
+ * this repository (only `@deepseek-ai/cordis` is), and the sibling packages
6
+ * declare the same seams by shape for the same reason (`dsh-eda-selection`,
7
+ * `dsh-huaqiu-about`, `dsh-tool-pcb-viewer/src/client/panel.tsx`). Every field
8
+ * below is read from the framework's published contract, not guessed:
9
+ *
10
+ * - `DocumentPreviewDefinition` / `DocumentLoadMode`
11
+ * `@deepseek-ai/dsh-client-ui-sidebar-documentpreview/src/client/document/registry.ts:6-33`
12
+ * - `DocumentContent` / `DocumentBodyOwner` / `DocumentPreviewProps`
13
+ * `…/src/client/document/contract.ts:17-98`
14
+ * - the owner fields a body actually receives, and the `locale`-less prop set
15
+ * `…/src/client/TextPreview.tsx:381-386`
16
+ * - `sidebar.right.tab.document` is a keyed slot whose `key` is the definition
17
+ * id and whose props carry the enclosing tab reader
18
+ * `…/src/client/document/contract.ts:48-60`
19
+ *
20
+ * A drift in any of these is a compile-time failure here, not a runtime
21
+ * surprise: the body components consume this module's types only.
22
+ *
23
+ * @module @huaqiu/dsh-hardware-ui/client/document/contract
24
+ */
25
+
26
+ /** Content delivery mode the document owner performs for a renderer. */
27
+ export type DocumentLoadMode = 'text-pages' | 'bytes-complete' | 'renderer'
28
+
29
+ /** One renderer implementation, independent of its keyed body registration. */
30
+ export interface DocumentPreviewDefinition {
31
+ /** Unique implementation name, also the document slot key. */
32
+ readonly id: string
33
+ /** File suffixes without a leading dot; matching is case-insensitive. */
34
+ readonly extensions: readonly string[]
35
+ /** Suffixes among `extensions` that are not readable text. */
36
+ readonly binaryExtensions?: readonly string[]
37
+ /** External implementations win over product implementations. */
38
+ readonly priority?: 'builtin' | 'extension'
39
+ /** Localized implementation label, evaluated when the toolbar renders. */
40
+ readonly title: () => string
41
+ /** Content delivery mode supplied by the document owner. */
42
+ readonly loading: DocumentLoadMode
43
+ /** Whether the implementation consumes the document's wrap preference. */
44
+ readonly wrap?: boolean
45
+ /** Whether a `text-pages` body exposes source-line anchors. */
46
+ readonly sourceLines?: boolean
47
+ }
48
+
49
+ /** One loaded text window; unused by whole-byte renderers, required by the union. */
50
+ export interface DocumentTextPage {
51
+ readonly offset: number
52
+ readonly text: string
53
+ readonly lines: number
54
+ }
55
+
56
+ /** Ordinary file contents, or a request for the selected renderer to load them. */
57
+ export type DocumentContent =
58
+ | {
59
+ readonly kind: 'text'
60
+ readonly text: string
61
+ readonly pages: readonly DocumentTextPage[]
62
+ readonly eof: boolean
63
+ }
64
+ | { readonly kind: 'bytes'; readonly data: Uint8Array<ArrayBuffer> }
65
+ | {
66
+ readonly kind: 'renderer'
67
+ readonly revision: number
68
+ readonly loaded: (version: string) => void
69
+ readonly failed: () => void
70
+ readonly reload: () => void
71
+ }
72
+
73
+ /** Content and viewing inputs the document body owner supplies. */
74
+ export interface DocumentBodyOwner {
75
+ readonly addResource: (address: string) => void
76
+ readonly setResources: (addresses: readonly string[]) => void
77
+ readonly resourceAddress: string
78
+ readonly content: DocumentContent
79
+ readonly wrap: boolean
80
+ readonly scrollportRef: (element: HTMLElement | null) => void
81
+ }
82
+
83
+ /** The enclosing document tab, as the tab reader exposes it. */
84
+ export interface DocumentTabInfo {
85
+ readonly tab: {
86
+ readonly id: string
87
+ /** Aborted when the tab record ends; every asynchronous mount binds to it. */
88
+ readonly signal: AbortSignal
89
+ }
90
+ }
91
+
92
+ /** Standard props of a `sidebar.right.tab.document` body. */
93
+ export interface DocumentBodyProps extends DocumentBodyOwner {
94
+ readonly sessionId: string
95
+ readonly useTabInfo: () => DocumentTabInfo
96
+ }
97
+
98
+ /** The slice of the slot registry this package registers through. */
99
+ export interface SlotSpec {
100
+ readonly name: string
101
+ readonly key: string
102
+ readonly locale?: string
103
+ readonly store?: unknown
104
+ readonly inject?: (...args: unknown[]) => object
105
+ }
106
+
107
+ /** The slice of the slot service this package calls. */
108
+ export interface SlotService {
109
+ inject(key: string, callback: () => () => void): () => void
110
+ register(spec: SlotSpec, component: unknown): () => void
111
+ }
112
+
113
+ /** The slice of the document-preview registry this package calls. */
114
+ export interface DocumentPreviewService {
115
+ register(definition: DocumentPreviewDefinition): () => void
116
+ }
117
+
118
+ /** Workspace byte window, matching the Host endpoint's `readBytes` options. */
119
+ export interface WorkspaceByteReadOptions {
120
+ readonly range?: { readonly offset?: number; readonly length?: number }
121
+ readonly baseFile?: string
122
+ }
123
+
124
+ /** Result envelope of one Client Remote call: failures travel, they do not throw. */
125
+ export type RemoteResult<T> =
126
+ | { readonly ok: true; readonly value: T }
127
+ | { readonly ok: false; readonly error: unknown }
128
+
129
+ /** The slice of `remote.workspaceFiles` a child-sheet probe needs. */
130
+ export interface WorkspaceFilesRemote {
131
+ readBytes(
132
+ sessionId: string,
133
+ path: string,
134
+ options: WorkspaceByteReadOptions,
135
+ signal?: AbortSignal,
136
+ ): Promise<RemoteResult<unknown>>
137
+ }
138
+
139
+ /**
140
+ * Client context this package's document integration needs.
141
+ *
142
+ * Every service is optional: the product UI registered by `apply` must keep
143
+ * working on a Host whose document-preview service is absent, so the caller
144
+ * guards each seat instead of parking the whole plugin behind `inject`.
145
+ */
146
+ export interface DocumentClientContext {
147
+ readonly documentPreviews?: DocumentPreviewService
148
+ readonly slots?: SlotService
149
+ readonly remote?: { readonly workspaceFiles?: WorkspaceFilesRemote }
150
+ effect?(fn: () => (() => void) | void, label?: string): void
151
+ inject?(dependencies: readonly string[], callback: (scope: DocumentClientContext) => void): void
152
+ get?(name: string): unknown
153
+ }
154
+
155
+ /** The document seat every body registers into. */
156
+ export const DOCUMENT_BODY_SLOT = 'sidebar.right.tab.document'
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Copy for the document-rendering surfaces, backed by the same DSH locale
3
+ * namespace as `../copy.ts`.
4
+ *
5
+ * The dictionaries are flat `{name}` templates in `../locales.ts`; this module
6
+ * keeps the structured read API so the bodies do not carry a `t` seat. Reads go
7
+ * through the active locale at call time, and DSH's renderer re-renders the
8
+ * document slot on a language change.
9
+ *
10
+ * Extension names, viewer verbs and unit symbols are not translated.
11
+ *
12
+ * @module @huaqiu/dsh-hardware-ui/client/document/copy
13
+ */
14
+
15
+ import { translateCopy } from '../copy.js'
16
+
17
+ export const DOCUMENT_COPY = {
18
+ /** Toolbar labels for the document viewer menu. */
19
+ viewer: {
20
+ get schematic(): string { return translateCopy('document.viewer.schematic') },
21
+ get pcb(): string { return translateCopy('document.viewer.pcb') },
22
+ get model(): string { return translateCopy('document.viewer.model') },
23
+ },
24
+ /** Progress and state lines. */
25
+ state: {
26
+ get loading(): string { return translateCopy('document.state.loading') },
27
+ get stepLoading(): string { return translateCopy('document.state.stepLoading') },
28
+ tooLarge: (limit: string): string => translateCopy('document.state.tooLarge', { limit }),
29
+ parseFailed: (message: string): string => translateCopy('document.state.parseFailed', { message }),
30
+ renderFailed: (message: string): string => translateCopy('document.state.renderFailed', { message }),
31
+ get aborted(): string { return translateCopy('document.state.aborted') },
32
+ /** Shown when the WebGL canvas cannot be created (no GPU, blocklisted driver). */
33
+ get noWebgl(): string { return translateCopy('document.state.noWebgl') },
34
+ get stepInvalid(): string { return translateCopy('document.state.stepInvalid') },
35
+ get wasmFailed(): string { return translateCopy('document.state.wasmFailed') },
36
+ },
37
+ /** Interaction hints overlaid on a rendered document. */
38
+ hint: {
39
+ get schematic(): string { return translateCopy('document.hint.schematic') },
40
+ get model(): string { return translateCopy('document.hint.model') },
41
+ },
42
+ /** Child-sheet disclosure under a schematic. */
43
+ sheets: {
44
+ title: (count: number): string => translateCopy('document.sheets.title', { count }),
45
+ missing: (label: string): string => translateCopy('document.sheets.missing', { label }),
46
+ found: (label: string): string => translateCopy('document.sheets.found', { label }),
47
+ get hint(): string { return translateCopy('document.sheets.hint') },
48
+ },
49
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Registration of the Hardware Engineering document renderers.
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
6
+ * existing `text` tab type — which already claims every workspace file — renders
7
+ * our bodies through the keyed `sidebar.right.tab.document` seat. No second tab
8
+ * system, no second explorer, no document identity of our own, and no change to
9
+ * the panel layout: the MDI decides *when* a document opens, we only decide
10
+ * *how* these four types are drawn.
11
+ *
12
+ * Priority is `'extension'` (a plugin implementation) rather than `'builtin'`,
13
+ * which is what makes the ECAD viewer, not the plain-text view, the default for
14
+ * a `.kicad_sch`. The text view stays available in the document's viewer menu
15
+ * because the owner keeps every matching definition as a candidate — being able
16
+ * to read the raw S-expression of the file you are looking at is a feature, not
17
+ * a fallback.
18
+ *
19
+ * @module @huaqiu/dsh-hardware-ui/client/document
20
+ */
21
+
22
+ import { DOCUMENT_BODY_SLOT, type DocumentClientContext, type DocumentPreviewDefinition } from './contract.js'
23
+ import { HARDWARE_UI_NS } from '../copy.js'
24
+ import { DOCUMENT_COPY } from './copy.js'
25
+ import { EcadBody, type EcadBodyInjected } from './EcadBody.js'
26
+ import { StepBody, type StepBodyInjected } from './StepBody.js'
27
+ import type { ProbeSheetFile } from './EcadBody.js'
28
+
29
+ /** Implementation identity of the schematic body; also its document slot key. */
30
+ export const SCHEMATIC_BODY_ID = '@huaqiu/dsh-hardware-ui/document/schematic'
31
+ /** Implementation identity of the PCB body; also its document slot key. */
32
+ export const PCB_BODY_ID = '@huaqiu/dsh-hardware-ui/document/pcb'
33
+ /** Implementation identity of the 3D model body; also its document slot key. */
34
+ export const STEP_BODY_ID = '@huaqiu/dsh-hardware-ui/document/step'
35
+
36
+ /** Suffixes each registration claims. Matching is case-insensitive in the registry. */
37
+ export const SCHEMATIC_EXTENSIONS = ['kicad_sch'] as const
38
+ export const PCB_EXTENSIONS = ['kicad_pcb'] as const
39
+ export const STEP_EXTENSIONS = ['step', 'stp'] as const
40
+
41
+ /**
42
+ * The four registrations, in the order they are installed.
43
+ * @returns fresh definitions; the registry rejects a duplicate id, so callers cannot share one object.
44
+ */
45
+ export function documentPreviewDefinitions(): readonly DocumentPreviewDefinition[] {
46
+ return [
47
+ {
48
+ id: SCHEMATIC_BODY_ID,
49
+ extensions: SCHEMATIC_EXTENSIONS,
50
+ priority: 'extension',
51
+ title: () => DOCUMENT_COPY.viewer.schematic,
52
+ // Both ECAD formats are read whole before parsing: the parser needs the
53
+ // complete S-expression tree, and a board or schematic is far below the
54
+ // Host's complete-read cap.
55
+ loading: 'bytes-complete',
56
+ wrap: false,
57
+ },
58
+ {
59
+ id: PCB_BODY_ID,
60
+ extensions: PCB_EXTENSIONS,
61
+ priority: 'extension',
62
+ title: () => DOCUMENT_COPY.viewer.pcb,
63
+ loading: 'bytes-complete',
64
+ wrap: false,
65
+ },
66
+ {
67
+ id: STEP_BODY_ID,
68
+ extensions: STEP_EXTENSIONS,
69
+ priority: 'extension',
70
+ title: () => DOCUMENT_COPY.viewer.model,
71
+ loading: 'bytes-complete',
72
+ wrap: false,
73
+ },
74
+ ]
75
+ }
76
+
77
+ /** What the host half of the product can contribute to the document surfaces. */
78
+ export interface DocumentPreviewOptions {
79
+ /**
80
+ * Build the child-sheet probe for one session, or return undefined when the
81
+ * workspace remote is unavailable. Absent means "disclose the references
82
+ * without claiming to know whether they exist".
83
+ */
84
+ readonly probeSheet?: (sessionId: string) => ProbeSheetFile | undefined
85
+ /** Same-origin URL of the packaged STEP reader; defaults to the host route. */
86
+ readonly stepWasmUrl?: string
87
+ }
88
+
89
+ /**
90
+ * Install the document renderers on a client context.
91
+ *
92
+ * Every seat is guarded: a Host without the document-preview service simply
93
+ * gets no ECAD preview, and the product's own panel keeps working. Registration
94
+ * runs inside `ctx.effect` when the framework offers it, so unloading the plugin
95
+ * (or an HMR reload) retires the definitions and bodies with it.
96
+ * @param ctx - client context carrying the document registry and slot registry.
97
+ * @param options - host-provided contributions.
98
+ */
99
+ export function installDocumentPreviews(ctx: DocumentClientContext, options: DocumentPreviewOptions = {}): void {
100
+ const previews = ctx.documentPreviews
101
+ const slots = ctx.slots
102
+ if (previews === undefined || slots === undefined) return
103
+ const effect = (fn: () => (() => void) | void, label: string): void => {
104
+ if (ctx.effect !== undefined) ctx.effect(fn, label)
105
+ else void fn()
106
+ }
107
+
108
+ for (const definition of documentPreviewDefinitions()) {
109
+ effect(() => previews.register(definition), `hardware-ui: document ${definition.id}`)
110
+ }
111
+
112
+ const ecad = (kind: 'schematic' | 'pcb', id: string): void => {
113
+ effect(() => slots.inject(DOCUMENT_BODY_SLOT, () => slots.register({
114
+ name: DOCUMENT_BODY_SLOT,
115
+ key: id,
116
+ locale: HARDWARE_UI_NS,
117
+ // The injected slice is what the body reads; the framework calls this
118
+ // once per mount with the enclosing session.
119
+ inject: (sessionId: unknown): EcadBodyInjected => {
120
+ const probe = options.probeSheet?.(String(sessionId))
121
+ return { kind, ...(probe === undefined ? {} : { probeSheet: probe }) }
122
+ },
123
+ }, EcadBody)), `hardware-ui: document body ${id}`)
124
+ }
125
+ ecad('schematic', SCHEMATIC_BODY_ID)
126
+ ecad('pcb', PCB_BODY_ID)
127
+
128
+ effect(() => slots.inject(DOCUMENT_BODY_SLOT, () => slots.register({
129
+ name: DOCUMENT_BODY_SLOT,
130
+ key: STEP_BODY_ID,
131
+ locale: HARDWARE_UI_NS,
132
+ inject: (): StepBodyInjected => (options.stepWasmUrl === undefined ? {} : { wasmUrl: options.stepWasmUrl }),
133
+ }, StepBody)), `hardware-ui: document body ${STEP_BODY_ID}`)
134
+ }