Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: upgrade editor custom theme system with multi-theme, dark mode support, CSS sandbox and WeChat copy inlining

tianma-if1b2f85bb22a8
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index ea36b57d..b0c9bfee 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -66,6 +66,7 @@ import { EditorOutline } from "./EditorOutline";
import { WeChatIcon } from "./WeChatIcon";
import { ThemeToggle } from "./ThemeToggle";
import { useTheme } from "./ThemeProvider";
+import { sanitizeAndScopeCss } from "@/lib/css-sandbox";
import { RevisionHistoryDialog } from "./dialogs/RevisionHistoryDialog";
import { api } from "@/lib/api";
import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceUrl } from "@/lib/desktop-resources";
@@ -1160,7 +1161,7 @@ const RichEditorPane = ({
onRequestMobileNativeEdit,
}: RichEditorPaneProps) => {
const { t, i18n } = useTranslation();
- const { customEditorTheme, editorTheme } = useTheme();
+ const { customEditorTheme, editorTheme, resolvedTheme } = useTheme();
const queryClient = useQueryClient();
const isSelectionMode = Boolean(selectionActionBar);
const [title, setTitle] = useState("");
@@ -3196,20 +3197,38 @@ const RichEditorPane = ({
<div
ref={setEditorScrollContainerRef}
- data-editor-theme={editorTheme}
- style={editorTheme === "custom" ? {
- "--editor-theme-bg": customEditorTheme.background,
- "--editor-theme-text": customEditorTheme.text,
- "--editor-theme-heading": customEditorTheme.heading,
- "--editor-theme-accent": customEditorTheme.accent,
- "--editor-theme-soft": customEditorTheme.soft,
- "--editor-theme-border": customEditorTheme.border,
- } as CSSProperties : undefined}
+ data-editor-theme={
+ editorTheme === "default" || editorTheme === "minimal-emerald" || editorTheme === "outline-emerald"
+ ? editorTheme
+ : "custom"
+ }
+ style={
+ editorTheme !== "default" && editorTheme !== "minimal-emerald" && editorTheme !== "outline-emerald"
+ ? {
+ "--editor-theme-bg": (resolvedTheme === "dark" ? customEditorTheme.dark : customEditorTheme.light).background,
+ "--editor-theme-text": (resolvedTheme === "dark" ? customEditorTheme.dark : customEditorTheme.light).text,
+ "--editor-theme-heading": (resolvedTheme === "dark" ? customEditorTheme.dark : customEditorTheme.light).heading,
+ "--editor-theme-accent": (resolvedTheme === "dark" ? customEditorTheme.dark : customEditorTheme.light).accent,
+ "--editor-theme-soft": (resolvedTheme === "dark" ? customEditorTheme.dark : customEditorTheme.light).soft,
+ "--editor-theme-border": (resolvedTheme === "dark" ? customEditorTheme.dark : customEditorTheme.light).border,
+ } as CSSProperties
+ : undefined
+ }
className={cn(
"edgeever-editor relative min-h-0 flex-1 bg-white",
useMobilePlainTextEditor ? "overflow-visible" : "overflow-y-auto"
)}
>
+ {editorTheme !== "default" &&
+ editorTheme !== "minimal-emerald" &&
+ editorTheme !== "outline-emerald" &&
+ customEditorTheme.customCss && (
+ <style
+ data-theme-custom-css
+ data-original-css={customEditorTheme.customCss}
+ dangerouslySetInnerHTML={{ __html: sanitizeAndScopeCss(customEditorTheme.customCss) }}
+ />
+ )}
<div
className={cn(
"flex min-h-full items-start gap-8 px-6 py-6 sm:px-10 transition-all duration-200",
diff --git a/apps/web/src/components/ThemeProvider.tsx b/apps/web/src/components/ThemeProvider.tsx
index 07479263..42b6181d 100644
--- a/apps/web/src/components/ThemeProvider.tsx
+++ b/apps/web/src/components/ThemeProvider.tsx
@@ -27,10 +27,9 @@ export const EDITOR_THEME_NAMES = [
"outline-emerald",
"custom",
] as const;
-export type EditorThemeName = (typeof EDITOR_THEME_NAMES)[number];
+export type EditorThemeName = string;
-export interface CustomEditorTheme {
- name: string;
+export interface ThemeColors {
background: string;
text: string;
heading: string;
@@ -39,8 +38,15 @@ export interface CustomEditorTheme {
border: string;
}
-export const DEFAULT_CUSTOM_EDITOR_THEME: CustomEditorTheme = {
- name: "My custom theme",
+export interface CustomEditorTheme {
+ id: string;
+ name: string;
+ light: ThemeColors;
+ dark: ThemeColors;
+ customCss?: string;
+}
+
+export const DEFAULT_CUSTOM_LIGHT_COLORS: ThemeColors = {
background: "#fffdf7",
text: "#292524",
heading: "#1c1917",
@@ -49,6 +55,23 @@ export const DEFAULT_CUSTOM_EDITOR_THEME: CustomEditorTheme = {
border: "#99f6e4",
};
+export const DEFAULT_CUSTOM_DARK_COLORS: ThemeColors = {
+ background: "#1c1917",
+ text: "#fafaf9",
+ heading: "#fafaf9",
+ accent: "#0d9488",
+ soft: "#292524",
+ border: "#44403c",
+};
+
+export const DEFAULT_CUSTOM_EDITOR_THEME: CustomEditorTheme = {
+ id: "custom-default",
+ name: "My custom theme",
+ light: DEFAULT_CUSTOM_LIGHT_COLORS,
+ dark: DEFAULT_CUSTOM_DARK_COLORS,
+ customCss: "",
+};
+
interface ThemeContextValue {
preference: ThemePreference;
resolvedTheme: ResolvedTheme;
@@ -57,6 +80,8 @@ interface ThemeContextValue {
setMermaidTheme: (theme: MermaidThemeName) => void;
editorTheme: EditorThemeName;
setEditorTheme: (theme: EditorThemeName) => void;
+ customEditorThemes: CustomEditorTheme[];
+ setCustomEditorThemes: (themes: CustomEditorTheme[]) => void;
customEditorTheme: CustomEditorTheme;
setCustomEditorTheme: (theme: CustomEditorTheme) => void;
}
@@ -69,6 +94,7 @@ const THEME_STORAGE_KEY = "edgeever.theme";
const MERMAID_THEME_STORAGE_KEY = "edgeever.mermaid-theme";
const EDITOR_THEME_STORAGE_KEY = "edgeever.editor-theme";
const CUSTOM_EDITOR_THEME_STORAGE_KEY = "edgeever.custom-editor-theme";
+const CUSTOM_EDITOR_THEMES_STORAGE_KEY = "edgeever.custom-editor-themes";
const LIGHT_THEME_COLOR = "#f8fafc";
const DARK_THEME_COLOR = "#0f172a";
const ThemeContext = createContext<ThemeContextValue | null>(null);
@@ -94,28 +120,61 @@ export const getStoredMermaidTheme = (): MermaidThemeName => {
return MERMAID_THEME_NAMES.includes(stored as MermaidThemeName) ? stored as MermaidThemeName : "zinc-light";
};
-export const getStoredEditorTheme = (): EditorThemeName => {
+export const getStoredEditorTheme = (): string => {
if (typeof window === "undefined") return "default";
const stored = window.localStorage.getItem(EDITOR_THEME_STORAGE_KEY);
- return EDITOR_THEME_NAMES.includes(stored as EditorThemeName) ? (stored as EditorThemeName) : "default";
+ return stored || "default";
};
const isHexColor = (value: unknown): value is string => typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value);
-export const getStoredCustomEditorTheme = (): CustomEditorTheme => {
- if (typeof window === "undefined") return DEFAULT_CUSTOM_EDITOR_THEME;
+export const getStoredCustomEditorThemes = (): CustomEditorTheme[] => {
+ if (typeof window === "undefined") return [DEFAULT_CUSTOM_EDITOR_THEME];
try {
- const stored = JSON.parse(window.localStorage.getItem(CUSTOM_EDITOR_THEME_STORAGE_KEY) || "null") as Partial<CustomEditorTheme> | null;
- if (!stored || typeof stored.name !== "string") return DEFAULT_CUSTOM_EDITOR_THEME;
- const colors = [stored.background, stored.text, stored.heading, stored.accent, stored.soft, stored.border];
- if (!colors.every(isHexColor)) return DEFAULT_CUSTOM_EDITOR_THEME;
- return { ...DEFAULT_CUSTOM_EDITOR_THEME, ...stored } as CustomEditorTheme;
+ const storedThemesStr = window.localStorage.getItem(CUSTOM_EDITOR_THEMES_STORAGE_KEY);
+ if (storedThemesStr) {
+ const parsed = JSON.parse(storedThemesStr) as CustomEditorTheme[];
+ if (Array.isArray(parsed) && parsed.length > 0) {
+ return parsed;
+ }
+ }
} catch {
- return DEFAULT_CUSTOM_EDITOR_THEME;
+ // Ignore error
}
+
+ // Migrate legacy single custom theme
+ try {
+ const oldThemeStr = window.localStorage.getItem(CUSTOM_EDITOR_THEME_STORAGE_KEY);
+ if (oldThemeStr) {
+ const oldTheme = JSON.parse(oldThemeStr) as any;
+ if (oldTheme && typeof oldTheme.name === "string") {
+ const migratedTheme: CustomEditorTheme = {
+ id: "custom-migrated",
+ name: oldTheme.name || "My custom theme",
+ light: {
+ background: oldTheme.background || DEFAULT_CUSTOM_LIGHT_COLORS.background,
+ text: oldTheme.text || DEFAULT_CUSTOM_LIGHT_COLORS.text,
+ heading: oldTheme.heading || DEFAULT_CUSTOM_LIGHT_COLORS.heading,
+ accent: oldTheme.accent || DEFAULT_CUSTOM_LIGHT_COLORS.accent,
+ soft: oldTheme.soft || DEFAULT_CUSTOM_LIGHT_COLORS.soft,
+ border: oldTheme.border || DEFAULT_CUSTOM_LIGHT_COLORS.border,
+ },
+ dark: DEFAULT_CUSTOM_DARK_COLORS,
+ customCss: "",
+ };
+ window.localStorage.setItem(CUSTOM_EDITOR_THEMES_STORAGE_KEY, JSON.stringify([migratedTheme]));
+ return [migratedTheme];
+ }
+ }
+ } catch {
+ // Ignore error
+ }
+
+ return [DEFAULT_CUSTOM_EDITOR_THEME];
};
+
const applyThemeToDocument = (preference: ThemePreference) => {
const resolvedTheme = resolveTheme(preference);
const root = document.documentElement;
@@ -135,8 +194,8 @@ export const ThemeProvider = ({ children }: ThemeProviderProps) => {
const [preference, setPreferenceState] = useState<ThemePreference>(getStoredThemePreference);
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>(() => resolveTheme(preference));
const [mermaidTheme, setMermaidThemeState] = useState<MermaidThemeName>(getStoredMermaidTheme);
- const [editorTheme, setEditorThemeState] = useState<EditorThemeName>(getStoredEditorTheme);
- const [customEditorTheme, setCustomEditorThemeState] = useState<CustomEditorTheme>(getStoredCustomEditorTheme);
+ const [editorTheme, setEditorThemeState] = useState<string>(getStoredEditorTheme);
+ const [customEditorThemes, setCustomEditorThemesState] = useState<CustomEditorTheme[]>(getStoredCustomEditorThemes);
useEffect(() => {
setResolvedTheme(applyThemeToDocument(preference));
@@ -152,6 +211,32 @@ export const ThemeProvider = ({ children }: ThemeProviderProps) => {
return () => mediaQuery.removeEventListener("change", handleSystemThemeChange);
}, [preference]);
+ const customEditorTheme = useMemo(() => {
+ const active = customEditorThemes.find((t) => t.id === editorTheme);
+ if (active) return active;
+ return customEditorThemes[0] || DEFAULT_CUSTOM_EDITOR_THEME;
+ }, [customEditorThemes, editorTheme]);
+
+ const setCustomEditorTheme = (updatedTheme: CustomEditorTheme) => {
+ const nextThemes = customEditorThemes.map((t) =>
+ t.id === updatedTheme.id ? updatedTheme : t
+ );
+ if (!customEditorThemes.some((t) => t.id === updatedTheme.id)) {
+ if (customEditorThemes.length > 0) {
+ nextThemes[0] = { ...customEditorThemes[0], ...updatedTheme };
+ } else {
+ nextThemes.push(updatedTheme);
+ }
+ }
+ setCustomEditorThemesState(nextThemes);
+ window.localStorage.setItem(CUSTOM_EDITOR_THEMES_STORAGE_KEY, JSON.stringify(nextThemes));
+ };
+
+ const setCustomEditorThemes = (nextThemes: CustomEditorTheme[]) => {
+ setCustomEditorThemesState(nextThemes);
+ window.localStorage.setItem(CUSTOM_EDITOR_THEMES_STORAGE_KEY, JSON.stringify(nextThemes));
+ };
+
const value = useMemo(
() => ({
preference,
@@ -163,17 +248,16 @@ export const ThemeProvider = ({ children }: ThemeProviderProps) => {
window.localStorage.setItem(MERMAID_THEME_STORAGE_KEY, nextTheme);
},
editorTheme,
- setEditorTheme: (nextTheme: EditorThemeName) => {
+ setEditorTheme: (nextTheme: string) => {
setEditorThemeState(nextTheme);
window.localStorage.setItem(EDITOR_THEME_STORAGE_KEY, nextTheme);
},
+ customEditorThemes,
+ setCustomEditorThemes,
customEditorTheme,
- setCustomEditorTheme: (nextTheme: CustomEditorTheme) => {
- setCustomEditorThemeState(nextTheme);
- window.localStorage.setItem(CUSTOM_EDITOR_THEME_STORAGE_KEY, JSON.stringify(nextTheme));
- },
+ setCustomEditorTheme,
}),
- [customEditorTheme, editorTheme, mermaidTheme, preference, resolvedTheme]
+ [customEditorThemes, customEditorTheme, editorTheme, mermaidTheme, preference, resolvedTheme]
);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
@@ -188,3 +272,4 @@ export const useTheme = () => {
return context;
};
+
diff --git a/apps/web/src/components/settings/CustomEditorThemeDialog.tsx b/apps/web/src/components/settings/CustomEditorThemeDialog.tsx
index 45e0a09f..53203c83 100644
--- a/apps/web/src/components/settings/CustomEditorThemeDialog.tsx
+++ b/apps/web/src/components/settings/CustomEditorThemeDialog.tsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
-import { RotateCcw } from "lucide-react";
+import { RotateCcw, Sun, Moon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import {
@@ -11,13 +11,21 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
-import { DEFAULT_CUSTOM_EDITOR_THEME, type CustomEditorTheme } from "../ThemeProvider";
+import { sanitizeAndScopeCss } from "@/lib/css-sandbox";
+import {
+ DEFAULT_CUSTOM_LIGHT_COLORS,
+ DEFAULT_CUSTOM_DARK_COLORS,
+ type CustomEditorTheme,
+ type ThemeColors,
+} from "../ThemeProvider";
interface CustomEditorThemeDialogProps {
open: boolean;
theme: CustomEditorTheme;
onOpenChange: (open: boolean) => void;
onSave: (theme: CustomEditorTheme) => void;
+ onDelete?: (id: string) => void;
+ isDefaultTheme?: boolean;
}
const COLOR_FIELDS = [
@@ -29,64 +37,203 @@ const COLOR_FIELDS = [
["border", "settings.customEditorTheme.border"],
] as const;
-export const CustomEditorThemeDialog = ({ open, theme, onOpenChange, onSave }: CustomEditorThemeDialogProps) => {
+export const CustomEditorThemeDialog = ({
+ open,
+ theme,
+ onOpenChange,
+ onSave,
+ onDelete,
+ isDefaultTheme = false,
+}: CustomEditorThemeDialogProps) => {
const { t } = useTranslation();
- const [draft, setDraft] = useState(theme);
+ const [draft, setDraft] = useState<CustomEditorTheme>(theme);
+ const [activeMode, setActiveMode] = useState<"light" | "dark">("light");
useEffect(() => {
- if (open) setDraft(theme);
+ if (open) {
+ setDraft(theme);
+ setActiveMode("light");
+ }
}, [open, theme]);
- const update = (key: keyof CustomEditorTheme, value: string) => setDraft((current) => ({ ...current, [key]: value }));
- const valid = COLOR_FIELDS.every(([key]) => /^#[0-9a-f]{6}$/i.test(draft[key])) && draft.name.trim().length > 0;
+ const updateName = (name: string) => setDraft((current) => ({ ...current, name }));
+
+ const updateColor = (key: keyof ThemeColors, value: string) => {
+ setDraft((current) => ({
+ ...current,
+ [activeMode]: {
+ ...current[activeMode],
+ [key]: value,
+ },
+ }));
+ };
+
+ const activeColors = draft[activeMode] || DEFAULT_CUSTOM_LIGHT_COLORS;
+ const defaultColors = activeMode === "light" ? DEFAULT_CUSTOM_LIGHT_COLORS : DEFAULT_CUSTOM_DARK_COLORS;
+
+ const validColors = (colors: ThemeColors) =>
+ COLOR_FIELDS.every(([key]) => /^#[0-9a-f]{6}$/i.test(colors[key]));
+
+ const valid =
+ draft.name.trim().length > 0 &&
+ validColors(draft.light) &&
+ validColors(draft.dark);
+
+ const handleReset = () => {
+ setDraft((current) => ({
+ ...current,
+ light: DEFAULT_CUSTOM_LIGHT_COLORS,
+ dark: DEFAULT_CUSTOM_DARK_COLORS,
+ customCss: "",
+ }));
+ };
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t("settings.customEditorTheme.title")}</DialogTitle>
- <DialogDescription>{t("settings.customEditorTheme.description")}</DialogDescription>
+ <DialogContent className="max-w-[440px] sm:max-w-[500px] max-h-[95vh] overflow-y-auto p-5">
+ <DialogHeader className="space-y-1">
+ <DialogTitle className="text-base">{t("settings.customEditorTheme.title")}</DialogTitle>
+ <DialogDescription className="text-xs">{t("settings.customEditorTheme.description")}</DialogDescription>
</DialogHeader>
- <div className="grid gap-4">
- <label className="grid gap-1.5 text-sm font-medium text-slate-700">
- {t("settings.customEditorTheme.name")}
- <Input value={draft.name} onChange={(event) => update("name", event.target.value)} maxLength={32} />
- </label>
- <div className="grid grid-cols-2 gap-3">
+ <div className="grid gap-3 mt-1.5">
+ {/* Theme Name */}
+ <div className="flex items-center justify-between gap-4 text-xs font-semibold text-slate-700">
+ <span>{t("settings.customEditorTheme.name")}</span>
+ <Input
+ value={draft.name}
+ onChange={(event) => updateName(event.target.value)}
+ maxLength={32}
+ className="h-8 max-w-[240px] text-xs"
+ />
+ </div>
+
+ {/* Mode Switcher */}
+ <div className="flex rounded-lg border border-slate-200 bg-slate-50 p-0.5">
+ <button
+ type="button"
+ onClick={() => setActiveMode("light")}
+ className={`flex flex-1 items-center justify-center gap-1.5 rounded-md py-1 text-xs font-medium transition-all ${
+ activeMode === "light"
+ ? "bg-white text-emerald-800 shadow-sm"
+ : "text-slate-500 hover:text-slate-800"
+ }`}
+ >
+ <Sun className="h-3.5 w-3.5" />
+ {t("settings.themeToggleToLight")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setActiveMode("dark")}
+ className={`flex flex-1 items-center justify-center gap-1.5 rounded-md py-1 text-xs font-medium transition-all ${
+ activeMode === "dark"
+ ? "bg-white text-emerald-800 shadow-sm"
+ : "text-slate-500 hover:text-slate-800"
+ }`}
+ >
+ <Moon className="h-3.5 w-3.5" />
+ {t("settings.themeToggleToDark")}
+ </button>
+ </div>
+
+ {/* Color Matrix */}
+ <div className="grid grid-cols-2 gap-x-6 gap-y-2">
{COLOR_FIELDS.map(([key, labelKey]) => (
- <label key={key} className="grid gap-1.5 text-sm font-medium text-slate-700">
- {t(labelKey)}
- <div className="flex items-center gap-2">
+ <div key={key} className="flex items-center justify-between gap-2 text-xs font-medium text-slate-700">
+ <span className="truncate">{t(labelKey)}</span>
+ <div className="flex items-center gap-1.5 shrink-0">
<input
type="color"
- value={/^#[0-9a-f]{6}$/i.test(draft[key]) ? draft[key] : DEFAULT_CUSTOM_EDITOR_THEME[key]}
- onChange={(event) => update(key, event.target.value)}
- className="h-10 w-12 cursor-pointer rounded-md border border-slate-200 bg-white p-1"
+ value={/^#[0-9a-f]{6}$/i.test(activeColors[key]) ? activeColors[key] : defaultColors[key]}
+ onChange={(event) => updateColor(key as keyof ThemeColors, event.target.value)}
+ className="h-7 w-7 cursor-pointer rounded border border-slate-200 bg-white p-0.5"
aria-label={t(labelKey)}
/>
- <Input value={draft[key]} onChange={(event) => update(key, event.target.value)} maxLength={7} />
+ <Input
+ value={activeColors[key]}
+ onChange={(event) => updateColor(key as keyof ThemeColors, event.target.value)}
+ maxLength={7}
+ className="h-7 w-20 px-1.5 font-mono text-[11px]"
+ />
</div>
- </label>
+ </div>
))}
</div>
+
+ {/* Custom CSS Textarea */}
+ <label className="grid gap-1 text-xs font-semibold text-slate-700">
+ {t("settings.customEditorTheme.customCss", "Custom CSS (高级自定义样式表)")}
+ <textarea
+ value={draft.customCss || ""}
+ onChange={(event) => setDraft((current) => ({ ...current, customCss: event.target.value }))}
+ placeholder="e.g. h1 { font-style: italic; } blockquote { border-radius: 6px; }"
+ className="min-h-[72px] w-full rounded-md border border-slate-200 bg-white p-2 font-mono text-[11px] focus:border-emerald-500 focus:outline-none"
+ maxLength={2000}
+ />
+ </label>
+
+ {/* Preview Panel */}
<div
- className="rounded-lg border p-4 text-sm leading-7"
- style={{ backgroundColor: draft.background, color: draft.text, borderColor: draft.border }}
+ className="edgeever-editor rounded-lg border transition-all"
+ style={{
+ backgroundColor: activeColors.background,
+ borderColor: activeColors.border,
+ }}
>
- <div className="text-lg font-semibold" style={{ color: draft.heading }}>{t("settings.customEditorTheme.previewTitle")}</div>
- <p>{t("settings.customEditorTheme.previewBody")}</p>
- <strong style={{ color: draft.accent }}>{t("settings.customEditorTheme.previewAccent")}</strong>
+ <div
+ className="ProseMirror p-3 text-xs leading-6"
+ style={{
+ color: activeColors.text,
+ }}
+ >
+ {draft.customCss && (
+ <style dangerouslySetInnerHTML={{ __html: sanitizeAndScopeCss(draft.customCss) }} />
+ )}
+ <div className="text-sm font-semibold mb-0.5" style={{ color: activeColors.heading }}>
+ {t("settings.customEditorTheme.previewTitle")}
+ </div>
+ <p className="mb-0.5">{t("settings.customEditorTheme.previewBody")}</p>
+ <strong style={{ color: activeColors.accent }}>
+ {t("settings.customEditorTheme.previewAccent")}
+ </strong>
+ </div>
</div>
</div>
- <DialogFooter>
- <Button variant="ghost" className="mr-auto" onClick={() => setDraft(DEFAULT_CUSTOM_EDITOR_THEME)}>
- <RotateCcw className="h-4 w-4" />
- {t("settings.customEditorTheme.reset")}
- </Button>
- <Button variant="outline" onClick={() => onOpenChange(false)}>{t("common.cancel")}</Button>
- <Button disabled={!valid} onClick={() => { onSave({ ...draft, name: draft.name.trim() }); onOpenChange(false); }}>
- {t("common.save")}
- </Button>
+ <DialogFooter className="gap-2 sm:gap-0 mt-3 pt-2 border-t border-slate-100">
+ <div className="flex flex-1 gap-2">
+ <Button variant="ghost" size="sm" className="h-8 px-2.5 text-xs text-slate-500 hover:text-slate-800" onClick={handleReset} title={t("settings.customEditorTheme.reset")}>
+ <RotateCcw className="h-3.5 w-3.5 mr-1" />
+ {t("settings.customEditorTheme.reset")}
+ </Button>
+ {onDelete && !isDefaultTheme && (
+ <Button
+ variant="danger"
+ size="sm"
+ className="h-8 text-xs"
+ onClick={() => {
+ onDelete(draft.id);
+ onOpenChange(false);
+ }}
+ >
+ {t("common.delete")}
+ </Button>
+ )}
+ </div>
+ <div className="flex gap-1.5">
+ <Button variant="outline" size="sm" className="h-8 text-xs" onClick={() => onOpenChange(false)}>
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={!valid}
+ size="sm"
+ className="h-8 text-xs"
+ onClick={() => {
+ onSave({ ...draft, name: draft.name.trim() });
+ onOpenChange(false);
+ }}
+ >
+ {t("common.save")}
+ </Button>
+ </div>
</DialogFooter>
</DialogContent>
</Dialog>
diff --git a/apps/web/src/components/settings/PreferenceCard.tsx b/apps/web/src/components/settings/PreferenceCard.tsx
index 8fbb6ceb..36a26f9f 100644
--- a/apps/web/src/components/settings/PreferenceCard.tsx
+++ b/apps/web/src/components/settings/PreferenceCard.tsx
@@ -1,5 +1,5 @@
import { ChartNoAxesCombined, Image, Languages, Palette, RefreshCw } from "lucide-react";
-import { useState } from "react";
+import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { writeSyncIntervalPreference, type ShortcutSettings, type SyncIntervalPreference } from "@/lib/app-helpers";
import { Button } from "@/components/ui/button";
@@ -15,7 +15,13 @@ import {
} from "@/i18n";
import { ShortcutSettingsItem } from "./ShortcutSettingsItem";
import { CustomEditorThemeDialog } from "./CustomEditorThemeDialog";
-import { EDITOR_THEME_NAMES, MERMAID_THEME_NAMES, useTheme } from "../ThemeProvider";
+import {
+ MERMAID_THEME_NAMES,
+ useTheme,
+ DEFAULT_CUSTOM_LIGHT_COLORS,
+ DEFAULT_CUSTOM_DARK_COLORS,
+ type CustomEditorTheme,
+} from "../ThemeProvider";
interface PreferenceCardProps {
imageCompressionEnabled: boolean;
@@ -35,9 +41,64 @@ export const PreferenceCard = ({
onShortcutSettingsChange,
}: PreferenceCardProps) => {
const { t } = useTranslation();
- const { editorTheme, mermaidTheme, customEditorTheme, setCustomEditorTheme, setEditorTheme, setMermaidTheme } = useTheme();
+ const {
+ editorTheme,
+ mermaidTheme,
+ customEditorThemes,
+ setCustomEditorThemes,
+ setEditorTheme,
+ setMermaidTheme,
+ } = useTheme();
const [customThemeDialogOpen, setCustomThemeDialogOpen] = useState(false);
+ const [editingTheme, setEditingTheme] = useState<CustomEditorTheme | null>(null);
const [activeLocalePreference, setActiveLocalePreference] = useState<AppLocalePreference>(() => getAppLocalePreference());
+ const [isMobile, setIsMobile] = useState(false);
+
+ useEffect(() => {
+ const mediaQuery = window.matchMedia("(max-width: 640px)");
+ setIsMobile(mediaQuery.matches);
+ const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches);
+ mediaQuery.addEventListener("change", handler);
+ return () => mediaQuery.removeEventListener("change", handler);
+ }, []);
+
+ const activeCustom = customEditorThemes.find((t) => t.id === editorTheme);
+ const isPreset = editorTheme === "default" || editorTheme === "minimal-emerald" || editorTheme === "outline-emerald";
+
+ const handleEditClick = () => {
+ if (activeCustom) {
+ setEditingTheme(activeCustom);
+ } else {
+ const newTheme: CustomEditorTheme = {
+ id: `custom-${Date.now()}`,
+ name: `New theme ${customEditorThemes.length + 1}`,
+ light: DEFAULT_CUSTOM_LIGHT_COLORS,
+ dark: DEFAULT_CUSTOM_DARK_COLORS,
+ };
+ setEditingTheme(newTheme);
+ }
+ setCustomThemeDialogOpen(true);
+ };
+
+ const handleSaveTheme = (saved: CustomEditorTheme) => {
+ const exists = customEditorThemes.some((t) => t.id === saved.id);
+ let nextThemes: CustomEditorTheme[];
+ if (exists) {
+ nextThemes = customEditorThemes.map((t) => (t.id === saved.id ? saved : t));
+ } else {
+ nextThemes = [...customEditorThemes, saved];
+ }
+ setCustomEditorThemes(nextThemes);
+ setEditorTheme(saved.id);
+ };
+
+ const handleDeleteTheme = (idToDelete: string) => {
+ const nextThemes = customEditorThemes.filter((t) => t.id !== idToDelete);
+ setCustomEditorThemes(nextThemes);
+ if (editorTheme === idToDelete) {
+ setEditorTheme("default");
+ }
+ };
const handleLocalePreferenceChange = (preference: AppLocalePreference) => {
setActiveLocalePreference(preference);
@@ -93,21 +154,51 @@ export const PreferenceCard = ({
</div>
</div>
<div className="flex w-full shrink-0 flex-col gap-2 sm:w-80 sm:flex-row">
- <Select value={editorTheme} onValueChange={(value) => setEditorTheme(value as typeof editorTheme)}>
+ <Select
+ value={isMobile && !isPreset ? "default" : editorTheme}
+ onValueChange={(value) => {
+ if (value === "create-new") {
+ const newTheme: CustomEditorTheme = {
+ id: `custom-${Date.now()}`,
+ name: `New theme ${customEditorThemes.length + 1}`,
+ light: DEFAULT_CUSTOM_LIGHT_COLORS,
+ dark: DEFAULT_CUSTOM_DARK_COLORS,
+ };
+ setEditingTheme(newTheme);
+ setCustomThemeDialogOpen(true);
+ } else {
+ setEditorTheme(value);
+ }
+ }}
+ >
<SelectTrigger aria-label={t("settings.editorThemeTitle")} className="h-9 w-full min-w-0 flex-1 bg-white">
<SelectValue />
</SelectTrigger>
<SelectContent>
- {EDITOR_THEME_NAMES.map((theme) => (
- <SelectItem key={theme} value={theme}>
- {theme === "custom" ? customEditorTheme.name : t(`settings.editorThemes.${theme}`)}
- </SelectItem>
- ))}
+ <SelectItem value="default">{t("settings.editorThemes.default")}</SelectItem>
+ <SelectItem value="minimal-emerald">{t("settings.editorThemes.minimal-emerald")}</SelectItem>
+ <SelectItem value="outline-emerald">{t("settings.editorThemes.outline-emerald")}</SelectItem>
+ {!isMobile && (
+ <>
+ {customEditorThemes.length > 0 && <div className="my-1 border-t border-slate-100" />}
+ {customEditorThemes.map((theme) => (
+ <SelectItem key={theme.id} value={theme.id}>
+ {theme.name}
+ </SelectItem>
+ ))}
+ <div className="my-1 border-t border-slate-100" />
+ <SelectItem value="create-new" className="text-emerald-700 font-medium">
+ + {t("settings.customEditorTheme.create", "Create New Theme...")}
+ </SelectItem>
+ </>
+ )}
</SelectContent>
</Select>
- <Button variant="outline" className="h-9 shrink-0 px-3 text-sm" onClick={() => setCustomThemeDialogOpen(true)}>
- {t("settings.customEditorTheme.edit")}
- </Button>
+ {!isMobile && (
+ <Button variant="outline" className="h-9 shrink-0 px-3 text-sm" onClick={handleEditClick}>
+ {activeCustom ? t("settings.customEditorTheme.edit") : t("settings.customEditorTheme.customize", "Customize")}
+ </Button>
+ )}
</div>
</div>
@@ -193,12 +284,16 @@ export const PreferenceCard = ({
/>
</div>
</CardContent>
- <CustomEditorThemeDialog
- open={customThemeDialogOpen}
- theme={customEditorTheme}
- onOpenChange={setCustomThemeDialogOpen}
- onSave={(theme) => { setCustomEditorTheme(theme); setEditorTheme("custom"); }}
- />
+ {!isMobile && editingTheme && (
+ <CustomEditorThemeDialog
+ open={customThemeDialogOpen}
+ theme={editingTheme}
+ onOpenChange={setCustomThemeDialogOpen}
+ onSave={handleSaveTheme}
+ onDelete={handleDeleteTheme}
+ isDefaultTheme={editingTheme.id === "custom-default"}
+ />
+ )}
</Card>
);
};
diff --git a/apps/web/src/lib/css-sandbox.ts b/apps/web/src/lib/css-sandbox.ts
new file mode 100644
index 00000000..036e2cf9
--- /dev/null
+++ b/apps/web/src/lib/css-sandbox.ts
@@ -0,0 +1,154 @@
+/**
+ * 安全的 CSS 过滤器与作用域限制器
+ */
+
+const ALLOWED_CSS_PROPERTIES = new Set([
+ "font-family",
+ "font-size",
+ "font-style",
+ "font-weight",
+ "line-height",
+ "letter-spacing",
+ "color",
+ "background",
+ "background-color",
+ "border",
+ "border-top",
+ "border-right",
+ "border-bottom",
+ "border-left",
+ "border-color",
+ "border-width",
+ "border-style",
+ "border-radius",
+ "padding",
+ "padding-top",
+ "padding-right",
+ "padding-bottom",
+ "padding-left",
+ "margin",
+ "margin-top",
+ "margin-right",
+ "margin-bottom",
+ "margin-left",
+ "text-align",
+ "text-decoration",
+ "text-transform",
+ "text-indent",
+ "word-break",
+ "word-wrap",
+ "white-space",
+ "list-style",
+ "list-style-type",
+]);
+
+/**
+ * 过滤单行 CSS 规则,仅保留安全的排版属性,阻断 url() 和定位等危险内容
+ */
+const sanitizeRulesBlock = (block: string): string => {
+ return block
+ .split(";")
+ .map((rule) => {
+ const parts = rule.split(":");
+ if (parts.length < 2) return "";
+ const property = parts[0].trim().toLowerCase();
+ const value = parts.slice(1).join(":").trim();
+
+ // 仅允许白名单属性
+ if (!ALLOWED_CSS_PROPERTIES.has(property)) {
+ return "";
+ }
+
+ // 深度拦截潜在危险值 (如 url, expression, javascript)
+ if (
+ /url\s*\(/i.test(value) ||
+ /expression/i.test(value) ||
+ /javascript\s*:/i.test(value) ||
+ /behavior/i.test(value) ||
+ /-moz-binding/i.test(value)
+ ) {
+ return "";
+ }
+
+ return `${property}: ${value};`;
+ })
+ .filter(Boolean)
+ .join(" ");
+};
+
+/**
+ * 对用户的 CSS 进行安全过滤,并将其作用域限定在当前编辑器的 ProseMirror 区域
+ */
+export const sanitizeAndScopeCss = (css: string): string => {
+ if (!css) return "";
+
+ // 1. 过滤全局危险指令
+ let cleaned = css
+ .replace(/@import/gi, "")
+ .replace(/@charset/gi, "")
+ .replace(/@namespace/gi, "");
+
+ // 2. 匹配选择器与大括号块
+ const scopePrefix = ".edgeever-editor .ProseMirror ";
+
+ // 匹配形如 selector { rules } 的结构
+ cleaned = cleaned.replace(/([^{]+)({[^}]+})/g, (_, selectors, blockContent) => {
+ // 提取大括号内部的规则块并过滤
+ const rawRules = blockContent.slice(1, -1);
+ const safeRules = sanitizeRulesBlock(rawRules);
+ if (!safeRules) return "";
+
+ // 给选择器加前缀,限制其影响范围
+ const scopedSelectors = selectors
+ .split(",")
+ .map((s: string) => {
+ const trimmed = s.trim();
+ if (!trimmed) return "";
+ // 若选择器已经有了前缀或特定类,不要重复加
+ if (trimmed.startsWith(".ProseMirror") || trimmed.includes(".edgeever-editor")) {
+ return trimmed;
+ }
+ return `${scopePrefix}${trimmed}`;
+ })
+ .filter(Boolean)
+ .join(", ");
+
+ return scopedSelectors ? `${scopedSelectors} { ${safeRules} }` : "";
+ });
+
+ return cleaned;
+};
+
+/**
+ * 动态解析用户的自定义 CSS,并提取出能直接应用于微信/富文本一键复制时的标签样式字典
+ */
+export const parseCustomCssToStyles = (css: string): Record<string, string> => {
+ const stylesMap: Record<string, string> = {};
+ if (!css) return stylesMap;
+
+ // 使用简单的正则匹配选择器和规则内容
+ const regex = /([^{]+){([^}]+)}/g;
+ let match;
+
+ while ((match = regex.exec(css)) !== null) {
+ const selectors = match[1].split(",");
+ const rawRules = match[2];
+ const safeRules = sanitizeRulesBlock(rawRules);
+
+ if (!safeRules) continue;
+
+ selectors.forEach((sel) => {
+ const key = sel.trim().toLowerCase();
+ // 只提取针对纯标签的简单选择器(如 h1, p, blockquote 等),这样便于直接在微信复制里进行标签内联样式动态覆盖
+ if (/^[a-z0-9]+$/i.test(key)) {
+ if (stylesMap[key]) {
+ stylesMap[key] = `${stylesMap[key]} ${safeRules}`;
+ } else {
+ stylesMap[key] = safeRules;
+ }
+ }
+ });
+ }
+
+ return stylesMap;
+};
diff --git a/apps/web/src/lib/wechat-copy.ts b/apps/web/src/lib/wechat-copy.ts
index c6d5ca28..4e0c34ab 100644
--- a/apps/web/src/lib/wechat-copy.ts
+++ b/apps/web/src/lib/wechat-copy.ts
@@ -1,5 +1,6 @@
import type { Editor } from "@tiptap/react";
import { marked } from "marked";
+import { parseCustomCssToStyles } from "@/lib/css-sandbox";
const WECHAT_STYLES: Record<string, string> = {
p: "margin: 0 0 1em; line-height: 1.75; font-size: 16px; color: #333;",
@@ -49,12 +50,55 @@ const THEME_BLOCK_STYLES: Record<string, { block: string; label: string }> = {
},
};
-const applyInlineStyles = (root: HTMLElement, editorTheme?: string) => {
- root.style.cssText = "font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 16px; line-height: 1.75; color: #333; word-break: break-word;";
+const applyInlineStyles = (
+ root: HTMLElement,
+ editorTheme?: string,
+ customColors?: { bg: string; text: string; accent: string; soft: string; border: string } | null,
+ customCss?: string
+) => {
+ const textColor = customColors ? customColors.text : "#333";
+ const bgColors = customColors ? customColors.bg : "#ffffff";
+ const accent = customColors ? customColors.accent : "#059669";
+ const soft = customColors ? customColors.soft : "#f0fdfa";
+ const border = customColors ? customColors.border : "#e5e7eb";
+
+ const customStyles = customCss ? parseCustomCssToStyles(customCss) : null;
+
+ root.style.cssText = `font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 16px; line-height: 1.75; color: ${textColor}; background-color: ${bgColors}; word-break: break-word;`;
+
root.querySelectorAll<HTMLElement>("*").forEach((element) => {
- const style = WECHAT_STYLES[element.tagName.toLowerCase()];
+ const tagName = element.tagName.toLowerCase();
+ let style = WECHAT_STYLES[tagName] || "";
+
+ if (customColors) {
+ if (tagName === "p") {
+ style = `margin: 0 0 1em; line-height: 1.75; font-size: 16px; color: ${textColor};`;
+ } else if (tagName === "h1" || tagName === "h2" || tagName === "h3") {
+ style = style.replace("color: #1f2937;", `color: ${textColor};`);
+ } else if (tagName === "blockquote") {
+ style = `margin: 1em 0; padding: 0.6em 1em; border-left: 4px solid ${accent}; background: ${soft}; color: ${textColor}; line-height: 1.75;`;
+ } else if (tagName === "a") {
+ style = `color: ${accent}; text-decoration: underline;`;
+ } else if (tagName === "code") {
+ style = `padding: 0.15em 0.35em; border-radius: 3px; background: ${soft}; color: ${textColor}; font-family: Menlo, Consolas, monospace; font-size: 0.9em;`;
+ } else if (tagName === "pre") {
+ style = `margin: 1em 0; padding: 12px 14px; overflow: hidden; border-radius: 6px; background: ${soft}; color: ${textColor}; line-height: 1.6; text-align: left;`;
+ } else if (tagName === "hr") {
+ style = `margin: 1.5em 0; border: 0; border-top: 1px solid ${border};`;
+ } else if (tagName === "th") {
+ style = `padding: 8px; border: 1px solid ${border}; background: ${soft}; font-weight: 700; text-align: left; color: ${textColor};`;
+ } else if (tagName === "td") {
+ style = `padding: 8px; border: 1px solid ${border}; text-align: left; color: ${textColor};`;
+ }
+ }
+
+ if (customStyles && customStyles[tagName]) {
+ style = `${style} ${customStyles[tagName]}`;
+ }
+
if (style) element.style.cssText = `${style}${element.style.cssText}`;
});
+
root.querySelectorAll<HTMLElement>("pre code").forEach((element) => {
element.style.cssText = "padding: 0; background: transparent; color: inherit; font-family: Menlo, Consolas, monospace; font-size: 13px; white-space: pre-wrap;";
});
@@ -62,12 +106,34 @@ const applyInlineStyles = (root: HTMLElement, editorTheme?: string) => {
root.querySelectorAll<HTMLElement>("[data-edgeever-theme-block]").forEach((block) => {
const kind = block.getAttribute("data-theme-block-kind") || "intro";
const themeStyles = THEME_BLOCK_STYLES[kind] || THEME_BLOCK_STYLES.intro;
- const accent = "#059669";
- block.style.cssText = `${themeStyles.block} border-left-color: ${accent}; ${block.style.cssText}`;
+
+ let blockStyle = themeStyles.block;
+ let labelStyle = themeStyles.label;
+
+ if (customColors) {
+ if (kind === "intro") {
+ blockStyle = `margin: 20px 0; padding: 0 0 4px; border-left: 5px solid ${accent}; background: ${soft}; color: ${textColor};`;
+ labelStyle = `padding: 10px 14px 0; color: ${accent}; font-size: 12px; font-weight: 700; letter-spacing: 1px;`;
+ } else if (kind === "key-point") {
+ blockStyle = `margin: 20px 0; padding: 0 0 4px; border: 1px solid ${border}; border-radius: 8px; background: ${soft}; color: ${textColor};`;
+ labelStyle = `padding: 10px 14px 0; color: ${accent}; font-size: 12px; font-weight: 700; letter-spacing: 1px;`;
+ } else if (kind === "callout") {
+ blockStyle = `margin: 20px 0; padding: 0 0 4px; border: 1px dashed ${border}; background: ${soft}; color: ${textColor};`;
+ labelStyle = `padding: 10px 14px 0; color: ${accent}; font-size: 12px; font-weight: 700; letter-spacing: 1px;`;
+ } else if (kind === "chapter") {
+ blockStyle = `margin: 28px 0 16px; padding: 0 0 4px; border-top: 3px solid ${accent}; color: ${textColor};`;
+ labelStyle = `padding: 10px 0 0; color: ${accent}; font-size: 12px; font-weight: 700; letter-spacing: 2px;`;
+ }
+ } else {
+ blockStyle = `${blockStyle} border-left-color: ${accent};`;
+ labelStyle = `${labelStyle} color: ${accent};`;
+ }
+
+ block.style.cssText = `${blockStyle}${block.style.cssText}`;
const label = document.createElement("p");
label.textContent = THEME_BLOCK_LABELS[kind] || "主题组件";
- label.style.cssText = `${themeStyles.label} color: ${accent}; margin: 0;`;
+ label.style.cssText = `${labelStyle} margin: 0;`;
block.insertBefore(label, block.firstChild);
});
};
@@ -276,8 +342,25 @@ const embedImagesForWeChat = async (root: HTMLElement, originalImages: HTMLImage
export const buildWeChatClipboardHtml = async (editor: Editor) => {
const container = document.createElement("div");
container.innerHTML = editor.getHTML();
- const editorTheme = editor.view.dom.closest<HTMLElement>("[data-editor-theme]")?.dataset.editorTheme;
- applyInlineStyles(container, editorTheme);
+
+ const closestContainer = editor.view.dom.closest<HTMLElement>("[data-editor-theme]");
+ const editorTheme = closestContainer?.dataset.editorTheme;
+
+ let customColors: { bg: string; text: string; accent: string; soft: string; border: string } | null = null;
+ if (closestContainer && editorTheme === "custom") {
+ customColors = {
+ bg: closestContainer.style.getPropertyValue("--editor-theme-bg") || "#ffffff",
+ text: closestContainer.style.getPropertyValue("--editor-theme-text") || "#1f2937",
+ accent: closestContainer.style.getPropertyValue("--editor-theme-accent") || "#059669",
+ soft: closestContainer.style.getPropertyValue("--editor-theme-soft") || "#ecfdf5",
+ border: closestContainer.style.getPropertyValue("--editor-theme-border") || "#a7f3d0",
+ };
+ }
+
+ const customStyleTag = closestContainer?.querySelector<HTMLStyleElement>("style[data-theme-custom-css]");
+ const customCss = customStyleTag?.dataset.originalCss || "";
+
+ applyInlineStyles(container, editorTheme, customColors, customCss);
await embedMermaidForWeChat(container, editor);
const originalImages = Array.from(editor.view.dom.querySelectorAll<HTMLImageElement>("img"));
await embedImagesForWeChat(container, originalImages);
@@ -315,7 +398,25 @@ export const copyEditorToWeChat = async (editor: Editor) =>
export const copyMarkdownToWeChat = async (markdown: string) => {
const container = document.createElement("div");
container.innerHTML = marked.parse(markdown, { async: false, gfm: true, breaks: false });
- applyInlineStyles(container);
+
+ const closestContainer = document.querySelector<HTMLElement>("[data-editor-theme]");
+ const editorTheme = closestContainer?.dataset.editorTheme;
+
+ let customColors: { bg: string; text: string; accent: string; soft: string; border: string } | null = null;
+ if (closestContainer && editorTheme === "custom") {
+ customColors = {
+ bg: closestContainer.style.getPropertyValue("--editor-theme-bg") || "#ffffff",
+ text: closestContainer.style.getPropertyValue("--editor-theme-text") || "#1f2937",
+ accent: closestContainer.style.getPropertyValue("--editor-theme-accent") || "#059669",
+ soft: closestContainer.style.getPropertyValue("--editor-theme-soft") || "#ecfdf5",
+ border: closestContainer.style.getPropertyValue("--editor-theme-border") || "#a7f3d0",
+ };
+ }
+
+ const customStyleTag = closestContainer?.querySelector<HTMLStyleElement>("style[data-theme-custom-css]");
+ const customCss = customStyleTag?.dataset.originalCss || "";
+
+ applyInlineStyles(container, editorTheme, customColors, customCss);
await embedMermaidForWeChat(container);
await embedImagesForWeChat(container);
await copyHtmlToClipboard(container.outerHTML, container.textContent ?? "");