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

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,183 @@
1
+ /**
2
+ * Browser half of `@huaqiu/dsh-hardware-ui`.
3
+ *
4
+ * Occupies existing DSH seats only: a root navigation occupant, a session
5
+ * header action, a `keepMounted` right-panel tab body, and a settings section.
6
+ * The shape below is structural on purpose: this package stays independently
7
+ * installable and does not import DSH internals.
8
+ */
9
+ import {
10
+ ContextualOpenAction, EngineeringNav, HardwareSettingsSection, HardwareViewerBody,
11
+ } from './components.js'
12
+ import type {
13
+ ConfigFormLike, HardwareActions, HardwareDestination, HardwareInjected,
14
+ HardwareInstallationConfig, NativeApplication,
15
+ } from './model.js'
16
+ import { createHardwareStore } from './store.js'
17
+ import { loadInstallations, loadProjects, openArtifact } from './transport.js'
18
+
19
+ /** Real Cordis service names this browser plugin waits for. */
20
+ export const inject = ['slots', 'sidebarRight', 'sidebarRightTabs', 'configForms'] as const
21
+
22
+ export const HARDWARE_SETTINGS_ID = 'hardware-engineering'
23
+ export const HARDWARE_TAB_ID = '@huaqiu/dsh-hardware-ui'
24
+ export const HARDWARE_TAB_KIND = 'hardware-engineering'
25
+
26
+ interface SlotSpec {
27
+ name: string
28
+ id?: string
29
+ key?: string
30
+ order?: number
31
+ label?: () => string
32
+ store?: unknown
33
+ inject?: (...args: unknown[]) => unknown
34
+ }
35
+
36
+ interface ClientContext {
37
+ readonly slots?: {
38
+ inject(key: string, callback: () => () => void): () => void
39
+ register(spec: SlotSpec, component: unknown): () => void
40
+ }
41
+ readonly sidebarRight?: {
42
+ openTab(kind: string, options?: {
43
+ params?: Readonly<Record<string, unknown>>
44
+ revealIfOpened?: boolean
45
+ }): void
46
+ }
47
+ readonly sidebarRightTabs?: {
48
+ register(definition: {
49
+ id: string
50
+ kind: string
51
+ keepMounted?: boolean
52
+ title: (address: string) => string
53
+ }): () => void
54
+ }
55
+ readonly configForms?: {
56
+ get<T>(entryId: string): ConfigFormLike<T>
57
+ }
58
+ effect?(fn: () => (() => void) | void, label?: string): void
59
+ }
60
+
61
+ function kindForPath(path: string): string {
62
+ if (path.endsWith('.kicad_sch')) return 'schematic'
63
+ if (path.endsWith('.kicad_pcb')) return 'pcb'
64
+ if (path.endsWith('.kicad_pro')) return 'project'
65
+ if (/\.(step|stp|glb)$/iu.test(path)) return 'mechanical-3d'
66
+ return 'bom'
67
+ }
68
+
69
+ /** Install all product UI contributions on a DSH client context. */
70
+ export function apply(ctx: ClientContext): void {
71
+ const store = createHardwareStore()
72
+ let actions: HardwareActions | undefined
73
+ let revision = 0
74
+ const effect = (fn: () => (() => void) | void, label: string): void => {
75
+ if (ctx.effect !== undefined) ctx.effect(fn, label)
76
+ else fn()
77
+ }
78
+
79
+ const captureActions = (...args: unknown[]): { hooks: HardwareInjected } => {
80
+ for (const candidate of args) {
81
+ if (candidate !== null && typeof candidate === 'object'
82
+ && typeof (candidate as HardwareActions).setActive === 'function') {
83
+ actions = candidate as HardwareActions
84
+ }
85
+ }
86
+ return { hooks: injected }
87
+ }
88
+
89
+ const injected: HardwareInjected = {
90
+ async refreshDiscovery(cwd, project) {
91
+ try {
92
+ const result = await loadProjects(cwd, project)
93
+ actions?.setDiscovery(result)
94
+ if (result.issue?.code === 'bad-manifest') actions?.setNotice(result.issue.message)
95
+ } catch (error) {
96
+ actions?.setNotice(`Artifact discovery failed: ${String(error)}`)
97
+ }
98
+ },
99
+ openDestination(destination: HardwareDestination, path) {
100
+ revision += 1
101
+ const kind = path === undefined ? undefined : kindForPath(path)
102
+ try {
103
+ ctx.sidebarRight?.openTab(HARDWARE_TAB_KIND, {
104
+ params: { destination, path, kind, revision },
105
+ revealIfOpened: true,
106
+ })
107
+ } catch (error) {
108
+ actions?.setNotice(`Open viewer failed: ${String(error)}`)
109
+ }
110
+ },
111
+ async openNative(application?: NativeApplication, artifactPath?: string) {
112
+ if (artifactPath === undefined || artifactPath === '') {
113
+ actions?.setNotice('Select an artifact before opening a native application.')
114
+ return
115
+ }
116
+ try {
117
+ await openArtifact({
118
+ application: application ?? 'kicad',
119
+ artifactPath,
120
+ kind: kindForPath(artifactPath),
121
+ })
122
+ } catch (error) {
123
+ actions?.setNotice(`Native launch failed: ${String(error)}`)
124
+ throw error
125
+ }
126
+ },
127
+ async saveInstallation(application, root) {
128
+ const form = ctx.configForms?.get<HardwareInstallationConfig>('hardware-artifacts')
129
+ if (form === undefined) throw new Error('host settings are unavailable')
130
+ const field = application === 'kicad' ? 'kicadRoot' : 'solidcraftRoot'
131
+ const accepted = await form.set(field, root)
132
+ if (!accepted) throw new Error(`the host rejected the ${field} setting`)
133
+ },
134
+ async fetchInstallations() {
135
+ try {
136
+ actions?.setInstallations(await loadInstallations())
137
+ } catch (error) {
138
+ actions?.setNotice(`Installation check failed: ${String(error)}`)
139
+ }
140
+ },
141
+ useConfigForm() {
142
+ return ctx.configForms?.get<HardwareInstallationConfig>('hardware-artifacts')
143
+ },
144
+ }
145
+
146
+ effect(() => ctx.sidebarRightTabs?.register({
147
+ id: HARDWARE_TAB_ID,
148
+ kind: HARDWARE_TAB_KIND,
149
+ keepMounted: true,
150
+ title: () => 'Hardware Engineering',
151
+ }) ?? (() => {}), 'hardware-ui: right-panel tab type')
152
+
153
+ const slots = ctx.slots
154
+ if (slots === undefined) return
155
+
156
+ effect(() => slots.inject('conversation.header.leading', () => slots.register({
157
+ name: 'conversation.header.leading',
158
+ store,
159
+ inject: captureActions,
160
+ }, EngineeringNav)), 'hardware-ui: six-destination navigation')
161
+
162
+ effect(() => slots.inject('sidebar.right.pane.tab', () => slots.register({
163
+ name: 'sidebar.right.pane.tab',
164
+ key: HARDWARE_TAB_ID,
165
+ store,
166
+ inject: captureActions,
167
+ }, HardwareViewerBody)), 'hardware-ui: viewer body')
168
+
169
+ effect(() => slots.inject('conversation.session.header.corner', () => slots.register({
170
+ name: 'conversation.session.header.corner',
171
+ store,
172
+ inject: captureActions,
173
+ }, ContextualOpenAction)), 'hardware-ui: contextual native action')
174
+
175
+ effect(() => slots.inject('settings.section', () => slots.register({
176
+ name: 'settings.section',
177
+ id: HARDWARE_SETTINGS_ID,
178
+ order: 85,
179
+ label: () => 'Hardware Engineering',
180
+ store,
181
+ inject: captureActions,
182
+ }, HardwareSettingsSection)), 'hardware-ui: CAD installation settings')
183
+ }
@@ -0,0 +1,116 @@
1
+ /** Product-owned navigation and artifact identity. No shadow project database. */
2
+
3
+ export type HardwareDestination = 'schematic' | 'pcb' | 'dfm' | 'bom' | '3d' | 'order'
4
+ export type NativeApplication = 'kicad' | 'solidcraft'
5
+
6
+ export const DESTINATIONS: readonly HardwareDestination[] = Object.freeze([
7
+ 'schematic', 'pcb', 'dfm', 'bom', '3d', 'order',
8
+ ])
9
+
10
+ export const DESTINATION_LABELS: Readonly<Record<HardwareDestination, string>> = Object.freeze({
11
+ schematic: 'Schematic',
12
+ pcb: 'PCB',
13
+ dfm: 'DFM',
14
+ bom: 'BOM',
15
+ '3d': '3D CAD',
16
+ order: 'Order Placing',
17
+ })
18
+
19
+ /** Which native application a destination can open, if any. */
20
+ export function applicationFor(destination: HardwareDestination): NativeApplication | undefined {
21
+ if (destination === 'schematic' || destination === 'pcb' || destination === 'dfm' || destination === 'bom') return 'kicad'
22
+ if (destination === '3d') return 'solidcraft'
23
+ return undefined
24
+ }
25
+
26
+ export interface HardwareArtifactInfo {
27
+ readonly id: string
28
+ readonly kind: string
29
+ readonly path: string
30
+ readonly title: string
31
+ readonly sourcePath?: string
32
+ }
33
+
34
+ export interface HardwareProjectInfo {
35
+ readonly path: string
36
+ readonly name: string
37
+ readonly sheetPath?: string
38
+ readonly schematic?: HardwareArtifactInfo
39
+ readonly bom?: HardwareArtifactInfo
40
+ readonly pcb3d?: HardwareArtifactInfo
41
+ readonly sheets?: readonly HardwareArtifactInfo[]
42
+ readonly boards?: readonly HardwareArtifactInfo[]
43
+ readonly mechanical?: readonly HardwareArtifactInfo[]
44
+ }
45
+
46
+ export interface InstallationsInfo {
47
+ readonly kicad?: {
48
+ readonly configured: boolean
49
+ readonly version?: string
50
+ readonly cli?: string
51
+ readonly pcbEditor?: string
52
+ readonly schematicEditor?: string
53
+ readonly error?: string
54
+ }
55
+ readonly solidcraft?: {
56
+ readonly configured: boolean
57
+ readonly executable?: string
58
+ readonly error?: string
59
+ }
60
+ }
61
+
62
+ export interface DiscoveryInfo {
63
+ readonly cwd?: string
64
+ readonly projects?: readonly HardwareProjectInfo[]
65
+ readonly selected?: HardwareProjectInfo
66
+ readonly issue?: { readonly code: string; readonly message: string }
67
+ }
68
+
69
+ export interface HardwareState {
70
+ readonly activeDestination: HardwareDestination
71
+ readonly workspaceRoot?: string
72
+ readonly projectPath?: string
73
+ readonly schematicPath?: string
74
+ readonly sheetPath?: string
75
+ readonly pcbPath?: string
76
+ readonly mechanicalPath?: string
77
+ readonly discovery?: DiscoveryInfo
78
+ readonly installations?: InstallationsInfo
79
+ readonly revision: number
80
+ readonly notice?: string
81
+ }
82
+
83
+ export interface HardwareActions {
84
+ setActive(destination: HardwareDestination): void
85
+ setWorkspaceRoot(root: string): void
86
+ setDiscovery(discovery: DiscoveryInfo): void
87
+ selectArtifact(path: string, kind: 'schematic' | 'pcb' | 'mechanical-3d'): void
88
+ setInstallations(installations: InstallationsInfo): void
89
+ setNotice(notice?: string): void
90
+ refresh(): void
91
+ }
92
+
93
+ export interface ConfigFormLike<T> {
94
+ getSnapshot(): { readonly value?: T; readonly status?: string; readonly writable?: boolean }
95
+ subscribe(listener: () => void): () => void
96
+ set(field: string, value: unknown): Promise<boolean>
97
+ }
98
+
99
+ export interface HardwareInstallationConfig {
100
+ readonly kicadRoot?: string
101
+ readonly solidcraftRoot?: string
102
+ }
103
+
104
+ /** Functions the UI receives through the slot `inject` face. */
105
+ export interface HardwareInjected {
106
+ refreshDiscovery(cwd?: string, project?: string): Promise<void>
107
+ openDestination(destination: HardwareDestination, path?: string): void
108
+ openNative(application?: NativeApplication, artifactPath?: string): Promise<void>
109
+ saveInstallation(application: NativeApplication, root: string): Promise<void>
110
+ fetchInstallations(): Promise<void>
111
+ useConfigForm?(): ConfigFormLike<HardwareInstallationConfig> | undefined
112
+ useSessions?(selector: (state: {
113
+ readonly ids: readonly string[]
114
+ readonly byId: Readonly<Record<string, { readonly cwd?: string }>>
115
+ }) => string | undefined): string | undefined
116
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * One store handle shared by the navigation, viewer, context action and
3
+ * settings registrations. It follows DSH's declared-store contract: a spec
4
+ * (init + complete write set) plus a per-scope instance factory. The handle is
5
+ * created inside `apply()`, never at module scope, so a plugin reload cannot
6
+ * resurrect an old snapshot.
7
+ */
8
+ import type {
9
+ HardwareActions, HardwareDestination, HardwareState, DiscoveryInfo, InstallationsInfo,
10
+ } from './model.js'
11
+
12
+ type Mutable<T> = { -readonly [K in keyof T]: T[K] }
13
+
14
+ type Mutator = (draft: Mutable<HardwareState>, ...params: unknown[]) => void
15
+
16
+ export interface HardwareStoreInstance {
17
+ readonly actions: HardwareActions
18
+ getSnapshot(): HardwareState
19
+ subscribe(listener: () => void): () => void
20
+ clearPersisted(): void
21
+ }
22
+
23
+ export interface HardwareStoreHandle {
24
+ readonly spec: {
25
+ readonly init: () => HardwareState
26
+ readonly actions: Record<string, Mutator>
27
+ }
28
+ create(scopeKey?: string): HardwareStoreInstance
29
+ }
30
+
31
+ function initial(): HardwareState {
32
+ return { activeDestination: 'schematic', revision: 0 }
33
+ }
34
+
35
+ const mutators = {
36
+ setActive(draft: Mutable<HardwareState>, destination: HardwareDestination): void {
37
+ draft.activeDestination = destination
38
+ draft.revision += 1
39
+ },
40
+ setWorkspaceRoot(draft: Mutable<HardwareState>, root: string): void {
41
+ draft.workspaceRoot = root
42
+ },
43
+ setDiscovery(draft: Mutable<HardwareState>, discovery: DiscoveryInfo): void {
44
+ draft.discovery = discovery
45
+ draft.workspaceRoot = discovery.cwd ?? draft.workspaceRoot
46
+ draft.projectPath = discovery.selected?.path
47
+ const selected = discovery.selected
48
+ draft.schematicPath = selected?.sheetPath ?? selected?.schematic?.path
49
+ draft.pcbPath = selected?.boards?.[0]?.path ?? selected?.pcb3d?.path
50
+ draft.mechanicalPath = selected?.mechanical?.[0]?.path
51
+ draft.revision += 1
52
+ },
53
+ selectArtifact(draft: Mutable<HardwareState>, path: string, kind: 'schematic' | 'pcb' | 'mechanical-3d'): void {
54
+ if (kind === 'schematic') draft.schematicPath = path
55
+ else if (kind === 'pcb') draft.pcbPath = path
56
+ else draft.mechanicalPath = path
57
+ draft.revision += 1
58
+ },
59
+ setInstallations(draft: Mutable<HardwareState>, installations: InstallationsInfo): void {
60
+ draft.installations = installations
61
+ draft.revision += 1
62
+ },
63
+ setNotice(draft: Mutable<HardwareState>, notice?: string): void {
64
+ if (notice === undefined) delete draft.notice
65
+ else draft.notice = notice
66
+ },
67
+ refresh(draft: Mutable<HardwareState>): void {
68
+ draft.revision += 1
69
+ },
70
+ }
71
+
72
+ /** Create the shared handle. Call once inside `apply()`. */
73
+ export function createHardwareStore(): HardwareStoreHandle {
74
+ return {
75
+ spec: { init: initial, actions: mutators as unknown as Record<string, Mutator> },
76
+ create(): HardwareStoreInstance {
77
+ let snapshot = initial()
78
+ const listeners = new Set<() => void>()
79
+ const commit = (mutate: (draft: Mutable<HardwareState>) => void): void => {
80
+ const draft: Mutable<HardwareState> = { ...snapshot }
81
+ mutate(draft)
82
+ snapshot = draft
83
+ for (const listener of [...listeners]) listener()
84
+ }
85
+ return {
86
+ actions: {
87
+ setActive: destination => commit(draft => mutators.setActive(draft, destination)),
88
+ setWorkspaceRoot: root => commit(draft => { draft.workspaceRoot = root }),
89
+ setDiscovery: discovery => commit(draft => mutators.setDiscovery(draft, discovery)),
90
+ selectArtifact: (path, kind) => commit(draft => mutators.selectArtifact(draft, path, kind)),
91
+ setInstallations: installations => commit(draft => mutators.setInstallations(draft, installations)),
92
+ setNotice: notice => commit(draft => mutators.setNotice(draft, notice)),
93
+ refresh: () => commit(draft => mutators.refresh(draft)),
94
+ },
95
+ getSnapshot: () => snapshot,
96
+ subscribe(listener) {
97
+ listeners.add(listener)
98
+ return () => { listeners.delete(listener) }
99
+ },
100
+ clearPersisted() {},
101
+ }
102
+ },
103
+ }
104
+ }
@@ -0,0 +1,63 @@
1
+ /** Same-origin calls to the `@huaqiu/hardware-artifacts` Host routes. */
2
+ import type {
3
+ DiscoveryInfo, HardwareProjectInfo, InstallationsInfo, NativeApplication,
4
+ } from './model.js'
5
+
6
+ const PREFIX = '/api/v1/hardware'
7
+
8
+ interface Envelope<T> {
9
+ readonly ok?: boolean
10
+ readonly error?: { readonly code?: string; readonly message?: string }
11
+ readonly data?: T
12
+ readonly [key: string]: unknown
13
+ }
14
+
15
+ async function request<T>(path: string, init?: RequestInit): Promise<T> {
16
+ const response = await fetch(`${PREFIX}${path}`, init)
17
+ const body = await response.json().catch(() => undefined) as Envelope<T> | undefined
18
+ if (!response.ok || body?.ok === false) {
19
+ const detail = body?.error?.message ?? `HTTP ${response.status}`
20
+ throw new Error(detail)
21
+ }
22
+ return body as T
23
+ }
24
+
25
+ function query(cwd: string | undefined, project?: string): string {
26
+ const params = new URLSearchParams()
27
+ if (cwd !== undefined && cwd !== '') params.set('cwd', cwd)
28
+ if (project !== undefined && project !== '') params.set('project', project)
29
+ const text = params.toString()
30
+ return text === '' ? '' : `?${text}`
31
+ }
32
+
33
+ export async function loadProjects(cwd?: string, project?: string): Promise<DiscoveryInfo> {
34
+ const body = await request<DiscoveryInfo>(`/projects${query(cwd, project)}`)
35
+ const fallback: DiscoveryInfo = {
36
+ cwd: body.cwd,
37
+ projects: Array.isArray(body.projects) ? body.projects : [],
38
+ ...(body.selected === undefined ? {} : { selected: body.selected as HardwareProjectInfo }),
39
+ ...(body.issue === undefined ? {} : { issue: body.issue }),
40
+ }
41
+ return fallback
42
+ }
43
+
44
+ export async function loadInstallations(): Promise<InstallationsInfo> {
45
+ return request<InstallationsInfo>('/installations')
46
+ }
47
+
48
+ export async function environment(): Promise<{ text?: string; childEnv?: Record<string, string> }> {
49
+ return request<{ text?: string; childEnv?: Record<string, string> }>('/environment')
50
+ }
51
+
52
+ export async function openArtifact(requestBody: {
53
+ application: NativeApplication
54
+ artifactPath: string
55
+ kind: string
56
+ projectPath?: string
57
+ }): Promise<void> {
58
+ await request('/open', {
59
+ method: 'POST',
60
+ headers: { 'content-type': 'application/json' },
61
+ body: JSON.stringify(requestBody),
62
+ })
63
+ }
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Node half of `@huaqiu/dsh-hardware-ui`.
3
+ *
4
+ * All product UI is browser-side. This entry exists so the package is a normal
5
+ * installable plugin in the DSH bundle; it intentionally provides no service
6
+ * and injects nothing. Host operations live in `@huaqiu/hardware-artifacts`.
7
+ */
8
+ export const name = '@huaqiu/dsh-hardware-ui'
9
+
10
+ /** Browser-only plugin: the node Loader seat intentionally does nothing. */
11
+ export function apply(): void {}
12
+
13
+ /** The tab kind owned by this product UI. */
14
+ export const HARDWARE_TAB_KIND = 'hardware-engineering'
15
+
16
+ /** Slots this product UI occupies. Exported for contract tests and readers. */
17
+ export const HARDWARE_UI_SLOTS = Object.freeze([
18
+ 'conversation.header.leading',
19
+ 'conversation.session.header.corner',
20
+ 'sidebar.right.pane.tab',
21
+ 'settings.section',
22
+ ] as const)