@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.
- package/lib/client.js +9612 -632
- package/lib/client.js.map +1 -1
- package/lib/index.d.mts +35 -14
- package/lib/index.mjs +118 -10
- package/package.json +8 -4
- package/src/client/brand.ts +17 -0
- package/src/client/components.tsx +26 -133
- package/src/client/copy.ts +372 -243
- package/src/client/document/EcadBody.tsx +212 -0
- package/src/client/document/StepBody.tsx +124 -0
- package/src/client/document/contract.ts +156 -0
- package/src/client/document/copy.ts +49 -0
- package/src/client/document/index.ts +134 -0
- package/src/client/document/mount.ts +261 -0
- package/src/client/document/occt.d.ts +54 -0
- package/src/client/document/paths.ts +122 -0
- package/src/client/document/sheets.ts +83 -0
- package/src/client/document/step.ts +255 -0
- package/src/client/index.ts +172 -4
- package/src/client/locales.ts +604 -0
- package/src/client/model.ts +18 -9
- package/src/client/order-page.ts +44 -0
- package/src/client/order-tab.tsx +117 -0
- package/src/client/order-watcher.ts +121 -0
- package/src/client/order.tsx +9 -9
- package/src/client/toolchain-view.tsx +724 -0
- package/src/client/toolchain.ts +620 -0
- package/src/client/transport.ts +83 -4
- package/src/client/wizard.tsx +312 -261
- package/src/index.ts +126 -10
- package/src/shared/occt-asset.ts +21 -0
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mount a workspace document's ECAD content into a container.
|
|
3
|
+
*
|
|
4
|
+
* This is the document-preview sibling of `../ecad.ts`, not a replacement: the
|
|
5
|
+
* product viewer reads its artifact through the hardware-artifacts host route,
|
|
6
|
+
* while a document preview already *has* the file bytes from DSH's own
|
|
7
|
+
* workspace read. Same parser, same renderer, different content source — which
|
|
8
|
+
* is the whole point of the difference (`docs/tasks/…full-impl-code-spec.md`
|
|
9
|
+
* §5.3: do not merge the two implementations to share a little code).
|
|
10
|
+
*
|
|
11
|
+
* Behaviour the document seat requires, and how each is met:
|
|
12
|
+
*
|
|
13
|
+
* - **A late result never paints.** Every asynchronous step is followed by an
|
|
14
|
+
* abort check, and a render that settles after the tab or the revision moved
|
|
15
|
+
* on is disposed instead of attached.
|
|
16
|
+
* - **A failed render is a value, not a crash.** The caller receives a rejected
|
|
17
|
+
* promise carrying a readable message; the body renders it inside the
|
|
18
|
+
* document.
|
|
19
|
+
* - **Nothing outlives the document.** `dispose()` releases the renderer's own
|
|
20
|
+
* GPU resources and removes the canvas this module created — the renderer's
|
|
21
|
+
* `dispose()` detaches its listeners but leaves the element in place.
|
|
22
|
+
* - **A zero-sized host is waited for, never fitted into.** The renderer fits the
|
|
23
|
+
* view during `load()` against the canvas it is given, so mounting into a box
|
|
24
|
+
* that has no layout yet would fit to nothing; the mount waits for a
|
|
25
|
+
* measurable box and gives up only when the document itself goes away.
|
|
26
|
+
* - **A timeout is a real deadline.** A render that never settles is abandoned
|
|
27
|
+
* with a readable message instead of leaving the body loading forever.
|
|
28
|
+
*
|
|
29
|
+
* @module @huaqiu/dsh-hardware-ui/client/document/mount
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { BoardParser, SchematicParser, type boardProto, type schematicProto } from '@huaqiu/kicad-sexpr-parser'
|
|
33
|
+
import { renderPcb, renderSchematic } from '@huaqiu/ecad-renderer'
|
|
34
|
+
|
|
35
|
+
/** Kinds of ECAD document this adapter renders. */
|
|
36
|
+
export type EcadDocumentKind = 'schematic' | 'pcb'
|
|
37
|
+
|
|
38
|
+
/** A renderer attached to a live document body. */
|
|
39
|
+
export interface MountedEcadDocument {
|
|
40
|
+
/** Release the renderer and the canvas it was mounted into. Idempotent. */
|
|
41
|
+
dispose(): void
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Why a mount failed, without losing the renderer's own message. */
|
|
45
|
+
export class DocumentRenderError extends Error {
|
|
46
|
+
readonly reason: 'parse' | 'render' | 'timeout' | 'aborted' | 'toolarge'
|
|
47
|
+
|
|
48
|
+
constructor(reason: DocumentRenderError['reason'], message: string) {
|
|
49
|
+
super(message)
|
|
50
|
+
this.name = 'DocumentRenderError'
|
|
51
|
+
this.reason = reason
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Content size above which a document is refused before parsing. */
|
|
56
|
+
export const MAX_DOCUMENT_BYTES = 32 * 1024 * 1024
|
|
57
|
+
/** Default ceiling for one mount, generous enough for a large board on a cold start. */
|
|
58
|
+
export const DEFAULT_RENDER_TIMEOUT_MS = 30_000
|
|
59
|
+
|
|
60
|
+
export function isAbortError(error: unknown): boolean {
|
|
61
|
+
return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function abortError(signal: AbortSignal): DocumentRenderError {
|
|
65
|
+
const reason = signal.reason instanceof Error ? signal.reason.message : 'render abandoned'
|
|
66
|
+
return new DocumentRenderError('aborted', reason)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function messageOf(error: unknown): string {
|
|
70
|
+
if (error instanceof Error) return error.message
|
|
71
|
+
return typeof error === 'string' ? error : 'unknown error'
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Wait until a container has a measurable box.
|
|
76
|
+
*
|
|
77
|
+
* A document body is laid out by the panel's flex column, so the first effect
|
|
78
|
+
* can run before the box exists — and a tab restored into a collapsed panel has
|
|
79
|
+
* no box at all until the user expands it. The wait therefore has no deadline of
|
|
80
|
+
* its own: it ends when the box appears or when the document goes away. Failing
|
|
81
|
+
* on a timer would turn "the panel is collapsed" into a rendering error the user
|
|
82
|
+
* has to dismiss; waiting leaves the loading line up until there is somewhere to
|
|
83
|
+
* draw, which is what is actually happening.
|
|
84
|
+
* @param container - element the renderer will fill.
|
|
85
|
+
* @param signal - document lifetime; the only thing that ends the wait empty-handed.
|
|
86
|
+
*/
|
|
87
|
+
export async function waitForLayout(container: HTMLElement, signal: AbortSignal): Promise<void> {
|
|
88
|
+
const measurable = (): boolean => container.clientWidth > 0 && container.clientHeight > 0
|
|
89
|
+
if (measurable()) return
|
|
90
|
+
await new Promise<void>((resolve, reject) => {
|
|
91
|
+
let settled = false
|
|
92
|
+
const finish = (error?: DocumentRenderError): void => {
|
|
93
|
+
if (settled) return
|
|
94
|
+
settled = true
|
|
95
|
+
observer?.disconnect()
|
|
96
|
+
signal.removeEventListener('abort', onAbort)
|
|
97
|
+
if (error === undefined) resolve()
|
|
98
|
+
else reject(error)
|
|
99
|
+
}
|
|
100
|
+
const onAbort = (): void => { finish(abortError(signal)) }
|
|
101
|
+
const observer = typeof ResizeObserver === 'undefined'
|
|
102
|
+
? undefined
|
|
103
|
+
: new ResizeObserver(() => { if (measurable()) finish() })
|
|
104
|
+
observer?.observe(container)
|
|
105
|
+
if (signal.aborted) {
|
|
106
|
+
finish(abortError(signal))
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
110
|
+
// A tab that mounts while the pane is animating in has no box in the first
|
|
111
|
+
// frame but does in the next; the observer alone would wait for a change.
|
|
112
|
+
requestAnimationFrame(() => { if (measurable()) finish() })
|
|
113
|
+
})
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Run one renderer promise under a deadline, disposing a result that arrives too late. */
|
|
117
|
+
async function withinDeadline<T extends { dispose(): void }>(
|
|
118
|
+
work: Promise<T>,
|
|
119
|
+
signal: AbortSignal,
|
|
120
|
+
timeoutMs: number,
|
|
121
|
+
): Promise<T> {
|
|
122
|
+
let abandoned = false
|
|
123
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
124
|
+
let onAbort: (() => void) | undefined
|
|
125
|
+
const release = (): void => {
|
|
126
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
127
|
+
if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
|
|
128
|
+
}
|
|
129
|
+
// A render that settles after the deadline must still free its GPU resources;
|
|
130
|
+
// nothing else holds a reference to it by then.
|
|
131
|
+
const disposeIfAbandoned = (): void => {
|
|
132
|
+
if (!abandoned) return
|
|
133
|
+
void work.then(result => { result.dispose() }, () => {})
|
|
134
|
+
}
|
|
135
|
+
const deadline = new Promise<never>((_resolve, reject) => {
|
|
136
|
+
onAbort = (): void => {
|
|
137
|
+
abandoned = true
|
|
138
|
+
disposeIfAbandoned()
|
|
139
|
+
reject(abortError(signal))
|
|
140
|
+
}
|
|
141
|
+
if (signal.aborted) {
|
|
142
|
+
onAbort()
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
146
|
+
timer = setTimeout(() => {
|
|
147
|
+
abandoned = true
|
|
148
|
+
disposeIfAbandoned()
|
|
149
|
+
reject(new DocumentRenderError('timeout', `render did not finish within ${timeoutMs}ms`))
|
|
150
|
+
}, timeoutMs)
|
|
151
|
+
})
|
|
152
|
+
try {
|
|
153
|
+
const result = await Promise.race([work, deadline])
|
|
154
|
+
if (abandoned || signal.aborted) {
|
|
155
|
+
result.dispose()
|
|
156
|
+
throw abortError(signal)
|
|
157
|
+
}
|
|
158
|
+
return result
|
|
159
|
+
} finally {
|
|
160
|
+
release()
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Create the absolutely-positioned canvas the renderer draws into. */
|
|
165
|
+
function createCanvas(container: HTMLElement): HTMLCanvasElement {
|
|
166
|
+
const canvas = document.createElement('canvas')
|
|
167
|
+
// The renderer owns the backing resolution but not the CSS box. Handing it an
|
|
168
|
+
// already-sized canvas is what makes its first fit match the panel instead of
|
|
169
|
+
// its 300x150 default.
|
|
170
|
+
canvas.style.cssText = 'position:absolute;inset:0;display:block;width:100%;height:100%;outline:none'
|
|
171
|
+
canvas.dataset.ecadCanvas = ''
|
|
172
|
+
container.append(canvas)
|
|
173
|
+
return canvas
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Parse ECAD source text with the shared parser, reporting the parser's own message. */
|
|
177
|
+
export function parseEcadSource(kind: EcadDocumentKind, text: string): schematicProto.I_KicadSch | boardProto.I_KicadPCB {
|
|
178
|
+
try {
|
|
179
|
+
return kind === 'schematic' ? new SchematicParser().parse(text) : new BoardParser().parse(text)
|
|
180
|
+
} catch (error) {
|
|
181
|
+
throw new DocumentRenderError('parse', messageOf(error))
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface EcadDocumentRequest {
|
|
186
|
+
readonly kind: EcadDocumentKind
|
|
187
|
+
/** Decoded document text; the file itself stays authoritative and is never written back. */
|
|
188
|
+
readonly text: string
|
|
189
|
+
readonly container: HTMLElement
|
|
190
|
+
/** Document lifetime: the tab's signal, or a superseded revision's controller. */
|
|
191
|
+
readonly signal: AbortSignal
|
|
192
|
+
readonly timeoutMs?: number
|
|
193
|
+
/** Parsed model, when the caller already parsed it to read the sheet hierarchy. */
|
|
194
|
+
readonly parsed?: schematicProto.I_KicadSch | boardProto.I_KicadPCB
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Parse, render and attach one ECAD document.
|
|
199
|
+
* @param request - content, target container, lifetime and deadline.
|
|
200
|
+
* @returns the live mount; call `dispose()` when the document closes or reloads.
|
|
201
|
+
*/
|
|
202
|
+
export async function mountEcadDocument(request: EcadDocumentRequest): Promise<MountedEcadDocument> {
|
|
203
|
+
const { kind, text, container, signal } = request
|
|
204
|
+
const timeoutMs = request.timeoutMs ?? DEFAULT_RENDER_TIMEOUT_MS
|
|
205
|
+
if (signal.aborted) throw abortError(signal)
|
|
206
|
+
await waitForLayout(container, signal)
|
|
207
|
+
if (signal.aborted) throw abortError(signal)
|
|
208
|
+
|
|
209
|
+
// Parsing is synchronous and can block for a large board; yield once so the
|
|
210
|
+
// document body paints its loading state before the main thread stalls.
|
|
211
|
+
await new Promise<void>((resolve) => { requestAnimationFrame(() => { resolve() }) })
|
|
212
|
+
if (signal.aborted) throw abortError(signal)
|
|
213
|
+
|
|
214
|
+
const parsed = request.parsed ?? parseEcadSource(kind, text)
|
|
215
|
+
if (signal.aborted) throw abortError(signal)
|
|
216
|
+
|
|
217
|
+
const canvas = createCanvas(container)
|
|
218
|
+
let rendered
|
|
219
|
+
try {
|
|
220
|
+
rendered = await withinDeadline(
|
|
221
|
+
kind === 'schematic'
|
|
222
|
+
? renderSchematic(parsed as schematicProto.I_KicadSch, { canvas, container, interactive: true })
|
|
223
|
+
: renderPcb(parsed as boardProto.I_KicadPCB, { canvas, container, interactive: true }),
|
|
224
|
+
signal,
|
|
225
|
+
timeoutMs,
|
|
226
|
+
)
|
|
227
|
+
} catch (error) {
|
|
228
|
+
canvas.remove()
|
|
229
|
+
if (error instanceof DocumentRenderError) throw error
|
|
230
|
+
throw new DocumentRenderError('render', messageOf(error))
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// The renderer fits once during `load()`, before the document body has its
|
|
234
|
+
// final box. Re-fit after two painted frames so the first view matches the
|
|
235
|
+
// panel; only at mount, because a later resize must not undo the user's own
|
|
236
|
+
// pan and zoom.
|
|
237
|
+
const viewer = rendered.viewer as { zoom_fit_top_item?: () => void }
|
|
238
|
+
if (typeof viewer.zoom_fit_top_item === 'function') {
|
|
239
|
+
await new Promise<void>((resolve) => {
|
|
240
|
+
requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) })
|
|
241
|
+
})
|
|
242
|
+
if (!signal.aborted) {
|
|
243
|
+
try {
|
|
244
|
+
viewer.zoom_fit_top_item()
|
|
245
|
+
} catch {
|
|
246
|
+
// A viewer that has been disposed by its own aborted load cannot fit;
|
|
247
|
+
// the drawn frame is still valid, so this is not a mount failure.
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
let disposed = false
|
|
253
|
+
return {
|
|
254
|
+
dispose: () => {
|
|
255
|
+
if (disposed) return
|
|
256
|
+
disposed = true
|
|
257
|
+
rendered.dispose()
|
|
258
|
+
canvas.remove()
|
|
259
|
+
},
|
|
260
|
+
}
|
|
261
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ambient types for `occt-import-js` (OpenCascade STEP/IGES/BREP reader).
|
|
3
|
+
*
|
|
4
|
+
* The package ships the emscripten glue and the `.wasm` but no type
|
|
5
|
+
* declarations, and its API is registered through embind at instantiation, so
|
|
6
|
+
* these types describe what the module exposes *after* `ready` resolves — as
|
|
7
|
+
* documented by the package README (`occt.ReadStepFile(buffer, params)`).
|
|
8
|
+
*
|
|
9
|
+
* @module @huaqiu/dsh-hardware-ui/client/document/occt
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
declare module 'occt-import-js' {
|
|
13
|
+
/** One tessellated solid: triangle soup plus an optional per-solid color. */
|
|
14
|
+
export interface OcctMesh {
|
|
15
|
+
readonly name?: string
|
|
16
|
+
readonly color?: readonly number[]
|
|
17
|
+
readonly attributes: {
|
|
18
|
+
readonly position: { readonly array: readonly number[] }
|
|
19
|
+
readonly normal?: { readonly array: readonly number[] }
|
|
20
|
+
}
|
|
21
|
+
readonly index?: { readonly array: readonly number[] }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Result of one import; `success` false means no geometry was produced. */
|
|
25
|
+
export interface OcctImportResult {
|
|
26
|
+
readonly success: boolean
|
|
27
|
+
readonly root?: unknown
|
|
28
|
+
readonly meshes: readonly OcctMesh[]
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The instantiated module's import entry points. */
|
|
32
|
+
export interface OcctModule {
|
|
33
|
+
ReadStepFile(buffer: Uint8Array, params: Record<string, unknown> | null): OcctImportResult
|
|
34
|
+
ReadIgesFile?(buffer: Uint8Array, params: Record<string, unknown> | null): OcctImportResult
|
|
35
|
+
ReadBrepFile?(buffer: Uint8Array, params: Record<string, unknown> | null): OcctImportResult
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Emscripten module overrides this package relies on. */
|
|
39
|
+
export interface OcctModuleOptions {
|
|
40
|
+
/** Complete `.wasm` bytes; supplying them keeps the module offline and path-independent. */
|
|
41
|
+
wasmBinary?: ArrayBuffer
|
|
42
|
+
/** Fallback used only when `wasmBinary` is absent. */
|
|
43
|
+
locateFile?(path: string, prefix: string): string
|
|
44
|
+
print?(text: string): void
|
|
45
|
+
printErr?(text: string): void
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Instantiate the reader.
|
|
50
|
+
* @param options - wasm source and logging hooks.
|
|
51
|
+
* @returns the ready module.
|
|
52
|
+
*/
|
|
53
|
+
export default function occtimportjs(options?: OcctModuleOptions): Promise<OcctModule>
|
|
54
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path arithmetic for a document preview.
|
|
3
|
+
*
|
|
4
|
+
* Two jobs, both deliberately narrow:
|
|
5
|
+
*
|
|
6
|
+
* 1. Turn the tab's `dsh-resource://file/…` address back into the path the Host
|
|
7
|
+
* reads. Grammar transcribed from
|
|
8
|
+
* `@deepseek-ai/dsh-util-workspace-path/src/file-address.ts:42-116`; an
|
|
9
|
+
* address outside the two known scopes is a programming error, exactly as in
|
|
10
|
+
* the framework's own `hostFileOf`.
|
|
11
|
+
* 2. Resolve a child schematic's `Sheet file` property against the owning
|
|
12
|
+
* document. KiCad writes those references with `/` separators on every
|
|
13
|
+
* platform, relative to the sheet that declares them, and allows `..`.
|
|
14
|
+
*
|
|
15
|
+
* Nothing here touches the filesystem: resolution is string arithmetic, and the
|
|
16
|
+
* Host remains the only authority on whether a resolved path exists.
|
|
17
|
+
*
|
|
18
|
+
* @module @huaqiu/dsh-hardware-ui/client/document/paths
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const FILE_ADDRESS_PREFIX = 'dsh-resource://file/'
|
|
22
|
+
|
|
23
|
+
/** A file address decomposed far enough to read it. */
|
|
24
|
+
export interface DocumentFilePath {
|
|
25
|
+
readonly scope: 'session' | 'absolute'
|
|
26
|
+
/** Session whose workspace resolves a relative path; absent for an absolute address. */
|
|
27
|
+
readonly sessionId?: string
|
|
28
|
+
/** Path handed to the Host. */
|
|
29
|
+
readonly path: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function decode(segment: string): string | undefined {
|
|
33
|
+
try {
|
|
34
|
+
return decodeURIComponent(segment)
|
|
35
|
+
} catch {
|
|
36
|
+
return undefined
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Read one document resource address.
|
|
42
|
+
* @param address - a tab's `dsh-resource://file/…` address.
|
|
43
|
+
* @returns its scope, session and path, or undefined when the address is not one this preview can read.
|
|
44
|
+
*/
|
|
45
|
+
export function documentFilePath(address: string): DocumentFilePath | undefined {
|
|
46
|
+
if (!address.startsWith(FILE_ADDRESS_PREFIX)) return undefined
|
|
47
|
+
const end = address.search(/[?#]/)
|
|
48
|
+
const body = address.slice(FILE_ADDRESS_PREFIX.length, end === -1 ? undefined : end)
|
|
49
|
+
const segments = body.split('/')
|
|
50
|
+
const scope = segments[0]
|
|
51
|
+
const rest = segments.slice(1)
|
|
52
|
+
if (scope === 'session') {
|
|
53
|
+
const id = rest[0]
|
|
54
|
+
if (id === undefined || id === '') return undefined
|
|
55
|
+
const sessionId = decode(id)
|
|
56
|
+
const path = rest.slice(1).map(decode)
|
|
57
|
+
if (sessionId === undefined || path.length === 0 || path.some(part => part === undefined)) return undefined
|
|
58
|
+
return { scope, sessionId, path: (path as string[]).join('/') }
|
|
59
|
+
}
|
|
60
|
+
if (scope === 'absolute') {
|
|
61
|
+
const parts = rest.map(decode)
|
|
62
|
+
if (parts.length === 0 || parts.some(part => part === undefined)) return undefined
|
|
63
|
+
return { scope, path: `/${(parts as string[]).join('/')}` }
|
|
64
|
+
}
|
|
65
|
+
return undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Split a KiCad-style path into the directory part and the final name. */
|
|
69
|
+
export function splitPath(path: string): { readonly directory: string; readonly name: string } {
|
|
70
|
+
const normalized = path.replaceAll('\\', '/')
|
|
71
|
+
const slash = normalized.lastIndexOf('/')
|
|
72
|
+
return slash === -1
|
|
73
|
+
? { directory: '', name: normalized }
|
|
74
|
+
: { directory: normalized.slice(0, slash), name: normalized.slice(slash + 1) }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Resolve a reference declared by a document against that document's path.
|
|
79
|
+
*
|
|
80
|
+
* Relative references are joined and then collapsed segment by segment, so
|
|
81
|
+
* `../shared/power.kicad_sch` from `boards/a/main.kicad_sch` becomes
|
|
82
|
+
* `boards/shared/power.kicad_sch`. A reference that escapes above the owning
|
|
83
|
+
* directory is still returned as written — the Host, not this module, decides
|
|
84
|
+
* whether that path is inside the authorized workspace.
|
|
85
|
+
* @param ownerPath - path of the document that declares the reference.
|
|
86
|
+
* @param reference - the declared reference, `/`- or `\`-separated.
|
|
87
|
+
* @returns the resolved path, or undefined for an empty reference.
|
|
88
|
+
*/
|
|
89
|
+
export function resolveReference(ownerPath: string, reference: string): string | undefined {
|
|
90
|
+
const trimmed = reference.trim().replaceAll('\\', '/')
|
|
91
|
+
if (trimmed === '') return undefined
|
|
92
|
+
// An absolute reference is already a complete path; only `..` needs collapsing.
|
|
93
|
+
const absolute = trimmed.startsWith('/') || /^[A-Za-z]:\//.test(trimmed)
|
|
94
|
+
const base = absolute ? '' : splitPath(ownerPath).directory
|
|
95
|
+
const joined = absolute ? trimmed : `${base}/${trimmed}`
|
|
96
|
+
const segments: string[] = []
|
|
97
|
+
for (const segment of joined.split('/')) {
|
|
98
|
+
if (segment === '' || segment === '.') continue
|
|
99
|
+
if (segment === '..') {
|
|
100
|
+
// Keep an unresolvable `..` instead of silently climbing above the workspace.
|
|
101
|
+
if (segments.length === 0 || segments[segments.length - 1] === '..') segments.push('..')
|
|
102
|
+
else segments.pop()
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
segments.push(segment)
|
|
106
|
+
}
|
|
107
|
+
if (segments.length === 0) return undefined
|
|
108
|
+
const resolved = segments.join('/')
|
|
109
|
+
// A drive-qualified path keeps its own root marker; only a POSIX absolute
|
|
110
|
+
// reference needs one added back.
|
|
111
|
+
return absolute && trimmed.startsWith('/') ? `/${resolved}` : resolved
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Name a path for display inside a document body.
|
|
116
|
+
* @param path - resolved or declared path.
|
|
117
|
+
* @returns the final segment, or the whole path when it has none.
|
|
118
|
+
*/
|
|
119
|
+
export function displayName(path: string): string {
|
|
120
|
+
const { name } = splitPath(path)
|
|
121
|
+
return name === '' ? path : name
|
|
122
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hierarchical child-sheet discovery for a standalone `.kicad_sch`.
|
|
3
|
+
*
|
|
4
|
+
* The rule this module exists to enforce: a child sheet is a sheet the file
|
|
5
|
+
* *declares*, never a `.kicad_sch` that happens to sit next to it. A workspace
|
|
6
|
+
* routinely holds several unrelated schematics in one directory, and merging
|
|
7
|
+
* them by proximity would invent a hierarchy the designer never drew.
|
|
8
|
+
*
|
|
9
|
+
* What KiCad actually writes is a `sheet` node whose `Sheet file` property names
|
|
10
|
+
* the child document, relative to the sheet that declares it:
|
|
11
|
+
*
|
|
12
|
+
* ```sexpr
|
|
13
|
+
* (sheet (at 63.5 45.72) (size 25.4 19.05)
|
|
14
|
+
* (property "Sheetname" "Power" …)
|
|
15
|
+
* (property "Sheet file" "power.kicad_sch" …)
|
|
16
|
+
* (instances …))
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* `I_SchematicSheet.properties` carries those pairs verbatim
|
|
20
|
+
* (`@huaqiu/kicad-sexpr-parser/dist/proto/schematic.d.ts:274-296`), so discovery
|
|
21
|
+
* needs no second parser and no project file.
|
|
22
|
+
*
|
|
23
|
+
* @module @huaqiu/dsh-hardware-ui/client/document/sheets
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { resolveReference } from './paths.js'
|
|
27
|
+
|
|
28
|
+
/** One child sheet a schematic declares. */
|
|
29
|
+
export interface SheetReference {
|
|
30
|
+
/** `Sheetname` as drawn, for display; falls back to the file name. */
|
|
31
|
+
readonly label: string
|
|
32
|
+
/** Path as written in the file. */
|
|
33
|
+
readonly declared: string
|
|
34
|
+
/** Resolved against the owning document; undefined when the reference is unusable. */
|
|
35
|
+
readonly resolved?: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Property names KiCad has used for the child document across format versions. */
|
|
39
|
+
const FILE_PROPERTY_NAMES = ['Sheet file', 'Sheetfile', 'SheetFile'] as const
|
|
40
|
+
/** Property names KiCad has used for the sheet's displayed name. */
|
|
41
|
+
const NAME_PROPERTY_NAMES = ['Sheetname', 'Sheet name', 'SheetName'] as const
|
|
42
|
+
|
|
43
|
+
interface PropertyLike {
|
|
44
|
+
readonly name?: unknown
|
|
45
|
+
readonly text?: unknown
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface SheetLike {
|
|
49
|
+
readonly properties?: readonly PropertyLike[]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function propertyText(properties: readonly PropertyLike[], names: readonly string[]): string | undefined {
|
|
53
|
+
for (const name of names) {
|
|
54
|
+
const hit = properties.find(property => property.name === name)
|
|
55
|
+
if (hit !== undefined && typeof hit.text === 'string' && hit.text.trim() !== '') return hit.text
|
|
56
|
+
}
|
|
57
|
+
return undefined
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* List the child documents a parsed schematic declares, in declaration order.
|
|
62
|
+
* @param schematic - parsed schematic (`I_KicadSch`); only `sheets` is read.
|
|
63
|
+
* @param ownerPath - path of the document these sheets belong to.
|
|
64
|
+
* @returns one entry per declared sheet, de-duplicated by resolved path.
|
|
65
|
+
*/
|
|
66
|
+
export function sheetReferences(schematic: unknown, ownerPath: string): readonly SheetReference[] {
|
|
67
|
+
const sheets = (schematic as { sheets?: unknown } | undefined)?.sheets
|
|
68
|
+
if (!Array.isArray(sheets)) return []
|
|
69
|
+
const seen = new Set<string>()
|
|
70
|
+
const references: SheetReference[] = []
|
|
71
|
+
for (const candidate of sheets as readonly SheetLike[]) {
|
|
72
|
+
const properties = Array.isArray(candidate?.properties) ? candidate.properties : []
|
|
73
|
+
const declared = propertyText(properties, FILE_PROPERTY_NAMES)
|
|
74
|
+
if (declared === undefined) continue
|
|
75
|
+
const resolved = resolveReference(ownerPath, declared)
|
|
76
|
+
const key = resolved ?? declared
|
|
77
|
+
if (seen.has(key)) continue
|
|
78
|
+
seen.add(key)
|
|
79
|
+
const label = propertyText(properties, NAME_PROPERTY_NAMES) ?? declared
|
|
80
|
+
references.push({ label, declared, ...(resolved === undefined ? {} : { resolved }) })
|
|
81
|
+
}
|
|
82
|
+
return references
|
|
83
|
+
}
|