feat(pcb): 프로젝트를 사용자 작업 디렉토리에 서버 저장 — workspace/pcb/<이름>/project.json(+gcode/), 이름 입력 시 자동 저장(1.5초 디바운스), 프로젝트 목록·열기·이름변경·휴지통, 다른 탭/기기 수정 충돌 감지(409), G-code 파일 폴더 저장, 시작 시 서버와 동기화
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d2334b23dd
commit
449cfeb6e2
3 files changed
+252
-9
No files matched your search
@@ -5,6 +5,9 @@ import { freeroutingStatus, runFreerouting } from '../../tools/pcb/freerouting';
|
||||
import { buildGcode } from '../../tools/pcb/gcode';
|
||||
import { findJumpers, jumperList } from '../../tools/pcb/jumpers';
|
||||
import { simulate, type SimSpec } from '../../tools/pcb/spice';
|
||||
import { getConfig, getUserWorkspace } from '../../config/config';
|
||||
import path from 'path';
|
||||
import { PcbProjects } from '../../tools/pcb/projects';
|
||||
import { jobCommand, millStatus, saveMillKey, startJob, uploadGcode } from '../../tools/pcb/octoprint';
|
||||
import { symbolGraphics, footprintsByFilter, kicadFootprint, kicadStatus, loadFpIndex, loadSymIndex, searchFootprints, searchSymbols, symbolDetail } from '../../tools/pcb/kicadlib';
|
||||
import { DEFAULT_RULES, type PcbProject, type Routed } from '../../tools/pcb/types';
|
||||
@@ -31,6 +34,38 @@ export function registerPcbRoutes(app: express.Application, requireGatewayAuth:
|
||||
res.json(freeroutingStatus());
|
||||
});
|
||||
|
||||
// ── 프로젝트 저장소(사용자 작업 디렉토리/pcb/<이름>/) ──────────────────────────
|
||||
const store = (req: express.Request) => {
|
||||
const u = getSessionUser(req);
|
||||
const ws = u?.username ? getUserWorkspace(u.username) : getConfig().getWorkspacePath();
|
||||
return new PcbProjects(path.join(ws, 'pcb'));
|
||||
};
|
||||
const fail = (res: express.Response, err: any, code = 400) => {
|
||||
if (err?.conflict) { res.status(409).json({ error: String(err.message), updated: err.conflict }); return; }
|
||||
res.status(code).json({ error: String(err?.message || err) });
|
||||
};
|
||||
app.get('/api/pcb/projects', requireGatewayAuth, (req, res) => { try { res.json({ projects: store(req).list() }); } catch (e) { fail(res, e); } });
|
||||
app.get('/api/pcb/projects/:name', requireGatewayAuth, (req, res) => {
|
||||
try { const r = store(req).load(String(req.params.name)); if (!r) { res.status(404).json({ error: '프로젝트가 없습니다.' }); return; } res.json(r); } catch (e) { fail(res, e); }
|
||||
});
|
||||
app.put('/api/pcb/projects/:name', requireGatewayAuth, (req, res) => {
|
||||
try {
|
||||
const pr = req.body?.project;
|
||||
if (!pr || typeof pr !== 'object' || !Array.isArray(pr.parts) || !pr.board) { res.status(400).json({ error: '프로젝트 데이터가 올바르지 않습니다.' }); return; }
|
||||
const base = req.body?.baseUpdated === undefined ? undefined : Number(req.body.baseUpdated);
|
||||
res.json(store(req).save(String(req.params.name), pr, base, req.body?.force === true));
|
||||
} catch (e) { fail(res, e); }
|
||||
});
|
||||
app.post('/api/pcb/projects/:name/gcode', requireGatewayAuth, (req, res) => {
|
||||
try { res.json({ saved: store(req).saveGcode(String(req.params.name), req.body?.files || {}) }); } catch (e) { fail(res, e); }
|
||||
});
|
||||
app.post('/api/pcb/projects/:name/rename', requireGatewayAuth, (req, res) => {
|
||||
try { store(req).rename(String(req.params.name), String(req.body?.to || '')); res.json({ ok: true }); } catch (e) { fail(res, e); }
|
||||
});
|
||||
app.delete('/api/pcb/projects/:name', requireGatewayAuth, (req, res) => {
|
||||
try { res.json({ trashed: store(req).trash(String(req.params.name)) }); } catch (e) { fail(res, e); }
|
||||
});
|
||||
|
||||
// ── KiCad 공식 라이브러리 ────────────────────────────────────────────────
|
||||
app.get('/api/pcb/kicad/status', requireGatewayAuth, (_req, res) => {
|
||||
const st = kicadStatus();
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// PCB 프로젝트의 서버 저장소 — 사용자 작업 디렉토리 아래 pcb/<프로젝트 이름>/
|
||||
// project.json 편집 상태(보드·부품·넷·회로도·배선 결과·시뮬/밀링 설정)
|
||||
// project.bak.json 직전 버전(5분 이상 지난 저장본만 백업 — 저장 폭주로 백업이 덮이지 않게)
|
||||
// gcode/*.nc, jumpers.txt 생성한 밀링 파일
|
||||
// 삭제는 pcb/.trash/<이름>-<시각>/ 로 옮긴다(되돌릴 수 있게).
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export const MAX_PROJECT_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
export function validName(name: string): boolean {
|
||||
const n = String(name || '');
|
||||
return n === n.trim() && n.length >= 1 && n.length <= 60 && !/[\\/:*?"<>|\x00-\x1f]/.test(n) && !n.startsWith('.') && n !== '..';
|
||||
}
|
||||
|
||||
export class PcbProjects {
|
||||
constructor(private root: string) {}
|
||||
|
||||
private dir(name: string): string {
|
||||
if (!validName(name)) throw new Error('프로젝트 이름이 올바르지 않습니다. (1~60자, / \\ : * ? " < > | 사용 불가, 점으로 시작 불가)');
|
||||
const d = path.resolve(this.root, name);
|
||||
if (path.dirname(d) !== path.resolve(this.root)) throw new Error('잘못된 경로입니다.');
|
||||
return d;
|
||||
}
|
||||
|
||||
list(): { name: string; updated: number; parts: number; nets: number; routed: boolean; gcode: boolean }[] {
|
||||
if (!fs.existsSync(this.root)) return [];
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(this.root, { withFileTypes: true })) {
|
||||
if (!e.isDirectory() || e.name.startsWith('.')) continue;
|
||||
const f = path.join(this.root, e.name, 'project.json');
|
||||
if (!fs.existsSync(f)) continue;
|
||||
let parts = 0, nets = 0, routed = false;
|
||||
try { const j = JSON.parse(fs.readFileSync(f, 'utf8')); parts = j.parts?.length || 0; nets = j.nets?.length || 0; routed = !!(j.routed && j.routed.traces?.length); } catch { /* 깨진 파일은 목록에서 0으로 */ }
|
||||
const g = path.join(this.root, e.name, 'gcode');
|
||||
out.push({ name: e.name, updated: fs.statSync(f).mtimeMs, parts, nets, routed, gcode: fs.existsSync(g) && fs.readdirSync(g).length > 0 });
|
||||
}
|
||||
return out.sort((a, b) => b.updated - a.updated);
|
||||
}
|
||||
|
||||
exists(name: string): boolean { return fs.existsSync(path.join(this.dir(name), 'project.json')); }
|
||||
|
||||
load(name: string): { project: any; updated: number } | null {
|
||||
const f = path.join(this.dir(name), 'project.json');
|
||||
if (!fs.existsSync(f)) return null;
|
||||
return { project: JSON.parse(fs.readFileSync(f, 'utf8')), updated: fs.statSync(f).mtimeMs };
|
||||
}
|
||||
|
||||
/** baseUpdated 가 주어졌는데 서버 파일이 그보다 새로우면 충돌(다른 탭/기기에서 수정됨). */
|
||||
save(name: string, project: any, baseUpdated?: number, force = false): { updated: number } {
|
||||
const d = this.dir(name), f = path.join(d, 'project.json');
|
||||
const text = JSON.stringify(project);
|
||||
if (Buffer.byteLength(text) > MAX_PROJECT_BYTES) throw new Error('프로젝트가 너무 큽니다(8MB 초과).');
|
||||
if (fs.existsSync(f)) {
|
||||
const m = fs.statSync(f).mtimeMs;
|
||||
if (!force && baseUpdated !== undefined && m > baseUpdated + 5) { const e: any = new Error('서버의 프로젝트가 다른 곳에서 수정되었습니다.'); e.conflict = m; throw e; }
|
||||
if (Date.now() - m > 5 * 60 * 1000) { try { fs.copyFileSync(f, path.join(d, 'project.bak.json')); } catch { /* 백업 실패는 저장을 막지 않음 */ } }
|
||||
}
|
||||
fs.mkdirSync(d, { recursive: true });
|
||||
const tmp = f + '.tmp';
|
||||
fs.writeFileSync(tmp, text);
|
||||
fs.renameSync(tmp, f); // 원자적 교체 — 쓰는 도중 끊겨도 기존 파일이 안 깨진다
|
||||
return { updated: fs.statSync(f).mtimeMs };
|
||||
}
|
||||
|
||||
saveGcode(name: string, files: Record<string, string>): string[] {
|
||||
const d = this.dir(name);
|
||||
if (!fs.existsSync(path.join(d, 'project.json'))) throw new Error('먼저 프로젝트를 저장하세요.');
|
||||
const g = path.join(d, 'gcode'); fs.mkdirSync(g, { recursive: true });
|
||||
const done: string[] = [];
|
||||
for (const [fn, content] of Object.entries(files)) {
|
||||
if (!/^[A-Za-z0-9_.\-]{1,60}$/.test(fn) || typeof content !== 'string' || content.length > 8_000_000) continue;
|
||||
fs.writeFileSync(path.join(g, fn), content); done.push(`gcode/${fn}`);
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
rename(from: string, to: string): void {
|
||||
const a = this.dir(from), b = this.dir(to);
|
||||
if (!fs.existsSync(a)) throw new Error('프로젝트가 없습니다.');
|
||||
if (fs.existsSync(b)) throw new Error('같은 이름의 프로젝트가 이미 있습니다.');
|
||||
fs.renameSync(a, b);
|
||||
}
|
||||
|
||||
trash(name: string): string {
|
||||
const a = this.dir(name);
|
||||
if (!fs.existsSync(a)) throw new Error('프로젝트가 없습니다.');
|
||||
const t = path.join(this.root, '.trash'); fs.mkdirSync(t, { recursive: true });
|
||||
const dest = path.join(t, `${name}-${new Date().toISOString().replace(/[-:T.Z]/g, '').slice(0, 14)}`);
|
||||
fs.renameSync(a, dest);
|
||||
return path.basename(dest);
|
||||
}
|
||||
}
|
||||
+124
-9
@@ -60,6 +60,11 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
.srow{display:grid;grid-template-columns:1fr 1fr;gap:4px;background:var(--panel2);border:1px solid var(--line);border-radius:8px;padding:6px;margin-bottom:6px}
|
||||
.srow .full{grid-column:1/3}.srow label{font-size:10.5px;color:var(--muted)}
|
||||
.pchk{display:inline-flex;align-items:center;gap:3px;margin:2px 8px 2px 0;font-size:12px}.pchk input{width:auto}
|
||||
#plistbox{display:none;position:absolute;top:46px;left:12px;z-index:60;width:400px;max-height:62vh;overflow:auto;background:var(--panel);border:1px solid var(--brand);border-radius:10px;padding:8px;box-shadow:0 8px 24px rgba(0,0,0,.35)}
|
||||
#plistbox .prow{display:flex;gap:6px;align-items:center;padding:6px 4px;border-bottom:1px solid var(--line)}
|
||||
#plistbox .prow .nm{flex:1;min-width:0;cursor:pointer}#plistbox .prow .nm b{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
#plistbox .prow .nm span{font-size:11px;color:var(--muted)}
|
||||
#pname{width:210px}
|
||||
@media (max-width:1000px){
|
||||
body{height:auto;overflow:auto}
|
||||
.wrap{display:block}
|
||||
@@ -69,9 +74,11 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="plistbox"></div>
|
||||
<header>
|
||||
<h1>🔌 PCB 제작</h1>
|
||||
<button class="btn" onclick="newProject(true)">새로 만들기</button>
|
||||
<input id="pname" placeholder="프로젝트 이름 (입력하면 서버에 자동 저장)" title="사용자 작업 폴더 pcb/<이름>/ 에 자동 저장됩니다" onchange="renameProject(this.value)"><button class="btn" onclick="toggleProjects()">📁 프로젝트</button><span id="psave" style="font-size:11.5px;color:var(--muted);max-width:340px"></span>
|
||||
<button class="btn" id="undo" onclick="undo()" title="실행 취소 (Ctrl+Z)" disabled>↶</button><button class="btn" id="redo" onclick="redo()" title="다시 실행 (Ctrl+Y)" disabled>↷</button>
|
||||
<select id="exsel" class="btn" style="width:auto" onchange="loadExample(this.value);this.value=''"><option value="">예제 ▾</option><option value="basic">기초: 핀헤더 + 저항 배선</option><option value="smps_fb">555 승압 SMPS + 전압 피드백 (5V→12.2V 정전압)</option><option value="smps">555 승압 SMPS 기초 (피드백 없음)</option></select>
|
||||
<button class="btn" onclick="saveFile()">💾 저장</button>
|
||||
@@ -203,10 +210,10 @@ details{margin-bottom:6px}summary{cursor:pointer;font-weight:700;font-size:12.5p
|
||||
const $=id=>document.getElementById(id);
|
||||
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
function authH(extra){let t='';try{t=sessionStorage.getItem('smallclaw_token')||localStorage.getItem('smallclaw_token')||'';}catch(e){}const h={...(extra||{})};if(t)h['Authorization']='Bearer '+t;return h;}
|
||||
async function api(url,body){
|
||||
const r=await fetch(url,{method:body?'POST':'GET',credentials:'include',headers:authH(body?{'Content-Type':'application/json'}:{}),body:body?JSON.stringify(body):undefined});
|
||||
async function api(url,body,method){
|
||||
const r=await fetch(url,{method:method||(body?'POST':'GET'),credentials:'include',headers:authH(body?{'Content-Type':'application/json'}:{}),body:body?JSON.stringify(body):undefined});
|
||||
const d=await r.json().catch(()=>({}));
|
||||
if(!r.ok) throw new Error(d.error||('서버 오류 '+r.status));
|
||||
if(!r.ok){const e=new Error(d.error||('서버 오류 '+r.status));e.status=r.status;e.data=d;throw e;}
|
||||
return d;
|
||||
}
|
||||
|
||||
@@ -221,8 +228,8 @@ const PREFIX={RES:'R',CAP:'C',LED:'D',DIODE:'D',DIP:'U',SOIC:'U',HDR:'J',TERM:'J
|
||||
|
||||
function newProject(ask){
|
||||
if(ask && P && P.parts.length && !confirm('현재 작업을 지우고 새로 만들까요?')) return;
|
||||
P={board:{w:50,h:35},parts:[],nets:[],fps:{},rules:{...DEF_RULES},mill:{...DEF_MILL}};
|
||||
routed=null; gres=null; sel=null; pending=null; histReset(); fitView(); syncUI(); changed(true);
|
||||
P={board:{w:50,h:35},parts:[],nets:[],fps:{},name:'',rules:{...DEF_RULES},mill:{...DEF_MILL}};
|
||||
routed=null; gres=null; sel=null; pending=null; histReset(); projDirty=false; if($('pname'))$('pname').value=''; fitView(); syncUI(); changed(true);
|
||||
}
|
||||
function loadSample(skipAsk){
|
||||
if(!skipAsk&&P&&P.parts.length&&!confirm('현재 작업을 예제로 바꿀까요?')) return;
|
||||
@@ -238,7 +245,7 @@ function pcbKey(){
|
||||
const t=JSON.stringify({b:P.board,p:P.parts.map(x=>[x.ref,x.fp,x.x,x.y,x.rot]),n:P.nets.map(n=>[n.name,n.pins]),r:[P.rules.trace,P.rules.clearance,P.rules.layers,P.rules.copper,P.rules.viaDia,P.rules.viaDrill]});
|
||||
let h=5381; for(let i=0;i<t.length;i++) h=((h<<5)+h+t.charCodeAt(i))|0; return String(h);
|
||||
}
|
||||
function save(){try{localStorage.setItem('pcb-project',JSON.stringify({...P,routed:routed||null,routedKey:routed?pcbKey():null}));}catch(e){}}
|
||||
function save(){try{localStorage.setItem('pcb-project',JSON.stringify({...P,routed:routed||null,routedKey:routed?pcbKey():null,dirty:projDirty}));}catch(e){} if(typeof serverSaveSoon==='function') serverSaveSoon();}
|
||||
function changed(keepRoute){
|
||||
if(!keepRoute){ routed=null; gres=null; $('rres').textContent=''; $('res').innerHTML=''; $('dl').innerHTML=''; }
|
||||
save(); renderNets(); updSel(); draw(); if(tab==='sch') drawSch(); if(typeof renderSim==='function') renderSim();
|
||||
@@ -515,6 +522,12 @@ async function doGcode(){
|
||||
$('res').innerHTML=`구멍 ${s.holes}개(드릴 ${s.drillSizes.join(', ')||'-'}mm) · 격리 경로 ${s.isolationLengthMm}mm · 예상 약 ${s.estMinutes}분`+gres.warnings.map(w=>`<div class="warn">⚠ ${esc(w)}</div>`).join('');
|
||||
$('dl').innerHTML=Object.keys(gres.files).map(n=>`<a href="#" onclick="dlFile('${esc(n)}');return false">⬇ ${esc(n)}</a>`).join('')+'<div class="note">순서: 격리(copper) → 드릴(공구 교체 시 M0 일시정지) → 외곽. jumpers.txt 는 조립 시 윗면에 납땜할 점퍼선 목록입니다. 가공 전 Z 영점·고정을 확인하세요.</div>';
|
||||
millPaths={};renderMill();draw();
|
||||
if(P.name&&!pconflict){
|
||||
try{ if(projDirty||!P.rev) await serverSave(false);
|
||||
const r=await api('/api/pcb/projects/'+encodeURIComponent(P.name)+'/gcode',{files:gres.files});
|
||||
$('res').insertAdjacentHTML('beforeend',`<div class="ok" style="margin-top:4px">📁 작업 폴더 pcb/${esc(P.name)}/gcode/ 에 ${r.saved.length}개 저장됨</div>`);
|
||||
}catch(e){ $('res').insertAdjacentHTML('beforeend',`<div class="warn">서버 폴더 저장 실패: ${esc(e.message)}</div>`); }
|
||||
} else if(!P.name) $('res').insertAdjacentHTML('beforeend','<div class="note">프로젝트 이름을 입력하면 이 파일들이 작업 폴더 pcb/<이름>/gcode/ 에도 저장됩니다.</div>');
|
||||
}catch(e){$('res').innerHTML=`<span class="bad">${esc(e.message)}</span>`;}
|
||||
finally{b.disabled=false;}
|
||||
}
|
||||
@@ -1233,7 +1246,7 @@ function histPush(){
|
||||
if(histBusy||!P) return; const sn=histSnap(); if(hist[hidx]===sn) return;
|
||||
hist=hist.slice(0,hidx+1); hist.push(sn); if(hist.length>100) hist.shift(); hidx=hist.length-1; updUndo();
|
||||
}
|
||||
function histReset(){hist=[];hidx=-1;}
|
||||
function histReset(){hist=[];hidx=-1;if(!srvSuppress){projDirty=false;const e=$('pname');if(e&&!(P&&P.name))e.value='';}}
|
||||
function updUndo(){const u=$('undo'),r=$('redo');if(u)u.disabled=hidx<=0;if(r)r.disabled=hidx>=hist.length-1;}
|
||||
function histRestore(){
|
||||
const o=JSON.parse(hist[hidx]); histBusy=true;
|
||||
@@ -1259,15 +1272,117 @@ function schRewire(){
|
||||
schAutoWires();
|
||||
}
|
||||
|
||||
// ───────────── 프로젝트: 사용자 작업 폴더에 서버 저장 ─────────────
|
||||
// 서버: <사용자 작업 폴더>/pcb/<이름>/project.json (+ gcode/). 이름을 정하면 편집·배선 때마다 자동 저장된다.
|
||||
// 브라우저 localStorage 는 그대로 보조 저장(오프라인·새로고침 복구)으로 둔다.
|
||||
let projDirty=false, psaveTimer=null, pconflict=false, srvSuppress=false;
|
||||
const NAME_BAD=/[\\/:*?"<>|\x00-\x1f]/;
|
||||
const okName=n=>n&&n===n.trim()&&n.length<=60&&!NAME_BAD.test(n)&&!n.startsWith('.');
|
||||
const clock=()=>new Date().toTimeString().slice(0,8);
|
||||
function setPstatus(h){const e=$('psave');if(e)e.innerHTML=h;}
|
||||
function projState(){
|
||||
if(!P) return;
|
||||
if(!P.name){ setPstatus(P.parts.length?'<span class="warn">이 브라우저에만 저장됨 — 이름을 입력하면 서버에 저장</span>':''); return; }
|
||||
if(pconflict) return;
|
||||
setPstatus(projDirty?'<span class="warn">● 저장 대기…</span>':`<span class="ok">☁ 서버에 저장됨 ${P.rev?new Date(P.rev).toTimeString().slice(0,8):''}</span>`);
|
||||
}
|
||||
function serializable(){const {fps,rev,name,...rest}=P;return {...rest,routed:routed||null,routedKey:routed?pcbKey():null};}
|
||||
function serverSaveSoon(){
|
||||
if(!P||!P.name||pconflict||srvSuppress) return;
|
||||
projDirty=true; projState(); clearTimeout(psaveTimer); psaveTimer=setTimeout(()=>serverSave(false),1500);
|
||||
}
|
||||
async function serverSave(force){
|
||||
if(!P||!P.name) return false; clearTimeout(psaveTimer);
|
||||
const name=P.name;
|
||||
try{
|
||||
setPstatus('<span class="warn">저장 중…</span>');
|
||||
const d=await api('/api/pcb/projects/'+encodeURIComponent(name),{project:serializable(),baseUpdated:force?undefined:P.rev,force:!!force},'PUT');
|
||||
if(P.name!==name) return false;
|
||||
P.rev=d.updated; projDirty=false; pconflict=false; try{localStorage.setItem('pcb-project',JSON.stringify({...P,routed:routed||null,routedKey:routed?pcbKey():null,dirty:false}));}catch(e){}
|
||||
projState(); return true;
|
||||
}catch(e){
|
||||
if(e.status===409){ pconflict=true; setPstatus('<span class="bad">⚠ 다른 곳에서 수정됨</span> <button class="btn" style="padding:1px 7px" onclick="conflictLoad()">서버 것 불러오기</button> <button class="btn" style="padding:1px 7px" onclick="conflictForce()">내 것으로 덮어쓰기</button>'); return false; }
|
||||
setPstatus(`<span class="bad">서버 저장 실패</span> (이 브라우저에는 저장됨): ${esc(e.message)}`); return false;
|
||||
}
|
||||
}
|
||||
async function conflictLoad(){pconflict=false;await openProject(P.name,true);}
|
||||
async function conflictForce(){pconflict=false;await serverSave(true);}
|
||||
|
||||
async function renameProject(v){
|
||||
v=(v||'').trim();
|
||||
if(!v){ $('pname').value=P.name||''; return; }
|
||||
if(!okName(v)){ alert('프로젝트 이름은 1~60자이며 / \\ : * ? " < > | 문자와 맨 앞의 점은 쓸 수 없습니다.'); $('pname').value=P.name||''; return; }
|
||||
if(v===P.name) return;
|
||||
let exists=false; try{exists=(await api('/api/pcb/projects')).projects.some(x=>x.name===v);}catch(e){}
|
||||
if(P.name){ // 이미 서버에 있는 프로젝트의 이름 변경
|
||||
if(exists){ alert('같은 이름의 프로젝트가 이미 있습니다.'); $('pname').value=P.name; return; }
|
||||
try{await api('/api/pcb/projects/'+encodeURIComponent(P.name)+'/rename',{to:v});P.name=v;try{localStorage.setItem('pcb-last',v);}catch(e){}projState();}
|
||||
catch(e){ if(e.status===400&&/없습니다/.test(e.message)){P.name=v;await serverSave(true);} else {alert('이름 변경 실패: '+e.message);$('pname').value=P.name;} }
|
||||
return;
|
||||
}
|
||||
if(exists&&!confirm(`'${v}' 프로젝트가 이미 있습니다. 지금 작업으로 덮어쓸까요?`)){ $('pname').value=''; return; }
|
||||
P.name=v; P.rev=undefined; try{localStorage.setItem('pcb-last',v);}catch(e){}
|
||||
await serverSave(true);
|
||||
}
|
||||
async function toggleProjects(){
|
||||
const b=$('plistbox'); if(b.style.display==='block'){b.style.display='none';return;}
|
||||
b.style.display='block'; b.innerHTML='<div class="note">불러오는 중…</div>';
|
||||
try{
|
||||
const {projects}=await api('/api/pcb/projects');
|
||||
b.innerHTML=`<div style="display:flex;gap:6px;margin-bottom:6px"><b style="flex:1">📁 내 PCB 프로젝트 (${projects.length})</b><button class="btn" onclick="newProject(true);$('plistbox').style.display='none'">+ 새 프로젝트</button><button class="btn" onclick="$('plistbox').style.display='none'">✕</button></div>`
|
||||
+(projects.map(x=>`<div class="prow"><div class="nm" onclick="openProject('${esc(x.name).replace(/'/g,''')}')"><b>${esc(x.name)}${x.name===P.name?' · 현재':''}</b><span>${new Date(x.updated).toLocaleString()} · 부품 ${x.parts} · 넷 ${x.nets}${x.routed?' · 배선됨':''}${x.gcode?' · G-code':''}</span></div><button class="btn" title="휴지통으로" onclick="deleteProject('${esc(x.name).replace(/'/g,''')}')">🗑</button></div>`).join('')||'<div class="note">아직 저장된 프로젝트가 없습니다. 이름을 입력하면 저장됩니다.</div>')
|
||||
+'<div class="note" style="margin-top:6px">저장 위치: 사용자 작업 폴더 / pcb / <이름> / project.json, gcode/</div>';
|
||||
}catch(e){b.innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
|
||||
}
|
||||
async function openProject(name,silent){
|
||||
if(!silent&&P&&P.name&&projDirty&&!confirm('저장되지 않은 변경이 있습니다. 그래도 다른 프로젝트를 열까요?')) return;
|
||||
try{const d=await api('/api/pcb/projects/'+encodeURIComponent(name)); applyProject(d.project,name,d.updated); $('plistbox').style.display='none';}
|
||||
catch(e){alert('불러오기 실패: '+e.message);}
|
||||
}
|
||||
function applyProject(pr,name,rev){
|
||||
srvSuppress=true;
|
||||
P={board:pr.board,parts:pr.parts,nets:pr.nets||[],fps:{},sch:pr.sch,sim:pr.sim,rules:{...DEF_RULES,...(pr.rules||{})},mill:{...DEF_MILL,...(pr.mill||{})},name,rev};
|
||||
routed=null; if(pr.routed&&pr.routedKey&&pr.routedKey===pcbKey()){routed=pr.routed;routedCache={key:pr.routedKey,routed};}
|
||||
gres=null;sel=null;pending=null;ssel=null;simRes=null;$('simpane').style.display='none';histReset();pconflict=false;projDirty=false;
|
||||
$('pname').value=name; try{localStorage.setItem('pcb-last',name);}catch(e){}
|
||||
registerFps(); syncUI(); fitView(); changed(true); ensureSch(); ensurePlaced(); if(tab==='sch'){schDerive();schFit();}
|
||||
srvSuppress=false; projDirty=false; projState();
|
||||
}
|
||||
async function deleteProject(name){
|
||||
if(!confirm(`'${name}' 프로젝트를 휴지통으로 옮길까요? (작업 폴더의 pcb/.trash/ 에 보관됩니다)`)) return;
|
||||
try{await api('/api/pcb/projects/'+encodeURIComponent(name),null,'DELETE'); if(P.name===name){P.name='';$('pname').value='';projDirty=false;projState();} toggleProjects();toggleProjects();}
|
||||
catch(e){alert('삭제 실패: '+e.message);}
|
||||
}
|
||||
|
||||
// 시작 시 서버 프로젝트와 맞춘다: ?p=이름 또는 마지막으로 연 프로젝트
|
||||
async function reconcileProject(saved){
|
||||
let want=''; try{want=new URLSearchParams(location.search).get('p')||''; if(!want)want=(saved&&saved.name)||'';}catch(e){}
|
||||
if(!want) return;
|
||||
try{
|
||||
const d=await api('/api/pcb/projects/'+encodeURIComponent(want));
|
||||
const localSame=saved&&saved.name===want;
|
||||
if(localSame&&saved.dirty){
|
||||
if(saved.rev===d.updated){ P.name=want; P.rev=d.updated; projDirty=true; $('pname').value=want; serverSaveSoon(); return; } // 서버는 그대로, 이 브라우저에만 반영 안 된 편집 → 올린다
|
||||
if(confirm(`'${want}' 프로젝트가 이 브라우저와 서버에서 모두 바뀌었습니다.\n확인 = 이 브라우저의 작업 유지(서버 덮어쓰기)\n취소 = 서버 버전 불러오기`)){ P.name=want; P.rev=d.updated; projDirty=true; $('pname').value=want; await serverSave(true); return; }
|
||||
}
|
||||
applyProject(d.project,want,d.updated);
|
||||
}catch(e){
|
||||
if(e.status===404&&saved&&saved.name===want){ P.name=want; P.rev=undefined; $('pname').value=want; projDirty=true; serverSaveSoon(); } // 서버에서 사라졌다면 이 브라우저 본으로 복구
|
||||
else if(saved&&saved.name===want){ P.name=want; $('pname').value=want; setPstatus('<span class="warn">서버에 연결할 수 없어 이 브라우저의 저장본을 씁니다</span>'); }
|
||||
}
|
||||
}
|
||||
|
||||
// ───────────── 시작 ─────────────
|
||||
(async function init(){
|
||||
try{FP=(await api('/api/pcb/footprints')).footprints;FPM=Object.fromEntries(FP.map(f=>[f.id,f]));}catch(e){$('lib').innerHTML=`<div class="note bad">${esc(e.message)}</div>`;}
|
||||
try{const s=await api('/api/pcb/status');$('fr').innerHTML=s.installed&&s.java?`<span class="ok">● Freerouting 준비됨</span> (Java ${esc(s.java)})`:`<span class="bad">● Freerouting 미설치</span> — scripts/install-freerouting.sh`;}catch(e){$('fr').textContent='';}
|
||||
let saved=null;try{saved=JSON.parse(localStorage.getItem('pcb-project')||'null');}catch(e){}
|
||||
if(saved&&saved.board&&saved.parts){P={board:saved.board,parts:saved.parts,nets:saved.nets||[],fps:saved.fps||{},sch:saved.sch,sim:saved.sim,rules:{...DEF_RULES,...(saved.rules||{})},mill:{...DEF_MILL,...(saved.mill||{})}};syncUI();renderNets();updSel();registerFps();if(saved.routed&&saved.routedKey&&saved.routedKey===pcbKey()){routed=saved.routed;routedCache={key:saved.routedKey,routed};}}
|
||||
if(saved&&saved.board&&saved.parts){P={board:saved.board,parts:saved.parts,nets:saved.nets||[],fps:saved.fps||{},name:saved.name||'',rev:saved.rev,sch:saved.sch,sim:saved.sim,rules:{...DEF_RULES,...(saved.rules||{})},mill:{...DEF_MILL,...(saved.mill||{})}};syncUI();renderNets();updSel();registerFps();if(saved.routed&&saved.routedKey&&saved.routedKey===pcbKey()){routed=saved.routed;routedCache={key:saved.routedKey,routed};}}
|
||||
else newProject(false);
|
||||
try{const k=await api('/api/pcb/kicad/status');$('kst').innerHTML=k.installed?`<span class="ok">● ${k.footprints.toLocaleString()} 풋프린트 · ${k.symbols.toLocaleString()} 심볼</span>`:'<span class="bad">미설치</span>';}catch(e){}
|
||||
renderLib();setMode('select');renderSim();resize();fitView();millRefresh();ensureSch();ensurePlaced();histReset();histPush();
|
||||
$('pname').value=P.name||'';projDirty=!!(saved&&saved.dirty&&saved.name===P.name);
|
||||
await reconcileProject(saved);
|
||||
renderLib();setMode('select');renderSim();resize();fitView();millRefresh();ensureSch();ensurePlaced();histReset();histPush();projState();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in new issue
Block a user