feat(workshop): .scad 파일 카드에 OpenSCAD 렌더 썸네일, 클릭하면 큰 렌더, </> 버튼으로 소스 보기

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5.5 committed 2026-10-05 21:47:32 +09:00
1 parent 71bfa19161
commit 1e75730353
2 files changed
+37 -10

No files matched your search

+12 -4
View File
@@ -20,7 +20,7 @@ import {
listDeletedProjects, restoreFromHistory, readHistory, duplicateProject, genWorkshopId,
} from './workshop-storage';
import { searchDanawa } from '../../tools/danawa';
import { renderStlPng, dropStlToFloor, convertAsciiStlToBinary } from '../../tools/stl-cad-core';
import { renderStlPng, dropStlToFloor, convertAsciiStlToBinary, runOpenscad } from '../../tools/stl-cad-core';
import { scanScadModules, unassignedParts } from './workshop-assembly';
import { renderAssemblyManual, readManifest, resolveScadPath, currentAssemblyHash, assemblyOutDir, ASSEMBLY_DIR_NAME, draftAssembly } from '../../tools/workshop-assembly-render';
import { clearHistory } from '../session';
@@ -246,7 +246,7 @@ export function registerWorkshopRoutes(
const projectId = String(req.query.projectId || '');
const relPath = String(req.query.relPath || '');
const segments = relPath.split('/').filter(Boolean);
if (!/^[a-zA-Z0-9_-]+$/.test(projectId) || !segments.length || segments.some(s => s === '..' || s === '.') || !/\.stl$/i.test(relPath)) {
if (!/^[a-zA-Z0-9_-]+$/.test(projectId) || !segments.length || segments.some(s => s === '..' || s === '.') || !/\.(stl|scad)$/i.test(relPath)) {
return res.status(400).json({ error: 'invalid' });
}
const workspace = getUserWorkspace(session.username);
@@ -255,7 +255,10 @@ export function registerWorkshopRoutes(
if (!isPathInsideDir(dir, stlPath) || !fs.existsSync(stlPath)) return res.status(404).json({ error: 'not found' });
const st = fs.statSync(stlPath);
if (st.size > 40 * 1024 * 1024) return res.status(404).json({ error: 'too large' });
const key = crypto.createHash('sha1').update(`${projectId}/${relPath}/${st.mtimeMs}/${st.size}`).digest('hex').slice(0, 24);
const isScad = /\.scad$/i.test(relPath);
// size=large → 클릭해서 여는 큰 미리보기(900px). 기본은 카드 썸네일(320px).
const px = req.query.size === 'large' ? 900 : 320;
const key = crypto.createHash('sha1').update(`${projectId}/${relPath}/${st.mtimeMs}/${st.size}/${px}`).digest('hex').slice(0, 24);
const cacheDir = path.join(workspace, '.smallclaw', 'workshop-thumbs');
const png = path.join(cacheDir, `${key}.png`);
const failMark = `${png}.fail`;
@@ -267,7 +270,12 @@ export function registerWorkshopRoutes(
fs.mkdirSync(cacheDir, { recursive: true });
const job = thumbQueue.then(async () => {
if (fs.existsSync(png)) return true;
const r = await renderStlPng(stlPath, 'iso', png, 320).catch(() => ({ ok: false as const, detail: 'exception' }));
// .scad는 STL을 거치지 않고 OpenSCAD가 바로 렌더한다(use/include는 파일 위치 기준으로 풀린다).
const r = isScad
? await runOpenscad(['-o', png, `--imgsize=${px},${px}`, '--colorscheme=Tomorrow', '--autocenter', '--viewall', stlPath], 90_000)
.then(x => (x.ok && fs.existsSync(png) && fs.statSync(png).size > 100 ? x : { ok: false as const, detail: x.ok ? 'empty' : x.detail }))
.catch(() => ({ ok: false as const, detail: 'exception' }))
: await renderStlPng(stlPath, 'iso', png, px).catch(() => ({ ok: false as const, detail: 'exception' }));
if (!r.ok) { try { fs.writeFileSync(failMark, ''); } catch { /* noop */ } return false; }
return true;
});
+25 -6
View File
@@ -108,25 +108,27 @@ function renderFiles(){
}
const STL_RE=/\.stl$/i;
const SCAD_RE=/\.scad$/i;
function stlThumbFail(img){
const sp=document.createElement('span');sp.className='rb-file-icon';sp.textContent='🔧';
const sp=document.createElement('span');sp.className='rb-file-icon';sp.textContent=img.dataset.fb||'🔧';
img.replaceWith(sp);
}
function renderFileCard(file){
const isStl=STL_RE.test(file.name);
const isGcode=/\.gcode$/i.test(file.name);
const isScad=SCAD_RE.test(file.name);
const icon=isStl?'🔧':(isGcode?'🖨️':(FILE_ICONS[file.category]||FILE_ICONS.other));
const proj=currentProject();
// STL은 서버가 OpenSCAD로 렌더한 썸네일(캐시)을 쓴다 — ASCII STL/큰 파일/렌더 실패는 404라
// onerror로 기존 🔧 아이콘으로 되돌아간다.
const thumb=file.category==='photo'
? `<img src="${escAttr(file.url)}" alt="${escAttr(file.name)}" loading="lazy">`
: (isStl&&proj)
? `<img class="stl-thumb" src="/api/workshop/thumb?projectId=${encodeURIComponent(proj.id)}&relPath=${encodeURIComponent(file.relPath)}&v=${encodeURIComponent(file.mtime||'')}" alt="" loading="lazy" onerror="stlThumbFail(this)">`
: ((isStl||isScad)&&proj)
? `<img class="stl-thumb" data-fb="${isScad?'📄':'🔧'}" src="/api/workshop/thumb?projectId=${encodeURIComponent(proj.id)}&relPath=${encodeURIComponent(file.relPath)}&v=${encodeURIComponent(file.mtime||'')}" alt="" loading="lazy" onerror="stlThumbFail(this)">`
: `<span class="rb-file-icon">${icon}</span>`;
// STL은 새탭 다운로드 대신 Three.js CAD 편집기 팝업으로 연다(작업실↔K2 CAD 플러그인 연동).
// G-code는 텍스트로 열어 봐야 알아볼 수 없다 — 슬라이서 미리보기 모드로 연다(툴패스·시간·K2 업로드). 원본은 ⬇ 링크로.
const openAttrs=isStl?`href="javascript:void(0)" onclick="openCadEditorForFile('${escJs(file.relPath)}')"`
const openAttrs=isScad?`href="javascript:void(0)" onclick="openScadPreview('${escJs(file.relPath)}')"`:isStl?`href="javascript:void(0)" onclick="openCadEditorForFile('${escJs(file.relPath)}')"`
:isGcode?`href="javascript:void(0)" onclick="openSlicerForGcode('${escJs(file.relPath)}')"`
:`href="${escAttr(file.url)}" target="_blank" rel="noopener"`;
// STL만 슬라이서로 보낼 다중선택 체크박스(09-22) — 여러 부품 STL을 한 판에 얹어 같이 슬라이싱.
@@ -134,21 +136,38 @@ function renderFileCard(file){
const selBox=isStl?`<input type="checkbox" class="rb-file-stl-sel" title="슬라이서로 보내기 선택" ${checked?'checked':''} onclick="event.stopPropagation()" onchange="toggleStlSelect('${escJs(file.relPath)}',this.checked)">`:'';
// STL 전용 도면 버튼(09-25) — OpenSCAD 3면도(외곽 치수선) 새 탭 생성.
const dlLink=isGcode?`<a class="rb-file-draw" href="${escAttr(file.url)}" download="${escAttr(file.name)}" onclick="event.stopPropagation()" title="G-code 원본 다운로드">⬇</a>`:'';
const srcBtn=isScad?`<a class="rb-file-draw" href="${escAttr(file.url)}" target="_blank" rel="noopener" onclick="event.stopPropagation()" title="소스 코드 보기">&lt;/&gt;</a>`:'';
const drawBtn=isStl?`<button class="rb-file-draw" onclick="openDrawingForFile('${escJs(file.relPath)}')" title="3면도 도면 생성">📐</button>`:'';
return `<div class="rb-file-card${checked?' stl-selected':''}" data-rel="${escAttr(file.relPath)}">
${selBox}
<button class="rb-file-del" onclick="deleteFile('${escJs(file.relPath)}')" title="삭제">✕</button>
${drawBtn}${dlLink}
${drawBtn}${dlLink}${srcBtn}
<a ${openAttrs}>
<div class="rb-file-thumb">${thumb}</div>
<div class="rb-file-info">
<div class="rb-file-name" title="${escAttr(file.name)}">${escAttr(file.name)}</div>
<div class="rb-file-size">${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}</div>
<div class="rb-file-size">${fmtFileSize(file.size)}${isStl?' · CAD 편집기에서 열기':''}${isGcode?' · 슬라이서에서 미리보기':''}${isScad?' · 렌더 미리보기':''}</div>
</div>
</a>
</div>`;
}
// .scad 클릭 — 큰 렌더 이미지를 새 탭에서 연다(렌더는 서버가 OpenSCAD로, 첫 렌더는 수 초). 소스는 </> 버튼.
async function openScadPreview(relPath){
const proj=currentProject();if(!proj)return;
const url='/api/workshop/thumb?projectId='+encodeURIComponent(proj.id)+'&relPath='+encodeURIComponent(relPath)+'&size=large';
const w=window.open('','_blank');
try{
const r=await fetch(url,{headers:authH()});
if(!r.ok)throw new Error(r.status===404?'렌더에 실패했습니다(코드 오류이거나 너무 오래 걸림). </> 버튼으로 소스를 확인하세요.':'서버 오류 '+r.status);
const blobUrl=URL.createObjectURL(await r.blob());
if(w)w.location.href=blobUrl;else window.open(blobUrl,'_blank');
}catch(e){
if(w)w.close();
alert('미리보기 실패: '+e.message);
}
}
// 작업실 프로젝트 relPath → 워크스페이스 전체 기준 상대경로. K2 CAD/슬라이서 라우트
// (/api/cad/file, /api/cad/list 등)는 findStlFiles()로 워크스페이스 전체를 훑으므로
// 이 접두어(workshop/<projectId>/)만 붙이면 작업실 파일도 그대로 잡힌다.