forked from DA0-DA0/dao-dao-ui
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MarkdownRenderer.tsx
192 lines (177 loc) · 5.36 KB
/
MarkdownRenderer.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { Check, Link } from '@mui/icons-material'
import clsx from 'clsx'
import { ComponentType, createElement, useEffect, useState } from 'react'
import toast from 'react-hot-toast'
import { useTranslation } from 'react-i18next'
import ReactMarkdown from 'react-markdown'
import { HeadingComponent } from 'react-markdown/lib/ast-to-react'
import rehypeSanitize from 'rehype-sanitize'
import remarkGfm from 'remark-gfm'
import { Transformer } from 'unified'
import { Node } from 'unist'
import { visitParents } from 'unist-util-visit-parents'
import { StatefulEntityDisplayProps } from '@dao-dao/types'
import { isValidBech32Address } from '@dao-dao/utils'
import { IconButton } from './icon_buttons/IconButton'
const ENTITY_DISPLAY_NODE_TAG = 'entityDisplay'
type NodeOrElement = Node & {
value?: string
tagName?: string
children?: NodeOrElement[]
properties?: Record<string, unknown>
}
export type MarkdownRendererProps = {
markdown: string
// Adds buttons to copy anchor URLs to the clipboard.
addAnchors?: boolean
className?: string
// If present, will try to render detected addresses as entities.
EntityDisplay?: ComponentType<StatefulEntityDisplayProps>
}
export const MarkdownRenderer = ({
markdown,
addAnchors,
className,
EntityDisplay,
}: MarkdownRendererProps) => (
<ReactMarkdown
className={clsx(
'prose prose-sm overflow-auto break-words dark:prose-invert',
className
)}
components={{
...(addAnchors
? {
h1: HeadingRenderer,
h2: HeadingRenderer,
h3: HeadingRenderer,
h4: HeadingRenderer,
h5: HeadingRenderer,
h6: HeadingRenderer,
}
: undefined),
...(EntityDisplay
? {
[ENTITY_DISPLAY_NODE_TAG]: EntityDisplay,
}
: undefined),
}}
linkTarget="_blank"
rawSourcePos
rehypePlugins={[
rehypeSanitize,
...(EntityDisplay ? [remarkEntityDisplay] : []),
]}
remarkPlugins={[remarkGfm]}
>
{markdown}
</ReactMarkdown>
)
const HeadingRenderer: HeadingComponent = ({
children,
level,
sourcePosition,
}) => {
const { t } = useTranslation()
const [copied, setCopied] = useState(false)
// Unset copied after 2 seconds.
useEffect(() => {
const timeout = setTimeout(() => setCopied(false), 2000)
// Cleanup on unmount.
return () => clearTimeout(timeout)
}, [copied])
const id = `L${sourcePosition!.start.line}`
return createElement(
'h' + level,
{
id,
onClick: () => {
const url = new URL(window.location.href)
url.hash = '#' + id
navigator.clipboard.writeText(url.href)
setCopied(true)
toast.success(t('info.copiedLinkToClipboard'))
},
className: 'group flex flex-row gap-4 items-center cursor-pointer',
},
[
<span key="children">{children}</span>,
<IconButton
key="copy"
Icon={copied ? Check : Link}
className="leading-none opacity-0 transition-opacity group-hover:opacity-100"
size="sm"
variant="none"
/>,
]
)
}
// Detect valid bech32 addresses in text nodes and replace them with
// EntityDisplay nodes.
const remarkEntityDisplay = () => {
const transformer: Transformer = (tree) => {
visitParents(tree, (node, ancestors) => {
const { value } = node as unknown as { value?: string }
if (node.type === 'text' && typeof value === 'string') {
const parent = ancestors[ancestors.length - 1]
if (!parent) {
return
}
const nodeIndex = (parent as { children: Node[] }).children.indexOf(
node
)
if (nodeIndex < 0) {
return
}
const words = value.split(' ')
const newNodes = words.reduce((nodes, word) => {
if (isValidBech32Address(word)) {
// Append entity display node.
nodes.push({
type: 'element',
tagName: ENTITY_DISPLAY_NODE_TAG,
children: [],
properties: {
address: word,
className: clsx(
'!inline-flex',
// If surrounded by other words, add some margin and
// translation to position it in line with text. If in its own
// element, no need for margin and translation.
words.length > 1 && 'translate-y-[0.375rem] p-2'
),
copyToClipboardProps: {
textClassName: 'm-0',
},
},
})
} else {
// Append word to last node if it is a text node, otherwise add a
// new text node.
const lastNode = nodes[nodes.length - 1]
if (lastNode && lastNode.type === 'text') {
lastNode.value += ' ' + word
} else {
nodes.push({
type: 'text',
value: word,
})
}
}
return nodes
}, [] as NodeOrElement[])
// If nothing changed, do nothing.
if (newNodes.length === 1 && newNodes[0].type === 'text') {
return
}
// Otherwise, replace the current node with the new nodes.
;(parent as { children: Node[] }).children.splice(
nodeIndex,
1,
...newNodes
)
}
})
}
return transformer
}