markdown.tsx 10.0 KB

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