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.

fix(insights): improve conditional formatting cell contrast in dark mode (#69316)

Sam Pennington97b963390698
diff --git a/common/storybook/.storybook/test-runner.ts b/common/storybook/.storybook/test-runner.ts
index e9e2dc87dbb5..7d4438f5731f 100644
--- a/common/storybook/.storybook/test-runner.ts
+++ b/common/storybook/.storybook/test-runner.ts
@@ -73,6 +73,12 @@ declare module 'storybook/internal/types' {
* Skip taking a dark mode snapshot. Useful for stories that don't support dark mode or have known issues in dark mode that would cause snapshot failures.
*/
skipDarkMode?: boolean
+ /**
+ * Skip taking a light mode snapshot. Useful for stories that pin themselves to dark mode
+ * (e.g. via story globals plus a mocked `theme_mode: 'dark'` user), where the light
+ * snapshot would render dark-computed values on a light background.
+ */
+ skipLightMode?: boolean
/**
* Suppress quill-charts canvas painting for this story's snapshot, avoiding flake from
* the charts' async paint. Handled by the `withChartCanvasSnapshot` decorator.
@@ -193,7 +199,11 @@ async function expectStoryToMatchSnapshot(
storyContext: StoryContext,
browser: SupportedBrowserName
): Promise<void> {
- const { skipIframeWait = false, skipDarkMode = false } = storyContext.parameters?.testOptions ?? {}
+ const {
+ skipIframeWait = false,
+ skipDarkMode = false,
+ skipLightMode = false,
+ } = storyContext.parameters?.testOptions ?? {}
await waitForPageReady(page, skipIframeWait)
// set up iframe load tracking early, before they start loading
@@ -283,7 +293,9 @@ async function expectStoryToMatchSnapshot(
}
// Snapshot both light and dark themes
- await takeSnapshotWithTheme(page, context, browser, 'light', storyContext)
+ if (!skipLightMode) {
+ await takeSnapshotWithTheme(page, context, browser, 'light', storyContext)
+ }
if (!skipDarkMode) {
await takeSnapshotWithTheme(page, context, browser, 'dark', storyContext)
}
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 254c154a17e9..e59fbc45779f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5994,6 +5994,10 @@ snapshots:
hash: v1.k794b7964.cc00450e03b730779f839814262f45aeb016075628e7b2e0fa3e49aec6f1fc7f.TF1Ss23Q9i7h6r3Lw4bezladG79Kyif_CYHRGhWsOmg
scenes-app-insights-sqllinechart--sql-line-chart-trend-line-quill--light:
hash: v1.k794b7964.c446ceed66b1a6056048603e17712a321d2689665867604245510d335c5fc547.aEjCQVGwfNkQ49GMID3RZuoXhA8T_hAD2xalr1WcXIE
+ scenes-app-insights-sqltableconditionalformatting--conditional-formatting-dark--dark:
+ hash: v1.k794b7964.6a09bd0fd015c4e072926c1ae2c7aa6e63245d8a202f2115894ad9294966a827.dHUY30WwiPjsAuOOqE5STWSsx4s1yBR_3KVczyNzR6M
+ scenes-app-insights-sqltableconditionalformatting--conditional-formatting-light--light:
+ hash: v1.k794b7964.d36479c0918232c1699974423947f5e4275220dd73407bb43b61aa5d1db72ce2.wHTxjjrO1gIW4D1_-JQ9Dby_EnWKug6pdte84r-Nvq8
scenes-app-legal-documents--legal-documents-list--dark:
hash: v1.k794b7964.9cb90971cdadb1eadf912754aeb2a82d4fcaf5d91aa716a39bed7b324e8f03be.M6963VTBjXD11KLz9OLd6vbdx2IBcrzUYEli26SO2as
scenes-app-legal-documents--legal-documents-list--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/ConditionalFormatting/ConditionalFormattingTab.tsx b/frontend/src/queries/nodes/DataVisualization/Components/ConditionalFormatting/ConditionalFormattingTab.tsx
index f9eaaab079d4..620093a4cef9 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/ConditionalFormatting/ConditionalFormattingTab.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/ConditionalFormatting/ConditionalFormattingTab.tsx
@@ -19,7 +19,7 @@ import { dataVisualizationLogic } from '../../dataVisualizationLogic'
import { FORMATTING_TEMPLATES } from '../../types'
import { conditionalFormattingLogic } from './conditionalFormattingLogic'
-const DEFAULT_PICKER_COLORS = [
+export const DEFAULT_PICKER_COLORS = [
'#FFADAD', // Current default
'#E8A598',
'#FFD6A5',
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx
index 2111d561f4a6..9f0f4d79b1f3 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx
@@ -10,6 +10,7 @@ import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { HeatmapSettings } from '~/queries/schema/schema-general'
+import { getContrastingTextClass } from '../../colorUtils'
import { dataVisualizationLogic } from '../../dataVisualizationLogic'
import {
buildFallbackGradientStops,
@@ -17,7 +18,6 @@ import {
formatHeatmapValue,
getHeatmapNullLabel,
getHeatmapNullValue,
- getHeatmapTextClassName,
interpolateHeatmapColor,
resolveGradientStops,
stretchGradientStopsToValues,
@@ -365,7 +365,7 @@ export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?:
key={`${yValue}-${xValue}`}
className={clsx(
'border border-border px-2 py-1 text-center',
- cellValue !== null && getHeatmapTextClassName(cellColor)
+ cellValue !== null && getContrastingTextClass(cellColor)
)}
style={{ backgroundColor: cellColor }}
>
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts
index b62ee3c7bf51..1fb4e8535992 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/heatmapUtils.ts
@@ -183,12 +183,6 @@ export const interpolateHeatmapColor = (value: number, stops: HeatmapGradientSto
return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
-export const getHeatmapTextClassName = (color: string): string => {
- const { r, g, b } = hexToRGB(color)
- const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
- return luminance < 140 ? 'text-white' : 'text-primary'
-}
-
const isNullishHeatmapValue = (value: unknown): boolean => {
if (value === null || value === undefined || value === '') {
return true
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
index 847cd92e2313..38e1a3aefdf5 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
@@ -18,6 +18,7 @@ import { QueryContext } from '~/queries/types'
import { LoadNext } from '../../DataNode/LoadNext'
import { renderColumn } from '../../DataTable/renderColumn'
import { renderColumnMeta } from '../../DataTable/renderColumnMeta'
+import { getContrastingTextClass } from '../colorUtils'
import { TableDataCell, convertTableValue, dataVisualizationLogic } from '../dataVisualizationLogic'
interface TableProps {
@@ -97,6 +98,74 @@ export const Table = (props: TableProps): JSX.Element => {
const columnTitle = settings?.display?.label || title || column.name
const formattedTitle = typeof columnTitle === 'string' ? formatColumnTitle(columnTitle) : columnTitle
+ const computeConditionalFormattingBackground = (data: TableDataCell<any>[]): string | undefined => {
+ const cell = data[index]
+
+ if (cell.isTransposedHeader) {
+ return undefined
+ }
+
+ const sourceColumnName = cell.sourceColumnName ?? column.name
+ const sourceColumnType = sourceTabularColumnsByName.get(sourceColumnName)?.column.type.name ?? cell.type
+ const conditionalFormattingMatches = conditionalFormattingRules
+ .filter((n) => n.columnName === sourceColumnName)
+ .filter((n) => {
+ const isValidHog = !!n.bytecode && n.bytecode.length > 0 && n.bytecode[0] === '_H'
+ if (!isValidHog) {
+ posthog.captureException(new Error('Invalid hog bytecode for conditional formatting'), {
+ formatRule: n,
+ })
+ }
+
+ return isValidHog
+ })
+ .map((n) => ({
+ rule: n,
+ result: execHog(n.bytecode, {
+ globals: {
+ value: cell.value,
+ input: convertTableValue(n.input, sourceColumnType),
+ },
+ functions: {},
+ maxAsyncSteps: 0,
+ }).result,
+ }))
+ .find((n) => Boolean(n.result))
+
+ if (!conditionalFormattingMatches) {
+ return undefined
+ }
+
+ const ruleColor = conditionalFormattingMatches.rule.color
+ const colorMode = conditionalFormattingMatches.rule.colorMode ?? 'light'
+
+ // If the color mode matches the current theme, use the color as it was saved
+ if ((colorMode === 'dark' && isDarkModeOn) || (colorMode === 'light' && !isDarkModeOn)) {
+ return ruleColor
+ }
+
+ // If the color mode is dark, but we're in light mode - then lighten the color
+ if (colorMode === 'dark' && !isDarkModeOn) {
+ return lightenDarkenColor(ruleColor, 30)
+ }
+
+ // If the color mode is light, but we're in dark mode - then darken the color
+ return lightenDarkenColor(ruleColor, -30)
+ }
+
+ // The `style` and `className` cell callbacks are invoked independently for the same cell,
+ // so memoize per row record to run the HogVM rules (and any captureException) only once.
+ // The cache lives in this per-render closure, so it can't go stale across theme/rule changes.
+ const backgroundByRecord = new WeakMap<TableDataCell<any>[], string | undefined>()
+ const resolveConditionalFormattingBackground = (data: TableDataCell<any>[]): string | undefined => {
+ if (backgroundByRecord.has(data)) {
+ return backgroundByRecord.get(data)
+ }
+ const backgroundColor = computeConditionalFormattingBackground(data)
+ backgroundByRecord.set(data, backgroundColor)
+ return backgroundColor
+ }
+
return {
...columnMeta,
key: column.name,
@@ -170,70 +239,14 @@ export const Table = (props: TableProps): JSX.Element => {
)
},
style: (_, data) => {
- const cell = data[index]
-
- if (cell.isTransposedHeader) {
- return undefined
- }
-
- const sourceColumnName = cell.sourceColumnName ?? column.name
- const sourceColumnType =
- sourceTabularColumnsByName.get(sourceColumnName)?.column.type.name ?? cell.type
- const cf = conditionalFormattingRules
- .filter((n) => n.columnName === sourceColumnName)
- .filter((n) => {
- const isValidHog = !!n.bytecode && n.bytecode.length > 0 && n.bytecode[0] === '_H'
- if (!isValidHog) {
- posthog.captureException(new Error('Invalid hog bytecode for conditional formatting'), {
- formatRule: n,
- })
- }
-
- return isValidHog
- })
- .map((n) => {
- const res = execHog(n.bytecode, {
- globals: {
- value: cell.value,
- input: convertTableValue(n.input, sourceColumnType),
- },
- functions: {},
- maxAsyncSteps: 0,
- })
-
- return {
- rule: n,
- result: res.result,
- }
- })
-
- const conditionalFormattingMatches = cf.find((n) => Boolean(n.result))
-
- if (conditionalFormattingMatches) {
- const ruleColor = conditionalFormattingMatches.rule.color
- const colorMode = conditionalFormattingMatches.rule.colorMode ?? 'light'
-
- // If the color mode matches the current theme, return as it was saved
- if ((colorMode === 'dark' && isDarkModeOn) || (colorMode === 'light' && !isDarkModeOn)) {
- return {
- backgroundColor: ruleColor,
- }
- }
-
- // If the color mode is dark, but we're in light mode - then lighten the color
- if (colorMode === 'dark' && !isDarkModeOn) {
- return {
- backgroundColor: lightenDarkenColor(ruleColor, 30),
- }
- }
-
- // If the color mode is light, but we're in dark mode - then darken the color
- return {
- backgroundColor: lightenDarkenColor(ruleColor, -30),
- }
- }
-
- return undefined
+ const backgroundColor = resolveConditionalFormattingBackground(data)
+ return backgroundColor ? { backgroundColor } : undefined
+ },
+ className: (_, data) => {
+ const backgroundColor = resolveConditionalFormattingBackground(data)
+ // Pin the text color to the cell background rather than inheriting the theme's text
+ // color, which is near-white in dark mode and unreadable on light backgrounds
+ return backgroundColor ? getContrastingTextClass(backgroundColor) : ''
},
}
}
diff --git a/frontend/src/queries/nodes/DataVisualization/colorUtils.ts b/frontend/src/queries/nodes/DataVisualization/colorUtils.ts
new file mode 100644
index 000000000000..76461b108323
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/colorUtils.ts
@@ -0,0 +1,24 @@
+import { hexToRGB } from 'lib/utils/colors'
+
+/**
+ * Returns a text color utility class (`text-white` / `text-black`) that stays readable on top of a
+ * colored data-viz cell background (conditional formatting, heatmap). The class is chosen from the
+ * background's relative luminance so it contrasts in both light and dark themes. Accepts either a
+ * hex string ('#RRGGBB') or an 'rgb(r,g,b)' string.
+ */
+export function getContrastingTextClass(background: string): 'text-white' | 'text-black' {
+ let r: number
+ let g: number
+ let b: number
+
+ const rgbMatch = background.match(/rgba?\(([^)]+)\)/)
+ if (rgbMatch) {
+ ;[r, g, b] = rgbMatch[1].split(',').map((v) => parseInt(v.trim(), 10))
+ } else {
+ ;({ r, g, b } = hexToRGB(background))
+ }
+
+ // Perceived luminance (0-255). Below the midpoint, use light text; otherwise dark text.
+ const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
+ return luminance < 140 ? 'text-white' : 'text-black'
+}
diff --git a/frontend/src/scenes/insights/stories/SQLTableConditionalFormatting.stories.tsx b/frontend/src/scenes/insights/stories/SQLTableConditionalFormatting.stories.tsx
new file mode 100644
index 000000000000..b7c6580a8dd1
--- /dev/null
+++ b/frontend/src/scenes/insights/stories/SQLTableConditionalFormatting.stories.tsx
@@ -0,0 +1,141 @@
+import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+
+import { Meta, StoryObj } from '@storybook/react'
+import { useActions, useValues } from 'kea'
+import { useEffect } from 'react'
+
+import { userLogic } from 'scenes/userLogic'
+
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
+import { useStorybookMocks } from '~/mocks/browser'
+import { DEFAULT_PICKER_COLORS } from '~/queries/nodes/DataVisualization/Components/ConditionalFormatting/ConditionalFormattingTab'
+import { DataTableVisualization } from '~/queries/nodes/DataVisualization/DataVisualization'
+import {
+ ConditionalFormattingRule,
+ DataVisualizationNode,
+ HogQLQueryResponse,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+// Compiled Hog for the "equals" template (`return value == input`): reads the `value` and `input`
+// globals, compares them (EQ = 11) and returns (RETURN = 38).
+const EQUALS_BYTECODE: (string | number)[] = ['_H', 1, 32, 'input', 1, 1, 32, 'value', 1, 1, 11, 38]
+
+function equalsRule(columnName: string, hex: string, colorMode: 'light' | 'dark'): ConditionalFormattingRule {
+ return {
+ id: `${colorMode}-${hex}`,
+ templateId: 'equals',
+ columnName,
+ input: hex,
+ color: hex,
+ colorMode,
+ bytecode: EQUALS_BYTECODE,
+ }
+}
+
+// One rule per default palette color, for both the "light rule" and "dark rule" columns, so every
+// color is exercised both as a rule saved in light mode and as one saved in dark mode.
+const conditionalFormatting: ConditionalFormattingRule[] = DEFAULT_PICKER_COLORS.flatMap((hex) => [
+ equalsRule('light', hex, 'light'),
+ equalsRule('dark', hex, 'dark'),
+])
+
+const query: DataVisualizationNode = {
+ kind: NodeKind.DataVisualizationNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT color, hex AS light, hex AS dark FROM palette',
+ },
+ display: ChartDisplayType.ActionsTable,
+ tableSettings: {
+ columns: [
+ { column: 'color' },
+ { column: 'light', settings: { display: { label: 'Rule saved in light mode' } } },
+ { column: 'dark', settings: { display: { label: 'Rule saved in dark mode' } } },
+ ],
+ conditionalFormatting,
+ },
+}
+
+// Each row shows a color's hex in both rule columns, so the cell text sits on its own color and its
+// legibility is obvious.
+const cachedResults: HogQLQueryResponse<string[][]> = {
+ results: DEFAULT_PICKER_COLORS.map((hex) => [hex, hex, hex]),
+ columns: ['color', 'light', 'dark'],
+ types: [
+ ['color', 'String'],
+ ['light', 'String'],
+ ['dark', 'String'],
+ ],
+}
+
+// The table computes cell colors in JS from `themeLogic.isDarkModeOn`, which the snapshot runner's
+// body-attribute theme flip does NOT reach (it only switches CSS variables). So each story pins one
+// theme end to end: the user is mocked with the matching `theme_mode` (kea side) and the story
+// globals pin the body attribute (CSS side). Rendering is held until `isDarkModeOn` reflects the
+// mocked user, so the snapshot's waitForSelector can't fire while the other theme's colors are up.
+function ConditionalFormattingTable({ mode }: { mode: 'light' | 'dark' }): JSX.Element | null {
+ useStorybookMocks({
+ get: {
+ '/api/users/@me/': () => [200, { ...MOCK_DEFAULT_USER, theme_mode: mode }],
+ },
+ })
+ const { user } = useValues(userLogic)
+ const { loadUser } = useActions(userLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+
+ // The KeaStory decorator mounts userLogic (kicking off the initial user load) before this
+ // render registers the mock override above, so if the default user won that race, fetch once
+ // more with the override in place.
+ useEffect(() => {
+ if (user && user.theme_mode !== mode) {
+ loadUser()
+ }
+ }, [user, mode, loadUser])
+
+ if (user?.theme_mode !== mode || isDarkModeOn !== (mode === 'dark')) {
+ return null
+ }
+
+ return (
+ <div className="p-4">
+ <DataTableVisualization
+ uniqueKey="conditional-formatting"
+ query={query}
+ setQuery={() => {}}
+ cachedResults={cachedResults}
+ readOnly
+ embedded
+ />
+ </div>
+ )
+}
+
+type Story = StoryObj<typeof DataTableVisualization>
+const meta: Meta<typeof DataTableVisualization> = {
+ title: 'Scenes-App/Insights/SQLTableConditionalFormatting',
+ component: DataTableVisualization,
+ parameters: {
+ testOptions: {
+ snapshotBrowsers: ['chromium'],
+ waitForSelector: '.DataVisualizationTable',
+ },
+ },
+}
+
+export default meta
+
+// Light theme: light-saved rules render their raw color, dark-saved rules are lightened by 30.
+export const ConditionalFormattingLight: Story = {
+ globals: { theme: 'light' },
+ parameters: { testOptions: { skipDarkMode: true } },
+ render: () => <ConditionalFormattingTable mode="light" />,
+}
+
+// Dark theme: dark-saved rules render their raw color, light-saved rules are darkened by 30.
+export const ConditionalFormattingDark: Story = {
+ globals: { theme: 'dark' },
+ parameters: { testOptions: { skipLightMode: true } },
+ render: () => <ConditionalFormattingTable mode="dark" />,
+}