Skip to content

: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.

perf(quill-charts): share one theme store across useChartTheme callers (#125515)

Ben White9179582abd2d
diff --git a/packages/quill/packages/charts/src/README.md b/packages/quill/packages/charts/src/README.md
index 0d72940432ab..1a0df0ba59bf 100644
--- a/packages/quill/packages/charts/src/README.md
+++ b/packages/quill/packages/charts/src/README.md
@@ -54,8 +54,11 @@ function App() {
}
```
-- `useChartTheme(opts?)` — React hook; re-reads the vars when the `class` / `theme`
- attribute flips on `<html>` or `<body>`.
+- `useChartTheme(opts?)` — React hook; re-reads the vars when the `class`, `theme` or
+ `data-theme` attribute changes on `<html>` or `<body>`. All calls with the same
+ options share one observer and one theme object, so calling it in every chart is
+ cheap. A chart re-renders only when a theme value changes. Treat the result as
+ read-only, because other charts hold the same object.
- `themeFromCssVars(opts?)` — one-shot, non-React read.
- `DEFAULT_CHART_COLORS` — fallback palette used when the token vars aren't loaded
(no quill-tokens stylesheet, or SSR). Without tokens loaded you get this palette,
diff --git a/packages/quill/packages/charts/src/core/theme.test.ts b/packages/quill/packages/charts/src/core/theme.test.ts
index 208b0d00c468..3376adf319a3 100644
--- a/packages/quill/packages/charts/src/core/theme.test.ts
+++ b/packages/quill/packages/charts/src/core/theme.test.ts
@@ -1,14 +1,26 @@
-import { renderHook } from '@testing-library/react'
+import { act, cleanup, renderHook } from '@testing-library/react'
import { createElement, type ReactNode } from 'react'
import { dataColorPalette } from '@posthog/quill-tokens'
-import { ChartThemeProvider, DEFAULT_CHART_COLORS, themeFromCssVars, useResolvedChartTheme } from './theme'
+import {
+ ChartThemeProvider,
+ DEFAULT_CHART_COLORS,
+ type ThemeFromCssOptions,
+ themeFromCssVars,
+ useChartTheme,
+ useResolvedChartTheme,
+} from './theme'
import type { ChartTheme } from './types'
describe('chart theme', () => {
afterEach(() => {
+ // Unmount first, so the resets below don't fire a live observer outside act().
+ cleanup()
+ jest.restoreAllMocks()
document.body.replaceChildren()
+ document.body.removeAttribute('style')
+ document.documentElement.removeAttribute('class')
})
function rootWithVars(vars: Record<string, string>): HTMLElement {
@@ -91,4 +103,74 @@ describe('chart theme', () => {
expect(result.current.colors[0]).toBe(expected)
document.body.style.removeProperty('--data-color-1')
})
+
+ function renderThemeHooks(
+ count: number,
+ options: ThemeFromCssOptions = {}
+ ): { hooks: { result: { current: ChartTheme }; unmount: () => void }[]; renders: () => number } {
+ let renders = 0
+ const hooks = Array.from({ length: count }, () =>
+ renderHook(() => {
+ renders++
+ return useChartTheme(options)
+ })
+ )
+ return { hooks, renders: () => renders }
+ }
+
+ it('shares one observer and one theme object across hook instances', () => {
+ const observe = jest.spyOn(MutationObserver.prototype, 'observe')
+
+ const { hooks } = renderThemeHooks(5)
+
+ expect(observe.mock.calls.filter(([target]) => target === document.documentElement)).toHaveLength(1)
+ expect(new Set(hooks.map((hook) => hook.result.current)).size).toBe(1)
+ })
+
+ it.each([
+ { name: 'keeps the object and skips renders when the vars are unchanged', nextColor: null },
+ { name: 'gives every caller one new object when a var changes', nextColor: '#222222' },
+ ])('on an html class change, $name', async ({ nextColor }) => {
+ document.body.style.setProperty('--data-color-1', '#111111')
+ const { hooks, renders } = renderThemeHooks(3)
+ const before = hooks[0].result.current
+ const rendersBefore = renders()
+
+ await act(async () => {
+ if (nextColor) {
+ document.body.style.setProperty('--data-color-1', nextColor)
+ }
+ document.documentElement.classList.toggle('some-unrelated-class')
+ })
+
+ const after = hooks.map((hook) => hook.result.current)
+ expect(new Set(after).size).toBe(1)
+ expect(after[0].colors[0]).toBe(nextColor ?? '#111111')
+ expect(after[0] === before).toBe(!nextColor)
+ expect(renders() - rendersBefore).toBe(nextColor ? hooks.length : 0)
+ })
+
+ it('disconnects after the last unmount and re-reads on the next mount', () => {
+ const disconnect = jest.spyOn(MutationObserver.prototype, 'disconnect')
+ document.body.style.setProperty('--data-color-1', '#111111')
+ const { hooks } = renderThemeHooks(3)
+
+ hooks.forEach((hook) => hook.unmount())
+ expect(disconnect).toHaveBeenCalledTimes(1)
+
+ document.body.style.setProperty('--data-color-1', '#222222')
+ expect(renderThemeHooks(1).hooks[0].result.current.colors[0]).toBe('#222222')
+ })
+
+ it('keeps a separate theme per root and colorCount', () => {
+ const root = rootWithVars({ '--data-color-1': '#333333' })
+
+ const [byDefault, byCount, byRoot] = [{}, { colorCount: 2 }, { root }].map(
+ (options) => renderThemeHooks(1, options).hooks[0].result.current
+ )
+
+ expect(byDefault.colors).toHaveLength(DEFAULT_CHART_COLORS.length)
+ expect(byCount.colors).toHaveLength(2)
+ expect(byRoot.colors[0]).toBe('#333333')
+ })
})
diff --git a/packages/quill/packages/charts/src/core/theme.ts b/packages/quill/packages/charts/src/core/theme.ts
index 42f8cf73d7b8..2fb87b914494 100644
--- a/packages/quill/packages/charts/src/core/theme.ts
+++ b/packages/quill/packages/charts/src/core/theme.ts
@@ -1,4 +1,4 @@
-import { createContext, useContext, useEffect, useState } from 'react'
+import { createContext, useCallback, useContext, useSyncExternalStore } from 'react'
import type { ChartTheme } from './types'
@@ -117,39 +117,122 @@ export function themeFromCssVars(options: ThemeFromCssOptions = {}): ChartTheme
}
}
+interface ThemeStore {
+ readonly options: ThemeFromCssOptions
+ theme: ChartTheme
+ /** Set while no observer runs, because a theme change in that time goes unseen. */
+ needsRead: boolean
+ readonly listeners: Set<() => void>
+ observer: MutationObserver | null
+}
+
+const FALLBACK_THEME: ChartTheme = { colors: [...DEFAULT_CHART_COLORS] }
+
+const WATCHED_ATTRIBUTES: MutationObserverInit = { attributes: true, attributeFilter: ['class', 'theme', 'data-theme'] }
+
+// Store key for an omitted `root`. The read resolves `document.body` at call time, so the key can't be the element.
+const DEFAULT_ROOT = {}
+const stores = new WeakMap<object, Map<number, ThemeStore>>()
+
+function getStore(root: HTMLElement | undefined, colorCount: number): ThemeStore {
+ const key = root ?? DEFAULT_ROOT
+ let byColorCount = stores.get(key)
+ if (!byColorCount) {
+ byColorCount = new Map()
+ stores.set(key, byColorCount)
+ }
+ let store = byColorCount.get(colorCount)
+ if (!store) {
+ store = {
+ options: { root, colorCount },
+ theme: FALLBACK_THEME,
+ needsRead: true,
+ listeners: new Set(),
+ observer: null,
+ }
+ byColorCount.set(colorCount, store)
+ }
+ return store
+}
+
+function sameValue(a: unknown, b: unknown): boolean {
+ if (Array.isArray(a) && Array.isArray(b)) {
+ return a.length === b.length && a.every((item, i) => item === b[i])
+ }
+ return a === b
+}
+
+function sameTheme(a: ChartTheme, b: ChartTheme): boolean {
+ const keys = Object.keys(a) as (keyof ChartTheme)[]
+ return keys.length === Object.keys(b).length && keys.every((key) => sameValue(a[key], b[key]))
+}
+
+function refresh(store: ThemeStore): boolean {
+ store.needsRead = false
+ const next = themeFromCssVars(store.options)
+ if (sameTheme(store.theme, next)) {
+ return false
+ }
+ store.theme = next
+ return true
+}
+
+function readSnapshot(store: ThemeStore): ChartTheme {
+ if (store.needsRead) {
+ refresh(store)
+ }
+ return store.theme
+}
+
+function subscribe(store: ThemeStore, listener: () => void): () => void {
+ store.listeners.add(listener)
+ if (!store.observer && typeof MutationObserver === 'function') {
+ const onMutation = (): void => {
+ if (refresh(store)) {
+ store.listeners.forEach((notify) => notify())
+ }
+ }
+ store.observer = new MutationObserver(onMutation)
+ store.observer.observe(document.documentElement, WATCHED_ATTRIBUTES)
+ store.observer.observe(document.body, WATCHED_ATTRIBUTES)
+ // The theme can change between the first render and this subscribe.
+ onMutation()
+ }
+ return () => {
+ store.listeners.delete(listener)
+ if (store.listeners.size === 0) {
+ store.observer?.disconnect()
+ store.observer = null
+ store.needsRead = true
+ }
+ }
+}
+
+const getServerSnapshot = (): ChartTheme => FALLBACK_THEME
+
/**
* React hook returning a {@link ChartTheme} read from the quill data-viz CSS
* vars, kept in sync as the active theme changes. Watches the `class` / `theme`
* attributes on both `<html>` and `<body>` (different toggling conventions set
* one or the other) and re-reads the vars whenever they flip.
+ * Callers with the same options share one object, so treat it as read-only.
*/
export function useChartTheme(options: ThemeFromCssOptions = {}): ChartTheme {
return useCssVarTheme(options, true)
}
-function useCssVarTheme(options: ThemeFromCssOptions, enabled: boolean): ChartTheme {
- const { root, colorCount } = options
- const [theme, setTheme] = useState<ChartTheme>(() => (enabled ? themeFromCssVars(options) : FALLBACK_THEME))
+const noopUnsubscribe = (): void => {}
- useEffect(() => {
- if (!enabled || typeof document === 'undefined' || typeof MutationObserver !== 'function') {
- return
- }
- const reread = (): void => setTheme(themeFromCssVars({ root, colorCount }))
- reread()
- const observer = new MutationObserver(reread)
- const opts: MutationObserverInit = { attributes: true, attributeFilter: ['class', 'theme', 'data-theme'] }
- observer.observe(document.documentElement, opts)
- observer.observe(document.body, opts)
- return () => observer.disconnect()
- // root/colorCount are the only inputs; options identity is intentionally ignored.
- }, [root, colorCount, enabled])
-
- return theme
+function useCssVarTheme(options: ThemeFromCssOptions, enabled: boolean): ChartTheme {
+ const store = getStore(options.root, options.colorCount ?? DEFAULT_CHART_COLORS.length)
+ const subscribeToStore = useCallback(
+ (listener: () => void) => (enabled ? subscribe(store, listener) : noopUnsubscribe),
+ [store, enabled]
+ )
+ const getSnapshot = useCallback(() => (enabled ? readSnapshot(store) : FALLBACK_THEME), [store, enabled])
+ return useSyncExternalStore(subscribeToStore, getSnapshot, getServerSnapshot)
}
-const FALLBACK_THEME: ChartTheme = { colors: [...DEFAULT_CHART_COLORS] }
-
const ChartThemeContext = createContext<ChartTheme | null>(null)
/** Gives every chart below it a theme, so a chart can omit its `theme` prop. Pass the result of