Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Memoize Highlight so it does not re-render on line click #3123

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 40 additions & 17 deletions src/ui/VirtualFileRenderer/VirtualFileRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { useWindowVirtualizer } from '@tanstack/react-virtual'
import { Dictionary } from 'lodash'
import isNaN from 'lodash/isNaN'
import Highlight, { defaultProps } from 'prism-react-renderer'
import { useLayoutEffect, useRef, useState } from 'react'
import { memo, useLayoutEffect, useRef, useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'

import { requestAnimationTimeout } from 'shared/utils/animationFrameUtils'
Expand Down Expand Up @@ -239,7 +239,40 @@ const CodeBody = ({
)
}

CodeBody.displayName = 'CodeBody'
interface MemoedHighlightProps {
code: string
fileType: string
coverage?: Dictionary<'H' | 'M' | 'P'>
codeDisplayOverlayRef: React.RefObject<HTMLDivElement>
}

const MemoedHighlight = memo(
({
code,
coverage,
fileType,
codeDisplayOverlayRef,
}: MemoedHighlightProps) => (
<Highlight
{...defaultProps}
code={code}
theme={undefined}
language={prismLanguageMapper(fileType)}
>
{({ tokens, getLineProps, getTokenProps }) => (
<CodeBody
tokens={tokens}
coverage={coverage}
getLineProps={getLineProps}
getTokenProps={getTokenProps}
codeDisplayOverlayRef={codeDisplayOverlayRef}
/>
)}
</Highlight>
)
)

MemoedHighlight.displayName = 'MemoedHighlight'

interface VirtualFileRendererProps {
code: string
Expand Down Expand Up @@ -396,22 +429,12 @@ export function VirtualFileRenderer({
}}
>
<div ref={widthDivRef} className="w-full">
<Highlight
{...defaultProps}
<MemoedHighlight
code={code}
theme={undefined}
language={prismLanguageMapper(fileType)}
>
{({ tokens, getLineProps, getTokenProps }) => (
<CodeBody
tokens={tokens}
coverage={coverage}
getLineProps={getLineProps}
getTokenProps={getTokenProps}
codeDisplayOverlayRef={codeDisplayOverlayRef}
/>
)}
</Highlight>
fileType={fileType}
coverage={coverage}
codeDisplayOverlayRef={codeDisplayOverlayRef}
/>
</div>
</div>
</div>
Expand Down
Loading