v4.3.19-2: 회계사 앱 스프레드시트 뷰어 수정 + helpers.js 5개 파일 분리
- coder_write_file이 xlsx/pptx/docx/pdf/zip 같은 바이너리 확장자로 파일을
만들려 하면 차단 (텍스트 escape로 바이너리를 흉내내다 파일이 깨지던 문제)
- 레거시 HTML 리다이렉트(/xlsx-viewer.html 등)가 쿼리스트링을 버리던 버그 수정
- xlsx-viewer: "새 시트"가 존재하지 않는 __new__.xlsx를 fetch하다 404나던
것을 빈 워크북 생성 후 저장 시 파일명 입력받는 흐름으로 교체
- xlsx-viewer: LuckyExcel 변환이 내놓는 손상된 숫자 서식("???.???")을
Luckysheet SSF 파서가 못 읽고 죽던 문제에 sanitizer 적용
- 회계사 앱 업로드가 존재하지 않는 /api/upload를 호출하던 것을
/api/upload/file로 수정
- web-ui/js/helpers.js(2240줄)를 helpers-core/markdown/voice/media/files.js
5개로 분리 (기능 변경 없음, 함수 단위 1:1 이관 확인됨)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4d0404ea0d
commit
0963231327
11 files changed
+2353
-2278
No files matched your search
@@ -383,6 +383,19 @@ print(json.dumps({'slides': slides, 'total': len(prs.slides)}, ensure_ascii=Fals
|
||||
if (filename && !filename.includes('/') && !filename.includes('\\') && CODE_EXTS.has(ext)) {
|
||||
filename = `${codeSubDir}/${filename}`;
|
||||
}
|
||||
const BINARY_EXTS: Record<string, string> = {
|
||||
xlsx: 'excel_write', xls: 'excel_write',
|
||||
pptx: 'pptx builder skill', ppt: 'pptx builder skill',
|
||||
docx: 'a document-generation tool', doc: 'a document-generation tool',
|
||||
pdf: 'a PDF-generation tool', zip: 'shell (e.g. python zipfile)',
|
||||
};
|
||||
if (BINARY_EXTS[ext]) {
|
||||
return {
|
||||
name, args,
|
||||
result: `[BLOCKED] coder_write_file cannot create "${filename}" — it writes plain text, and binary ${ext.toUpperCase()} content cannot be represented as text (writing escape sequences like "PK\\u0003\\u0004" produces a corrupted file, not real binary). Use ${BINARY_EXTS[ext]} to create this file instead.`,
|
||||
error: true,
|
||||
};
|
||||
}
|
||||
const filePath = path.join(workspacePath, filename);
|
||||
if (!isPathInsideDir(workspacePath, filePath)) return { name, args, result: 'Access denied: path escapes workspace', error: true };
|
||||
if (fs.existsSync(filePath)) {
|
||||
|
||||
@@ -4345,7 +4345,9 @@ const LEGACY_HTML_REDIRECTS = [
|
||||
'/python-runner.html','/xlsx-viewer.html','/dental-agent.html'
|
||||
];
|
||||
for (const p of LEGACY_HTML_REDIRECTS) {
|
||||
app.get(p, (_req, res) => { res.redirect(`/html${p}`); });
|
||||
// req.url retains the original query string (e.g. xlsx-viewer.html?file=...);
|
||||
// redirecting with the bare path `p` silently drops it.
|
||||
app.get(p, (req, res) => { res.redirect(`/html${req.url}`); });
|
||||
}
|
||||
|
||||
app.get('/{*path}', (_req, res) => { res.sendFile(path.join(webUiPath, 'html', 'index.html')); });
|
||||
|
||||
@@ -362,7 +362,7 @@ function openViewer(apiPath, name){
|
||||
const closeBtn=document.getElementById('viewer-close-btn');
|
||||
const title=document.getElementById('viewer-title');
|
||||
empty.style.display='none';
|
||||
iframe.src='/xlsx-viewer.html?file='+encodeURIComponent(apiPath)+'&save='+encodeURIComponent(apiPath)+'&title='+encodeURIComponent(name);
|
||||
iframe.src='/html/xlsx-viewer.html?file='+encodeURIComponent(apiPath)+'&save='+encodeURIComponent(apiPath)+'&title='+encodeURIComponent(name);
|
||||
iframe.classList.add('visible');
|
||||
title.textContent=name;
|
||||
closeBtn.style.display='';
|
||||
@@ -385,7 +385,7 @@ async function uploadExcelFile(file){
|
||||
addMsg('system','📊 '+escHtml(file.name)+' 업로드 중...');
|
||||
try{
|
||||
const form=new FormData();form.append('file',file);
|
||||
const r=await fetch('/api/upload',{method:'POST',headers:authH(),body:form});
|
||||
const r=await fetch('/api/upload/file',{method:'POST',headers:authH(),body:form});
|
||||
if(!r.ok)throw new Error('업로드 실패 '+r.status);
|
||||
const data=await r.json();
|
||||
const apiPath=data.url||data.path||'/api/files/'+file.name;
|
||||
|
||||
@@ -1943,7 +1943,11 @@
|
||||
</div>
|
||||
|
||||
<script src="../js/voice-call.js"></script>
|
||||
<script src="../js/helpers.js"></script>
|
||||
<script src="../js/helpers-core.js"></script>
|
||||
<script src="../js/markdown.js"></script>
|
||||
<script src="../js/voice.js"></script>
|
||||
<script src="../js/media.js"></script>
|
||||
<script src="../js/files.js"></script>
|
||||
<script src="../js/chat-sse.js"></script>
|
||||
<script src="../js/app.js"></script>
|
||||
|
||||
|
||||
@@ -54,6 +54,9 @@
|
||||
var fileUrl = params.get('file');
|
||||
var saveUrl = params.get('save') || fileUrl;
|
||||
var title = decodeURIComponent(params.get('title') || '스프레드시트');
|
||||
// "새 시트" opens with a sentinel path that doesn't exist on disk — create a
|
||||
// blank sheet locally instead of fetching, and ask for a real filename on save.
|
||||
var isNewFile = /\/__new__\.xlsx$/.test(fileUrl || '');
|
||||
|
||||
document.getElementById('title').textContent = title;
|
||||
document.title = title;
|
||||
@@ -63,44 +66,85 @@
|
||||
'<div style="padding:24px;color:#b91c1c;font-size:13px">' + msg + '</div>';
|
||||
}
|
||||
|
||||
function renderSheets(sheets) {
|
||||
document.getElementById('container').innerHTML = '';
|
||||
luckysheet.create({
|
||||
container: 'container',
|
||||
data: sheets,
|
||||
title: '',
|
||||
lang: 'en',
|
||||
showinfobar: false,
|
||||
showstatisticBar: false,
|
||||
sheetBottomConfig: true,
|
||||
allowUpdate: true,
|
||||
enableAddRow: true,
|
||||
enableAddCol: true,
|
||||
showToolbar: true,
|
||||
plugins: [],
|
||||
defaultFontSize: 11,
|
||||
defaultFontName: 'Nanum Gothic',
|
||||
});
|
||||
}
|
||||
|
||||
// LuckyExcel occasionally emits a placeholder number-format string like
|
||||
// "???.???" for formats it can't map during conversion; Luckysheet's own
|
||||
// SSF parser then throws "unsupported format" on that literal placeholder
|
||||
// and the sheet never renders. Strip any format string containing "?".
|
||||
function sanitizeSheets(sheets) {
|
||||
(sheets || []).forEach(function(sheet) {
|
||||
(sheet.celldata || []).forEach(function(cell) {
|
||||
var ct = cell && cell.v && cell.v.ct;
|
||||
if (ct && typeof ct.fa === 'string' && ct.fa.indexOf('?') !== -1) {
|
||||
ct.fa = 'General';
|
||||
}
|
||||
});
|
||||
});
|
||||
return sheets;
|
||||
}
|
||||
|
||||
function loadFromFile(file) {
|
||||
LuckyExcel.transformExcelToLucky(file, function(exportInfo) {
|
||||
renderSheets(sanitizeSheets(exportInfo.sheets));
|
||||
}, function(err) {
|
||||
showError('Excel 변환 오류: ' + String(err?.message || err));
|
||||
});
|
||||
}
|
||||
|
||||
if (!fileUrl) { showError('파일 URL이 없습니다.'); return; }
|
||||
|
||||
fetch(fileUrl, { credentials: 'include' })
|
||||
.then(function(r) {
|
||||
if (r.status === 401 || r.status === 403) throw new Error('인증 오류 — 메인 탭에서 먼저 로그인하세요.');
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.arrayBuffer();
|
||||
})
|
||||
.then(function(buf) {
|
||||
var file = new File([buf], 'sheet.xlsx', {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
});
|
||||
LuckyExcel.transformExcelToLucky(file, function(exportInfo) {
|
||||
document.getElementById('container').innerHTML = '';
|
||||
luckysheet.create({
|
||||
container: 'container',
|
||||
data: exportInfo.sheets,
|
||||
title: '',
|
||||
lang: 'en',
|
||||
showinfobar: false,
|
||||
showstatisticBar: false,
|
||||
sheetBottomConfig: true,
|
||||
allowUpdate: true,
|
||||
enableAddRow: true,
|
||||
enableAddCol: true,
|
||||
showToolbar: true,
|
||||
plugins: [],
|
||||
defaultFontSize: 11,
|
||||
defaultFontName: 'Nanum Gothic',
|
||||
});
|
||||
}, function(err) {
|
||||
showError('Excel 변환 오류: ' + String(err?.message || err));
|
||||
});
|
||||
})
|
||||
.catch(function(e) { showError('불러오기 실패: ' + e.message); });
|
||||
if (isNewFile) {
|
||||
// Build a real (if minimal) xlsx and run it through the same LuckyExcel
|
||||
// conversion as a normal file, rather than hand-rolling Luckysheet's
|
||||
// internal sheet JSON (undocumented and error-prone).
|
||||
var blankWb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(blankWb, XLSX.utils.aoa_to_sheet([['']]), 'Sheet1');
|
||||
var blankBuf = XLSX.write(blankWb, { type: 'array', bookType: 'xlsx' });
|
||||
loadFromFile(new File([blankBuf], 'sheet.xlsx', {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
}));
|
||||
} else {
|
||||
fetch(fileUrl, { credentials: 'include' })
|
||||
.then(function(r) {
|
||||
if (r.status === 401 || r.status === 403) throw new Error('인증 오류 — 메인 탭에서 먼저 로그인하세요.');
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.arrayBuffer();
|
||||
})
|
||||
.then(function(buf) {
|
||||
loadFromFile(new File([buf], 'sheet.xlsx', {
|
||||
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
}));
|
||||
})
|
||||
.catch(function(e) { showError('불러오기 실패: ' + e.message); });
|
||||
}
|
||||
|
||||
window.saveFile = function() {
|
||||
if (!saveUrl) { alert('저장할 파일 경로가 없습니다.'); return; }
|
||||
if (isNewFile) {
|
||||
var name = prompt('저장할 파일 이름을 입력하세요', '새 시트.xlsx');
|
||||
if (!name) return;
|
||||
if (!/\.xlsx$/i.test(name)) name += '.xlsx';
|
||||
saveUrl = '/api/files/' + name;
|
||||
}
|
||||
var btn = document.getElementById('save-btn');
|
||||
btn.disabled = true; btn.textContent = '저장 중…';
|
||||
var relPath = saveUrl.replace(/^\/api\/files\//, '');
|
||||
@@ -121,7 +165,16 @@
|
||||
body: new Uint8Array(buf),
|
||||
}).then(function(r) {
|
||||
btn.disabled = false;
|
||||
if (r.ok) { btn.textContent = '✅ 저장됨'; setTimeout(function() { btn.textContent = '💾 저장'; }, 2000); }
|
||||
if (r.ok) {
|
||||
btn.textContent = '✅ 저장됨'; setTimeout(function() { btn.textContent = '💾 저장'; }, 2000);
|
||||
if (isNewFile) {
|
||||
isNewFile = false;
|
||||
title = relPath.split('/').pop();
|
||||
document.getElementById('title').textContent = title;
|
||||
document.title = title;
|
||||
}
|
||||
try { if (parent && parent !== window && typeof parent.loadExcelFiles === 'function') parent.loadExcelFiles(); } catch (e) {}
|
||||
}
|
||||
else { btn.textContent = '❌ 실패'; setTimeout(function() { btn.textContent = '💾 저장'; }, 2000); }
|
||||
}).catch(function(e) {
|
||||
btn.disabled = false; btn.textContent = '❌ 오류';
|
||||
|
||||
@@ -0,0 +1,767 @@
|
||||
// files.js — file preview + attachment handling extracted from helpers.js.
|
||||
// Sheet preview (PDF embed, XLSX viewer, Luckysheet modal) + file upload/attachment
|
||||
// staging (handleImageUpload, handleFileUpload, stageAttachment, renderStagedAttachments,
|
||||
// pdfPageToText, ...). stagedAttachments stays global (sendChat reads it).
|
||||
function togglePdfEmbed(url, containerId, btn) {
|
||||
var container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
var iframe = container.querySelector('iframe');
|
||||
if (container.style.display === 'none') {
|
||||
container.style.display = 'block';
|
||||
if (iframe) iframe.src = url; // src=""이면 현재페이지로 해석 → 항상 명시 설정
|
||||
btn.innerHTML = '▲ 닫기';
|
||||
} else {
|
||||
container.style.display = 'none';
|
||||
btn.innerHTML = '◀ 미리보기';
|
||||
}
|
||||
}
|
||||
|
||||
var _luckyCurrentSaveUrl = null;
|
||||
|
||||
function openXlsxNewWindow(url, title) {
|
||||
var q = '/html/xlsx-viewer.html?file=' + encodeURIComponent(url)
|
||||
+ '&save=' + encodeURIComponent(url)
|
||||
+ '&title=' + encodeURIComponent(title || '스프레드시트');
|
||||
window.open(q, '_blank', 'width=1200,height=800,menubar=no,toolbar=no,location=no,status=no,scrollbars=no,resizable=yes');
|
||||
}
|
||||
|
||||
function toggleXlsxEmbedBtn(btn) {
|
||||
var url = encodeURI(btn.getAttribute('data-xlsx-url'));
|
||||
var card = btn.closest('.xlsx-card');
|
||||
var nameEl = card ? card.querySelector('span[style*="font-weight"]') : null;
|
||||
var title = nameEl ? nameEl.textContent : url.split('/').pop();
|
||||
var saveUrl = card ? card.querySelector('[data-xlsx-save-url]')?.getAttribute('data-xlsx-save-url') : null;
|
||||
openLuckyModal(url, title, saveUrl);
|
||||
}
|
||||
|
||||
function openLuckyModal(url, title, saveUrl) {
|
||||
var modal = document.getElementById('lucky-modal');
|
||||
var titleEl = document.getElementById('lucky-modal-title');
|
||||
var container = document.getElementById('lucky-container');
|
||||
if (!modal || !container) return;
|
||||
|
||||
// Reset box to centered state on each open
|
||||
var box = document.getElementById('lucky-modal-box');
|
||||
if (box) {
|
||||
box.style.position = 'relative';
|
||||
box.style.left = ''; box.style.top = '';
|
||||
box.style.width = '96vw'; box.style.height = '92vh';
|
||||
box._isAbsolute = false; box.dataset.minimized = '0';
|
||||
}
|
||||
modal.style.display = 'flex';
|
||||
modal.style.alignItems = 'center';
|
||||
modal.style.justifyContent = 'center';
|
||||
titleEl.textContent = title || '스프레드시트';
|
||||
_luckyCurrentSaveUrl = saveUrl || null;
|
||||
container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#666;font-size:13px">Luckysheet 로딩 중… (최초 1회 ~3MB)</div>';
|
||||
initLuckyModalInteraction();
|
||||
|
||||
fetch(url, { headers: authHeaders() })
|
||||
.then(function(r) { if (!r.ok) throw new Error('HTTP ' + r.status); return r.arrayBuffer(); })
|
||||
.then(function(buf) {
|
||||
loadLuckysheet(function() {
|
||||
if (typeof LuckyExcel === 'undefined' || typeof luckysheet === 'undefined') {
|
||||
container.innerHTML = '<div style="padding:20px;color:red">Luckysheet 로드 실패 — 네트워크 연결을 확인하세요.</div>'; return;
|
||||
}
|
||||
var file = new File([buf], 'sheet.xlsx', { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
|
||||
LuckyExcel.transformExcelToLucky(file, function(exportInfo) {
|
||||
container.innerHTML = '';
|
||||
try { luckysheet.destroy(); } catch(e) {}
|
||||
luckysheet.create({
|
||||
container: 'lucky-container',
|
||||
data: exportInfo.sheets,
|
||||
title: '',
|
||||
lang: 'en',
|
||||
showinfobar: false,
|
||||
showstatisticBar: false,
|
||||
sheetBottomConfig: true,
|
||||
allowUpdate: true,
|
||||
enableAddRow: true,
|
||||
enableAddCol: true,
|
||||
showToolbar: true,
|
||||
plugins: [],
|
||||
defaultFontSize: 11,
|
||||
defaultFontName: 'Nanum Gothic',
|
||||
});
|
||||
}, function(err) {
|
||||
container.innerHTML = '<div style="padding:20px;color:red">Excel 변환 오류: ' + escHtml(String(err?.message || err)) + '</div>';
|
||||
});
|
||||
});
|
||||
})
|
||||
.catch(function(e) {
|
||||
container.innerHTML = '<div style="padding:20px;color:red">불러오기 실패: ' + escHtml(e.message) + '</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function minimizeLuckyModal() {
|
||||
var box = document.getElementById('lucky-modal-box');
|
||||
var modal = document.getElementById('lucky-modal');
|
||||
var btn = event.target;
|
||||
if (!box || !modal) return;
|
||||
var minimized = box.dataset.minimized === '1';
|
||||
if (minimized) {
|
||||
box.style.height = box._savedHeight || '92vh';
|
||||
box.dataset.minimized = '0';
|
||||
btn.textContent = '–';
|
||||
btn.title = '최소화';
|
||||
if (!box._isAbsolute) { modal.style.alignItems = 'center'; modal.style.justifyContent = 'center'; }
|
||||
} else {
|
||||
box._savedHeight = box.style.height || '92vh';
|
||||
box.dataset.minimized = '1';
|
||||
btn.innerHTML = '◻';
|
||||
btn.title = '복원';
|
||||
if (box._isAbsolute) {
|
||||
box.style.top = (window.innerHeight - 52) + 'px';
|
||||
box.style.height = 'auto';
|
||||
} else {
|
||||
box.style.height = 'auto';
|
||||
modal.style.alignItems = 'flex-end';
|
||||
modal.style.justifyContent = 'center';
|
||||
modal.style.paddingBottom = '0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function closeLuckyModal() {
|
||||
var modal = document.getElementById('lucky-modal');
|
||||
var box = document.getElementById('lucky-modal-box');
|
||||
if (modal) { modal.style.display = 'none'; modal.style.alignItems = 'center'; modal.style.justifyContent = 'center'; }
|
||||
if (box) {
|
||||
box.style.position = 'relative';
|
||||
box.style.left = ''; box.style.top = '';
|
||||
box.style.width = '96vw'; box.style.height = '92vh';
|
||||
box._isAbsolute = false; box._savedHeight = null;
|
||||
box.dataset.minimized = '0';
|
||||
}
|
||||
try { luckysheet.destroy(); } catch(e) {}
|
||||
_luckyCurrentSaveUrl = null;
|
||||
}
|
||||
|
||||
// Close on backdrop click
|
||||
document.getElementById('lucky-modal')?.addEventListener('click', function(e) {
|
||||
if (e.target === this) closeLuckyModal();
|
||||
});
|
||||
|
||||
function initLuckyModalInteraction() {
|
||||
var box = document.getElementById('lucky-modal-box');
|
||||
var modal = document.getElementById('lucky-modal');
|
||||
if (!box || box._interactInit) return;
|
||||
box._interactInit = true;
|
||||
|
||||
// Inject 8 resize handles
|
||||
[
|
||||
{ dir:'n', css:'top:0;left:10px;right:10px;height:6px;cursor:n-resize' },
|
||||
{ dir:'s', css:'bottom:0;left:10px;right:10px;height:6px;cursor:s-resize' },
|
||||
{ dir:'e', css:'right:0;top:10px;bottom:10px;width:6px;cursor:e-resize' },
|
||||
{ dir:'w', css:'left:0;top:10px;bottom:10px;width:6px;cursor:w-resize' },
|
||||
{ dir:'ne', css:'top:0;right:0;width:12px;height:12px;cursor:ne-resize' },
|
||||
{ dir:'nw', css:'top:0;left:0;width:12px;height:12px;cursor:nw-resize' },
|
||||
{ dir:'se', css:'bottom:0;right:0;width:12px;height:12px;cursor:se-resize' },
|
||||
{ dir:'sw', css:'bottom:0;left:0;width:12px;height:12px;cursor:sw-resize' },
|
||||
].forEach(function(d) {
|
||||
var h = document.createElement('div');
|
||||
h.className = 'lucky-rh';
|
||||
h.dataset.dir = d.dir;
|
||||
h.style.cssText = 'position:absolute;z-index:200;' + d.css;
|
||||
box.appendChild(h);
|
||||
});
|
||||
|
||||
function toAbsolute() {
|
||||
if (box._isAbsolute) return;
|
||||
var rect = box.getBoundingClientRect();
|
||||
modal.style.display = 'block';
|
||||
box.style.position = 'absolute';
|
||||
box.style.left = rect.left + 'px';
|
||||
box.style.top = rect.top + 'px';
|
||||
box.style.width = rect.width + 'px';
|
||||
box.style.height = rect.height + 'px';
|
||||
box._isAbsolute = true;
|
||||
}
|
||||
|
||||
// Title bar drag
|
||||
var header = box.firstElementChild;
|
||||
if (header) {
|
||||
header.style.cursor = 'grab';
|
||||
header.addEventListener('mousedown', function(e) {
|
||||
if (e.target.tagName === 'BUTTON') return;
|
||||
toAbsolute();
|
||||
var rect = box.getBoundingClientRect();
|
||||
var ox = e.clientX - rect.left, oy = e.clientY - rect.top;
|
||||
header.style.cursor = 'grabbing';
|
||||
function onMove(e) {
|
||||
box.style.left = (e.clientX - ox) + 'px';
|
||||
box.style.top = Math.max(0, e.clientY - oy) + 'px';
|
||||
}
|
||||
function onUp() {
|
||||
header.style.cursor = 'grab';
|
||||
document.removeEventListener('mousemove', onMove);
|
||||
document.removeEventListener('mouseup', onUp);
|
||||
}
|
||||
document.addEventListener('mousemove', onMove);
|
||||
document.addEventListener('mouseup', onUp);
|
||||
e.preventDefault();
|
||||
});
|
||||
}
|
||||
|
||||
// Resize handle drag
|
||||
box.addEventListener('mousedown', function(e) {
|
||||
var handle = e.target.closest ? e.target.closest('.lucky-rh') : null;
|
||||
if (!handle) return;
|
||||
toAbsolute();
|
||||
var dir = handle.dataset.dir;
|
||||
var rect = box.getBoundingClientRect();
|
||||
var sx = e.clientX, sy = e.clientY;
|
||||
var sl = rect.left, st = rect.top, sw = rect.width, sh = rect.height;
|
||||
document.body.style.userSelect = 'none';
|
||||
document.body.style.cursor = handle.style.cursor;
|
||||
function onMove(e) {
|
||||
var dx = e.clientX - sx, dy = e.clientY - sy;
|
||||
var nl = sl, nt = st, nw = sw, nh = sh;
|
||||
if (dir.includes('e')) nw = Math.max(380, sw + dx);
|
||||
if (dir.includes('s')) nh = Math.max(180, sh + dy);
|
||||
if (dir.includes('w')) { nw = Math.max(380, sw - dx); nl = sl + sw - nw; }
|
||||
if (dir.includes('n')) { nh = Math.max(180, sh - dy); nt = st + sh - nh; }
|
||||
box.style.left = nl + 'px'; box.style.top = nt + 'px';
|
||||
box.style.width = nw + 'px'; box.style.height = nh + 'px';
|
||||
}
|
||||
function onUp() {
|
||||
document.body.style.userSelect = '';
|
||||
document.body.style.cursor = '';
|
||||
document.removeEventListener('mousemove', onMove);
|
||||
document.removeEventListener('mouseup', onUp);
|
||||
}
|
||||
document.addEventListener('mousemove', onMove);
|
||||
document.addEventListener('mouseup', onUp);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
});
|
||||
}
|
||||
|
||||
function saveLuckyModal() {
|
||||
var url = _luckyCurrentSaveUrl;
|
||||
if (!url) { alert('저장할 파일 경로가 없습니다.'); return; }
|
||||
var btn = document.getElementById('lucky-modal-save');
|
||||
var relPath = url.replace(/^\/api\/files\//, '');
|
||||
loadSheetJS(function() {
|
||||
try {
|
||||
// Luckysheet → SheetJS aoa conversion
|
||||
var sheets = luckysheet.getAllSheets();
|
||||
var wb = XLSX.utils.book_new();
|
||||
sheets.forEach(function(sheet) {
|
||||
var celldata = sheet.celldata || [];
|
||||
if (!celldata.length) { XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet([[]]), sheet.name || 'Sheet'); return; }
|
||||
var maxR = 0, maxC = 0;
|
||||
celldata.forEach(function(c) { maxR = Math.max(maxR, c.r); maxC = Math.max(maxC, c.c); });
|
||||
var aoa = [];
|
||||
for (var r = 0; r <= maxR; r++) aoa.push(new Array(maxC + 1).fill(''));
|
||||
celldata.forEach(function(c) {
|
||||
if (c.v == null) return;
|
||||
var val = (typeof c.v === 'object') ? (c.v.m !== undefined ? c.v.m : (c.v.v !== undefined ? c.v.v : '')) : c.v;
|
||||
aoa[c.r][c.c] = val;
|
||||
});
|
||||
XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), sheet.name || 'Sheet');
|
||||
});
|
||||
var xlsxBuf = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
|
||||
btn.disabled = true; btn.textContent = '저장 중…';
|
||||
fetch('/api/files/' + relPath, {
|
||||
method: 'PUT', headers: authHeaders(),
|
||||
body: new Blob([xlsxBuf], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
|
||||
})
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(res) {
|
||||
btn.disabled = false; btn.innerHTML = '💾 저장';
|
||||
if (res.success) { btn.textContent = '✓ 저장됨'; setTimeout(function() { btn.innerHTML = '💾 저장'; }, 2000); }
|
||||
else alert('저장 실패: ' + (res.error || '알 수 없는 오류'));
|
||||
})
|
||||
.catch(function(e) { btn.disabled = false; btn.innerHTML = '💾 저장'; alert('저장 오류: ' + e.message); });
|
||||
} catch(e) { alert('Excel 변환 오류: ' + e.message); }
|
||||
});
|
||||
}
|
||||
|
||||
function toggleStagedExcelPreview(id) {
|
||||
var el = document.getElementById('excel-staged-' + id);
|
||||
if (!el) return;
|
||||
el.style.display = el.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function toggleTxtEmbedBtn(btn) {
|
||||
var card = btn.closest('.txt-card');
|
||||
if (!card) return;
|
||||
var container = card.querySelector('.txt-preview-body');
|
||||
if (!container) return;
|
||||
var url = encodeURI(btn.getAttribute('data-txt-url'));
|
||||
if (container.style.display === 'none') {
|
||||
container.style.display = 'block';
|
||||
btn.innerHTML = '▲ 접기';
|
||||
if (!container.dataset.loaded) {
|
||||
container.textContent = '불러오는 중…';
|
||||
fetch(url, { headers: authHeaders() })
|
||||
.then(function(r) {
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.text();
|
||||
})
|
||||
.then(function(t) {
|
||||
container.textContent = t;
|
||||
container.dataset.loaded = '1';
|
||||
})
|
||||
.catch(function(e) {
|
||||
container.textContent = '텍스트를 불러올 수 없습니다. (' + e.message + ')';
|
||||
});
|
||||
}
|
||||
} else {
|
||||
container.style.display = 'none';
|
||||
btn.innerHTML = '◀ 미리보기';
|
||||
}
|
||||
}
|
||||
function togglePptxPreview(fileUrl, containerId, btn) {
|
||||
var container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
var isVisible = container.style.display !== 'none';
|
||||
if (isVisible) {
|
||||
container.style.display = 'none';
|
||||
btn.innerHTML = '◀ Preview';
|
||||
return;
|
||||
}
|
||||
// Show loading state
|
||||
container.style.display = 'flex';
|
||||
container.innerHTML = '<span style="color:var(--muted);font-size:13px;padding:12px">Generating preview...</span>';
|
||||
btn.innerHTML = '▲ Preview';
|
||||
btn.classList.add('loading');
|
||||
|
||||
// Extract relative path from various URL formats:
|
||||
// /api/files/Folder/file.pptx → Folder/file.pptx
|
||||
// https://host/api/files/Folder/file.pptx → Folder/file.pptx
|
||||
// Folder/file.pptx → Folder/file.pptx
|
||||
var filePath = fileUrl;
|
||||
// Handle sandboxed environments where origin may be sandbox:/
|
||||
if (fileUrl.charAt(0) === '/') {
|
||||
filePath = fileUrl; // Already an absolute path, use as-is
|
||||
} else {
|
||||
try { filePath = new URL(fileUrl, window.location.origin).pathname; } catch(e) {}
|
||||
}
|
||||
filePath = filePath.replace(/^\/api\/files\/?/, '');
|
||||
// If the link itself is a preview URL, extract the path query parameter
|
||||
var previewMatch = filePath.match(/^\/api\/pptx\/preview\?path=(.+)$/);
|
||||
if (previewMatch) {
|
||||
filePath = previewMatch[1];
|
||||
}
|
||||
// Safely decode - handle already-decoded or invalid encodings
|
||||
try { filePath = decodeURIComponent(filePath); } catch(e) {}
|
||||
fetch('/api/pptx/preview?path=' + encodeURIComponent(filePath), {
|
||||
headers: authHeaders()
|
||||
})
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
btn.classList.remove('loading');
|
||||
if (!data.success || !data.images || !data.images.length) {
|
||||
container.innerHTML = '<span style="color:#ef4444;font-size:13px;padding:12px">Preview failed: ' + escHtml(data.error || 'No slides found') + '</span>';
|
||||
return;
|
||||
}
|
||||
// img 태그는 Bearer 헤더를 보낼 수 없어서 auth 없이 요청 → user context 미설정 → 파일 못 찾음.
|
||||
// fetch()로 auth 포함해 가져온 뒤 Blob URL로 교체.
|
||||
Promise.all(data.images.map(function(imgUrl) {
|
||||
return fetch(imgUrl, { headers: authHeaders() })
|
||||
.then(function(r) { return r.ok ? r.blob() : Promise.reject(new Error('HTTP ' + r.status)); })
|
||||
.then(function(blob) { return URL.createObjectURL(blob); })
|
||||
.catch(function() { return imgUrl; });
|
||||
})).then(function(srcs) {
|
||||
container.innerHTML = srcs.map(function(src, i) {
|
||||
return '<img src="' + src + '" alt="Slide ' + (i + 1) + '" onclick="openImageZoom(this.src)" loading="lazy" />';
|
||||
}).join('');
|
||||
});
|
||||
})
|
||||
.catch(function(err) {
|
||||
btn.classList.remove('loading');
|
||||
container.innerHTML = '<span style="color:#ef4444;font-size:13px;padding:12px">Preview error: ' + escHtml(err.message) + '</span>';
|
||||
});
|
||||
}
|
||||
|
||||
function handleImageUpload(input) {
|
||||
var file = input.files && input.files[0];
|
||||
if (!file) return;
|
||||
input.value = '';
|
||||
var formData = new FormData();
|
||||
formData.append('image', file);
|
||||
fetch('/api/upload/image', {
|
||||
method: 'POST',
|
||||
headers: authHeaders(),
|
||||
body: formData
|
||||
})
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.success && data.path) {
|
||||
var chatInput = document.getElementById('chat-input');
|
||||
var imgRef = '';
|
||||
chatInput.value = chatInput.value ? chatInput.value + '\n' + imgRef : imgRef;
|
||||
chatInput.focus();
|
||||
} else {
|
||||
alert(data.error || 'Upload failed');
|
||||
}
|
||||
})
|
||||
.catch(function(e) { alert('Upload error: ' + e.message); });
|
||||
}
|
||||
|
||||
// ── 파일 첨부 (이미지·PDF·Excel·txt·csv 등) ─────────────────────────────────
|
||||
function handleFileUpload(input) {
|
||||
var file = input.files && input.files[0];
|
||||
if (!file) return;
|
||||
input.value = '';
|
||||
var name = file.name.toLowerCase();
|
||||
|
||||
// MIDI → 악보 변환
|
||||
if (/\.(mid|midi)$/.test(name) || file.type === 'audio/midi' || file.type === 'audio/x-midi') {
|
||||
uploadMidiAndRender(file);
|
||||
return;
|
||||
}
|
||||
|
||||
// 이미지
|
||||
if (file.type.startsWith('image/')) {
|
||||
var imgForm = new FormData();
|
||||
imgForm.append('image', file);
|
||||
fetch('/api/upload/image', { method: 'POST', headers: authHeaders(), body: imgForm })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.success && data.path) {
|
||||
insertIntoChatInput('');
|
||||
} else { alert(data.error || '이미지 업로드 실패'); }
|
||||
})
|
||||
.catch(function(e) { alert('업로드 오류: ' + e.message); });
|
||||
|
||||
// txt / md
|
||||
} else if (/\.(txt|md)$/.test(name)) {
|
||||
var r1 = new FileReader();
|
||||
r1.onload = function(e) {
|
||||
var ext = name.split('.').pop();
|
||||
stageAttachment(file.name, null, '**[파일: ' + file.name + ']**\n```' + ext + '\n' + e.target.result + '\n```', 'text');
|
||||
};
|
||||
r1.readAsText(file, 'UTF-8');
|
||||
|
||||
// CSV
|
||||
} else if (/\.csv$/.test(name)) {
|
||||
var r2 = new FileReader();
|
||||
r2.onload = function(e) {
|
||||
stageAttachment(file.name, null, '**[파일: ' + file.name + ']**\n```csv\n' + e.target.result + '\n```', 'csv');
|
||||
};
|
||||
r2.readAsText(file, 'UTF-8');
|
||||
|
||||
// Excel
|
||||
} else if (/\.(xlsx|xls)$/.test(name)) {
|
||||
var xlsxFile = file;
|
||||
var xlsxForm = new FormData();
|
||||
xlsxForm.append('file', xlsxFile);
|
||||
var xlsxUploadPromise = fetch('/api/upload/file', { method: 'POST', headers: authHeaders(), body: xlsxForm })
|
||||
.then(function(r) { return r.json(); }).catch(function() { return {}; });
|
||||
loadSheetJS(function() {
|
||||
var r3 = new FileReader();
|
||||
r3.onload = function(e) {
|
||||
try {
|
||||
var wb = XLSX.read(e.target.result, { type: 'array' });
|
||||
var markdownContent = '**[파일: ' + xlsxFile.name + ']**\n\n';
|
||||
var previewHtml = '';
|
||||
wb.SheetNames.forEach(function(sn) {
|
||||
var rows = XLSX.utils.sheet_to_json(wb.Sheets[sn], { header: 1 });
|
||||
markdownContent += '### ' + sn + '\n';
|
||||
rows.forEach(function(row) { markdownContent += '| ' + row.map(function(c) { return String(c ?? ''); }).join(' | ') + ' |\n'; });
|
||||
markdownContent += '\n';
|
||||
previewHtml += '<div style="margin-bottom:6px;font-weight:700;font-size:11px">' + escHtml(sn) + '</div>';
|
||||
previewHtml += '<div style="overflow-x:auto"><table style="border-collapse:collapse;font-size:11px">';
|
||||
rows.slice(0, 30).forEach(function(row, ri) {
|
||||
previewHtml += '<tr>';
|
||||
row.forEach(function(cell) {
|
||||
var tag = ri === 0 ? 'th' : 'td';
|
||||
previewHtml += '<' + tag + ' style="border:1px solid var(--line);padding:3px 7px;text-align:left;white-space:nowrap">' + escHtml(String(cell ?? '')) + '</' + tag + '>';
|
||||
});
|
||||
previewHtml += '</tr>';
|
||||
});
|
||||
if (rows.length > 30) previewHtml += '<tr><td colspan="99" style="text-align:center;color:var(--muted);font-size:10px;padding:4px">… ' + (rows.length - 30) + '행 더</td></tr>';
|
||||
previewHtml += '</table></div>';
|
||||
});
|
||||
xlsxUploadPromise.then(function(d) {
|
||||
var fileUrl = (d.success && d.path) ? '/api/files/' + d.path : null;
|
||||
stageAttachment(xlsxFile.name, fileUrl, markdownContent, 'excel', { excelPreviewHtml: previewHtml });
|
||||
});
|
||||
} catch(err) { alert('Excel 파싱 오류: ' + err.message); }
|
||||
};
|
||||
r3.readAsArrayBuffer(xlsxFile);
|
||||
});
|
||||
|
||||
// PDF — 업로드 + PDF.js 텍스트 추출 + txt 자동 저장
|
||||
} else if (/\.pdf$/.test(name)) {
|
||||
var pdfFile = file;
|
||||
var pdfForm = new FormData();
|
||||
pdfForm.append('file', pdfFile);
|
||||
var uploadPromise = fetch('/api/upload/file', { method: 'POST', headers: authHeaders(), body: pdfForm })
|
||||
.then(function(r) { return r.json(); });
|
||||
|
||||
var extractPromise = new Promise(function(resolve) {
|
||||
loadPdfJs(function() {
|
||||
var fr = new FileReader();
|
||||
fr.onload = function(e) {
|
||||
pdfjsLib.getDocument({ data: new Uint8Array(e.target.result) }).promise
|
||||
.then(function(pdf) {
|
||||
var pages = [];
|
||||
for (var i = 1; i <= pdf.numPages; i++) pages.push(pdf.getPage(i));
|
||||
Promise.all(pages).then(function(ps) {
|
||||
return Promise.all(ps.map(function(p, pi) {
|
||||
return p.getTextContent().then(function(tc) {
|
||||
return pdfPageToText(tc.items, pi + 1, pdf.numPages);
|
||||
});
|
||||
}));
|
||||
}).then(function(texts) {
|
||||
resolve({ text: texts.join('\n\n'), pages: pdf.numPages });
|
||||
}).catch(function() { resolve({ text: '', pages: 0 }); });
|
||||
}).catch(function() { resolve({ text: '', pages: 0 }); });
|
||||
};
|
||||
fr.readAsArrayBuffer(pdfFile);
|
||||
});
|
||||
});
|
||||
|
||||
Promise.all([uploadPromise, extractPromise]).then(function(res) {
|
||||
var upData = res[0], extracted = res[1];
|
||||
var fileUrl = (upData.success && upData.path) ? '/api/files/' + upData.path : null;
|
||||
var fullText = (extracted.text || '').trim();
|
||||
|
||||
if (fullText) {
|
||||
var txtName = pdfFile.name.replace(/\.pdf$/i, '.txt');
|
||||
var txtBlob = new Blob([extracted.text], { type: 'text/plain; charset=utf-8' });
|
||||
var txtForm = new FormData();
|
||||
txtForm.append('file', new File([txtBlob], txtName, { type: 'text/plain' }));
|
||||
fetch('/api/upload/file', { method: 'POST', headers: authHeaders(), body: txtForm })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(d) {
|
||||
var txtUrl = (d.success && d.path) ? '/api/files/' + d.path : null;
|
||||
if (txtUrl) addProcessEntry('info', '📝 텍스트 저장: ' + txtName);
|
||||
var content = '[' + pdfFile.name + '](' + (fileUrl || '') + ')';
|
||||
if (txtUrl) content += '\n[' + txtName + '](' + txtUrl + ')';
|
||||
content += '\n\n이 파일로 무엇을 도와드릴까요? 사용자가 원하는 작업을 직접 알려주기 전까지 어떤 변환이나 생성 작업도 시작하지 마세요.';
|
||||
stageAttachment(pdfFile.name, fileUrl, content, 'pdf', {
|
||||
txtPreview: fullText.slice(0, 500),
|
||||
txtUrl: txtUrl,
|
||||
txtName: txtName,
|
||||
pages: extracted.pages
|
||||
});
|
||||
}).catch(function() {
|
||||
var content = '[' + pdfFile.name + '](' + (fileUrl || '') + ')\n\n이 파일로 무엇을 도와드릴까요?';
|
||||
stageAttachment(pdfFile.name, fileUrl, content, 'pdf', {
|
||||
txtPreview: fullText.slice(0, 500),
|
||||
pages: extracted.pages
|
||||
});
|
||||
});
|
||||
} else {
|
||||
var content = '[' + pdfFile.name + '](' + (fileUrl || '') + ')\n*(텍스트 추출 불가 — 스캔 이미지이거나 보안 잠금 PDF)*';
|
||||
stageAttachment(pdfFile.name, fileUrl, content, 'pdf');
|
||||
}
|
||||
}).catch(function(e) { alert('PDF 처리 오류: ' + e.message); });
|
||||
|
||||
// 기타 (docx/pptx 등)
|
||||
} else {
|
||||
var otherForm = new FormData();
|
||||
otherForm.append('file', file);
|
||||
fetch('/api/upload/file', { method: 'POST', headers: authHeaders(), body: otherForm })
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.success && data.path) {
|
||||
insertIntoChatInput('[' + file.name + '](/api/files/' + data.path + ')');
|
||||
} else { alert(data.error || '파일 업로드 실패'); }
|
||||
})
|
||||
.catch(function(e) { alert('업로드 오류: ' + e.message); });
|
||||
}
|
||||
}
|
||||
|
||||
function insertIntoChatInput(text) {
|
||||
var el = document.getElementById('chat-input');
|
||||
el.value = el.value ? el.value + '\n' + text : text;
|
||||
el.focus();
|
||||
el.dispatchEvent(new Event('input'));
|
||||
}
|
||||
|
||||
// ── 첨부 파일 스테이징 ──────────────────────────────────────────────────────
|
||||
var stagedAttachments = [];
|
||||
|
||||
function stageAttachment(name, url, content, type, extra) {
|
||||
var id = 'att-' + Date.now() + '-' + Math.random().toString(36).substr(2, 5);
|
||||
var att = { id: id, name: name, url: url, content: content, type: type };
|
||||
if (extra) Object.assign(att, extra);
|
||||
stagedAttachments.push(att);
|
||||
renderStagedAttachments();
|
||||
}
|
||||
|
||||
function removeStagedAttachment(id) {
|
||||
stagedAttachments = stagedAttachments.filter(function(a) { return a.id !== id; });
|
||||
renderStagedAttachments();
|
||||
}
|
||||
|
||||
function clearStagedAttachments() {
|
||||
stagedAttachments = [];
|
||||
renderStagedAttachments();
|
||||
}
|
||||
|
||||
function renderStagedAttachments() {
|
||||
var container = document.getElementById('staged-attachments');
|
||||
if (!container) return;
|
||||
if (!stagedAttachments.length) { container.style.display = 'none'; container.innerHTML = ''; return; }
|
||||
container.style.display = 'flex';
|
||||
container.innerHTML = stagedAttachments.map(function(a) {
|
||||
var icon = a.type === 'pdf' ? '📄' : a.type === 'excel' ? '📊' : a.type === 'csv' ? '📋' : '📝';
|
||||
var btnStyle = 'background:none;border:1px solid var(--brand);cursor:pointer;font-size:11px;color:var(--brand);padding:2px 6px;border-radius:4px';
|
||||
|
||||
// PDF 카드
|
||||
if (a.type === 'pdf') {
|
||||
var txtPreview = a.txtPreview ? escHtml(a.txtPreview) + (a.txtPreview.length >= 500 ? '...' : '') : '';
|
||||
var pagesInfo = a.pages ? ' (' + a.pages + '페이지)' : '';
|
||||
return '<div id="card-' + a.id + '" style="display:flex;flex-direction:column;gap:4px;background:var(--panel-2);border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:12px;max-width:320px">'
|
||||
+ '<div style="display:flex;align-items:center;gap:6px">'
|
||||
+ '<span>📄</span>'
|
||||
+ '<span style="font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="' + escHtml(a.name) + pagesInfo + '">' + escHtml(a.name) + '</span>'
|
||||
+ (txtPreview ? '<button onclick="toggleStagedTxtPdfPreview(\'' + a.id + '\')" style="' + btnStyle + '">txt 미리보기</button>' : '')
|
||||
+ (a.url ? '<button onclick="toggleStagedPdfPreview(\'' + a.id + '\')" style="' + btnStyle + '">PDF</button>' : '')
|
||||
+ (a.txtUrl ? '<a href="' + escHtml(a.txtUrl) + '" download="' + escHtml(a.txtName || '') + '" style="' + btnStyle + ';text-decoration:none;display:inline-block" title="txt 다운로드">📝⬇</a>' : '')
|
||||
+ '<button onclick="removeStagedAttachment(\'' + a.id + '\')" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:14px;line-height:1;padding:0 2px">✕</button>'
|
||||
+ '</div>'
|
||||
+ (pagesInfo ? '<div style="font-size:10px;color:var(--muted);padding-left:2px">텍스트 추출 완료' + pagesInfo + '</div>' : '')
|
||||
+ (txtPreview ? '<div id="txt-pdf-preview-' + a.id + '" style="display:none;max-height:200px;overflow-y:auto;background:var(--panel-1);border:1px solid var(--line);border-radius:6px;padding:8px;font-size:11px;white-space:pre-wrap;word-break:break-all;color:var(--text)">' + txtPreview + '</div>' : '')
|
||||
+ '<div id="pdf-preview-' + a.id + '" style="display:none"><iframe data-src="' + escHtml(a.url || '') + '" style="width:100%;height:400px;border:1px solid var(--line);border-radius:6px"></iframe></div>'
|
||||
+ '</div>';
|
||||
}
|
||||
|
||||
// TXT 자동저장 카드 (미리보기 + 다운로드)
|
||||
if (a.type === 'txt-auto') {
|
||||
var preview = escHtml((a.content || '').slice(0, 300)) + ((a.content || '').length > 300 ? '...' : '');
|
||||
return '<div id="card-' + a.id + '" style="display:flex;flex-direction:column;gap:4px;background:var(--panel-2);border:1px dashed var(--brand);border-radius:8px;padding:6px 10px;font-size:12px;max-width:320px">'
|
||||
+ '<div style="display:flex;align-items:center;gap:6px">'
|
||||
+ '<span>📝</span>'
|
||||
+ '<span style="font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escHtml(a.name) + '</span>'
|
||||
+ '<button onclick="toggleStagedTxtPreview(\'' + a.id + '\')" style="' + btnStyle + '">미리보기</button>'
|
||||
+ (a.url ? '<a href="' + escHtml(a.url) + '" download="' + escHtml(a.name) + '" style="' + btnStyle + ';text-decoration:none;display:inline-block" title="다운로드">⬇ 저장</a>' : '')
|
||||
+ '<button onclick="removeStagedAttachment(\'' + a.id + '\')" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:14px;line-height:1;padding:0 2px">✕</button>'
|
||||
+ '</div>'
|
||||
+ '<div id="txt-preview-' + a.id + '" style="display:none;max-height:200px;overflow-y:auto;background:var(--panel-1);border:1px solid var(--line);border-radius:6px;padding:8px;font-size:11px;white-space:pre-wrap;word-break:break-all;color:var(--text)">' + preview + '</div>'
|
||||
+ '</div>';
|
||||
}
|
||||
|
||||
// excel 카드
|
||||
if (a.type === 'excel') {
|
||||
return '<div id="card-' + a.id + '" style="display:flex;flex-direction:column;gap:4px;background:var(--panel-2);border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:12px;max-width:360px">'
|
||||
+ '<div style="display:flex;align-items:center;gap:6px">'
|
||||
+ '<span>📊</span>'
|
||||
+ '<span style="font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escHtml(a.name) + '</span>'
|
||||
+ (a.excelPreviewHtml ? '<button onclick="toggleStagedExcelPreview(\'' + a.id + '\')" style="' + btnStyle + '">미리보기</button>' : '')
|
||||
+ (a.url ? '<a href="' + escHtml(a.url) + '" download="' + escHtml(a.name) + '" style="' + btnStyle + ';text-decoration:none;display:inline-block">⬇ 저장</a>' : '')
|
||||
+ '<button onclick="removeStagedAttachment(\'' + a.id + '\')" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:14px;line-height:1;padding:0 2px">✕</button>'
|
||||
+ '</div>'
|
||||
+ (a.excelPreviewHtml ? '<div id="excel-staged-' + a.id + '" style="display:none;max-height:260px;overflow:auto;background:var(--panel-1);border:1px solid var(--line);border-radius:6px;padding:8px">' + a.excelPreviewHtml + '</div>' : '')
|
||||
+ '</div>';
|
||||
}
|
||||
|
||||
// 기타 카드 (text, csv)
|
||||
return '<div id="card-' + a.id + '" style="display:flex;flex-direction:column;gap:4px;background:var(--panel-2);border:1px solid var(--line);border-radius:8px;padding:6px 10px;font-size:12px;max-width:320px">'
|
||||
+ '<div style="display:flex;align-items:center;gap:6px">'
|
||||
+ '<span>' + icon + '</span>'
|
||||
+ '<span style="font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + escHtml(a.name) + '</span>'
|
||||
+ '<button onclick="removeStagedAttachment(\'' + a.id + '\')" style="background:none;border:none;cursor:pointer;color:var(--muted);font-size:14px;line-height:1;padding:0 2px">✕</button>'
|
||||
+ '</div>'
|
||||
+ '</div>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function toggleStagedPdfPreview(id) {
|
||||
var el = document.getElementById('pdf-preview-' + id);
|
||||
if (!el) return;
|
||||
var att = stagedAttachments.find(function(a) { return a.id === id; });
|
||||
if (el.style.display === 'none') {
|
||||
el.style.display = 'block';
|
||||
var iframe = el.querySelector('iframe');
|
||||
if (iframe && att && att.url) iframe.src = att.url; // 항상 명시 설정
|
||||
} else {
|
||||
el.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function toggleStagedTxtPreview(id) {
|
||||
var el = document.getElementById('txt-preview-' + id);
|
||||
if (!el) return;
|
||||
el.style.display = el.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
function toggleStagedTxtPdfPreview(id) {
|
||||
var el = document.getElementById('txt-pdf-preview-' + id);
|
||||
if (!el) return;
|
||||
el.style.display = el.style.display === 'none' ? 'block' : 'none';
|
||||
}
|
||||
|
||||
// PDF 카드에 txt 저장 버튼 동적 삽입 (txt 업로드 완료 후 호출)
|
||||
function addTxtButtonToPdfCard(pdfName, txtName, txtUrl) {
|
||||
// stagedAttachments에서 해당 PDF 찾기
|
||||
var att = stagedAttachments.find(function(a) { return a.name === pdfName && a.type === 'pdf'; });
|
||||
if (!att) return;
|
||||
// txt 정보를 attachment에 저장 (전송 시 displayMessage에 포함용)
|
||||
att.txtName = txtName;
|
||||
att.txtUrl = txtUrl;
|
||||
// 카드 DOM에 txt 버튼 삽입
|
||||
var card = document.getElementById('card-' + att.id);
|
||||
if (!card) return;
|
||||
var btnRow = card.querySelector('div');
|
||||
if (!btnRow) return;
|
||||
var btnStyle = 'background:none;border:1px solid var(--brand);cursor:pointer;font-size:11px;color:var(--brand);padding:2px 6px;border-radius:4px;text-decoration:none;display:inline-block';
|
||||
var txtBtn = document.createElement('a');
|
||||
txtBtn.href = txtUrl;
|
||||
txtBtn.download = txtName;
|
||||
txtBtn.title = txtName + ' 다운로드';
|
||||
txtBtn.style.cssText = btnStyle;
|
||||
txtBtn.innerHTML = '📝 txt ⬇';
|
||||
// ✕ 버튼 바로 앞에 삽입
|
||||
var closeBtn = btnRow.lastElementChild;
|
||||
btnRow.insertBefore(txtBtn, closeBtn);
|
||||
}
|
||||
|
||||
// ── PDF 페이지 텍스트 구조화 ────────────────────────────────────────────────
|
||||
function pdfPageToText(items, pageNum, totalPages) {
|
||||
// filter out empty items
|
||||
var valid = items.filter(function(it) { return it.str && it.str.trim() !== ''; });
|
||||
if (!valid.length) return '';
|
||||
|
||||
// sort top→bottom (y desc), left→right (x asc)
|
||||
valid.sort(function(a, b) {
|
||||
var ay = a.transform[5], by = b.transform[5];
|
||||
if (Math.abs(ay - by) > 2) return by - ay;
|
||||
return a.transform[4] - b.transform[4];
|
||||
});
|
||||
|
||||
// group items into lines by y-coordinate proximity
|
||||
var LINE_Y_THRESH = 3;
|
||||
var lines = [];
|
||||
var cur = null;
|
||||
valid.forEach(function(item) {
|
||||
var y = item.transform[5];
|
||||
var h = item.height || 10;
|
||||
if (!cur || Math.abs(y - cur.y) > LINE_Y_THRESH) {
|
||||
cur = { y: y, h: h, items: [item] };
|
||||
lines.push(cur);
|
||||
} else {
|
||||
cur.items.push(item);
|
||||
if (h > cur.h) cur.h = h;
|
||||
}
|
||||
});
|
||||
|
||||
// build output: join items per line; insert blank line on large y-gaps (paragraph break)
|
||||
var out = [];
|
||||
if (totalPages > 1) out.push('── ' + pageNum + '페이지 ──');
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
var lineText = lines[i].items.map(function(it) { return it.str; }).join('').replace(/\s+/g, ' ').trim();
|
||||
if (!lineText) continue;
|
||||
|
||||
// paragraph break: gap > 1.4× current line height
|
||||
if (i > 0) {
|
||||
var gap = lines[i - 1].y - lines[i].y;
|
||||
if (gap > lines[i - 1].h * 1.4) out.push('');
|
||||
}
|
||||
// fix hyphenation: merge "단어-\n다음줄" → "단어다음줄"
|
||||
if (out.length && out[out.length - 1].endsWith('-')) {
|
||||
out[out.length - 1] = out[out.length - 1].slice(0, -1) + lineText;
|
||||
} else {
|
||||
out.push(lineText);
|
||||
}
|
||||
}
|
||||
return out.join('\n');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// helpers-core.js — foundational helpers extracted from helpers.js.
|
||||
// escHtml + file/link button builder + chat-bubble/image-zoom/download UI +
|
||||
// dynamic CDN loaders (SheetJS, Luckysheet, PDF.js) + timeAgo/openOllamaInfo.
|
||||
// Plain globals; loaded before the other split helper files and before app.js.
|
||||
function escHtml(str) {
|
||||
if (!str) return '';
|
||||
return String(str).replace(/&/g,'&').replace(/\\/g,'\').replace(/`/g,'`').replace(/\$/g,'$').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||
}
|
||||
|
||||
function _normalizeFileUrl(url) {
|
||||
// Convert sandbox:/mnt/... or /mnt/user-data/... paths to /api/files/... URLs
|
||||
if (/^sandbox:/i.test(url)) {
|
||||
var p = url.replace(/^sandbox:\/*/i, '');
|
||||
var idx = p.indexOf('uploads/');
|
||||
return '/api/files/' + (idx !== -1 ? p.slice(idx) : 'uploads/' + p.split('/').pop());
|
||||
}
|
||||
if (/^\/mnt\/(user-data|data)\//i.test(url)) {
|
||||
var idx = url.indexOf('uploads/');
|
||||
return '/api/files/' + (idx !== -1 ? url.slice(idx) : 'uploads/' + url.split('/').pop());
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
function _renderLinkButton(text, url, opts) {
|
||||
var hideDownload = opts && opts.hideDownload;
|
||||
url = _normalizeFileUrl(url);
|
||||
var fileExts = ['.pptx','.pdf','.xlsx','.xls','.docx','.doc','.zip','.csv','.mp4','.mp3'];
|
||||
var isDownload = fileExts.some(function(ext) { return text.toLowerCase().endsWith(ext); })
|
||||
|| fileExts.some(function(ext) { return decodeURIComponent(url).toLowerCase().indexOf(ext) !== -1; });
|
||||
var decodedUrl = decodeURIComponent(url).toLowerCase();
|
||||
var isPptx = decodedUrl.indexOf('.pptx') !== -1 || text.toLowerCase().endsWith('.pptx');
|
||||
var isPdf = decodedUrl.indexOf('.pdf') !== -1 || text.toLowerCase().endsWith('.pdf');
|
||||
var isXlsx = /\.(xlsx|xls)(\?.*)?$/i.test(decodedUrl) || /\.(xlsx|xls)$/i.test(text.toLowerCase());
|
||||
if (isPptx) {
|
||||
var previewId = 'pptx-preview-' + Math.random().toString(36).substr(2, 9);
|
||||
return '<div class="pptx-file-row">'
|
||||
+ '<a href="' + url + '" onclick="downloadFile(event, this)" class="download-btn" title="Download ' + text + '">'
|
||||
+ '<span class="download-icon">⬇</span> ' + text + '</a>'
|
||||
+ ' <button class="pptx-preview-btn" onclick="togglePptxPreview(\'' + escHtml(url) + '\', \'' + previewId + '\', this)" title="미리보기">◀ 미리보기</button>'
|
||||
+ '<div id="' + previewId + '" class="pptx-preview-strip" style="display:none"></div>'
|
||||
+ '</div>';
|
||||
}
|
||||
if (isPdf) {
|
||||
var pdfId = 'pdf-embed-' + Math.random().toString(36).substr(2, 9);
|
||||
return '<div class="pdf-file-row" style="display:flex;flex-direction:column;gap:6px;margin:4px 0">'
|
||||
+ '<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">'
|
||||
+ '<a href="' + url + '" target="_blank" rel="noopener" class="download-btn" title="새 탭에서 열기">'
|
||||
+ '<span style="font-size:14px">📄</span> ' + text + '</a>'
|
||||
+ '<button class="pptx-preview-btn" onclick="togglePdfEmbed(\'' + escHtml(url) + '\',\'' + pdfId + '\',this)">◀ 미리보기</button>'
|
||||
+ (hideDownload ? '' : '<a href="' + url + '" onclick="downloadFile(event,this)" class="pptx-preview-btn" style="text-decoration:none">⬇ 저장</a>')
|
||||
+ '</div>'
|
||||
+ '<div id="' + pdfId + '" style="display:none">'
|
||||
+ '<iframe style="width:100%;height:600px;border:1px solid var(--line);border-radius:8px" allowfullscreen></iframe>'
|
||||
+ '</div>'
|
||||
+ '</div>';
|
||||
}
|
||||
if (isXlsx) {
|
||||
var xlsxSafeUrl = escHtml(url);
|
||||
return '<div class="pdf-file-row xlsx-card" style="display:flex;flex-direction:column;gap:6px;margin:4px 0">'
|
||||
+ '<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">'
|
||||
+ '<span style="font-size:14px">📊</span>'
|
||||
+ '<span style="font-weight:600;color:var(--text)">' + escHtml(text) + '</span>'
|
||||
+ '<button class="pptx-preview-btn" data-xlsx-url="' + xlsxSafeUrl + '" data-xlsx-save-url="' + xlsxSafeUrl + '" onclick="toggleXlsxEmbedBtn(this)" style="background:linear-gradient(135deg,#3b82f6,#2563eb)">✏️ 편집</button>'
|
||||
+ '<button class="pptx-preview-btn" onclick="openXlsxNewWindow(\'' + xlsxSafeUrl + '\',\'' + escHtml(text) + '\')" style="background:linear-gradient(135deg,#6366f1,#4f46e5)" title="새 창에서 열기">↗ 새 창</button>'
|
||||
+ '<a href="' + xlsxSafeUrl + '" download class="pptx-preview-btn" style="text-decoration:none">⬇ 다운로드</a>'
|
||||
+ '</div>'
|
||||
+ ''
|
||||
+ '</div>';
|
||||
}
|
||||
var isTxt = /\.txt(\?[^"]*)?$/i.test(decodedUrl) || /\.txt$/i.test(text.toLowerCase());
|
||||
if (isTxt) {
|
||||
var txtLabel = escHtml(text.replace(/^📝\s*/, ''));
|
||||
return '<div class="pdf-file-row txt-card" style="display:flex;flex-direction:column;gap:6px;margin:4px 0">'
|
||||
+ '<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">'
|
||||
+ '<span style="font-size:14px">📝</span>'
|
||||
+ '<span style="font-weight:600;color:var(--text)">' + txtLabel + '</span>'
|
||||
+ '<button class="pptx-preview-btn" data-txt-url="' + escHtml(url) + '" onclick="toggleTxtEmbedBtn(this)">◀ 미리보기</button>'
|
||||
+ '<a href="' + escHtml(url) + '" download="' + txtLabel + '" class="pptx-preview-btn" style="text-decoration:none">⬇ 저장</a>'
|
||||
+ '</div>'
|
||||
+ '<div class="txt-preview-body" style="display:none;max-height:420px;overflow-y:auto;background:var(--panel-1);border:1px solid var(--line);border-radius:8px;padding:12px;font-size:12px;white-space:pre-wrap;word-break:break-word;line-height:1.7;color:var(--text);font-family:inherit"></div>'
|
||||
+ '</div>';
|
||||
}
|
||||
if (isDownload) {
|
||||
return '<a href="' + url + '" onclick="downloadFile(event, this)" class="download-btn" title="Download ' + text + '">'
|
||||
+ '<span class="download-icon">⬇</span> ' + text + '</a>';
|
||||
}
|
||||
return '<a href="' + url + '" target="_blank" rel="noopener">' + text + '</a>';
|
||||
}
|
||||
function appendChatBubble(role, html) {
|
||||
var wrap = document.getElementById('chat-messages');
|
||||
if (!wrap) return;
|
||||
var div = document.createElement('div');
|
||||
div.className = 'msg msg-' + role;
|
||||
div.innerHTML = '<div class="msg-content">' + html + '</div>';
|
||||
wrap.appendChild(div);
|
||||
wrap.scrollTop = wrap.scrollHeight;
|
||||
}
|
||||
|
||||
function openImageZoom(src) {
|
||||
var modal = document.getElementById('image-zoom-modal');
|
||||
var img = document.getElementById('image-zoom-img');
|
||||
if (modal && img) {
|
||||
img.src = src;
|
||||
modal.style.display = 'flex';
|
||||
}
|
||||
}
|
||||
|
||||
function closeImageZoom() {
|
||||
var modal = document.getElementById('image-zoom-modal');
|
||||
if (modal) modal.style.display = 'none';
|
||||
}
|
||||
|
||||
// Cache of checked /api/files/ URLs: url -> true (exists) | false (not found)
|
||||
var _dlLinkCache = {};
|
||||
|
||||
function markDownloadLinkError(btn) {
|
||||
var href = btn.getAttribute ? btn.getAttribute('href') : (btn.href || '');
|
||||
var filename = decodeURIComponent((href || '').split('/').pop() || '파일');
|
||||
_dlLinkCache[href] = false;
|
||||
var span = document.createElement('span');
|
||||
span.className = 'download-btn-error';
|
||||
span.title = '파일을 찾을 수 없음: ' + filename;
|
||||
span.textContent = '⚠ ' + filename + ' (파일 없음)';
|
||||
if (btn.parentNode) btn.parentNode.replaceChild(span, btn);
|
||||
}
|
||||
|
||||
function validateDownloadLinks(container) {
|
||||
var buttons = (container || document).querySelectorAll('a.download-btn[href]');
|
||||
buttons.forEach(function(btn) {
|
||||
var url = btn.getAttribute('href');
|
||||
if (!url || url.indexOf('/api/files/') === -1) return;
|
||||
if (_dlLinkCache[url] === false) { markDownloadLinkError(btn); return; }
|
||||
if (_dlLinkCache[url] === true || _dlLinkCache[url] === 'pending') return;
|
||||
_dlLinkCache[url] = 'pending';
|
||||
fetch(url, { method: 'HEAD', headers: authHeaders() })
|
||||
.then(function(r) {
|
||||
_dlLinkCache[url] = r.ok;
|
||||
if (!r.ok) {
|
||||
var found = (container || document).querySelector('a.download-btn[href="' + url.replace(/"/g, '\\"') + '"]');
|
||||
if (found) markDownloadLinkError(found);
|
||||
}
|
||||
})
|
||||
.catch(function() { _dlLinkCache[url] = false; });
|
||||
});
|
||||
}
|
||||
|
||||
function downloadFile(e, el) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
var url = el.getAttribute('href');
|
||||
if (!url) return;
|
||||
|
||||
// Ensure absolute URL (handle sandboxed environments where origin may be sandbox:/)
|
||||
if (!url.match(/^https?:\/\//)) {
|
||||
if (url.charAt(0) === '/') {
|
||||
// Already an absolute path — use relative to current host
|
||||
url = url;
|
||||
} else {
|
||||
url = new URL(url, window.location.origin).href;
|
||||
}
|
||||
}
|
||||
|
||||
var filename = decodeURIComponent(url.split('/').pop() || 'download');
|
||||
|
||||
fetch(url, {
|
||||
headers: authHeaders()
|
||||
})
|
||||
.then(function(r) {
|
||||
if (!r.ok) throw new Error(r.status);
|
||||
return r.blob();
|
||||
})
|
||||
.then(function(blob) {
|
||||
var blobUrl = URL.createObjectURL(blob);
|
||||
var a = document.createElement('a');
|
||||
a.href = blobUrl;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(blobUrl);
|
||||
})
|
||||
.catch(function(err) {
|
||||
markDownloadLinkError(el);
|
||||
});
|
||||
}
|
||||
var _sheetJsLoaded = false;
|
||||
function loadSheetJS(cb) {
|
||||
if (_sheetJsLoaded) return cb();
|
||||
var s = document.createElement('script');
|
||||
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js';
|
||||
s.onload = function() { _sheetJsLoaded = true; cb(); };
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
var _luckyLoaded = false;
|
||||
function loadLuckysheet(cb) {
|
||||
if (_luckyLoaded) return cb();
|
||||
var cssList = [
|
||||
'https://cdn.jsdelivr.net/npm/luckysheet@2.1.13/dist/plugins/css/pluginsCss.css',
|
||||
'https://cdn.jsdelivr.net/npm/luckysheet@2.1.13/dist/plugins/plugins.css',
|
||||
'https://cdn.jsdelivr.net/npm/luckysheet@2.1.13/dist/css/luckysheet.css',
|
||||
'https://cdn.jsdelivr.net/npm/luckysheet@2.1.13/dist/assets/iconfont/iconfont.css',
|
||||
];
|
||||
cssList.forEach(function(href) {
|
||||
var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = href;
|
||||
document.head.appendChild(l);
|
||||
});
|
||||
var scripts = [
|
||||
'https://cdn.jsdelivr.net/npm/luckysheet@2.1.13/dist/plugins/js/plugin.js',
|
||||
'https://cdn.jsdelivr.net/npm/luckysheet@2.1.13/dist/luckysheet.umd.js',
|
||||
'https://cdn.jsdelivr.net/npm/luckyexcel@1.0.1/dist/luckyexcel.umd.js',
|
||||
];
|
||||
function next(i) {
|
||||
if (i >= scripts.length) { _luckyLoaded = true; cb(); return; }
|
||||
var s = document.createElement('script');
|
||||
s.src = scripts[i]; s.onload = function() { next(i + 1); };
|
||||
s.onerror = function() { next(i + 1); }; // 실패해도 진행
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
next(0);
|
||||
}
|
||||
|
||||
var _pdfJsLoaded = false;
|
||||
function loadPdfJs(cb) {
|
||||
if (_pdfJsLoaded) return cb();
|
||||
var s = document.createElement('script');
|
||||
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js';
|
||||
s.onload = function() {
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';
|
||||
_pdfJsLoaded = true; cb();
|
||||
};
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
|
||||
function timeAgo(ts) {
|
||||
const diff = Date.now() - ts;
|
||||
if (diff < 60000) return 'just now';
|
||||
if (diff < 3600000) return `${Math.floor(diff/60000)}m ago`;
|
||||
if (diff < 86400000) return `${Math.floor(diff/3600000)}h ago`;
|
||||
return `${Math.floor(diff/86400000)}d ago`;
|
||||
}
|
||||
|
||||
function openOllamaInfo() { window.open('http://localhost:11434','_blank'); }
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,348 @@
|
||||
// markdown.js — markdown rendering + embed-URL converters extracted from helpers.js.
|
||||
// windyToEmbedUrl/youtubeToEmbedUrl/mapsToEmbedUrl + renderMarkdown (hand-rolled).
|
||||
// Generates inline onclick strings referencing functions in media.js/files.js/
|
||||
// helpers-core.js (resolved at click time, so load order is not runtime-critical).
|
||||
function windyToEmbedUrl(url) {
|
||||
try {
|
||||
var u = new URL(url);
|
||||
// Already an embed URL — use as-is
|
||||
if (u.hostname === 'embed.windy.com') return url;
|
||||
// windy.com map URL → convert to embed
|
||||
if (/windy\.com/.test(u.hostname)) {
|
||||
var lat = u.searchParams.get('lat') || '';
|
||||
var lon = u.searchParams.get('lon') || '';
|
||||
var zoom = u.searchParams.get('zoom') || '';
|
||||
var overlay = u.searchParams.get('overlay') || '';
|
||||
var level = u.searchParams.get('level') || 'surface';
|
||||
// Handle windy.com comma format: ?overlay,lat,lon,zoom or pathname /-overlay?overlay,lat,lon,zoom
|
||||
if (!lat || !lon) {
|
||||
var qs = u.search.slice(1); // e.g. 'radar,36.545,127.974,7'
|
||||
var parts = qs.split(',');
|
||||
if (parts.length >= 3) {
|
||||
overlay = overlay || parts[0];
|
||||
lat = parts[1];
|
||||
lon = parts[2];
|
||||
zoom = zoom || parts[3] || '7';
|
||||
}
|
||||
}
|
||||
lat = lat || '37.5';
|
||||
lon = lon || '126.9';
|
||||
zoom = zoom || '7';
|
||||
overlay = overlay || 'rain';
|
||||
// Map radar overlay name
|
||||
if (overlay === '-radar' || overlay === 'radar') overlay = 'radar';
|
||||
return 'https://embed.windy.com/embed2.html?lat=' + lat + '&lon=' + lon +
|
||||
'&zoom=' + zoom + '&level=' + level + '&overlay=' + overlay +
|
||||
'&menu=&message=true&marker=&calendar=now&pressure=&type=map' +
|
||||
'&location=coordinates&detail=&metricWind=m%2Fs&metricTemp=%C2%B0C';
|
||||
}
|
||||
return null;
|
||||
} catch(e) { return null; }
|
||||
}
|
||||
|
||||
function youtubeToEmbedUrl(url) {
|
||||
try {
|
||||
var u = new URL(url);
|
||||
var id = null;
|
||||
if (u.hostname === 'youtu.be') {
|
||||
id = u.pathname.slice(1).split(/[/?]/)[0];
|
||||
} else if (/youtube\.com/.test(u.hostname)) {
|
||||
id = u.searchParams.get('v');
|
||||
if (!id) {
|
||||
var m = u.pathname.match(/\/(?:shorts|embed)\/([^/?]+)/);
|
||||
if (m) id = m[1];
|
||||
}
|
||||
}
|
||||
if (!id) return null;
|
||||
var start = u.searchParams.get('t') || u.searchParams.get('start');
|
||||
return 'https://www.youtube.com/embed/' + id + (start ? '?start=' + parseInt(start, 10) : '');
|
||||
} catch(e) { return null; }
|
||||
}
|
||||
|
||||
function mapsToEmbedUrl(url) {
|
||||
try {
|
||||
var u = new URL(url);
|
||||
var q = null;
|
||||
var placeMatch = u.pathname.match(/\/maps\/place\/([^/@?]+)/);
|
||||
if (placeMatch) q = decodeURIComponent(placeMatch[1].replace(/\+/g, ' '));
|
||||
if (!q) {
|
||||
var searchMatch = u.pathname.match(/\/maps\/search\/([^/@?]+)/);
|
||||
if (searchMatch) q = decodeURIComponent(searchMatch[1].replace(/\+/g, ' '));
|
||||
}
|
||||
if (!q) {
|
||||
var coordMatch = u.pathname.match(/\/@(-?\d+\.?\d*),(-?\d+\.?\d*)/);
|
||||
if (coordMatch) q = coordMatch[1] + ',' + coordMatch[2];
|
||||
}
|
||||
if (!q) q = u.searchParams.get('q') || u.searchParams.get('query');
|
||||
if (!q) return null;
|
||||
return 'https://maps.google.com/maps?q=' + encodeURIComponent(q) + '&output=embed&hl=ko';
|
||||
} catch(e) { return null; }
|
||||
}
|
||||
|
||||
function renderMarkdown(text, opts) {
|
||||
if (!text) return '';
|
||||
|
||||
// Extract existing <img> tags before escaping so they survive escHtml()
|
||||
var imgPlaceholders = [];
|
||||
var imgRe = /<img\s+[^>]*class=["']md-img["'][^>]*>/gi;
|
||||
var textSafe = text.replace(imgRe, function(m) {
|
||||
var idx = imgPlaceholders.length;
|
||||
imgPlaceholders.push(m);
|
||||
return '\x00IMG' + idx + '\x00';
|
||||
});
|
||||
|
||||
var html = escHtml(textSafe);
|
||||
|
||||
// Restore <img> tags (already safe HTML)
|
||||
imgPlaceholders.forEach(function(img, i) {
|
||||
html = html.replace('\x00IMG' + i + '\x00', img);
|
||||
});
|
||||
|
||||
// Code blocks (``` ... ```) — escHtml() above already turned literal backticks into
|
||||
// ` (it escapes backtick/backslash/$ too, not just &<>"'), so matching on literal
|
||||
// backticks here never matched anything — every special widget block (midi-widget, abc,
|
||||
// lilypond, tradingview, kstock, smiles) silently fell through as escaped plain text.
|
||||
// Rendered widget HTML (smiles data-smiles attrs especially) can itself contain raw
|
||||
// "[X](Y)"-shaped substrings (SMILES stereo notation like [C@@H](C) reads exactly like
|
||||
// markdown link syntax) that the later link/image/bold regexes would then mangle mid-
|
||||
// attribute. Stash each block's final HTML behind a placeholder and restore it after
|
||||
// all other text transforms have run, the same trick used for <img> above.
|
||||
var codeBlockPlaceholders = [];
|
||||
html = html.replace(/```([\w-]*)\n([\s\S]*?)```/g, function(_, lang, code) {
|
||||
var result = (function() {
|
||||
// code.trim() would strip leading whitespace off only the FIRST line (it operates on
|
||||
// the whole string, not per-line), misaligning ASCII-art whose top row is indented
|
||||
// (e.g. a right-shifted "O" over a left-aligned structure below it). Only drop fully
|
||||
// blank leading/trailing lines so every line's own indentation survives intact.
|
||||
var trimmed = code.replace(/^\n+/, '').replace(/\n+$/, '');
|
||||
if (lang === 'midi-widget') {
|
||||
try {
|
||||
var mwRaw = trimmed.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/gi,'"').replace(/'/g,"'");
|
||||
var mwData = JSON.parse(mwRaw);
|
||||
var mwFilename = mwData.filename || (mwData.saved_to ? mwData.saved_to.split('/').pop() : 'score.mid');
|
||||
return buildMidiPickerWidget(mwData, mwFilename).html;
|
||||
} catch(e) {
|
||||
return '<pre class="md-code-block"><code>' + escHtml(trimmed) + '</code></pre>';
|
||||
}
|
||||
}
|
||||
if (lang === 'abc' || lang === 'lilypond') {
|
||||
var encoded = encodeURIComponent(trimmed);
|
||||
var widgetId = 'music-' + Math.random().toString(36).slice(2, 9);
|
||||
return '<div class="music-widget" id="' + widgetId + '">' +
|
||||
'<div class="music-widget-header">' +
|
||||
'<span class="music-widget-label">🎵 ' + (lang === 'abc' ? 'ABC Notation' : 'LilyPond') + '</span>' +
|
||||
'<div style="display:flex;gap:6px;align-items:center">' +
|
||||
'<button class="music-render-btn" onclick="renderMusicBlock(\'' + widgetId + '\', decodeURIComponent(\'' + encoded + '\'))">악보 렌더링</button>' +
|
||||
'<button onclick="toggleMusicWidget(\'' + widgetId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="접기/펼치기">▾</button>' +
|
||||
'<button onclick="closeMusicWidget(\'' + widgetId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="닫기">✕</button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="music-widget-body">' +
|
||||
'<pre class="md-code-block music-source" style="margin:0;border-radius:0;border:none;border-bottom:1px solid var(--line);max-height:120px;overflow-y:auto;font-size:11px"><code>' + escHtml(trimmed) + '</code></pre>' +
|
||||
'<div class="music-output" style="display:none"></div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
if (lang === 'tradingview') {
|
||||
var tvSymbol = '', tvInterval = 'D';
|
||||
// code content is already HTML-escaped at this point — unescape before parsing
|
||||
var tvRaw = trimmed.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/gi,'"').replace(/'/g,"'").trim();
|
||||
if (tvRaw.startsWith('{')) {
|
||||
try {
|
||||
var tvJson = JSON.parse(tvRaw);
|
||||
tvSymbol = (tvJson.symbol || tvJson.SYMBOL || '').toString().toUpperCase();
|
||||
tvInterval = (tvJson.interval || tvJson.INTERVAL || 'D').toString().toUpperCase();
|
||||
} catch(e) { tvSymbol = tvRaw.split('|')[0].trim().toUpperCase(); }
|
||||
} else {
|
||||
var parts = tvRaw.split('|');
|
||||
tvSymbol = (parts[0] || '').trim().toUpperCase();
|
||||
tvInterval = (parts[1] || 'D').trim().toUpperCase();
|
||||
}
|
||||
if (!tvSymbol) return '<pre class="md-code-block"><code>' + trimmed + '</code></pre>';
|
||||
var tvId = 'tv-' + Math.random().toString(36).slice(2, 9);
|
||||
return '<div class="music-widget" id="' + tvId + '">' +
|
||||
'<div class="music-widget-header">' +
|
||||
'<span class="music-widget-label">📈 ' + escHtml(tvSymbol) + ' · ' + escHtml(tvInterval) + '</span>' +
|
||||
'<div style="display:flex;gap:6px;align-items:center">' +
|
||||
'<button class="music-render-btn" onclick="renderTVChart(this,\'' + tvId + '-c\',\'' + escHtml(tvSymbol) + '\',\'' + escHtml(tvInterval) + '\')">📈 차트 불러오기</button>' +
|
||||
'<button onclick="toggleMusicWidget(\'' + tvId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="접기/펼치기">▾</button>' +
|
||||
'<button onclick="closeMusicWidget(\'' + tvId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="닫기">✕</button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="music-widget-body">' +
|
||||
'<div id="' + tvId + '-c" style="height:440px;width:100%"></div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
if (lang === 'kstock') {
|
||||
var ksRaw = trimmed.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').trim();
|
||||
var ksParts = ksRaw.split('|');
|
||||
var ksCode = ksParts[0].trim().replace(/\D/g,''); // 숫자만 (005930)
|
||||
var ksPeriod = (ksParts[1] || 'day').trim().toLowerCase();
|
||||
var ksPeriodMap = { '1d':'day','day':'day','1w':'week','week':'week','1m':'month','month':'month','3m':'3month','3month':'3month','1y':'year','year':'year','3y':'3year','3year':'3year' };
|
||||
var ksNaverPeriod = ksPeriodMap[ksPeriod] || 'day';
|
||||
var ksPeriodLabel = { day:'일봉', week:'주봉', month:'월봉', '3month':'3개월', year:'1년', '3year':'3년' }[ksNaverPeriod] || ksNaverPeriod;
|
||||
if (!ksCode) return '<pre class="md-code-block"><code>' + trimmed + '</code></pre>';
|
||||
var ksId = 'ks-' + Math.random().toString(36).slice(2, 9);
|
||||
var ksImgUrl = 'https://ssl.pstatic.net/imgfinance/chart/item/area/' + ksNaverPeriod + '/' + ksCode + '.png';
|
||||
var ksNaverUrl = 'https://finance.naver.com/item/main.naver?code=' + ksCode;
|
||||
return '<div class="music-widget" id="' + ksId + '">' +
|
||||
'<div class="music-widget-header">' +
|
||||
'<span class="music-widget-label">📈 ' + escHtml(ksCode) + ' · ' + escHtml(ksPeriodLabel) + ' · 네이버금융</span>' +
|
||||
'<div style="display:flex;gap:6px;align-items:center">' +
|
||||
'<a href="' + ksNaverUrl + '" target="_blank" style="font-size:12px;color:var(--muted);text-decoration:none">네이버금융 ↗</a>' +
|
||||
'<button onclick="toggleMusicWidget(\'' + ksId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="접기/펼치기">▾</button>' +
|
||||
'<button onclick="closeMusicWidget(\'' + ksId + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="닫기">✕</button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="music-widget-body" style="padding:8px;text-align:center">' +
|
||||
'<img src="' + ksImgUrl + '" alt="' + escHtml(ksCode) + ' 차트" style="max-width:100%;border-radius:4px" onerror="this.parentNode.innerHTML=\'<span style=\\\"color:var(--muted);font-size:13px\\\">차트를 불러올 수 없습니다.</span>\'">' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
if (lang === 'smiles') {
|
||||
// Also undo escHtml()'s backslash/backtick/$ escaping (not just the amp/lt/gt/quote
|
||||
// set the other widget blocks unescape) — SMILES cis/trans bond notation uses
|
||||
// backslash (e.g. C/C=C/C), which would otherwise stay mangled as \.
|
||||
var smRaw = trimmed.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/gi,'"').replace(/'/g,"'").replace(/`/g,'`').replace(/$/g,'$').replace(/\/g,'\\').trim();
|
||||
if (!smRaw) return '<pre class="md-code-block"><code>' + trimmed + '</code></pre>';
|
||||
// Textbook-style: no header/button chrome, auto-rendered by renderSmilesIn() right
|
||||
// after insertion (mirrors renderKatexIn — innerHTML doesn't run embedded <script>,
|
||||
// so *something* has to trigger the draw call after the SVG lands in the DOM).
|
||||
var smId = 'sm-' + Math.random().toString(36).slice(2, 9);
|
||||
var smSize = smilesSizeFor(smRaw);
|
||||
return '<span class="smiles-inline" data-smiles="' + escHtml(smRaw) + '">' +
|
||||
'<svg id="' + smId + '" width="' + smSize.width + '" height="' + smSize.height + '"></svg>' +
|
||||
'</span>';
|
||||
}
|
||||
return '<pre class="md-code-block"><code>' + trimmed + '</code></pre>';
|
||||
})();
|
||||
var phIdx = codeBlockPlaceholders.length;
|
||||
codeBlockPlaceholders.push(result);
|
||||
return '\x00CODEBLK' + phIdx + '\x00';
|
||||
});
|
||||
|
||||
// Inline code — same escHtml()-escapes-backticks issue as the fenced code blocks above.
|
||||
// Content may still contain other entities (&, <, ...), so only exclude another
|
||||
// ` sequence rather than excluding every '&' (which would truncate on those entities).
|
||||
html = html.replace(/`((?:(?!`)[\s\S])+?)`/g, '<code class="md-inline-code">$1</code>');
|
||||
|
||||
// Images: 
|
||||
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, function(_, alt, url) {
|
||||
var safeAlt = alt.replace(/"/g, '"');
|
||||
var errAlt = (alt || '이미지').replace(/'/g, ''').replace(/</g, '<');
|
||||
var onerr = "this.onerror=null;this.style.display='none';this.insertAdjacentHTML('afterend','<span class="md-img-err">✖ " + errAlt + "를 불러올 수 없습니다.</span>')";
|
||||
return '<img class="md-img" src="' + url + '" alt="' + safeAlt + '" loading="lazy" onclick="openImageZoom(this.src)" onerror="' + onerr + '" />';
|
||||
});
|
||||
|
||||
// Links: [text](url) — render download links for file types as buttons, PPTX gets preview
|
||||
html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, function(_, text, url) {
|
||||
return _renderLinkButton(text, url, opts);
|
||||
});
|
||||
|
||||
// Bare /api/files/... URLs — auto-convert to download buttons even without markdown syntax
|
||||
html = html.replace(/(\s|^)(\/api\/files\/[^\s<"]+)/g, function(_, space, url) {
|
||||
return space + _renderLinkButton(decodeURIComponent(url.split('/').pop() || 'download'), url, opts);
|
||||
});
|
||||
|
||||
// YouTube URLs on their own line → inline iframe
|
||||
html = html.replace(/((?:^|\n)[ \t]*)(https?:\/\/(?:(?:www\.|m\.)?youtube\.com\/(?:watch|shorts|embed)|youtu\.be\/)[^\s<>")\n]*)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) {
|
||||
var embedUrl = youtubeToEmbedUrl(url);
|
||||
if (!embedUrl) return m;
|
||||
var safeEmbed = embedUrl.replace(/"/g, '"');
|
||||
var safeOrig = url.replace(/"/g, '"');
|
||||
return pre + '<div class="yt-embed-wrap"><iframe class="yt-embed" src="' + safeEmbed + '" allowfullscreen allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" loading="lazy"></iframe><div class="map-embed-link"><a href="' + safeOrig + '" target="_blank" rel="noopener">YouTube에서 열기 ↗</a></div></div>' + post;
|
||||
});
|
||||
|
||||
// Google Maps URLs on their own line → inline iframe
|
||||
html = html.replace(/((?:^|\n)[ \t]*)(https?:\/\/(?:www\.google\.com\/maps|maps\.google\.com|goo\.gl\/maps)[^\s<>")\n]*)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) {
|
||||
var embedUrl = mapsToEmbedUrl(url);
|
||||
if (!embedUrl) return m;
|
||||
var safeEmbed = embedUrl.replace(/"/g, '"');
|
||||
var safeOrig = url.replace(/"/g, '"');
|
||||
return pre + '<div class="map-embed-wrap"><iframe class="map-embed" src="' + safeEmbed + '" allowfullscreen loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe><div class="map-embed-link"><a href="' + safeOrig + '" target="_blank" rel="noopener">Google 지도에서 열기 ↗</a></div></div>' + post;
|
||||
});
|
||||
|
||||
// Windy URLs in <img src="..."> (model used  syntax) → inline iframe [must run first]
|
||||
html = html.replace(/<img\s[^>]*src="(https?:\/\/(?:embed\.windy\.com|(?:www\.)?windy\.com)[^"]*)"[^>]*\/?>/gi, function(m, url) {
|
||||
var embedUrl = windyToEmbedUrl(url);
|
||||
if (!embedUrl) return m;
|
||||
var safeEmbed = embedUrl.replace(/"/g, '"');
|
||||
var safeOrig = url.replace(/"/g, '"');
|
||||
return '<div class="windy-embed-wrap"><iframe class="windy-embed" src="' + safeEmbed + '" allowfullscreen loading="lazy"></iframe><div class="map-embed-link"><a href="' + safeOrig + '" target="_blank" rel="noopener">Windy에서 열기 ↗</a></div></div>';
|
||||
});
|
||||
|
||||
// Windy URLs inside anchor tags (markdown links) → inline iframe [must run BEFORE bare-URL regex]
|
||||
html = html.replace(/<a\s[^>]*href="(https?:\/\/(?:embed\.windy\.com|(?:www\.)?windy\.com)[^"]*)"[^>]*>[^<]*<\/a>/gi, function(m, url) {
|
||||
var embedUrl = windyToEmbedUrl(url);
|
||||
if (!embedUrl) return m;
|
||||
var safeEmbed = embedUrl.replace(/"/g, '"');
|
||||
var safeOrig = url.replace(/"/g, '"');
|
||||
return '<div class="windy-embed-wrap"><iframe class="windy-embed" src="' + safeEmbed + '" allowfullscreen loading="lazy"></iframe><div class="map-embed-link"><a href="' + safeOrig + '" target="_blank" rel="noopener">Windy에서 열기 ↗</a></div></div>';
|
||||
});
|
||||
|
||||
// Windy URLs on their own line → inline iframe [runs after anchor regex to avoid double-render]
|
||||
html = html.replace(/((?:^|\n)[ \t]*)(https?:\/\/(?:embed\.windy\.com|(?:www\.)?windy\.com)[^\s<>")\n]*)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) {
|
||||
var embedUrl = windyToEmbedUrl(url);
|
||||
if (!embedUrl) return m;
|
||||
var safeEmbed = embedUrl.replace(/"/g, '"');
|
||||
var safeOrig = url.replace(/"/g, '"');
|
||||
return pre + '<div class="windy-embed-wrap"><iframe class="windy-embed" src="' + safeEmbed + '" allowfullscreen loading="lazy"></iframe><div class="map-embed-link"><a href="' + safeOrig + '" target="_blank" rel="noopener">Windy에서 열기 ↗</a></div></div>' + post;
|
||||
});
|
||||
|
||||
// Bare image URLs on their own line → inline image
|
||||
html = html.replace(/((?:^|\n)[ \t]*)(https?:\/\/[^\s<>"()\n#?]+\.(?:jpe?g|png|gif|webp|svg|bmp|avif|tiff)(?:[?#][^\s<>"()\n]*)?)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) {
|
||||
var onerr = "this.onerror=null;this.style.display='none';this.insertAdjacentHTML('afterend','<span class="md-img-err">✖ 이미지를 불러올 수 없습니다.</span>')";
|
||||
return pre + '<img class="md-img" src="' + url + '" alt="" loading="lazy" onclick="openImageZoom(this.src)" onerror="' + onerr + '" />' + post;
|
||||
});
|
||||
|
||||
// Bold
|
||||
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
||||
|
||||
// Italic
|
||||
html = html.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g, '<em>$1</em>');
|
||||
|
||||
// Markdown tables → HTML (line-by-line, O(n), must run BEFORE \n → <br>)
|
||||
(function() {
|
||||
var lines = html.split('\n');
|
||||
var out = [];
|
||||
var parseRow = function(line) {
|
||||
var cells = line.trim().split('|');
|
||||
if (cells.length && cells[0].trim() === '') cells.shift();
|
||||
if (cells.length && cells[cells.length - 1].trim() === '') cells.pop();
|
||||
return cells.map(function(c) { return c.trim(); });
|
||||
};
|
||||
var isSep = function(line) { return /^\|[\s|:\-]+\|[ \t]*$/.test(line.trim()); };
|
||||
var isRow = function(line) { return /^\|.+\|[ \t]*$/.test(line.trim()); };
|
||||
var i = 0;
|
||||
while (i < lines.length) {
|
||||
var line = lines[i];
|
||||
if (isRow(line) && i + 1 < lines.length && isSep(lines[i + 1])) {
|
||||
var tbl = [line, lines[i + 1]];
|
||||
var j = i + 2;
|
||||
while (j < lines.length && isRow(lines[j])) { tbl.push(lines[j]); j++; }
|
||||
var headers = parseRow(tbl[0]);
|
||||
var thead = '<thead><tr>' + headers.map(function(h) { return '<th>' + h + '</th>'; }).join('') + '</tr></thead>';
|
||||
var tbody = '<tbody>' + tbl.slice(2).map(function(row) {
|
||||
return '<tr>' + parseRow(row).map(function(c) { return '<td>' + c + '</td>'; }).join('') + '</tr>';
|
||||
}).join('') + '</tbody>';
|
||||
out.push('<div class="md-table-wrap"><table class="md-table">' + thead + tbody + '</table></div>');
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
out.push(line);
|
||||
i++;
|
||||
}
|
||||
html = out.join('\n');
|
||||
})();
|
||||
|
||||
// Restore widget HTML stashed before the link/image/bold/table passes above.
|
||||
codeBlockPlaceholders.forEach(function(blockHtml, i) {
|
||||
html = html.replace('\x00CODEBLK' + i + '\x00', function() { return blockHtml; });
|
||||
});
|
||||
|
||||
// Line breaks
|
||||
html = html.replace(/\n/g, '<br>');
|
||||
|
||||
return html;
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
// media.js — rich media widgets extracted from helpers.js.
|
||||
// smiles (chemistry), tradingview (charts), music/MIDI (midiRouter + widgets).
|
||||
// Referenced via inline onclick strings generated by renderMarkdown (markdown.js).
|
||||
function renderTVChart(btn, containerId, symbol, interval) {
|
||||
btn.disabled = true;
|
||||
btn.textContent = '로딩 중...';
|
||||
var isDark = document.documentElement.getAttribute('data-theme') !== 'light';
|
||||
function doInit() {
|
||||
try {
|
||||
new TradingView.widget({
|
||||
container_id: containerId,
|
||||
autosize: true,
|
||||
symbol: symbol,
|
||||
interval: interval || 'D',
|
||||
timezone: 'Asia/Seoul',
|
||||
theme: isDark ? 'dark' : 'light',
|
||||
style: '1',
|
||||
locale: 'kr',
|
||||
enable_publishing: false,
|
||||
allow_symbol_change: true,
|
||||
save_image: false,
|
||||
withdateranges: true,
|
||||
hide_side_toolbar: false,
|
||||
studies: ['RSI@tv-basicstudies', 'MACD@tv-basicstudies'],
|
||||
});
|
||||
btn.style.display = 'none';
|
||||
} catch(e) {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '📈 차트 불러오기';
|
||||
}
|
||||
}
|
||||
if (window.TradingView && window.TradingView.widget) {
|
||||
doInit();
|
||||
} else {
|
||||
var s = document.createElement('script');
|
||||
s.src = 'https://s3.tradingview.com/tv.js';
|
||||
s.onload = doInit;
|
||||
s.onerror = function() { btn.disabled = false; btn.textContent = '📈 차트 불러오기'; };
|
||||
document.head.appendChild(s);
|
||||
}
|
||||
}
|
||||
|
||||
// Fixed 180x130 was tuned for benzene-sized rings and left bigger molecules (e.g.
|
||||
// cholesterol's 4 fused rings + side chain) cramped/illegible. Scale the canvas with a
|
||||
// rough heavy-atom count from the raw SMILES so the figure stays roomy either way.
|
||||
function smilesSizeFor(smiles) {
|
||||
var atomCount = (smiles.match(/Cl|Br|\[[^\]]+\]|[BCNOFPSIbcnops]/g) || []).length;
|
||||
var extra = Math.max(0, atomCount - 6);
|
||||
var width = Math.min(420, 180 + extra * 8);
|
||||
var height = Math.min(320, 130 + extra * 6);
|
||||
return { width: width, height: height };
|
||||
}
|
||||
|
||||
// SMILES → 2D 화학 구조식 (결합선 포함). SmilesDrawer는 로컬 캔버스 렌더링이라
|
||||
// 네트워크 지연 없이 즉시 그려지지만, innerHTML로 삽입된 <canvas>는 아직 DOM에
|
||||
// 붙기 전이라 위젯 코드 블록에서 바로 그릴 수 없음 — 버튼 클릭으로 트리거.
|
||||
// Auto-renders every not-yet-rendered .smiles-inline in `container` — mirrors
|
||||
// renderKatexIn(): innerHTML doesn't execute embedded <script>, so something has to
|
||||
// walk the freshly-inserted DOM and trigger the actual draw call. Small textbook-style
|
||||
// figure, no header/button chrome (see the 'smiles' code-block case in renderMarkdown).
|
||||
function renderSmilesIn(container) {
|
||||
if (!window.SmilesDrawer || !container) return;
|
||||
var isDark = document.documentElement.getAttribute('data-theme') !== 'light';
|
||||
var nodes = container.querySelectorAll('.smiles-inline:not([data-rendered])');
|
||||
nodes.forEach(function(el) {
|
||||
var smiles = el.getAttribute('data-smiles');
|
||||
var svg = el.querySelector('svg');
|
||||
if (!smiles || !svg) return;
|
||||
el.setAttribute('data-rendered', '1');
|
||||
try {
|
||||
SmilesDrawer.parse(smiles, function(tree) {
|
||||
try {
|
||||
var smSize = smilesSizeFor(smiles);
|
||||
var drawer = new SmilesDrawer.SvgDrawer({ width: smSize.width, height: smSize.height });
|
||||
drawer.draw(tree, svg.id, isDark ? 'dark' : 'light');
|
||||
} catch (e) {
|
||||
el.innerHTML = '<span style="font-size:11px;color:var(--muted)" title="' + smiles + '">⚠️ 구조식 렌더링 실패</span>';
|
||||
}
|
||||
}, function() {
|
||||
el.innerHTML = '<span style="font-size:11px;color:var(--muted)" title="' + smiles + '">⚠️ SMILES 파싱 실패</span>';
|
||||
});
|
||||
} catch (e) {}
|
||||
});
|
||||
}
|
||||
|
||||
function toggleMusicWidget(widgetId) {
|
||||
var widget = document.getElementById(widgetId);
|
||||
if (!widget) return;
|
||||
// widgetId may point to either .music-widget or .music-widget-body
|
||||
var body = widget.classList.contains('music-widget-body')
|
||||
? widget
|
||||
: widget.querySelector('.music-widget-body');
|
||||
var btn = widget.classList.contains('music-widget-body')
|
||||
? widget.closest('.music-widget')?.querySelector('[title="접기/펼치기"]')
|
||||
: widget.querySelector('[title="접기/펼치기"]');
|
||||
if (!body) return;
|
||||
var collapsed = body.classList.toggle('collapsed');
|
||||
if (btn) btn.textContent = collapsed ? '▸' : '▾';
|
||||
}
|
||||
|
||||
function closeMusicWidget(widgetId) {
|
||||
var el = document.getElementById(widgetId);
|
||||
if (!el) return;
|
||||
var widget = el.closest('.music-widget') || el;
|
||||
widget.remove();
|
||||
}
|
||||
|
||||
// ── Web MIDI router ──────────────────────────────────────────────────────────
|
||||
const midiRouter = {
|
||||
access: null,
|
||||
timers: [],
|
||||
isPlaying: false,
|
||||
|
||||
stop() {
|
||||
this.timers.forEach(t => clearTimeout(t));
|
||||
this.timers = [];
|
||||
this.isPlaying = false;
|
||||
if (this.access) {
|
||||
this.access.outputs.forEach(out => {
|
||||
for (let ch = 0; ch < 16; ch++) {
|
||||
try { out.send([0xB0 | ch, 123, 0]); } catch {} // All Notes Off
|
||||
try { out.send([0xB0 | ch, 121, 0]); } catch {} // Reset All Controllers
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
// Parse raw MIDI bytes → scheduled events list
|
||||
// Returns [{timeMs, msg:[...bytes]}, ...]
|
||||
_parseMidiRaw(buf) {
|
||||
const u8 = new Uint8Array(buf);
|
||||
const dv = new DataView(buf);
|
||||
if (dv.getUint32(0) !== 0x4D546864) return []; // not MThd
|
||||
const tpq = dv.getUint16(12);
|
||||
const ntrk = dv.getUint16(10);
|
||||
let tempo = 500000;
|
||||
const events = [];
|
||||
|
||||
const readVarLen = (pos) => {
|
||||
let val = 0, b;
|
||||
do { b = u8[pos++]; val = (val << 7) | (b & 0x7F); } while (b & 0x80);
|
||||
return { val, pos };
|
||||
};
|
||||
const ticksToMs = (ticks) => (ticks / tpq) * (tempo / 1000);
|
||||
|
||||
let p = 14;
|
||||
for (let t = 0; t < ntrk; t++) {
|
||||
if (p + 8 > u8.length || dv.getUint32(p) !== 0x4D54726B) break;
|
||||
const tlen = dv.getUint32(p + 4);
|
||||
p += 8;
|
||||
const end = p + tlen;
|
||||
let tick = 0, rs = 0;
|
||||
while (p < end) {
|
||||
const dl = readVarLen(p); p = dl.pos; tick += dl.val;
|
||||
let b = u8[p];
|
||||
if (b & 0x80) { rs = b; p++; } else { b = rs; }
|
||||
const typ = b & 0xF0, ch = b & 0x0F;
|
||||
const ms = ticksToMs(tick);
|
||||
if (typ === 0x90 || typ === 0x80) {
|
||||
const note = u8[p++], vel = u8[p++];
|
||||
events.push({ ms, msg: [typ | ch, note, vel] });
|
||||
} else if (typ === 0xA0 || typ === 0xB0 || typ === 0xE0) {
|
||||
events.push({ ms, msg: [b, u8[p], u8[p+1]] }); p += 2;
|
||||
} else if (typ === 0xC0) {
|
||||
events.push({ ms, msg: [0xC0 | ch, u8[p++]] });
|
||||
} else if (typ === 0xD0) {
|
||||
events.push({ ms, msg: [b, u8[p++]] });
|
||||
} else if (b === 0xFF) {
|
||||
const mt = u8[p++];
|
||||
const ll = readVarLen(p); p = ll.pos;
|
||||
if (mt === 0x51 && ll.val >= 3) {
|
||||
// Tempo change: recalculate from current tick
|
||||
tempo = (u8[p] << 16) | (u8[p+1] << 8) | u8[p+2];
|
||||
}
|
||||
p += ll.val;
|
||||
} else if (b === 0xF0 || b === 0xF7) {
|
||||
const ll = readVarLen(p); p = ll.pos + ll.val;
|
||||
} else { p++; }
|
||||
}
|
||||
p = end;
|
||||
}
|
||||
events.sort((a, b) => a.ms - b.ms);
|
||||
return events;
|
||||
},
|
||||
|
||||
async play(midiUrl, outputId, onStatus) {
|
||||
this.stop();
|
||||
const output = this.access.outputs.get(outputId);
|
||||
if (!output) throw new Error('기기를 찾을 수 없습니다');
|
||||
|
||||
if (onStatus) onStatus('로딩 중...');
|
||||
const resp = await fetch(midiUrl);
|
||||
const buf = await resp.arrayBuffer();
|
||||
|
||||
// Parse raw MIDI for exact Program Change + all events
|
||||
const events = this._parseMidiRaw(buf);
|
||||
if (!events.length) throw new Error('MIDI 파싱 실패');
|
||||
|
||||
// GM Reset SysEx → 신디를 GM 모드로 초기화
|
||||
try { output.send(new Uint8Array([0xF0, 0x7E, 0x7F, 0x09, 0x01, 0xF7])); } catch {}
|
||||
|
||||
// Send all PC + Bank Select (CC#0=0, CC#32=0) events upfront
|
||||
const initPc = new Set();
|
||||
events.forEach(ev => {
|
||||
if ((ev.msg[0] & 0xF0) === 0xC0 && !initPc.has(ev.msg[0] & 0x0F)) {
|
||||
initPc.add(ev.msg[0] & 0x0F);
|
||||
const ch = ev.msg[0] & 0x0F;
|
||||
try { output.send(new Uint8Array([0xB0 | ch, 0, 0])); } catch {} // Bank Select MSB=0
|
||||
try { output.send(new Uint8Array([0xB0 | ch, 32, 0])); } catch {} // Bank Select LSB=0
|
||||
try { output.send(new Uint8Array(ev.msg)); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
const NOTE_DELAY = 200; // ms — give synth time to process GM reset + PCs
|
||||
const totalMs = events[events.length - 1].ms + NOTE_DELAY + 500;
|
||||
this.isPlaying = true;
|
||||
if (onStatus) onStatus('재생 중...');
|
||||
|
||||
events.forEach(ev => {
|
||||
this.timers.push(setTimeout(() => {
|
||||
if (!this.isPlaying) return;
|
||||
try { output.send(new Uint8Array(ev.msg)); } catch {}
|
||||
}, ev.ms + NOTE_DELAY));
|
||||
});
|
||||
|
||||
this.timers.push(setTimeout(() => {
|
||||
this.isPlaying = false;
|
||||
if (onStatus) onStatus('완료');
|
||||
}, totalMs));
|
||||
}
|
||||
};
|
||||
|
||||
async function midiRouterToggle(routerId, btnId) {
|
||||
const panel = document.getElementById(routerId);
|
||||
if (!panel) { alert('패널을 찾을 수 없습니다: ' + routerId); return; }
|
||||
const isHidden = panel.style.display === 'none' || panel.style.display === '';
|
||||
if (isHidden) {
|
||||
panel.style.display = 'flex';
|
||||
panel.style.flexWrap = 'wrap';
|
||||
panel.style.gap = '6px';
|
||||
panel.style.alignItems = 'center';
|
||||
const sel = document.getElementById(routerId + '-sel');
|
||||
const st = document.getElementById(routerId + '-st');
|
||||
try {
|
||||
if (!navigator.requestMIDIAccess) throw new Error('Web MIDI 미지원 — Chrome/Edge 필요');
|
||||
if (!midiRouter.access) {
|
||||
midiRouter.access = await navigator.requestMIDIAccess();
|
||||
}
|
||||
if (sel) {
|
||||
sel.innerHTML = '<option value="">-- MIDI 기기 선택 --</option>';
|
||||
midiRouter.access.outputs.forEach((out, id) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = id; opt.textContent = out.name; sel.appendChild(opt);
|
||||
});
|
||||
if (sel.options.length <= 1 && st) st.textContent = 'MIDI 출력 기기 없음';
|
||||
}
|
||||
} catch (e) {
|
||||
if (st) st.textContent = '오류: ' + e.message;
|
||||
}
|
||||
} else {
|
||||
panel.style.display = 'none';
|
||||
midiRouter.stop();
|
||||
}
|
||||
}
|
||||
|
||||
async function midiRouterPlay(routerId, midiUrl) {
|
||||
const sel = document.getElementById(routerId + '-sel');
|
||||
const st = document.getElementById(routerId + '-st');
|
||||
const outputId = sel ? sel.value : '';
|
||||
if (!outputId) { if (st) st.textContent = '기기를 선택하세요'; return; }
|
||||
try {
|
||||
await midiRouter.play(midiUrl, outputId, msg => { if (st) st.textContent = msg; });
|
||||
} catch (e) { if (st) st.textContent = '오류: ' + e.message; }
|
||||
}
|
||||
|
||||
function midiRouterStop(routerId) {
|
||||
midiRouter.stop();
|
||||
const st = document.getElementById(routerId + '-st');
|
||||
if (st) st.textContent = '정지';
|
||||
}
|
||||
|
||||
function buildMusicActions(data, downloadName) {
|
||||
var midiUrl = data.midi_url;
|
||||
var pdfUrl = data.pdf_url;
|
||||
var rid = 'mr-' + Math.random().toString(36).slice(2, 10);
|
||||
var html = '<div class="music-actions">';
|
||||
if (data.saved_to) {
|
||||
html += '<div style="font-size:11px;color:var(--muted);margin-bottom:6px;width:100%">💾 ' + escHtml(data.saved_to) + '</div>';
|
||||
}
|
||||
if (midiUrl) {
|
||||
html += '<div class="midi-router-panel" id="' + rid + '" style="display:none;margin-bottom:4px">'
|
||||
+ '<select class="midi-router-sel" id="' + rid + '-sel" style="font-size:11px;padding:2px 6px;border:1px solid var(--line);border-radius:6px"><option value="">-- MIDI 기기 선택 --</option></select>'
|
||||
+ '<button class="music-page-btn" onclick="midiRouterPlay(\'' + rid + '\',\'' + midiUrl + '\')">▶</button>'
|
||||
+ '<button class="music-page-btn" onclick="midiRouterStop(\'' + rid + '\')">■</button>'
|
||||
+ '<span style="font-size:11px;color:var(--muted)" id="' + rid + '-st"></span>'
|
||||
+ '</div>';
|
||||
html += '<button class="music-dl-btn btn-green" id="' + rid + '-btn" onclick="midiRouterToggle(\'' + rid + '\',\'' + rid + '-btn\')">▶ 외부 신디</button>';
|
||||
html += '<button class="music-dl-btn btn-purple" onclick="window.open(\'/music-app.html?edit=\'+encodeURIComponent(\'' + midiUrl + '\'),\'_blank\',\'noopener,noreferrer\')">🎹 편집</button>';
|
||||
html += '<a class="music-dl-btn" href="' + midiUrl + '" download="' + escHtml(downloadName || 'score.midi') + '">⬇ MIDI</a>';
|
||||
}
|
||||
if (pdfUrl) html += '<a class="music-dl-btn" href="' + pdfUrl + '" download="score.pdf">⬇ PDF</a>';
|
||||
html += '</div>';
|
||||
return html;
|
||||
}
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
function buildSvgPagesHtml(data) {
|
||||
var pages = data.page_count || 1;
|
||||
var baseId = data.id;
|
||||
// Use a random suffix so duplicate renders in chat history never share the same navId
|
||||
var navId = 'music-nav-' + Math.random().toString(36).slice(2, 10);
|
||||
var src1 = pages === 1 ? data.svg_url : '/api/music/file/' + baseId + '/svg/1';
|
||||
|
||||
var nav = '';
|
||||
if (pages > 1) {
|
||||
nav = '<div class="music-page-nav" id="' + navId + '" data-page="1" data-total="' + pages + '" data-id="' + baseId + '">' +
|
||||
'<button class="music-page-btn" onclick="musicPageNav(\'' + navId + '\',-1)" id="' + navId + '-prev" disabled>◀</button>' +
|
||||
'<span id="' + navId + '-label">1 / ' + pages + '</span>' +
|
||||
'<button class="music-page-btn" onclick="musicPageNav(\'' + navId + '\',1)" id="' + navId + '-next"' + (pages <= 1 ? ' disabled' : '') + '>▶</button>' +
|
||||
'</div>';
|
||||
}
|
||||
return nav + '<img id="' + navId + '-img" src="' + src1 + '" alt="악보" style="width:100%;height:auto;background:#fff;border-radius:8px;padding:8px;display:block" />';
|
||||
}
|
||||
|
||||
function musicPageNav(navId, delta) {
|
||||
var nav = document.getElementById(navId);
|
||||
if (!nav) return;
|
||||
var cur = parseInt(nav.dataset.page, 10);
|
||||
var total = parseInt(nav.dataset.total, 10);
|
||||
var next = cur + delta;
|
||||
if (next < 1 || next > total) return;
|
||||
nav.dataset.page = String(next);
|
||||
var baseId = nav.dataset.id;
|
||||
var img = document.getElementById(navId + '-img');
|
||||
var lbl = document.getElementById(navId + '-label');
|
||||
var prev = document.getElementById(navId + '-prev');
|
||||
var nxt = document.getElementById(navId + '-next');
|
||||
var url = '/api/music/file/' + baseId + '/svg/' + next;
|
||||
if (img) img.src = url;
|
||||
if (lbl) lbl.textContent = next + ' / ' + total;
|
||||
if (prev) prev.disabled = next <= 1;
|
||||
if (nxt) nxt.disabled = next >= total;
|
||||
}
|
||||
|
||||
async function renderMusicBlock(widgetId, source) {
|
||||
var widget = document.getElementById(widgetId);
|
||||
if (!widget) return;
|
||||
var btn = widget.querySelector('.music-render-btn');
|
||||
var output = widget.querySelector('.music-output');
|
||||
if (btn) { btn.disabled = true; btn.textContent = '렌더링 중…'; }
|
||||
try {
|
||||
var data = await api('/api/music/render', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ source: source }),
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
|
||||
var html = buildSvgPagesHtml(data);
|
||||
html += buildMusicActions(data, 'score.midi');
|
||||
|
||||
if (output) {
|
||||
output.innerHTML = html;
|
||||
output.style.display = 'block';
|
||||
// Update chatHistory so the rendered output survives page reload
|
||||
persistActiveChat();
|
||||
}
|
||||
if (btn) { btn.textContent = '다시 렌더링'; btn.disabled = false; }
|
||||
} catch (e) {
|
||||
if (output) {
|
||||
output.innerHTML = '<span style="color:var(--err);font-size:12px">렌더링 실패: ' + escHtml(e.message) + '</span>';
|
||||
output.style.display = 'block';
|
||||
}
|
||||
if (btn) { btn.textContent = '악보 렌더링'; btn.disabled = false; }
|
||||
}
|
||||
}
|
||||
|
||||
// ─── MIDI 업로드 → 액션 피커 ──────────────────────────────────────────────────
|
||||
|
||||
function buildMidiPickerWidget(data, filename) {
|
||||
var wid = 'midi-' + Math.random().toString(36).slice(2, 10);
|
||||
var midiUrl = data.midi_url;
|
||||
var rid = 'mr-' + Math.random().toString(36).slice(2, 10);
|
||||
|
||||
var savedLine = data.saved_to
|
||||
? '<div style="font-size:11px;color:var(--muted);margin-bottom:8px">💾 ' + escHtml(data.saved_to) + '</div>'
|
||||
: '';
|
||||
|
||||
// MIDI player panel (hidden by default) — includes MIDI download
|
||||
var playerPanel =
|
||||
'<div id="' + rid + '" class="midi-router-panel" style="display:none;margin-top:8px">' +
|
||||
'<select class="midi-router-sel" id="' + rid + '-sel" style="font-size:11px;padding:2px 6px;border:1px solid var(--line);border-radius:6px"><option value="">-- MIDI 기기 선택 --</option></select>' +
|
||||
'<button class="music-page-btn" onclick="midiRouterPlay(\'' + rid + '\',\'' + midiUrl + '\')">▶</button>' +
|
||||
'<button class="music-page-btn" onclick="midiRouterStop(\'' + rid + '\')">■</button>' +
|
||||
'<a class="music-dl-btn" href="' + midiUrl + '" download="' + escHtml(filename) + '" style="padding:2px 8px;font-size:11px">⬇ MIDI</a>' +
|
||||
'<span style="font-size:11px;color:var(--muted)" id="' + rid + '-st"></span>' +
|
||||
'</div>';
|
||||
|
||||
// Score area — always hidden by default; content pre-filled if already rendered
|
||||
var scoreInner = (data.has_svg && data.svg_url)
|
||||
? buildSvgPagesHtml(data) + buildMusicActions(data, filename)
|
||||
: '';
|
||||
var scoreArea = '<div id="' + wid + '-score" style="margin-top:8px;display:none">' + scoreInner + '</div>';
|
||||
|
||||
var scoreBtnLabel = '🎼 악보';
|
||||
|
||||
var html =
|
||||
'<div class="music-widget" id="' + wid + '">' +
|
||||
'<div class="music-widget-header">' +
|
||||
'<span class="music-widget-label">🎵 ' + escHtml(filename) + '</span>' +
|
||||
'<div style="display:flex;gap:6px;align-items:center">' +
|
||||
'<button onclick="toggleMusicWidget(\'' + wid + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="접기/펼치기">▾</button>' +
|
||||
'<button onclick="closeMusicWidget(\'' + wid + '\')" style="background:none;border:none;cursor:pointer;font-size:14px;color:var(--muted);padding:2px 4px" title="닫기">✕</button>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="music-widget-body"><div class="music-output">' +
|
||||
savedLine +
|
||||
'<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">' +
|
||||
'<button class="music-dl-btn btn-green" onclick="midiRouterToggle(\'' + rid + '\',\'' + rid + '\')">▶ 재생</button>' +
|
||||
'<button class="music-dl-btn btn-purple" onclick="window.open(\'/music-app.html?edit=\'+encodeURIComponent(\'' + midiUrl + '\'),\'_blank\',\'noopener,noreferrer\')">🎹 편집</button>' +
|
||||
'<button class="music-dl-btn btn-amber" id="' + wid + '-score-btn" onclick="midiPickerScore(\'' + wid + '\',\'' + data.id + '\',\'' + escHtml(filename) + '\')">' + scoreBtnLabel + '</button>' +
|
||||
'</div>' +
|
||||
playerPanel +
|
||||
scoreArea +
|
||||
'</div></div>' +
|
||||
'</div>';
|
||||
return { wid, html };
|
||||
}
|
||||
|
||||
async function midiPickerScore(wid, midiId, filename) {
|
||||
var scoreDiv = document.getElementById(wid + '-score');
|
||||
var btn = document.getElementById(wid + '-score-btn');
|
||||
if (!scoreDiv) return;
|
||||
|
||||
// If score already rendered, toggle visibility
|
||||
if (scoreDiv.style.display !== 'none' && scoreDiv.innerHTML.trim()) {
|
||||
scoreDiv.style.display = 'none';
|
||||
if (btn) btn.textContent = '📄 악보';
|
||||
return;
|
||||
}
|
||||
if (scoreDiv.innerHTML.trim()) {
|
||||
scoreDiv.style.display = '';
|
||||
if (btn) btn.textContent = '📄 닫기';
|
||||
return;
|
||||
}
|
||||
|
||||
// Show progress
|
||||
scoreDiv.style.display = '';
|
||||
scoreDiv.innerHTML = '<div style="font-size:12px;color:var(--muted);padding:8px 0">📄 악보 변환 중... <span id="' + wid + '-sprog"></span></div>';
|
||||
if (btn) btn.disabled = true;
|
||||
|
||||
try {
|
||||
var resp = await fetch('/api/music/midi-score', {
|
||||
method: 'POST',
|
||||
headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
|
||||
body: JSON.stringify({ id: midiId }),
|
||||
});
|
||||
if (!resp.ok || !resp.body) throw new Error('서버 오류 ' + resp.status);
|
||||
var reader = resp.body.getReader(), decoder = new TextDecoder(), buf = '';
|
||||
|
||||
while (true) {
|
||||
var chunk = await reader.read();
|
||||
if (chunk.done) break;
|
||||
buf += decoder.decode(chunk.value, { stream: true });
|
||||
var parts = buf.split('\n\n'); buf = parts.pop() || '';
|
||||
for (var i = 0; i < parts.length; i++) {
|
||||
if (!parts[i].startsWith('data: ')) continue;
|
||||
var ev; try { ev = JSON.parse(parts[i].slice(6)); } catch { continue; }
|
||||
if (ev.type === 'progress') {
|
||||
var sp = document.getElementById(wid + '-sprog'); if (sp) sp.textContent = ev.message;
|
||||
} else if (ev.type === 'done') {
|
||||
scoreDiv.innerHTML = buildSvgPagesHtml(ev) + buildMusicActions(ev, filename);
|
||||
if (btn) { btn.disabled = false; btn.textContent = '📄 닫기'; }
|
||||
} else if (ev.type === 'error') {
|
||||
scoreDiv.innerHTML = '<span style="color:var(--err);font-size:12px">악보 변환 실패: ' + escHtml(ev.message) + '</span>';
|
||||
if (btn) { btn.disabled = false; btn.textContent = '📄 악보'; }
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
scoreDiv.innerHTML = '<span style="color:var(--err);font-size:12px">오류: ' + escHtml(e.message) + '</span>';
|
||||
if (btn) { btn.disabled = false; btn.textContent = '📄 악보'; }
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadMidiAndRender(file) {
|
||||
var msgId = 'midi-upload-' + Date.now();
|
||||
appendChatBubble('system',
|
||||
'<div id="' + msgId + '" style="font-size:13px;color:var(--muted)">🎵 <strong>' + escHtml(file.name) + '</strong> 업로드 중...</div>'
|
||||
);
|
||||
try {
|
||||
var form = new FormData();
|
||||
form.append('file', file);
|
||||
var resp = await fetch('/api/music/midi', { method: 'POST', headers: authHeaders(), body: form });
|
||||
var data = await resp.json();
|
||||
if (!resp.ok) throw new Error(data.error || '서버 오류 ' + resp.status);
|
||||
|
||||
var result = buildMidiPickerWidget(data, file.name);
|
||||
var placeholder = document.getElementById(msgId);
|
||||
if (placeholder) placeholder.outerHTML = result.html;
|
||||
chatHistory.push({ role: 'widget', content: result.html });
|
||||
persistActiveChat();
|
||||
} catch (e) {
|
||||
var pl = document.getElementById(msgId);
|
||||
if (pl) pl.outerHTML = '<span style="color:var(--err);font-size:12px">업로드 실패: ' + escHtml(e.message) + '</span>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
// voice.js — TTS + mic/STT extracted from helpers.js.
|
||||
// Korean number normalization for speech, playTTSText/playTTSMsg/initTTSToggle,
|
||||
// mic recording (initAppVoice, toggleMicRecording, ...). Shares _appSendFn.
|
||||
var _speechRecog = null;
|
||||
var _isRecording = false;
|
||||
var _micAutosend = localStorage.getItem('micAutosend') !== 'false'; // default on
|
||||
|
||||
function updateMicAutosend() {
|
||||
_micAutosend = document.getElementById('mic-autosend-toggle').checked;
|
||||
localStorage.setItem('micAutosend', String(_micAutosend));
|
||||
}
|
||||
|
||||
function initMicAutosendToggle() {
|
||||
var toggle = document.getElementById('mic-autosend-toggle');
|
||||
if (toggle) toggle.checked = _micAutosend;
|
||||
}
|
||||
|
||||
function toggleMicRecording() {
|
||||
if (_isRecording) stopMicRecording();
|
||||
else startMicRecording();
|
||||
}
|
||||
|
||||
function startMicRecording() {
|
||||
var SpeechRecog = window.SpeechRecognition || window.webkitSpeechRecognition;
|
||||
if (!SpeechRecog) {
|
||||
alert('이 브라우저는 음성 인식을 지원하지 않습니다.\nChrome을 사용해주세요.');
|
||||
return;
|
||||
}
|
||||
_speechRecog = new SpeechRecog();
|
||||
_speechRecog.lang = 'ko-KR';
|
||||
_speechRecog.interimResults = false;
|
||||
_speechRecog.maxAlternatives = 1;
|
||||
_speechRecog.continuous = false;
|
||||
|
||||
var btn = document.getElementById('mic-btn');
|
||||
|
||||
_speechRecog.onstart = function() {
|
||||
_isRecording = true;
|
||||
if (btn) { btn.textContent = '⏹'; btn.title = '말하는 중… (클릭 시 중지)'; btn.classList.add('recording'); }
|
||||
};
|
||||
_speechRecog.onresult = function(e) {
|
||||
var transcript = e.results[0][0].transcript;
|
||||
var input = document.getElementById('chat-input');
|
||||
if (input && transcript) {
|
||||
input.value = (input.value ? input.value + ' ' : '') + transcript;
|
||||
input.focus();
|
||||
input.dispatchEvent(new Event('input'));
|
||||
if (_micAutosend) setTimeout(function() { (_appSendFn || handleSendStop)(); }, 50);
|
||||
}
|
||||
};
|
||||
_speechRecog.onerror = function(e) {
|
||||
if (e.error !== 'no-speech') alert('음성 인식 오류: ' + e.error);
|
||||
};
|
||||
_speechRecog.onend = function() {
|
||||
_isRecording = false;
|
||||
_speechRecog = null;
|
||||
if (btn) { btn.textContent = '🎤'; btn.title = '음성 입력'; btn.classList.remove('recording'); }
|
||||
};
|
||||
_speechRecog.start();
|
||||
}
|
||||
|
||||
function stopMicRecording() {
|
||||
if (_speechRecog) { _speechRecog.stop(); }
|
||||
}
|
||||
|
||||
// ── Voice: TTS (음성 출력) ───────────────────────────────────────────────
|
||||
var _ttsEnabled = localStorage.getItem('ttsEnabled') !== 'false'; // default on
|
||||
var _ttsAudio = null;
|
||||
var _ttsBtnActive = null;
|
||||
var _ttsAbort = null;
|
||||
var _ttsSeqResolve = null; // resolves the currently-awaited piece's completion, so _ttsStop() can unblock the playback loop
|
||||
var _appSendFn = null;
|
||||
|
||||
function initAppVoice(sendFn) {
|
||||
_appSendFn = sendFn || null;
|
||||
}
|
||||
|
||||
// Stops whatever is currently loading/playing (abort in-flight fetch, pause audio, reset button).
|
||||
function _ttsStop() {
|
||||
if (_ttsAbort) { _ttsAbort.abort(); _ttsAbort = null; }
|
||||
if (_ttsAudio) { _ttsAudio.pause(); _ttsAudio = null; }
|
||||
if (_ttsSeqResolve) { var r = _ttsSeqResolve; _ttsSeqResolve = null; r(); }
|
||||
if (_ttsBtnActive) { _ttsBtnActive.textContent = '🔊'; _ttsBtnActive.classList.remove('playing'); _ttsBtnActive = null; }
|
||||
}
|
||||
|
||||
// Splits raw text (before per-piece cleaning) into sentence/line-sized
|
||||
// pieces synthesized and played back-to-back, instead of one big combined
|
||||
// call. A single long combined call to OmniVoice measurably drops/garbles
|
||||
// content (verified via STT round-trip, 2026-07-10, see project_tts_edge
|
||||
// memory) — short calls are far more reliable. Splits on "\n" too, not just
|
||||
// .!?, so bullet-list facts each become their own call rather than getting
|
||||
// joined into one comma-separated blob (a comma pause alone wasn't enough —
|
||||
// still failed reliably in testing). Tiny fragments get merged (mirrors
|
||||
// voice-call.js's MIN_TTS_CHARS=15) so we don't fire a round-trip per clause.
|
||||
// Splits raw text into pieces synthesized and played back-to-back, one pass:
|
||||
// short sentence/line fragments accumulate into a buffer and flush once they
|
||||
// cross MIN_CHARS (mirrors voice-call.js's MIN_TTS_CHARS=15, but lower — that
|
||||
// threshold dates back to XTTS's streaming inference crashing on very short
|
||||
// standalone text, which OmniVoice doesn't share; tested down to ~6 chars).
|
||||
// Markdown table cells are the exception: each one is pushed as its own
|
||||
// never-merged piece — tested 8/8 clean vs. frequent drops when cells get
|
||||
// joined into one comma-list or merged across a row boundary (2026-07-10,
|
||||
// e.g. "81%" vanishing, or "습도 바람 서울" nonsensically mixing header/data
|
||||
// cells together). A separator row ("|---|---|") is dropped, it has no
|
||||
// spoken content. Leading bullet markers get stripped per-piece too — once
|
||||
// merged with plain spaces (not a real "\n"), _cleanForSpeech's ^...$/gm
|
||||
// regexes only see the whole joined string as one line.
|
||||
function _splitForSpeech(text) {
|
||||
var out = [];
|
||||
var buf = '';
|
||||
var MIN_CHARS = 6;
|
||||
function flush() { if (buf) { out.push(buf); buf = ''; } }
|
||||
function addPiece(s, isLineBreak) {
|
||||
s = s.trim();
|
||||
if (!s) return;
|
||||
if (/^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?$/.test(s)) return; // separator row
|
||||
var rowMatch = /^\|(.+)\|$/.exec(s);
|
||||
if (rowMatch) {
|
||||
flush(); // don't let a pending sentence fragment bleed into table cells
|
||||
// Numbers are where the model actually loses reliability (measured
|
||||
// repeatedly, project_tts_edge memory) — isolating every single cell
|
||||
// fixed that but made a whole table read out painfully slowly (one
|
||||
// network round-trip per cell). Words alone rarely garble, so merge
|
||||
// consecutive non-numeric cells (e.g. city + weather condition) and
|
||||
// only isolate cells that contain a digit — cuts call count roughly in
|
||||
// half on a typical weather table while keeping the error-prone cells
|
||||
// separate (reported 2026-07-10).
|
||||
var cellBuf = '';
|
||||
rowMatch[1].split('|').map(function(c) { return c.trim(); }).filter(Boolean).forEach(function(cell) {
|
||||
if (/\d/.test(cell)) {
|
||||
if (cellBuf) { out.push(cellBuf); cellBuf = ''; }
|
||||
out.push(cell);
|
||||
} else {
|
||||
cellBuf = cellBuf ? cellBuf + ', ' + cell : cell;
|
||||
}
|
||||
});
|
||||
if (cellBuf) out.push(cellBuf);
|
||||
return;
|
||||
}
|
||||
var bulletStripped = s.replace(/^[-*+]\s+/, '');
|
||||
if (!bulletStripped) return;
|
||||
if (isLineBreak) {
|
||||
// A line break (bullet item, paragraph line) is an intentional
|
||||
// structural separation, same reasoning as table cells above — never
|
||||
// merge it with a neighbor. Without this, a short line like "습도:
|
||||
// 86%" (under MIN_CHARS) silently absorbed the next bullet line and
|
||||
// the pause between them vanished (reported 2026-07-10). Plain prose
|
||||
// sentences (.!? boundaries, not a line break) still merge below —
|
||||
// that's normal conversational flow, not an itemized fact list.
|
||||
flush();
|
||||
out.push(bulletStripped);
|
||||
return;
|
||||
}
|
||||
buf = buf ? buf + ' ' + bulletStripped : bulletStripped;
|
||||
if (buf.replace(/[^\p{L}\p{N}]/gu, '').length >= MIN_CHARS) flush();
|
||||
}
|
||||
|
||||
var start = 0;
|
||||
for (var i = 0; i < text.length; i++) {
|
||||
if (text[i] === '.' && /\d/.test(text[i - 1] || '') && /\d/.test(text[i + 1] || '')) continue; // decimal point, not a boundary
|
||||
if (/[.!?\n]/.test(text[i])) {
|
||||
var j = i + 1;
|
||||
while (j < text.length && /[\s.!?]/.test(text[j])) j++;
|
||||
addPiece(text.slice(start, j), text[i] === '\n');
|
||||
start = j;
|
||||
i = j - 1;
|
||||
}
|
||||
}
|
||||
addPiece(text.slice(start), false);
|
||||
flush();
|
||||
return out.length ? out : [text];
|
||||
}
|
||||
|
||||
async function _ttsPlaySequence(btn, pieces) {
|
||||
for (var idx = 0; idx < pieces.length; idx++) {
|
||||
if (_ttsBtnActive !== btn) return; // stopped/superseded before this piece started
|
||||
var cleaned = _cleanForSpeech(pieces[idx]);
|
||||
if (!cleaned) continue;
|
||||
var ac = new AbortController();
|
||||
_ttsAbort = ac;
|
||||
var blob;
|
||||
try {
|
||||
var r = await fetch('/api/voice/tts', {
|
||||
method: 'POST',
|
||||
headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ text: cleaned.slice(0, 2000) }),
|
||||
signal: ac.signal,
|
||||
});
|
||||
if (!r.ok) throw new Error('TTS 오류 ' + r.status);
|
||||
blob = await r.blob();
|
||||
} catch (e) {
|
||||
if (e.name === 'AbortError' || _ttsBtnActive !== btn) return;
|
||||
_ttsStop();
|
||||
alert('TTS 오류: ' + e.message);
|
||||
return;
|
||||
}
|
||||
if (_ttsBtnActive !== btn) return; // superseded while this piece was fetching
|
||||
var url = URL.createObjectURL(blob);
|
||||
var audio = new Audio(url);
|
||||
_ttsAudio = audio;
|
||||
btn.textContent = '⏹';
|
||||
var done = new Promise(function(resolve) {
|
||||
_ttsSeqResolve = resolve;
|
||||
audio.onended = function() { URL.revokeObjectURL(url); _ttsSeqResolve = null; resolve(); };
|
||||
audio.onerror = function() { URL.revokeObjectURL(url); _ttsSeqResolve = null; resolve(); };
|
||||
});
|
||||
audio.play();
|
||||
await done;
|
||||
if (_ttsBtnActive !== btn) return; // stopped mid-playback
|
||||
}
|
||||
if (_ttsBtnActive === btn) _ttsStop(); // whole sequence finished naturally
|
||||
}
|
||||
|
||||
// Shared core for playTTSText/playTTSMsg. Guards every async callback with a
|
||||
// "is this still the active button?" check so a slow/stale response from a
|
||||
// superseded click can never start overlapping playback (the echo bug).
|
||||
function _ttsPlay(btn, text) {
|
||||
if (!text) return;
|
||||
var wasActive = (_ttsBtnActive === btn);
|
||||
_ttsStop();
|
||||
if (wasActive) return; // clicking the active button again = stop
|
||||
|
||||
btn.textContent = '⌛'; btn.classList.add('playing');
|
||||
_ttsBtnActive = btn;
|
||||
_ttsPlaySequence(btn, _splitForSpeech(text));
|
||||
}
|
||||
|
||||
// Sino-Korean digit-string reading, e.g. 27 -> "이십칠", 0 -> "영". Handles
|
||||
// 0-9999 (plenty for the measurement-style numbers TTS text actually
|
||||
// contains — temperatures, percentages, speeds); larger numbers get an
|
||||
// extra 만/억 grouping pass but aren't the target use case.
|
||||
function _sinoKoreanInt(n) {
|
||||
if (n === 0) return '영';
|
||||
var digits = ['', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'];
|
||||
var smallUnits = ['', '십', '백', '천'];
|
||||
var bigUnits = ['', '만', '억', '조'];
|
||||
function fourDigit(num) {
|
||||
if (num === 0) return '';
|
||||
var s = '';
|
||||
var ds = String(num).padStart(4, '0').split('').map(Number);
|
||||
for (var i = 0; i < 4; i++) {
|
||||
var d = ds[i], unit = smallUnits[3 - i];
|
||||
if (d === 0) continue;
|
||||
s += (d === 1 && unit !== '') ? unit : (digits[d] + unit);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
var groups = [];
|
||||
var rem = n;
|
||||
while (rem > 0) { groups.push(rem % 10000); rem = Math.floor(rem / 10000); }
|
||||
var result = '';
|
||||
for (var g = groups.length - 1; g >= 0; g--) {
|
||||
if (groups[g] === 0) continue;
|
||||
result += fourDigit(groups[g]) + bigUnits[g];
|
||||
}
|
||||
return result || '영';
|
||||
}
|
||||
|
||||
// "27.7" -> "이십칠점칠" (decimal digits read one at a time, standard
|
||||
// Korean convention), "-3.2" -> "마이너스 삼점이".
|
||||
function _numToHangulWord(numStr) {
|
||||
var neg = numStr[0] === '-';
|
||||
if (neg) numStr = numStr.slice(1);
|
||||
var parts = numStr.split('.');
|
||||
var word = _sinoKoreanInt(parseInt(parts[0], 10) || 0);
|
||||
if (parts[1]) {
|
||||
var d = ['영', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'];
|
||||
word += '점' + parts[1].split('').map(function(c) { return d[+c]; }).join('');
|
||||
}
|
||||
return (neg ? '마이너스 ' : '') + word;
|
||||
}
|
||||
|
||||
// Korean uses native-Korean numerals (하나/둘/셋...), not Sino-Korean
|
||||
// (일/이/삼...), specifically for clock hours and hour-durations — "9시" is
|
||||
// "아홉 시", never "구시" (reported 2026-07-10). Everything else (분, 초,
|
||||
// 도, %, dates, etc.) correctly stays Sino-Korean via _numToHangulWord.
|
||||
var _NATIVE_HOUR = { 1: '한', 2: '두', 3: '세', 4: '네', 5: '다섯', 6: '여섯', 7: '일곱', 8: '여덟', 9: '아홉', 10: '열', 11: '열한', 12: '열두' };
|
||||
function _hourReplacer(m, numStr, suffix) {
|
||||
var n = parseInt(numStr, 10);
|
||||
return _NATIVE_HOUR[n] ? _NATIVE_HOUR[n] + suffix : m;
|
||||
}
|
||||
|
||||
// Strips markdown, emoji and bare parens before handing text to the GPU
|
||||
// voice engine (OmniVoice). Mirrors voice-call.js's sanitizeForSpeech: emoji
|
||||
// get mispronounced as garbled syllables, a lone "(" makes OmniVoice
|
||||
// stop generating audio entirely instead of just mispronouncing it, and a
|
||||
// bare "°C"/"°F" gets read as "그램"(grams) instead of degrees.
|
||||
function _cleanForSpeech(text) {
|
||||
return (text || '')
|
||||
.replace(/!\[.*?\]\(.*?\)/g, '')
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
.replace(/```[\s\S]*?```/g, '')
|
||||
// Table handling was also never ported from voice-call.js — a leftover
|
||||
// "|" right before a cell's content (e.g. "| 81% |") is yet another
|
||||
// unknown-symbol case that makes OmniVoice choke and drop content
|
||||
// (reported 2026-07-10, e.g. "81%" vanishing entirely from a table row).
|
||||
.replace(/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/gm, ' ')
|
||||
.replace(/^\s*\|(.+)\|\s*$/gm, function(_m, row) { return row.split('|').map(function(c) { return c.trim(); }).filter(Boolean).join(', '); })
|
||||
// Bullet markers were never stripped here (unlike voice-call.js's
|
||||
// sanitizeForSpeech, which already had this) — a leftover "- " right
|
||||
// after the newline-to-comma pause below reads as a rushed, breathless
|
||||
// run-on (reported 2026-07-10). Must run before \n gets consumed.
|
||||
.replace(/^\s*[-*+]\s+/gm, '')
|
||||
.replace(/[#*`_~>]/g, ' ')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*°C/gi, '섭씨 $1도')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*°F/gi, '화씨 $1도')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*°/g, '$1도')
|
||||
// Spell out common units so a bare symbol doesn't get read wrong
|
||||
// (measured: numerals+symbols like "%"/"m/s" have a real error rate,
|
||||
// spelling everything in Hangul is dramatically more reliable, 2026-07-10).
|
||||
.replace(/(\d+(?:\.\d+)?)\s*%/g, '$1퍼센트')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*km\/h/gi, '$1킬로미터 매 시')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*m\/s/gi, '$1미터 매 초')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*mm/gi, '$1밀리미터')
|
||||
.replace(/(\d+(?:\.\d+)?)\s*km/gi, '$1킬로미터')
|
||||
// Wind-direction abbreviations in parens (e.g. "2.6 m/s (SSW)") aren't
|
||||
// Korean words, so OmniVoice mangles them — spell out the compass point
|
||||
// instead. Longest abbreviations first so "SSW" doesn't partial-match as
|
||||
// "S" (reported 2026-07-10). Must run before the generic paren->period
|
||||
// conversion below, while the parens are still intact to anchor on.
|
||||
.replace(/\((NNE|ENE|ESE|SSE|SSW|WSW|WNW|NNW|NE|SE|SW|NW|N|S|E|W)\)/g, function(_m, dir) {
|
||||
var d = { N: '북', NNE: '북북동', NE: '북동', ENE: '동북동', E: '동', ESE: '동남동', SE: '남동', SSE: '남남동', S: '남', SSW: '남남서', SW: '남서', WSW: '서남서', W: '서', WNW: '서북서', NW: '북서', NNW: '북북서' };
|
||||
return d[dir] ? ' ' + d[dir] + ' ' : _m;
|
||||
})
|
||||
// Swap parens for a period rather than just erasing them — still no bare
|
||||
// "(" reaches the model (the crash trigger), but a period gives the
|
||||
// parenthetical aside a clearer pause than a comma did (measured: comma
|
||||
// ~+0.02-0.08s over a bare space, period ~2-3x that, 2026-07-10).
|
||||
.replace(/[((]\s*/g, '. ')
|
||||
.replace(/\s*[))]\s*/g, '. ')
|
||||
.replace(/\.\s*\./g, '.')
|
||||
// Paragraph/line breaks were silently vanishing into the final \s+ ->
|
||||
// ' ' collapse below, so a blank line between two unrelated facts (e.g.
|
||||
// wind speed, then a separate rain/comfort sentence) got read with zero
|
||||
// pause at all — worse than the old paren-as-space bug. Give them a
|
||||
// pause proportional to how strong a break they represent.
|
||||
.replace(/(?<![.!?,:;])\n{2,}/g, '. ')
|
||||
.replace(/(?<![.!?,:;])\n/g, ', ')
|
||||
.replace(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{1F1E6}-\u{1F1FF}\u{2190}-\u{21FF}\u{2B00}-\u{2BFF}\u{FE0F}]/gu, '')
|
||||
// Hour numbers use native-Korean counting, not Sino-Korean — must run
|
||||
// before the generic number pass below so "9시" doesn't become "구시".
|
||||
.replace(/(\d{1,2})(\s*시간?)/g, _hourReplacer)
|
||||
// Final pass: every remaining numeral (including ones the unit
|
||||
// conversions above just introduced digits next to, e.g. "27.7도")
|
||||
// becomes spelled-out Hangul — this is the single biggest reliability
|
||||
// win measured today (raw numerals: frequent digit swaps/drops;
|
||||
// spelled-out: ~7/8 clean in repeated STT round-trip testing).
|
||||
.replace(/-?\d+(?:\.\d+)?/g, function(m) { return _numToHangulWord(m); })
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function playTTSText(btn, text) {
|
||||
_ttsPlay(btn, text || '');
|
||||
}
|
||||
|
||||
function updateTTSMode() {
|
||||
_ttsEnabled = document.getElementById('tts-mode-toggle').checked;
|
||||
localStorage.setItem('ttsEnabled', String(_ttsEnabled));
|
||||
document.body.classList.toggle('tts-disabled', !_ttsEnabled);
|
||||
if (!_ttsEnabled && _ttsAudio) {
|
||||
_ttsAudio.pause(); _ttsAudio = null;
|
||||
if (_ttsBtnActive) { _ttsBtnActive.textContent = '🔊'; _ttsBtnActive.classList.remove('playing'); _ttsBtnActive = null; }
|
||||
}
|
||||
}
|
||||
|
||||
function initTTSToggle() {
|
||||
var toggle = document.getElementById('tts-mode-toggle');
|
||||
if (toggle) toggle.checked = _ttsEnabled;
|
||||
document.body.classList.toggle('tts-disabled', !_ttsEnabled);
|
||||
}
|
||||
|
||||
function playTTSMsg(btn, idx) {
|
||||
var msg = chatHistory[idx];
|
||||
if (!msg) return;
|
||||
_ttsPlay(btn, msg.content || '');
|
||||
}
|
||||
Reference in new issue
Block a user