@huaqiu/dsh-engineering-workbench 0.7.28 → 0.7.30
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/README.md +40 -26
- package/lib/client.js +13089 -1260
- package/lib/host.mjs +137 -18
- package/package.json +17 -2
- package/src/BomDialogs.tsx +220 -0
- package/src/BomGrid.tsx +172 -0
- package/src/Drawings.tsx +30 -0
- package/src/FabricationFiles.tsx +94 -0
- package/src/Manufacture.tsx +195 -0
- package/src/Mechanical.tsx +173 -0
- package/src/ToolRail.tsx +46 -0
- package/src/Workbench.tsx +227 -0
- package/src/bom-csv.ts +107 -0
- package/src/bom-export.ts +34 -0
- package/src/bom-rows.ts +35 -0
- package/src/bom-snapshot.ts +85 -0
- package/src/bom-styles.ts +86 -0
- package/src/caption-copy.ts +43 -0
- package/src/caption-menu.ts +158 -0
- package/src/client.tsx +100 -0
- package/src/files.ts +56 -0
- package/src/manufacturing-host.mjs +158 -0
- package/src/navigation.mjs +32 -0
- package/src/pages.ts +12 -0
- package/src/price.mjs +79 -0
- package/src/procurement.ts +91 -0
- package/src/styles.ts +41 -0
- package/src/tool.mjs +24 -0
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { View } from './pages'
|
|
2
|
+
import { captionCopyFor } from './caption-copy'
|
|
3
|
+
|
|
4
|
+
export interface MountedSession {
|
|
5
|
+
getSnapshot(): string | undefined
|
|
6
|
+
subscribe(listener: () => void): () => void
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const entries = ['design', 'review', 'manufacture'] as const
|
|
10
|
+
|
|
11
|
+
/** The Windows caption is created by the desktop preload, sometimes after the plugins. */
|
|
12
|
+
export function installCaptionMenu(mounted: MountedSession, activate: (session: string, view: View) => void) {
|
|
13
|
+
let bar: HTMLElement | undefined
|
|
14
|
+
let menu: HTMLElement | undefined
|
|
15
|
+
function closeMenu(restoreFocus=false) {
|
|
16
|
+
if (!menu) return
|
|
17
|
+
const popup=menu
|
|
18
|
+
menu=undefined
|
|
19
|
+
popup.remove()
|
|
20
|
+
buttons[0]!.setAttribute('aria-expanded','false')
|
|
21
|
+
if(restoreFocus)buttons[0]!.focus()
|
|
22
|
+
}
|
|
23
|
+
function showMenu(focusLast=false) {
|
|
24
|
+
const trigger=buttons[0]!
|
|
25
|
+
if (!bar || trigger.disabled) return
|
|
26
|
+
closeMenu()
|
|
27
|
+
const copy=captionCopyFor(document.documentElement.lang)
|
|
28
|
+
const popup=document.createElement('div')
|
|
29
|
+
popup.id='engineering-design-menu'
|
|
30
|
+
popup.setAttribute('role','menu')
|
|
31
|
+
popup.setAttribute('aria-label',copy('design'))
|
|
32
|
+
const rect=trigger.getBoundingClientRect()
|
|
33
|
+
Object.assign(popup.style,{position:'fixed',top:rect.bottom+'px',left:rect.left+'px',minWidth:'124px',
|
|
34
|
+
display:'grid',padding:'4px',border:'1px solid var(--dsw-alias-border-l2)',borderRadius:'6px',
|
|
35
|
+
background:'var(--dsw-alias-bg-layer-1)',boxShadow:'0 4px 14px #0002'})
|
|
36
|
+
for(const view of ['design','mechanical'] as const){
|
|
37
|
+
const item=document.createElement('button')
|
|
38
|
+
item.type='button'
|
|
39
|
+
item.tabIndex=-1
|
|
40
|
+
item.setAttribute('role','menuitem')
|
|
41
|
+
item.textContent=copy(view==='design'?'circuitDesign':'mechanicalDesign')
|
|
42
|
+
item.style.textAlign='start'
|
|
43
|
+
item.onclick=()=>{
|
|
44
|
+
closeMenu(true)
|
|
45
|
+
const session=mounted.getSnapshot()
|
|
46
|
+
if(session!==undefined)activate(session,view)
|
|
47
|
+
}
|
|
48
|
+
popup.append(item)
|
|
49
|
+
}
|
|
50
|
+
popup.onkeydown=e=>{
|
|
51
|
+
const items=Array.from(popup.querySelectorAll('button'))
|
|
52
|
+
if(e.key==='Escape'){closeMenu(true)}
|
|
53
|
+
else if(['ArrowDown','ArrowUp','Home','End'].includes(e.key)){
|
|
54
|
+
const index=items.indexOf(e.target as HTMLButtonElement)
|
|
55
|
+
items[e.key==='Home'?0:e.key==='End'?1:1-index]?.focus()
|
|
56
|
+
}else return
|
|
57
|
+
e.preventDefault();e.stopPropagation()
|
|
58
|
+
}
|
|
59
|
+
popup.addEventListener('focusout',e=>{if(!popup.contains(e.relatedTarget as Node|null))closeMenu()})
|
|
60
|
+
bar.after(popup)
|
|
61
|
+
menu=popup
|
|
62
|
+
trigger.setAttribute('aria-expanded','true')
|
|
63
|
+
popup.querySelector<HTMLButtonElement>(focusLast?'button:last-child':'button')?.focus()
|
|
64
|
+
}
|
|
65
|
+
const buttons = entries.map(view => {
|
|
66
|
+
const button = document.createElement('button')
|
|
67
|
+
button.type = 'button'
|
|
68
|
+
button.setAttribute('role', 'menuitem')
|
|
69
|
+
button.tabIndex = -1
|
|
70
|
+
button.textContent = captionCopyFor(document.documentElement.lang)(view)
|
|
71
|
+
if(view==='design'){
|
|
72
|
+
button.setAttribute('aria-haspopup','menu')
|
|
73
|
+
button.setAttribute('aria-controls','engineering-design-menu')
|
|
74
|
+
button.setAttribute('aria-expanded','false')
|
|
75
|
+
button.onkeydown=e=>{
|
|
76
|
+
if(e.key==='ArrowDown'||e.key==='ArrowUp'){
|
|
77
|
+
e.preventDefault();e.stopPropagation();showMenu(e.key==='ArrowUp')
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// Like Edit and Place Order, preserve the composer selection on pointer activation.
|
|
82
|
+
button.onpointerdown = button.onmousedown = event => event.preventDefault()
|
|
83
|
+
button.onclick = () => {
|
|
84
|
+
if(view==='design'){if(menu)closeMenu(true);else showMenu();return}
|
|
85
|
+
closeMenu()
|
|
86
|
+
const session = mounted.getSnapshot()
|
|
87
|
+
if (session !== undefined) activate(session, view)
|
|
88
|
+
}
|
|
89
|
+
return button
|
|
90
|
+
})
|
|
91
|
+
const update = () => {
|
|
92
|
+
closeMenu()
|
|
93
|
+
const copy = captionCopyFor(document.documentElement.lang)
|
|
94
|
+
const disabled = mounted.getSnapshot() === undefined
|
|
95
|
+
buttons.forEach((button, index) => {
|
|
96
|
+
const label = copy(entries[index]!)
|
|
97
|
+
button.disabled = disabled
|
|
98
|
+
button.textContent = label
|
|
99
|
+
button.title = disabled ? copy('needSession') : copy('openPage', { title: label })
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
// Preload keeps a private list for arrow navigation. Bridge the three added items
|
|
103
|
+
// at its boundaries, leaving the native submenus and their own shortcuts intact.
|
|
104
|
+
const move = (event: KeyboardEvent) => {
|
|
105
|
+
if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft') return
|
|
106
|
+
const items = Array.from(bar!.querySelectorAll<HTMLButtonElement>('button[role=menuitem]:enabled'))
|
|
107
|
+
const index = items.indexOf(event.target as HTMLButtonElement)
|
|
108
|
+
if (index < 0) return
|
|
109
|
+
const next = items[(index + (event.key === 'ArrowRight' ? 1 : -1) + items.length) % items.length]!
|
|
110
|
+
if (!buttons.includes(items[index]!) && !buttons.includes(next)) return
|
|
111
|
+
event.preventDefault()
|
|
112
|
+
event.stopPropagation()
|
|
113
|
+
for (const item of items) item.tabIndex = item === next ? 0 : -1
|
|
114
|
+
next.focus()
|
|
115
|
+
}
|
|
116
|
+
const detach = () => {
|
|
117
|
+
closeMenu()
|
|
118
|
+
bar?.removeEventListener('keydown', move, true)
|
|
119
|
+
if (bar && buttons.some(b => b.tabIndex === 0)) {
|
|
120
|
+
const first = bar.querySelector<HTMLButtonElement>('button[aria-haspopup=menu]')
|
|
121
|
+
if (first) first.tabIndex = 0
|
|
122
|
+
}
|
|
123
|
+
for (const button of buttons) { button.remove(); button.tabIndex = -1 }
|
|
124
|
+
bar = undefined
|
|
125
|
+
}
|
|
126
|
+
const mount = () => {
|
|
127
|
+
const root = document.querySelector('[data-windows-menu]')?.shadowRoot
|
|
128
|
+
const next = root?.querySelector<HTMLElement>('[role=menubar]')
|
|
129
|
+
if (next === bar) return
|
|
130
|
+
detach()
|
|
131
|
+
if (!next) return
|
|
132
|
+
bar = next
|
|
133
|
+
// The desktop's own order entry is the natural seat: our views sit left of it.
|
|
134
|
+
// That entry was renamed once already (`data-place-order` → `data-order`), so
|
|
135
|
+
// accept both and fall back to the end of the bar. A renamed or removed anchor
|
|
136
|
+
// must not silence the whole menu, which is how it went missing before.
|
|
137
|
+
const anchor = next.querySelector<HTMLButtonElement>('button[data-order], button[data-place-order]')
|
|
138
|
+
for (const button of buttons) {
|
|
139
|
+
if (anchor) next.insertBefore(button, anchor)
|
|
140
|
+
else next.append(button)
|
|
141
|
+
}
|
|
142
|
+
next.addEventListener('keydown', move, true)
|
|
143
|
+
update()
|
|
144
|
+
}
|
|
145
|
+
const observer = new MutationObserver(mount)
|
|
146
|
+
// The desktop keeps its UI language on `html[lang]`, so follow the same seat:
|
|
147
|
+
// a language flip relabels the entries and closes an open design popup.
|
|
148
|
+
const localeObserver = new MutationObserver(update)
|
|
149
|
+
localeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] })
|
|
150
|
+
const dismiss=(e:PointerEvent)=>{
|
|
151
|
+
if(menu && !e.composedPath().includes(menu) && !e.composedPath().includes(buttons[0]!))closeMenu()
|
|
152
|
+
}
|
|
153
|
+
document.addEventListener('pointerdown',dismiss,true)
|
|
154
|
+
observer.observe(document.body, {childList:true})
|
|
155
|
+
const unsubscribe = mounted.subscribe(update)
|
|
156
|
+
mount()
|
|
157
|
+
return () => { document.removeEventListener('pointerdown',dismiss,true);observer.disconnect(); localeObserver.disconnect(); unsubscribe(); detach() }
|
|
158
|
+
}
|
package/src/client.tsx
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from 'react'
|
|
2
|
+
import { Workbench, type Face, type Nav } from './Workbench'
|
|
3
|
+
import { installCaptionMenu, type MountedSession } from './caption-menu'
|
|
4
|
+
import { pages, views } from './pages'
|
|
5
|
+
import { Mechanical, type WorkspaceModels } from './Mechanical'
|
|
6
|
+
import { ToolRail, type RailTool } from './ToolRail'
|
|
7
|
+
import type { Selection } from './Workbench'
|
|
8
|
+
import { requestsIn } from './navigation.mjs'
|
|
9
|
+
import { provideHost } from '@huaqiu/dsh-plugin-utils'
|
|
10
|
+
import { optionalClientHostOf } from '@huaqiu/dsh-plugin-utils/client'
|
|
11
|
+
|
|
12
|
+
export const inject = ['slots','sidebarRight','sidebarRightTabs','sessions','conversation','remote','remote.workspaceFiles']
|
|
13
|
+
const EMPTY:unknown[]=[]
|
|
14
|
+
type UseNodes=(read:(s:{nodes?:unknown[]; legacy?:{nodes?:unknown[]}}|undefined)=>unknown[])=>unknown[]
|
|
15
|
+
interface HeaderProps {sessionId:string; useChat?:UseNodes; useSession?:UseNodes; open:Face['open']}
|
|
16
|
+
function ConversationNavigation({sessionId,useChat,useSession,open}:HeaderProps) {
|
|
17
|
+
const chat=useChat?.(s=>s?.legacy?.nodes??EMPTY)??EMPTY
|
|
18
|
+
const nodes=useSession?.(s=>s?.nodes??EMPTY)??EMPTY
|
|
19
|
+
const [suggestion,setSuggestion]=useState<Nav>()
|
|
20
|
+
const [error,setError]=useState('')
|
|
21
|
+
const since=useRef(Date.now())
|
|
22
|
+
const seen=useRef(new Set<string>())
|
|
23
|
+
useEffect(()=>{
|
|
24
|
+
// Old transcripts can arrive after mounting. Their host timestamps predate this view.
|
|
25
|
+
const latest=requestsIn([...chat,...nodes]).filter(n=>n.issuedAt>=since.current&&!seen.current.has(n.requestId))
|
|
26
|
+
for(const n of latest)seen.current.add(n.requestId)
|
|
27
|
+
const last=latest.at(-1)
|
|
28
|
+
if(last){
|
|
29
|
+
if(last.action==='suggest')setSuggestion(last)
|
|
30
|
+
else {setSuggestion(undefined);try{open(sessionId,pages[last.view as Nav["view"]].kind,last)}catch(e){setError(String(e))}}
|
|
31
|
+
}
|
|
32
|
+
},[chat,nodes,sessionId,open])
|
|
33
|
+
if (!suggestion) return error ? <span role="status">{error}</span> : null
|
|
34
|
+
return <button type="button" title={error || '打开建议的工程页面'} onClick={() => {
|
|
35
|
+
try { open(sessionId, pages[suggestion.view].kind, {...suggestion}); setSuggestion(undefined); setError('') }
|
|
36
|
+
catch (e) { setError(String(e)) }
|
|
37
|
+
}}>在右侧查看</button>
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface Client {
|
|
41
|
+
effect:(fn:()=>void|(()=>void),label:string)=>void
|
|
42
|
+
slots:{inject:(name:string,cb:()=>()=>void)=>()=>void;register:(spec:Record<string,unknown>,body:unknown)=>()=>void}
|
|
43
|
+
sidebarRightTabs:{register:(def:Record<string,unknown>)=>()=>void}
|
|
44
|
+
sidebarRight:{mounted:MountedSession;openTab:(kind:string,opts:Record<string,unknown>)=>void}
|
|
45
|
+
remote?:{workspaceFiles:WorkspaceModels}
|
|
46
|
+
get:(name:string)=>unknown
|
|
47
|
+
provide:(name:string,value:unknown)=>void
|
|
48
|
+
sessions:{binding:(id:string)=>object}
|
|
49
|
+
conversation:{input:{requestDraftInitialization:(binding:unknown,options:Record<string,string>)=>string}}
|
|
50
|
+
}
|
|
51
|
+
export function apply(ctx:Client) {
|
|
52
|
+
const open:Face['open']=(session,kind,params)=>{
|
|
53
|
+
if(ctx.sidebarRight.mounted.getSnapshot()!==session)throw new Error('请先打开该会话。')
|
|
54
|
+
ctx.sidebarRight.openTab(kind,{params,revealIfOpened:true})
|
|
55
|
+
}
|
|
56
|
+
const draft:Face['draft']=(session,text)=>{
|
|
57
|
+
const result=ctx.conversation.input.requestDraftInitialization(ctx.sessions.binding(session),{prompt:text,whenDraftExists:'append'})
|
|
58
|
+
if(result!=='applied')throw new Error('输入框暂时不可用,请稍后重试。')
|
|
59
|
+
}
|
|
60
|
+
const selections = new WeakMap<object, Selection>()
|
|
61
|
+
function selectionFor(session: string) {
|
|
62
|
+
const binding = ctx.sessions.binding(session)
|
|
63
|
+
let selection = selections.get(binding)
|
|
64
|
+
if (!selection) { selection = {}; selections.set(binding, selection) }
|
|
65
|
+
return selection
|
|
66
|
+
}
|
|
67
|
+
function activateTool(session:string,tool:RailTool) {
|
|
68
|
+
const selected=selectionFor(session)
|
|
69
|
+
const view=tool==='review'||tool==='manufacture'||tool==='mechanical'?tool:'design'
|
|
70
|
+
const path=tool==='schematic'?selected.sheet:tool==='mechanical'?undefined:selected.board
|
|
71
|
+
open(session,pages[view].kind,{view,project:selected.project,path,
|
|
72
|
+
designTool:view==='design'?tool:undefined,requestId:crypto.randomUUID()})
|
|
73
|
+
}
|
|
74
|
+
ctx.effect(()=>ctx.slots.inject('shell.overlay',()=>ctx.slots.register({
|
|
75
|
+
name:'shell.overlay',id:'engineering-tool-rail',order:60,inject:()=>({mounted:ctx.sidebarRight.mounted,activate:activateTool}),
|
|
76
|
+
},ToolRail)), 'engineering tool rail')
|
|
77
|
+
for (const [index, view] of views.entries()) {
|
|
78
|
+
const {id, kind, title} = pages[view]
|
|
79
|
+
ctx.effect(() => ctx.sidebarRightTabs.register({
|
|
80
|
+
id, kind, keepMounted: true, title: () => title,
|
|
81
|
+
guide: [{id:'open', order:15+index, title:() => title, icon:() => <span aria-hidden="true">▤</span>}],
|
|
82
|
+
}), 'engineering tab: ' + view)
|
|
83
|
+
ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({
|
|
84
|
+
name:'sidebar.right.pane.tab', key:id, inject:() => view==='mechanical'?{files:ctx.remote?.workspaceFiles}:{open, draft, view, selectionFor},
|
|
85
|
+
}, view==='mechanical'?Mechanical:Workbench)), 'engineering page: ' + view)
|
|
86
|
+
}
|
|
87
|
+
// The Windows caption is a desktop-shell surface: in a browser the installer
|
|
88
|
+
// would watch for a menubar that can never appear. The shell fact says which
|
|
89
|
+
// one we are, and publishing it lets later rows read `ctx.host`.
|
|
90
|
+
const host = optionalClientHostOf(ctx)
|
|
91
|
+
if (host !== undefined) provideHost(ctx, host)
|
|
92
|
+
if (host?.shell !== 'web') {
|
|
93
|
+
ctx.effect(() => installCaptionMenu(ctx.sidebarRight.mounted, (session, view) => {
|
|
94
|
+
open(session, pages[view].kind)
|
|
95
|
+
}), 'engineering caption menu')
|
|
96
|
+
}
|
|
97
|
+
ctx.effect(()=>ctx.slots.inject('conversation.session.header.actions',()=>ctx.slots.register({
|
|
98
|
+
name:'conversation.session.header.actions',id:'engineering-workbench-launch',order:60,inject:()=>({open}),
|
|
99
|
+
},(p:HeaderProps)=><ConversationNavigation key={p.sessionId} {...p}/>)), 'engineering workbench launcher')
|
|
100
|
+
}
|
package/src/files.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { HardwareArtifactInfo as FileInfo, HardwareProjectInfo as Project } from '../../dsh-hardware-ui/src/client/model'
|
|
2
|
+
|
|
3
|
+
export function filesOf(project?: Project) {
|
|
4
|
+
const sheets = [project?.rootSheet, project?.schematic, ...(project?.sheets ?? [])].filter((s): s is FileInfo => !!s)
|
|
5
|
+
return { sheets: [...new Map(sheets.map(s => [s.path, s])).values()], boards: project?.boards ?? [] }
|
|
6
|
+
}
|
|
7
|
+
export const basename = (path: string) => path.split(/[\\/]/).pop() || path
|
|
8
|
+
/** Choose a production project only when the workspace layout identifies one unambiguously. */
|
|
9
|
+
export function defaultCircuitProject(projects:readonly Project[],cwd:string) {
|
|
10
|
+
if(!cwd)return undefined
|
|
11
|
+
const normalize=(path:string)=>{
|
|
12
|
+
const slashes=path.replaceAll('\\','/')
|
|
13
|
+
return /^(?:[a-z]:\/|\/\/)/i.test(slashes)?slashes.toLowerCase():slashes
|
|
14
|
+
}
|
|
15
|
+
const root=normalize(cwd).replace(/\/+$/,'')+'/'
|
|
16
|
+
const candidates=projects.filter(project=>{
|
|
17
|
+
const path=normalize(project.path)
|
|
18
|
+
if(!path.startsWith(root) || !/\.kicad_pro$/i.test(path))return false
|
|
19
|
+
const dirs=path.slice(root.length).split('/').slice(0,-1)
|
|
20
|
+
return dirs.at(-1)?.toLowerCase()==='project' &&
|
|
21
|
+
!dirs.some(dir=>/^\.?candidates?(?:$|[-_.\d])/i.test(dir) || ['.history','.runtime'].includes(dir.toLowerCase()))
|
|
22
|
+
})
|
|
23
|
+
return candidates.length===1?candidates[0]:undefined
|
|
24
|
+
}
|
|
25
|
+
export function matches(path: string, wanted: string) {
|
|
26
|
+
const normal = (s: string) => s.replaceAll('\\', '/').replace(/^\.\//, '')
|
|
27
|
+
let p = normal(path), w = normal(wanted)
|
|
28
|
+
if (/^[a-z]:\//i.test(p) || p.startsWith('//')) { p = p.toLowerCase(); w = w.toLowerCase() }
|
|
29
|
+
return p === w || (!/^(?:\/|[a-z]:)/i.test(w) && p.endsWith('/' + w))
|
|
30
|
+
}
|
|
31
|
+
export interface Part {
|
|
32
|
+
ref: string
|
|
33
|
+
value: string
|
|
34
|
+
footprint: string
|
|
35
|
+
location: string
|
|
36
|
+
pins: {number: string; net: string}[]
|
|
37
|
+
}
|
|
38
|
+
type Property = { name?: string|null; value?: string|null; text?: string|null }
|
|
39
|
+
interface Foot {
|
|
40
|
+
properties_kicad_8?: Property[]|null
|
|
41
|
+
fp_texts?: {type: string; text: string}[]
|
|
42
|
+
library_link?: string|null
|
|
43
|
+
layer?: string
|
|
44
|
+
at?: {position?: {x:number; y:number}}
|
|
45
|
+
pads?: {number?: string|null; net?: {name?: string|null}|null}[]|null
|
|
46
|
+
}
|
|
47
|
+
export function partsOf(footprints: Foot[]): Part[] {
|
|
48
|
+
return footprints.flatMap(fp => {
|
|
49
|
+
const field = (key: string) => fp.properties_kicad_8?.find(p => p.name === key)?.value ??
|
|
50
|
+
fp.fp_texts?.find(text => text.type === key.toLowerCase())?.text ?? ''
|
|
51
|
+
const ref = field('Reference')
|
|
52
|
+
const xy = fp.at?.position
|
|
53
|
+
const location = xy ? [fp.layer, `X ${xy.x.toFixed(2)} · Y ${xy.y.toFixed(2)} mm`].filter(Boolean).join(' · ') : ''
|
|
54
|
+
return ref ? [{ ref, value: field('Value'), footprint: fp.library_link || '', location, pins: (fp.pads || []).filter(p => p.number).map(p => ({number: p.number!, net: p.net?.name || '—'})) }] : []
|
|
55
|
+
}).sort((a,b) => a.ref.localeCompare(b.ref, undefined, {numeric:true}))
|
|
56
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { lstat, mkdtemp, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { tmpdir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { promisify } from 'node:util'
|
|
7
|
+
import gerberToSvg from 'gerber-to-svg'
|
|
8
|
+
import { unzipSync } from 'fflate'
|
|
9
|
+
import { parseCsv, groupBomRows } from './bom-csv.ts'
|
|
10
|
+
import { quoteBoard } from './price.mjs'
|
|
11
|
+
import { apply as navigation } from './tool.mjs'
|
|
12
|
+
import { validSnapshot } from './bom-snapshot.ts'
|
|
13
|
+
import { descriptionFields, manufacturerFields, mpnFields } from './bom-rows.ts'
|
|
14
|
+
export { name, inject } from './tool.mjs'
|
|
15
|
+
|
|
16
|
+
const run = promisify(execFile)
|
|
17
|
+
const route = '/api/v1/engineering-workbench/manufacture'
|
|
18
|
+
const isLayer = name => /\.(gbr|ger|g[bt][clmops]|gko|gm\d+|g\d+|drl|xln)$/i.test(name)
|
|
19
|
+
const fields = [...mpnFields,...manufacturerFields,...descriptionFields,'Huaqiu PN','华秋料号']
|
|
20
|
+
const pendingSaves=new Map()
|
|
21
|
+
async function readSavedBom(file){
|
|
22
|
+
let info
|
|
23
|
+
try {info=await lstat(file)} catch(e){if(e.code==='ENOENT')return null;throw e}
|
|
24
|
+
if(!info.isFile() || info.size>24*1024*1024)throw new Error('BOM 保存文件无效或过大。')
|
|
25
|
+
const saved=JSON.parse(await readFile(file,'utf8'))
|
|
26
|
+
if(!validSnapshot(saved) || typeof saved.version!=='string' || typeof saved.savedAt!=='string')throw new Error('BOM 保存文件格式无效。')
|
|
27
|
+
return saved
|
|
28
|
+
}
|
|
29
|
+
export async function saveBom(file,snapshot,expectedVersion){
|
|
30
|
+
if(!validSnapshot(snapshot))throw new Error('BOM 数据格式无效,请刷新并重试。')
|
|
31
|
+
const key=process.platform==='win32'?file.toLowerCase():file
|
|
32
|
+
const write=(pendingSaves.get(key)??Promise.resolve()).catch(()=>{}).then(async()=>{
|
|
33
|
+
const previous=await readSavedBom(file)
|
|
34
|
+
if((previous?.version??null)!==expectedVersion)throw new Error('此 BOM 已在其他窗口更新,请重新打开后再保存。')
|
|
35
|
+
const version=randomUUID(),savedAt=new Date().toISOString()
|
|
36
|
+
const temp=file+'.'+version+'.tmp'
|
|
37
|
+
try{
|
|
38
|
+
await writeFile(temp,JSON.stringify({...snapshot,version,savedAt}),'utf8')
|
|
39
|
+
await rename(temp,file)
|
|
40
|
+
}finally{await rm(temp,{force:true})}
|
|
41
|
+
return {version,savedAt}
|
|
42
|
+
})
|
|
43
|
+
pendingSaves.set(key,write)
|
|
44
|
+
try{return await write}finally{if(pendingSaves.get(key)===write)pendingSaves.delete(key)}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function exportText(service, source, kind, signal) {
|
|
48
|
+
const cli = service.installations().kicad?.cli
|
|
49
|
+
if (!cli) throw new Error('请在「设置 → 硬件工程」配置 KiCad。')
|
|
50
|
+
const directory = await mkdtemp(join(tmpdir(), 'huaqiu-workbench-'))
|
|
51
|
+
try {
|
|
52
|
+
const output = join(directory, 'export.csv')
|
|
53
|
+
const args = kind === 'bom'
|
|
54
|
+
? ['sch','export','bom','--fields',['Reference','Value','Footprint','QUANTITY','DNP',...fields].join(','),
|
|
55
|
+
'--labels',['Refs','Value','Footprint','Qty','DNP',...fields].join(',')]
|
|
56
|
+
: ['pcb','export','pos','--format','csv','--units','mm','--side','both']
|
|
57
|
+
await run(cli, [...args, '--output', output, source.path], { windowsHide:true, signal, timeout:90000 })
|
|
58
|
+
const text = await readFile(output,'utf8')
|
|
59
|
+
return kind === 'bom' ? { rows:groupBomRows(parseCsv(text)) } : { text }
|
|
60
|
+
} finally { await rm(directory, {recursive:true,force:true}) }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function searchOffers(tools, query, signal) {
|
|
64
|
+
const find = tools.get('search_hqsch_parts')
|
|
65
|
+
const supply = tools.get('get_hqsch_supply_chain')
|
|
66
|
+
if (!find || !supply) throw new Error('请启用华秋器件搜索插件。')
|
|
67
|
+
const page = await find.execute({query,page_size:6,require_eda_model:false}, {signal})
|
|
68
|
+
const candidates = (page.items || []).filter(p => p.manufacturer?.id && p.mpn)
|
|
69
|
+
if (!candidates.length) return { candidates:[] }
|
|
70
|
+
signal.throwIfAborted()
|
|
71
|
+
const offers = await supply.execute({parts:candidates.map(p => ({manufacturer_id:p.manufacturer.id,mpn:p.mpn}))}, {signal})
|
|
72
|
+
return { candidates:candidates.map(p => ({
|
|
73
|
+
mpn:p.mpn, manufacturer:p.manufacturer.name, manufacturerId:p.manufacturer.id, package:p.package, huaqiuPn:p.huaqiuPn,
|
|
74
|
+
description:p.description,
|
|
75
|
+
offers:offers.filter(o => o.manufacturerId === p.manufacturer.id && o.mpn.toUpperCase() === p.mpn.toUpperCase())
|
|
76
|
+
.map(o => ({ vendor:o.vendorName || o.vendor, sku:o.sku, stock:o.stock, moq:o.moq, priceBreaks:o.priceBreaks }))
|
|
77
|
+
})) }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function renderLayer(text) {
|
|
81
|
+
const warnings = new Set()
|
|
82
|
+
const svg = await new Promise((resolve,reject) => {
|
|
83
|
+
gerberToSvg(text, { attributes:{color:'#9ee4bd'} }, (error, svg) => error ? reject(error) : resolve(svg))
|
|
84
|
+
.on('warning', warning => { if (warnings.size < 3) warnings.add(warning.message || String(warning)) })
|
|
85
|
+
})
|
|
86
|
+
return {svg,warnings:[...warnings]}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function manufacture(ctx, input, signal) {
|
|
90
|
+
const {operation, path, quantity} = input
|
|
91
|
+
if (operation === 'local-gerber') {
|
|
92
|
+
if (typeof input.text !== 'string' || !input.text.trim() || Buffer.byteLength(input.text) > 16*1024*1024) throw new Error('Gerber 文件为空或超过 16 MiB。')
|
|
93
|
+
return renderLayer(input.text)
|
|
94
|
+
}
|
|
95
|
+
if (operation === 'parts') {
|
|
96
|
+
if (typeof input.query !== 'string' || !input.query.trim() || input.query.length > 200) throw new Error('无效的器件查询。')
|
|
97
|
+
return searchOffers(ctx.tools, input.query, signal)
|
|
98
|
+
}
|
|
99
|
+
const hardware = ctx.get('hardwareArtifacts')
|
|
100
|
+
if (!hardware) throw new Error('请启用硬件工程插件。')
|
|
101
|
+
if (typeof path !== 'string' || path.length > 4096) throw new Error('请选择工程文件。')
|
|
102
|
+
if (operation === 'layers' || operation === 'gerber') {
|
|
103
|
+
const pkg = await hardware.fabricate({boardPath:path,signal})
|
|
104
|
+
const layers = pkg.archive.files.filter(f => isLayer(f.name))
|
|
105
|
+
if (operation === 'layers') return {layers}
|
|
106
|
+
const layer = layers.find(f => f.name === input.layer)
|
|
107
|
+
if (!layer || layer.bytes > 32 * 1024 * 1024) throw new Error('图层不存在或超出 32 MiB 预览上限。')
|
|
108
|
+
const files = unzipSync(pkg.archiveData, {filter:f => f.name === layer.name})
|
|
109
|
+
return renderLayer(new TextDecoder().decode(files[layer.name]))
|
|
110
|
+
}
|
|
111
|
+
const source = await hardware.readSource({artifactPath:path, signal})
|
|
112
|
+
if (source.kind === 'schematic' && (operation==='bom' || operation==='save-bom')){
|
|
113
|
+
const file=source.path+'.hq-bom.json'
|
|
114
|
+
if(operation==='save-bom')return saveBom(file,input.snapshot,input.version)
|
|
115
|
+
let saved=null,warning=''
|
|
116
|
+
try{saved=await readSavedBom(file)}catch(e){warning='无法读取已保存的 BOM。'+e.message}
|
|
117
|
+
try{return {...await exportText(hardware,source,'bom',signal),saved,warning}}
|
|
118
|
+
catch(e){
|
|
119
|
+
if(!saved || signal.aborted)throw e
|
|
120
|
+
return {rows:saved.lines.filter(l=>!l.row.manual).map(l=>l.row.source??l.row),saved,warning:'无法重新生成原理图 BOM,当前显示上次保存的版本。'+e.message}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (source.kind !== 'pcb') throw new Error('请选择 PCB 文件。')
|
|
124
|
+
if (operation === 'positions') return exportText(hardware, source, 'positions', signal)
|
|
125
|
+
if (['pcb','smt'].includes(operation) && Number.isSafeInteger(quantity) && quantity >= 1 && quantity <= 100000) {
|
|
126
|
+
return quoteBoard(operation,source.text,quantity,signal)
|
|
127
|
+
}
|
|
128
|
+
throw new Error('制造请求参数无效。')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function apply(ctx) {
|
|
132
|
+
navigation(ctx)
|
|
133
|
+
ctx.inject(['webServer'], scope => scope.effect(() => scope.webServer.register({
|
|
134
|
+
kind:'exact', path:route, async handler(req,res) {
|
|
135
|
+
if (req.method !== 'POST' || !req.headers['content-type']?.startsWith('application/json')) {
|
|
136
|
+
res.writeHead(405); res.end(); return
|
|
137
|
+
}
|
|
138
|
+
res.setHeader('Content-Type','application/json; charset=utf-8')
|
|
139
|
+
res.setHeader('Cache-Control','no-store')
|
|
140
|
+
const ctrl = new AbortController()
|
|
141
|
+
res.on('close', () => ctrl.abort())
|
|
142
|
+
try {
|
|
143
|
+
req.setEncoding('utf8')
|
|
144
|
+
let body = ''
|
|
145
|
+
for await (const chunk of req) {
|
|
146
|
+
body += chunk
|
|
147
|
+
if (body.length > 20*1024*1024) throw new Error('请求过大。')
|
|
148
|
+
}
|
|
149
|
+
const data = await manufacture(ctx,JSON.parse(body),AbortSignal.any([ctrl.signal,AbortSignal.timeout(100000)]))
|
|
150
|
+
res.end(JSON.stringify(data))
|
|
151
|
+
} catch(error) {
|
|
152
|
+
if (res.destroyed) return
|
|
153
|
+
res.statusCode = 400
|
|
154
|
+
res.end(JSON.stringify({error:error instanceof Error ? error.message : String(error)}))
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
}), 'manufacturing preview and quotes'))
|
|
158
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const TOOL = 'hardware_open_workbench'
|
|
2
|
+
export const KIND = 'huaqiu-engineering-workbench'
|
|
3
|
+
export const MODES = ['design', 'mechanical', 'review', 'manufacture']
|
|
4
|
+
|
|
5
|
+
export function validRequest(value) {
|
|
6
|
+
return !!value && MODES.includes(value.view)
|
|
7
|
+
&& (value.designTool === undefined || (value.view === 'design' && ['schematic','pcb','3d'].includes(value.designTool)))
|
|
8
|
+
&& (value.action === undefined || ['open','suggest'].includes(value.action))
|
|
9
|
+
&& [value.path, value.project, value.reference].every(s => s === undefined || (typeof s === 'string' && s.trim() && s.length <= 4096))
|
|
10
|
+
&& (value.path === undefined || /\.kicad_(pcb|sch)$/i.test(value.path))
|
|
11
|
+
&& (value.project === undefined || /\.kicad_pro$/i.test(value.project))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Read only successful results from our own tool. Identifiers are generated by the host half.
|
|
15
|
+
export function requestsIn(nodes) {
|
|
16
|
+
const requests = new Map()
|
|
17
|
+
const visit = node => {
|
|
18
|
+
if (!node || typeof node !== 'object') return
|
|
19
|
+
if (node.kind === 'tool-result' && node.call?.name === TOOL && Array.isArray(node.content)) {
|
|
20
|
+
for (const block of node.content) {
|
|
21
|
+
if (block.type !== 'text') continue
|
|
22
|
+
try {
|
|
23
|
+
const value = JSON.parse(block.text)
|
|
24
|
+
if (validRequest(value) && typeof value.requestId === 'string' && Number.isFinite(value.issuedAt)) requests.set(value.requestId, value)
|
|
25
|
+
} catch { /* Other presentation blocks carry no navigation. */ }
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
for (const key of ['children', 'nodes', 'subCalls']) if (Array.isArray(node[key])) node[key].forEach(visit)
|
|
29
|
+
}
|
|
30
|
+
nodes.forEach(visit)
|
|
31
|
+
return [...requests.values()]
|
|
32
|
+
}
|
package/src/pages.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Reuse the original tab identity for Design so saved desktop layouts still resolve.
|
|
2
|
+
const baseId = '@huaqiu/dsh-engineering-workbench'
|
|
3
|
+
const baseKind = 'huaqiu-engineering-workbench'
|
|
4
|
+
|
|
5
|
+
export const pages = {
|
|
6
|
+
design: { title: '电路设计', id: baseId, kind: baseKind },
|
|
7
|
+
mechanical: { title: '结构设计', id: baseId + '/mechanical', kind: baseKind + '-mechanical' },
|
|
8
|
+
review: { title: '评审', id: baseId + '/review', kind: baseKind + '-review' },
|
|
9
|
+
manufacture: { title: '制造', id: baseId + '/manufacture', kind: baseKind + '-manufacture' },
|
|
10
|
+
} as const
|
|
11
|
+
export type View = keyof typeof pages
|
|
12
|
+
export const views = Object.keys(pages) as View[]
|
package/src/price.mjs
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { pcbOrderForm, readBoardFacts, parseSexpr } from '../../hardware-artifacts/src/order.ts'
|
|
2
|
+
|
|
3
|
+
const pcbFees = 'testfee plate clc gch bgafee impendancefee pin copperfee colorfee sprayfee extraurgentfee viasfee bankongfee utilizationfee discountfee boardfee difficultyfee coverfee blindfee pressingfee cjfee pthfee viainpadfee reportfee populerfee paperfee userstampfee acceptancefee crossfee invoicefee insurancefee zkfee cutfee luocao luocheng'.split(' ')
|
|
4
|
+
const priceUrls = {
|
|
5
|
+
pcb: 'https://www.eda.cn/openapi/api/hqpcb/public/ajax_valuation',
|
|
6
|
+
smt: 'https://www.eda.cn/openapi/api/smt-hqchip/smtservice/app/price/pricing',
|
|
7
|
+
}
|
|
8
|
+
const child = (node, key) => node.find(entry => Array.isArray(entry) && entry[0] === key)
|
|
9
|
+
|
|
10
|
+
export function quoteForm(kind, source, quantity) {
|
|
11
|
+
const facts = readBoardFacts(source)
|
|
12
|
+
if (!(facts.widthMm > 0 && facts.heightMm > 0)) throw new Error('请先在 Edge.Cuts 层绘制板框。')
|
|
13
|
+
const board = pcbOrderForm(facts, { quantity })
|
|
14
|
+
if (kind === 'pcb') return { ...board, service: 'pcb', region_id: '211', country: '211', express: '顺丰快递', address: '广东省深圳市' }
|
|
15
|
+
|
|
16
|
+
const root = parseSexpr(source)[0]
|
|
17
|
+
let smd = 0, through = 0
|
|
18
|
+
const sides = new Set(), materials = new Set()
|
|
19
|
+
for (const fp of root.filter(node => Array.isArray(node) && node[0] === 'footprint')) {
|
|
20
|
+
const attr = child(fp, 'attr') || []
|
|
21
|
+
if (attr.includes('dnp') || attr.includes('exclude_from_pos_files') || attr.includes('board_only')) continue
|
|
22
|
+
const pads = fp.filter(node => Array.isArray(node) && node[0] === 'pad' && node[1] !== '')
|
|
23
|
+
const mounted = pads.filter(p => p[2] === 'smd' || p[2] === 'thru_hole')
|
|
24
|
+
if (!mounted.length) continue
|
|
25
|
+
smd += mounted.filter(p => p[2] === 'smd').length
|
|
26
|
+
through += mounted.filter(p => p[2] === 'thru_hole').length
|
|
27
|
+
if (mounted.some(p => p[2] === 'smd')) sides.add(child(fp, 'layer')?.[1])
|
|
28
|
+
const value = fp.find(n => Array.isArray(n) && n[0] === 'property' && n[1] === 'Value')?.[2]
|
|
29
|
+
?? fp.find(n => Array.isArray(n) && n[0] === 'fp_text' && n[1] === 'value')?.[2]
|
|
30
|
+
materials.add(JSON.stringify([fp[1], value]))
|
|
31
|
+
}
|
|
32
|
+
if (!materials.size) throw new Error('板上没有可计价的贴装器件。')
|
|
33
|
+
return {
|
|
34
|
+
add_plat_form: 5, application_sphere: '1', is_pcb_soft_board: '0', custom_pcb_ban: '1',
|
|
35
|
+
number: String(quantity), single_or_double_technique: sides.size > 1 ? '2' : '1',
|
|
36
|
+
pcb_ban_height: board.blength, pcb_ban_width: board.bwidth, bom_purchase: '2',
|
|
37
|
+
bom_material_type_number: String(materials.size), patch_pad_number: String(smd),
|
|
38
|
+
is_plug: through ? '1' : '0', plug_number: String(through),
|
|
39
|
+
steel_type: '0', is_steel_follow_delivery: '0', solder_paste_type: '0',
|
|
40
|
+
is_assembly_weld: '0', is_layout_cleaning: '0', is_material_baking: '0', is_welding_wire: '0',
|
|
41
|
+
is_test: '0', is_assemble: '0', is_program_burning: '0', need_split: '0', is_increase_tinning: '0',
|
|
42
|
+
need_conformal_coating: '0', is_first_confirm: '0', packing_type: '0', x_ray_number: '1', x_ray_unit_number: '1',
|
|
43
|
+
patch_file_name: '', bom_file_name: '', pcb_file_name: '',
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function amount(value) {
|
|
48
|
+
if (typeof value !== 'number' && !(typeof value === 'string' && value.trim())) return undefined
|
|
49
|
+
const n = Number(value)
|
|
50
|
+
return Number.isFinite(n) ? n : undefined
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function quoteTotal(kind, body) {
|
|
54
|
+
let total
|
|
55
|
+
if (kind === 'pcb') {
|
|
56
|
+
const record = body?.data?.list?.pcb ?? (body?.suggest && body)
|
|
57
|
+
if (record) {
|
|
58
|
+
const fees = pcbFees.map(key => amount(record[key])).filter(n => n !== undefined)
|
|
59
|
+
if (fees.length) total = fees.reduce((a,b) => a+b, 0)
|
|
60
|
+
}
|
|
61
|
+
} else if (body?.suc === true || body?.suc === 1) {
|
|
62
|
+
const values = body.body || {}
|
|
63
|
+
const net = amount(values.smt_goods_fee_no_tax), tax = amount(values.smt_goods_fee_tax)
|
|
64
|
+
total = net !== undefined && tax !== undefined ? net + tax : amount(values.total)
|
|
65
|
+
}
|
|
66
|
+
if (!(total > 0)) throw new Error(body?.msg || body?.message || '华秋暂未返回有效金额。')
|
|
67
|
+
return Math.round(total * 100) / 100
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function quoteBoard(kind, text, quantity, signal) {
|
|
71
|
+
const form = quoteForm(kind, text, quantity)
|
|
72
|
+
const pcb = kind === 'pcb'
|
|
73
|
+
const res = await fetch(priceUrls[kind], {
|
|
74
|
+
method:'POST', signal, headers:{'content-type':pcb?'application/x-www-form-urlencoded':'application/json'},
|
|
75
|
+
body:pcb ? new URLSearchParams(form) : JSON.stringify(form),
|
|
76
|
+
})
|
|
77
|
+
if (!res.ok) throw new Error('华秋计价服务 HTTP ' + res.status)
|
|
78
|
+
return { total: quoteTotal(kind, await res.json()), currency:'CNY' }
|
|
79
|
+
}
|