markdown.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import { useMarked } from "../context/marked"
  2. import { useI18n } from "../context/i18n"
  3. import DOMPurify from "dompurify"
  4. import morphdom from "morphdom"
  5. import { checksum } from "@opencode-ai/core/util/encode"
  6. import { ComponentProps, createEffect, createResource, createSignal, onCleanup, splitProps } from "solid-js"
  7. import { isServer } from "solid-js/web"
  8. import { stream } from "./markdown-stream"
  9. type Entry = {
  10. hash: string
  11. html: string
  12. }
  13. const max = 200
  14. const cache = new Map<string, Entry>()
  15. if (typeof window !== "undefined" && DOMPurify.isSupported) {
  16. DOMPurify.addHook("afterSanitizeAttributes", (node: Element) => {
  17. if (!(node instanceof HTMLAnchorElement)) return
  18. if (node.target !== "_blank") return
  19. const rel = node.getAttribute("rel") ?? ""
  20. const set = new Set(rel.split(/\s+/).filter(Boolean))
  21. set.add("noopener")
  22. set.add("noreferrer")
  23. node.setAttribute("rel", Array.from(set).join(" "))
  24. })
  25. }
  26. const config = {
  27. USE_PROFILES: { html: true, mathMl: true },
  28. SANITIZE_NAMED_PROPS: true,
  29. FORBID_TAGS: ["style"],
  30. FORBID_CONTENTS: ["style", "script"],
  31. ADD_TAGS: ["svg", "path"],
  32. ADD_ATTR: ["d", "viewBox", "preserveAspectRatio", "xmlns"],
  33. }
  34. const iconPaths = {
  35. copy: '<path d="M6.2513 6.24935V2.91602H17.0846V13.7493H13.7513M13.7513 6.24935V17.0827H2.91797V6.24935H13.7513Z" stroke="currentColor" stroke-linecap="round"/>',
  36. check: '<path d="M5 11.9657L8.37838 14.7529L15 5.83398" stroke="currentColor" stroke-linecap="square"/>',
  37. }
  38. function sanitize(html: string) {
  39. if (!DOMPurify.isSupported) return ""
  40. return DOMPurify.sanitize(html, config)
  41. }
  42. function escape(text: string) {
  43. return text
  44. .replace(/&/g, "&amp;")
  45. .replace(/</g, "&lt;")
  46. .replace(/>/g, "&gt;")
  47. .replace(/"/g, "&quot;")
  48. .replace(/'/g, "&#39;")
  49. }
  50. function fallback(markdown: string) {
  51. return escape(markdown).replace(/\r\n?/g, "\n").replace(/\n/g, "<br>")
  52. }
  53. type CopyLabels = {
  54. copy: string
  55. copied: string
  56. }
  57. const urlPattern = /^https?:\/\/[^\s<>()`"']+$/
  58. function codeUrl(text: string) {
  59. const href = text.trim().replace(/[),.;!?]+$/, "")
  60. if (!urlPattern.test(href)) return
  61. try {
  62. const url = new URL(href)
  63. return url.toString()
  64. } catch {
  65. return
  66. }
  67. }
  68. function createIcon(path: string, slot: string) {
  69. const icon = document.createElement("div")
  70. icon.setAttribute("data-component", "icon")
  71. icon.setAttribute("data-size", "small")
  72. icon.setAttribute("data-slot", slot)
  73. const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
  74. svg.setAttribute("data-slot", "icon-svg")
  75. svg.setAttribute("fill", "none")
  76. svg.setAttribute("viewBox", "0 0 20 20")
  77. svg.setAttribute("aria-hidden", "true")
  78. svg.innerHTML = path
  79. icon.appendChild(svg)
  80. return icon
  81. }
  82. function createCopyButton(labels: CopyLabels) {
  83. const button = document.createElement("button")
  84. button.type = "button"
  85. button.setAttribute("data-component", "icon-button")
  86. button.setAttribute("data-variant", "secondary")
  87. button.setAttribute("data-size", "small")
  88. button.setAttribute("data-slot", "markdown-copy-button")
  89. button.setAttribute("aria-label", labels.copy)
  90. button.setAttribute("data-tooltip", labels.copy)
  91. button.appendChild(createIcon(iconPaths.copy, "copy-icon"))
  92. button.appendChild(createIcon(iconPaths.check, "check-icon"))
  93. return button
  94. }
  95. function setCopyState(button: HTMLButtonElement, labels: CopyLabels, copied: boolean) {
  96. if (copied) {
  97. button.setAttribute("data-copied", "true")
  98. button.setAttribute("aria-label", labels.copied)
  99. button.setAttribute("data-tooltip", labels.copied)
  100. return
  101. }
  102. button.removeAttribute("data-copied")
  103. button.setAttribute("aria-label", labels.copy)
  104. button.setAttribute("data-tooltip", labels.copy)
  105. }
  106. function ensureCodeWrapper(block: HTMLPreElement, labels: CopyLabels) {
  107. const parent = block.parentElement
  108. if (!parent) return
  109. const wrapped = parent.getAttribute("data-component") === "markdown-code"
  110. if (!wrapped) {
  111. const wrapper = document.createElement("div")
  112. wrapper.setAttribute("data-component", "markdown-code")
  113. parent.replaceChild(wrapper, block)
  114. wrapper.appendChild(block)
  115. wrapper.appendChild(createCopyButton(labels))
  116. return
  117. }
  118. const buttons = Array.from(parent.querySelectorAll('[data-slot="markdown-copy-button"]')).filter(
  119. (el): el is HTMLButtonElement => el instanceof HTMLButtonElement,
  120. )
  121. if (buttons.length === 0) {
  122. parent.appendChild(createCopyButton(labels))
  123. return
  124. }
  125. for (const button of buttons.slice(1)) {
  126. button.remove()
  127. }
  128. }
  129. function markCodeLinks(root: HTMLDivElement) {
  130. const codeNodes = Array.from(root.querySelectorAll(":not(pre) > code"))
  131. for (const code of codeNodes) {
  132. const href = codeUrl(code.textContent ?? "")
  133. const parentLink =
  134. code.parentElement instanceof HTMLAnchorElement && code.parentElement.classList.contains("external-link")
  135. ? code.parentElement
  136. : null
  137. if (!href) {
  138. if (parentLink) parentLink.replaceWith(code)
  139. continue
  140. }
  141. if (parentLink) {
  142. parentLink.href = href
  143. continue
  144. }
  145. const link = document.createElement("a")
  146. link.href = href
  147. link.className = "external-link"
  148. link.target = "_blank"
  149. link.rel = "noopener noreferrer"
  150. code.parentNode?.replaceChild(link, code)
  151. link.appendChild(code)
  152. }
  153. }
  154. function decorate(root: HTMLDivElement, labels: CopyLabels) {
  155. const blocks = Array.from(root.querySelectorAll("pre"))
  156. for (const block of blocks) {
  157. ensureCodeWrapper(block, labels)
  158. }
  159. markCodeLinks(root)
  160. }
  161. function setupCodeCopy(root: HTMLDivElement, getLabels: () => CopyLabels) {
  162. const timeouts = new Map<HTMLButtonElement, ReturnType<typeof setTimeout>>()
  163. const updateLabel = (button: HTMLButtonElement) => {
  164. const labels = getLabels()
  165. const copied = button.getAttribute("data-copied") === "true"
  166. setCopyState(button, labels, copied)
  167. }
  168. const handleClick = async (event: MouseEvent) => {
  169. const target = event.target
  170. if (!(target instanceof Element)) return
  171. const button = target.closest('[data-slot="markdown-copy-button"]')
  172. if (!(button instanceof HTMLButtonElement)) return
  173. const code = button.closest('[data-component="markdown-code"]')?.querySelector("code")
  174. const content = code?.textContent ?? ""
  175. if (!content) return
  176. const clipboard = navigator?.clipboard
  177. if (!clipboard) return
  178. await clipboard.writeText(content)
  179. const labels = getLabels()
  180. setCopyState(button, labels, true)
  181. const existing = timeouts.get(button)
  182. if (existing) clearTimeout(existing)
  183. const timeout = setTimeout(() => setCopyState(button, labels, false), 2000)
  184. timeouts.set(button, timeout)
  185. }
  186. const buttons = Array.from(root.querySelectorAll('[data-slot="markdown-copy-button"]'))
  187. for (const button of buttons) {
  188. if (button instanceof HTMLButtonElement) updateLabel(button)
  189. }
  190. root.addEventListener("click", handleClick)
  191. return () => {
  192. root.removeEventListener("click", handleClick)
  193. for (const timeout of timeouts.values()) {
  194. clearTimeout(timeout)
  195. }
  196. }
  197. }
  198. function touch(key: string, value: Entry) {
  199. cache.delete(key)
  200. cache.set(key, value)
  201. if (cache.size <= max) return
  202. const first = cache.keys().next().value
  203. if (!first) return
  204. cache.delete(first)
  205. }
  206. export function Markdown(
  207. props: ComponentProps<"div"> & {
  208. text: string
  209. cacheKey?: string
  210. streaming?: boolean
  211. class?: string
  212. classList?: Record<string, boolean>
  213. },
  214. ) {
  215. const [local, others] = splitProps(props, ["text", "cacheKey", "streaming", "class", "classList"])
  216. const marked = useMarked()
  217. const i18n = useI18n()
  218. const [root, setRoot] = createSignal<HTMLDivElement>()
  219. const [html] = createResource(
  220. () => ({
  221. text: local.text,
  222. key: local.cacheKey,
  223. streaming: local.streaming ?? false,
  224. }),
  225. async (src) => {
  226. if (isServer) return fallback(src.text)
  227. if (!src.text) return ""
  228. const base = src.key ?? checksum(src.text)
  229. return Promise.all(
  230. stream(src.text, src.streaming).map(async (block, index) => {
  231. const hash = checksum(block.raw)
  232. const key = base ? `${base}:${index}:${block.mode}` : hash
  233. if (key && hash) {
  234. const cached = cache.get(key)
  235. if (cached && cached.hash === hash) {
  236. touch(key, cached)
  237. return cached.html
  238. }
  239. }
  240. const next = await Promise.resolve(marked.parse(block.src))
  241. const safe = sanitize(next)
  242. if (key && hash) touch(key, { hash, html: safe })
  243. return safe
  244. }),
  245. )
  246. .then((list) => list.join(""))
  247. .catch(() => fallback(src.text))
  248. },
  249. { initialValue: fallback(local.text) },
  250. )
  251. let copyCleanup: (() => void) | undefined
  252. createEffect(() => {
  253. const container = root()
  254. const content = local.text ? (html.latest ?? html() ?? "") : ""
  255. if (!container) return
  256. if (isServer) return
  257. if (!content) {
  258. container.innerHTML = ""
  259. return
  260. }
  261. const labels = {
  262. copy: i18n.t("ui.message.copy"),
  263. copied: i18n.t("ui.message.copied"),
  264. }
  265. const temp = document.createElement("div")
  266. temp.innerHTML = content
  267. decorate(temp, labels)
  268. morphdom(container, temp, {
  269. childrenOnly: true,
  270. onBeforeElUpdated: (fromEl, toEl) => {
  271. if (
  272. fromEl instanceof HTMLButtonElement &&
  273. toEl instanceof HTMLButtonElement &&
  274. fromEl.getAttribute("data-slot") === "markdown-copy-button" &&
  275. toEl.getAttribute("data-slot") === "markdown-copy-button" &&
  276. fromEl.getAttribute("data-copied") === "true"
  277. ) {
  278. setCopyState(toEl, labels, true)
  279. }
  280. if (fromEl.isEqualNode(toEl)) return false
  281. return true
  282. },
  283. })
  284. if (!copyCleanup)
  285. copyCleanup = setupCodeCopy(container, () => ({
  286. copy: i18n.t("ui.message.copy"),
  287. copied: i18n.t("ui.message.copied"),
  288. }))
  289. })
  290. onCleanup(() => {
  291. if (copyCleanup) copyCleanup()
  292. })
  293. return (
  294. <div
  295. data-component="markdown"
  296. classList={{
  297. ...local.classList,
  298. [local.class ?? ""]: !!local.class,
  299. }}
  300. ref={setRoot}
  301. {...others}
  302. />
  303. )
  304. }