@huaqiu/dsh-engineering-workbench 0.7.29 → 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 -27
- package/lib/client.js +12860 -1273
- package/lib/host.mjs +55 -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,94 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from 'react'
|
|
2
|
+
import { parseCsv } from './bom-csv'
|
|
3
|
+
import { basename } from './files'
|
|
4
|
+
import { manufacturingRequest } from './procurement'
|
|
5
|
+
|
|
6
|
+
function CoordinatesPreview({ text, filename }: {text:string;filename?:string}) {
|
|
7
|
+
const records = useMemo(() => {
|
|
8
|
+
const firstLine = text.split(/\r?\n/u, 1)[0] ?? ''
|
|
9
|
+
const tabSeparated = /\.tsv$/i.test(filename ?? '') || (!/\.csv$/i.test(filename ?? '') && firstLine.includes('\t'))
|
|
10
|
+
return parseCsv(text, tabSeparated ? '\t' : ',')
|
|
11
|
+
}, [text, filename])
|
|
12
|
+
const [header, ...rows] = records
|
|
13
|
+
if (!header) return <p role="status">坐标文件没有可预览的记录。</p>
|
|
14
|
+
|
|
15
|
+
const delimited = !filename || /\.(csv|tsv)$/i.test(filename)
|
|
16
|
+
|| (header.length > 1 && rows.length > 0 && rows.every(row => row.length === header.length))
|
|
17
|
+
if (!delimited) return <pre className="ew-coordinates" tabIndex={0}>{text}</pre>
|
|
18
|
+
|
|
19
|
+
const width = rows.reduce((max, row) => Math.max(max, row.length), header.length)
|
|
20
|
+
const columns = Array.from({ length: width }, (_, index) => {
|
|
21
|
+
const label = header[index]?.trim() || '列 ' + (index + 1)
|
|
22
|
+
return { label, numeric: /^(?:pos[xy]|[xy]|rot(?:ation)?)$/iu.test(label) }
|
|
23
|
+
})
|
|
24
|
+
return <div className="ew-position-scroll" tabIndex={0} role="region" aria-label="坐标数据,可滚动">
|
|
25
|
+
<table className="ew-position-table" aria-label="坐标文件表格">
|
|
26
|
+
<thead><tr>{columns.map(({ label, numeric }, index) => <th key={index} scope="col" data-numeric={numeric}>{label}</th>)}</tr></thead>
|
|
27
|
+
<tbody>{rows.map((row, index) => <tr key={index}>
|
|
28
|
+
{columns.map(({ numeric }, column) => <td key={column} data-numeric={numeric}>
|
|
29
|
+
<span title={row[column]}>{row[column]}</span>
|
|
30
|
+
</td>)}
|
|
31
|
+
</tr>)}</tbody>
|
|
32
|
+
</table>
|
|
33
|
+
</div>
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function FabricationFiles({tab, board}: {tab:'Gerber'|'坐标文件';board:string}) {
|
|
37
|
+
const [layers,setLayers] = useState<{name:string;bytes:number}[]>([])
|
|
38
|
+
const [layer,setLayer] = useState('')
|
|
39
|
+
const [svg,setSvg] = useState('')
|
|
40
|
+
const [note,setNote] = useState('')
|
|
41
|
+
const [file,setFile] = useState<File>()
|
|
42
|
+
const [text,setText] = useState('')
|
|
43
|
+
const [status,setStatus] = useState('')
|
|
44
|
+
const [layerError,setLayerError] = useState('')
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
if (tab !== 'Gerber' || !board || file) return
|
|
47
|
+
const ctrl = new AbortController()
|
|
48
|
+
setLayerError('')
|
|
49
|
+
manufacturingRequest<{layers:typeof layers}>('layers',{path:board},ctrl.signal).then(data => {
|
|
50
|
+
if (ctrl.signal.aborted) return
|
|
51
|
+
setLayers(data.layers)
|
|
52
|
+
setLayer(data.layers.find(f => /F[._-]Cu|\.gtl$/i.test(f.name))?.name || data.layers[0]?.name || '')
|
|
53
|
+
if (!data.layers.length) setLayerError('此板没有导出的 Gerber 图层。')
|
|
54
|
+
}).catch(e => {if (!ctrl.signal.aborted) setLayerError(String(e.message))})
|
|
55
|
+
return () => ctrl.abort()
|
|
56
|
+
},[board,tab,file])
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
const ctrl = new AbortController()
|
|
59
|
+
setSvg('');setText('');setNote('')
|
|
60
|
+
if (!board && !file) {setStatus('选择板文件或打开本机文件。');return}
|
|
61
|
+
async function load() {
|
|
62
|
+
if (file && file.size > 16*1024*1024) throw new Error('单个预览文件上限为 16 MiB。')
|
|
63
|
+
if (tab === '坐标文件') {
|
|
64
|
+
const value = file ? await file.text() : (await manufacturingRequest<{text:string}>('positions',{path:board},ctrl.signal)).text
|
|
65
|
+
if (!ctrl.signal.aborted) {setText(value);setStatus(value.trim() ? '' : '坐标文件为空。')}
|
|
66
|
+
} else {
|
|
67
|
+
if (!file && !layer) return
|
|
68
|
+
const data = file ? await manufacturingRequest<{svg:string;warnings:string[]}>('local-gerber',{text:await file.text()},ctrl.signal)
|
|
69
|
+
: await manufacturingRequest<{svg:string;warnings:string[]}>('gerber',{path:board,layer},ctrl.signal)
|
|
70
|
+
if (!ctrl.signal.aborted) {setSvg(data.svg);setNote(data.warnings.join(' · '));setStatus('')}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
setStatus(tab === 'Gerber' ? '正在准备 Gerber 图层…' : '正在读取坐标文件…')
|
|
74
|
+
load().catch(e => {if (!ctrl.signal.aborted) setStatus(String(e.message))})
|
|
75
|
+
return () => ctrl.abort()
|
|
76
|
+
},[tab,board,layer,file])
|
|
77
|
+
const gerber = tab === 'Gerber'
|
|
78
|
+
const openLabel = gerber ? '打开Gerber文件' : '打开坐标文件'
|
|
79
|
+
return <section className="ew-fab-file" aria-label={tab+'预览'}>
|
|
80
|
+
<header>
|
|
81
|
+
{gerber && !file && layers.length > 0 && <label>图层 <select value={layer} onChange={e=>setLayer(e.target.value)}>{layers.map(f=><option key={f.name}>{f.name}</option>)}</select></label>}
|
|
82
|
+
{!gerber && !file && board && <strong>{basename(board).replace(/\.kicad_pcb$/i,'-positions.csv')}</strong>}
|
|
83
|
+
<label className="ew-model-picker">{openLabel}<input type="file" aria-label={openLabel} accept={gerber?'.gbr,.ger,.gtl,.gbl,.gts,.gbs,.gto,.gbo,.gtp,.gbp,.gko,.gm1,.drl,.xln':'.csv,.pos,.txt,.tsv'} onChange={e=>{
|
|
84
|
+
if(e.target.files?.[0])setFile(e.target.files[0])
|
|
85
|
+
e.target.value=''
|
|
86
|
+
}}/></label>
|
|
87
|
+
{file && <><span>{file.name}</span><button onClick={()=>setFile(undefined)}>返回工程文件</button></>}
|
|
88
|
+
</header>
|
|
89
|
+
{(status || (!file && layerError)) && <p role="status">{(!file && layerError) || status}</p>}
|
|
90
|
+
{svg && <div className="ew-gerber"><img alt={file?.name || layer} src={'data:image/svg+xml;charset=utf-8,'+encodeURIComponent(svg)}/></div>}
|
|
91
|
+
{note && <p role="status">图层解析提示 {note}</p>}
|
|
92
|
+
{text.trim() && <CoordinatesPreview text={text} filename={file?.name} />}
|
|
93
|
+
</section>
|
|
94
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { useEffect, useMemo, useState } from 'react'
|
|
2
|
+
import { BomGrid } from './BomGrid'
|
|
3
|
+
import { FabricationFiles } from './FabricationFiles'
|
|
4
|
+
import { restoreMatches, restoreRows, snapshotLines, type SavedBom } from './bom-snapshot'
|
|
5
|
+
import { bomCsv, downloadBom } from './bom-export'
|
|
6
|
+
import { boardReferences, manufacturerOf, originalMpn, rowKey, type BomLine } from './bom-rows'
|
|
7
|
+
import { basket,identity,manufacturingRequest,matchRow,readManufacturingBom,searchTerm,type Candidate,type MatchTable } from './procurement'
|
|
8
|
+
|
|
9
|
+
export const manufacturingTabs = ['BOM','Gerber','坐标文件'] as const
|
|
10
|
+
export type ManufacturingTab = typeof manufacturingTabs[number]
|
|
11
|
+
interface Props {
|
|
12
|
+
tab:ManufacturingTab; path:string; board:string; boardKey?:string; cwd:string; session:string; reference:string; location?:string
|
|
13
|
+
select:(v:string)=>void; order:()=>void; ask:()=>void
|
|
14
|
+
}
|
|
15
|
+
const money = (n:number, digits=2) => '¥'+n.toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:digits})
|
|
16
|
+
|
|
17
|
+
export function Manufacture({tab,path,board,boardKey=board,cwd,session,reference,location,select,order,ask}:Props) {
|
|
18
|
+
const [lines,setLines] = useState<readonly BomLine[]>()
|
|
19
|
+
const rows = useMemo(() => lines ?? [], [lines])
|
|
20
|
+
const [loading,setLoading]=useState(!!path)
|
|
21
|
+
const [message,setMessage] = useState('')
|
|
22
|
+
const [quantity,setQuantity] = useState(5)
|
|
23
|
+
const [quoteRows,setQuoteRows] = useState<readonly {row:BomLine;query:string}[]>()
|
|
24
|
+
const [matches,setMatches] = useState<MatchTable>({})
|
|
25
|
+
const [busy,setBusy] = useState(false)
|
|
26
|
+
const [builtIn,setBuiltIn] = useState(false)
|
|
27
|
+
const [quotes,setQuotes] = useState({pcb:'待查询',smt:'待查询'})
|
|
28
|
+
const [queriedAt,setQueriedAt]=useState('')
|
|
29
|
+
const [saved,setSaved]=useState<Pick<SavedBom,'version'|'savedAt'>>()
|
|
30
|
+
const [saving,setSaving]=useState(false)
|
|
31
|
+
const [dirty,setDirty]=useState(false)
|
|
32
|
+
const [saveError,setSaveError]=useState('')
|
|
33
|
+
useEffect(()=>{
|
|
34
|
+
if (!path) {setMessage('请选择原理图以生成 BOM。');return}
|
|
35
|
+
const ctrl = new AbortController()
|
|
36
|
+
setLoading(true)
|
|
37
|
+
setMessage('正在从原理图生成 BOM…')
|
|
38
|
+
readManufacturingBom(path,cwd,session,ctrl.signal).then(bom=>{
|
|
39
|
+
if (ctrl.signal.aborted)return
|
|
40
|
+
const loaded=bom.saved ? restoreRows(bom.rows,bom.saved) : bom.rows
|
|
41
|
+
setLines(loaded)
|
|
42
|
+
setBuiltIn(bom.builtIn)
|
|
43
|
+
let message=bom.warning || (bom.rows.length?'':'该原理图没有物料记录。')
|
|
44
|
+
if(bom.saved){
|
|
45
|
+
const previous=bom.saved
|
|
46
|
+
const restored=restoreMatches(loaded,previous)
|
|
47
|
+
setSaved({version:previous.version,savedAt:previous.savedAt});setMatches(restored.matches)
|
|
48
|
+
setQuantity(previous.quantity);setQueriedAt(previous.queriedAt)
|
|
49
|
+
if(previous.boardKey===boardKey)setQuotes(previous.quotes)
|
|
50
|
+
if(restored.changed){
|
|
51
|
+
message=[message,'原理图物料已变更,仅恢复了未变更行的采购结果。'].filter(Boolean).join(' ')
|
|
52
|
+
setDirty(true)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
setMessage(message)
|
|
56
|
+
}).catch(e=>{if(!ctrl.signal.aborted)setMessage(String(e.message))}).finally(()=>{if(!ctrl.signal.aborted)setLoading(false)})
|
|
57
|
+
return ()=>ctrl.abort()
|
|
58
|
+
},[path,cwd,session,boardKey])
|
|
59
|
+
|
|
60
|
+
useEffect(()=>{
|
|
61
|
+
if (!quoteRows) return
|
|
62
|
+
const ctrl = new AbortController()
|
|
63
|
+
setQuotes({pcb:board?'查询中…':'请选择板文件',smt:board?'查询中…':'请选择板文件'})
|
|
64
|
+
if (board) for (const kind of ['pcb','smt'] as const) {
|
|
65
|
+
manufacturingRequest<{total:number}>(kind,{path:board,quantity},ctrl.signal).then(q=>{
|
|
66
|
+
if (!ctrl.signal.aborted) setQuotes(prev=>({...prev,[kind]:money(q.total)}))
|
|
67
|
+
}).catch(e=>{ if (!ctrl.signal.aborted) setQuotes(prev=>({...prev,[kind]:'未报价 · '+e.message})) })
|
|
68
|
+
}
|
|
69
|
+
return ()=>ctrl.abort()
|
|
70
|
+
},[quoteRows,quantity,board])
|
|
71
|
+
|
|
72
|
+
useEffect(()=>{
|
|
73
|
+
if (!quoteRows?.length || builtIn) return
|
|
74
|
+
const ctrl = new AbortController()
|
|
75
|
+
const groups = new Map<string,BomLine[]>()
|
|
76
|
+
for (const {row,query} of quoteRows) {
|
|
77
|
+
groups.set(query,[...(groups.get(query) || []),row])
|
|
78
|
+
}
|
|
79
|
+
const jobs = [...groups]
|
|
80
|
+
async function worker() {
|
|
81
|
+
while (!ctrl.signal.aborted && jobs.length) {
|
|
82
|
+
const [query,group] = jobs.shift()!
|
|
83
|
+
let candidates:Candidate[] = [], error=''
|
|
84
|
+
try {
|
|
85
|
+
if (query) ({candidates}=await manufacturingRequest<{candidates:Candidate[]}>('parts',{query},ctrl.signal))
|
|
86
|
+
} catch(e) {error=e instanceof Error ? e.message : String(e)}
|
|
87
|
+
if (ctrl.signal.aborted) return
|
|
88
|
+
setMatches(prev=>{
|
|
89
|
+
const next={...prev}
|
|
90
|
+
for (const row of group) {
|
|
91
|
+
const key=rowKey(row), match=matchRow(row,candidates)
|
|
92
|
+
const current=prev[key]
|
|
93
|
+
const preferred=current?.selected ?? current?.pending
|
|
94
|
+
if (!preferred) {
|
|
95
|
+
next[key]={...match,error}
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
const refreshed=candidates.find(part=>identity(part)===identity(preferred))
|
|
99
|
+
const retained=refreshed ?? {...preferred,offers:[]}
|
|
100
|
+
next[key]={candidates:refreshed?candidates:[retained,...candidates],error,
|
|
101
|
+
selected:current?.selected?retained:undefined,pending:current?.pending?retained:undefined}
|
|
102
|
+
}
|
|
103
|
+
return next
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
setBusy(true)
|
|
108
|
+
Promise.all([worker(),worker()]).then(()=>{if(!ctrl.signal.aborted)setBusy(false)})
|
|
109
|
+
return ()=>ctrl.abort()
|
|
110
|
+
},[quoteRows,builtIn])
|
|
111
|
+
|
|
112
|
+
const summary=useMemo(()=>basket(rows,matches,quantity),[rows,matches,quantity])
|
|
113
|
+
const part = rows.find(r=>!r.manual && boardReferences(r).some(ref=>ref.toUpperCase()===reference.toUpperCase()))
|
|
114
|
+
const total=summary.covered ? money(summary.total)+(summary.covered<summary.lines?'(部分)':'') : queriedAt?'暂无已报价项':'待查询'
|
|
115
|
+
const querying=busy || quotes.pcb==='查询中…' || quotes.smt==='查询中…'
|
|
116
|
+
const editable=!!lines && !loading && !querying && !saving && !builtIn
|
|
117
|
+
|
|
118
|
+
function quote() {
|
|
119
|
+
setQuoteRows(rows.filter(row=>!row.dnp).map(row=>{
|
|
120
|
+
const match=matches[rowKey(row)]
|
|
121
|
+
return {row,query:(match?.selected ?? match?.pending)?.mpn ?? searchTerm(row)}
|
|
122
|
+
}))
|
|
123
|
+
setQueriedAt(new Date().toISOString())
|
|
124
|
+
setDirty(true)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function add(row:BomLine) {
|
|
128
|
+
setLines(previous=>[...(previous??[]),row])
|
|
129
|
+
setDirty(true)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function edit(row:BomLine, update:BomLine) {
|
|
133
|
+
const next=row.manual ? update : {...update,source:row.source??row}
|
|
134
|
+
const previousKey=rowKey(row)
|
|
135
|
+
const nextKey=rowKey(next)
|
|
136
|
+
const materialChanged=row.value!==next.value || row.footprint!==next.footprint
|
|
137
|
+
|| originalMpn(row)!==originalMpn(next) || manufacturerOf(row)!==manufacturerOf(next)
|
|
138
|
+
setLines(previous=>previous?.map(line=>line===row?next:line))
|
|
139
|
+
if (materialChanged || previousKey!==nextKey) setMatches(previous=>{
|
|
140
|
+
const match=previous[previousKey]
|
|
141
|
+
const changed={...previous}
|
|
142
|
+
delete changed[previousKey]
|
|
143
|
+
if (!materialChanged && match) changed[nextKey]=match
|
|
144
|
+
return changed
|
|
145
|
+
})
|
|
146
|
+
setDirty(true)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function nominate(key:string,part:Candidate,candidates:Candidate[]) {
|
|
150
|
+
setMatches(previous=>({...previous,[key]:{candidates,pending:part}}))
|
|
151
|
+
setQueriedAt(new Date().toISOString())
|
|
152
|
+
setDirty(true)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function choose(key:string,part:Candidate) {
|
|
156
|
+
setMatches(previous=>({...previous,[key]:{candidates:previous[key]?.candidates??[part],selected:part}}))
|
|
157
|
+
setDirty(true)
|
|
158
|
+
}
|
|
159
|
+
async function save(){
|
|
160
|
+
setSaving(true);setSaveError('')
|
|
161
|
+
try{
|
|
162
|
+
const result=await manufacturingRequest<Pick<SavedBom,'version'|'savedAt'>>('save-bom',{path,version:saved?.version??null,
|
|
163
|
+
snapshot:{schema:1,boardKey,quantity,queriedAt,quotes,lines:snapshotLines(rows,matches)}},new AbortController().signal)
|
|
164
|
+
setSaved(result);setDirty(false)
|
|
165
|
+
}catch(e){setSaveError('保存失败。'+(e instanceof Error?e.message:String(e)))}
|
|
166
|
+
finally{setSaving(false)}
|
|
167
|
+
}
|
|
168
|
+
return <section className="ew-manufacture" data-manufacturing-tab={tab}>
|
|
169
|
+
<header className="ew-pricing"><label>生产套数 <input type="number" min="1" max="100000" value={quantity} onChange={e=>{
|
|
170
|
+
const n=e.target.valueAsNumber
|
|
171
|
+
if(Number.isSafeInteger(n) && n>=1 && n<=100000 && n!==quantity){
|
|
172
|
+
setQuantity(n);setDirty(true)
|
|
173
|
+
if(!quoteRows)setQuotes({pcb:'待查询',smt:'待查询'})
|
|
174
|
+
}
|
|
175
|
+
}} disabled={saving || loading}/> 套</label><button onClick={quote} disabled={loading || querying || saving || builtIn || !rows.length && !board}>{busy?'正在匹配器件…':'查询华秋价格'}</button>
|
|
176
|
+
<button disabled={!board} onClick={order}>报价与下单 ↗</button></header>
|
|
177
|
+
{builtIn && <p role="status">已用内置接口读取原理图 BOM。请从系统托盘退出华秋 DSH 后重新打开,以启用制造报价。</p>}
|
|
178
|
+
<dl className="ew-prices" aria-label="本批次报价">
|
|
179
|
+
<div><dt>BOM 采购</dt><dd>{total}</dd>{queriedAt && summary.lines>0 && <small>{summary.covered}/{summary.lines} 行有价</small>}</div>
|
|
180
|
+
<div><dt>PCB 裸板</dt><dd>{quotes.pcb}</dd></div><div><dt>SMT 贴装</dt><dd>{quotes.smt}</dd></div>
|
|
181
|
+
</dl>
|
|
182
|
+
{tab!=='BOM' ? <FabricationFiles key={tab+board} tab={tab} board={board}/> : <>
|
|
183
|
+
{message && (message!=='该原理图没有物料记录。' || !rows.length) && <p role="status">{message}</p>}
|
|
184
|
+
<div className="ew-files">
|
|
185
|
+
<button onClick={save} disabled={!rows.length || querying || saving || builtIn}>{saving?'保存中…':'保存 BOM'}</button>
|
|
186
|
+
<button disabled={!rows.length || querying} onClick={()=>downloadBom(path,bomCsv(rows,matches,quantity,queriedAt))}>导出 CSV</button>
|
|
187
|
+
<span role="status">{saveError || (dirty?'有未保存的更改':saved?'已保存 · '+new Date(saved.savedAt).toLocaleString('zh-CN'):'')}</span>
|
|
188
|
+
</div>
|
|
189
|
+
<BomGrid rows={rows} matches={matches} quantity={quantity} reference={reference} busy={busy} summary={summary}
|
|
190
|
+
select={select} editable={editable} add={editable ? add : undefined} choose={choose} edit={edit} nominate={nominate}/>
|
|
191
|
+
{part && <footer><label>位号 <select aria-label="物料位号" value={reference} onChange={e=>select(e.target.value)}>{boardReferences(part).map(ref=><option key={ref}>{ref}</option>)}</select></label>
|
|
192
|
+
<span>{location || '当前 PCB 未匹配到位置'}</span><button onClick={ask}>询问助手</button></footer>}
|
|
193
|
+
</>}
|
|
194
|
+
</section>
|
|
195
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from 'react'
|
|
2
|
+
// This panel and the `.stl`/`.obj` document body draw the same file, so they
|
|
3
|
+
// mount it the same way: the product's own model document renderer owns the
|
|
4
|
+
// parsers, the unit conversion, the light rig and the disposal order. The panel
|
|
5
|
+
// keeps only what differs — which file the user picked and how it is reported.
|
|
6
|
+
import { DocumentRenderError, MAX_DOCUMENT_BYTES } from '../../dsh-hardware-ui/src/client/document/mount'
|
|
7
|
+
import { mountModelDocument } from '../../dsh-hardware-ui/src/client/document/model'
|
|
8
|
+
import { styles } from './styles'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Say what went wrong the way the rest of this panel speaks.
|
|
12
|
+
*
|
|
13
|
+
* The document renderer reports typed reasons with English text meant for a
|
|
14
|
+
* developer; a person who dragged the wrong file into a workbench panel needs
|
|
15
|
+
* the next step, not the parser's sentence. Anything unrecognised keeps its own
|
|
16
|
+
* message rather than being replaced by a vague one.
|
|
17
|
+
*/
|
|
18
|
+
function previewFailure(error: unknown): string {
|
|
19
|
+
if (!(error instanceof DocumentRenderError)) {
|
|
20
|
+
return String((error as { message?: unknown } | undefined)?.message ?? error)
|
|
21
|
+
}
|
|
22
|
+
switch (error.reason) {
|
|
23
|
+
case 'toolarge': return '模型超过 32 MiB 预览上限。'
|
|
24
|
+
case 'parse': return '这个文件无法解析为 STL 或 OBJ 模型。'
|
|
25
|
+
case 'empty': return '文件里没有可预览的几何体。'
|
|
26
|
+
case 'render': return '当前环境无法创建 3D 预览。'
|
|
27
|
+
case 'timeout': return '预览超时,请重试。'
|
|
28
|
+
case 'missing-companion': return `缺少文件 ${error.message}。`
|
|
29
|
+
default: return error.message
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type Result<T> = {ok:true;value:T}|{ok:false;error:{code?:string;message?:string}}
|
|
34
|
+
interface Directory { entries:{name:string;type:string;size?:number}[]; truncated:boolean }
|
|
35
|
+
export interface WorkspaceModels {
|
|
36
|
+
list(session:string,path:string,signal:AbortSignal):Promise<Result<Directory>>
|
|
37
|
+
readBytes(session:string,path:string,options:Record<string,never>,signal:AbortSignal):Promise<Result<{data:Uint8Array<ArrayBuffer>;eof:boolean}>>
|
|
38
|
+
}
|
|
39
|
+
interface Model {name:string;path:string;size?:number;file?:File}
|
|
40
|
+
interface Catalog {models:Model[];notice?:string;folder?:string;folders?:string[]}
|
|
41
|
+
type Source={folder?:string;local?:Catalog}
|
|
42
|
+
const supported=(name:string)=>/\.(stl|obj)$/i.test(name)
|
|
43
|
+
const sortModels=(models:Model[])=>models.sort((a,b)=>a.name.localeCompare(b.name,undefined,{numeric:true}))
|
|
44
|
+
|
|
45
|
+
export async function scan(files:WorkspaceModels,session:string,folder:string|undefined,signal:AbortSignal):Promise<Catalog>{
|
|
46
|
+
const groups=new Map<string,Model[]>()
|
|
47
|
+
const named=new Set<string>()
|
|
48
|
+
const pending=[{path:folder??'.',prefix:'',group:folder}]
|
|
49
|
+
let incomplete=false
|
|
50
|
+
while(pending.length){
|
|
51
|
+
signal.throwIfAborted()
|
|
52
|
+
await Promise.all(pending.splice(-4).map(async ({path,prefix,group})=>{
|
|
53
|
+
const result=await files.list(session,path,signal)
|
|
54
|
+
if(!result.ok){
|
|
55
|
+
if(path!==(folder??'.')){incomplete=true;return}
|
|
56
|
+
throw new Error(result.error.code==='workspace-file/not-found'?'找不到该文件夹,请切换目录。':result.error.message || '无法读取文件夹。')
|
|
57
|
+
}
|
|
58
|
+
incomplete ||= result.value.truncated
|
|
59
|
+
for(const entry of result.value.entries){
|
|
60
|
+
const child=path==='.'?entry.name:path.replace(/[/\\]+$/,'')+'/'+entry.name
|
|
61
|
+
if(entry.type==='directory'){
|
|
62
|
+
if(!folder && ['.git','node_modules'].includes(entry.name))continue
|
|
63
|
+
const startsGroup=!group && /^(mechanical|mechnical)$/i.test(entry.name)
|
|
64
|
+
if(startsGroup)named.add(child)
|
|
65
|
+
pending.push({path:child,prefix:startsGroup?'':prefix+entry.name+'/',group:startsGroup?child:group})
|
|
66
|
+
}else if(entry.type==='file' && supported(entry.name)){
|
|
67
|
+
const key=group??path
|
|
68
|
+
const models=groups.get(key)??[]
|
|
69
|
+
models.push({name:group?prefix+entry.name:entry.name,path:child,size:entry.size})
|
|
70
|
+
groups.set(key,models)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}))
|
|
74
|
+
}
|
|
75
|
+
const priority=(dir:string)=>named.has(dir)?0:groups.get(dir)?.some(m=>/\.stl$/i.test(m.name))?1:2
|
|
76
|
+
const folders=Array.from(new Set([...groups.keys(),...named])).sort((a,b)=>
|
|
77
|
+
Number(!groups.has(a))-Number(!groups.has(b)) || priority(a)-priority(b) ||
|
|
78
|
+
a.split('/').length-b.split('/').length || a.localeCompare(b,undefined,{numeric:true}))
|
|
79
|
+
const resolved=folder??folders[0]
|
|
80
|
+
return {folder:resolved,folders,models:sortModels(groups.get(resolved??'')??[]),
|
|
81
|
+
notice:incomplete?'部分目录未能完整列出,可直接切换到对应子目录。':undefined}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function ModelPreview({model,files,session}:{model:Model;files?:WorkspaceModels;session:string}){
|
|
85
|
+
const host=useRef<HTMLDivElement>(null)
|
|
86
|
+
const [status,setStatus]=useState('正在读取模型…')
|
|
87
|
+
useEffect(()=>{
|
|
88
|
+
const controller=new AbortController()
|
|
89
|
+
const {signal}=controller
|
|
90
|
+
let preview:{dispose():void}|undefined
|
|
91
|
+
async function load(){
|
|
92
|
+
if((model.size??0)>MAX_DOCUMENT_BYTES)throw new Error('模型超过 32 MiB。')
|
|
93
|
+
let buffer:ArrayBuffer
|
|
94
|
+
if(model.file) buffer=await model.file.arrayBuffer()
|
|
95
|
+
else{
|
|
96
|
+
if(!files)throw new Error('当前会话无法读取模型。')
|
|
97
|
+
const result=await files.readBytes(session,model.path,{},signal)
|
|
98
|
+
if(!result.ok)throw new Error(result.error.message||'无法读取文件。')
|
|
99
|
+
const {data,eof}=result.value
|
|
100
|
+
if(!eof || data.byteLength>MAX_DOCUMENT_BYTES)throw new Error('模型超过预览上限或文件不完整。')
|
|
101
|
+
buffer=data.slice().buffer
|
|
102
|
+
}
|
|
103
|
+
signal.throwIfAborted()
|
|
104
|
+
// `path` decides which importer reads the bytes; a file picked in the
|
|
105
|
+
// browser has no Host path, so its name stands in for one.
|
|
106
|
+
const mounted=await mountModelDocument({
|
|
107
|
+
bytes:new Uint8Array(buffer), path:model.path || model.name, container:host.current!, signal,
|
|
108
|
+
})
|
|
109
|
+
if(signal.aborted){mounted.dispose();return}
|
|
110
|
+
preview=mounted
|
|
111
|
+
setStatus('')
|
|
112
|
+
}
|
|
113
|
+
setStatus('正在读取模型…')
|
|
114
|
+
load().catch(e=>{if(!signal.aborted)setStatus('无法预览模型。'+previewFailure(e))})
|
|
115
|
+
return ()=>{controller.abort();preview?.dispose()}
|
|
116
|
+
},[model,files,session])
|
|
117
|
+
return <div className="ew-stage"><div className="ew-surface" ref={host}/>
|
|
118
|
+
{status && <div className="ew-message" role="status">{status}</div>}</div>
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function Mechanical({files,sessionId}:{files?:WorkspaceModels;sessionId:string}){
|
|
122
|
+
return <ModelBrowser key={sessionId} files={files} session={sessionId}/>
|
|
123
|
+
}
|
|
124
|
+
function ModelBrowser({files,session}:{files?:WorkspaceModels;session:string}){
|
|
125
|
+
const [source,setSource]=useState<Source>({})
|
|
126
|
+
const [draft,setDraft]=useState<string>()
|
|
127
|
+
const [folders,setFolders]=useState<string[]>([])
|
|
128
|
+
const [loaded,setLoaded]=useState<{source:Source;catalog:Catalog}>()
|
|
129
|
+
const [selected,setSelected]=useState('')
|
|
130
|
+
const picker=useRef<HTMLInputElement | null>(null)
|
|
131
|
+
const catalog=source.local??(loaded?.source===source?loaded.catalog:undefined)
|
|
132
|
+
const input=draft??source.folder??catalog?.folder??''
|
|
133
|
+
const currentFolder=source.folder??catalog?.folder??''
|
|
134
|
+
const model=catalog?.models.find(item=>item.name===selected)??catalog?.models[0]
|
|
135
|
+
useEffect(()=>{
|
|
136
|
+
if(source.local)return
|
|
137
|
+
const controller=new AbortController()
|
|
138
|
+
const list=files?scan(files,session,source.folder,controller.signal):Promise.reject(new Error('工作区目录不可用,请使用「浏览文件夹」。'))
|
|
139
|
+
list.then(catalog=>{if(!controller.signal.aborted){
|
|
140
|
+
if(!source.folder)setFolders(catalog.folders??[])
|
|
141
|
+
setLoaded({source,catalog})
|
|
142
|
+
}})
|
|
143
|
+
.catch(e=>{if(!controller.signal.aborted)setLoaded({source,catalog:{models:[],notice:String(e.message||e)}})})
|
|
144
|
+
return ()=>controller.abort()
|
|
145
|
+
},[source,files,session])
|
|
146
|
+
return <section className="ew" aria-label="结构设计" data-view="mechanical"><style>{styles}</style>
|
|
147
|
+
<form className="ew-files ew-model-folder" onSubmit={e=>{e.preventDefault();if(input.trim())setSource({folder:input.trim()})}}>
|
|
148
|
+
{folders.length>1 && <label>已定位目录 <select value={!source.local && folders.includes(currentFolder)?currentFolder:''} onChange={e=>{
|
|
149
|
+
setDraft(undefined);setSelected('');setSource({folder:e.target.value})
|
|
150
|
+
}}><option value="" disabled>选择目录</option>{folders.map(dir=><option key={dir} value={dir}>{dir}</option>)}</select></label>}
|
|
151
|
+
<label>文件夹 <input value={input} title={input} onChange={e=>setDraft(e.target.value)} placeholder="工作区模型目录"/></label>
|
|
152
|
+
<button type="submit" disabled={!input.trim()}>打开目录</button>
|
|
153
|
+
<button type="button" onClick={()=>{setSource({});setSelected('');setDraft(undefined)}}>自动定位</button>
|
|
154
|
+
<button type="button" onClick={()=>picker.current?.click()}>浏览文件夹</button>
|
|
155
|
+
<input type="file" hidden multiple ref={el=>{picker.current=el;el?.setAttribute('webkitdirectory','')}} aria-label="选择本机文件夹" onChange={e=>{
|
|
156
|
+
const entries=Array.from(e.target.files??[])
|
|
157
|
+
e.target.value=''
|
|
158
|
+
if(!entries.length)return
|
|
159
|
+
const folder=entries[0]!.webkitRelativePath.split('/')[0]!
|
|
160
|
+
const models=entries.filter(f=>supported(f.name)).map(file=>({file,path:file.webkitRelativePath,name:file.webkitRelativePath.slice(folder.length+1),size:file.size}))
|
|
161
|
+
setDraft(undefined);setSource({folder,local:{models:sortModels(models)}});setSelected('')
|
|
162
|
+
}}/>
|
|
163
|
+
</form>
|
|
164
|
+
<div className="ew-files"><label>结构件 <select value={model?.name??''} disabled={!model} onChange={e=>setSelected(e.target.value)}>
|
|
165
|
+
{!model && <option value="">选择模型</option>}{catalog?.models.map(m=><option key={m.name} value={m.name}>{m.name}</option>)}</select></label>
|
|
166
|
+
{model && <span>拖动旋转,滚轮缩放</span>}</div>
|
|
167
|
+
{catalog?.notice && <p role="status">{catalog.notice}</p>}
|
|
168
|
+
<section className="ew-pane ew-model" aria-label="结构件预览">
|
|
169
|
+
{model ? <ModelPreview model={model} files={files} session={session}/> :
|
|
170
|
+
<div className="ew-stage"><div className="ew-message" role="status">{!catalog?'正在查找结构件…':catalog.notice?'请选择其他模型目录。':source.folder?'此文件夹及其子目录中没有 STL 或 OBJ 模型。':'当前工作区中没有找到 STL 或 OBJ 模型。'}</div></div>}
|
|
171
|
+
</section>
|
|
172
|
+
</section>
|
|
173
|
+
}
|
package/src/ToolRail.tsx
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { useState, useSyncExternalStore } from 'react'
|
|
2
|
+
import type { MountedSession } from './caption-menu'
|
|
3
|
+
|
|
4
|
+
const tools = {
|
|
5
|
+
schematic: {label:'原理图', path:'M2 7h6m8 0h6M8 4h8v6H8zM5 7v10h6m0-3v6m4-6v6m0-3h5V7'},
|
|
6
|
+
pcb: {label:'PCB', path:'M3 3h18v18H3z M6 6h3v3H6z M15 15h3v3h-3z M9 8h3l4 4v3 M6 17h3l3-3'},
|
|
7
|
+
'3d': {label:'3D', path:'M12 2 22 7.5v9L12 22 2 16.5v-9z M2 7.5 12 13l10-5.5 M12 13v9 M7 5l10 5.5'},
|
|
8
|
+
mechanical: {label:'结构件', path:'M2 11 12 6l10 5-10 5z M2 11v5l10 5 10-5v-5 M12 16v5 M7 8.5V5l5-2.5L17 5v3.5 M7 5l5 2.5L17 5 M12 7.5V11'},
|
|
9
|
+
review: {label:'评审', path:'M13 21H4V3h11l4 4v4 M14 3v5h5 M7 11h6 M7 15h3 M13 16l3 3 6-7'},
|
|
10
|
+
manufacture: {label:'制造', path:'M2 21V10l7-4v6l6-4v5h7v8z M17 12l1-9h3l1 10 M5 17h2m3 0h2m3 0h3'},
|
|
11
|
+
} as const
|
|
12
|
+
export type RailTool = keyof typeof tools
|
|
13
|
+
export type DesignTool = Exclude<RailTool,'review'|'manufacture'|'mechanical'>
|
|
14
|
+
const designTools: RailTool[] = ['schematic','pcb','3d','mechanical']
|
|
15
|
+
|
|
16
|
+
const railStyles = `
|
|
17
|
+
/* Leave a dedicated strip beside the frame, including when the dock is closed. */
|
|
18
|
+
:has(>[data-shell-overlay] .ew-rail){margin-inline-end:54px}
|
|
19
|
+
.ew-rail{position:fixed;inset:var(--dsh-windows-titlebar-height,0px) 0 0 auto;box-sizing:border-box;width:54px;overflow-y:auto;scrollbar-width:thin;display:flex;flex-direction:column;align-items:stretch;gap:3px;padding:8px 3px 6px;background:var(--dsw-alias-bg-base,#20332b);color:var(--dsw-alias-label-primary,#edf4ed);border-inline-start:1px solid var(--dsw-alias-border-l2,#587062);font:500 11px/1.15 system-ui,sans-serif;pointer-events:auto}
|
|
20
|
+
.ew-rail button{appearance:none;position:relative;box-sizing:border-box;width:100%;display:grid;place-content:center;justify-items:center;gap:3px;padding:2px 0;white-space:nowrap;min-height:44px;border:1px solid transparent;border-radius:4px;background:transparent;color:inherit;font:inherit;cursor:pointer}
|
|
21
|
+
.ew-rail button:hover,.ew-rail button:focus-visible{background:var(--dsw-alias-bg-hover,rgba(123,155,137,.2));border-color:currentColor}
|
|
22
|
+
.ew-rail button:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
|
|
23
|
+
.ew-rail svg{width:21px;height:21px;fill:none;stroke:currentColor;stroke-width:1.55;stroke-linejoin:round;stroke-linecap:round}
|
|
24
|
+
.ew-rail .ew-branch{min-height:25px;display:flex;align-items:center;justify-content:center;gap:3px}
|
|
25
|
+
.ew-branch svg{width:9px;height:9px}.ew-branch[aria-expanded=false] svg{transform:rotate(-90deg)}
|
|
26
|
+
.ew-tree{border-inline-start:1px solid var(--dsw-alias-border-l2,#587062);margin:0 0 4px 2px;padding-inline-start:3px}
|
|
27
|
+
.ew-tree button::before{content:"";position:absolute;width:4px;border-top:1px solid var(--dsw-alias-border-l2,#587062);top:50%;left:-4px}
|
|
28
|
+
.ew-tree[hidden]{display:none}
|
|
29
|
+
`
|
|
30
|
+
|
|
31
|
+
export function ToolRail({mounted,activate}:{mounted:MountedSession;activate:(session:string,tool:RailTool)=>void}) {
|
|
32
|
+
const session=useSyncExternalStore(fn=>mounted.subscribe(fn),()=>mounted.getSnapshot())
|
|
33
|
+
const [expanded,setExpanded]=useState(true)
|
|
34
|
+
if(session===undefined)return null
|
|
35
|
+
function button(tool:RailTool) {
|
|
36
|
+
const {label,path}=tools[tool]
|
|
37
|
+
return <button type="button" key={tool} title={tool==='3d'?'板级 3D':label} onClick={()=>activate(session!,tool)}>
|
|
38
|
+
<svg viewBox="0 0 24 24" aria-hidden="true"><path d={path}/></svg>{label}</button>
|
|
39
|
+
}
|
|
40
|
+
return <nav className="ew-rail" aria-label="工程工具栏"><style>{railStyles}</style>
|
|
41
|
+
<button className="ew-branch" type="button" aria-expanded={expanded} onClick={()=>setExpanded(!expanded)}>
|
|
42
|
+
<svg viewBox="0 0 10 10" aria-hidden="true"><path d="m1 3 4 4 4-4"/></svg>设计</button>
|
|
43
|
+
<div className="ew-tree" role="group" aria-label="设计工具" hidden={!expanded}>{designTools.map(button)}</div>
|
|
44
|
+
{button('review')}{button('manufacture')}
|
|
45
|
+
</nav>
|
|
46
|
+
}
|