Files
gsfdc/portal/app/utils/answerMarkdown.ts
T
wuzilongandCursor 9c7c80e194 feat: 把估价智能体和部署配置提交到主分支
门户估价对话、会员与智能体账号,以及生产 Docker 部署一直停在工作区,远端主分支还没有这些改动。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-23 09:42:44 +08:00

166 lines
5.4 KiB
TypeScript

const ESCAPE: Record<string, string> = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
}
function escapeHtml(value: string): string {
return value.replace(/[&<>"]/g, (char) => ESCAPE[char] || char)
}
function renderInline(value: string): string {
const codes: string[] = []
let text = escapeHtml(value).replace(/`([^`\n]+)`/g, (_match, code: string) => {
const token = `\u0000${codes.length}\u0000`
codes.push(code)
return token
})
text = text.replace(
/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g,
'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>',
)
text = text.replace(/\*\*([^*\n]+)\*\*/g, "<strong>$1</strong>")
text = text.replace(/__([^_\n]+)__/g, "<strong>$1</strong>")
text = text
.split(/(<[^>]+>)/)
.map((part) => (part.startsWith("<") ? part : linkBareUrls(part)))
.join("")
return text.replace(/\u0000(\d+)\u0000/g, (_match, index: string) => `<code>${codes[Number(index)]}</code>`)
}
function linkBareUrls(value: string): string {
return value.replace(/https?:\/\/[^\s<]+/g, (url) => {
const clean = url.replace(/[.,;:!?)]+$/, "")
const tail = url.slice(clean.length)
return `<a href="${clean}" target="_blank" rel="noopener noreferrer">${clean}</a>${tail}`
})
}
function splitCells(line: string): string[] {
let text = line.trim()
if (text.startsWith("|")) text = text.slice(1)
if (text.endsWith("|")) text = text.slice(0, -1)
const cells: string[] = []
let current = ""
for (let index = 0; index < text.length; index += 1) {
const char = text[index]
if (char === "\\" && text[index + 1] === "|") {
current += "|"
index += 1
continue
}
if (char === "|") {
cells.push(current.trim())
current = ""
continue
}
current += char
}
cells.push(current.trim())
return cells
}
function isSeparatorRow(line: string): boolean {
if (!line.includes("|")) return false
const cells = splitCells(line)
return cells.length > 1 && cells.every((cell) => /^:?-+:?$/.test(cell))
}
function isTableStart(lines: string[], index: number): boolean {
const line = lines[index]?.trim() || ""
const next = lines[index + 1]?.trim() || ""
return line.includes("|") && isSeparatorRow(next)
}
function renderTable(header: string[], rows: string[][]): string {
const width = Math.max(header.length, ...rows.map((row) => row.length), 1)
const cells = (row: string[], tag: "th" | "td") => {
const padded = row.concat(Array(Math.max(0, width - row.length)).fill(""))
return padded.slice(0, width).map((cell) => `<${tag}>${renderInline(cell)}</${tag}>`).join("")
}
const body = rows.map((row) => `<tr>${cells(row, "td")}</tr>`).join("")
return `<div class="table-wrap"><table><thead><tr>${cells(header, "th")}</tr></thead><tbody>${body}</tbody></table></div>`
}
function isList(line: string): "ul" | "ol" | "" {
if (/^[-*]\s+\S/.test(line)) return "ul"
if (/^\d+\.\s+\S/.test(line)) return "ol"
return ""
}
export function renderAnswerMarkdown(source: string): string {
const lines = source.replace(/\r\n/g, "\n").split("\n")
const blocks: string[] = []
let index = 0
while (index < lines.length) {
const raw = lines[index]
const line = raw.trim()
if (!line) {
index += 1
continue
}
if (line.startsWith("```")) {
const body: string[] = []
index += 1
while (index < lines.length && !lines[index].trim().startsWith("```")) {
body.push(escapeHtml(lines[index]))
index += 1
}
if (index < lines.length) index += 1
blocks.push(`<pre><code>${body.join("\n")}</code></pre>`)
continue
}
const heading = /^(#{1,4})\s+(.+)$/.exec(line)
if (heading) {
const level = heading[1].length
blocks.push(`<h${level}>${renderInline(heading[2])}</h${level}>`)
index += 1
continue
}
if (isTableStart(lines, index)) {
const header = splitCells(lines[index])
index += 2
const rows: string[][] = []
while (index < lines.length && lines[index].trim().includes("|") && !isSeparatorRow(lines[index].trim())) {
rows.push(splitCells(lines[index]))
index += 1
}
blocks.push(renderTable(header, rows))
continue
}
const listKind = isList(line)
if (listKind) {
const items: string[] = []
let start = 1
while (index < lines.length) {
const current = lines[index].trim()
if (!current) {
index += 1
const upcoming = lines[index]?.trim() || ""
if (isList(upcoming) !== listKind) break
continue
}
if (isList(current) !== listKind) break
if (listKind === "ol" && items.length === 0) start = Number(/^(\d+)\./.exec(current)?.[1] || "1")
const body = current.replace(listKind === "ol" ? /^\d+\.\s+/ : /^[-*]\s+/, "")
items.push(`<li>${renderInline(body)}</li>`)
index += 1
}
const startAttr = listKind === "ol" && start !== 1 ? ` start="${start}"` : ""
blocks.push(`<${listKind}${startAttr}>${items.join("")}</${listKind}>`)
continue
}
const paragraph = [renderInline(line)]
index += 1
while (index < lines.length) {
const current = lines[index].trim()
if (!current || current.startsWith("```") || /^(#{1,4})\s+/.test(current) || isList(current) || isTableStart(lines, index)) break
paragraph.push(renderInline(current))
index += 1
}
blocks.push(`<p>${paragraph.join("<br>")}</p>`)
}
return blocks.join("")
}