:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(frontend): load code snippet highlighting on demand (#105131)
Paul D'Ambra9988381adbea
diff --git a/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsx b/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsxindex 1226fe75ee46..3a493763c3b3 100644--- a/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsx+++ b/frontend/src/lib/components/CodeSnippet/CodeSnippet.test.tsx@@ -2,12 +2,17 @@ import { act, fireEvent, render } from '@testing-library/react'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { CodeSnippet } from './CodeSnippet'+import { CodeSnippet, Language } from './CodeSnippet'jest.mock('lib/utils/copyToClipboard', () => ({copyToClipboard: jest.fn(),}))+// Every case here renders with the highlighter chunk unavailable, as after a deploy removes it.+jest.mock('./HighlightedCodeLine', () => {+ throw new Error('highlighter chunk unavailable')+})+describe('CodeSnippet', () => {beforeEach(() => {jest.clearAllMocks()@@ -31,4 +36,15 @@ describe('CodeSnippet', () => {expect(copyToClipboard).toHaveBeenCalledWith('echo hello', 'snippet')expect(onCopy).toHaveBeenCalledTimes(expectedCalls)})++ it('keeps the plain code when the highlighter fails to load', async () => {+ const { container } = render(<CodeSnippet language={Language.JavaScript}>const a = 1</CodeSnippet>)++ // The failed import settles over several microtasks, so let one macrotask pass.+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0))+ })++ expect(container.querySelector('.CodeSnippet code')?.textContent).toBe('const a = 1')+ })})diff --git a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsxindex 90d96f234f08..5d6637c13c56 100644--- a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx+++ b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx@@ -1,26 +1,25 @@import './CodeSnippet.scss'import clsx from 'clsx'-import { toHtml } from 'hast-util-to-html'-import dart from 'highlight.js/lib/languages/dart'-import elixir from 'highlight.js/lib/languages/elixir'-import groovy from 'highlight.js/lib/languages/groovy'-import http from 'highlight.js/lib/languages/http'-import { useValues } from 'kea'-import { common, createLowlight } from 'lowlight'-import React, { useMemo, useState } from 'react'+import React, { Suspense, lazy, useState } from 'react'import { IconCollapse, IconCopy, IconExpand } from '@posthog/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'-import { themeLogic } from 'lib/logic/themeLogic'import { copyToClipboard } from 'lib/utils/copyToClipboard'+import { retryImport } from 'lib/utils/retryImport'-import terraform from './terraformLanguage'+import { PlainCodeLine } from './PlainCodeLine'-// `common` already registers most of our languages (including rust, c, and cpp) — only add the missing ones.-const lowlight = createLowlight(common)-lowlight.register({ dart, elixir, groovy, http, terraform })+// highlight.js grammars are large, and markdown renders code snippets on pages that every+// logged-in user loads. Show the plain text first and add the highlighting when it arrives.+// Highlighting is cosmetic, so when the chunk cannot load (for example, a stale chunk after a+// deploy) the plain text stays, and no error boundary or page reload runs.+const HighlightedCodeLine = lazy(() =>+ retryImport(() => import('./HighlightedCodeLine'))+ .then((m) => ({ default: m.HighlightedCodeLine }))+ .catch(() => ({ default: PlainCodeLine }))+)export enum Language {Text = 'text',@@ -220,21 +219,13 @@ export function CodeLine({wrapLines: booleanlanguage: Language}): JSX.Element {- const { isDarkModeOn } = useValues(themeLogic)-- const highlighted = useMemo(- () => (lowlight.registered(language) ? lowlight.highlight(language, text) : lowlight.highlightAuto(text)),- [language, text]- )- const style = wrapLines ? ({ whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' } as const) : {}+ const wrapClassName = wrapLines ? 'whitespace-pre-wrap wrap-anywhere' : undefinedreturn (<pre className="m-0">- <code- className={clsx('hljs', isDarkModeOn && 'hljs-dark')}- style={style}- dangerouslySetInnerHTML={{ __html: toHtml(highlighted) }}- />+ <Suspense fallback={<PlainCodeLine text={text} className={wrapClassName} />}>+ <HighlightedCodeLine text={text} language={language} className={wrapClassName} />+ </Suspense></pre>)}diff --git a/frontend/src/lib/components/CodeSnippet/HighlightedCodeLine.tsx b/frontend/src/lib/components/CodeSnippet/HighlightedCodeLine.tsxnew file mode 100644index 000000000000..eaaa4de830e2--- /dev/null+++ b/frontend/src/lib/components/CodeSnippet/HighlightedCodeLine.tsx@@ -0,0 +1,41 @@+import clsx from 'clsx'+import { toHtml } from 'hast-util-to-html'+import dart from 'highlight.js/lib/languages/dart'+import elixir from 'highlight.js/lib/languages/elixir'+import groovy from 'highlight.js/lib/languages/groovy'+import http from 'highlight.js/lib/languages/http'+import { useValues } from 'kea'+import { common, createLowlight } from 'lowlight'+import { useMemo } from 'react'++import { themeLogic } from 'lib/logic/themeLogic'++import terraform from './terraformLanguage'++// `common` already registers most of our languages (including rust, c, and cpp) — only add the missing ones.+const lowlight = createLowlight(common)+lowlight.register({ dart, elixir, groovy, http, terraform })++export function HighlightedCodeLine({+ text,+ language,+ className,+}: {+ text: string+ language: string+ className?: string+}): JSX.Element {+ const { isDarkModeOn } = useValues(themeLogic)++ const highlighted = useMemo(+ () => (lowlight.registered(language) ? lowlight.highlight(language, text) : lowlight.highlightAuto(text)),+ [language, text]+ )++ return (+ <code+ className={clsx('hljs', isDarkModeOn && 'hljs-dark', className)}+ dangerouslySetInnerHTML={{ __html: toHtml(highlighted) }}+ />+ )+}diff --git a/frontend/src/lib/components/CodeSnippet/PlainCodeLine.tsx b/frontend/src/lib/components/CodeSnippet/PlainCodeLine.tsxnew file mode 100644index 000000000000..a59f74664cd4--- /dev/null+++ b/frontend/src/lib/components/CodeSnippet/PlainCodeLine.tsx@@ -0,0 +1,10 @@+import clsx from 'clsx'+import { useValues } from 'kea'++import { themeLogic } from 'lib/logic/themeLogic'++export function PlainCodeLine({ text, className }: { text: string; className?: string }): JSX.Element {+ const { isDarkModeOn } = useValues(themeLogic)++ return <code className={clsx('hljs', isDarkModeOn && 'hljs-dark', className)}>{text}</code>+}