/
text.js
256 lines (231 loc) · 8.95 KB
/
text.js
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import styles from './text.module.css'
import ReactMarkdown from 'react-markdown'
import YouTube from 'react-youtube'
import gfm from 'remark-gfm'
import { LightAsync as SyntaxHighlighter } from 'react-syntax-highlighter'
import atomDark from 'react-syntax-highlighter/dist/cjs/styles/prism/atom-dark'
import mention from '@/lib/remark-mention'
import sub from '@/lib/remark-sub'
import React, { useState, memo, useRef, useCallback, useMemo, useEffect } from 'react'
import GithubSlugger from 'github-slugger'
import LinkIcon from '@/svgs/link.svg'
import Thumb from '@/svgs/thumb-up-fill.svg'
import { toString } from 'mdast-util-to-string'
import copy from 'clipboard-copy'
import ZoomableImage, { decodeOriginalUrl } from './image'
import { IMGPROXY_URL_REGEXP, parseInternalLinks } from '@/lib/url'
import reactStringReplace from 'react-string-replace'
import { rehypeInlineCodeProperty } from '@/lib/md'
import { Button } from 'react-bootstrap'
import { useRouter } from 'next/router'
import Link from 'next/link'
import { UNKNOWN_LINK_REL } from '@/lib/constants'
import isEqual from 'lodash/isEqual'
export function SearchText ({ text }) {
return (
<div className={styles.text}>
<p className={styles.p}>
{reactStringReplace(text, /\*\*\*([^*]+)\*\*\*/g, (match, i) => {
return <mark key={`strong-${match}-${i}`}>{match}</mark>
})}
</p>
</div>
)
}
// this is one of the slowest components to render
export default memo(function Text ({ rel, imgproxyUrls, children, tab, itemId, outlawed, topLevel, noFragments }) {
const [overflowing, setOverflowing] = useState(false)
const router = useRouter()
const [show, setShow] = useState(false)
const containerRef = useRef(null)
useEffect(() => {
setShow(router.asPath.includes('#'))
const handleRouteChange = (url, { shallow }) => {
setShow(url.includes('#'))
}
router.events.on('hashChangeStart', handleRouteChange)
return () => {
router.events.off('hashChangeStart', handleRouteChange)
}
}, [router])
useEffect(() => {
const container = containerRef.current
if (!container || overflowing) return
function checkOverflow () {
setOverflowing(container.scrollHeight > window.innerHeight * 2)
}
let resizeObserver
if (!overflowing && 'ResizeObserver' in window) {
resizeObserver = new window.ResizeObserver(checkOverflow).observe(container)
}
window.addEventListener('resize', checkOverflow)
checkOverflow()
return () => {
window.removeEventListener('resize', checkOverflow)
resizeObserver?.disconnect()
}
}, [containerRef.current, setOverflowing])
const slugger = new GithubSlugger()
const Heading = useCallback(({ children, node, ...props }) => {
const [copied, setCopied] = useState(false)
const nodeText = toString(node)
const id = useMemo(() => noFragments ? undefined : slugger?.slug(nodeText.replace(/[^\w\-\s]+/gi, '')), [nodeText, noFragments, slugger])
const h = useMemo(() => {
if (topLevel) {
return node?.TagName
}
const h = parseInt(node?.tagName?.replace('h', '') || 0)
if (h < 4) return `h${h + 3}`
return 'h6'
}, [node, topLevel])
const Icon = copied ? Thumb : LinkIcon
return (
<span className={styles.heading}>
{React.createElement(h || node?.tagName, { id, ...props }, children)}
{!noFragments && topLevel &&
<a className={`${styles.headingLink} ${copied ? styles.copied : ''}`} href={`#${id}`}>
<Icon
onClick={() => {
const location = new URL(window.location)
location.hash = `${id}`
copy(location.href)
setTimeout(() => setCopied(false), 1500)
setCopied(true)
}}
width={18}
height={18}
className='fill-grey'
/>
</a>}
</span>
)
}, [topLevel, noFragments, slugger.current])
const Table = useCallback(({ node, ...props }) =>
<span className='table-responsive'>
<table className='table table-bordered table-sm' {...props} />
</span>, [])
const Code = useCallback(({ node, inline, className, children, style, ...props }) => {
return inline
? (
<code className={className} {...props}>
{children}
</code>
)
: (
<SyntaxHighlighter style={atomDark} language='text' PreTag='div' {...props}>
{children}
</SyntaxHighlighter>
)
}, [])
const P = useCallback(({ children, node, ...props }) => <div className={styles.p} {...props}>{children}</div>, [])
const Img = useCallback(({ node, src, ...props }) => {
const url = IMGPROXY_URL_REGEXP.test(src) ? decodeOriginalUrl(src) : src
// if outlawed, render the image link as text
if (outlawed) {
return url
}
const srcSet = imgproxyUrls?.[url]
return <ZoomableImage srcSet={srcSet} tab={tab} src={src} rel={rel ?? UNKNOWN_LINK_REL} {...props} topLevel />
}, [imgproxyUrls, topLevel, tab])
return (
<div className={`${styles.text} ${show ? styles.textUncontained : overflowing ? styles.textContained : ''}`} ref={containerRef}>
<ReactMarkdown
components={{
h1: Heading,
h2: Heading,
h3: Heading,
h4: Heading,
h5: Heading,
h6: Heading,
table: Table,
p: P,
li: props => {
return <li {...props} id={props.id && itemId ? `${props.id}-${itemId}` : props.id} />
},
code: Code,
a: ({ node, href, children, ...props }) => {
children = children ? Array.isArray(children) ? children : [children] : []
// don't allow zoomable images to be wrapped in links
if (children.some(e => e?.props?.node?.tagName === 'img')) {
return <>{children}</>
}
// if outlawed, render the link as text
if (outlawed) {
return href
}
// If [text](url) was parsed as <a> and text is not empty and not a link itself,
// we don't render it as an image since it was probably a conscious choice to include text.
const text = children[0]
let url
try {
url = !href.startsWith('/') && new URL(href)
} catch {
// ignore invalid URLs
}
const internalURL = process.env.NEXT_PUBLIC_URL
if (!!text && !/^https?:\/\//.test(text)) {
if (props['data-footnote-ref'] || typeof props['data-footnote-backref'] !== 'undefined') {
return (
<Link
{...props}
id={props.id && itemId ? `${props.id}-${itemId}` : props.id}
href={itemId ? `${href}-${itemId}` : href}
>{text}
</Link>
)
}
if (href.startsWith('/') || url?.origin === internalURL) {
return (
<Link
id={props.id}
href={href}
>
{text}
</Link>
)
}
return (
// eslint-disable-next-line
<a id={props.id} target='_blank' rel={rel ?? UNKNOWN_LINK_REL} href={href}>{text}</a>
)
}
try {
const linkText = parseInternalLinks(href)
if (linkText) {
return <Link href={href}>{linkText}</Link>
}
} catch {
// ignore errors like invalid URLs
}
// if the link is to a youtube video, render the video
const youtube = href.match(/(https?:\/\/)?((www\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/)|youtu\.be\/)(?<id>[_0-9a-z-]+)((?:\?|&)(?:t|start)=(?<start>\d+))?/i)
if (youtube?.groups?.id) {
return (
<div style={{ maxWidth: topLevel ? '640px' : '320px', paddingRight: '15px', margin: '0.5rem 0' }}>
<YouTube
videoId={youtube.groups.id} className={styles.youtubeContainer} opts={{
playerVars: {
start: youtube?.groups?.start
}
}}
/>
</div>
)
}
// assume the link is an image which will fallback to link if it's not
return <Img src={href} rel={rel ?? UNKNOWN_LINK_REL} {...props}>{children}</Img>
},
img: Img
}}
remarkPlugins={[gfm, mention, sub]}
rehypePlugins={[rehypeInlineCodeProperty]}
>
{children}
</ReactMarkdown>
{overflowing && !show &&
<Button size='lg' variant='info' className={styles.textShowFull} onClick={() => setShow(true)}>
show full text
</Button>}
</div>
)
}, isEqual)