markdown.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. function createIcon(path: string, slot: string) {
  44. const icon = document.createElement("div")
  45. icon.setAttribute("data-component", "icon")
  46. icon.setAttribute("data-size", "small")
  47. icon.setAttribute("data-slot", slot)
  48. const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg")
  49. svg.setAttribute("data-slot", "icon-svg")
  50. svg.setAttribute("fill", "none")
  51. svg.setAttribute("viewBox", "0 0 20 20")
  52. svg.setAttribute("aria-hidden", "true")
  53. svg.innerHTML = path
  54. icon.appendChild(svg)
  55. return icon
  56. }
  57. function createCopyButton(labels: CopyLabels) {
  58. const button = document.createElement("button")
  59. button.type = "button"
  60. button.setAttribute("data-component", "icon-button")
  61. button.setAttribute("data-variant", "secondary")
  62. button.setAttribute("data-size", "small")
  63. button.setAttribute("data-slot", "markdown-copy-button")
  64. button.setAttribute("aria-label", labels.copy)
  65. button.setAttribute("title", labels.copy)
  66. button.appendChild(createIcon(iconPaths.copy, "copy-icon"))
  67. button.appendChild(createIcon(iconPaths.check, "check-icon"))
  68. return button
  69. }
  70. function setCopyState(button: HTMLButtonElement, labels: CopyLabels, copied: boolean) {
  71. if (copied) {
  72. button.setAttribute("data-copied", "true")
  73. button.setAttribute("aria-label", labels.copied)
  74. button.setAttribute("title", labels.copied)
  75. return
  76. }
  77. button.removeAttribute("data-copied")
  78. button.setAttribute("aria-label", labels.copy)
  79. button.setAttribute("title", labels.copy)
  80. }
  81. function setupCodeCopy(root: HTMLDivElement, labels: CopyLabels) {
  82. const timeouts = new Map<HTMLButtonElement, ReturnType<typeof setTimeout>>()
  83. const updateLabel = (button: HTMLButtonElement) => {
  84. const copied = button.getAttribute("data-copied") === "true"
  85. setCopyState(button, labels, copied)
  86. }
  87. const ensureWrapper = (block: HTMLPreElement) => {
  88. const parent = block.parentElement
  89. if (!parent) return
  90. const wrapped = parent.getAttribute("data-component") === "markdown-code"
  91. if (wrapped) return
  92. const wrapper = document.createElement("div")
  93. wrapper.setAttribute("data-component", "markdown-code")
  94. parent.replaceChild(wrapper, block)
  95. wrapper.appendChild(block)
  96. wrapper.appendChild(createCopyButton(labels))
  97. }
  98. const handleClick = async (event: MouseEvent) => {
  99. const target = event.target
  100. if (!(target instanceof Element)) return
  101. const button = target.closest('[data-slot="markdown-copy-button"]')
  102. if (!(button instanceof HTMLButtonElement)) return
  103. const code = button.closest('[data-component="markdown-code"]')?.querySelector("code")
  104. const content = code?.textContent ?? ""
  105. if (!content) return
  106. const clipboard = navigator?.clipboard
  107. if (!clipboard) return
  108. await clipboard.writeText(content)
  109. setCopyState(button, labels, true)
  110. const existing = timeouts.get(button)
  111. if (existing) clearTimeout(existing)
  112. const timeout = setTimeout(() => setCopyState(button, labels, false), 2000)
  113. timeouts.set(button, timeout)
  114. }
  115. const blocks = Array.from(root.querySelectorAll("pre"))
  116. for (const block of blocks) {
  117. ensureWrapper(block)
  118. }
  119. const buttons = Array.from(root.querySelectorAll('[data-slot="markdown-copy-button"]'))
  120. for (const button of buttons) {
  121. if (button instanceof HTMLButtonElement) updateLabel(button)
  122. }
  123. root.addEventListener("click", handleClick)
  124. return () => {
  125. root.removeEventListener("click", handleClick)
  126. for (const timeout of timeouts.values()) {
  127. clearTimeout(timeout)
  128. }
  129. }
  130. }
  131. function touch(key: string, value: Entry) {
  132. cache.delete(key)
  133. cache.set(key, value)
  134. if (cache.size <= max) return
  135. const first = cache.keys().next().value
  136. if (!first) return
  137. cache.delete(first)
  138. }
  139. export function Markdown(
  140. props: ComponentProps<"div"> & {
  141. text: string
  142. cacheKey?: string
  143. class?: string
  144. classList?: Record<string, boolean>
  145. },
  146. ) {
  147. const [local, others] = splitProps(props, ["text", "cacheKey", "class", "classList"])
  148. const marked = useMarked()
  149. const i18n = useI18n()
  150. const [root, setRoot] = createSignal<HTMLDivElement>()
  151. const [html] = createResource(
  152. () => local.text,
  153. async (markdown) => {
  154. if (isServer) return ""
  155. const hash = checksum(markdown)
  156. const key = local.cacheKey ?? hash
  157. if (key && hash) {
  158. const cached = cache.get(key)
  159. if (cached && cached.hash === hash) {
  160. touch(key, cached)
  161. return cached.html
  162. }
  163. }
  164. const next = await marked.parse(markdown)
  165. const safe = sanitize(next)
  166. if (key && hash) touch(key, { hash, html: safe })
  167. return safe
  168. },
  169. { initialValue: "" },
  170. )
  171. let copySetupTimer: ReturnType<typeof setTimeout> | undefined
  172. let copyCleanup: (() => void) | undefined
  173. createEffect(() => {
  174. const container = root()
  175. const content = html()
  176. if (!container) return
  177. if (isServer) return
  178. if (!content) {
  179. container.innerHTML = ""
  180. return
  181. }
  182. const temp = document.createElement("div")
  183. temp.innerHTML = content
  184. morphdom(container, temp, {
  185. childrenOnly: true,
  186. onBeforeElUpdated: (fromEl, toEl) => {
  187. if (fromEl.isEqualNode(toEl)) return false
  188. if (fromEl.getAttribute("data-component") === "markdown-code") {
  189. const fromPre = fromEl.querySelector("pre")
  190. const toPre = toEl.querySelector("pre")
  191. if (fromPre && toPre && !fromPre.isEqualNode(toPre)) {
  192. morphdom(fromPre, toPre)
  193. }
  194. return false
  195. }
  196. return true
  197. },
  198. onBeforeNodeDiscarded: (node) => {
  199. if (node instanceof Element) {
  200. if (node.getAttribute("data-slot") === "markdown-copy-button") return false
  201. if (node.getAttribute("data-component") === "markdown-code") return false
  202. }
  203. return true
  204. },
  205. })
  206. if (copySetupTimer) clearTimeout(copySetupTimer)
  207. copySetupTimer = setTimeout(() => {
  208. if (copyCleanup) copyCleanup()
  209. copyCleanup = setupCodeCopy(container, {
  210. copy: i18n.t("ui.message.copy"),
  211. copied: i18n.t("ui.message.copied"),
  212. })
  213. }, 150)
  214. })
  215. onCleanup(() => {
  216. if (copySetupTimer) clearTimeout(copySetupTimer)
  217. if (copyCleanup) copyCleanup()
  218. })
  219. return (
  220. <div
  221. data-component="markdown"
  222. classList={{
  223. ...(local.classList ?? {}),
  224. [local.class ?? ""]: !!local.class,
  225. }}
  226. ref={setRoot}
  227. {...others}
  228. />
  229. )
  230. }