markdown.tsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { useMarked } from "../context/marked"
  2. import DOMPurify from "dompurify"
  3. import { checksum } from "@opencode-ai/util/encode"
  4. import { ComponentProps, createResource, splitProps } from "solid-js"
  5. import { isServer } from "solid-js/web"
  6. type Entry = {
  7. hash: string
  8. html: string
  9. }
  10. const max = 200
  11. const cache = new Map<string, Entry>()
  12. if (typeof window !== "undefined" && DOMPurify.isSupported) {
  13. DOMPurify.addHook("afterSanitizeAttributes", (node: Element) => {
  14. if (!(node instanceof HTMLAnchorElement)) return
  15. if (node.target !== "_blank") return
  16. const rel = node.getAttribute("rel") ?? ""
  17. const set = new Set(rel.split(/\s+/).filter(Boolean))
  18. set.add("noopener")
  19. set.add("noreferrer")
  20. node.setAttribute("rel", Array.from(set).join(" "))
  21. })
  22. }
  23. const config = {
  24. USE_PROFILES: { html: true, mathMl: true },
  25. SANITIZE_NAMED_PROPS: true,
  26. FORBID_TAGS: ["style"],
  27. FORBID_CONTENTS: ["style", "script"],
  28. }
  29. function sanitize(html: string) {
  30. if (!DOMPurify.isSupported) return ""
  31. return DOMPurify.sanitize(html, config)
  32. }
  33. function touch(key: string, value: Entry) {
  34. cache.delete(key)
  35. cache.set(key, value)
  36. if (cache.size <= max) return
  37. const first = cache.keys().next().value
  38. if (!first) return
  39. cache.delete(first)
  40. }
  41. export function Markdown(
  42. props: ComponentProps<"div"> & {
  43. text: string
  44. cacheKey?: string
  45. class?: string
  46. classList?: Record<string, boolean>
  47. },
  48. ) {
  49. const [local, others] = splitProps(props, ["text", "cacheKey", "class", "classList"])
  50. const marked = useMarked()
  51. const [html] = createResource(
  52. () => local.text,
  53. async (markdown) => {
  54. if (isServer) return ""
  55. const hash = checksum(markdown)
  56. const key = local.cacheKey ?? hash
  57. if (key && hash) {
  58. const cached = cache.get(key)
  59. if (cached && cached.hash === hash) {
  60. touch(key, cached)
  61. return cached.html
  62. }
  63. }
  64. const next = await marked.parse(markdown)
  65. const safe = sanitize(next)
  66. if (key && hash) touch(key, { hash, html: safe })
  67. return safe
  68. },
  69. { initialValue: "" },
  70. )
  71. return (
  72. <div
  73. data-component="markdown"
  74. classList={{
  75. ...(local.classList ?? {}),
  76. [local.class ?? ""]: !!local.class,
  77. }}
  78. innerHTML={html.latest}
  79. {...others}
  80. />
  81. )
  82. }