Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(code): automatic light/dark theme
Elian Dorandf67ca8bc6b0
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a3f929bd5d..f329ed38b3 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2176,7 +2176,12 @@"code_theme": {"title": "Appearance","word_wrapping": "Word wrapping",- "color-scheme": "Color scheme"+ "color-scheme": "Color scheme",+ "theme_mode": "Theme mode",+ "match_app_appearance": "Match app appearance",+ "always_use_one_theme": "Always use one theme",+ "light_theme": "Light theme",+ "dark_theme": "Dark theme"},"cpu_arch_warning": {"title": "Please download the ARM64 version",diff --git a/apps/client/src/widgets/type_widgets/code/Code.tsx b/apps/client/src/widgets/type_widgets/code/Code.tsxindex 6c74dc8219..e801d12120 100644--- a/apps/client/src/widgets/type_widgets/code/Code.tsx+++ b/apps/client/src/widgets/type_widgets/code/Code.tsx@@ -3,11 +3,12 @@ import "./code.css";import { default as VanillaCodeMirror, getThemeById } from "@triliumnext/codemirror";import { NoteType } from "@triliumnext/commons";import { Ref } from "preact";-import { useEffect, useRef, useState } from "preact/hooks";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";import appContext, { CommandListenerData } from "../../../components/app_context";import FNote from "../../../entities/fnote";import { t } from "../../../services/i18n";+import { getEffectiveThemeStyle } from "../../../services/theme";import utils from "../../../services/utils";import { useEditorSpacedUpdate, useKeyboardShortcuts, useLegacyImperativeHandlers, useNoteBlob, useNoteLabelInt, useNoteLabelOptionalBool, useNoteProperty, useSyncedRef, useTriliumEvent, useTriliumOption, useTriliumOptionBool } from "../../react/hooks";import { refToJQuerySelector } from "../../react/react_utils";@@ -169,6 +170,27 @@ export function CodeEditor({ parentComponent, ntxId, containerRef: externalContaconst [ codeNoteTheme ] = useTriliumOption("codeNoteTheme");const [ codeNoteTabWidth ] = useTriliumOption("codeNoteTabWidth");const [ codeNoteIndentWithTabs ] = useTriliumOptionBool("codeNoteIndentWithTabs");+ const [ matchesApp ] = useTriliumOptionBool("codeNoteThemeMatchesApp");+ const [ lightTheme ] = useTriliumOption("codeNoteThemeLight");+ const [ darkTheme ] = useTriliumOption("codeNoteThemeDark");++ // When "match app appearance" is enabled, resolve the theme based on the+ // current effective app style and react to OS color-scheme changes.+ const [ appStyle, setAppStyle ] = useState(getEffectiveThemeStyle);+ useEffect(() => {+ if (!matchesApp) return;+ // Re-evaluate whenever the OS preference changes.+ const mq = window.matchMedia("(prefers-color-scheme: dark)");+ const handler = () => setAppStyle(getEffectiveThemeStyle());+ mq.addEventListener("change", handler);+ // Also recalculate immediately in case the app theme option changed.+ setAppStyle(getEffectiveThemeStyle());+ return () => mq.removeEventListener("change", handler);+ }, [ matchesApp ]);++ const effectiveTheme = matchesApp+ ? (appStyle === "dark" ? darkTheme : lightTheme)+ : codeNoteTheme;// React to background color.const [ backgroundColor, setBackgroundColor ] = useState<string>();@@ -177,10 +199,9 @@ export function CodeEditor({ parentComponent, ntxId, containerRef: externalContaparentComponent?.$widget.closest(".scrolling-container").css("--code-background-color", backgroundColor);}, [ backgroundColor ]);- // React to theme changes.- useEffect(() => {- if (codeEditorRef.current && codeNoteTheme.startsWith(DEFAULT_PREFIX)) {- const theme = getThemeById(codeNoteTheme.substring(DEFAULT_PREFIX.length));+ const applyTheme = useCallback((themeName: string) => {+ if (codeEditorRef.current && themeName.startsWith(DEFAULT_PREFIX)) {+ const theme = getThemeById(themeName.substring(DEFAULT_PREFIX.length));if (theme) {codeEditorRef.current.setTheme(theme).then(() => {const editor = containerRef.current?.querySelector(".cm-editor");@@ -190,7 +211,12 @@ export function CodeEditor({ parentComponent, ntxId, containerRef: externalConta});}}- }, [ codeEditorRef, codeNoteTheme ]);+ }, []);++ // React to theme changes.+ useEffect(() => {+ applyTheme(effectiveTheme);+ }, [ codeEditorRef, effectiveTheme, applyTheme ]);useTriliumEvent("executeWithCodeEditor", async ({ resolve, ntxId: eventNtxId }) => {if (eventNtxId !== ntxId) return;diff --git a/apps/client/src/widgets/type_widgets/options/code_notes.tsx b/apps/client/src/widgets/type_widgets/options/code_notes.tsxindex 511c40b38f..e8f3133d40 100644--- a/apps/client/src/widgets/type_widgets/options/code_notes.tsx+++ b/apps/client/src/widgets/type_widgets/options/code_notes.tsx@@ -1,6 +1,6 @@import "./code_notes.css";-import CodeMirror, { ColorThemes, getThemeById } from "@triliumnext/codemirror";+import CodeMirror, { ColorThemes, getThemeById, type ThemeVariant } from "@triliumnext/codemirror";import { default as codeNoteMimeTypes } from "@triliumnext/codemirror/src/syntax_highlighting";import { MimeType } from "@triliumnext/commons";import { byMimeType as codeBlockMimeTypes } from "@triliumnext/highlightjs/src/syntax_highlighting";@@ -8,9 +8,12 @@ import { useEffect, useMemo, useRef } from "preact/hooks";import { t } from "../../../services/i18n";import mime_types from "../../../services/mime_types";+import { getEffectiveThemeStyle } from "../../../services/theme";+import { ButtonGroup } from "../../react/Button";import FormSelect from "../../react/FormSelect";import { FormTextBoxWithUnit } from "../../react/FormTextBox";import { useStaticTooltip, useTriliumOption, useTriliumOptionBool, useTriliumOptionJson } from "../../react/hooks";+import Icon from "../../react/Icon";import { CODE_THEME_DEFAULT_PREFIX as DEFAULT_PREFIX } from "../constants";import CheckboxList from "./components/CheckboxList";import OptionsRow, { OptionsRowWithToggle } from "./components/OptionsRow";@@ -87,27 +90,80 @@ interface AppearanceProps {indentSize: number;}+function useFilteredThemes(variant?: ThemeVariant) {+ return useMemo(() => {+ return ColorThemes+ .filter((theme) => !variant || theme.variant === variant)+ .map(({ id, name }) => ({+ id: `default:${id}`,+ name+ }));+ }, [variant]);+}+function Appearance({ wordWrapping, indentSize }: AppearanceProps) {const [codeNoteTheme, setCodeNoteTheme] = useTriliumOption("codeNoteTheme");+ const [matchesApp, setMatchesApp] = useTriliumOptionBool("codeNoteThemeMatchesApp");+ const [lightTheme, setLightTheme] = useTriliumOption("codeNoteThemeLight");+ const [darkTheme, setDarkTheme] = useTriliumOption("codeNoteThemeDark");- const themes = useMemo(() => {- return ColorThemes.map(({ id, name }) => ({- id: `default:${id}`,- name- }));- }, []);+ const allThemes = useFilteredThemes();+ const lightThemes = useFilteredThemes("light");+ const darkThemes = useFilteredThemes("dark");++ const effectiveTheme = matchesApp+ ? (getEffectiveThemeStyle() === "dark" ? darkTheme : lightTheme)+ : codeNoteTheme;return (<OptionsSection title={t("code_theme.title")}>- <OptionsRow name="color-scheme" label={t("code_theme.color-scheme")}>- <FormSelect- values={themes}- keyProperty="id" titleProperty="name"- currentValue={codeNoteTheme} onChange={setCodeNoteTheme}- />+ <OptionsRow name="theme-mode" label={t("code_theme.theme_mode")}>+ <ButtonGroup>+ <button+ type="button"+ className={`btn btn-sm btn-secondary ${matchesApp ? "active" : ""}`}+ onClick={() => setMatchesApp(true)}+ >+ <Icon icon="bx bx-brightness-half" />{" "}{t("code_theme.match_app_appearance")}+ </button>+ <button+ type="button"+ className={`btn btn-sm btn-secondary ${!matchesApp ? "active" : ""}`}+ onClick={() => setMatchesApp(false)}+ >+ <Icon icon="bx bx-pin" />{" "}{t("code_theme.always_use_one_theme")}+ </button>+ </ButtonGroup></OptionsRow>- <CodeNotePreview wordWrapping={wordWrapping} themeName={codeNoteTheme} indentSize={indentSize} />+ {matchesApp ? (+ <>+ <OptionsRow name="light-theme" label={t("code_theme.light_theme")}>+ <FormSelect+ values={lightThemes}+ keyProperty="id" titleProperty="name"+ currentValue={lightTheme} onChange={setLightTheme}+ />+ </OptionsRow>+ <OptionsRow name="dark-theme" label={t("code_theme.dark_theme")}>+ <FormSelect+ values={darkThemes}+ keyProperty="id" titleProperty="name"+ currentValue={darkTheme} onChange={setDarkTheme}+ />+ </OptionsRow>+ </>+ ) : (+ <OptionsRow name="color-scheme" label={t("code_theme.color-scheme")}>+ <FormSelect+ values={allThemes}+ keyProperty="id" titleProperty="name"+ currentValue={codeNoteTheme} onChange={setCodeNoteTheme}+ />+ </OptionsRow>+ )}++ <CodeNotePreview wordWrapping={wordWrapping} themeName={effectiveTheme} indentSize={indentSize} /></OptionsSection>);}diff --git a/packages/codemirror/src/color_themes.ts b/packages/codemirror/src/color_themes.tsindex a50afe8567..550bb9f32d 100644--- a/packages/codemirror/src/color_themes.ts+++ b/packages/codemirror/src/color_themes.ts@@ -1,8 +1,11 @@import type { Extension } from '@codemirror/state';+export type ThemeVariant = "light" | "dark";+export interface ThemeDefinition {id: string;name: string;+ variant: ThemeVariant;load(): Promise<Extension>;}@@ -10,161 +13,193 @@ const themes: ThemeDefinition[] = [{id: "abyss",name: "Abyss",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-abyss")).abyss},{id: "abcdef",name: "ABCDEF",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-abcdef")).abcdef},{id: "android-studio",name: "Android Studio",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-android-studio")).androidStudio},{id: "andromeda",name: "Andromeda",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-andromeda")).andromeda},{id: "basic-dark",name: "Basic Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-basic-dark")).basicDark},{id: "basic-light",name: "Basic Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-basic-light")).basicLight},{id: "catppuccin-frappe",name: "Catppuccin Frappé",+ variant: "dark",load: async () => (await import("@catppuccin/codemirror")).catppuccinFrappe},{id: "catppuccin-latte",name: "Catppuccin Latte",+ variant: "light",load: async () => (await import("@catppuccin/codemirror")).catppuccinLatte},{id: "catppuccin-macchiato",name: "Catppuccin Macchiato",+ variant: "dark",load: async () => (await import("@catppuccin/codemirror")).catppuccinMacchiato},{id: "catppuccin-mocha",name: "Catppuccin Mocha",+ variant: "dark",load: async () => (await import("@catppuccin/codemirror")).catppuccinMocha},{id: "cobalt2",name: "Cobalt2",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-cobalt2")).cobalt2},{id: "forest",name: "Forest",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-forest")).forest},{id: "github-dark",name: "GitHub Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-github-dark")).githubDark},{id: "github-light",name: "GitHub Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-github-light")).githubLight},{id: "high-contrast-dark",name: "High Contrast Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-high-contrast-dark")).highContrastDark},{id: "high-contrast-light",name: "High Contrast Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-high-contrast-light")).highContrastLight},{id: "gruvbox-dark",name: "Gruvbox Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-gruvbox-dark")).gruvboxDark},{id: "gruvbox-light",name: "Gruvbox Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-gruvbox-light")).gruvboxLight},{id: "material-mark",name: "Material Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-material-dark")).materialDark},{id: "material-light",name: "Material Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-material-light")).materialLight},{id: "material-ocean",name: "Material Ocean",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-material-ocean")).materialOcean},{id: "monokai",name: "Monokai",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-monokai")).monokai},{id: "nord",name: "Nord",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-nord")).nord},{id: "palenight",name: "Palenight",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-palenight")).palenight},{id: "solarized-dark",name: "Solarized Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-solarized-dark")).solarizedDark},{id: "solarized-light",name: "Solarized Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-solarized-light")).solarizedLight},{id: "synthwave-84",name: "Synthwave '84",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-synthwave-84")).synthwave84},{id: "tokyo-night-day",name: "Tokyo Night Day",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-tokyo-night-day")).tokyoNightDay},{id: "tokyo-night-storm",name: "Tokyo Night Storm",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-tokyo-night-storm")).tokyoNightStorm},{id: "volcano",name: "Volcano",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-volcano")).volcano},{id: "vs-code-dark",name: "VS Code Dark",+ variant: "dark",load: async () => (await import("@fsegurai/codemirror-theme-vscode-dark")).vsCodeDark},{id: "vs-code-light",name: "VS Code Light",+ variant: "light",load: async () => (await import("@fsegurai/codemirror-theme-vscode-light")).vsCodeLight},]diff --git a/packages/codemirror/src/index.ts b/packages/codemirror/src/index.tsindex f71c1f2960..5cbaac90fa 100644--- a/packages/codemirror/src/index.ts+++ b/packages/codemirror/src/index.ts@@ -10,7 +10,7 @@ import smartIndentWithTab from "./extensions/custom_tab.js";import type { ThemeDefinition } from "./color_themes.js";import { createSearchHighlighter, SearchHighlighter, searchMatchHighlightTheme } from "./find_replace.js";-export { default as ColorThemes, type ThemeDefinition, getThemeById } from "./color_themes.js";+export { default as ColorThemes, type ThemeDefinition, type ThemeVariant, getThemeById } from "./color_themes.js";// Custom keymap to prevent Ctrl+Enter from inserting a newline// This allows the parent application to handle the shortcut (e.g., for "Run Active Note")diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 5ecc585e61..7b2cd4113b 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -136,6 +136,9 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActibackdropEffectsEnabled: boolean;smoothScrollEnabled: boolean;codeNoteTheme: string;+ codeNoteThemeMatchesApp: boolean;+ codeNoteThemeLight: string;+ codeNoteThemeDark: string;initialized: boolean;databaseReadonly: boolean;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex ed3b4b07c3..0802923828 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -33,6 +33,9 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["codeBlockWordWrap","codeBlockTabWidth","codeNoteTheme",+ "codeNoteThemeMatchesApp",+ "codeNoteThemeLight",+ "codeNoteThemeDark","codeNoteTabWidth","codeNoteIndentWithTabs","syncServerHost",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex f445ce964b..abde9c7293 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -197,6 +197,9 @@ const defaultOptions: DefaultOption[] = [},isSynced: false},+ { name: "codeNoteThemeMatchesApp", value: "false", isSynced: false },+ { name: "codeNoteThemeLight", value: "default:vs-code-light", isSynced: false },+ { name: "codeNoteThemeDark", value: "default:vs-code-dark", isSynced: false },{ name: "motionEnabled", value: "true", isSynced: false },{ name: "shadowsEnabled", value: "true", isSynced: false },{ name: "backdropEffectsEnabled", value: "true", isSynced: false },