: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
chore(toolbar): move themeLogic and dataThemeLogic to lib/logic (#69134)
Rafael Audiberted1dfd4e8d52
diff --git a/.agents/toolbar-migration.md b/.agents/toolbar-migration.mdindex 0453a0808e17..16b699c5e8f3 100644--- a/.agents/toolbar-migration.md+++ b/.agents/toolbar-migration.md@@ -4,7 +4,7 @@ This file is the committed source of truth for the toolbar bundle modernization## Status-- **Current step**: Steps 1–4 and 7 implemented and in review as a Graphite stack (drafts), plus a seventh PR batching the simple Step 5/6 moves (PanelSettings, UrlMatchingHints, KeyboardShortcut, LemonMarkdown mermaid barrel — baseline 31 → 25) and an eighth cutting the preflight + web-analytics-achievements edges (baseline 25 → 18). Next: merge the base of the stack before extending further, then the remaining Step 6 seams (Link→DraggableToNotebook, LemonColor→theme logics, taxonomy/PropertyKeyInfo→surveyQuestionLabelsLogic) and Step 8.+- **Current step**: Steps 1–4 and 7 implemented and in review as a Graphite stack (drafts), plus a seventh PR batching the simple Step 5/6 moves (PanelSettings, UrlMatchingHints, KeyboardShortcut, LemonMarkdown mermaid barrel — baseline 31 → 25) an eighth cutting the preflight + web-analytics-achievements edges (baseline 25 → 18), and a ninth moving themeLogic/dataThemeLogic to `lib/logic/` (baseline 18 → 12). A lint-guard PR (#69133) now sits at the bottom of the stack (oxlint exhaustive-deps suppressions where `--fix-dangerously` corrupted files). Next: Link→DraggableToNotebook DI seam, then the Step 7 eager-logic audit, then Step 8 (riskiest, last). The remaining survey-labels/taxonomy/experiments/product-tours edges are candidates for documented intentional seams rather than cuts.- **Last updated**: 2026-07-07- **PRs**: Step 1 — `rafa/toolbar-migration-1-graph-guard` (#69045); Step 3 — `rafa/toolbar-migration-2-products-urls-split` (#69071); chain cuts + shim-leak fix — `rafa/toolbar-migration-3-shim-leak-and-chain-cuts` (#69088); Step 2 — `rafa/toolbar-migration-4-loader-esm-splitting` (#69093); Step 4 — `rafa/toolbar-migration-5-types-replay-shared-cut` (#69106); Step 7 — `rafa/toolbar-migration-6-lazy-menus` (#69113); Step 5/6 batch — `rafa/toolbar-migration-7-simple-edge-cuts` (#69122) (each stacked on the previous)- **Reorder note (resolved)**: a trial Step 2 build emitted **487 dead chunks** — with `products.tsx` reachable, every product scene's dynamic import becomes a real chunk in `dist/toolbar/`. The gate was: flip the format only once `products.tsx` leaves the graph. That's now done via two moves in the third PR. First, the remaining chains all funneled through one root cause: the kea shims only matched exact alias strings (`scenes/teamLogic`), so relative imports (`dataThemeLogic` → `./teamLogic`) and `~/`-prefixed imports pulled the REAL logics and their whole app graph — fixed with relative + `~/` matching in `createToolbarModulePlugin`, disconnecting `products.tsx`, `scenes.ts`, `teamLogic`, `PersonDisplay`, and `experimentsLogic` in one move. Second, `scenes/urls` itself (imported by lib components shared with the app) is shimmed to the toolbar's parity-tested `~/toolbar/urls` duplicate from Step 3, taking the last products-manifest path out. Bundle graph 8448 → ~1000 files (99 → ~13.5 MiB source), shipped `dist/toolbar.js` 9.95 MB → ~4 MB (was just under the 10 MB CloudFront cliff). Graph budget ratcheted 110 MB → 18 MB.@@ -106,7 +106,7 @@ Approach (revised on review): rather than restructuring the generated products m### Step 6 — shared lib → scenes back-edges (each also helps the main app)- [ ] `lib/lemon-ui/Link/Link.tsx` → `DraggableToNotebook` (drags notebooks → tiptap): invert with a registry/context seam (the flagship shim→DI replacement)-- [ ] `lib/lemon-ui/LemonColor/*` → `scenes/dataThemeLogic` (its `./teamLogic` import is now shimmed, so this edge is boundary-only, not a leak): theme via props/context+- [x] `lib/lemon-ui/LemonColor/*` → `dataThemeLogic` and HedgehogMode/JSONViewer/LemonColorGlyph → `themeLogic`: both logics (plus `themes.ts`) moved to `lib/logic/` — they're global UI state whose app-zone deps (sceneLogic, userLogic, teamLogic) already resolve to toolbar shims, so the move is placement-only. Old paths re-export for the ~60 app importers; all `src/lib` importers repointed. Cuts 6 baseline edges (props/context seam not needed)- [x] `lib/lemon-ui/LemonMarkdown/index.ts`: the barrel no longer re-exports `LemonMarkdownWithMermaid` (the one product user imports the module directly); the `mermaid` deny in `toolbar-config.mjs` is retired, reintroduction caught by FORBIDDEN_PACKAGES- [x] `HeatmapEventsPanel` → `PersonDisplay`: replaced with a plain span (PersonDisplay renders exactly that for a distinct_id-only person with `noPopover`); `TZLabel` → teamLogic edge now shimmed at resolve time (`~/scenes/teamLogic` matching)- [x] `KeyboardShortcut` moved out of `layout/navigation-3000/components/` into `lib/components/KeyboardShortcut/` (25 importers repointed; cuts the 4 lemon-ui → layout edges)diff --git a/frontend/bin/toolbar-graph-baseline.json b/frontend/bin/toolbar-graph-baseline.jsonindex 81c2c8103f24..33a4591811ec 100644--- a/frontend/bin/toolbar-graph-baseline.json+++ b/frontend/bin/toolbar-graph-baseline.json@@ -1,13 +1,7 @@{"//": "Toolbar -> app-zone import edges that exist today, enforced by bin/check-toolbar-graph.mjs. Do not add entries; delete them as the migration (.agents/toolbar-migration.md) cuts each edge.","edges": [- "src/lib/components/HedgehogMode/HedgehogMode.tsx -> src/layout/navigation-3000/themeLogic.ts",- "src/lib/components/JSONViewer.tsx -> src/layout/navigation-3000/themeLogic.ts","src/lib/components/PropertyKeyInfo.tsx -> src/scenes/surveys/surveyQuestionLabelsLogic.ts",- "src/lib/lemon-ui/LemonColor/LemonColorButton.tsx -> src/scenes/dataThemeLogic.tsx",- "src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx -> src/layout/navigation-3000/themeLogic.ts",- "src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx -> src/scenes/dataThemeLogic.tsx",- "src/lib/lemon-ui/LemonColor/LemonColorPicker.tsx -> src/scenes/dataThemeLogic.tsx","src/lib/lemon-ui/Link/Link.tsx -> src/scenes/notebooks/AddToNotebook/DraggableToNotebook.tsx","src/lib/utils/eventUsageLogic.ts -> src/scenes/product-tours/constants.ts","src/taxonomy/helpers.ts -> src/scenes/surveys/surveyQuestionLabelsLogic.ts",diff --git a/frontend/src/layout/navigation-3000/themeLogic.ts b/frontend/src/layout/navigation-3000/themeLogic.tsindex 52d697061c08..da2dfa45104d 100644--- a/frontend/src/layout/navigation-3000/themeLogic.ts+++ b/frontend/src/layout/navigation-3000/themeLogic.ts@@ -1,119 +1 @@-import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'--import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { sceneLogic } from 'scenes/sceneLogic'-import { userLogic } from 'scenes/userLogic'--import type { themeLogicType } from './themeLogicType'-import { Theme, themes } from './themes'--export const themeLogic = kea<themeLogicType>([- path(['layout', 'navigation-3000', 'themeLogic']),- connect(() => ({- logic: [sceneLogic],- values: [userLogic, ['themeMode'], featureFlagLogic, ['featureFlags']],- actions: [userLogic, ['updateUser']],- })),-- actions({- syncDarkModePreference: (darkModePreference: boolean) => ({ darkModePreference }),- setTheme: (theme: string | null) => ({ theme }),- saveCustomCss: true,- setPersistedCustomCss: (css: string | null) => ({ css }),- setPreviewingCustomCss: (css: string | null) => ({ css }),- toggleTheme: true,- }),- reducers({- darkModeSystemPreference: [- window.matchMedia('(prefers-color-scheme: dark)').matches,- {- syncDarkModePreference: (_, { darkModePreference }) => darkModePreference,- },- ],- selectedTheme: [- null as string | null,- { persist: true },- {- setTheme: (_, { theme }) => theme,- },- ],- persistedCustomCss: [- null as string | null,- { persist: true },- {- setPersistedCustomCss: (_, { css }) => css,- },- ],- previewingCustomCss: [- null as string | null,- { persist: true },- {- setPreviewingCustomCss: (_, { css }) => css,- },- ],- }),- selectors({- theme: [- (s) => [s.selectedTheme, s.featureFlags],- (selectedTheme, featureFlags): Theme | null => {- const flagVariant = featureFlags[FEATURE_FLAGS.THEME_OVERRIDE]- return (- (selectedTheme ? themes.find((theme) => theme.id === selectedTheme) : null) ??- (typeof flagVariant === 'string' ? themes.find((theme) => theme.id === flagVariant) : null) ??- null- )- },- ],- customCssEnabled: [- (s) => [s.featureFlags],- (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.CUSTOM_CSS_THEMES],- ],- customCss: [- (s) => [s.persistedCustomCss, s.previewingCustomCss],- (persistedCustomCss, previewingCustomCss): string | null => previewingCustomCss || persistedCustomCss,- ],- isDarkModeOn: [- (s) => [s.themeMode, s.darkModeSystemPreference, sceneLogic.selectors.sceneConfig, s.theme],- (themeMode, darkModeSystemPreference, sceneConfig, theme) => {- if (- typeof window !== 'undefined' &&- window.document &&- document.body.classList.contains('storybook-test-runner') &&- document.body.getAttribute('theme') == 'dark'- ) {- return true- }- if (theme) {- return !!theme?.dark- }- // NOTE: Unauthenticated users always get the light mode until we have full support for dark mode there- if (sceneConfig?.allowUnauthenticated || sceneConfig?.onlyUnauthenticated) {- return false- }-- return themeMode === 'system' ? darkModeSystemPreference : themeMode === 'dark'- },- ],- }),- listeners(({ values, actions }) => ({- saveCustomCss() {- actions.setPersistedCustomCss(values.previewingCustomCss)- actions.setPreviewingCustomCss(null)- },- toggleTheme() {- actions.updateUser({ theme_mode: values.isDarkModeOn ? 'light' : 'dark' })- },- })),- events(({ cache, actions }) => ({- afterMount() {- cache.disposables.add(() => {- const prefersColorSchemeMedia = window.matchMedia('(prefers-color-scheme: dark)')- const onPrefersColorSchemeChange = (e: MediaQueryListEvent): void =>- actions.syncDarkModePreference(e.matches)- prefersColorSchemeMedia.addEventListener('change', onPrefersColorSchemeChange)- return () => prefersColorSchemeMedia.removeEventListener('change', onPrefersColorSchemeChange)- }, 'prefersColorSchemeListener')- },- })),-])+export * from 'lib/logic/themeLogic'diff --git a/frontend/src/lib/charts/hooks.ts b/frontend/src/lib/charts/hooks.tsindex 4bf83694f597..e05094f95fcb 100644--- a/frontend/src/lib/charts/hooks.ts+++ b/frontend/src/lib/charts/hooks.ts@@ -5,8 +5,7 @@ import type { ChartTheme, DateRangeZoomData } from '@posthog/quill-charts'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { themeLogic } from 'lib/logic/themeLogic'import { buildTheme } from './utils/theme'diff --git a/frontend/src/lib/components/Account/AccountMenu.tsx b/frontend/src/lib/components/Account/AccountMenu.tsxindex 7eab5eb48f19..fe1eba68a5e0 100644--- a/frontend/src/lib/components/Account/AccountMenu.tsx+++ b/frontend/src/lib/components/Account/AccountMenu.tsx@@ -31,6 +31,7 @@ import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture/ProfilePicture'import { UploadedLogo } from 'lib/lemon-ui/UploadedLogo/UploadedLogo'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { preflightLogic } from 'lib/logic/preflightLogic'+import { themeLogic } from 'lib/logic/themeLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import {DropdownMenu,@@ -54,7 +55,6 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { navigation3000Logic } from '~/layout/navigation-3000/navigationLogic'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { AccessLevelIndicator } from '~/layout/navigation/AccessLevelIndicator'import { getTreeItemsGames } from '~/products'import { UserTheme } from '~/types'diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsxindex dad35144492a..3b5a9bd9e78c 100644--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx@@ -13,6 +13,7 @@ import { FEATURE_FLAGS } from 'lib/constants'import { usePageVisibility } from 'lib/hooks/usePageVisibility'import { SpinnerOverlay } from 'lib/lemon-ui/Spinner/Spinner'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { themeLogic } from 'lib/logic/themeLogic'import { accessLevelSatisfied, getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { BreakdownColorConfig } from 'scenes/dashboard/DashboardInsightColorsModal'@@ -26,7 +27,6 @@ import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { insightLogic } from 'scenes/insights/insightLogic'import { ErrorBoundary } from '~/layout/ErrorBoundary'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { extractValidationError, extractValidationErrorCode } from '~/queries/nodes/InsightViz/utils'import { Query } from '~/queries/Query/Query'import { DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'diff --git a/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsx b/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsxindex 805136c1df0e..c53ffa264d0c 100644--- a/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsx@@ -4,10 +4,10 @@ import React, { useState } from 'react'import { CardMeta } from 'lib/components/Cards/CardMeta'import { LemonMenuItemList } from 'lib/lemon-ui/LemonMenu/LemonMenu'+import { themeLogic } from 'lib/logic/themeLogic'import { urls } from 'scenes/urls'import { ErrorBoundary } from '~/layout/ErrorBoundary'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { Query } from '~/queries/Query/Query'import { Node } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'diff --git a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsxindex 255027cbdc6a..053daa95c501 100644--- a/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx+++ b/frontend/src/lib/components/CodeSnippet/CodeSnippet.tsx@@ -13,10 +13,9 @@ import React, { useMemo, 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 { themeLogic } from '~/layout/navigation-3000/themeLogic'-import terraform from './terraformLanguage'// `common` already registers 16 of our 20 languages — only add the missing ones.diff --git a/frontend/src/lib/components/CompactList/CompactList.tsx b/frontend/src/lib/components/CompactList/CompactList.tsxindex 90cf7816619f..a2e0132cfcdd 100644--- a/frontend/src/lib/components/CompactList/CompactList.tsx+++ b/frontend/src/lib/components/CompactList/CompactList.tsx@@ -6,8 +6,7 @@ import { useValues } from 'kea'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { themeLogic } from 'lib/logic/themeLogic'import { EmptyMessage, EmptyMessageProps } from '../EmptyMessage/EmptyMessage'diff --git a/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx b/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsxindex eeac055e78ed..cfb8abc3fc9b 100644--- a/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx+++ b/frontend/src/lib/components/HedgehogMode/HedgehogMode.tsx@@ -1,10 +1,10 @@import { useActions, useValues } from 'kea'import { Suspense } from 'react'+import { themeLogic } from 'lib/logic/themeLogic'import { inStorybook } from 'lib/utils/dom'import { lazyWithRetry } from 'lib/utils/retryImport'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { useShortcut } from '../Shortcuts/useShortcut'diff --git a/frontend/src/lib/components/JSONViewer.tsx b/frontend/src/lib/components/JSONViewer.tsxindex fcbb20c08999..2e9ebd49c6aa 100644--- a/frontend/src/lib/components/JSONViewer.tsx+++ b/frontend/src/lib/components/JSONViewer.tsx@@ -4,11 +4,10 @@ import type { ReactJsonViewProps } from '@microlink/react-json-view'import { useValues } from 'kea'import { Suspense } from 'react'+import { themeLogic } from 'lib/logic/themeLogic'import { WrappingLoadingSkeleton } from 'lib/ui/WrappingLoadingSkeleton/WrappingLoadingSkeleton'import { lazyWithRetry } from 'lib/utils/retryImport'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'-const ReactJson = lazyWithRetry(() => import('@microlink/react-json-view'))export enum JSONViewerTheme {diff --git a/frontend/src/lib/components/Map/Map.tsx b/frontend/src/lib/components/Map/Map.tsxindex 785449ce27a2..f147d111a9bb 100644--- a/frontend/src/lib/components/Map/Map.tsx+++ b/frontend/src/lib/components/Map/Map.tsx@@ -9,8 +9,7 @@ import { useEffect, useRef } from 'react'import useResizeObserver from 'use-resize-observer'import { preflightLogic } from 'lib/logic/preflightLogic'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { themeLogic } from 'lib/logic/themeLogic'const protocol = new Protocol()maplibregl.addProtocol('pmtiles', protocol.tile)diff --git a/frontend/src/lib/components/Menus/ThemeMenu.tsx b/frontend/src/lib/components/Menus/ThemeMenu.tsxindex 44f77b4002a7..840c80c1b84e 100644--- a/frontend/src/lib/components/Menus/ThemeMenu.tsx+++ b/frontend/src/lib/components/Menus/ThemeMenu.tsx@@ -5,12 +5,12 @@ import { IconDay, IconLaptop, IconNight, IconPalette } from '@posthog/icons'import { LemonTag } from 'lib/lemon-ui/LemonTag/LemonTag'import { Link } from 'lib/lemon-ui/Link/Link'+import { themeLogic } from 'lib/logic/themeLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { MenuOpenIndicator } from 'lib/ui/Menus/Menus'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { UserTheme } from '~/types'export function ThemeMenu(): JSX.Element {diff --git a/frontend/src/lib/components/Search/Search.tsx b/frontend/src/lib/components/Search/Search.tsxindex a7c722cdbbdf..7608456d6269 100644--- a/frontend/src/lib/components/Search/Search.tsx+++ b/frontend/src/lib/components/Search/Search.tsx@@ -23,6 +23,7 @@ import { KeyboardShortcut } from 'lib/components/KeyboardShortcut/KeyboardShortcimport { filterSearchItems } from 'lib/components/Search/utils'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'+import { themeLogic } from 'lib/logic/themeLogic'import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'import { ContextMenu, ContextMenuContent, ContextMenuGroup, ContextMenuTrigger } from 'lib/ui/ContextMenu/ContextMenu'import { Label } from 'lib/ui/Label/Label'@@ -31,7 +32,6 @@ import { cn } from 'lib/utils/css-classes'import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { ProductIconWrapper, iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { MenuItems } from '~/layout/panel-layout/ProjectTree/menus/MenuItems'import { fileSystemTypes } from '~/products'diff --git a/frontend/src/lib/components/SeriesGlyph.tsx b/frontend/src/lib/components/SeriesGlyph.tsxindex bf8a24bfc954..4d7ba75566c7 100644--- a/frontend/src/lib/components/SeriesGlyph.tsx+++ b/frontend/src/lib/components/SeriesGlyph.tsx@@ -1,11 +1,10 @@import { useValues } from 'kea'import { getSeriesColor } from 'lib/colors'+import { themeLogic } from 'lib/logic/themeLogic'import { RGBToRGBA, hexToRGBA, lightenDarkenColor } from 'lib/utils/colors'import { alphabet } from 'lib/utils/strings'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'-interface SeriesGlyphProps {className?: stringchildren?: React.ReactNodediff --git a/frontend/src/lib/components/Sharing/SharingModal.test.tsx b/frontend/src/lib/components/Sharing/SharingModal.test.tsxindex 38b89eba3a44..2b1ed22d0fec 100644--- a/frontend/src/lib/components/Sharing/SharingModal.test.tsx+++ b/frontend/src/lib/components/Sharing/SharingModal.test.tsx@@ -3,9 +3,9 @@ import '@testing-library/jest-dom'import { cleanup, render, screen, within } from '@testing-library/react'import { expectLogic } from 'kea-test-utils'+import { themeLogic } from 'lib/logic/themeLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { useAvailableFeatures } from '~/mocks/features'import { useMocks } from '~/mocks/jest'import { NodeKind } from '~/queries/schema/schema-general'diff --git a/frontend/src/lib/hooks/useThemedHtml.ts b/frontend/src/lib/hooks/useThemedHtml.tsindex c647dfd6508f..f4d58fdea031 100644--- a/frontend/src/lib/hooks/useThemedHtml.ts+++ b/frontend/src/lib/hooks/useThemedHtml.ts@@ -2,10 +2,9 @@ import { useValues } from 'kea'import posthog from 'posthog-js'import { useEffect } from 'react'+import { themeLogic } from 'lib/logic/themeLogic'import { sceneLogic } from 'scenes/sceneLogic'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'-export function useThemedHtml(overflowHidden = true, forcedTheme: 'light' | 'dark' | null = null): void {const { isDarkModeOn, customCss } = useValues(themeLogic)const { sceneConfig } = useValues(sceneLogic)diff --git a/frontend/src/lib/lemon-ui/LemonColor/LemonColorButton.tsx b/frontend/src/lib/lemon-ui/LemonColor/LemonColorButton.tsxindex 534d2a169522..a41382b7343d 100644--- a/frontend/src/lib/lemon-ui/LemonColor/LemonColorButton.tsx+++ b/frontend/src/lib/lemon-ui/LemonColor/LemonColorButton.tsx@@ -3,8 +3,8 @@ import './LemonColorButton.scss'import { useValues } from 'kea'import { DataColorToken } from 'lib/colors'+import { dataThemeLogic } from 'lib/logic/dataThemeLogic'import { cn } from 'lib/utils/css-classes'-import { dataThemeLogic } from 'scenes/dataThemeLogic'import { LemonButton, LemonButtonWithoutSideActionProps } from '../LemonButton'import { LemonColorGlyph } from './LemonColorGlyph'diff --git a/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx b/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsxindex 2319abd1459b..a1e63b84f514 100644--- a/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx+++ b/frontend/src/lib/lemon-ui/LemonColor/LemonColorGlyph.tsx@@ -3,11 +3,10 @@ import './LemonColorGlyph.scss'import { useValues } from 'kea'import { DataColorToken } from 'lib/colors'+import { dataThemeLogic } from 'lib/logic/dataThemeLogic'+import { themeLogic } from 'lib/logic/themeLogic'import { RGBToRGBA, hexToRGBA, lightenDarkenColor } from 'lib/utils/colors'import { cn } from 'lib/utils/css-classes'-import { dataThemeLogic } from 'scenes/dataThemeLogic'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { LemonButtonWithoutSideActionProps } from '../LemonButton'diff --git a/frontend/src/lib/lemon-ui/LemonColor/LemonColorPicker.tsx b/frontend/src/lib/lemon-ui/LemonColor/LemonColorPicker.tsxindex 2825b2fbe965..aae7d7fd9d47 100644--- a/frontend/src/lib/lemon-ui/LemonColor/LemonColorPicker.tsx+++ b/frontend/src/lib/lemon-ui/LemonColor/LemonColorPicker.tsx@@ -4,7 +4,7 @@ import { cloneElement, useEffect, useState } from 'react'import { LemonColorGlyph, LemonInput, LemonLabel, Popover } from '@posthog/lemon-ui'import { DataColorToken } from 'lib/colors'-import { dataThemeLogic } from 'scenes/dataThemeLogic'+import { dataThemeLogic } from 'lib/logic/dataThemeLogic'import { LemonColorButton } from './LemonColorButton'import { LemonColorList } from './LemonColorList'diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsxindex c73522dbaa17..de31d26fe484 100644--- a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsx@@ -6,7 +6,7 @@ jest.mock('kea', () => ({useValues: () => ({ isDarkModeOn: false }),}))-jest.mock('~/layout/navigation-3000/themeLogic', () => ({+jest.mock('lib/logic/themeLogic', () => ({themeLogic: { values: {} },}))diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsxindex dedaa27868f5..631b6ce21a77 100644--- a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsx+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsx@@ -3,8 +3,7 @@ import { useEffect, useId, useState } from 'react'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { Spinner } from 'lib/lemon-ui/Spinner'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { themeLogic } from 'lib/logic/themeLogic'type MermaidApi = {initialize: (config: Record<string, unknown>) => voiddiff --git a/frontend/src/lib/logic/dataThemeLogic.tsx b/frontend/src/lib/logic/dataThemeLogic.tsxnew file mode 100644index 000000000000..8518df5805ab--- /dev/null+++ b/frontend/src/lib/logic/dataThemeLogic.tsx@@ -0,0 +1,132 @@+import { actions, afterMount, connect, kea, path, props, reducers, selectors, useValues } from 'kea'+import { loaders } from 'kea-loaders'++import api from 'lib/api'+import { DataColorTheme, DataColorToken } from 'lib/colors'+import { teamLogic } from 'scenes/teamLogic'++import { DataColorThemeModel } from '~/types'++import type { dataThemeLogicType } from './dataThemeLogicType'++export function getColorFromToken(theme: DataColorTheme, colorToken: string): string {+ const colorNo = parseInt(colorToken.replace('preset-', ''))+ const availableColors = Object.keys(theme).length++ // once all colors are exhausted, start again from the beginning+ const wrappedNum = ((colorNo - 1) % availableColors) + 1+ return theme[`preset-${wrappedNum}`]+}++export const ThemeName = ({ id }: { id: number }): JSX.Element => {+ const { themes } = useValues(dataThemeLogic)+ const theme = themes?.find((theme) => theme.id === id)++ return theme ? <span>{theme.name}</span> : <span className="italic">No theme found for id: {id}</span>+}++export type DataThemeLogicProps = {+ themes?: DataColorThemeModel[]+}++export const dataThemeLogic = kea<dataThemeLogicType>([+ props({} as DataThemeLogicProps),+ path(['scenes', 'dataThemeLogic']),+ connect(() => ({ values: [teamLogic, ['currentTeam']] })),+ actions({ setThemes: (themes) => ({ themes }) }),+ loaders(({ props }) => ({+ themes: [+ props.themes || null,+ {+ loadThemes: async () => await api.dataColorThemes.list(),+ },+ ],+ })),+ reducers({+ themes: {+ setThemes: (_, { themes }) => themes,+ },+ }),+ selectors({+ posthogTheme: [+ (s) => [s.themes],+ (themes) => {+ if (!themes) {+ return null+ }++ return themes.sort((theme) => theme.id).find((theme) => theme.is_global)+ },+ ],+ defaultTheme: [+ (s) => [s.currentTeam, s.themes, s.posthogTheme],+ (currentTeam, themes, posthogTheme): DataColorThemeModel | null => {+ if (!themes) {+ return null+ }++ // use the posthog theme unless someone set a specific theme for the team+ const environmentTheme = themes.find(+ (theme) => !currentTeam || theme.id === currentTeam.default_data_theme+ )+ return environmentTheme || posthogTheme || null+ },+ ],+ getTheme: [+ (s) => [s.themes, s.defaultTheme],+ (themes, defaultTheme) =>+ (themeId: string | number | null | undefined): DataColorTheme | null => {+ let customTheme++ if (Number.isInteger(themeId) && themes != null) {+ customTheme = themes.find((theme) => theme.id === themeId)+ }++ if (customTheme) {+ return customTheme.colors.reduce((theme, color, index) => {+ theme[`preset-${index + 1}`] = color+ return theme+ }, {} as DataColorTheme)+ }++ if (defaultTheme) {+ return defaultTheme.colors.reduce((theme, color, index) => {+ theme[`preset-${index + 1}`] = color+ return theme+ }, {} as DataColorTheme)+ }++ return null+ },+ ],+ getColorFromToken: [+ (s) => [s.getTheme],+ (getTheme: (themeId: string | number | null | undefined) => DataColorTheme | null) =>+ (themeId: string | number | null | undefined, colorToken: string): string | null => {+ const theme = getTheme(themeId)+ if (!theme) {+ return null+ }+ return getColorFromToken(theme, colorToken)+ },+ ],+ getAvailableColorTokens: [+ (s) => [s.getTheme],+ (getTheme: (themeId: string | number | null | undefined) => DataColorTheme | null) =>+ (themeId: string | number | null | undefined): DataColorToken[] | null => {+ const theme = getTheme(themeId)+ if (!theme) {+ return null+ }+ return Object.keys(theme || {}) as DataColorToken[]+ },+ ],+ }),+ afterMount(({ actions }) => {+ if (typeof window !== 'undefined' && window.POSTHOG_RENDER_QUERY_PAYLOAD?.themes) {+ actions.setThemes(window.POSTHOG_RENDER_QUERY_PAYLOAD?.themes)+ } else {+ actions.loadThemes()+ }+ }),+])diff --git a/frontend/src/lib/logic/themeLogic.ts b/frontend/src/lib/logic/themeLogic.tsnew file mode 100644index 000000000000..52d697061c08--- /dev/null+++ b/frontend/src/lib/logic/themeLogic.ts@@ -0,0 +1,119 @@+import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { sceneLogic } from 'scenes/sceneLogic'+import { userLogic } from 'scenes/userLogic'++import type { themeLogicType } from './themeLogicType'+import { Theme, themes } from './themes'++export const themeLogic = kea<themeLogicType>([+ path(['layout', 'navigation-3000', 'themeLogic']),+ connect(() => ({+ logic: [sceneLogic],+ values: [userLogic, ['themeMode'], featureFlagLogic, ['featureFlags']],+ actions: [userLogic, ['updateUser']],+ })),++ actions({+ syncDarkModePreference: (darkModePreference: boolean) => ({ darkModePreference }),+ setTheme: (theme: string | null) => ({ theme }),+ saveCustomCss: true,+ setPersistedCustomCss: (css: string | null) => ({ css }),+ setPreviewingCustomCss: (css: string | null) => ({ css }),+ toggleTheme: true,+ }),+ reducers({+ darkModeSystemPreference: [+ window.matchMedia('(prefers-color-scheme: dark)').matches,+ {+ syncDarkModePreference: (_, { darkModePreference }) => darkModePreference,+ },+ ],+ selectedTheme: [+ null as string | null,+ { persist: true },+ {+ setTheme: (_, { theme }) => theme,+ },+ ],+ persistedCustomCss: [+ null as string | null,+ { persist: true },+ {+ setPersistedCustomCss: (_, { css }) => css,+ },+ ],+ previewingCustomCss: [+ null as string | null,+ { persist: true },+ {+ setPreviewingCustomCss: (_, { css }) => css,+ },+ ],+ }),+ selectors({+ theme: [+ (s) => [s.selectedTheme, s.featureFlags],+ (selectedTheme, featureFlags): Theme | null => {+ const flagVariant = featureFlags[FEATURE_FLAGS.THEME_OVERRIDE]+ return (+ (selectedTheme ? themes.find((theme) => theme.id === selectedTheme) : null) ??+ (typeof flagVariant === 'string' ? themes.find((theme) => theme.id === flagVariant) : null) ??+ null+ )+ },+ ],+ customCssEnabled: [+ (s) => [s.featureFlags],+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.CUSTOM_CSS_THEMES],+ ],+ customCss: [+ (s) => [s.persistedCustomCss, s.previewingCustomCss],+ (persistedCustomCss, previewingCustomCss): string | null => previewingCustomCss || persistedCustomCss,+ ],+ isDarkModeOn: [+ (s) => [s.themeMode, s.darkModeSystemPreference, sceneLogic.selectors.sceneConfig, s.theme],+ (themeMode, darkModeSystemPreference, sceneConfig, theme) => {+ if (+ typeof window !== 'undefined' &&+ window.document &&+ document.body.classList.contains('storybook-test-runner') &&+ document.body.getAttribute('theme') == 'dark'+ ) {+ return true+ }+ if (theme) {+ return !!theme?.dark+ }+ // NOTE: Unauthenticated users always get the light mode until we have full support for dark mode there+ if (sceneConfig?.allowUnauthenticated || sceneConfig?.onlyUnauthenticated) {+ return false+ }++ return themeMode === 'system' ? darkModeSystemPreference : themeMode === 'dark'+ },+ ],+ }),+ listeners(({ values, actions }) => ({+ saveCustomCss() {+ actions.setPersistedCustomCss(values.previewingCustomCss)+ actions.setPreviewingCustomCss(null)+ },+ toggleTheme() {+ actions.updateUser({ theme_mode: values.isDarkModeOn ? 'light' : 'dark' })+ },+ })),+ events(({ cache, actions }) => ({+ afterMount() {+ cache.disposables.add(() => {+ const prefersColorSchemeMedia = window.matchMedia('(prefers-color-scheme: dark)')+ const onPrefersColorSchemeChange = (e: MediaQueryListEvent): void =>+ actions.syncDarkModePreference(e.matches)+ prefersColorSchemeMedia.addEventListener('change', onPrefersColorSchemeChange)+ return () => prefersColorSchemeMedia.removeEventListener('change', onPrefersColorSchemeChange)+ }, 'prefersColorSchemeListener')+ },+ })),+])diff --git a/frontend/src/layout/navigation-3000/themes.ts b/frontend/src/lib/logic/themes.tssimilarity index 100%rename from frontend/src/layout/navigation-3000/themes.tsrename to frontend/src/lib/logic/themes.tsdiff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex 7b7343f94b11..31d7ae9b3f94 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -10,6 +10,7 @@ import 'lib/monaco/monacoEnvironment'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { usePageVisibility } from 'lib/hooks/usePageVisibility'import { Spinner } from 'lib/lemon-ui/Spinner'+import { themeLogic } from 'lib/logic/themeLogic'import { codeEditorLogic } from 'lib/monaco/codeEditorLogic'import { codeEditorLogicType } from 'lib/monaco/codeEditorLogicType'import { findNextFocusableElement, findPreviousFocusableElement } from 'lib/monaco/domUtils'@@ -24,7 +25,6 @@ import { clearLogicReference, initModel } from 'lib/monaco/modelLogicReference'import { sharedMonacoOverflowRoot } from 'lib/monaco/sharedMonacoOverflowRoot'import { inStorybookTestRunner } from 'lib/utils/dom'-import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { AnyDataNode, HogLanguage, HogQLMetadataResponse, NodeKind } from '~/queries/schema/schema-general'export interface CodeEditorProps extends Omit<EditorProps, 'loading' | 'theme'> {diff --git a/frontend/src/lib/ui/Colors/Colors.stories.tsx b/frontend/src/lib/ui/Colors/Colors.stories.tsxindex 60db5e3e38e7..be997d569737 100644--- a/frontend/src/lib/ui/Colors/Colors.stories.tsx+++ b/frontend/src/lib/ui/Colors/Colors.stories.tsx@@ -3,8 +3,7 @@ import { useValues } from 'kea'import { useEffect, useState } from 'react'import { LemonSlider } from 'lib/lemon-ui/LemonSlider'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'+import { themeLogic } from 'lib/logic/themeLogic'const meta: Meta = {title: 'UI/Colors',diff --git a/frontend/src/scenes/dataThemeLogic.tsx b/frontend/src/scenes/dataThemeLogic.tsxindex e40337eaf2c3..1169ffdbf468 100644--- a/frontend/src/scenes/dataThemeLogic.tsx+++ b/frontend/src/scenes/dataThemeLogic.tsx@@ -1,132 +1 @@-import { actions, afterMount, connect, kea, path, props, reducers, selectors, useValues } from 'kea'-import { loaders } from 'kea-loaders'--import api from 'lib/api'-import { DataColorTheme, DataColorToken } from 'lib/colors'--import { DataColorThemeModel } from '~/types'--import type { dataThemeLogicType } from './dataThemeLogicType'-import { teamLogic } from './teamLogic'--export function getColorFromToken(theme: DataColorTheme, colorToken: string): string {- const colorNo = parseInt(colorToken.replace('preset-', ''))- const availableColors = Object.keys(theme).length-- // once all colors are exhausted, start again from the beginning- const wrappedNum = ((colorNo - 1) % availableColors) + 1- return theme[`preset-${wrappedNum}`]-}--export const ThemeName = ({ id }: { id: number }): JSX.Element => {- const { themes } = useValues(dataThemeLogic)- const theme = themes?.find((theme) => theme.id === id)-- return theme ? <span>{theme.name}</span> : <span className="italic">No theme found for id: {id}</span>-}--export type DataThemeLogicProps = {- themes?: DataColorThemeModel[]-}--export const dataThemeLogic = kea<dataThemeLogicType>([- props({} as DataThemeLogicProps),- path(['scenes', 'dataThemeLogic']),- connect(() => ({ values: [teamLogic, ['currentTeam']] })),- actions({ setThemes: (themes) => ({ themes }) }),- loaders(({ props }) => ({- themes: [- props.themes || null,- {- loadThemes: async () => await api.dataColorThemes.list(),- },- ],- })),- reducers({- themes: {- setThemes: (_, { themes }) => themes,- },- }),- selectors({- posthogTheme: [- (s) => [s.themes],- (themes) => {- if (!themes) {- return null- }-- return themes.sort((theme) => theme.id).find((theme) => theme.is_global)- },- ],- defaultTheme: [- (s) => [s.currentTeam, s.themes, s.posthogTheme],- (currentTeam, themes, posthogTheme): DataColorThemeModel | null => {- if (!themes) {- return null- }-- // use the posthog theme unless someone set a specific theme for the team- const environmentTheme = themes.find(- (theme) => !currentTeam || theme.id === currentTeam.default_data_theme- )- return environmentTheme || posthogTheme || null- },- ],- getTheme: [- (s) => [s.themes, s.defaultTheme],- (themes, defaultTheme) =>- (themeId: string | number | null | undefined): DataColorTheme | null => {- let customTheme-- if (Number.isInteger(themeId) && themes != null) {- customTheme = themes.find((theme) => theme.id === themeId)- }-- if (customTheme) {- return customTheme.colors.reduce((theme, color, index) => {- theme[`preset-${index + 1}`] = color- return theme- }, {} as DataColorTheme)- }-- if (defaultTheme) {- return defaultTheme.colors.reduce((theme, color, index) => {- theme[`preset-${index + 1}`] = color- return theme- }, {} as DataColorTheme)- }-- return null- },- ],- getColorFromToken: [- (s) => [s.getTheme],- (getTheme: (themeId: string | number | null | undefined) => DataColorTheme | null) =>- (themeId: string | number | null | undefined, colorToken: string): string | null => {- const theme = getTheme(themeId)- if (!theme) {- return null- }- return getColorFromToken(theme, colorToken)- },- ],- getAvailableColorTokens: [- (s) => [s.getTheme],- (getTheme: (themeId: string | number | null | undefined) => DataColorTheme | null) =>- (themeId: string | number | null | undefined): DataColorToken[] | null => {- const theme = getTheme(themeId)- if (!theme) {- return null- }- return Object.keys(theme || {}) as DataColorToken[]- },- ],- }),- afterMount(({ actions }) => {- if (typeof window !== 'undefined' && window.POSTHOG_RENDER_QUERY_PAYLOAD?.themes) {- actions.setThemes(window.POSTHOG_RENDER_QUERY_PAYLOAD?.themes)- } else {- actions.loadThemes()- }- }),-])+export * from 'lib/logic/dataThemeLogic'