finai/miniapp/utils/parse-image.js

28 lines
874 B
JavaScript

// 把 AI 回答里的 markdown 图片语法 ![alt](url) 从纯文本里切出来,
// 让 chat.wxml 能把图片用真正的 <image> 组件渲染 (可长按引用),
// 其余文本仍走 <text> 保持现状。
// 只识别标准 markdown image, 不解析加粗/列表等其他语法。
const IMG_RE = /!\[[^\]]*\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)/g
function splitMarkdownImages(text) {
const src = String(text || '')
if (!src) return []
const out = []
let cursor = 0
IMG_RE.lastIndex = 0
let m
while ((m = IMG_RE.exec(src)) !== null) {
if (m.index > cursor) {
out.push({ type: 'text', text: src.slice(cursor, m.index) })
}
out.push({ type: 'img', src: m[1] })
cursor = IMG_RE.lastIndex
}
if (cursor < src.length) {
out.push({ type: 'text', text: src.slice(cursor) })
}
return out
}
module.exports = { splitMarkdownImages }