-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathVirtualDiffRenderer.tsx
474 lines (438 loc) · 15.5 KB
/
VirtualDiffRenderer.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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/**
* The VirtualDiffRenderer component is used to render code files in a
* virtualized way that enables us to render large files without performance
* issues. This component uses TanStack Virtual to handle the virtualization of
* the code blocks we want to render. There are a few tricks hidden within
* these components to enable features to provide a better UX.
*
* We use a textarea element that is "transparent" from the user but still
* accessible to the browser. This textarea element is used to store the code
* content and is used to sync the scroll position of the code display element,
* highlight/select code for copy pasting, and also to enable users to cmd/ctrl
* + f to search for text in the code. We also use the width of the textarea to
* set the width of the code display element so the code display element can
* scroll horizontally in sync with the text area.
*/
import * as Sentry from '@sentry/react'
import { useWindowVirtualizer } from '@tanstack/react-virtual'
import Highlight, { defaultProps } from 'prism-react-renderer'
import { memo, useEffect, useRef } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { useDisablePointerEvents } from 'shared/useDisablePointerEvents'
import { cn } from 'shared/utils/cn'
import { prismLanguageMapper } from 'shared/utils/prism/prismLanguageMapper'
import { ColorBar } from './ColorBar'
import { LINE_ROW_HEIGHT } from './constants'
import { LineNumber } from './LineNumber'
import { ScrollBar } from './ScrollBar'
import { CoverageValue, Token } from './types'
import { useIsOverflowing } from './useIsOverflowing'
import { useScrollLeftSync } from './useScrollLeftSync'
import { useSyncScrollMargin } from './useSyncScrollMargin'
import { useSyncTotalWidth } from './useSyncTotalWidth'
import { useSyncWrapperWidth } from './useSyncWrapperWidth'
// prism theme is required to come before so it doesn't override our custom css
import 'shared/utils/prism/prismTheme.css'
import './VirtualFileRenderer.css'
export interface LineData {
headNumber: string | null
baseNumber: string | null
headCoverage: CoverageValue
baseCoverage: CoverageValue
hitCount: number | undefined
}
export type { CoverageValue } from './types'
interface CoverageHitCounterProps {
coverage: CoverageValue
hitCount: number | undefined
}
// exporting for testing purposes
export const CoverageHitCounter = ({
coverage,
hitCount,
}: CoverageHitCounterProps) => {
if (typeof hitCount === 'number' && hitCount > 0) {
return (
<div className="flex items-center justify-center pr-1">
<span
data-testid="coverage-hit-counter"
className={cn(
'flex content-center items-center justify-center whitespace-nowrap rounded-full px-1.5 text-center text-xs text-white',
coverage === 'M' && 'bg-ds-primary-red',
coverage === 'P' && 'bg-ds-primary-yellow',
coverage === 'H' && 'bg-ds-primary-green'
)}
>
{hitCount}
</span>
</div>
)
}
return null
}
interface CodeBodyProps {
tokens: Token[][]
getLineProps: Highlight['getLineProps']
getTokenProps: Highlight['getTokenProps']
lineData: Array<LineData>
hashedPath: string
codeDisplayOverlayRef: React.RefObject<HTMLDivElement>
wrapperWidth: number | '100%'
setWrapperRefState: React.Dispatch<
React.SetStateAction<HTMLDivElement | null>
>
}
const CodeBody = ({
tokens,
getLineProps,
getTokenProps,
lineData,
hashedPath,
codeDisplayOverlayRef,
wrapperWidth,
setWrapperRefState,
}: CodeBodyProps) => {
const history = useHistory()
const location = useLocation()
const scrollMargin = useSyncScrollMargin({
overlayRef: codeDisplayOverlayRef,
})
const virtualizer = useWindowVirtualizer({
count: tokens.length,
estimateSize: () => LINE_ROW_HEIGHT,
overscan: 45,
scrollMargin: scrollMargin ?? 0,
})
const initializeRender = useRef(true)
useEffect(() => {
if (!initializeRender.current) {
return
}
if (!codeDisplayOverlayRef.current) {
return
}
initializeRender.current = false
// set the parent div height to the total size of the virtualizer
codeDisplayOverlayRef.current.style.height = `${virtualizer.getTotalSize()}px`
codeDisplayOverlayRef.current.style.position = 'relative'
// More robust hash parsing to handle different formats
if (location.hash) {
// First try to parse the complex format: #path-[LR]number
const complexMatch = location.hash.match(/^#(.*)-([LR])(\d+)$/)
if (complexMatch && complexMatch.length === 4) {
const [, path, lineType, lineNumberStr] = complexMatch
if (path === hashedPath) {
const lineNumber = lineNumberStr
const isBase = lineType === 'L'
const isHead = lineType === 'R'
const index = lineData.findIndex(
(line) =>
(isHead && line.headNumber === lineNumber) ||
(isBase && line.baseNumber === lineNumber)
)
if (index >= 0 && index < tokens.length) {
virtualizer.scrollToIndex(index, { align: 'start' })
} else {
Sentry.captureMessage(
`Invalid line number in file renderer hash: ${location.hash}`,
{ fingerprint: ['file-renderer-invalid-line-number'] }
)
}
}
} else {
// Try to handle simple format: #Lnumber
const simpleMatch = location.hash.match(/^#L(\d+)$/)
if (simpleMatch && simpleMatch[1]) {
const lineNumber = simpleMatch[1]
// For simple format, try to find a matching base line number
const index = lineData.findIndex(
(line) => line.baseNumber === lineNumber
)
if (index >= 0 && index < tokens.length) {
virtualizer.scrollToIndex(index, { align: 'start' })
}
}
}
}
}, [
codeDisplayOverlayRef,
hashedPath,
lineData,
location.hash,
tokens.length,
virtualizer,
])
return (
// setting this function handler to this directly seems to solve the re-render issues.
<div className="flex flex-1" ref={setWrapperRefState}>
{/* this div contains the base line numbers */}
<div className="relative z-[2] h-full w-[86px] min-w-[86px] pr-[10px]">
{virtualizer.getVirtualItems().map((item) => {
const line = lineData[item.index]
const lineNumber = line?.baseNumber
const hash = `#${hashedPath}-L${lineNumber}`
let coverageValue
if (lineNumber) {
coverageValue = line.baseCoverage
}
return (
<LineNumber
key={item.index}
index={item.index}
virtualizer={virtualizer}
lineNumber={lineNumber}
item={item}
isHighlighted={location.hash === hash}
coverageValue={coverageValue}
onClick={() => {
if (lineNumber) {
location.hash = location.hash === hash ? '' : hash
history.push(location)
}
}}
/>
)
})}
</div>
<div className="relative z-[2] h-full w-[86px] min-w-[86px] pr-[10px]">
{virtualizer.getVirtualItems().map((item) => {
const line = lineData[item.index]
const lineNumber = line?.headNumber
const hash = `#${hashedPath}-R${lineNumber}`
let coverageValue
if (lineNumber) {
coverageValue = line?.headCoverage
}
return (
<LineNumber
key={item.index}
index={item.index}
virtualizer={virtualizer}
lineNumber={lineNumber}
item={item}
isHighlighted={location.hash === hash}
coverageValue={coverageValue}
onClick={() => {
if (lineNumber) {
location.hash = location.hash === hash ? '' : hash
history.push(location)
}
}}
/>
)
})}
</div>
{/* this div contains the actual code lines */}
<div
// @ts-expect-error - TODO - Update inert when inert is available in React 19
inert=""
className="pointer-events-none size-full"
>
{virtualizer.getVirtualItems().map((item) => {
const line = lineData[item.index]
const baseHash = `#${hashedPath}-L${line?.baseNumber}`
const headHash = `#${hashedPath}-R${line?.headNumber}`
// get any specific things from code highlighting library for this given line
const { style: lineStyle } = getLineProps({
// casting this cause it is guaranteed to be present in the array
line: tokens[item.index]!,
key: item.index,
})
return (
<div
ref={virtualizer.measureElement}
key={item.index}
data-index={item.index}
style={{
width: wrapperWidth,
height: `${item.size}px`,
transform: `translateY(${
item.start - virtualizer.options.scrollMargin
}px)`,
}}
className="absolute left-0 top-0 pl-[192px]"
>
<div className="grid">
<div className="z-[-1] col-start-1 row-start-1 ">
<ColorBar
isHighlighted={
location.hash === headHash || location.hash === baseHash
}
coverage={lineData?.[item.index]?.headCoverage}
/>
</div>
<div
className="col-start-1 row-start-1 flex flex-1 justify-between"
style={{
...lineStyle,
height: `${LINE_ROW_HEIGHT}px`,
lineHeight: `${LINE_ROW_HEIGHT}px`,
}}
>
<div>
{tokens[item.index]?.map((token: Token, key: React.Key) => (
<span {...getTokenProps({ token, key })} key={key} />
))}
</div>
{lineData?.[item.index]?.hitCount ? (
<CoverageHitCounter
coverage={lineData?.[item.index]?.headCoverage}
hitCount={lineData?.[item.index]?.hitCount}
/>
) : null}
</div>
</div>
</div>
)
})}
</div>
</div>
)
}
interface MemoedHighlightProps {
code: string
fileType: string
hashedPath: string
codeDisplayOverlayRef: React.RefObject<HTMLDivElement>
lineData: Array<LineData>
wrapperWidth: number | '100%'
setWrapperRefState: React.Dispatch<
React.SetStateAction<HTMLDivElement | null>
>
}
const MemoedHighlight = memo(
({
code,
fileType,
lineData,
hashedPath,
codeDisplayOverlayRef,
wrapperWidth,
setWrapperRefState,
}: MemoedHighlightProps) => (
<Highlight
{...defaultProps}
code={code}
theme={undefined}
language={prismLanguageMapper(fileType)}
>
{({ tokens, getLineProps, getTokenProps }) => (
<CodeBody
tokens={tokens}
lineData={lineData}
getLineProps={getLineProps}
getTokenProps={getTokenProps}
hashedPath={hashedPath}
codeDisplayOverlayRef={codeDisplayOverlayRef}
wrapperWidth={wrapperWidth}
setWrapperRefState={setWrapperRefState}
/>
)}
</Highlight>
)
)
MemoedHighlight.displayName = 'MemoedHighlight'
interface VirtualDiffRendererProps {
code: string
fileName: string
hashedPath: string
lineData: Array<LineData>
}
function VirtualDiffRendererComponent({
code,
fileName: fileType,
hashedPath,
lineData,
}: VirtualDiffRendererProps) {
const widthDivRef = useRef<HTMLDivElement>(null)
const codeDisplayOverlayRef = useRef<HTMLDivElement>(null)
const textAreaRef = useRef<HTMLTextAreaElement>(null)
const scrollBarRef = useRef<HTMLDivElement>(null)
const virtualCodeRendererRef = useRef<HTMLDivElement>(null)
const { wrapperWidth, setWrapperRefState } = useSyncWrapperWidth()
// disable pointer events will scrolling
useDisablePointerEvents(virtualCodeRendererRef)
// sync the width of the wrapper with the width of the text area
useSyncTotalWidth({ textAreaRef, widthDivRef })
// check if the code display overlay is overflowing, so we can conditionally render the scroll bar
const isOverflowing = useIsOverflowing(codeDisplayOverlayRef)
// sync the scroll position of the text area with the code display overlay and scroll bar
useScrollLeftSync({
scrollingRef: textAreaRef,
refsToSync: [codeDisplayOverlayRef, scrollBarRef],
})
// sync the scroll position of the scroll bar with the code display overlay and text area
useScrollLeftSync({
scrollingRef: scrollBarRef,
refsToSync: [codeDisplayOverlayRef, textAreaRef],
})
return (
<div
data-testid="virtual-file-renderer"
style={{ tabSize: '8' }}
ref={virtualCodeRendererRef}
className="relative w-full overflow-x-auto border border-solid border-ds-gray-tertiary"
>
{/**
* This text area is used to store the code content and is used to sync
* the scroll position of the code display element, highlight/select code
* for copy pasting, and also to enable users to cmd/ctrl + f to search
* for text in the code.
*/}
<textarea
ref={textAreaRef}
data-testid="virtual-file-renderer-text-area"
style={{
tabSize: '8',
overscrollBehaviorX: 'none',
lineHeight: `${LINE_ROW_HEIGHT}px`,
scrollbarWidth: 'none',
}}
className="absolute z-[1] size-full resize-none overflow-y-hidden whitespace-pre bg-[unset] pl-[192px] font-mono text-transparent outline-none"
// Directly setting the value of the text area to the code content
value={code}
// need to set to true since we're setting a value without an onChange handler
readOnly={true}
// disable all the things for text area's so it doesn't interfere with the code display element
autoCapitalize="false"
autoCorrect="false"
spellCheck="false"
inputMode="none"
aria-readonly="true"
tabIndex={0}
aria-multiline="true"
aria-haspopup="false"
/>
<div
ref={codeDisplayOverlayRef}
data-testid="virtual-file-renderer-overlay"
className="overflow-y-hidden whitespace-pre font-mono"
style={{
// @ts-expect-error - it is a legacy value that is still valid
// you can read more about it here: https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-x#values
overflowX: 'overlay',
scrollbarWidth: 'none',
}}
>
<div ref={widthDivRef} className="size-full">
<MemoedHighlight
code={code}
fileType={fileType}
lineData={lineData}
hashedPath={hashedPath}
codeDisplayOverlayRef={codeDisplayOverlayRef}
wrapperWidth={wrapperWidth}
setWrapperRefState={setWrapperRefState}
/>
</div>
</div>
{isOverflowing ? (
<ScrollBar scrollBarRef={scrollBarRef} wrapperWidth={wrapperWidth} />
) : null}
</div>
)
}
export const VirtualDiffRenderer = Sentry.withProfiler(
VirtualDiffRendererComponent,
{ name: 'VirtualDiffRenderer' }
)