markdown.tsx 8.9 KB

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