nomadro/apps/miniprogram/xhs/tool/book/markdown.js
eric 1d3e513ae2 Ship Douyin tt/ miniprogram: offline reader, clipboard privacy, README.
Add apps/miniprogram/tt as a standalone Douyin app with official usePrivacyCheck + tt.showModal/setClipboardData flow, single-chapter offline reader, and document console privacy setup for clipboard.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 15:17:52 +08:00

353 lines
9.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Lightweight markdown → HTML for offline 小红书小工具.
* Images: park as @@IMGn@@ then emit <img> after escape — never escape HTML tags as text.
* No eval / network / Worker.
*/
(function (global) {
function themeColors(theme) {
if (theme === "light") {
return {
text: "#1e1630",
muted: "#6d6286",
accent: "#db2777",
accentSoft: "rgba(219,39,119,.1)",
code: "#7c3aed",
strong: "#120f1d",
};
}
if (theme === "sepia") {
return {
text: "#3d2f1f",
muted: "#8a7358",
accent: "#c2410c",
accentSoft: "rgba(194,65,12,.12)",
code: "#c2410c",
strong: "#2a1f14",
};
}
return {
text: "#f3eefc",
muted: "#b4a9c8",
accent: "#ff7ab6",
accentSoft: "rgba(255,122,182,.14)",
code: "#c4b5fd",
strong: "#ffffff",
};
}
function escapeHtml(s) {
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
function inline(s, c) {
return escapeHtml(s)
.replace(/\*\*(.+?)\*\*/g, '<strong style="color:' + c.strong + ';font-weight:700;">$1</strong>')
.replace(/\*(.+?)\*/g, '<em style="color:' + c.muted + ';">$1</em>')
.replace(/`([^`]+)`/g, '<span class="md-code">$1</span>')
.replace(
/\[(.+?)\]\((https?:\/\/.+?)\)/g,
'<a href="$2" style="color:' + c.accent + ';text-decoration:underline;">$1</a>',
);
}
function imgHtml(src, alt, width) {
var style = width
? 'style="max-width:100%;width:' +
width +
'px;height:auto;display:block;margin:12px auto;border-radius:8px;"'
: 'style="max-width:100%;height:auto;display:block;margin:12px auto;border-radius:8px;"';
return (
'<p class="md-img"><img src="' +
String(src).replace(/"/g, "&quot;") +
'" alt="' +
escapeHtml(alt || "") +
'" ' +
style +
"/></p>"
);
}
function markdownToHtml(src, opts) {
opts = opts || {};
var dropCap = opts.dropCap !== false;
var c = themeColors(opts.theme || "dark");
var text = String(src || "").replace(/\r\n/g, "\n");
text = text.replace(/<!--[\s\S]*?-->/g, "");
text = text.replace(/<video[\s\S]*?<\/video>/gi, "> 🎬 视频请在异度世界公众号查看");
// 先把图片停到占位符,避免后续 escapeHtml 把 <img> 当正文转义
var images = [];
function park(srcUrl, alt, width) {
// 离线包配图目录是 ./images/,勿留微信分包路径
srcUrl = String(srcUrl || "").replace(
/^\/packageBook\/assets\/book-images\//,
"./images/",
);
var key = "@@IMG" + images.length + "@@";
images.push({ src: srcUrl, alt: alt || "", width: width || 0 });
return key;
}
text = text.replace(/<img\b[\s\S]*?>/gi, function (tag) {
var srcM = /src=["']((?:https?:\/\/|data:image\/|\.\/|\/)[^"']+)["']/i.exec(tag);
if (!srcM) return "";
var srcUrl = srcM[1];
if (/^file:/i.test(srcUrl) || /^[A-Za-z]:\\/.test(srcUrl)) return "";
var w = /width=["']?(\d+)/i.exec(tag);
return park(srcUrl, "", w ? Number(w[1]) : 0);
});
text = text.replace(/!\[[^\]]*\]\(file:\/\/\/[^)]+\)/gi, "");
text = text.replace(/!\[[^\]]*\]\((?:[A-Za-z]:\\)[^)]+\)/g, "");
text = text.replace(
/!\[([^\]]*)\]\(((?:https?:\/\/|data:image\/|\.\/|\/)[^)\s]+)\)/g,
function (_m, alt, srcUrl) {
return park(srcUrl, alt || "", 0);
},
);
text = text.replace(/!\[[^\]]*\]\([^)]+\)/g, "> 🖼 配图不可用");
var lines = text.split("\n");
var out = [];
var inCode = false;
var codeBuf = [];
var inUl = false;
var inOl = false;
var olIndex = 0;
var inQuote = false;
var quoteBuf = [];
var paraCount = 0;
var skippedChapterTitle = false;
function closeLists() {
if (inUl) {
out.push("</div>");
inUl = false;
}
if (inOl) {
out.push("</div>");
inOl = false;
olIndex = 0;
}
}
function flushQuote() {
if (!inQuote) return;
var body = quoteBuf
.map(function (q) {
return inline(q, c);
})
.join("<br/>");
out.push('<div class="md-quote">' + body + "</div>");
inQuote = false;
quoteBuf = [];
}
function isTableSep(line) {
return /^\s*\|?[\s:-]+\|[\s|:-]*\|?\s*$/.test(line);
}
function splitRow(line) {
var s = line.trim();
if (s.charAt(0) === "|") s = s.slice(1);
if (s.charAt(s.length - 1) === "|") s = s.slice(0, -1);
return s.split("|").map(function (cell) {
return cell.trim();
});
}
function renderTable(rows) {
if (!rows.length) return;
var html = ['<div class="md-table-wrap"><table class="md-table"><thead><tr>'];
rows[0].forEach(function (cell) {
html.push("<th>" + inline(cell, c) + "</th>");
});
html.push("</tr></thead><tbody>");
for (var r = 1; r < rows.length; r++) {
html.push("<tr>");
rows[r].forEach(function (cell) {
html.push("<td>" + inline(cell, c) + "</td>");
});
html.push("</tr>");
}
html.push("</tbody></table></div>");
out.push(html.join(""));
}
function emitImgTokens(line) {
var parts = String(line).split(/(@@IMG\d+@@)/g);
var buf = [];
for (var p = 0; p < parts.length; p++) {
var part = parts[p];
if (!part) continue;
var m = /^@@IMG(\d+)@@$/.exec(part);
if (m) {
var meta = images[Number(m[1])];
if (meta) buf.push(imgHtml(meta.src, meta.alt, meta.width));
} else {
buf.push(inline(part, c));
}
}
return buf.join("");
}
for (var i = 0; i < lines.length; i++) {
var raw = lines[i];
var line = raw;
var trimmed = line.trim();
if (/^```/.test(line)) {
flushQuote();
closeLists();
if (inCode) {
out.push('<pre class="md-pre"><code>' + escapeHtml(codeBuf.join("\n")) + "</code></pre>");
codeBuf = [];
inCode = false;
} else {
inCode = true;
}
continue;
}
if (inCode) {
codeBuf.push(line);
continue;
}
// 整行只有图片占位 → 直接输出 img,不包进转义段落
if (/^@@IMG\d+@@$/.test(trimmed)) {
flushQuote();
closeLists();
out.push(emitImgTokens(trimmed));
continue;
}
if (line.indexOf("|") !== -1 && i + 1 < lines.length && isTableSep(lines[i + 1])) {
flushQuote();
closeLists();
var rows = [splitRow(line)];
i += 1;
while (i + 1 < lines.length && lines[i + 1].indexOf("|") !== -1 && lines[i + 1].trim()) {
i += 1;
if (isTableSep(lines[i])) continue;
rows.push(splitRow(lines[i]));
}
renderTable(rows);
continue;
}
if (/^\s*>\s?/.test(line)) {
closeLists();
inQuote = true;
quoteBuf.push(line.replace(/^\s*>\s?/, ""));
continue;
}
if (inQuote) flushQuote();
if (/^\s*---+\s*$/.test(line) || /^\s*\*\*\*+\s*$/.test(line)) {
closeLists();
out.push('<hr class="md-hr"/>');
continue;
}
var h1 = /^#\s+(.+)$/.exec(line);
if (h1) {
closeLists();
if (!skippedChapterTitle) {
skippedChapterTitle = true;
continue;
}
out.push("<h2>" + emitImgTokens(h1[1]) + "</h2>");
continue;
}
var h2 = /^##\s+(.+)$/.exec(line);
if (h2) {
closeLists();
if (!skippedChapterTitle) {
skippedChapterTitle = true;
continue;
}
out.push("<h2>" + emitImgTokens(h2[1]) + "</h2>");
continue;
}
var h3 = /^###\s+(.+)$/.exec(line);
if (h3) {
closeLists();
out.push("<h3>" + emitImgTokens(h3[1]) + "</h3>");
continue;
}
var task = /^\s*[-*+]\s+\[([ xX])\]\s+(.+)$/.exec(line);
if (task) {
if (inOl) {
out.push("</div>");
inOl = false;
olIndex = 0;
}
if (!inUl) {
out.push('<div class="md-list">');
inUl = true;
}
var mark = /x/i.test(task[1]) ? "☑" : "☐";
out.push("<div>" + mark + " " + emitImgTokens(task[2]) + "</div>");
continue;
}
var ul = /^\s*[-*+]\s+(.+)$/.exec(line);
if (ul) {
if (inOl) {
out.push("</div>");
inOl = false;
olIndex = 0;
}
if (!inUl) {
out.push('<div class="md-list">');
inUl = true;
}
out.push("<div>• " + emitImgTokens(ul[1]) + "</div>");
continue;
}
var ol = /^\s*(\d+)\.\s+(.+)$/.exec(line);
if (ol) {
if (inUl) {
out.push("</div>");
inUl = false;
}
if (!inOl) {
out.push('<div class="md-list">');
inOl = true;
olIndex = 0;
}
olIndex += 1;
out.push("<div>" + olIndex + ". " + emitImgTokens(ol[2]) + "</div>");
continue;
}
if (!line.trim()) {
closeLists();
continue;
}
closeLists();
paraCount += 1;
var cls = dropCap && paraCount === 1 ? ' class="dropcap"' : "";
// 行内混有图片占位时:文本转义,图片单独展开
if (/@@IMG\d+@@/.test(trimmed)) {
out.push("<p" + cls + ">" + emitImgTokens(trimmed) + "</p>");
} else {
out.push("<p" + cls + ">" + inline(trimmed, c) + "</p>");
}
}
flushQuote();
closeLists();
if (inCode) {
out.push('<pre class="md-pre"><code>' + escapeHtml(codeBuf.join("\n")) + "</code></pre>");
}
return out.join("");
}
global.MarkdownLite = { markdownToHtml: markdownToHtml, themeColors: themeColors };
})(typeof window !== "undefined" ? window : this);