Files
homeclaw/web-ui/js/app/markdown.js
T

393 lines
24 KiB
JavaScript

// 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; }
}
// 2026-10-14: 국내 지도는 카카오맵. 프롬프트로 지시해도 모델이 구글 URL을 그대로 내는 일이 있어(주안동 670
// 사례) 화면에서 되돌린다. 질의에 한글 행정구역·도로·역 표지가 있으면 국내 지명으로 보고 카카오 검색으로
// 바꾼다. 해외 지명(에펠탑 등)은 표지가 없어 구글 그대로 간다. 좌표(@lat,lng)만 있는 URL은 건드리지 않는다.
var KR_PLACE_RE = /(^|[\s+])(서울|부산|대구|인천|광주|대전|울산|세종|경기|강원|충북|충남|전북|전남|경북|경남|제주|충청|전라|경상)|[가-힣0-9]+(시|군|구|동|읍|면|리|로|길|역)(?=[\s+0-9]|$)|번지/;
function googleMapsToKakaoUrl(url) {
try {
var u = new URL(url);
var q = null;
var m = u.pathname.match(/\/maps\/(?:place|search)\/([^/@?]+)/);
if (m) q = decodeURIComponent(m[1].replace(/\+/g, ' '));
if (!q) q = u.searchParams.get('q') || u.searchParams.get('query');
if (!q || !/[가-힣]/.test(q) || !KR_PLACE_RE.test(q)) return null;
return 'https://map.kakao.com/link/search/' + encodeURIComponent(q.trim()).replace(/[()!'*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); });
} 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
// &#96; (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(/&#96;&#96;&#96;([\w-]*)\n([\s\S]*?)&#96;&#96;&#96;/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(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/gi,'"').replace(/&#39;/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(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/gi,'"').replace(/&#39;/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(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/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 &#92;.
var smRaw = trimmed.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/gi,'"').replace(/&#39;/g,"'").replace(/&#96;/g,'`').replace(/&#36;/g,'$').replace(/&#92;/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 (&amp;, &lt;, ...), so only exclude another
// &#96; sequence rather than excluding every '&' (which would truncate on those entities).
html = html.replace(/&#96;((?:(?!&#96;)[\s\S])+?)&#96;/g, '<code class="md-inline-code">$1</code>');
// Images: ![alt](url)
html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, function(_, alt, url) {
var safeAlt = alt.replace(/"/g, '&quot;');
var errAlt = (alt || '이미지').replace(/'/g, '&#39;').replace(/</g, '&lt;');
var onerr = "this.onerror=null;this.style.display='none';this.insertAdjacentHTML('afterend','<span class=&quot;md-img-err&quot;>&#x2716; " + 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, '&quot;');
var safeOrig = url.replace(/"/g, '&quot;');
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;
});
// Kakao Map URLs on their own line → inline iframe (2026-10-14: 국내 지도는 구글 대신 카카오맵).
// map.kakao.com/link/map|search|to|by/... 는 이름·좌표만으로 열리는 공개 링크 형식이다(키 불필요). by/car는 길찾기 경로.
// 모델이 "지도: URL", "길찾기 지도: URL"처럼 짧은 이름표를 붙여 내는 일이 많아(10-23 길찾기 답) 콜론으로 끝나는
// 20자 이내 이름표는 떼고 지도로 띄운다.
html = html.replace(/((?:^|\n)[ \t]*)(?:[^\n<>:]{1,20}:[ \t]*)?(https:\/\/map\.kakao\.com\/link\/(?:map|search|to|by)\/[^\s<>")\n]+)([ \t]*)(?=\n|$)/gim, function(m, pre, url, post) {
var safeEmbed = url.replace(/"/g, '&quot;');
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="' + safeEmbed + '" target="_blank" rel="noopener">카카오맵에서 열기 ↗</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 kakaoUrl = googleMapsToKakaoUrl(url);
if (kakaoUrl) {
return pre + '<div class="map-embed-wrap"><iframe class="map-embed" src="' + kakaoUrl + '" allowfullscreen loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe><div class="map-embed-link"><a href="' + kakaoUrl + '" target="_blank" rel="noopener">카카오맵에서 열기 ↗</a></div></div>' + post;
}
var embedUrl = mapsToEmbedUrl(url);
if (!embedUrl) return m;
var safeEmbed = embedUrl.replace(/"/g, '&quot;');
var safeOrig = url.replace(/"/g, '&quot;');
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 ![alt](url) 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, '&quot;');
var safeOrig = url.replace(/"/g, '&quot;');
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, '&quot;');
var safeOrig = url.replace(/"/g, '&quot;');
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, '&quot;');
var safeOrig = url.replace(/"/g, '&quot;');
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=&quot;md-img-err&quot;>&#x2716; 이미지를 불러올 수 없습니다.</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 = [];
// 셀 구분자 '|' 분리: <code>…</code> 안의 '|'와 '\|'(이스케이프)는 구분자가 아니다.
var splitCells = function(line) {
var cells = [], cur = '', inCode = false;
for (var k = 0; k < line.length; k++) {
if (line.startsWith('<code', k)) inCode = true;
else if (line.startsWith('</code>', k)) inCode = false;
var ch = line[k];
if (ch === '\\' && line[k + 1] === '|') { cur += '|'; k++; continue; }
if (ch === '|' && !inCode) { cells.push(cur); cur = ''; continue; }
cur += ch;
}
cells.push(cur);
return cells;
};
var parseRow = function(line) {
var cells = splitCells(line.trim());
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) { var t = line.trim(); return /^\|[\s|:\-_=]+\|[ \t]*$/.test(t) && t.indexOf('-') !== -1; };
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;
}