import { cn } from "@suphark/ui/lib/utils"; import { Marked, type Tokens } from "marked"; /** * แสดง markdown (GFM) เป็น HTML — ทำงานใน server component ได้ (ไม่มี hook ไม่ส่ง JS ไป browser) * ใช้ทำหน้าคู่มือ: แอปอ่าน `docs/*.md` ฝั่ง server แล้วส่งข้อความเข้ามา */ export interface MarkdownHeading { id: string; /** ข้อความหัวข้อ (ไม่มี markup) */ text: string; depth: number; } export interface MarkdownRenderOptions { /** แปลงลิงก์ก่อนแสดง เช่น `docs/x.md` → `/admin/docs/x` · คืนค่าเดิมถ้าไม่ต้องแปลง */ resolveHref?: (href: string) => string; /** render HTML ดิบใน markdown — ค่าเริ่มต้น false (แสดงเป็นข้อความ) */ allowHtml?: boolean; /** ตัดหัวข้อระดับ 1 แรกออก (แอปแสดงชื่อหน้าเอง — ได้ค่าใน `title`) */ stripTitle?: boolean; } export interface MarkdownRenderResult { html: string; /** หัวข้อทุกระดับตามลำดับ พร้อม id สำหรับลิงก์ `#id` (ใช้ทำสารบัญ) */ headings: MarkdownHeading[]; /** หัวข้อระดับ 1 แรก (ถ้ามี) */ title?: string; } export interface MarkdownText { /** หัวสารบัญข้างเนื้อหา (จอกว้าง) */ toc: string; /** ปุ่มเปิดสารบัญ (จอแคบ) */ tocToggle: string; /** ชื่อกรอบเลื่อนของตารางกว้าง (โปรแกรมอ่านหน้าจอ) */ tableRegion: string; } export const MARKDOWN_TEXT_TH: MarkdownText = { toc: "ในหน้านี้", tocToggle: "สารบัญ", tableRegion: "ตาราง (เลื่อนแนวนอนได้)", }; export const MARKDOWN_TEXT_EN: MarkdownText = { toc: "On this page", tocToggle: "Contents", tableRegion: "Table (scrolls horizontally)", }; const escapeHtml = (value: string) => value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); const stripTags = (html: string) => html .replace(/<[^>]+>/g, "") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/</g, "<") .replace(/>/g, ">") .replace(/&/g, "&"); /** id ของหัวข้อ — คงอักษรไทย/ตัวเลข/ละติน ตัดเครื่องหมาย ช่องว่างเป็น "-" */ export function markdownSlug(text: string) { return ( text .toLowerCase() .replace(/[`*_~[\]()<>{}:;,.!?'"/\\|@#$%^&=+—–·…]/g, "") .trim() .replace(/\s+/g, "-") || "section" ); } /** ลิงก์อันตราย (javascript:/data:/vbscript:) → "#" */ function safeHref(href: string) { return /^\s*(javascript|data|vbscript):/i.test(href) ? "#" : href; } type InlineParser = { parser: { parseInline: (tokens: Tokens.Generic[]) => string } }; /** markdown → HTML + หัวข้อ (เรียกเองได้เมื่อต้องการชื่อหน้า/สารบัญไปวางที่อื่น) */ export function renderMarkdown( source: string, { resolveHref, allowHtml = false, stripTitle = false }: MarkdownRenderOptions = {}, text: MarkdownText = MARKDOWN_TEXT_TH, ): MarkdownRenderResult { const titleMatch = source.match(/^# (.+)$/m); const title = titleMatch?.[1]?.trim(); const body = stripTitle && titleMatch ? source.replace(titleMatch[0], "") : source; const headings: MarkdownHeading[] = []; const used = new Map(); const marked = new Marked({ gfm: true, async: false }); marked.use({ renderer: { heading(this: InlineParser, token) { const inner = this.parser.parseInline(token.tokens); const plain = stripTags(inner); const base = markdownSlug(plain); const n = used.get(base) ?? 0; used.set(base, n + 1); const id = n === 0 ? base : `${base}-${n}`; headings.push({ id, text: plain, depth: token.depth }); const attr = escapeHtml(id); return `${inner}\n`; }, link(this: InlineParser, token) { const href = safeHref(resolveHref ? resolveHref(token.href) : token.href); const external = /^https?:\/\//i.test(href); const title = token.title ? ` title="${escapeHtml(token.title)}"` : ""; const target = external ? ' target="_blank" rel="noreferrer"' : ""; return `${this.parser.parseInline(token.tokens)}`; }, image(token) { const src = safeHref(resolveHref ? resolveHref(token.href) : token.href); return `${escapeHtml(token.text)}`; }, html(token) { return allowHtml ? token.text : escapeHtml(token.text); }, }, }); const html = (marked.parse(body) as string) // ตารางกว้างเลื่อนแนวนอนในกรอบของตัวเอง — หน้าไม่ล้นบนมือถือ .replace( //g, `
`, ) .replace(/<\/table>/g, "
"); return { html, headings, title }; } /** สารบัญจากหัวข้อ (ค่าเริ่มต้นระดับ 2–3) — ใช้คู่กับ `renderMarkdown` เมื่อวางเอง */ export function MarkdownToc({ headings, depths = [2, 3], className, }: { headings: MarkdownHeading[]; depths?: number[]; className?: string; }) { const items = headings.filter((h) => depths.includes(h.depth)); if (items.length === 0) return null; const minDepth = Math.min(...items.map((h) => h.depth)); return ( ); } export interface MarkdownProps extends MarkdownRenderOptions { /** ข้อความ markdown */ source: string; /** * แสดงสารบัญจากหัวข้อระดับ 2: จอกว้างเป็นคอลัมน์ขวาติดตามการเลื่อน, จอแคบพับไว้เหนือเนื้อหา * (แสดงเมื่อมีอย่างน้อย 2 หัวข้อ) */ toc?: boolean; /** ระยะจากขอบบนของสารบัญที่ติดตามการเลื่อน — ค่าเริ่มต้นใต้หัวแอป */ tocTop?: string; text?: Partial; className?: string; } /** * แสดงเอกสาร markdown ตามรูปแบบตัวอักษรของ design system — หัวข้อมี id ลิงก์ `#หัวข้อ` ได้ (รวมภาษาไทย), * ลิงก์ภายนอกเปิดแท็บใหม่, ตารางกว้างเลื่อนในกรอบ, HTML ดิบแสดงเป็นข้อความ (เว้นแต่ `allowHtml`) * * const source = await readFile("docs/guide.md", "utf8"); // server component * */ export function Markdown({ source, toc = false, tocTop = "calc(var(--app-header-height, 3.5rem) + 1rem)", text: textOverride, className, ...options }: MarkdownProps) { const text = { ...MARKDOWN_TEXT_TH, ...textOverride }; const { html, headings } = renderMarkdown(source, options, text); const content = (
); const tocHeadings = headings.filter((h) => h.depth === 2); if (!toc || tocHeadings.length < 2) return content; return (
{text.tocToggle}
{content}
); }