Compare commits
11
Commits
e67f47feb6
...
eeca3e95fb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eeca3e95fb | ||
|
|
f89e87bea4 | ||
|
|
c08af925ec | ||
|
|
931c3e4647 | ||
|
|
dfa8b43b31 | ||
|
|
74c44ba6e4 | ||
|
|
c319bad5f7 | ||
|
|
5b3ab4ad6c | ||
|
|
f6cdad8701 | ||
|
|
d4bce517a1 | ||
|
|
f6c5a2eb86 |
No files matched your search
@@ -1938,10 +1938,15 @@ async function handleChat(
|
||||
// 또 예고만 반복. deferral 넛지는 "잠시만 기다려"류만 잡고 실행형 요청은 아예 제외라 이
|
||||
// 케이스가 두 망 다 통과했다. 행동 예고로 끝났는데 이번 턴 도구 호출이 0개면 1회 넛지 —
|
||||
// 지금 실행하게 하거나, 못 하는 사정이 있으면 예고 대신 지금 말하게.
|
||||
// 2026-10-06 보강(작업실 "조립설명서 만들어줘"): 1차 넛지 후 SCAD를 읽는 도구는 불렀지만 "지금 바로
|
||||
// 수정하겠습니다. 잠시만 기다려 주세요."로 또 끝났는데, 이 가드가 "도구 0개 + 넛지 1회"라 두 번째
|
||||
// 약속은 아무 망에도 안 걸려 그대로 정지했다. 이제 넛지 2회까지, 도구를 이미 썼어도
|
||||
// 행동 예고 + "잠시만 기다려" 가 함께 있으면(좁은 조건) 잡는다.
|
||||
const shouldNudgeActionPromise =
|
||||
actionPromiseNudges < 1
|
||||
&& allToolResults.length === 0
|
||||
&& isActionPromiseNoTool(candidateText);
|
||||
actionPromiseNudges < 2
|
||||
&& (allToolResults.length === 0
|
||||
? isActionPromiseNoTool(candidateText)
|
||||
: isActionPromiseNoTool(candidateText) && isDeferralPromiseReply(candidateText));
|
||||
if (shouldNudgeActionPromise) {
|
||||
actionPromiseNudges++;
|
||||
console.log(`[v2] ACTION-PROMISE POST-CHECK: promised an action ("...${candidateText.slice(-70).trim()}") but made 0 tool calls this turn. Nudging once...`);
|
||||
|
||||
@@ -551,7 +551,7 @@ export function isActionPromiseNoTool(text: string): boolean {
|
||||
if (!s || s.length > 800) return false;
|
||||
const tail = s.slice(-220);
|
||||
return (
|
||||
/(검색|찾|조사|다운로드|받아|불러|만들|생성|저장|정리|수집|모으|확인|시작|진행|시도|실행)[가-힣\s]{0,5}겠(습니다|다)|시작합니다|(?:let\s+me|i'?ll|i\s+will)\s+(?:search|find|check|look|download|fetch|grab|read|create|make|try)\b/i.test(tail)
|
||||
/(검색|찾|조사|다운로드|받아|불러|만들|생성|저장|정리|수집|모으|확인|시작|진행|시도|실행|수정|추가|변경|고치|작성|적용|바꾸|렌더|출력)[가-힣\s]{0,5}겠(습니다|다)|시작합니다|(?:let\s+me|i'?ll|i\s+will)\s+(?:search|find|check|look|download|fetch|grab|read|create|make|try)\b/i.test(tail)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -59,7 +59,9 @@ export function registerDentalJournalRoutes(app: express.Application, requireGat
|
||||
// journal=all | joe | joe,jad,jerd (쉼표로 여러 저널 동시 선택)
|
||||
const jid = String(req.query.journal || 'all');
|
||||
const ids = jid.split(',').map(x => x.trim()).filter(Boolean);
|
||||
const wholePubmed = ids.includes(PUBMED_ALL.id);
|
||||
// raw=1: PubMed 직접 검색 — 번역·단어 완화·저널 제한 없이 입력한 검색식을 그대로 PubMed에 보낸다.
|
||||
const raw = req.query.raw === '1';
|
||||
const wholePubmed = raw || ids.includes(PUBMED_ALL.id);
|
||||
const picked = ids.includes('all') ? DENTAL_JOURNALS : DENTAL_JOURNALS.filter(j => ids.includes(j.id));
|
||||
if (!picked.length && !wholePubmed) { res.status(400).json({ error: 'unknown journal' }); return; }
|
||||
|
||||
@@ -70,13 +72,11 @@ export function registerDentalJournalRoutes(app: express.Application, requireGat
|
||||
const y = Number(req.query.min_year);
|
||||
if (!Number.isInteger(y) || y < 1800 || y > 2100) { res.status(400).json({ error: '연도는 1800~2100 사이의 숫자여야 합니다.' }); return; }
|
||||
}
|
||||
const q = rawQ ? await toPaperSearchQuery(rawQ) : '';
|
||||
let q = raw ? rawQ : rawQ ? await toPaperSearchQuery(rawQ) : '';
|
||||
// 결과 내 검색(서브 검색): sub를 여러 번 받아 메인 검색어에 AND로 누적한다. 서버에서 걸러서
|
||||
// 화면에 로드된 20건만이 아니라 전체 결과 집합이 좁혀진다.
|
||||
const rawSubs = ([] as any[]).concat(req.query.sub ?? []).map(x => String(x).trim()).filter(Boolean).slice(0, 8);
|
||||
const subs = await Promise.all(rawSubs.map(x => toPaperSearchQuery(x)));
|
||||
const parts = [q, ...subs].filter(Boolean);
|
||||
const queryText = parts.map(x => `(${x})`).join(' AND ');
|
||||
const subs = await Promise.all(rawSubs.map(x => raw ? x : toPaperSearchQuery(x)));
|
||||
const typeIds = String(req.query.types || '').split(',').map(x => x.trim()).filter(Boolean);
|
||||
const pickedTypes = PAPER_TYPES.filter(t => typeIds.includes(t.id));
|
||||
if (typeIds.length && pickedTypes.length !== new Set(typeIds).size) { res.status(400).json({ error: `알 수 없는 논문 종류: ${typeIds.filter(x => !PAPER_TYPES.some(t => t.id === x)).join(', ')}` }); return; }
|
||||
@@ -84,9 +84,13 @@ export function registerDentalJournalRoutes(app: express.Application, requireGat
|
||||
const journalClause = '(' + picked.map(j => `"${j.ta}"[ta]`).join(' OR ') + ')';
|
||||
// 사용자가 쓴 PubMed 문법(AND/OR 등)이 우선순위를 망치지 않도록 괄호로 감싼다.
|
||||
// PubMed 전체가 켜져 있으면 저널 조건을 걸지 않는다(저널 논문도 모두 포함되는 상위 집합).
|
||||
const base = wholePubmed ? queryText : (queryText ? `${queryText} AND ${journalClause}` : journalClause);
|
||||
// 논문 종류는 저널·검색어 조건에 AND로 덧붙인다(종류만 골라도 선택한 저널의 해당 종류 논문이 나온다).
|
||||
const term = typeClause ? (base ? `${base} AND ${typeClause}` : typeClause) : base;
|
||||
const buildTerm = (mainQ: string): { queryText: string; term: string } => {
|
||||
const queryText = [mainQ, ...subs].filter(Boolean).map(x => `(${x})`).join(' AND ');
|
||||
const base = wholePubmed ? queryText : (queryText ? `${queryText} AND ${journalClause}` : journalClause);
|
||||
return { queryText, term: typeClause ? (base ? `${base} AND ${typeClause}` : typeClause) : base };
|
||||
};
|
||||
let { queryText, term } = buildTerm(q);
|
||||
if (!term || (wholePubmed && !queryText)) { res.status(400).json({ error: 'PubMed 전체 검색은 검색어가 필요합니다.' }); return; }
|
||||
|
||||
const maxResults = Math.min(Math.max(Number(req.query.max) || 20, 1), 50);
|
||||
@@ -96,11 +100,26 @@ export function registerDentalJournalRoutes(app: express.Application, requireGat
|
||||
const sort = req.query.sort === 'date' || !queryText ? 'date' : 'relevance';
|
||||
|
||||
const { pubmedSearchTool } = await import('../../tools/pubmed.js');
|
||||
const r = await pubmedSearchTool.execute({ query: term, max_results: maxResults, sort, min_year: minYear, offset });
|
||||
let r = await pubmedSearchTool.execute({ query: term, max_results: maxResults, sort, min_year: minYear, offset });
|
||||
if (!r.success) { res.status(502).json({ error: r.error || 'search failed' }); return; }
|
||||
// 번역된 키워드는 PubMed가 전부 AND로 묶어서, 저널·연도·종류 필터와 겹치면 0건이 되기 쉽다.
|
||||
// 첫 페이지가 0건이면 뒤쪽(덜 중요한) 단어부터 하나씩 빼며 재시도하고, 완화했다는 사실을 알린다.
|
||||
// 사용자가 직접 쓴 PubMed 문법(따옴표·[태그]·AND/OR)은 의도가 명확하므로 건드리지 않는다.
|
||||
let relaxedFrom: string | null = null;
|
||||
if (!raw && offset === 0 && !(r.data?.total_count) && q && !/[[\]"()]|\b(AND|OR|NOT)\b/.test(q)) {
|
||||
const words = q.split(/\s+/);
|
||||
for (let n = words.length - 1; n >= 1 && words.length > 1; n--) {
|
||||
const tryQ = words.slice(0, n).join(' ');
|
||||
const t = buildTerm(tryQ);
|
||||
const rr = await pubmedSearchTool.execute({ query: t.term, max_results: maxResults, sort, min_year: minYear, offset });
|
||||
if (rr.success && rr.data?.total_count) { relaxedFrom = q; q = tryQ; queryText = t.queryText; term = t.term; r = rr; break; }
|
||||
}
|
||||
}
|
||||
res.json({
|
||||
query_used: q || null,
|
||||
translated: !!q && q !== rawQ,
|
||||
relaxed_from: relaxedFrom,
|
||||
raw,
|
||||
subs_used: subs,
|
||||
// 모델 채팅이 앱과 똑같은 결과를 pubmed_search로 재현·페이징할 수 있도록 실제 검색식을 돌려준다.
|
||||
term, sort, min_year: minYear ?? null, types: pickedTypes.map(t => t.id),
|
||||
|
||||
@@ -510,6 +510,10 @@ describe('도달률 감사 회귀 (2026-09-04)', () => {
|
||||
// 도구 0개로 턴 종료. deferral 넛지가 "잠시만 기다려"류만 잡고 실행형 요청은 제외라 두 망 다
|
||||
// 통과한 케이스. 아래 실측 문구는 로그에서 그대로 가져왔다.
|
||||
describe('isActionPromiseNoTool — 행동 예고 후 도구 0개 턴', () => {
|
||||
test('10-06 실측: 수정 예고 + 잠시만 기다려(조립설명서)', () => {
|
||||
assert.equal(isActionPromiseNoTool('지금 바로 소스 코드를 수정하겠습니다. 잠시만 기다려 주세요.'), true);
|
||||
assert.equal(isActionPromiseNoTool('결과는 다음과 같습니다. 문제 없습니다.'), false);
|
||||
});
|
||||
test('오늘 실측 문구들', () => {
|
||||
assert.equal(isActionPromiseNoTool(
|
||||
'죄송합니다. 말만 하고 실제 행동(도구 호출)을 하지 않았습니다. 바로 LanderPi의 오픈소스 자료(URDF, ROS2 패키지, 설계 파일 등)를 검색해서 프로젝트 폴더에 채워 넣겠습니다.\n\n먼저 GitHub 등에서 관련 리포지토리를 찾겠습니다.',
|
||||
|
||||
@@ -306,3 +306,13 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
|
||||
.rb-console-warn{font-size:11px;color:#f59e0b;margin-bottom:6px;}
|
||||
#console-term{height:min(62vh,640px);min-height:320px;background:#0d1117;border:1px solid var(--line);border-radius:8px;padding:6px;overflow:hidden;}
|
||||
|
||||
|
||||
/* 부품 폴더식 묶음 — 이름 앞 [태그] 기준 */
|
||||
.rb-pgroup-hdr{display:flex;align-items:center;gap:8px;padding:8px 4px;margin:10px 0 6px;border-bottom:1px solid var(--line);cursor:pointer;user-select:none;font-size:13px;font-weight:700;}
|
||||
.rb-pgroup-hdr:first-child{margin-top:0;}
|
||||
.rb-pgroup-hdr:hover{color:#f59e0b;}
|
||||
.rb-pg-chev{font-size:10px;color:var(--muted);width:12px;flex-shrink:0;}
|
||||
.rb-pg-cnt{font-size:11px;font-weight:400;color:var(--muted);}
|
||||
.rb-pg-sum{margin-left:auto;font-size:12px;font-weight:600;color:var(--muted);white-space:nowrap;}
|
||||
.rb-ptable tr.rb-pgroup-row td{padding:0;border-bottom:none;}
|
||||
.rb-ptable tr.rb-pgroup-row .rb-pgroup-hdr{margin:10px 0 2px;}
|
||||
@@ -450,26 +450,36 @@ function renderMd(text){
|
||||
.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
|
||||
.replace(/\*(.+?)\*/g,'<em>$1</em>')
|
||||
.replace(/^#{1,3}\s+(.+)$/gm,'<h3>$1</h3>')
|
||||
.replace(/^\|(.+)\|$/gm,row=>{
|
||||
const cells=row.slice(1,-1).split('|').map(c=>`<td>${c.trim()}</td>`).join('');
|
||||
return `<tr>${cells}</tr>`;
|
||||
})
|
||||
.replace(/(<tr>.*?<\/tr>)/gs, tbl=>{
|
||||
const rows=tbl.match(/<tr>.*?<\/tr>/gs)||[];
|
||||
if(!rows.length)return tbl;
|
||||
const header=rows[0].replace(/<td>/g,'<th>').replace(/<\/td>/g,'</th>');
|
||||
const body=rows.slice(2).join('');
|
||||
return `<table><thead>${header}</thead><tbody>${body}</tbody></table>`;
|
||||
})
|
||||
.split(/(<pre>[\s\S]*?<\/pre>)/).map((seg,i)=>i%2?seg:mdTables(seg)).join('')
|
||||
.replace(/^-{3,}$/gm,'<hr>')
|
||||
.replace(/\n\n/g,'</p><p>').replace(/^/,'<p>').replace(/$/,'</p>')
|
||||
.replace(/<p><\/p>/g,'')
|
||||
.replace(/<p>(<h3>)/g,'$1').replace(/(<\/h3>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<pre>)/g,'$1').replace(/(<\/pre>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<table>)/g,'$1').replace(/(<\/table>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<div style="overflow-x:auto">)/g,'$1').replace(/(<\/table><\/div>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<hr>)/g,'$1').replace(/(<hr>)<\/p>/g,'$1');
|
||||
}
|
||||
|
||||
// 마크다운 표: '|'로 시작하는 연속 줄 + 두 번째 줄이 구분선(|---|---|)인 블록만 <table>로 바꾼다.
|
||||
// 입력은 이미 HTML 이스케이프된 상태. 셀 안의 `코드`·**굵게**는 이후 인라인 변환이 처리한다.
|
||||
function mdTables(text){
|
||||
const cells=l=>l.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>c.trim());
|
||||
const isSep=l=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)&&l.includes('-')&&/\|/.test(l);
|
||||
const lines=text.split('\n'),out=[];
|
||||
for(let i=0;i<lines.length;){
|
||||
if(/^\s*\|/.test(lines[i])&&i+1<lines.length&&isSep(lines[i+1])){
|
||||
const head=cells(lines[i]),al=cells(lines[i+1]).map(c=>/^:-+:$/.test(c)?'center':/-:$/.test(c)?'right':'');
|
||||
let j=i+2;const rows=[];
|
||||
while(j<lines.length&&/^\s*\|/.test(lines[j])){rows.push(cells(lines[j]));j++;}
|
||||
const td=(t,c,k)=>`<${t}${al[k]?` style="text-align:${al[k]}"`:''}>${c}</${t}>`;
|
||||
out.push('<div style="overflow-x:auto"><table><thead><tr>'+head.map((c,k)=>td('th',c,k)).join('')+'</tr></thead><tbody>'+
|
||||
rows.map(r=>'<tr>'+head.map((_,k)=>td('td',r[k]??'',k)).join('')+'</tr>').join('')+'</tbody></table></div>');
|
||||
i=j;
|
||||
}else out.push(lines[i++]);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
async function sendMessage(){
|
||||
const input=document.getElementById('chat-input');
|
||||
const msg=input.value.trim();
|
||||
|
||||
@@ -117,6 +117,7 @@ button:disabled{opacity:.5;cursor:default}
|
||||
<div class="row">
|
||||
<input id="q" placeholder="검색어 (한국어도 OK, 비우면 선택한 저널의 최신 논문)" onkeydown="if(event.key==='Enter')newSearch()">
|
||||
<input id="yr" type="number" placeholder="연도~" min="1990" max="2100">
|
||||
<label title="번역·저널 제한 없이 입력한 PubMed 검색식을 그대로 실행 (예: "root canal"[tiab] AND irrigation, 저자 Kim[au])" style="display:flex;align-items:center;gap:4px;font-size:13px;color:var(--muted)"><input type="checkbox" id="raw" onchange="try{localStorage.setItem('dj-raw',this.checked?'1':'0')}catch(e){}"> 🔬 PubMed 직접</label>
|
||||
<select id="sort"><option value="relevance">관련도순</option><option value="date">최신순</option></select>
|
||||
<button class="go" id="sbtn" onclick="newSearch()">🔍 검색</button>
|
||||
</div>
|
||||
@@ -218,6 +219,7 @@ async function init(){
|
||||
try{ localStorage.setItem('dj-known',JSON.stringify(ids)); }catch(e){}
|
||||
if(Array.isArray(saved)) saveSel();
|
||||
try{ const t=JSON.parse(localStorage.getItem('dj-types')||'[]'); if(Array.isArray(t)) tsel=new Set(t.filter(x=>ptypes.some(p=>p.id===x))); }catch(e){}
|
||||
try{ $('raw').checked=localStorage.getItem('dj-raw')==='1'; }catch(e){}
|
||||
loadState();
|
||||
renderChips(); renderTypes();
|
||||
doSearch(true);
|
||||
@@ -262,13 +264,15 @@ function renderSubs(){
|
||||
async function doSearch(reset){
|
||||
if(reset){ offset=0; total=0; shown=[]; $('results').innerHTML=''; $('more').style.display='none'; clsClearFilter(); if(typeof clsRefreshCounts==='function') clsRefreshCounts(); }
|
||||
saveState();
|
||||
if(!sel.size){ $('status').textContent='검색할 저널을 하나 이상 켜 주세요.'; return; }
|
||||
if(sel.has('pubmed') && !baseQ && !subs.length){ $('status').textContent='PubMed 전체는 검색어가 필요합니다. 검색어를 입력하거나 PubMed 카드를 꺼 주세요.'; return; }
|
||||
if(!sel.size && !$('raw').checked){ $('status').textContent='검색할 저널을 하나 이상 켜 주세요.'; return; }
|
||||
if($('raw').checked && !baseQ && !subs.length){ $('status').textContent='PubMed 직접 검색은 검색식이 필요합니다.'; return; }
|
||||
if(!$('raw').checked && sel.has('pubmed') && !baseQ && !subs.length){ $('status').textContent='PubMed 전체는 검색어가 필요합니다. 검색어를 입력하거나 PubMed 카드를 꺼 주세요.'; return; }
|
||||
if(busy){ if(reset) pending=true; return; } busy=true;
|
||||
$('sbtn').disabled=true; $('more').style.display='none';
|
||||
$('status').textContent='검색 중…';
|
||||
try{
|
||||
const p=new URLSearchParams({journal:[...sel].join(','),q:baseQ,sort:$('sort').value,offset,max:20});
|
||||
if($('raw').checked) p.set('raw','1');
|
||||
subs.forEach(x=>p.append('sub',x));
|
||||
if(tsel.size) p.set('types',[...tsel].join(','));
|
||||
if($('yr').value){ const y=Number($('yr').value); if(!Number.isInteger(y)||y<1800||y>2100) throw new Error('연도는 1800~2100 사이의 숫자여야 합니다.'); p.set('min_year',y); }
|
||||
@@ -278,10 +282,12 @@ async function doSearch(reset){
|
||||
total=d.total; offset+=d.results.length; shown.push(...d.results); lastInfo={q:baseQ,qEn:d.query_used,subs:[...subs],sources:[...sel],total,term:d.term,sort:d.sort,minYear:d.min_year,types:(d.types||[]).map(id=>(ptypes.find(t=>t.id===id)||{}).label||id)};
|
||||
$('results').insertAdjacentHTML('beforeend',d.results.map(card).join(''));
|
||||
let s=`${total.toLocaleString()}건 중 ${offset}건 표시`;
|
||||
if(sel.has('pubmed')) s+=' · PubMed 전체 포함(치과 외 논문 섞임, 저널 카드 무관)';
|
||||
if(d.raw) s+=' · 🔬 PubMed 직접 검색(저널 제한·번역 없음)';
|
||||
else if(sel.has('pubmed')) s+=' · PubMed 전체 포함(치과 외 논문 섞임, 저널 카드 무관)';
|
||||
if(subs.length) s+=` · 좁힘: ${subs.join(' + ')}`;
|
||||
if(tsel.size) s+=` · 종류: ${ptypes.filter(t=>tsel.has(t.id)).map(t=>t.label).join(' / ')}`;
|
||||
if(d.translated) s+=` · 검색어 변환: “${d.query_used}”`;
|
||||
if(d.relaxed_from) s+=` · ⚠️ “${d.relaxed_from}”는 0건이라 단어를 줄여 “${d.query_used}”로 검색`;
|
||||
if(!d.results.length && reset) s='결과 없음';
|
||||
$('status').textContent=s;
|
||||
$('more').style.display=offset<total?'block':'none';
|
||||
|
||||
@@ -2018,6 +2018,7 @@ function renderMd(text){
|
||||
return text
|
||||
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
||||
.replace(/```[\w]*\n?([\s\S]*?)```/g,'<pre><code>$1</code></pre>')
|
||||
.split(/(<pre>[\s\S]*?<\/pre>)/).map((seg,i)=>i%2?seg:mdTables(seg)).join('')
|
||||
.replace(/`([^`]+)`/g,'<code>$1</code>')
|
||||
.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
|
||||
.replace(/\*(.+?)\*/g,'<em>$1</em>')
|
||||
@@ -2026,7 +2027,27 @@ function renderMd(text){
|
||||
.replace(/^[-*]\s+(.+)$/gm,'<li>$1</li>')
|
||||
.replace(/(<li>[\s\S]+?<\/li>)/g,m=>`<ul style="padding-left:16px;margin:3px 0">${m}</ul>`)
|
||||
.replace(/\n\n/g,'</p><p>').replace(/^/,'<p>').replace(/$/,'</p>')
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<[hup])/g,'$1').replace(/(<\/[hup][^>]*>)<\/p>/g,'$1');
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<[hup]|<div style="overflow-x:auto">)/g,'$1').replace(/(<\/[hup][^>]*>|<\/table><\/div>)<\/p>/g,'$1');
|
||||
}
|
||||
|
||||
// 마크다운 표: '|'로 시작하는 연속 줄 + 두 번째 줄이 구분선(|---|---|)인 블록만 <table>로 바꾼다.
|
||||
// 입력은 이미 HTML 이스케이프된 상태. 셀 안의 `코드`·**굵게**는 이후 인라인 변환이 처리한다.
|
||||
function mdTables(text){
|
||||
const cells=l=>l.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>c.trim());
|
||||
const isSep=l=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)&&l.includes('-')&&/\|/.test(l);
|
||||
const lines=text.split('\n'),out=[];
|
||||
for(let i=0;i<lines.length;){
|
||||
if(/^\s*\|/.test(lines[i])&&i+1<lines.length&&isSep(lines[i+1])){
|
||||
const head=cells(lines[i]),al=cells(lines[i+1]).map(c=>/^:-+:$/.test(c)?'center':/-:$/.test(c)?'right':'');
|
||||
let j=i+2;const rows=[];
|
||||
while(j<lines.length&&/^\s*\|/.test(lines[j])){rows.push(cells(lines[j]));j++;}
|
||||
const td=(t,c,k)=>`<${t}${al[k]?` style="text-align:${al[k]}"`:''}>${c}</${t}>`;
|
||||
out.push('<div style="overflow-x:auto"><table><thead><tr>'+head.map((c,k)=>td('th',c,k)).join('')+'</tr></thead><tbody>'+
|
||||
rows.map(r=>'<tr>'+head.map((_,k)=>td('td',r[k]??'',k)).join('')+'</tr>').join('')+'</tbody></table></div>');
|
||||
i=j;
|
||||
}else out.push(lines[i++]);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
async function sendMessage(){
|
||||
|
||||
@@ -1389,6 +1389,7 @@ function renderMd(text){
|
||||
return text
|
||||
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
||||
.replace(/```[\w]*\n?([\s\S]*?)```/g,'<pre><code>$1</code></pre>')
|
||||
.split(/(<pre>[\s\S]*?<\/pre>)/).map((seg,i)=>i%2?seg:mdTables(seg)).join('')
|
||||
.replace(/`([^`]+)`/g,'<code>$1</code>')
|
||||
.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
|
||||
.replace(/\*(.+?)\*/g,'<em>$1</em>')
|
||||
@@ -1397,7 +1398,27 @@ function renderMd(text){
|
||||
.replace(/^[-*]\s+(.+)$/gm,'<li>$1</li>')
|
||||
.replace(/(<li>[\s\S]+?<\/li>)/g,m=>`<ul style="padding-left:16px;margin:3px 0">${m}</ul>`)
|
||||
.replace(/\n\n/g,'</p><p>').replace(/^/,'<p>').replace(/$/,'</p>')
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<[hup])/g,'$1').replace(/(<\/[hup][^>]*>)<\/p>/g,'$1');
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<[hup]|<div style="overflow-x:auto">)/g,'$1').replace(/(<\/[hup][^>]*>|<\/table><\/div>)<\/p>/g,'$1');
|
||||
}
|
||||
|
||||
// 마크다운 표: '|'로 시작하는 연속 줄 + 두 번째 줄이 구분선(|---|---|)인 블록만 <table>로 바꾼다.
|
||||
// 입력은 이미 HTML 이스케이프된 상태. 셀 안의 `코드`·**굵게**는 이후 인라인 변환이 처리한다.
|
||||
function mdTables(text){
|
||||
const cells=l=>l.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>c.trim());
|
||||
const isSep=l=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)&&l.includes('-')&&/\|/.test(l);
|
||||
const lines=text.split('\n'),out=[];
|
||||
for(let i=0;i<lines.length;){
|
||||
if(/^\s*\|/.test(lines[i])&&i+1<lines.length&&isSep(lines[i+1])){
|
||||
const head=cells(lines[i]),al=cells(lines[i+1]).map(c=>/^:-+:$/.test(c)?'center':/-:$/.test(c)?'right':'');
|
||||
let j=i+2;const rows=[];
|
||||
while(j<lines.length&&/^\s*\|/.test(lines[j])){rows.push(cells(lines[j]));j++;}
|
||||
const td=(t,c,k)=>`<${t}${al[k]?` style="text-align:${al[k]}"`:''}>${c}</${t}>`;
|
||||
out.push('<div style="overflow-x:auto"><table><thead><tr>'+head.map((c,k)=>td('th',c,k)).join('')+'</tr></thead><tbody>'+
|
||||
rows.map(r=>'<tr>'+head.map((_,k)=>td('td',r[k]??'',k)).join('')+'</tr>').join('')+'</tbody></table></div>');
|
||||
i=j;
|
||||
}else out.push(lines[i++]);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
// 사용자 메시지 HTML — 카메라 프레임 마크다운()은 썸네일로, 나머지는 이스케이프 텍스트로.
|
||||
|
||||
@@ -705,31 +705,8 @@ function addMsg(role,html){
|
||||
return b;
|
||||
}
|
||||
|
||||
function renderMd(text){
|
||||
// First extract chart blocks to replace with links
|
||||
let out=text;
|
||||
// Replace kstock blocks with a clickable chip
|
||||
out=out.replace(/```kstock\s*\n([^`]+)\n```/g,(m,body)=>{
|
||||
const parts=body.trim().split('|');const code=parts[0].trim().replace(/\D/g,'');const period=(parts[1]||'day').trim();
|
||||
if(!code)return m;
|
||||
return `<span class="iv-chart-link" onclick="loadKStock('${code}','${code}','${period}')">📈 ${code} ${period} 차트 보기</span>`;
|
||||
});
|
||||
// Replace tradingview blocks with a clickable chip
|
||||
out=out.replace(/```tradingview\s*\n([^`]+)\n```/g,(m,body)=>{
|
||||
const parts=body.trim().split('|');const sym=parts[0].trim().toUpperCase();const iv=(parts[1]||'D').trim();
|
||||
if(!sym)return m;
|
||||
return `<span class="iv-chart-link" onclick="loadTV('${sym}','${iv}','${sym}')">📈 ${sym} 차트 보기</span>`;
|
||||
});
|
||||
return out
|
||||
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
||||
// restore already-HTML chart links before further escaping
|
||||
.replace(/<span class="iv-chart-link"([^&]*)>(.*?)<\/span>/g,(m)=>{
|
||||
// this won't work — need to do escaping AFTER substitution
|
||||
return m;
|
||||
})
|
||||
// Actually process differently below
|
||||
;
|
||||
}
|
||||
// 대화 기록 복원용 — 실시간 응답과 같은 렌더러를 쓴다(예전 구현은 이스케이프만 하고 끝나 마크다운이 안 먹었다).
|
||||
function renderMd(text){ return renderMdSafe(text); }
|
||||
|
||||
function renderMdSafe(text){
|
||||
// Do chart block substitution BEFORE HTML escaping
|
||||
@@ -753,6 +730,7 @@ function renderMdSafe(text){
|
||||
out=out
|
||||
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
||||
.replace(/```[\w]*\n?([\s\S]*?)```/g,'<pre><code>$1</code></pre>')
|
||||
.split(/(<pre>[\s\S]*?<\/pre>)/).map((seg,i)=>i%2?seg:mdTables(seg)).join('')
|
||||
.replace(/`([^`]+)`/g,'<code>$1</code>')
|
||||
.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
|
||||
.replace(/\*(.+?)\*/g,'<em>$1</em>')
|
||||
@@ -762,12 +740,33 @@ function renderMdSafe(text){
|
||||
.replace(/\n\n/g,'</p><p>').replace(/^/,'<p>').replace(/$/,'</p>')
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<h3>)/g,'$1').replace(/(<\/h3>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<pre>)/g,'$1').replace(/(<\/pre>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<ul>)/g,'$1').replace(/(<\/ul>)<\/p>/g,'$1');
|
||||
.replace(/<p>(<ul>)/g,'$1').replace(/(<\/ul>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<div style="overflow-x:auto">)/g,'$1').replace(/(<\/table><\/div>)<\/p>/g,'$1');
|
||||
// Restore chart placeholders
|
||||
charts.forEach((html,i)=>{out=out.replace(new RegExp(`\x00CHART${i}\x00`,'g'),html);});
|
||||
return out;
|
||||
}
|
||||
|
||||
// 마크다운 표: '|'로 시작하는 연속 줄 + 두 번째 줄이 구분선(|---|---|)인 블록만 <table>로 바꾼다.
|
||||
// 입력은 이미 HTML 이스케이프된 상태. 셀 안의 `코드`·**굵게**는 이후 인라인 변환이 처리한다.
|
||||
function mdTables(text){
|
||||
const cells=l=>l.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>c.trim());
|
||||
const isSep=l=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)&&l.includes('-')&&/\|/.test(l);
|
||||
const lines=text.split('\n'),out=[];
|
||||
for(let i=0;i<lines.length;){
|
||||
if(/^\s*\|/.test(lines[i])&&i+1<lines.length&&isSep(lines[i+1])){
|
||||
const head=cells(lines[i]),al=cells(lines[i+1]).map(c=>/^:-+:$/.test(c)?'center':/-:$/.test(c)?'right':'');
|
||||
let j=i+2;const rows=[];
|
||||
while(j<lines.length&&/^\s*\|/.test(lines[j])){rows.push(cells(lines[j]));j++;}
|
||||
const td=(t,c,k)=>`<${t}${al[k]?` style="text-align:${al[k]}"`:''}>${c}</${t}>`;
|
||||
out.push('<div style="overflow-x:auto"><table><thead><tr>'+head.map((c,k)=>td('th',c,k)).join('')+'</tr></thead><tbody>'+
|
||||
rows.map(r=>'<tr>'+head.map((_,k)=>td('td',r[k]??'',k)).join('')+'</tr>').join('')+'</tbody></table></div>');
|
||||
i=j;
|
||||
}else out.push(lines[i++]);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
async function sendMessage(){
|
||||
const input=document.getElementById('chat-input');
|
||||
const msg=input.value.trim();
|
||||
|
||||
@@ -1732,6 +1732,7 @@ function renderMd(text){
|
||||
return text
|
||||
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
||||
.replace(/```[\w]*\n?([\s\S]*?)```/g,'<pre><code>$1</code></pre>')
|
||||
.split(/(<pre>[\s\S]*?<\/pre>)/).map((seg,i)=>i%2?seg:mdTables(seg)).join('')
|
||||
.replace(/`([^`]+)`/g,'<code>$1</code>')
|
||||
.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
|
||||
.replace(/\*(.+?)\*/g,'<em>$1</em>')
|
||||
@@ -1740,7 +1741,27 @@ function renderMd(text){
|
||||
.replace(/^[-*]\s+(.+)$/gm,'<li>$1</li>')
|
||||
.replace(/(<li>[\s\S]+?<\/li>)/g,m=>`<ul style="padding-left:16px;margin:3px 0">${m}</ul>`)
|
||||
.replace(/\n\n/g,'</p><p>').replace(/^/,'<p>').replace(/$/,'</p>')
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<[hup])/g,'$1').replace(/(<\/[hup][^>]*>)<\/p>/g,'$1');
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<[hup]|<div style="overflow-x:auto">)/g,'$1').replace(/(<\/[hup][^>]*>|<\/table><\/div>)<\/p>/g,'$1');
|
||||
}
|
||||
|
||||
// 마크다운 표: '|'로 시작하는 연속 줄 + 두 번째 줄이 구분선(|---|---|)인 블록만 <table>로 바꾼다.
|
||||
// 입력은 이미 HTML 이스케이프된 상태. 셀 안의 `코드`·**굵게**는 이후 인라인 변환이 처리한다.
|
||||
function mdTables(text){
|
||||
const cells=l=>l.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>c.trim());
|
||||
const isSep=l=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)&&l.includes('-')&&/\|/.test(l);
|
||||
const lines=text.split('\n'),out=[];
|
||||
for(let i=0;i<lines.length;){
|
||||
if(/^\s*\|/.test(lines[i])&&i+1<lines.length&&isSep(lines[i+1])){
|
||||
const head=cells(lines[i]),al=cells(lines[i+1]).map(c=>/^:-+:$/.test(c)?'center':/-:$/.test(c)?'right':'');
|
||||
let j=i+2;const rows=[];
|
||||
while(j<lines.length&&/^\s*\|/.test(lines[j])){rows.push(cells(lines[j]));j++;}
|
||||
const td=(t,c,k)=>`<${t}${al[k]?` style="text-align:${al[k]}"`:''}>${c}</${t}>`;
|
||||
out.push('<div style="overflow-x:auto"><table><thead><tr>'+head.map((c,k)=>td('th',c,k)).join('')+'</tr></thead><tbody>'+
|
||||
rows.map(r=>'<tr>'+head.map((_,k)=>td('td',r[k]??'',k)).join('')+'</tr>').join('')+'</tbody></table></div>');
|
||||
i=j;
|
||||
}else out.push(lines[i++]);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
async function sendMessage(){
|
||||
|
||||
@@ -1231,6 +1231,7 @@ function renderMd(text){
|
||||
return text
|
||||
.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')
|
||||
.replace(/```[\w]*\n?([\s\S]*?)```/g,'<pre><code>$1</code></pre>')
|
||||
.split(/(<pre>[\s\S]*?<\/pre>)/).map((seg,i)=>i%2?seg:mdTables(seg)).join('')
|
||||
.replace(/`([^`]+)`/g,'<code>$1</code>')
|
||||
.replace(/\*\*(.+?)\*\*/g,'<strong>$1</strong>')
|
||||
.replace(/\*(.+?)\*/g,'<em>$1</em>')
|
||||
@@ -1239,7 +1240,28 @@ function renderMd(text){
|
||||
.replace(/\n\n/g,'</p><p>').replace(/^/,'<p>').replace(/$/,'</p>')
|
||||
.replace(/<p><\/p>/g,'').replace(/<p>(<h3>)/g,'$1').replace(/(<\/h3>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<pre>)/g,'$1').replace(/(<\/pre>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<blockquote)/g,'$1').replace(/(<\/blockquote>)<\/p>/g,'$1');
|
||||
.replace(/<p>(<blockquote)/g,'$1').replace(/(<\/blockquote>)<\/p>/g,'$1')
|
||||
.replace(/<p>(<div style="overflow-x:auto">)/g,'$1').replace(/(<\/table><\/div>)<\/p>/g,'$1');
|
||||
}
|
||||
|
||||
// 마크다운 표: '|'로 시작하는 연속 줄 + 두 번째 줄이 구분선(|---|---|)인 블록만 <table>로 바꾼다.
|
||||
// 입력은 이미 HTML 이스케이프된 상태. 셀 안의 `코드`·**굵게**는 이후 인라인 변환이 처리한다.
|
||||
function mdTables(text){
|
||||
const cells=l=>l.trim().replace(/^\|/,'').replace(/\|$/,'').split('|').map(c=>c.trim());
|
||||
const isSep=l=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(l)&&l.includes('-')&&/\|/.test(l);
|
||||
const lines=text.split('\n'),out=[];
|
||||
for(let i=0;i<lines.length;){
|
||||
if(/^\s*\|/.test(lines[i])&&i+1<lines.length&&isSep(lines[i+1])){
|
||||
const head=cells(lines[i]),al=cells(lines[i+1]).map(c=>/^:-+:$/.test(c)?'center':/-:$/.test(c)?'right':'');
|
||||
let j=i+2;const rows=[];
|
||||
while(j<lines.length&&/^\s*\|/.test(lines[j])){rows.push(cells(lines[j]));j++;}
|
||||
const td=(t,c,k)=>`<${t}${al[k]?` style="text-align:${al[k]}"`:''}>${c}</${t}>`;
|
||||
out.push('<div style="overflow-x:auto"><table><thead><tr>'+head.map((c,k)=>td('th',c,k)).join('')+'</tr></thead><tbody>'+
|
||||
rows.map(r=>'<tr>'+head.map((_,k)=>td('td',r[k]??'',k)).join('')+'</tr>').join('')+'</tbody></table></div>');
|
||||
i=j;
|
||||
}else out.push(lines[i++]);
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
function sendToChat(message,statusMsg){
|
||||
|
||||
@@ -903,12 +903,13 @@ function schGuard(){ ensureSch(); if(!schDriven()&&P.nets.length&&!confirm('회
|
||||
const SX=x=>x*sview.s+sview.ox, SY=y=>y*sview.s+sview.oy;
|
||||
function resizeSch(){const r=sc2.getBoundingClientRect(),d=window.devicePixelRatio||1;if(!r.width)return;sc2.width=Math.round(r.width*d);sc2.height=Math.round(r.height*d);sctx.setTransform(d,0,0,d,0,0);drawSch();}
|
||||
new ResizeObserver(resizeSch).observe($('scv'));
|
||||
function stext(t,x,y,align,color,size){sctx.fillStyle=color;sctx.font=(size||Math.max(8,1.27*sview.s))+'px sans-serif';sctx.textAlign=align||'left';sctx.fillText(t,x,y);}
|
||||
const STXT=1.0; // 회로도 글자 배율
|
||||
function stext(t,x,y,align,color,size){sctx.fillStyle=color;sctx.font=Math.round((size||Math.max(8,1.27*sview.s))*STXT*10)/10+'px sans-serif';sctx.textAlign=align||'left';sctx.fillText(t,x,y);}
|
||||
function drawSym(part,pos,isSel){
|
||||
const g=partGfx(part), c=sctx, S=sview.s; if(!g||g.loading){const b=partBoxS(part);c.strokeStyle='#888';c.setLineDash([4,3]);c.strokeRect(SX(b.x0),SY(b.y0),(b.x1-b.x0)*S,(b.y1-b.y0)*S);c.setLineDash([]);stext(part.ref+' …',SX(b.x0)+3,SY(b.y0)+12,'left','#aaa',10);return;}
|
||||
const lay=layoutOf(g), col=isSel?'#fff176':'#e8c27a';
|
||||
const T=(lx,ly,i)=>{const [x,y]=sxf(pos,lx,ly-lay.offs[i]);return [SX(x),SY(y)];};
|
||||
c.lineWidth=Math.max(1,0.28*S*0.7);c.lineJoin='round';
|
||||
c.lineWidth=Math.max(1.5,0.28*S*1.05);c.lineJoin='round';
|
||||
g.units.forEach((u,i)=>{
|
||||
c.strokeStyle=col;c.fillStyle='rgba(255,235,160,.13)';
|
||||
for(const r of u.rects){const a=T(r.x0,r.y0,i),b=T(r.x1,r.y0,i),d=T(r.x1,r.y1,i),e=T(r.x0,r.y1,i);c.beginPath();c.moveTo(a[0],a[1]);c.lineTo(b[0],b[1]);c.lineTo(d[0],d[1]);c.lineTo(e[0],e[1]);c.closePath();if(r.fill)c.fill();c.stroke();}
|
||||
@@ -918,9 +919,9 @@ function drawSym(part,pos,isSel){
|
||||
for(const p of u.pins){
|
||||
const rad=p.angle*Math.PI/180, ex=p.x+p.length*Math.cos(rad), ey=p.y+p.length*Math.sin(rad), a=T(p.x,p.y,i), b=T(ex,ey,i);
|
||||
c.strokeStyle=isSel?'#fff176':'#7ec8e3';c.beginPath();c.moveTo(a[0],a[1]);c.lineTo(b[0],b[1]);c.stroke();
|
||||
if(part.dots&&part.dots.includes(String(p.n))){const l=Math.hypot(b[0]-a[0],b[1]-a[1])||1,ux=(b[0]-a[0])/l,uy=(b[1]-a[1])/l,r=Math.max(2.6,0.5*S);c.save();c.fillStyle='#ffb74d';c.beginPath();c.arc(b[0]+ux*(r+1.5),b[1]+uy*(r+1.5),r,0,7);c.fill();c.restore();}
|
||||
if(part.dots&&part.dots.includes(String(p.n))){const l=Math.hypot(b[0]-a[0],b[1]-a[1])||1,ux=(b[0]-a[0])/l,uy=(b[1]-a[1])/l,r=Math.max(3.5,0.65*S);c.save();c.fillStyle='#ffb74d';c.beginPath();c.arc(b[0]+ux*(r+1.5),b[1]+uy*(r+1.5),r,0,7);c.fill();c.restore();}
|
||||
const open=schDriven()&&!sres.conn.has(part.ref+'-'+p.n);
|
||||
if(open){c.strokeStyle='#ef5350';c.lineWidth=1.5;c.beginPath();c.arc(a[0],a[1],Math.max(2.5,0.5*S),0,7);c.stroke();c.lineWidth=Math.max(1,0.28*S*0.7);}
|
||||
if(open){c.strokeStyle='#ef5350';c.lineWidth=1.5;c.beginPath();c.arc(a[0],a[1],Math.max(2.5,0.5*S),0,7);c.stroke();c.lineWidth=Math.max(1.5,0.28*S*1.05);}
|
||||
if(S<4.5) continue;
|
||||
const dx=b[0]-a[0], dy=b[1]-a[1], horiz=Math.abs(dx)>=Math.abs(dy), ux=Math.sign(dx)||0, uy=Math.sign(dy)||0;
|
||||
if(g.showNumbers&&p.n){const mx=(a[0]+b[0])/2,my=(a[1]+b[1])/2;if(horiz)stext(p.n,mx,my-3,'center','#9bb',Math.max(7,0.9*S));else stext(p.n,mx-3,my+3,'right','#9bb',Math.max(7,0.9*S));}
|
||||
@@ -1000,8 +1001,8 @@ function schFit(){
|
||||
if(!P) return; ensureSch(); ensurePlaced(); const r=sc2.getBoundingClientRect(); if(!r.width) return;
|
||||
let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9; const add=b=>{x0=Math.min(x0,b.x0);y0=Math.min(y0,b.y0);x1=Math.max(x1,b.x1);y1=Math.max(y1,b.y1);};
|
||||
P.parts.forEach(p=>{const b=partBoxS(p);if(b)add(b);}); P.sch.wires.forEach(w=>w.pts.forEach(q=>add({x0:q[0],y0:q[1],x1:q[0],y1:q[1]})));
|
||||
if(x0>x1){x0=0;y0=0;x1=100;y1=70;} const m=40, w=x1-x0+8, h=y1-y0+10;
|
||||
sview.s=Math.max(2.5,Math.min(14,Math.min((r.width-2*m)/w,(r.height-2*m)/h))); sview.ox=(r.width-w*sview.s)/2-(x0-4)*sview.s; sview.oy=(r.height-h*sview.s)/2-(y0-6)*sview.s; drawSch();
|
||||
if(x0>x1){x0=0;y0=0;x1=100;y1=70;} const m=16, w=x1-x0+4, h=y1-y0+6;
|
||||
sview.s=Math.max(2.5,Math.min(14,Math.min((r.width-2*m)/w,(r.height-2*m)/h))); sview.ox=(r.width-w*sview.s)/2-(x0-2)*sview.s; sview.oy=(r.height-h*sview.s)/2-(y0-4)*sview.s; drawSch();
|
||||
}
|
||||
|
||||
// ── 입력 ──
|
||||
|
||||
@@ -82,4 +82,39 @@
|
||||
} catch (e2) {}
|
||||
}
|
||||
};
|
||||
|
||||
// 스트리밍 응답 자동 렌더링: 앱들은 토큰이 올 때마다 bubble.innerHTML을 통째로 덮어쓰는데,
|
||||
// renderKatexIn은 말풍선을 처음 만들 때(빈 상태) 한 번만 불려서 실시간 답변의 `$\rightarrow$`가
|
||||
// 날것으로 남았다(대화 기록 복원은 addMsg가 내용을 채워 만들어서 정상). 앱마다 스트림 루프를
|
||||
// 고치는 대신 채팅 영역의 DOM 변화를 지켜보다가, 변화가 잠시(350ms) 멈추면 그 말풍선을 렌더링한다.
|
||||
// 스트리밍 중에는 매 토큰이 덮어쓰므로 중간 렌더링은 자연히 버려지고, 마지막 상태만 남는다.
|
||||
function watchChat() {
|
||||
var root = document.getElementById('chat-msgs');
|
||||
if (!root || !window.MutationObserver) return;
|
||||
var pending = new Set(), timer = null;
|
||||
var mo = new MutationObserver(function (muts) {
|
||||
muts.forEach(function (m) {
|
||||
var el = m.target.nodeType === 1 ? m.target : m.target.parentElement;
|
||||
var b = el && el.closest && el.closest('[class*="-bubble"]');
|
||||
if (b && root.contains(b) && !b.closest('.user, .system')) pending.add(b);
|
||||
});
|
||||
if (!pending.size) return;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(flush, 350);
|
||||
});
|
||||
function flush() {
|
||||
var list = Array.from(pending); pending.clear();
|
||||
mo.disconnect(); // KaTeX가 DOM을 바꾸므로 자기 변경에 다시 반응하지 않게 끊고 렌더링한다.
|
||||
try {
|
||||
list.forEach(function (b) {
|
||||
if (/\$|\\\(|\\\[/.test(b.textContent)) window.renderKatexIn(b);
|
||||
});
|
||||
} finally {
|
||||
mo.observe(root, { childList: true, subtree: true, characterData: true });
|
||||
}
|
||||
}
|
||||
mo.observe(root, { childList: true, subtree: true, characterData: true });
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', watchChat);
|
||||
else watchChat();
|
||||
})();
|
||||
@@ -21,6 +21,33 @@ function setPartsView(v){partsView=v;try{localStorage.setItem('ws_parts_view',v)
|
||||
function setPartsFilter(f){partsFilter=f;renderParts();}
|
||||
function setPartsSort(v){partsSort=v;renderParts();}
|
||||
|
||||
// ── 폴더식 묶음(2026-10-06) — 이름 앞 "[태그]"를 폴더 이름으로 쓴다(데이터 변경 없음). "순서" 정렬일 때만, 태그 있는 부품이 하나라도 있으면 묶는다.
|
||||
const PART_TAG_RE=/^\s*\[([^\]]+)\]\s*/;
|
||||
const partGroupName=p=>{const m=PART_TAG_RE.exec(String(p.name||''));return m?m[1].trim():'기타';};
|
||||
const stripPartTag=n=>String(n||'').replace(PART_TAG_RE,'');
|
||||
let collapsedPartGroups=new Set();
|
||||
try{collapsedPartGroups=new Set(JSON.parse(localStorage.getItem('ws_parts_collapsed')||'[]'));}catch{}
|
||||
function togglePartGroup(enc){
|
||||
const g=decodeURIComponent(enc);
|
||||
if(collapsedPartGroups.has(g))collapsedPartGroups.delete(g);else collapsedPartGroups.add(g);
|
||||
try{localStorage.setItem('ws_parts_collapsed',JSON.stringify([...collapsedPartGroups]));}catch{}
|
||||
renderParts();
|
||||
}
|
||||
function groupParts(list){
|
||||
const map=new Map();
|
||||
for(const p of list){const g=partGroupName(p);if(!map.has(g))map.set(g,[]);map.get(g).push(p);}
|
||||
return [...map].sort((a,b)=>(a[0]==='기타')-(b[0]==='기타')).map(([name,items])=>({name,items}));
|
||||
}
|
||||
function partGroupHdrHtml(g,asRow){
|
||||
const col=collapsedPartGroups.has(g.name);
|
||||
const sum=g.items.reduce((t,p)=>t+p.qty*p.unitPrice,0);
|
||||
const inner=`<span class="rb-pg-chev">${col?'▶':'▼'}</span><span class="rb-pg-name">📁 ${escAttr(g.name)}</span><span class="rb-pg-cnt">${g.items.length}개</span><span class="rb-pg-sum">${fmtWon(sum)}</span>`;
|
||||
const on=`togglePartGroup('${encodeURIComponent(g.name)}')`;
|
||||
return asRow?`<tr class="rb-pgroup-row" onclick="${on}"><td colspan="7"><div class="rb-pgroup-hdr">${inner}</div></td></tr>`
|
||||
:`<div class="rb-pgroup-hdr" onclick="${on}">${inner}</div>`;
|
||||
}
|
||||
let partsGrouped=false;
|
||||
|
||||
function visibleParts(){
|
||||
let list=parts.filter(p=>partsFilter==='all'||p.status===partsFilter);
|
||||
if(partsSort==='name')list=[...list].sort((a,b)=>String(a.name).localeCompare(String(b.name),'ko'));
|
||||
@@ -57,7 +84,7 @@ function renderPartCard(p){
|
||||
<div class="rb-part-card${expanded?' expanded':''}" data-id="${escAttr(p.id)}">
|
||||
<div class="rb-part-hdr" onclick="togglePartExpand('${p.id}')">
|
||||
<span class="rb-part-chevron">▶</span>
|
||||
<span class="rb-part-name">${escAttr(p.name)||'(이름 없음)'}</span>
|
||||
<span class="rb-part-name">${escAttr(partsGrouped?stripPartTag(p.name):p.name)||'(이름 없음)'}</span>
|
||||
<span class="rb-part-badge st-${escAttr(p.status)}">${escAttr(p.status)}</span>
|
||||
<span class="rb-part-sub">${fmtWon(p.qty*p.unitPrice)}</span>
|
||||
</div>
|
||||
@@ -98,7 +125,7 @@ function renderPartCard(p){
|
||||
|
||||
function renderPartsTable(list){
|
||||
const total=list.reduce((sum,p)=>sum+p.qty*p.unitPrice,0);
|
||||
const rows=list.map(p=>`
|
||||
const partRow=p=>`
|
||||
<tr data-id="${escAttr(p.id)}">
|
||||
<td><input type="text" value="${escAttr(p.name)}" placeholder="(이름 없음)" oninput="updatePart('${p.id}','name',this.value)"></td>
|
||||
<td style="width:64px"><input type="number" min="0" value="${escAttr(p.qty)}" oninput="updatePart('${p.id}','qty',this.value)"></td>
|
||||
@@ -109,7 +136,8 @@ function renderPartsTable(list){
|
||||
</select></td>
|
||||
<td><input type="text" value="${escAttr(p.memo)}" oninput="updatePart('${p.id}','memo',this.value)"></td>
|
||||
<td style="white-space:nowrap"><button class="rb-mini-btn" title="시세 조회" onclick="checkPartPrice('${p.id}')">💰</button> <button class="rb-del-btn" onclick="deletePart('${p.id}')">✕</button></td>
|
||||
</tr>`).join('');
|
||||
</tr>`;
|
||||
const rows=partsGrouped?groupParts(list).map(g=>partGroupHdrHtml(g,true)+(collapsedPartGroups.has(g.name)?'':g.items.map(partRow).join(''))).join(''):list.map(partRow).join('');
|
||||
return `<table class="rb-ptable"><thead><tr>
|
||||
<th class="sortable" onclick="setPartsSort('name')">이름</th><th>수량</th><th>단가</th>
|
||||
<th class="sortable" onclick="setPartsSort('amount')">소계</th><th class="sortable" onclick="setPartsSort('status')">상태</th><th>메모</th><th></th>
|
||||
@@ -129,7 +157,10 @@ function renderParts(){
|
||||
if(!parts.length){container.innerHTML='<div class="rb-empty">아직 등록된 부품이 없습니다. "+ 부품 추가"를 누르거나 채팅으로 등록해 보세요.</div>';return;}
|
||||
const list=visibleParts();
|
||||
if(!list.length){container.innerHTML='<div class="rb-empty">이 상태의 부품이 없습니다.</div>';return;}
|
||||
container.innerHTML=partsView==='table'?renderPartsTable(list):list.map(renderPartCard).join('');
|
||||
partsGrouped=partsSort==='order'&&list.some(p=>PART_TAG_RE.test(String(p.name||'')));
|
||||
container.innerHTML=partsView==='table'?renderPartsTable(list)
|
||||
:partsGrouped?groupParts(list).map(g=>partGroupHdrHtml(g,false)+(collapsedPartGroups.has(g.name)?'':g.items.map(renderPartCard).join(''))).join('')
|
||||
:list.map(renderPartCard).join('');
|
||||
}
|
||||
|
||||
function updatePart(id,field,value){
|
||||
@@ -146,7 +177,7 @@ function updatePart(id,field,value){
|
||||
const card=document.querySelector(`.rb-part-card[data-id="${id}"]`);
|
||||
if(card){
|
||||
if(field==='qty'||field==='unitPrice')card.querySelector('.rb-part-sub').textContent=fmtWon(p.qty*p.unitPrice);
|
||||
if(field==='name')card.querySelector('.rb-part-name').textContent=p.name||'(이름 없음)';
|
||||
if(field==='name')card.querySelector('.rb-part-name').textContent=(partsGrouped?stripPartTag(p.name):p.name)||'(이름 없음)';
|
||||
if(field==='status'){
|
||||
const badge=card.querySelector('.rb-part-badge');
|
||||
badge.className='rb-part-badge st-'+p.status;
|
||||
|
||||
Reference in new issue
Block a user