A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
test: add read-only CodeMirror theme fixture (#10481)
Kiran Gadhave95a5ec182962
diff --git a/frontend/src/components/editor/code/__tests__/readonly-python-code.test.tsx b/frontend/src/components/editor/code/__tests__/readonly-python-code.test.tsxindex 0f69b2fba4..1169af113c 100644--- a/frontend/src/components/editor/code/__tests__/readonly-python-code.test.tsx+++ b/frontend/src/components/editor/code/__tests__/readonly-python-code.test.tsx@@ -1,13 +1,61 @@/* Copyright 2026 Marimo. All rights reserved. */-import { fireEvent, render, screen } from "@testing-library/react";-import { beforeAll, describe, expect, it } from "vitest";+import { EditorView } from "@codemirror/view";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vitest";import { SetupMocks } from "@/__mocks__/common";import { TooltipProvider } from "@/components/ui/tooltip";import { ReadonlyCode } from "../readonly-python-code";+const themeState = vi.hoisted(() => ({+ value: "light" as "light" | "dark",+}));++let originalRangeGetClientRects: PropertyDescriptor | undefined;++vi.mock("@/theme/useTheme", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/theme/useTheme")>();+ return {+ ...actual,+ useTheme: () => ({ theme: themeState.value }),+ };+});+beforeAll(() => {SetupMocks.resizeObserver();+ originalRangeGetClientRects = Object.getOwnPropertyDescriptor(+ Range.prototype,+ "getClientRects",+ );+ Object.defineProperty(Range.prototype, "getClientRects", {+ configurable: true,+ value: () => [],+ });+});++afterAll(() => {+ // Keep the shared JSDOM prototype unchanged for other test files.+ if (originalRangeGetClientRects) {+ Object.defineProperty(+ Range.prototype,+ "getClientRects",+ originalRangeGetClientRects,+ );+ } else {+ Reflect.deleteProperty(Range.prototype, "getClientRects");+ }+});++beforeEach(() => {+ themeState.value = "light";});/**@@ -26,7 +74,71 @@ function isCollapsed(root: ParentNode) {return root.querySelector(".cm")?.classList.contains("opacity-20") ?? false;}+function getEditorIdentity(view: EditorView) {+ return {+ doc: view.state.doc,+ dom: view.dom,+ contentDOM: view.contentDOM,+ scrollDOM: view.scrollDOM,+ };+}++function expectEditorIdentity(+ view: EditorView,+ identity: ReturnType<typeof getEditorIdentity>,+) {+ expect(view.state.doc).toBe(identity.doc);+ expect(view.dom).toBe(identity.dom);+ expect(view.contentDOM).toBe(identity.contentDOM);+ expect(view.scrollDOM).toBe(identity.scrollDOM);+}+describe("ReadonlyCode", () => {+ it("reconfigures the theme without replacing the editor", async () => {+ let createdView: EditorView | undefined;+ const onCreateEditor = (view: EditorView) => {+ createdView = view;+ };+ const renderCode = (id: string) => (+ <TooltipProvider>+ <ReadonlyCode+ id={id}+ code={"line_1 = 1\nline_2 = 2\nline_3 = 3"}+ showCopyCode={false}+ onCreateEditor={onCreateEditor}+ />+ </TooltipProvider>+ );++ const { rerender } = render(renderCode("light"));+ await waitFor(() => {+ expect(createdView).toBeDefined();+ });++ const view = createdView;+ if (!view) {+ throw new Error("ReadonlyCode did not create an editor view");+ }+ const identity = getEditorIdentity(view);+ expect(view.state.facet(EditorView.darkTheme)).toBe(false);++ themeState.value = "dark";+ rerender(renderCode("dark"));+ await waitFor(() => {+ expect(view.state.facet(EditorView.darkTheme)).toBe(true);+ });+ expect(createdView).toBe(view);+ expectEditorIdentity(view, identity);++ themeState.value = "light";+ rerender(renderCode("light-again"));+ await waitFor(() => {+ expect(view.state.facet(EditorView.darkTheme)).toBe(false);+ });+ expect(createdView).toBe(view);+ expectEditorIdentity(view, identity);+ });+it("starts collapsed when initiallyHideCode is true", () => {const { container } = renderReadonly({ initiallyHideCode: true });expect(isCollapsed(container)).toBe(true);diff --git a/frontend/src/core/codemirror/find-replace/search-highlight.ts b/frontend/src/core/codemirror/find-replace/search-highlight.tsindex 1286a6ae89..c314cac625 100644--- a/frontend/src/core/codemirror/find-replace/search-highlight.ts+++ b/frontend/src/core/codemirror/find-replace/search-highlight.ts@@ -140,11 +140,16 @@ export const searchHighlighter = ViewPlugin.fromClass();export const highlightTheme = EditorView.baseTheme({- "&light .cm-searchMatch": { backgroundColor: "#99ff7780" },- "&dark .cm-searchMatch": { backgroundColor: "#22bb0070" },+ "&light .cm-searchMatch": {+ backgroundColor: "var(--cm-search-match-background-light)",+ },+ "&dark .cm-searchMatch": {+ backgroundColor: "var(--cm-search-match-background-dark)",+ },"&light .cm-searchMatch-selected": { backgroundColor: "transparent" },"&dark .cm-searchMatch.cm-searchMatch-selected": {- backgroundColor: "#6199ff88 !important",+ backgroundColor:+ "var(--cm-search-match-selected-background-dark) !important",},});diff --git a/frontend/src/core/codemirror/theme/__tests__/light.test.ts b/frontend/src/core/codemirror/theme/__tests__/light.test.tsindex b1385b30d6..1e3de71a92 100644--- a/frontend/src/core/codemirror/theme/__tests__/light.test.ts+++ b/frontend/src/core/codemirror/theme/__tests__/light.test.ts@@ -1,136 +1,72 @@/* Copyright 2026 Marimo. All rights reserved. */-import { type Tag, tags as t } from "@lezer/highlight";-import { describe, expect, it } from "vitest";+import type { Extension } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { afterEach, describe, expect, it } from "vitest";+import { darkTheme } from "../dark";import { lightTheme } from "../light";-// Helper function to get theme configuration from the source-const getThemeConfig = () => ({- variant: "light",- settings: {- background: "#ffffff",- foreground: "#000000",- caret: "#000000",- selection: "#d7d4f0",- lineHighlight: "#cceeff44",- gutterBackground: "var(--color-background)",- gutterForeground: "var(--gray-10)",- },- styles: [- { tag: t.comment, color: "#708090" },- { tag: t.variableName, color: "#000000" },- { tag: [t.string, t.special(t.brace)], color: "#a11" },- { tag: t.number, color: "#164" },- { tag: t.bool, color: "#219" },- { tag: t.null, color: "#219" },- { tag: t.keyword, color: "#708", fontWeight: 500 },- { tag: t.className, color: "#00f" },- { tag: t.definition(t.typeName), color: "#00f" },- { tag: t.typeName, color: "#085" },- { tag: t.angleBracket, color: "#000000" },- { tag: t.tagName, color: "#170" },- { tag: t.attributeName, color: "#00c" },- { tag: t.operator, color: "#a2f", fontWeight: 500 },- { tag: [t.function(t.variableName)], color: "#00c" },- { tag: [t.propertyName], color: "#05a" },- ],-});--describe("lightTheme", () => {- it("should export a theme", () => {- expect(lightTheme).toBeDefined();- expect(typeof lightTheme).toBe("object");- });-- describe("theme configuration", () => {- const config = getThemeConfig();-- it("should have correct basic settings", () => {- expect(config.variant).toBe("light");- expect(config.settings).toEqual({- background: "#ffffff",- foreground: "#000000",- caret: "#000000",- selection: "#d7d4f0",- lineHighlight: "#cceeff44",- gutterBackground: "var(--color-background)",- gutterForeground: "var(--gray-10)",- });- });+const mounted: Array<{ host: HTMLDivElement; view: EditorView }> = [];- describe("syntax highlighting", () => {- const findStyle = (tag: Tag | readonly Tag[]) =>- config.styles.find((s) =>- Array.isArray(s.tag) ? s.tag.includes(tag as Tag) : s.tag === tag,- );+function mountTheme(extension: Extension) {+ const host = document.createElement("div");+ document.body.append(host);+ const root = host.attachShadow({ mode: "open" });+ const parent = document.createElement("div");+ root.append(parent);+ const view = new EditorView({ extensions: extension, parent, root });+ mounted.push({ host, view });- it("should style comments", () => {- expect(findStyle(t.comment)).toEqual({- tag: t.comment,- color: "#708090",- });- });+ const style = root.querySelector("style");+ if (!style) {+ throw new Error("CodeMirror did not mount its theme styles");+ }+ return { css: style.textContent ?? "", view };+}- it("should style strings", () => {- const style = findStyle(t.string);- expect(style).toBeDefined();- expect(style?.color).toBe("#a11");- expect(Array.isArray(style?.tag)).toBe(true);- expect(style?.tag).toContain(t.string);- expect(style?.tag).toContain(t.special(t.brace));- });-- it("should style numbers and boolean values", () => {- expect(findStyle(t.number)).toEqual({- tag: t.number,- color: "#164",- });- expect(findStyle(t.bool)).toEqual({- tag: t.bool,- color: "#219",- });- });-- it("should style keywords with emphasis", () => {- expect(findStyle(t.keyword)).toEqual({- tag: t.keyword,- color: "#708",- fontWeight: 500,- });- });+afterEach(() => {+ for (const { host, view } of mounted.splice(0)) {+ view.destroy();+ host.remove();+ }+});- it("should style operators with emphasis", () => {- expect(findStyle(t.operator)).toEqual({- tag: t.operator,- color: "#a2f",- fontWeight: 500,- });- });+const themeCases = [+ {+ name: "light",+ extension: lightTheme,+ dark: false,+ selectionAlias: "var(--cm-selection-background-light)",+ reactiveColor: "var(--cm-reactive-reference-color-light)",+ },+ {+ name: "dark",+ extension: darkTheme,+ dark: true,+ selectionAlias: "var(--cm-selection-background-dark)",+ reactiveColor: "var(--cm-reactive-reference-color-dark)",+ },+] as const;- it("should style class and type names", () => {- expect(findStyle(t.className)).toEqual({- tag: t.className,- color: "#00f",- });- expect(findStyle(t.typeName)).toEqual({- tag: t.typeName,- color: "#085",- });- });+describe.each(themeCases)("$name theme", (theme) => {+ it("uses the production theme tokens", () => {+ const { css, view } = mountTheme(theme.extension);- it("should style function names", () => {- const style = findStyle(t.function(t.variableName));- expect(style).toBeDefined();- expect(style?.color).toBe("#00c");- expect(Array.isArray(style?.tag)).toBe(true);- });+ expect(view.state.facet(EditorView.darkTheme)).toBe(theme.dark);+ expect(css).toContain(+ `--cm-selection-background: ${theme.selectionAlias};`,+ );+ expect(css).toContain("background-color: var(--cm-selection-background);");+ expect(css).toContain(`color: ${theme.reactiveColor};`);+ expect(css).toContain(+ "border-bottom: 2px solid var(--cm-reactive-reference-border-color);",+ );- it("should style property names", () => {- const style = findStyle(t.propertyName);- expect(style).toBeDefined();- expect(style?.color).toBe("#05a");- expect(Array.isArray(style?.tag)).toBe(true);- });- });+ const hoverRule = css+ .split("\n")+ .find((rule) => rule.includes(".mo-cm-reactive-reference-hover"));+ expect(hoverRule).toBeDefined();+ expect(hoverRule).toContain("cursor: pointer;");+ expect(hoverRule).not.toContain("border-bottom");});});diff --git a/frontend/src/core/codemirror/theme/dark.ts b/frontend/src/core/codemirror/theme/dark.tsindex e81dd0dc7a..8806f15ec0 100644--- a/frontend/src/core/codemirror/theme/dark.ts+++ b/frontend/src/core/codemirror/theme/dark.ts@@ -11,7 +11,7 @@ export const darkTheme = [background: "var(--cm-background)",foreground: "#abb2bf",caret: "#528bff",- selection: "#3E4451",+ selection: "var(--cm-selection-background)",lineHighlight: "#2c313c",gutterBackground: "var(--color-background)",gutterForeground: "var(--gray-10)",@@ -36,15 +36,16 @@ export const darkTheme = [],}),EditorView.theme({+ "&": {+ "--cm-selection-background": "var(--cm-selection-background-dark)",+ },".mo-cm-reactive-reference": {fontWeight: "400",- color: "#2a7aa5",- borderBottom: "2px solid #bad3de",+ color: "var(--cm-reactive-reference-color-dark)",+ borderBottom: "2px solid var(--cm-reactive-reference-border-color)",},".mo-cm-reactive-reference-hover": {cursor: "pointer",- borderBottomWidth: "3px",- borderBottomColor: "#4a90a5",},}),];diff --git a/frontend/src/core/codemirror/theme/light.ts b/frontend/src/core/codemirror/theme/light.tsindex d0a977bf68..f9739f7a7f 100644--- a/frontend/src/core/codemirror/theme/light.ts+++ b/frontend/src/core/codemirror/theme/light.ts@@ -11,7 +11,7 @@ export const lightTheme = [background: "#ffffff",foreground: "#000000",caret: "#000000",- selection: "#d7d4f0",+ selection: "var(--cm-selection-background)",lineHighlight: "#cceeff44",gutterBackground: "var(--color-background)",gutterForeground: "var(--gray-10)",@@ -45,14 +45,16 @@ export const lightTheme = [],}),EditorView.theme({+ "&": {+ "--cm-selection-background": "var(--cm-selection-background-light)",+ },".mo-cm-reactive-reference": {fontWeight: "400",- color: "#005f87",- borderBottom: "2px solid #bad3de",+ color: "var(--cm-reactive-reference-color-light)",+ borderBottom: "2px solid var(--cm-reactive-reference-border-color)",},".mo-cm-reactive-reference-hover": {cursor: "pointer",- borderBottomWidth: "3px",},}),];diff --git a/frontend/src/css/app/codemirror.css b/frontend/src/css/app/codemirror.cssindex 3209536e2f..675236b159 100644--- a/frontend/src/css/app/codemirror.css+++ b/frontend/src/css/app/codemirror.css@@ -1,14 +1,18 @@@reference "../globals.css";.light .cm-selectionBackground {- /* This is the background for selected text when focused,- but we want to use it when not in focus either because we- will often lose focus during find/replace or in another editor */- background-color: #d7d4f0 !important;+ /* Keep drawn selections visible when focus moves to find/replace or another editor. */+ background-color: var(+ --cm-selection-background,+ var(--cm-selection-background-light)+ ) !important;}.dark .cm-selectionBackground {- background-color: #1177cc80 !important;+ background-color: var(+ --cm-selection-background,+ var(--cm-selection-background-dark)+ ) !important;}.cm-focused.cm-focused {@@ -125,7 +129,7 @@/* -- Codeium -- */.cm-codeium-cycle {- font-size: 9px;+ font-size: 0.5625rem;background-color: var(--sky-3);padding: 2px;border-radius: 2px;@@ -133,7 +137,7 @@}.cm-codeium-cycle-key {- font-size: 9px;+ font-size: 0.5625rem;font-family: monospace;display: inline-block;padding: 2px;diff --git a/frontend/src/css/globals.css b/frontend/src/css/globals.cssindex 1d143c604d..deea37a319 100644--- a/frontend/src/css/globals.css+++ b/frontend/src/css/globals.css@@ -107,6 +107,14 @@/* Codemirror editor */--cm-background: light-dark(var(--background), #282c34);--cm-comment: light-dark(#708090, #6b7280);+ --cm-selection-background-light: #d7d4f0;+ --cm-selection-background-dark: #1177cc80;+ --cm-reactive-reference-color-light: #005f87;+ --cm-reactive-reference-color-dark: #2a7aa5;+ --cm-reactive-reference-border-color: #bad3de;+ --cm-search-match-background-light: #99ff7780;+ --cm-search-match-background-dark: #22bb0070;+ --cm-search-match-selected-background-dark: #6199ff88;}.dark,diff --git a/frontend/src/stories/theme.stories.tsx b/frontend/src/stories/theme.stories.tsxindex b8fd3c42cc..7515c9686b 100644--- a/frontend/src/stories/theme.stories.tsx+++ b/frontend/src/stories/theme.stories.tsx@@ -4,11 +4,14 @@ import { python } from "@codemirror/lang-python";import { EditorState, type Extension } from "@codemirror/state";import { EditorView } from "@codemirror/view";import type { Meta, StoryObj } from "@storybook/react-vite";-import React, { useEffect, useRef } from "react";+import React, { useEffect, useRef, useState } from "react";+import { ReadonlyCode } from "../components/editor/code/readonly-python-code";import { basicBundle, type CodeMirrorSetupOpts } from "../core/codemirror/cm";+import { userConfigAtom } from "../core/config/config";import { darkTheme } from "../core/codemirror/theme/dark";import { lightTheme } from "../core/codemirror/theme/light";import { OverridingHotkeyProvider } from "../core/hotkeys/hotkeys";+import { store } from "../core/state/jotai";// Partial config for storybook democonst demoConfig: Partial<CodeMirrorSetupOpts> = {@@ -52,6 +55,11 @@ result = example.get_value()size = example.data_size`.trim();+const READONLY_CONTENT = Array.from(+ { length: 80 },+ (_, index) => `value_${index + 1} = ${index + 1}`,+).join("\n");+const Editor = (opts: { extensions?: Extension[] }): React.ReactNode => {const ref = useRef<HTMLDivElement>(null);useEffect(() => {@@ -110,3 +118,65 @@ export const ThemeComparison: Story = {</div>),};++const ReadonlyCodeThemeFixture = (): React.ReactNode => {+ const [theme, setTheme] = useState<"light" | "dark">("light");+ const [initialTheme] = useState(+ () => store.get(userConfigAtom).display.theme,+ );++ useEffect(() => {+ store.set(userConfigAtom, (config) => ({+ ...config,+ display: { ...config.display, theme },+ }));+ }, [theme]);++ useEffect(() => {+ // Leave Storybook's theme in the state it had before this fixture mounted.+ return () => {+ store.set(userConfigAtom, (config) => ({+ ...config,+ display: { ...config.display, theme: initialTheme },+ }));+ };+ }, [initialTheme]);++ return (+ <div className="max-w-3xl space-y-3" style={{ colorScheme: theme }}>+ <div className="flex items-center justify-between gap-4">+ <div>+ <h3 className="text-lg font-semibold">ReadonlyCode fixture</h3>+ <p className="text-sm text-muted-foreground">+ Select text, scroll, then switch themes to check that both remain.+ </p>+ </div>+ <div className="flex gap-2" role="group" aria-label="Theme">+ {(["light", "dark"] as const).map((nextTheme) => (+ <button+ aria-pressed={theme === nextTheme}+ className="rounded border px-3 py-1 text-sm"+ key={nextTheme}+ onClick={() => setTheme(nextTheme)}+ type="button"+ >+ {nextTheme}+ </button>+ ))}+ </div>+ </div>+ <div className="h-64 overflow-hidden rounded border">+ <ReadonlyCode+ className="h-full [&_.cm-editor]:h-full [&_.cm-scroller]:h-full [&_.cm-theme-none]:h-full"+ code={READONLY_CONTENT}+ showCopyCode={false}+ showHideCode={false}+ />+ </div>+ </div>+ );+};++export const ReadonlyCodeThemeReconfiguration: Story = {+ render: () => <ReadonlyCodeThemeFixture />,+};