加入历史项目管理
This commit is contained in:
@@ -119,7 +119,7 @@ class Engine:
|
||||
if current_manifest and previous_manifest and current_manifest!=previous_manifest:
|
||||
with self.store.db() as db:db.execute('DELETE FROM artifacts WHERE task_id=?',(tid,))
|
||||
data={**old,**value,'simulation':self.settings.mode=='simulation'}
|
||||
self.store.save_task(data)
|
||||
if not self.store.save_task(data):return
|
||||
delivery=data.get('delivery') or {}
|
||||
for item in delivery.get('artifacts',[]):
|
||||
path=item.get('absolute_path') or item.get('path')
|
||||
@@ -139,6 +139,9 @@ class Engine:
|
||||
def public_task(self,data):
|
||||
result={k:v for k,v in data.items() if k not in {'delivery','manufacturing_package','native_job_id'}}
|
||||
if result.get('state')=='delivery_ready' and (result.get('manufacturing_blockers') or result.get('download_ready') is not True):result['state']='draft_ready'
|
||||
history=self.store.history(data['task_id'])
|
||||
if history.get('display_title'):result['title']=history['display_title']
|
||||
result['pinned']=bool(history.get('pinned'))
|
||||
result['mode']=self.settings.mode
|
||||
if data.get('delivery'):
|
||||
d=data['delivery'];result['delivery']={'manifest_sha256':d.get('manifest_sha256'),'archive_sha256':d.get('archive_sha256'),'artifacts':self.artifacts(data['task_id'])}
|
||||
|
||||
+32
-1
@@ -1,4 +1,4 @@
|
||||
import asyncio,csv,hashlib,hmac,io,json,secrets,time,uuid
|
||||
import asyncio,csv,hashlib,hmac,io,json,re,secrets,shutil,time,uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI,Request,HTTPException,UploadFile,File,Form
|
||||
@@ -96,6 +96,35 @@ def create_app(settings=None,start_workers=True):
|
||||
return {'operation_id':op['id'],'request_id':op['request_id'],'state':op['state'],'task_id':op['task_id'],'result':result,'created_at':op['created'],'updated_at':op['updated']}
|
||||
@app.get('/api/v1/tasks')
|
||||
def tasks():return {'items':[engine.public_task(t) for t in store.tasks()]}
|
||||
@app.post('/api/v1/tasks/{tid}/history')
|
||||
async def manage_history(tid:str,request:Request):
|
||||
if not re.fullmatch(r'pcb-[a-z0-9]{12,32}',tid):raise HTTPException(422,'无效设计编号')
|
||||
raw=await request.body()
|
||||
if len(raw)>4096:raise HTTPException(413,'历史操作内容过长')
|
||||
try:p=json.loads(raw)
|
||||
except ValueError:raise HTTPException(422,'无效JSON')
|
||||
if not isinstance(p,dict):raise HTTPException(422,'历史操作字段无效')
|
||||
action=p.get('action')
|
||||
allowed={'rename':{'action','title'},'pin':{'action','pinned'},'archive':{'action'}}
|
||||
if not isinstance(action,str) or action not in allowed or set(p)!=allowed[action]:raise HTTPException(422,'历史操作字段无效')
|
||||
title=p.get('title');pinned=p.get('pinned')
|
||||
if action=='rename':
|
||||
if not isinstance(title,str) or not 1<=len(title.strip())<=120:raise HTTPException(422,'名称须为1至120个字符')
|
||||
title=title.strip()
|
||||
if action=='pin' and not isinstance(pinned,bool):raise HTTPException(422,'置顶状态无效')
|
||||
def cleanup():
|
||||
parent=(settings.core_root/'tasks').resolve()
|
||||
directory=parent/tid
|
||||
if directory.is_symlink() or directory.resolve().parent!=parent:raise Conflict('设计目录不安全,无法删除')
|
||||
if directory.exists():shutil.rmtree(directory)
|
||||
try:await asyncio.to_thread(store.manage_history,tid,action,title=title,pinned=pinned,cleanup=cleanup if action=='archive' else None)
|
||||
except KeyError:raise HTTPException(404,'设计不存在或已删除')
|
||||
except Conflict as exc:raise HTTPException(409,str(exc))
|
||||
except OSError:raise HTTPException(500,'工程文件删除失败,请稍后重试')
|
||||
if action=='archive':return {'deleted':True,'task_id':tid}
|
||||
data=store.task(tid)
|
||||
if not data:raise HTTPException(404,'设计已删除')
|
||||
return engine.public_task(data)
|
||||
@app.get('/api/v1/tasks/{tid}')
|
||||
async def task(tid:str):
|
||||
data=store.task(tid)
|
||||
@@ -104,6 +133,8 @@ def create_app(settings=None,start_workers=True):
|
||||
fresh=await asyncio.to_thread(engine.provider.call,{'request_id':'status-'+uuid.uuid4().hex,'action':'status','payload':{'task_id':tid}},None,15)
|
||||
if fresh.get('task_id'):engine.update_task(fresh);data=store.task(tid)
|
||||
except Exception:pass # Keep last durable snapshot; events/operation endpoint expose failures.
|
||||
data=store.task(tid)
|
||||
if not data:raise HTTPException(404,'设计已删除')
|
||||
return engine.public_task(data)
|
||||
@app.get('/api/v1/events')
|
||||
async def events(request:Request,after:int=0,task_id:str|None=None):
|
||||
|
||||
@@ -18,6 +18,7 @@ class Store:
|
||||
db.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS operations(id TEXT PRIMARY KEY,request_id TEXT UNIQUE,body_hash TEXT,command TEXT,state TEXT,task_id TEXT,result TEXT,created REAL,updated REAL);
|
||||
CREATE TABLE IF NOT EXISTS tasks(id TEXT PRIMARY KEY,data TEXT,updated REAL);
|
||||
CREATE TABLE IF NOT EXISTS task_history(task_id TEXT PRIMARY KEY,display_title TEXT,pinned INTEGER NOT NULL DEFAULT 0,deleted INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE IF NOT EXISTS events(seq INTEGER PRIMARY KEY AUTOINCREMENT,task_id TEXT,operation_id TEXT,kind TEXT,data TEXT,created REAL);
|
||||
CREATE TABLE IF NOT EXISTS uploads(id TEXT PRIMARY KEY,path TEXT,name TEXT,kind TEXT,sha256 TEXT,size INTEGER);
|
||||
CREATE TABLE IF NOT EXISTS artifacts(id TEXT PRIMARY KEY,task_id TEXT,path TEXT,kind TEXT,sha256 TEXT,mime TEXT,simulation INTEGER,release_only INTEGER,UNIQUE(task_id,path));
|
||||
@@ -39,6 +40,8 @@ class Store:
|
||||
if row:
|
||||
if row['body_hash']!=digest:raise Conflict('同一个 request_id 的内容发生了变化')
|
||||
return dict(row),False
|
||||
tid=command.get('payload',{}).get('task_id')
|
||||
if tid and db.execute('SELECT 1 FROM task_history WHERE task_id=? AND deleted=1',(tid,)).fetchone():raise Conflict('设计已删除')
|
||||
oid='op-'+uuid.uuid4().hex
|
||||
db.execute('INSERT INTO operations VALUES(?,?,?,?,?,?,?,?,?)',(oid,command['request_id'],digest,body,'queued',task_id,None,now,now))
|
||||
return dict(db.execute('SELECT * FROM operations WHERE id=?',(oid,)).fetchone()),True
|
||||
@@ -64,12 +67,42 @@ class Store:
|
||||
row=db.execute('SELECT data FROM tasks WHERE id=?',(tid,)).fetchone();return json.loads(row['data']) if row else None
|
||||
def save_task(self,data):
|
||||
with self.db() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
if db.execute('SELECT 1 FROM task_history WHERE task_id=? AND deleted=1',(data['task_id'],)).fetchone():return False
|
||||
db.execute('INSERT INTO tasks VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data,updated=excluded.updated',(data['task_id'],dumps(data),time.time()))
|
||||
return True
|
||||
def tasks(self):
|
||||
with self.db() as db:return [json.loads(r['data']) for r in db.execute('SELECT data FROM tasks ORDER BY updated DESC LIMIT 100')]
|
||||
with self.db() as db:return [json.loads(r['data']) for r in db.execute('SELECT t.data FROM tasks t LEFT JOIN task_history h ON h.task_id=t.id WHERE COALESCE(h.deleted,0)=0 ORDER BY COALESCE(h.pinned,0) DESC,t.updated DESC LIMIT 100')]
|
||||
def event(self,tid,oid,kind,data):
|
||||
with self.db() as db:db.execute('INSERT INTO events(task_id,operation_id,kind,data,created) VALUES(?,?,?,?,?)',(tid,oid,kind,dumps(data),time.time()))
|
||||
def events(self,after=0,tid=None):
|
||||
with self.db() as db:
|
||||
rows=db.execute('SELECT * FROM events WHERE seq>? '+('AND task_id=? ' if tid else '')+'ORDER BY seq LIMIT 200',((after,tid) if tid else (after,))).fetchall()
|
||||
return [{**dict(r),'data':json.loads(r['data'])} for r in rows]
|
||||
|
||||
def history(self,tid):
|
||||
with self.db() as db:
|
||||
row=db.execute('SELECT * FROM task_history WHERE task_id=?',(tid,)).fetchone()
|
||||
return dict(row) if row else {}
|
||||
|
||||
def manage_history(self,tid,action,*,title=None,pinned=None,cleanup=None):
|
||||
with self.db() as db:
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
row=db.execute('SELECT data FROM tasks WHERE id=?',(tid,)).fetchone()
|
||||
if not row:raise KeyError(tid)
|
||||
db.execute('INSERT OR IGNORE INTO task_history(task_id) VALUES(?)',(tid,))
|
||||
if action=='rename':
|
||||
db.execute('UPDATE task_history SET display_title=? WHERE task_id=?',(title,tid))
|
||||
elif action=='pin':
|
||||
db.execute('UPDATE task_history SET pinned=? WHERE task_id=?',(int(pinned),tid))
|
||||
elif action=='archive':
|
||||
data=json.loads(row['data'])
|
||||
if data.get('state') not in {'completed','failed','cancelled','draft_ready','delivery_ready','needs_input','awaiting_selection'}:
|
||||
raise Conflict('设计正在执行,请等待完成或取消后再归档删除')
|
||||
if db.execute("SELECT 1 FROM operations WHERE task_id=? AND state IN ('queued','running')",(tid,)).fetchone():
|
||||
raise Conflict('该设计仍有操作在执行,请稍后再归档删除')
|
||||
if cleanup:cleanup()
|
||||
db.execute('UPDATE task_history SET display_title=NULL,pinned=0,deleted=1 WHERE task_id=?',(tid,))
|
||||
for table in ('tasks','operations','events','artifacts'):
|
||||
db.execute('DELETE FROM '+table+' WHERE '+('id' if table=='tasks' else 'task_id')+'=?',(tid,))
|
||||
else:raise ValueError('未知历史操作')
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""History mutations use a temporary database and never run a real design."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'api'))
|
||||
from app.config import Settings
|
||||
from app.main import create_app
|
||||
from app.store import Conflict, Store
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
class HistoryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
|
||||
self.settings=Settings(Path(self.tmp.name),Path(self.tmp.name)/'unused',mode='real')
|
||||
self.app=create_app(self.settings,start_workers=False);self.store=self.app.state.store
|
||||
self.client=TestClient(self.app);self.client.get('/api/v1/session')
|
||||
self.tid='pcb-'+'a'*20;self.other='pcb-'+'b'*20
|
||||
for tid in (self.tid,self.other):self.store.save_task({'task_id':tid,'title':'原始需求','state':'failed'})
|
||||
self.headers={'Origin':'http://127.0.0.1:5173'}
|
||||
def post(self,p,tid=None,**kw):
|
||||
return self.client.post('/api/v1/tasks/'+(tid or self.tid)+'/history',json=p,headers=kw.get('headers',self.headers))
|
||||
def test_rename_survives_snapshot_refresh_and_restart(self):
|
||||
r=self.post({'action':'rename','title':' 电源板 '});self.assertEqual(r.status_code,200);self.assertEqual(r.json()['title'],'电源板')
|
||||
self.app.state.engine.update_task({'task_id':self.tid,'state':'failed','title':'模型又返回原名'})
|
||||
self.assertEqual(self.app.state.engine.public_task(self.store.task(self.tid))['title'],'电源板')
|
||||
self.assertEqual(Store(self.settings.root).history(self.tid)['display_title'],'电源板')
|
||||
for title in (' ','x'*121,None):self.assertEqual(self.post({'action':'rename','title':title}).status_code,422)
|
||||
def test_pinned_items_sort_before_recent_tasks_and_can_be_unpinned(self):
|
||||
self.assertEqual(self.post({'action':'pin','pinned':True}).status_code,200)
|
||||
self.store.save_task({'task_id':self.other,'state':'failed','title':'更新的任务'})
|
||||
items=self.client.get('/api/v1/tasks').json()['items']
|
||||
self.assertEqual(items[0]['task_id'],self.tid);self.assertTrue(items[0]['pinned'])
|
||||
self.post({'action':'pin','pinned':False})
|
||||
self.assertEqual(self.client.get('/api/v1/tasks').json()['items'][0]['task_id'],self.other)
|
||||
self.assertEqual(self.post({'action':'pin','pinned':'yes'}).status_code,422)
|
||||
def test_archive_deletes_files_and_api_records_without_resurrection(self):
|
||||
folder=self.settings.core_root/'tasks'/self.tid;folder.mkdir(parents=True);(folder/'task.json').write_text('{}');(folder/'output.zip').write_bytes(b'data')
|
||||
self.store.event(self.tid,None,'old',{})
|
||||
op,_=self.store.enqueue({'request_id':'finished','action':'status','payload':{'task_id':self.tid}},self.tid);self.store.finish(op['id'],{'task_id':self.tid})
|
||||
self.assertEqual(self.post({'action':'archive'}).status_code,200)
|
||||
self.assertFalse(folder.exists());self.assertIsNone(self.store.task(self.tid));self.assertIsNone(self.store.operation(op['id']));self.assertEqual(self.store.events(tid=self.tid),[])
|
||||
self.app.state.engine.update_task({'task_id':self.tid,'state':'failed','title':'迟到结果'})
|
||||
self.assertIsNone(self.store.task(self.tid));self.assertEqual(self.client.get('/api/v1/tasks/'+self.tid).status_code,404)
|
||||
self.assertEqual(self.post({'action':'archive'}).status_code,404)
|
||||
with self.assertRaises(Conflict):self.store.enqueue({'request_id':'late','action':'status','payload':{'task_id':self.tid}},self.tid)
|
||||
def test_active_designs_and_pending_operations_cannot_be_deleted(self):
|
||||
self.store.save_task({'task_id':self.tid,'state':'designing'})
|
||||
self.assertEqual(self.post({'action':'archive'}).status_code,409)
|
||||
self.store.save_task({'task_id':self.tid,'state':'failed'})
|
||||
self.store.enqueue({'request_id':'pending','action':'recover','payload':{'task_id':self.tid}},self.tid)
|
||||
self.assertEqual(self.post({'action':'archive'}).status_code,409);self.assertIsNotNone(self.store.task(self.tid))
|
||||
def test_session_origin_and_path_validation(self):
|
||||
self.assertEqual(self.post({'action':'archive'},headers={}).status_code,403)
|
||||
self.assertEqual(self.post({'action':'archive'},headers={'Origin':'https://foreign.invalid'}).status_code,403)
|
||||
self.client.cookies.clear();self.assertEqual(self.post({'action':'archive'}).status_code,401)
|
||||
def test_symlink_cannot_delete_another_directory(self):
|
||||
parent=self.settings.core_root/'tasks';parent.mkdir(parents=True)
|
||||
outside=Path(self.tmp.name)/'outside';outside.mkdir();(outside/'keep').write_text('keep')
|
||||
(parent/self.tid).symlink_to(outside,target_is_directory=True)
|
||||
self.assertEqual(self.post({'action':'archive'}).status_code,409);self.assertTrue((outside/'keep').exists())
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { stateLabel, type Task } from './client.js';
|
||||
export function DesignHistory({ tasks, selected, disabled, onSelect, onManage }: {
|
||||
tasks: Task[]; selected: string | null; disabled: boolean;
|
||||
onSelect: (id: string | null) => void;
|
||||
onManage: (id: string, action: 'rename' | 'pin' | 'archive', value?: string | boolean) => Promise<boolean>;
|
||||
}) {
|
||||
const [expanded,setExpanded]=useState(false), [menu,setMenu]=useState<string|null>(null),
|
||||
[renaming,setRenaming]=useState<string|null>(null), [name,setName]=useState(''), [working,setWorking]=useState(false);
|
||||
const root=useRef<HTMLDivElement>(null), input=useRef<HTMLInputElement>(null);
|
||||
const current=tasks.find(t=>t.task_id===selected);
|
||||
useEffect(()=>{
|
||||
const outside=(e:PointerEvent)=>{if(!root.current?.contains(e.target as Node)){setExpanded(false);setMenu(null);setRenaming(null)}};
|
||||
const escape=(e:KeyboardEvent)=>{if(e.key==='Escape'){setExpanded(false);setMenu(null);setRenaming(null)}};
|
||||
document.addEventListener('pointerdown',outside);document.addEventListener('keydown',escape);
|
||||
return ()=>{document.removeEventListener('pointerdown',outside);document.removeEventListener('keydown',escape)};
|
||||
},[]);
|
||||
useEffect(()=>{if(renaming){input.current?.focus();input.current?.select()}},[renaming]);
|
||||
const manage=async(tid:string,action:'rename'|'pin'|'archive',value?:string|boolean)=>{
|
||||
if(disabled||working)return;
|
||||
setWorking(true);
|
||||
try {if(await onManage(tid,action,value)){setMenu(null);setRenaming(null)}} finally{setWorking(false)}
|
||||
};
|
||||
const sorted=[...tasks].sort((a,b)=>Number(!!b.pinned)-Number(!!a.pinned));
|
||||
return <div className="pcb-history" ref={root}>
|
||||
<span className="pcb-history-label">设计历史</span>
|
||||
<button type="button" className="pcb-history-trigger" aria-label="展开设计历史" aria-expanded={expanded} aria-controls="pcb-history-list" onClick={()=>setExpanded(v=>!v)}>
|
||||
<span>{current ? `${current.pinned?'★ ':''}${current.title || current.task_id}`:'新设计'}</span><span aria-hidden="true">{expanded?'⌃':'⌄'}</span>
|
||||
</button>
|
||||
{expanded && <div className="pcb-history-list" id="pcb-history-list" aria-label="设计历史列表">
|
||||
<button type="button" className={`pcb-history-new ${!selected?'selected':''}`} onClick={()=>{onSelect(null);setExpanded(false);setMenu(null);setRenaming(null)}}>+ 新设计</button>
|
||||
{!tasks.length && <p className="pcb-history-empty">还没有历史设计</p>}
|
||||
{sorted.map(t=><div key={t.task_id} className={`pcb-history-row ${selected===t.task_id?'selected':''}`}>
|
||||
<div className="pcb-history-row-top"><button type="button" className="pcb-history-select" title={t.title || t.task_id} onClick={()=>{onSelect(t.task_id);setExpanded(false);setMenu(null);setRenaming(null)}}>
|
||||
<span>{t.pinned && <i aria-label="已置顶">★ </i>}{t.title || t.task_id}</span><small>{stateLabel[t.state] || t.state}</small>
|
||||
</button><button type="button" className="pcb-history-more" aria-label={`管理设计:${t.title || t.task_id}`} aria-haspopup="menu" aria-expanded={menu===t.task_id} disabled={disabled||working} onClick={()=>{setMenu(menu===t.task_id?null:t.task_id);setRenaming(null)}}>•••</button></div>
|
||||
{menu===t.task_id && <div className="pcb-history-menu" role="menu" aria-label="设计操作">
|
||||
<button role="menuitem" disabled={working||disabled} onClick={()=>{setRenaming(t.task_id);setName(t.title || '')}}>重命名</button>
|
||||
<button role="menuitem" disabled={working||disabled} onClick={()=>void manage(t.task_id,'pin',!t.pinned)}>{t.pinned?'取消置顶':'置顶'}</button>
|
||||
<button role="menuitem" className="pcb-history-delete" disabled={working||disabled} title="删除此设计记录及工程成果,无法恢复" onClick={()=>void manage(t.task_id,'archive')}>归档(删除)</button>
|
||||
</div>}
|
||||
{renaming===t.task_id && <form className="pcb-history-rename" aria-label="重命名设计" onSubmit={e=>{e.preventDefault();void manage(t.task_id,'rename',name.trim())}}>
|
||||
<label>设计名称<input ref={input} aria-label="新的设计名称" maxLength={120} value={name} disabled={working} onChange={e=>setName(e.target.value)}/></label>
|
||||
<div><button type="submit" disabled={disabled||working||!name.trim()}>{working?'保存中…':'保存'}</button><button type="button" disabled={working} onClick={()=>setRenaming(null)}>取消</button></div>
|
||||
</form>}
|
||||
</div>)}
|
||||
<p className="pcb-history-hint">归档会删除设计记录及工程成果,无法恢复。</p>
|
||||
</div>}
|
||||
</div>;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
} from './client.js';
|
||||
import './pcb-service.css';
|
||||
import { ProjectVisuals } from './ProjectVisuals.js';
|
||||
import { DesignHistory } from './DesignHistory.js';
|
||||
|
||||
const ACTIVE = 'vibemake.pcb-service.active',
|
||||
PENDING = 'vibemake.pcb-service.operation';
|
||||
@@ -353,6 +354,29 @@ export function PcbServiceDock({
|
||||
setError((e as Error).message);
|
||||
}
|
||||
};
|
||||
const newDesign = () => {
|
||||
setId(null); setTask(null); setText(''); setAnswer(''); setError('');
|
||||
setAttachments([]); setPreview(null); setBom(null);
|
||||
};
|
||||
const manageHistory = async (tid: string, action: 'rename' | 'pin' | 'archive', value?: string | boolean) => {
|
||||
setSending(true); setError('');
|
||||
try {
|
||||
const payload = action === 'rename' ? {action, title: value} : action === 'pin' ? {action, pinned: value} : {action};
|
||||
const result = await request<Task | {deleted: boolean}>(`/tasks/${encodeURIComponent(tid)}/history`, {
|
||||
method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(payload),
|
||||
});
|
||||
if (action === 'archive') {
|
||||
setTasks(old=>old.filter(t=>t.task_id!==tid));
|
||||
if(idRef.current===tid) newDesign();
|
||||
} else {
|
||||
const updated=result as Task;
|
||||
setTasks(old=>old.map(t=>t.task_id===tid?updated:t));
|
||||
if(idRef.current===tid) setTask(updated);
|
||||
}
|
||||
return true;
|
||||
} catch(e) {setError((e as Error).message);return false}
|
||||
finally {setSending(false)}
|
||||
};
|
||||
const artifacts = task?.delivery?.artifacts ?? [],
|
||||
busy = sending || !!pending || !!queued;
|
||||
return createPortal(
|
||||
@@ -377,21 +401,14 @@ export function PcbServiceDock({
|
||||
<main className="pcb-flow-panel"><div className="pcb-flow-heading"><span className="pcb-eyebrow">DESIGN WORKFLOW</span><h2>PCB 生成流程</h2><p>从需求到工程,跟踪每一步设计进展。</p></div> <div className="pcb-task-picker">
|
||||
<button
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setId(null);
|
||||
setTask(null);
|
||||
setText('');
|
||||
setAnswer('');
|
||||
setError('');
|
||||
setAttachments([]);
|
||||
}}
|
||||
onClick={newDesign}
|
||||
>
|
||||
+ 新建设计
|
||||
</button>
|
||||
<button onClick={() => void refresh().catch((e) => setError(String(e)))}>
|
||||
刷新任务列表
|
||||
</button>
|
||||
<label>设计历史<select aria-label="切换设计任务" value={id || ''} onChange={(e)=>setId(e.target.value || null)}><option value="">新设计</option>{tasks.map(t=><option key={t.task_id} value={t.task_id}>{t.title || t.task_id} · {stateLabel[t.state] || t.state}</option>)}</select></label>
|
||||
<DesignHistory tasks={tasks} selected={id} disabled={busy} onSelect={(next)=>next ? setId(next) : newDesign()} onManage={manageHistory}/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
|
||||
@@ -13,6 +13,7 @@ export interface Task {
|
||||
task_id: string;
|
||||
state: string;
|
||||
title?: string;
|
||||
pinned?: boolean;
|
||||
revision?: string;
|
||||
questions?: string[];
|
||||
proposal_hash?: string;
|
||||
|
||||
@@ -288,3 +288,28 @@
|
||||
.pcb-service-preview { background: #14212b; border-color: #3b5364; }
|
||||
@media(max-width:1100px) { .pcb-service-body { grid-template-columns: 265px minmax(0,1fr); padding: 10px; gap: 10px; } .pcb-project-visuals { gap: 10px; } .pcb-panel-head { padding: 10px 12px; } .pcb-sim-controls { flex-wrap: wrap; justify-content: flex-end; } .pcb-sim-caption { flex-wrap: wrap; gap: 3px; } .pcb-preview-caption > span:last-child { display: none; } }
|
||||
@media(max-width:760px) { .pcb-service-window { inset: 0; border-radius: 0; } .pcb-service-body { display: flex; flex-direction: column; overflow: auto; } .pcb-service-body .pcb-flow-panel { flex: 0 0 auto; max-height: 48vh; padding: 15px; } .pcb-project-visuals { flex: 0 0 auto; display: flex; flex-direction: column; } .pcb-project-preview { height: 380px; } .pcb-circuit-panel { height: 340px; } .pcb-sim-toolbar { flex-wrap: wrap; gap: 7px; } .pcb-panel-head { flex-wrap: wrap; } .pcb-mini-scope { width: 125px; } }
|
||||
|
||||
/* History uses real buttons so every design can expose an actions menu. */
|
||||
.pcb-history { width: 100%; min-width: 0; }
|
||||
.pcb-history-label { display: block; font-size: 11px; color: #8da1b3; margin: 3px 0 7px; }
|
||||
.pcb-service-window .pcb-history-trigger { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 9px 10px; text-align: left; gap: 8px; background: #101c26; }
|
||||
.pcb-history-trigger > span:first-child { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
|
||||
.pcb-history-list { max-height: 310px; overflow: auto; border: 1px solid #334958; border-radius: 6px; background: #0d1821; margin-top: 6px; padding: 5px; }
|
||||
.pcb-service-window .pcb-history-new { display: block; width: 100%; text-align: left; background: transparent; border-color: transparent; padding: 9px; }
|
||||
.pcb-history-row { border-radius: 4px; margin-top: 4px; border: 1px solid transparent; }
|
||||
.pcb-history-row.selected,.pcb-history-list .selected { background: #1a343a; border-color: #365c62; }
|
||||
.pcb-history-row-top { display: flex; align-items: center; min-width: 0; }
|
||||
.pcb-service-window .pcb-history-select { flex: 1; min-width: 0; text-align: left; background: transparent; border: 0; padding: 8px; }
|
||||
.pcb-history-select > span { display: block; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: 11px; }
|
||||
.pcb-history-select i { color: #dfc080; font-style: normal; }
|
||||
.pcb-service-window .pcb-history-select small { font-size: 10px; color: #89a3b6; margin-top: 3px; }
|
||||
.pcb-service-window .pcb-history-more { flex-shrink: 0; border-color: transparent; background: transparent; padding: 7px; margin-right: 3px; font-size: 11px; letter-spacing: 1px; min-height: 32px; }
|
||||
.pcb-history-menu { display: flex; flex-wrap: wrap; gap: 5px; padding: 6px; border-top: 1px solid #29404e; }
|
||||
.pcb-service-window .pcb-history-menu button { font-size: 10px; padding: 6px 7px; flex: 1; white-space: nowrap; }
|
||||
.pcb-service-window .pcb-history-menu .pcb-history-delete { color: #f2a797; }
|
||||
.pcb-history-hint,.pcb-history-empty { color: #8299a9; font-size: 9px; padding: 4px 6px; margin: 5px 0; }
|
||||
.pcb-history-rename { padding: 7px; border-top: 1px solid #29404e; }
|
||||
.pcb-history-rename label { display: block; font-size: 10px; }
|
||||
.pcb-history-rename input { width: 100%; box-sizing: border-box; margin: 5px 0 8px; padding: 8px; color: #e1edf4; background: #08131c; border: 1px solid #416779; border-radius: 4px; font: inherit; }
|
||||
.pcb-history-rename > div { display: flex; gap: 6px; }
|
||||
.pcb-history-rename button { font-size: 10px; }
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
|
||||
import { DesignHistory } from '@ziroeda/designer/src/pcb-service/DesignHistory.js';
|
||||
afterEach(cleanup);
|
||||
const tasks=[{task_id:'pcb-a',title:'电源板',state:'failed'}, {task_id:'pcb-b',title:'传感器板',state:'completed',pinned:true}];
|
||||
it('puts pinned history first and keeps ellipsis actions separate from task selection',()=>{
|
||||
const select=vi.fn(),manage=vi.fn(async()=>true);
|
||||
render(<DesignHistory tasks={tasks} selected="pcb-a" disabled={false} onSelect={select} onManage={manage}/>);
|
||||
fireEvent.click(screen.getByLabelText('展开设计历史'));
|
||||
const list=screen.getByLabelText('设计历史列表');
|
||||
expect(list.textContent!.indexOf('传感器板')).toBeLessThan(list.textContent!.indexOf('电源板'));
|
||||
fireEvent.click(screen.getByLabelText('管理设计:电源板'));
|
||||
expect(select).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole('menuitem',{name:'置顶',exact:true}));
|
||||
expect(manage).toHaveBeenCalledWith('pcb-a','pin',true);
|
||||
});
|
||||
it('renames on submit and uses archive as deletion rather than task selection',async()=>{
|
||||
const manage=vi.fn(async()=>false),select=vi.fn();
|
||||
render(<DesignHistory tasks={tasks} selected={null} disabled={false} onSelect={select} onManage={manage}/>);
|
||||
fireEvent.click(screen.getByLabelText('展开设计历史'));fireEvent.click(screen.getByLabelText('管理设计:电源板'));
|
||||
fireEvent.click(screen.getByRole('menuitem',{name:'重命名'}));
|
||||
fireEvent.change(screen.getByLabelText('新的设计名称'),{target:{value:' 新电源板 '}});
|
||||
fireEvent.submit(screen.getByRole('form',{name:'重命名设计'}));
|
||||
expect(manage).toHaveBeenCalledWith('pcb-a','rename','新电源板');
|
||||
await vi.waitFor(()=>expect((screen.getByRole('menuitem',{name:'归档(删除)'}) as HTMLButtonElement).disabled).toBe(false));
|
||||
fireEvent.click(screen.getByRole('menuitem',{name:'归档(删除)'}));
|
||||
expect(manage).toHaveBeenCalledWith('pcb-a','archive',undefined);expect(select).not.toHaveBeenCalled();
|
||||
});
|
||||
it('closes history on Escape and selects designs with a separate button',()=>{
|
||||
const select=vi.fn();render(<DesignHistory tasks={tasks} selected={null} disabled={false} onSelect={select} onManage={async()=>true}/>);
|
||||
fireEvent.click(screen.getByLabelText('展开设计历史'));fireEvent.keyDown(document,{key:'Escape'});
|
||||
expect(screen.queryByLabelText('设计历史列表')).toBeNull();
|
||||
fireEvent.click(screen.getByLabelText('展开设计历史'));fireEvent.click(screen.getByTitle('电源板'));
|
||||
expect(select).toHaveBeenCalledWith('pcb-a');expect(screen.queryByLabelText('设计历史列表')).toBeNull();
|
||||
});
|
||||
Reference in New Issue
Block a user