@huaqiu/dsh-hardware-ui 0.0.0-stage → 0.7.13

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,17 @@
1
+ //#region src/index.d.ts
2
+ /**
3
+ * Node half of `@huaqiu/dsh-hardware-ui`.
4
+ *
5
+ * All product UI is browser-side. This entry exists so the package is a normal
6
+ * installable plugin in the DSH bundle; it intentionally provides no service
7
+ * and injects nothing. Host operations live in `@huaqiu/hardware-artifacts`.
8
+ */
9
+ declare const name = "@huaqiu/dsh-hardware-ui";
10
+ /** Browser-only plugin: the node Loader seat intentionally does nothing. */
11
+ declare function apply(): void;
12
+ /** The tab kind owned by this product UI. */
13
+ declare const HARDWARE_TAB_KIND = "hardware-engineering";
14
+ /** Slots this product UI occupies. Exported for contract tests and readers. */
15
+ declare const HARDWARE_UI_SLOTS: readonly ["conversation.header.leading", "conversation.session.header.corner", "sidebar.right.pane.tab", "settings.section"];
16
+ //#endregion
17
+ export { HARDWARE_TAB_KIND, HARDWARE_UI_SLOTS, apply, name };
package/lib/index.mjs ADDED
@@ -0,0 +1,22 @@
1
+ //#region src/index.ts
2
+ /**
3
+ * Node half of `@huaqiu/dsh-hardware-ui`.
4
+ *
5
+ * All product UI is browser-side. This entry exists so the package is a normal
6
+ * installable plugin in the DSH bundle; it intentionally provides no service
7
+ * and injects nothing. Host operations live in `@huaqiu/hardware-artifacts`.
8
+ */
9
+ const name = "@huaqiu/dsh-hardware-ui";
10
+ /** Browser-only plugin: the node Loader seat intentionally does nothing. */
11
+ function apply() {}
12
+ /** The tab kind owned by this product UI. */
13
+ const HARDWARE_TAB_KIND = "hardware-engineering";
14
+ /** Slots this product UI occupies. Exported for contract tests and readers. */
15
+ const HARDWARE_UI_SLOTS = Object.freeze([
16
+ "conversation.header.leading",
17
+ "conversation.session.header.corner",
18
+ "sidebar.right.pane.tab",
19
+ "settings.section"
20
+ ]);
21
+ //#endregion
22
+ export { HARDWARE_TAB_KIND, HARDWARE_UI_SLOTS, apply, name };
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@huaqiu/dsh-hardware-ui",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.7.13",
4
+ "type": "module",
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
+ "license": "MIT",
7
+ "main": "./lib/index.mjs",
8
+ "types": "./lib/index.d.mts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/index.d.mts",
12
+ "default": "./lib/index.mjs"
13
+ },
14
+ "./client": {
15
+ "default": "./lib/client.js"
16
+ },
17
+ "./cordis.patch.yml": "./cordis.patch.yml",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "dsh": {
21
+ "bundle": {
22
+ "patch": "./cordis.patch.yml"
23
+ },
24
+ "client": {
25
+ "platform": "web",
26
+ "inject": [
27
+ "@deepseek-ai/dsh-client-ui-slots"
28
+ ]
29
+ }
30
+ },
31
+ "engines": {
32
+ "dsh": "^0.2.2-rc.1"
33
+ },
34
+ "peerDependencies": {
35
+ "@deepseek-ai/cordis": "^4.0.1",
36
+ "react": "^18"
37
+ },
38
+ "devDependencies": {
39
+ "@huaqiu/ecad-renderer": "0.2.4",
40
+ "@huaqiu/kicad-sexpr-parser": "0.1.1",
41
+ "three": "^0.185.1",
42
+ "@deepseek-ai/cordis": "^4.0.2",
43
+ "@types/react": "~18.3.1",
44
+ "@types/three": "^0.185.4",
45
+ "react": "^18.3.1",
46
+ "react-dom": "^18.3.1",
47
+ "tsdown": "^0.22.14",
48
+ "typescript": "^5.9.0",
49
+ "vitest": "^4.1.0"
50
+ },
51
+ "files": [
52
+ "lib",
53
+ "src",
54
+ "cordis.patch.yml",
55
+ "README.md"
56
+ ],
57
+ "publishConfig": {
58
+ "access": "public"
59
+ },
60
+ "scripts": {
61
+ "typecheck": "tsc --noEmit",
62
+ "build": "tsdown",
63
+ "test": "vitest run"
64
+ }
6
65
  }
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Hardware Engineering UI components. All state reaches them through the
3
+ * standard slot props (`useStore`, `actions`) and one injected hook bundle;
4
+ * nothing here imports Node APIs or reaches into another plugin's singleton.
5
+ */
6
+ import {
7
+ createElement, useEffect, useMemo, useState, useSyncExternalStore,
8
+ type ChangeEvent, type CSSProperties, type ReactNode,
9
+ } from 'react'
10
+ import {
11
+ applicationFor, DESTINATIONS, DESTINATION_LABELS,
12
+ type HardwareActions, type HardwareArtifactInfo, type HardwareDestination,
13
+ type HardwareInjected, type HardwareInstallationConfig, type HardwareState,
14
+ } from './model.js'
15
+ import { HardwarePreview } from './preview.js'
16
+
17
+ type UseStore = <S>(selector: (state: HardwareState) => S) => S
18
+
19
+ interface SlotProps {
20
+ readonly useStore: UseStore
21
+ readonly actions: HardwareActions
22
+ readonly hooks: HardwareInjected
23
+ readonly t?: (key: string) => string
24
+ }
25
+
26
+ const ROW: CSSProperties = { display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }
27
+ const NAV: CSSProperties = { ...ROW, minWidth: 0, fontSize: 12 }
28
+ const TAB: CSSProperties = {
29
+ border: '1px solid var(--dsw-alias-border-default, rgba(127,127,127,0.3))',
30
+ borderRadius: 6, background: 'transparent', color: 'var(--dsw-alias-label-secondary)',
31
+ padding: '3px 8px', cursor: 'pointer', font: 'inherit', whiteSpace: 'nowrap',
32
+ }
33
+ const ACTIVE: CSSProperties = {
34
+ ...TAB, color: 'var(--dsw-alias-label-primary)', borderColor: 'var(--dsw-alias-brand-primary, currentColor)',
35
+ background: 'color-mix(in srgb, var(--dsw-alias-brand-primary, currentColor) 10%, transparent)',
36
+ }
37
+ const PATH: CSSProperties = {
38
+ minWidth: 0, maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
39
+ color: 'var(--dsw-alias-label-tertiary)', fontSize: 11,
40
+ }
41
+ const ROOT: CSSProperties = {
42
+ display: 'flex', flexDirection: 'column', height: '100%', minWidth: 0,
43
+ boxSizing: 'border-box', padding: 12, gap: 10,
44
+ color: 'var(--dsw-alias-label-primary)', overflow: 'auto',
45
+ }
46
+ const HEADER: CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }
47
+ const TITLE: CSSProperties = { margin: 0, fontSize: 14, fontWeight: 600 }
48
+ const BUTTON: CSSProperties = {
49
+ ...TAB, padding: '5px 10px', color: 'var(--dsw-alias-label-primary)',
50
+ }
51
+ const FIELD: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12 }
52
+ const INPUT: CSSProperties = {
53
+ width: '100%', boxSizing: 'border-box', padding: '6px 8px', borderRadius: 6,
54
+ border: '1px solid var(--dsw-alias-border-default, rgba(127,127,127,0.3))',
55
+ background: 'transparent', color: 'inherit', font: 'inherit',
56
+ }
57
+ const MUTED: CSSProperties = { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12, margin: 0 }
58
+ const SELECT: CSSProperties = { ...INPUT, cursor: 'pointer' }
59
+
60
+ function option(value: string, label: string, selected: boolean): ReactNode {
61
+ return createElement('option', { key: value, value, selected }, label)
62
+ }
63
+
64
+ function artworkOptions(artifacts: readonly HardwareArtifactInfo[] | undefined, kind: string): ReactNode[] {
65
+ return (artifacts ?? []).filter(artifact => artifact.kind === kind)
66
+ .map(artifact => option(artifact.path, artifact.title || artifact.path, false))
67
+ }
68
+
69
+ /** Five persistent destinations in the conversation header's leading seat. */
70
+ export function EngineeringNav({
71
+ useStore, actions, hooks, useSessions,
72
+ }: SlotProps & {
73
+ useSessions?: (selector: (state: {
74
+ readonly ids: readonly string[]
75
+ readonly byId: Readonly<Record<string, { readonly cwd?: string }>>
76
+ }) => string | undefined) => string | undefined
77
+ }): ReactNode {
78
+ const active = useStore(state => state.activeDestination)
79
+ const projectPath = useStore(state => state.projectPath)
80
+ const cwd = useSessions?.(state => {
81
+ const id = state.ids[0]
82
+ return id === undefined ? undefined : state.byId[id]?.cwd
83
+ })
84
+ useEffect(() => { void hooks.refreshDiscovery(cwd) }, [cwd, hooks])
85
+ return createElement(
86
+ 'div',
87
+ { style: NAV, 'data-hardware-nav': true },
88
+ ...DESTINATIONS.map(destination => createElement(
89
+ 'button',
90
+ {
91
+ key: destination, type: 'button',
92
+ style: destination === active ? ACTIVE : TAB,
93
+ 'aria-pressed': destination === active,
94
+ 'data-destination': destination,
95
+ onClick: () => {
96
+ actions.setActive(destination)
97
+ hooks.openDestination(destination)
98
+ },
99
+ },
100
+ DESTINATION_LABELS[destination],
101
+ )),
102
+ ...(projectPath === undefined ? [] : [createElement('span', { key: 'path', style: PATH, title: projectPath }, projectPath)]),
103
+ )
104
+ }
105
+
106
+ /** The artifact a destination previews, with its canonical identity. */
107
+ export function selectedArtifact(state: HardwareState, destination: HardwareDestination): HardwareArtifactInfo | undefined {
108
+ const project = state.discovery?.selected
109
+ const schematic: HardwareArtifactInfo | undefined = state.schematicPath === undefined
110
+ ? project?.schematic
111
+ : { id: `schematic:${state.schematicPath}`, kind: 'schematic', path: state.schematicPath, title: state.schematicPath.split(/[\\/]/u).pop() ?? state.schematicPath }
112
+ const board: HardwareArtifactInfo | undefined = state.pcbPath === undefined
113
+ ? project?.boards?.find(candidate => candidate.path === project?.defaultBoard) ?? project?.boards?.[0]
114
+ : { id: `pcb:${state.pcbPath}`, kind: 'pcb', path: state.pcbPath, title: state.pcbPath.split(/[\\/]/u).pop() ?? state.pcbPath }
115
+ if (destination === 'schematic' || destination === 'bom') return schematic
116
+ if (destination === 'pcb' || destination === '3d') return board
117
+ return board
118
+ }
119
+
120
+ function missingReason(state: HardwareState, destination: HardwareDestination): string | undefined {
121
+ const discovery = state.discovery
122
+ if (discovery === undefined) return undefined
123
+ if (discovery.issue?.code === 'selection-required' && discovery.projects !== undefined && discovery.projects.length > 1) {
124
+ return `${discovery.projects.length} projects found; choose one explicitly.`
125
+ }
126
+ if (discovery.selected === undefined) return 'No hardware project selected. Open or select a hardware project.'
127
+ if (destination === 'schematic' || destination === 'bom') {
128
+ if (discovery.selected.schematic === undefined) return 'This project has no discoverable root schematic.'
129
+ }
130
+ if (destination === 'pcb' || destination === '3d') {
131
+ if ((discovery.selected.boards?.length ?? 0) === 0) return 'This project has no discoverable .kicad_pcb board.'
132
+ }
133
+ if (destination === 'order') {
134
+ if ((discovery.selected.boards?.length ?? 0) === 0) return 'Select a board before quoting or ordering fabrication.'
135
+ }
136
+ return undefined
137
+ }
138
+
139
+ /** Right-panel body: one destination at a time, with explicit selectors. */
140
+ export function HardwareViewerBody({
141
+ useStore, actions, hooks, tab,
142
+ }: SlotProps & {
143
+ tab?: {
144
+ readonly navigation?: {
145
+ readonly params?: Readonly<Record<string, unknown>>
146
+ readonly revision?: number
147
+ }
148
+ }
149
+ }): ReactNode {
150
+ const active = useStore(state => state.activeDestination)
151
+ const discovery = useStore(state => state.discovery)
152
+ const projectPath = useStore(state => state.projectPath)
153
+ const schematicPath = useStore(state => state.schematicPath)
154
+ const pcbPath = useStore(state => state.pcbPath)
155
+ const notice = useStore(state => state.notice)
156
+ const installations = useStore(state => state.installations)
157
+ const revision = tab?.navigation?.revision ?? 0
158
+ const selectedProject = discovery?.selected
159
+
160
+ useEffect(() => { void hooks.fetchInstallations() }, [hooks])
161
+
162
+ const artifact = useStore(state => selectedArtifact(state, active))
163
+ const reason = useStore(state => missingReason(state, active))
164
+ const application = applicationFor(active)
165
+ const kicadConfigured = installations?.kicad?.configured ?? false
166
+ const nativeLabel = application === 'kicad' ? 'Open in KiCad' : 'No native action'
167
+ const canOpenNative = application !== undefined && kicadConfigured && artifact !== undefined && active !== 'order'
168
+
169
+ const header = createElement(
170
+ 'div',
171
+ { style: HEADER },
172
+ createElement('h2', { style: TITLE }, DESTINATION_LABELS[active]),
173
+ ...(application === undefined ? [] : [createElement(
174
+ 'button',
175
+ {
176
+ key: 'native', type: 'button', style: BUTTON, disabled: !canOpenNative,
177
+ title: canOpenNative
178
+ ? `${nativeLabel}: ${artifact?.path ?? ''}`
179
+ : kicadConfigured
180
+ ? 'Select an artifact before opening it in KiCad.'
181
+ : 'Configure KiCad in Settings → Hardware Engineering.',
182
+ 'data-hardware-native-open': true,
183
+ onClick: () => { void hooks.openNative(application, artifact?.path).catch(error => actions.setNotice(String(error))) },
184
+ },
185
+ nativeLabel,
186
+ )]),
187
+ )
188
+
189
+ const selectors: ReactNode[] = []
190
+ if (discovery !== undefined && (discovery.projects?.length ?? 0) > 0) {
191
+ selectors.push(createElement(
192
+ 'label',
193
+ { key: 'project', style: FIELD },
194
+ 'Project',
195
+ createElement('select', {
196
+ style: SELECT, value: projectPath ?? '',
197
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
198
+ actions.selectProject(event.currentTarget.value)
199
+ void hooks.refreshDiscovery(undefined, event.currentTarget.value)
200
+ },
201
+ },
202
+ option('', 'Select a project…', projectPath === undefined),
203
+ ...(discovery?.projects ?? []).map(project => option(project.path, project.name, project.path === projectPath))),
204
+ ))
205
+ }
206
+ if ((active === 'schematic' || active === 'bom') && selectedProject !== undefined) {
207
+ const candidates: HardwareArtifactInfo[] = [selectedProject.schematic, ...(selectedProject.sheets ?? [])]
208
+ .filter((candidate): candidate is HardwareArtifactInfo => candidate !== undefined)
209
+ selectors.push(createElement(
210
+ 'label',
211
+ { key: 'sheet', style: FIELD },
212
+ 'Schematic / sheet',
213
+ createElement('select', {
214
+ style: SELECT, value: schematicPath ?? '',
215
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
216
+ actions.selectArtifact(event.currentTarget.value, 'schematic')
217
+ hooks.openDestination(active, event.currentTarget.value)
218
+ },
219
+ },
220
+ option('', 'Select a schematic…', schematicPath === undefined),
221
+ ...candidates.map(candidate => option(candidate.path, candidate.title, false))),
222
+ ))
223
+ }
224
+ if ((active === 'pcb' || active === '3d' || active === 'order') && selectedProject !== undefined) {
225
+ selectors.push(createElement(
226
+ 'label',
227
+ { key: 'board', style: FIELD },
228
+ 'Board',
229
+ createElement('select', {
230
+ style: SELECT, value: pcbPath ?? '',
231
+ onChange: (event: ChangeEvent<HTMLSelectElement>) => {
232
+ actions.selectArtifact(event.currentTarget.value, 'pcb')
233
+ hooks.openDestination(active, event.currentTarget.value)
234
+ },
235
+ },
236
+ option('', 'Select a board…', pcbPath === undefined),
237
+ ...artworkOptions(selectedProject.boards, 'pcb')),
238
+ ))
239
+ }
240
+
241
+ return createElement(
242
+ 'div',
243
+ { style: ROOT, 'data-hardware-destination': active },
244
+ header,
245
+ ...(notice === undefined ? [] : [createElement('p', { key: 'notice', style: MUTED, role: 'status' }, notice)]),
246
+ ...(discovery?.issue === undefined || discovery.issue.code === 'selection-required' && (discovery.projects?.length ?? 0) <= 1
247
+ ? []
248
+ : [createElement('p', { key: 'issue', style: MUTED, role: 'status' }, discovery.issue.message)]),
249
+ createElement('p', { key: 'project-path', style: MUTED },
250
+ projectPath === undefined ? 'No canonical KiCad project selected.' : `Project: ${projectPath}`),
251
+ ...selectors,
252
+ ...(reason === undefined
253
+ ? [createElement(HardwarePreview, {
254
+ key: `preview:${revision}`,
255
+ destination: active,
256
+ artifact,
257
+ projectPath,
258
+ revision: revision,
259
+ notice,
260
+ })]
261
+ : [createElement('p', { key: 'reason', style: MUTED, role: 'status', 'data-hardware-state': 'missing' }, reason)]),
262
+ ...(application === undefined || kicadConfigured ? [] : [createElement('p', {
263
+ key: 'unconfigured', style: MUTED,
264
+ }, 'Configure KiCad in Settings → Hardware Engineering to enable previews and native open.')]),
265
+ ...(artifact === undefined || reason !== undefined ? [] : [createElement('p', {
266
+ key: 'identity', style: MUTED, 'data-hardware-identity': true,
267
+ }, `Selected: ${artifact.path}`)]),
268
+ )
269
+ }
270
+
271
+ /** Settings section for the two CAD installation roots. */
272
+ export function HardwareSettingsSection({ hooks }: { readonly hooks: HardwareInjected }): ReactNode {
273
+ const form = hooks.useConfigForm?.()
274
+ const emptySnapshot: { value?: HardwareInstallationConfig } = {}
275
+ const snapshot = useSyncExternalStore<{ value?: HardwareInstallationConfig }>(
276
+ form?.subscribe.bind(form) ?? (() => () => {}),
277
+ form?.getSnapshot.bind(form) ?? (() => emptySnapshot),
278
+ form?.getSnapshot.bind(form) ?? (() => emptySnapshot),
279
+ )
280
+ const value = snapshot.value
281
+ const [kicadRoot, setKicadRoot] = useState(value?.kicadRoot ?? '')
282
+ const [solidcraftRoot, setSolidcraftRoot] = useState(value?.solidcraftRoot ?? '')
283
+ const [message, setMessage] = useState('')
284
+ useEffect(() => {
285
+ setKicadRoot(value?.kicadRoot ?? '')
286
+ setSolidcraftRoot(value?.solidcraftRoot ?? '')
287
+ }, [value?.kicadRoot, value?.solidcraftRoot])
288
+
289
+ const save = async (application: 'kicad' | 'solidcraft', root: string): Promise<void> => {
290
+ try {
291
+ await hooks.saveInstallation(application, root)
292
+ await hooks.fetchInstallations()
293
+ setMessage(`${application === 'kicad' ? 'KiCad' : 'SolidCraft'} installation saved and validated.`)
294
+ } catch (error) {
295
+ setMessage(String(error))
296
+ }
297
+ }
298
+
299
+ return createElement(
300
+ 'div',
301
+ { style: { ...ROOT, height: 'auto' }, 'data-hardware-settings': true },
302
+ createElement('h2', { style: TITLE }, 'Hardware Engineering'),
303
+ createElement('label', { style: FIELD }, 'KiCad installation root or kicad-cli path',
304
+ createElement('input', { style: INPUT, value: kicadRoot, onChange: event => setKicadRoot(event.currentTarget.value) }),
305
+ ),
306
+ createElement('button', { type: 'button', style: BUTTON, onClick: () => { void save('kicad', kicadRoot) } }, 'Validate / Save KiCad'),
307
+ createElement('p', { style: MUTED },
308
+ 'Used for PCB GLB export, native artifact opening, and the agent environment context.'),
309
+ createElement('label', { style: FIELD }, 'SolidCraft installation root or executable path',
310
+ createElement('input', { style: INPUT, value: solidcraftRoot, onChange: event => setSolidcraftRoot(event.currentTarget.value) }),
311
+ ),
312
+ createElement('button', { type: 'button', style: BUTTON, onClick: () => { void save('solidcraft', solidcraftRoot) } }, 'Validate / Save SolidCraft'),
313
+ createElement('p', { style: MUTED },
314
+ 'SolidCraft is agent environment context only in this POC; it has no native open action.'),
315
+ ...(message === '' ? [] : [createElement('p', { style: MUTED, role: 'status' }, message)]),
316
+ )
317
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Saved-file ECAD rendering adapter.
3
+ *
4
+ * Reads the exact saved artifact through the host route, parses it with
5
+ * `@huaqiu/kicad-sexpr-parser` and renders with `@huaqiu/ecad-renderer`'s
6
+ * documented main-thread API. No renderer worker is used: the current worker
7
+ * protocol is parser-only/stubbed in the published renderer.
8
+ */
9
+ import { BoardParser, SchematicParser } from '@huaqiu/kicad-sexpr-parser'
10
+ import { renderPcb, renderSchematic } from '@huaqiu/ecad-renderer'
11
+ import { loadArtifactSource, type ArtifactSource } from './transport.js'
12
+
13
+ export type EcadKind = 'schematic' | 'pcb'
14
+ export interface MountedEcad {
15
+ /** Documented renderer disposal: detaches the canvas and frees GPU resources. */
16
+ dispose(): void
17
+ readonly sourceRevision: string
18
+ readonly source: ArtifactSource
19
+ }
20
+
21
+ export function isAbortError(error: unknown): boolean {
22
+ return error instanceof Error && error.name === 'AbortError'
23
+ }
24
+
25
+ function aborted(signal: AbortSignal): DOMException {
26
+ return new DOMException('render abandoned: navigation changed', 'AbortError')
27
+ }
28
+
29
+ /**
30
+ * Mount one parsed artifact into `container`.
31
+ *
32
+ * The abort signal is checked after every asynchronous step; a result that
33
+ * arrives after the navigation changed is disposed instead of attached, so a
34
+ * late fetch or a slow parse can never paint into an obsolete viewer.
35
+ */
36
+ export async function mountEcad(
37
+ kind: EcadKind,
38
+ artifactPath: string,
39
+ container: HTMLElement,
40
+ options: { readonly signal: AbortSignal; readonly revision?: string },
41
+ ): Promise<MountedEcad> {
42
+ const source = await loadArtifactSource(artifactPath, options.signal, options.revision)
43
+ if (options.signal.aborted) throw aborted(options.signal)
44
+ if (source.kind !== undefined && source.kind !== kind) {
45
+ throw new Error(`host returned a ${source.kind} artifact for a ${kind} preview`)
46
+ }
47
+
48
+ let rendered
49
+ if (kind === 'schematic') {
50
+ rendered = await renderSchematic(new SchematicParser().parse(source.text), { container, interactive: true })
51
+ } else {
52
+ rendered = await renderPcb(new BoardParser().parse(source.text), { container, interactive: true })
53
+ }
54
+
55
+ if (options.signal.aborted) {
56
+ rendered.dispose()
57
+ throw aborted(options.signal)
58
+ }
59
+
60
+ return {
61
+ dispose: () => { rendered.dispose() },
62
+ sourceRevision: source.revision,
63
+ source,
64
+ }
65
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Three.js viewer for the host-generated PCB GLB.
3
+ *
4
+ * The GLB is a derived output: the `.kicad_pcb` stays authoritative and the
5
+ * viewer keeps the source revision visible. Only GLTFLoader from `three` is
6
+ * used; no editor, no external asset URL.
7
+ */
8
+ import {
9
+ AmbientLight, Box3, Color, DirectionalLight, PerspectiveCamera, Scene, Vector3, WebGLRenderer,
10
+ } from 'three'
11
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
12
+
13
+ export interface MountedGlb {
14
+ dispose(): void
15
+ }
16
+
17
+ export interface GlbViewerOptions {
18
+ readonly signal: AbortSignal
19
+ readonly background?: string
20
+ }
21
+
22
+ function aborted(signal: AbortSignal): DOMException {
23
+ return new DOMException('3D view abandoned: navigation changed', 'AbortError')
24
+ }
25
+
26
+ /**
27
+ * Load and display one GLB URL inside `container`.
28
+ *
29
+ * Drag rotates, the wheel zooms, and the camera is fitted to the model bounds.
30
+ * Disposal removes the canvas and frees GPU resources; an aborted mount never
31
+ * installs a listener or leaves a canvas behind.
32
+ */
33
+ export async function mountGlb(url: string, container: HTMLElement, options: GlbViewerOptions): Promise<MountedGlb> {
34
+ const scene = new Scene()
35
+ const background = new Color(options.background ?? '#111318')
36
+ scene.background = background
37
+
38
+ const camera = new PerspectiveCamera(45, 1, 0.1, 10_000)
39
+ const renderer = new WebGLRenderer({ antialias: true, alpha: false })
40
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2))
41
+
42
+ const loader = new GLTFLoader()
43
+ const gltf = await loader.loadAsync(url)
44
+ if (options.signal.aborted) {
45
+ disposeGltf(gltf.scene)
46
+ renderer.dispose()
47
+ throw aborted(options.signal)
48
+ }
49
+
50
+ scene.add(gltf.scene)
51
+ scene.add(new AmbientLight(0xffffff, 1.2))
52
+ const key = new DirectionalLight(0xffffff, 2)
53
+ key.position.set(40, 60, 30)
54
+ scene.add(key)
55
+ const fill = new DirectionalLight(0xffffff, 1)
56
+ fill.position.set(-30, -20, -40)
57
+ scene.add(fill)
58
+
59
+ const bounds = new Box3().setFromObject(gltf.scene)
60
+ const center = bounds.getCenter(new Vector3())
61
+ const size = bounds.getSize(new Vector3())
62
+ const radius = Math.max(size.x, size.y, size.z, 0.001) / 2
63
+ const distance = radius / Math.sin(Math.PI / 8)
64
+
65
+ let yaw = 0.6
66
+ let pitch = 0.45
67
+ let zoom = 1
68
+ const place = (): void => {
69
+ const horizontal = distance * zoom
70
+ camera.position.set(
71
+ center.x + horizontal * Math.cos(pitch) * Math.sin(yaw),
72
+ center.y + horizontal * Math.sin(pitch),
73
+ center.z + horizontal * Math.cos(pitch) * Math.cos(yaw),
74
+ )
75
+ camera.lookAt(center)
76
+ camera.near = Math.max(radius / 1000, 0.01)
77
+ camera.far = distance * 20
78
+ camera.updateProjectionMatrix()
79
+ }
80
+ place()
81
+
82
+ let dragging = false
83
+ let lastX = 0
84
+ let lastY = 0
85
+ const onPointerDown = (event: PointerEvent): void => {
86
+ dragging = true
87
+ lastX = event.clientX
88
+ lastY = event.clientY
89
+ renderer.domElement.setPointerCapture(event.pointerId)
90
+ }
91
+ const onPointerMove = (event: PointerEvent): void => {
92
+ if (!dragging) return
93
+ const dx = event.clientX - lastX
94
+ const dy = event.clientY - lastY
95
+ lastX = event.clientX
96
+ lastY = event.clientY
97
+ yaw -= dx * 0.01
98
+ pitch = Math.max(-1.45, Math.min(1.45, pitch + dy * 0.01))
99
+ place()
100
+ draw()
101
+ }
102
+ const onPointerUp = (event: PointerEvent): void => {
103
+ dragging = false
104
+ if (renderer.domElement.hasPointerCapture(event.pointerId)) renderer.domElement.releasePointerCapture(event.pointerId)
105
+ }
106
+ const onWheel = (event: WheelEvent): void => {
107
+ event.preventDefault()
108
+ zoom = Math.max(0.2, Math.min(8, zoom * (event.deltaY > 0 ? 1.1 : 0.9)))
109
+ place()
110
+ draw()
111
+ }
112
+
113
+ const resize = (): void => {
114
+ const width = Math.max(container.clientWidth, 240)
115
+ const height = Math.max(container.clientHeight, 220)
116
+ renderer.setSize(width, height, false)
117
+ camera.aspect = width / height
118
+ camera.updateProjectionMatrix()
119
+ draw()
120
+ }
121
+
122
+ let frame = 0
123
+ const draw = (): void => {
124
+ if (frame !== 0) return
125
+ frame = requestAnimationFrame(() => {
126
+ frame = 0
127
+ renderer.render(scene, camera)
128
+ })
129
+ }
130
+
131
+ const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(resize)
132
+ observer?.observe(container)
133
+ renderer.domElement.style.cssText = 'display:block;width:100%;height:100%;touch-action:none;cursor:grab'
134
+ renderer.domElement.addEventListener('pointerdown', onPointerDown)
135
+ renderer.domElement.addEventListener('pointermove', onPointerMove)
136
+ renderer.domElement.addEventListener('pointerup', onPointerUp)
137
+ renderer.domElement.addEventListener('pointercancel', onPointerUp)
138
+ renderer.domElement.addEventListener('wheel', onWheel, { passive: false })
139
+ container.append(renderer.domElement)
140
+ resize()
141
+
142
+ return {
143
+ dispose: () => {
144
+ if (frame !== 0) cancelAnimationFrame(frame)
145
+ observer?.disconnect()
146
+ renderer.domElement.removeEventListener('pointerdown', onPointerDown)
147
+ renderer.domElement.removeEventListener('pointermove', onPointerMove)
148
+ renderer.domElement.removeEventListener('pointerup', onPointerUp)
149
+ renderer.domElement.removeEventListener('pointercancel', onPointerUp)
150
+ renderer.domElement.removeEventListener('wheel', onWheel)
151
+ renderer.domElement.remove()
152
+ disposeGltf(gltf.scene)
153
+ renderer.dispose()
154
+ scene.clear()
155
+ },
156
+ }
157
+ }
158
+
159
+ /** Release geometries, materials and textures owned by the loaded scene. */
160
+ function disposeGltf(root: { traverse(callback: (object: unknown) => void): void }): void {
161
+ root.traverse((object) => {
162
+ const mesh = object as {
163
+ geometry?: { dispose(): void }
164
+ material?: { dispose(): void } | readonly { dispose(): void }[]
165
+ }
166
+ mesh.geometry?.dispose()
167
+ const material = mesh.material
168
+ if (Array.isArray(material)) for (const entry of material) entry.dispose()
169
+ else (material as { dispose(): void } | undefined)?.dispose()
170
+ })
171
+ }