The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { |
| 3 | MousePointer2Icon, |
| 4 | PaintbrushIcon, |
| 5 | PlusIcon, |
| 6 | XIcon, |
| 7 | ChevronDownIcon, |
| 8 | ChevronRightIcon, |
| 9 | ChevronUpIcon, |
| 10 | } from "lucide-react"; |
| 11 | import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react"; |
| 12 | import { |
| 13 | applyThemeColorPreview, |
| 14 | THEME_COLOR_ROLES, |
| 15 | THEME_FILE_VERSION, |
| 16 | createVividThemeColors, |
| 17 | getCustomThemes, |
| 18 | getStandardThemeColors, |
| 19 | getThemeColorsForMode, |
| 20 | getThemeModes, |
| 21 | installCustomTheme, |
| 22 | isThemeColor, |
| 23 | parseThemeFile, |
| 24 | removeCustomTheme, |
| 25 | themeIdFromName, |
| 26 | updateThemeColorFamily, |
| 27 | updateCustomTheme, |
| 28 | type ThemeAppearance, |
| 29 | type ThemeColors, |
| 30 | type ThemeColorRole, |
| 31 | type ThemeDefinition, |
| 32 | } from "../../themePalette"; |
| 33 | import { useViewportSize } from "../../hooks/useViewportSize"; |
| 34 | import { cn } from "../../lib/utils"; |
| 35 | import { Button } from "../ui/button"; |
| 36 | import { Input } from "../ui/input"; |
| 37 | import { Switch } from "../ui/switch"; |
| 38 | import { Toggle, ToggleGroup } from "../ui/toggle-group"; |
| 39 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 40 | import { getThemeRoleLabel, ThemeColorField } from "./ThemeColorPicker"; |
| 41 | import { ThemeCssEditor } from "./ThemeCssEditor"; |
| 42 | import { |
| 43 | clearThemeInspectorHover, |
| 44 | clearThemeInspectorHighlights, |
| 45 | highlightThemeRoleUsage, |
| 46 | inspectThemeRoleAtElement, |
| 47 | inspectThemeRoleFromUtilitiesAtElement, |
| 48 | refreshThemeInspectorSpotlight, |
| 49 | showThemeInspectorHover, |
| 50 | type ThemeElementInspection, |
| 51 | } from "./themeInspector"; |
| 52 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 53 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 54 | |
| 55 | const THEME_EDITOR_SIMPLE_ROLES: ReadonlyArray<ThemeColorRole> = ["canvas", "accent"]; |
| 56 | |
| 57 | type ThemeEditorColorFamily = Readonly<{ |
| 58 | id: string; |
| 59 | label: string; |
| 60 | role: ThemeColorRole; |
| 61 | roles: ReadonlyArray<ThemeColorRole>; |
| 62 | }>; |
| 63 | |
| 64 | const THEME_EDITOR_ROLE_GROUPS: ReadonlyArray<{ |
| 65 | id: string; |
| 66 | title: string; |
| 67 | families: ReadonlyArray<ThemeEditorColorFamily>; |
| 68 | }> = [ |
| 69 | { |
| 70 | id: "foundation", |
| 71 | title: msg("Foundation"), |
| 72 | families: [ |
| 73 | { |
| 74 | id: "background", |
| 75 | label: msg("Background"), |
| 76 | role: "canvas", |
| 77 | roles: ["canvas", "chrome", "toolbar"], |
| 78 | }, |
| 79 | { id: "surface", label: msg("Surface"), role: "surface", roles: ["surface"] }, |
| 80 | { |
| 81 | id: "raised-surface", |
| 82 | label: msg("Raised surface"), |
| 83 | role: "surfaceRaised", |
| 84 | roles: ["surfaceRaised"], |
| 85 | }, |
| 86 | { |
| 87 | id: "overlay", |
| 88 | label: msg("Overlay"), |
| 89 | role: "surfaceOverlay", |
| 90 | roles: ["surfaceOverlay"], |
| 91 | }, |
| 92 | { |
| 93 | id: "text", |
| 94 | label: msg("Text"), |
| 95 | role: "text", |
| 96 | roles: ["text", "toolbarForeground", "toolbarControlForeground"], |
| 97 | }, |
| 98 | { |
| 99 | id: "muted-text", |
| 100 | label: msg("Muted text"), |
| 101 | role: "mutedForeground", |
| 102 | roles: [ |
| 103 | "textMuted", |
| 104 | "mutedForeground", |
| 105 | "placeholder", |
| 106 | "secondaryLabel", |
| 107 | "iconMuted", |
| 108 | "sidebarMutedForeground", |
| 109 | ], |
| 110 | }, |
| 111 | { |
| 112 | id: "border", |
| 113 | label: msg("Border"), |
| 114 | role: "border", |
| 115 | roles: ["border", "toolbarBorder", "sidebarBorder"], |
| 116 | }, |
| 117 | { id: "input", label: msg("Input"), role: "input", roles: ["input"] }, |
| 118 | ], |
| 119 | }, |
| 120 | { |
| 121 | id: "brand-content", |
| 122 | title: msg("Brand & content"), |
| 123 | families: [ |
| 124 | { |
| 125 | id: "subtle-surface", |
| 126 | label: msg("Subtle surface"), |
| 127 | role: "secondary", |
| 128 | roles: ["secondary", "secondaryForeground", "muted", "toolbarControl"], |
| 129 | }, |
| 130 | { |
| 131 | id: "highlight-surface", |
| 132 | label: msg("Highlight surface"), |
| 133 | role: "accentSurface", |
| 134 | roles: ["accentSurface", "accentSurfaceForeground", "toolbarControlHover"], |
| 135 | }, |
| 136 | { |
| 137 | id: "accent", |
| 138 | label: msg("Accent"), |
| 139 | role: "accent", |
| 140 | roles: [ |
| 141 | "accent", |
| 142 | "accentForeground", |
| 143 | "focus", |
| 144 | "update", |
| 145 | "updateForeground", |
| 146 | "updateSurface", |
| 147 | "terminalCursor", |
| 148 | ], |
| 149 | }, |
| 150 | { |
| 151 | id: "action", |
| 152 | label: msg("Action"), |
| 153 | role: "messageAction", |
| 154 | roles: ["messageAction", "messageActionForeground", "messageActionHover"], |
| 155 | }, |
| 156 | { |
| 157 | id: "message-surface", |
| 158 | label: msg("Message surface"), |
| 159 | role: "messageSurface", |
| 160 | roles: ["messageSurface", "messageForeground"], |
| 161 | }, |
| 162 | { |
| 163 | id: "code-surface", |
| 164 | label: msg("Code surface"), |
| 165 | role: "codeBackground", |
| 166 | roles: ["codeBackground", "codeForeground"], |
| 167 | }, |
| 168 | ], |
| 169 | }, |
| 170 | { |
| 171 | id: "search", |
| 172 | title: msg("Search"), |
| 173 | families: [ |
| 174 | { |
| 175 | id: "search-matches", |
| 176 | label: msg("Search matches"), |
| 177 | role: "searchMatchBackground", |
| 178 | roles: ["searchMatchBackground", "searchMatchForeground"], |
| 179 | }, |
| 180 | { |
| 181 | id: "current-match", |
| 182 | label: msg("Current match"), |
| 183 | role: "searchMatchActiveBackground", |
| 184 | roles: ["searchMatchActiveBackground", "searchMatchActiveForeground"], |
| 185 | }, |
| 186 | ], |
| 187 | }, |
| 188 | { |
| 189 | id: "context", |
| 190 | title: msg("Context"), |
| 191 | families: [ |
| 192 | { |
| 193 | id: "sidebar-background", |
| 194 | label: msg("Sidebar background"), |
| 195 | role: "sidebar", |
| 196 | roles: ["sidebar", "sidebarForeground"], |
| 197 | }, |
| 198 | { |
| 199 | id: "sidebar-controls", |
| 200 | label: msg("Sidebar controls"), |
| 201 | role: "sidebarControlSurface", |
| 202 | roles: ["sidebarControlSurface"], |
| 203 | }, |
| 204 | { |
| 205 | id: "sidebar-selection", |
| 206 | label: msg("Sidebar selection"), |
| 207 | role: "sidebarRowSelected", |
| 208 | roles: ["sidebarRowHover", "sidebarRowActive", "sidebarRowSelected"], |
| 209 | }, |
| 210 | { |
| 211 | id: "terminal-background", |
| 212 | label: msg("Terminal background"), |
| 213 | role: "terminalBackground", |
| 214 | roles: [ |
| 215 | "terminalBackground", |
| 216 | "terminalForeground", |
| 217 | "terminalSelection", |
| 218 | "terminalScrollbar", |
| 219 | "terminalScrollbarHover", |
| 220 | ], |
| 221 | }, |
| 222 | ], |
| 223 | }, |
| 224 | { |
| 225 | id: "status", |
| 226 | title: msg("Status"), |
| 227 | families: [ |
| 228 | { |
| 229 | id: "error", |
| 230 | label: msg("Error"), |
| 231 | role: "error", |
| 232 | roles: ["error", "errorForeground", "errorSurface"], |
| 233 | }, |
| 234 | { |
| 235 | id: "warning", |
| 236 | label: msg("Warning"), |
| 237 | role: "warning", |
| 238 | roles: ["warning", "warningForeground", "warningSurface"], |
| 239 | }, |
| 240 | ], |
| 241 | }, |
| 242 | ]; |
| 243 | |
| 244 | const THEME_EDITOR_COLOR_FAMILIES = THEME_EDITOR_ROLE_GROUPS.flatMap((group) => group.families); |
| 245 | const THEME_EDITOR_COLOR_FAMILY_BY_ROLE = new Map( |
| 246 | THEME_EDITOR_COLOR_FAMILIES.flatMap((family) => |
| 247 | family.roles.map((role) => [role, family] as const), |
| 248 | ), |
| 249 | ); |
| 250 | |
| 251 | function getThemeEditorColorFamily(role: ThemeColorRole): ThemeEditorColorFamily | null { |
| 252 | return THEME_EDITOR_COLOR_FAMILY_BY_ROLE.get(role) ?? null; |
| 253 | } |
| 254 | |
| 255 | function themeEditorRoleLabel(role: ThemeColorRole, resolve: MessageResolver = m): string { |
| 256 | const family = getThemeEditorColorFamily(role); |
| 257 | return family ? resolve(family.label) : getThemeRoleLabel(role, resolve); |
| 258 | } |
| 259 | |
| 260 | type ThemeEditorColors = ThemeColors; |
| 261 | type ThemeEditorColorsByAppearance = Record<ThemeAppearance, ThemeEditorColors>; |
| 262 | |
| 263 | function getThemeEditorDefaults(appearance: ThemeAppearance): ThemeEditorColors { |
| 264 | return { ...getStandardThemeColors(appearance) }; |
| 265 | } |
| 266 | |
| 267 | function getThemeEditorColorsByAppearance(): ThemeEditorColorsByAppearance { |
| 268 | return { |
| 269 | light: getThemeEditorDefaults("light"), |
| 270 | dark: getThemeEditorDefaults("dark"), |
| 271 | }; |
| 272 | } |
| 273 | |
| 274 | function isThemeEditorColor(value: string): boolean { |
| 275 | return isThemeColor(value.trim()); |
| 276 | } |
| 277 | |
| 278 | function getManagedEditorColors( |
| 279 | appearance: ThemeAppearance, |
| 280 | colors: ThemeEditorColors, |
| 281 | ): ThemeEditorColors { |
| 282 | const defaults = getStandardThemeColors(appearance); |
| 283 | return createVividThemeColors( |
| 284 | appearance, |
| 285 | isThemeEditorColor(colors.canvas) ? colors.canvas : defaults.canvas, |
| 286 | isThemeEditorColor(colors.accent) ? colors.accent : defaults.accent, |
| 287 | ); |
| 288 | } |
| 289 | |
| 290 | const PANEL_MARGIN = 8; |
| 291 | const PANEL_MIN_WIDTH = 280; |
| 292 | const PANEL_MIN_HEIGHT = 220; |
| 293 | |
| 294 | /** Keeps the panel horizontally inside the viewport. Vertically only its header must stay |
| 295 | * visible, so users can park the panel low to see the app behind it. */ |
| 296 | function clampPanelPosition( |
| 297 | viewport: { readonly width: number; readonly height: number }, |
| 298 | x: number, |
| 299 | y: number, |
| 300 | width: number, |
| 301 | ) { |
| 302 | const maxX = Math.max(PANEL_MARGIN, viewport.width - width - PANEL_MARGIN); |
| 303 | const maxY = Math.max(PANEL_MARGIN, viewport.height - 48); |
| 304 | return { |
| 305 | x: Math.min(Math.max(x, PANEL_MARGIN), maxX), |
| 306 | y: Math.min(Math.max(y, PANEL_MARGIN), maxY), |
| 307 | }; |
| 308 | } |
| 309 | |
| 310 | const readWindowViewport = () => ({ width: window.innerWidth, height: window.innerHeight }); |
| 311 | |
| 312 | // Kept out of the component: the compiler cannot lower a throw inside try/catch. |
| 313 | function retireMergedTheme(retired: ThemeDefinition, mergeTarget: ThemeDefinition) { |
| 314 | try { |
| 315 | removeCustomTheme(retired.id); |
| 316 | } catch (cause) { |
| 317 | // Restore the pre-merge target on retirement failure; leaving the persisted merge would collide on retry. |
| 318 | try { |
| 319 | updateCustomTheme(mergeTarget); |
| 320 | } catch {} |
| 321 | throw cause; |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | export function ThemeEditorPanel({ |
| 326 | open, |
| 327 | onOpenChange, |
| 328 | onSaved, |
| 329 | editingTheme, |
| 330 | initialAppearance, |
| 331 | seedTheme, |
| 332 | seedName, |
| 333 | restoreTheme, |
| 334 | }: { |
| 335 | open: boolean; |
| 336 | onOpenChange: (open: boolean) => void; |
| 337 | onSaved: ( |
| 338 | theme: ThemeDefinition, |
| 339 | context: { |
| 340 | created: boolean; |
| 341 | mergedAppearance?: ThemeAppearance; |
| 342 | }, |
| 343 | ) => boolean; |
| 344 | editingTheme: ThemeDefinition | null; |
| 345 | initialAppearance: ThemeAppearance; |
| 346 | seedTheme?: ThemeDefinition | null; |
| 347 | seedName?: string | undefined; |
| 348 | restoreTheme: () => void; |
| 349 | }) { |
| 350 | const messages = useMessages(); |
| 351 | const gt = useGT(); |
| 352 | const isEditing = editingTheme !== null; |
| 353 | const [name, setName] = useState(""); |
| 354 | const [activeAppearance, setActiveAppearance] = useState<ThemeAppearance>(initialAppearance); |
| 355 | const [isAdvanced, setIsAdvanced] = useState(false); |
| 356 | const [colorsByAppearance, setColorsByAppearance] = useState<ThemeEditorColorsByAppearance>(() => |
| 357 | getThemeEditorColorsByAppearance(), |
| 358 | ); |
| 359 | const [simpleColorsDirtyByAppearance, setSimpleColorsDirtyByAppearance] = useState< |
| 360 | Record<ThemeAppearance, boolean> |
| 361 | >({ light: false, dark: false }); |
| 362 | const [shouldRegenerateGuidedColors, setShouldRegenerateGuidedColors] = useState(false); |
| 363 | const [css, setCss] = useState(""); |
| 364 | const [cssOpen, setCssOpen] = useState(false); |
| 365 | const [error, setError] = useState<string | null>(null); |
| 366 | const [isMinimized, setIsMinimized] = useState(false); |
| 367 | const [roleQuery, setRoleQuery] = useState(""); |
| 368 | const [isInspecting, setIsInspecting] = useState(false); |
| 369 | const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null); |
| 370 | const [usageCount, setUsageCount] = useState<number | null>(null); |
| 371 | // The rendered width is CSS-sized unless the user resized the panel, so the position |
| 372 | // remembers the width measured at the last drag or resize. |
| 373 | const [position, setPosition] = useState<{ x: number; y: number; width: number } | null>(null); |
| 374 | const [size, setSize] = useState<{ width: number; height: number } | null>(null); |
| 375 | const panelRef = useRef<HTMLDivElement>(null); |
| 376 | const colorEditSnapshotRef = useRef<{ |
| 377 | colorsByAppearance: ThemeEditorColorsByAppearance; |
| 378 | simpleColorsDirtyByAppearance: Record<ThemeAppearance, boolean>; |
| 379 | shouldRegenerateGuidedColors: boolean; |
| 380 | } | null>(null); |
| 381 | const dragOffsetRef = useRef<{ dx: number; dy: number; width: number } | null>(null); |
| 382 | const resizeStartRef = useRef<{ |
| 383 | pointerX: number; |
| 384 | pointerY: number; |
| 385 | left: number; |
| 386 | top: number; |
| 387 | width: number; |
| 388 | height: number; |
| 389 | } | null>(null); |
| 390 | // Seed during render so the first open frame cannot preview the previous session's colors. |
| 391 | const [seededOpen, setSeededOpen] = useState(false); |
| 392 | if (seededOpen !== open) { |
| 393 | setSeededOpen(open); |
| 394 | if (open) { |
| 395 | const sourceTheme = editingTheme ?? seedTheme ?? null; |
| 396 | const nextColors = getThemeEditorColorsByAppearance(); |
| 397 | const nextAppearance = sourceTheme |
| 398 | ? getThemeColorsForMode(sourceTheme, initialAppearance) |
| 399 | ? initialAppearance |
| 400 | : sourceTheme.appearance |
| 401 | : initialAppearance; |
| 402 | if (sourceTheme) { |
| 403 | nextColors[sourceTheme.appearance] = { ...sourceTheme.colors }; |
| 404 | for (const appearance of ["light", "dark"] as const) { |
| 405 | const variantColors = sourceTheme.variants?.[appearance]; |
| 406 | if (variantColors) nextColors[appearance] = { ...variantColors }; |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | setName(editingTheme?.label ?? seedName ?? ""); |
| 411 | setActiveAppearance(nextAppearance); |
| 412 | // Open unmanaged themes in advanced mode to preserve imported or hand-tuned colors. |
| 413 | setIsAdvanced(sourceTheme !== null && sourceTheme.managed !== true); |
| 414 | setSimpleColorsDirtyByAppearance({ light: false, dark: false }); |
| 415 | setShouldRegenerateGuidedColors(sourceTheme !== null && sourceTheme.managed !== true); |
| 416 | setColorsByAppearance(nextColors); |
| 417 | setCss(sourceTheme?.css ?? ""); |
| 418 | setCssOpen(Boolean(sourceTheme?.css)); |
| 419 | setSelectedRole(null); |
| 420 | setUsageCount(null); |
| 421 | setIsInspecting(false); |
| 422 | setError(null); |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | const nameTargetId = themeIdFromName(name); |
| 427 | const normalizedName = name.trim().toLowerCase(); |
| 428 | const mergeTarget = |
| 429 | normalizedName === "" |
| 430 | ? null |
| 431 | : (getCustomThemes().find( |
| 432 | (theme) => |
| 433 | theme.id !== editingTheme?.id && |
| 434 | (theme.id === nameTargetId || theme.label.trim().toLowerCase() === normalizedName), |
| 435 | ) ?? null); |
| 436 | const takenAppearances = mergeTarget ? getThemeModes(mergeTarget) : []; |
| 437 | // A merge keeps the target's CSS when this draft has none. |
| 438 | const cssForSave = css.trim() ? css : (mergeTarget?.css ?? ""); |
| 439 | const editableAppearances = editingTheme ? getThemeModes(editingTheme) : null; |
| 440 | |
| 441 | const appearanceLockReason = (appearance: ThemeAppearance): string | null => { |
| 442 | if (editableAppearances && !editableAppearances.includes(appearance)) { |
| 443 | return appearance === "light" |
| 444 | ? gt("“{label}” has no light palette. Create a theme with the same name to add one.", { |
| 445 | label: editingTheme?.label, |
| 446 | }) |
| 447 | : gt("“{label}” has no dark palette. Create a theme with the same name to add one.", { |
| 448 | label: editingTheme?.label, |
| 449 | }); |
| 450 | } |
| 451 | if (!isEditing && takenAppearances.includes(appearance)) { |
| 452 | return appearance === "light" |
| 453 | ? gt("“{label}” already has a light palette.", { label: mergeTarget?.label }) |
| 454 | : gt("“{label}” already has a dark palette.", { label: mergeTarget?.label }); |
| 455 | } |
| 456 | return null; |
| 457 | }; |
| 458 | |
| 459 | const mergeKey = |
| 460 | isEditing || mergeTarget === null ? null : `${mergeTarget.id}:${takenAppearances.join(",")}`; |
| 461 | const [appliedMergeKey, setAppliedMergeKey] = useState<string | null>(null); |
| 462 | if (appliedMergeKey !== mergeKey) { |
| 463 | setAppliedMergeKey(mergeKey); |
| 464 | if ( |
| 465 | mergeKey !== null && |
| 466 | takenAppearances.length === 1 && |
| 467 | takenAppearances.includes(activeAppearance) |
| 468 | ) { |
| 469 | setActiveAppearance(takenAppearances[0] === "light" ? "dark" : "light"); |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the edited colors to the document as a live theme preview while the editor is open |
| 474 | useEffect(() => { |
| 475 | if (!open) return; |
| 476 | applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance, cssForSave); |
| 477 | }, [activeAppearance, colorsByAppearance, cssForSave, open]); |
| 478 | |
| 479 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores the document theme when the editor closes or unmounts |
| 480 | useEffect(() => { |
| 481 | if (!open) return; |
| 482 | return () => { |
| 483 | restoreTheme(); |
| 484 | }; |
| 485 | }, [open, restoreTheme]); |
| 486 | |
| 487 | const updateColor = (role: ThemeColorRole, value: string) => { |
| 488 | setColorsByAppearance((current) => { |
| 489 | const nextColors = { ...current[activeAppearance], [role]: value }; |
| 490 | const shouldManageColors = |
| 491 | !isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value); |
| 492 | |
| 493 | return { |
| 494 | ...current, |
| 495 | [activeAppearance]: isAdvanced |
| 496 | ? updateThemeColorFamily(activeAppearance, current[activeAppearance], role, value) |
| 497 | : shouldManageColors |
| 498 | ? getManagedEditorColors(activeAppearance, nextColors) |
| 499 | : nextColors, |
| 500 | }; |
| 501 | }); |
| 502 | if (!isAdvanced && THEME_EDITOR_SIMPLE_ROLES.includes(role) && isThemeEditorColor(value)) { |
| 503 | setSimpleColorsDirtyByAppearance((current) => ({ |
| 504 | ...current, |
| 505 | [activeAppearance]: true, |
| 506 | })); |
| 507 | } |
| 508 | if (isAdvanced) setShouldRegenerateGuidedColors(true); |
| 509 | }; |
| 510 | |
| 511 | // A color edit also rewrites derived roles, so cancelling restores the whole snapshot rather than |
| 512 | // replaying the previous value through updateColor. |
| 513 | const startColorEdit = () => { |
| 514 | colorEditSnapshotRef.current = { |
| 515 | colorsByAppearance, |
| 516 | simpleColorsDirtyByAppearance, |
| 517 | shouldRegenerateGuidedColors, |
| 518 | }; |
| 519 | }; |
| 520 | |
| 521 | const cancelColorEdit = () => { |
| 522 | const snapshot = colorEditSnapshotRef.current; |
| 523 | colorEditSnapshotRef.current = null; |
| 524 | if (!snapshot) return; |
| 525 | setColorsByAppearance(snapshot.colorsByAppearance); |
| 526 | setSimpleColorsDirtyByAppearance(snapshot.simpleColorsDirtyByAppearance); |
| 527 | setShouldRegenerateGuidedColors(snapshot.shouldRegenerateGuidedColors); |
| 528 | }; |
| 529 | |
| 530 | const selectThemeRole = (role: ThemeColorRole, reveal = false) => { |
| 531 | const visibleRole = getThemeEditorColorFamily(role)?.role ?? role; |
| 532 | setSelectedRole(visibleRole); |
| 533 | if (!THEME_EDITOR_SIMPLE_ROLES.includes(visibleRole)) { |
| 534 | setIsAdvanced(true); |
| 535 | setRoleQuery(""); |
| 536 | } |
| 537 | if (!reveal) return; |
| 538 | |
| 539 | requestAnimationFrame(() => { |
| 540 | panelRef.current?.querySelector(`[data-theme-color-role="${visibleRole}"]`)?.scrollIntoView({ |
| 541 | behavior: window.matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth", |
| 542 | block: "nearest", |
| 543 | }); |
| 544 | }); |
| 545 | }; |
| 546 | |
| 547 | const toggleThemeRole = (role: ThemeColorRole) => { |
| 548 | setSelectedRole((current) => (current === role ? null : role)); |
| 549 | }; |
| 550 | |
| 551 | const clearInspectorSelection = () => { |
| 552 | setSelectedRole(null); |
| 553 | setUsageCount(null); |
| 554 | setIsInspecting(false); |
| 555 | }; |
| 556 | |
| 557 | const selectedHighlightRoles = selectedRole |
| 558 | ? isAdvanced |
| 559 | ? (getThemeEditorColorFamily(selectedRole)?.roles ?? [selectedRole]) |
| 560 | : THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole) |
| 561 | ? THEME_COLOR_ROLES.filter( |
| 562 | (role) => |
| 563 | colorsByAppearance[activeAppearance][role].trim().toLowerCase() === |
| 564 | colorsByAppearance[activeAppearance][selectedRole].trim().toLowerCase(), |
| 565 | ) |
| 566 | : [selectedRole] |
| 567 | : []; |
| 568 | const selectedHighlightRolesKey = selectedHighlightRoles.join(","); |
| 569 | |
| 570 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- highlights role usage in the DOM, refreshed by a MutationObserver and resize and scroll listeners |
| 571 | useEffect(() => { |
| 572 | clearThemeInspectorHighlights(); |
| 573 | if (!open || selectedRole === null || isInspecting) return; |
| 574 | |
| 575 | const highlightedRoles = selectedHighlightRolesKey.split(",") as Array<ThemeColorRole>; |
| 576 | const refreshHighlights = () => setUsageCount(highlightThemeRoleUsage(highlightedRoles)); |
| 577 | refreshHighlights(); |
| 578 | // Each refresh snapshots the whole tree twice; throttle streaming and virtualization mutations. |
| 579 | const MIN_REFRESH_INTERVAL_MS = 500; |
| 580 | let refreshFrame: number | null = null; |
| 581 | let refreshTimer: ReturnType<typeof setTimeout> | null = null; |
| 582 | let lastRefreshAt = performance.now(); |
| 583 | const scheduleRefresh = () => { |
| 584 | if (refreshFrame !== null || refreshTimer !== null) return; |
| 585 | const wait = Math.max(0, MIN_REFRESH_INTERVAL_MS - (performance.now() - lastRefreshAt)); |
| 586 | const run = () => { |
| 587 | refreshFrame = null; |
| 588 | refreshTimer = null; |
| 589 | lastRefreshAt = performance.now(); |
| 590 | refreshHighlights(); |
| 591 | }; |
| 592 | if (wait === 0) refreshFrame = requestAnimationFrame(run); |
| 593 | else refreshTimer = setTimeout(run, wait); |
| 594 | }; |
| 595 | const observer = new MutationObserver((mutations) => { |
| 596 | if ( |
| 597 | mutations.every( |
| 598 | (mutation) => |
| 599 | mutation.target instanceof Element && |
| 600 | (mutation.target.closest("#theme-inspector-spotlight") || |
| 601 | mutation.target.closest("[data-theme-editor-panel]")), |
| 602 | ) |
| 603 | ) { |
| 604 | return; |
| 605 | } |
| 606 | scheduleRefresh(); |
| 607 | }); |
| 608 | observer.observe(document.body, { childList: true, subtree: true }); |
| 609 | let spotlightFrame: number | null = null; |
| 610 | const scheduleSpotlightRefresh = () => { |
| 611 | if (spotlightFrame !== null) return; |
| 612 | spotlightFrame = requestAnimationFrame(() => { |
| 613 | spotlightFrame = null; |
| 614 | refreshThemeInspectorSpotlight(); |
| 615 | }); |
| 616 | }; |
| 617 | window.addEventListener("resize", scheduleSpotlightRefresh); |
| 618 | window.addEventListener("scroll", scheduleSpotlightRefresh, true); |
| 619 | return () => { |
| 620 | observer.disconnect(); |
| 621 | if (refreshFrame !== null) cancelAnimationFrame(refreshFrame); |
| 622 | if (refreshTimer !== null) clearTimeout(refreshTimer); |
| 623 | if (spotlightFrame !== null) cancelAnimationFrame(spotlightFrame); |
| 624 | window.removeEventListener("resize", scheduleSpotlightRefresh); |
| 625 | window.removeEventListener("scroll", scheduleSpotlightRefresh, true); |
| 626 | clearThemeInspectorHighlights(); |
| 627 | setUsageCount(null); |
| 628 | }; |
| 629 | }, [isInspecting, open, selectedHighlightRolesKey, selectedRole]); |
| 630 | |
| 631 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- document pointer, click and key listeners that drive the inspect-mode hover overlay |
| 632 | useEffect(() => { |
| 633 | if (!open || !isInspecting) { |
| 634 | clearThemeInspectorHover(); |
| 635 | return; |
| 636 | } |
| 637 | |
| 638 | let shouldDisarmAfterClick = false; |
| 639 | let hoverTarget: Element | null = null; |
| 640 | let hoverInspection: ThemeElementInspection | null = null; |
| 641 | let hoverTimer: number | null = null; |
| 642 | let hoverFrame: number | null = null; |
| 643 | const clearHoverTimer = () => { |
| 644 | if (hoverTimer === null) return; |
| 645 | window.clearTimeout(hoverTimer); |
| 646 | hoverTimer = null; |
| 647 | }; |
| 648 | const clearHover = () => { |
| 649 | clearHoverTimer(); |
| 650 | hoverTarget = null; |
| 651 | hoverInspection = null; |
| 652 | clearThemeInspectorHover(); |
| 653 | }; |
| 654 | const showInspection = (inspection: ThemeElementInspection) => { |
| 655 | hoverInspection = inspection; |
| 656 | showThemeInspectorHover(inspection, themeEditorRoleLabel(inspection.role)); |
| 657 | }; |
| 658 | const handlePointerOver = (event: PointerEvent) => { |
| 659 | const target = event.target; |
| 660 | if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) { |
| 661 | clearHover(); |
| 662 | return; |
| 663 | } |
| 664 | |
| 665 | clearHoverTimer(); |
| 666 | hoverTarget = target; |
| 667 | hoverInspection = null; |
| 668 | const utilityInspection = inspectThemeRoleFromUtilitiesAtElement(target); |
| 669 | if (utilityInspection) { |
| 670 | showInspection(utilityInspection); |
| 671 | return; |
| 672 | } |
| 673 | |
| 674 | clearThemeInspectorHover(); |
| 675 | hoverTimer = window.setTimeout(() => { |
| 676 | hoverTimer = null; |
| 677 | if (hoverTarget !== target || !target.isConnected) return; |
| 678 | const inspection = inspectThemeRoleAtElement(target); |
| 679 | if (inspection) showInspection(inspection); |
| 680 | }, 140); |
| 681 | }; |
| 682 | const handlePointerOut = (event: PointerEvent) => { |
| 683 | if (event.relatedTarget === null) clearHover(); |
| 684 | }; |
| 685 | const handlePointerDown = (event: PointerEvent) => { |
| 686 | const target = event.target; |
| 687 | if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) return; |
| 688 | event.preventDefault(); |
| 689 | event.stopPropagation(); |
| 690 | clearHoverTimer(); |
| 691 | const inspection = |
| 692 | hoverTarget === target && hoverInspection |
| 693 | ? hoverInspection |
| 694 | : inspectThemeRoleAtElement(target); |
| 695 | if (!inspection) return; |
| 696 | clearHover(); |
| 697 | // preventDefault keeps focus put; blur so a focused color field commits its draft before |
| 698 | // selectThemeRole can switch modes and unmount it. |
| 699 | if (document.activeElement instanceof HTMLElement) document.activeElement.blur(); |
| 700 | selectThemeRole(inspection.role, true); |
| 701 | shouldDisarmAfterClick = true; |
| 702 | }; |
| 703 | const blockInspectedClick = (event: MouseEvent) => { |
| 704 | const target = event.target; |
| 705 | if (!(target instanceof Element) || target.closest("[data-theme-editor-panel]")) return; |
| 706 | event.preventDefault(); |
| 707 | event.stopPropagation(); |
| 708 | if (shouldDisarmAfterClick) setIsInspecting(false); |
| 709 | shouldDisarmAfterClick = false; |
| 710 | }; |
| 711 | const cancelInspection = (event: KeyboardEvent) => { |
| 712 | if (event.key !== "Escape") return; |
| 713 | // Esc leaves inspection only; Settings must not see it and close too. |
| 714 | event.preventDefault(); |
| 715 | event.stopImmediatePropagation(); |
| 716 | clearHover(); |
| 717 | clearInspectorSelection(); |
| 718 | }; |
| 719 | const refreshHover = () => { |
| 720 | if (!hoverInspection || hoverFrame !== null) return; |
| 721 | hoverFrame = requestAnimationFrame(() => { |
| 722 | hoverFrame = null; |
| 723 | if (hoverInspection) { |
| 724 | showThemeInspectorHover(hoverInspection, themeEditorRoleLabel(hoverInspection.role)); |
| 725 | } |
| 726 | }); |
| 727 | }; |
| 728 | const clearHoverOnScroll = () => clearHover(); |
| 729 | |
| 730 | document.addEventListener("pointerover", handlePointerOver, true); |
| 731 | document.addEventListener("pointerout", handlePointerOut, true); |
| 732 | document.addEventListener("pointerdown", handlePointerDown, true); |
| 733 | document.addEventListener("click", blockInspectedClick, true); |
| 734 | document.addEventListener("keydown", cancelInspection, true); |
| 735 | window.addEventListener("resize", refreshHover); |
| 736 | window.addEventListener("scroll", clearHoverOnScroll, true); |
| 737 | return () => { |
| 738 | document.removeEventListener("pointerover", handlePointerOver, true); |
| 739 | document.removeEventListener("pointerout", handlePointerOut, true); |
| 740 | document.removeEventListener("pointerdown", handlePointerDown, true); |
| 741 | document.removeEventListener("click", blockInspectedClick, true); |
| 742 | document.removeEventListener("keydown", cancelInspection, true); |
| 743 | window.removeEventListener("resize", refreshHover); |
| 744 | window.removeEventListener("scroll", clearHoverOnScroll, true); |
| 745 | clearHoverTimer(); |
| 746 | if (hoverFrame !== null) cancelAnimationFrame(hoverFrame); |
| 747 | clearThemeInspectorHover(); |
| 748 | }; |
| 749 | }, [clearInspectorSelection, isInspecting, open, selectThemeRole]); |
| 750 | |
| 751 | const handleAdvancedChange = (checked: boolean) => { |
| 752 | setIsAdvanced(checked); |
| 753 | if (checked) return; |
| 754 | if (selectedRole && !THEME_EDITOR_SIMPLE_ROLES.includes(selectedRole)) { |
| 755 | setSelectedRole(null); |
| 756 | } |
| 757 | if (!shouldRegenerateGuidedColors) return; |
| 758 | |
| 759 | const managedAppearances: ReadonlyArray<ThemeAppearance> = |
| 760 | editingTheme && getThemeModes(editingTheme).length > 1 |
| 761 | ? ["light", "dark"] |
| 762 | : [activeAppearance]; |
| 763 | setSimpleColorsDirtyByAppearance((current) => { |
| 764 | const next = { ...current }; |
| 765 | for (const appearance of managedAppearances) next[appearance] = true; |
| 766 | return next; |
| 767 | }); |
| 768 | setColorsByAppearance((current) => { |
| 769 | const next = { ...current }; |
| 770 | for (const appearance of managedAppearances) { |
| 771 | next[appearance] = getManagedEditorColors(appearance, current[appearance]); |
| 772 | } |
| 773 | return next; |
| 774 | }); |
| 775 | setShouldRegenerateGuidedColors(false); |
| 776 | }; |
| 777 | |
| 778 | const handleSubmit = () => { |
| 779 | if (!name.trim()) { |
| 780 | setError(gt("Name your theme first.")); |
| 781 | return; |
| 782 | } |
| 783 | |
| 784 | if (mergeTarget?.css && css.trim() && mergeTarget.css !== css) { |
| 785 | setError( |
| 786 | gt("“{label}” has different custom CSS. Use the same CSS or pick another name.", { |
| 787 | label: mergeTarget.label, |
| 788 | }), |
| 789 | ); |
| 790 | return; |
| 791 | } |
| 792 | |
| 793 | try { |
| 794 | const colorsForSave = !isAdvanced |
| 795 | ? { |
| 796 | light: simpleColorsDirtyByAppearance.light |
| 797 | ? getManagedEditorColors("light", colorsByAppearance.light) |
| 798 | : colorsByAppearance.light, |
| 799 | dark: simpleColorsDirtyByAppearance.dark |
| 800 | ? getManagedEditorColors("dark", colorsByAppearance.dark) |
| 801 | : colorsByAppearance.dark, |
| 802 | } |
| 803 | : colorsByAppearance; |
| 804 | |
| 805 | let savedTheme: ThemeDefinition; |
| 806 | let mergedAppearance: ThemeAppearance | null = null; |
| 807 | let retiredTheme: ThemeDefinition | null = null; |
| 808 | if (editingTheme && mergeTarget) { |
| 809 | const editedModes = getThemeModes(editingTheme); |
| 810 | const collision = editedModes.find((mode) => takenAppearances.includes(mode)); |
| 811 | if (collision) { |
| 812 | setError( |
| 813 | collision === "light" |
| 814 | ? gt("“{label}” already has a light palette. Pick another name.", { |
| 815 | label: mergeTarget.label, |
| 816 | }) |
| 817 | : gt("“{label}” already has a dark palette. Pick another name.", { |
| 818 | label: mergeTarget.label, |
| 819 | }), |
| 820 | ); |
| 821 | return; |
| 822 | } |
| 823 | mergedAppearance = editedModes[0] ?? null; |
| 824 | savedTheme = updateCustomTheme({ |
| 825 | ...parseThemeFile({ |
| 826 | version: THEME_FILE_VERSION, |
| 827 | id: mergeTarget.id, |
| 828 | name: mergeTarget.label, |
| 829 | appearance: mergeTarget.appearance, |
| 830 | colors: mergeTarget.colors, |
| 831 | variants: { |
| 832 | ...mergeTarget.variants, |
| 833 | ...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])), |
| 834 | }, |
| 835 | ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}), |
| 836 | ...(cssForSave ? { css: cssForSave } : {}), |
| 837 | }), |
| 838 | ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}), |
| 839 | }); |
| 840 | retiredTheme = editingTheme; |
| 841 | retireMergedTheme(editingTheme, mergeTarget); |
| 842 | } else if (editingTheme) { |
| 843 | const baseAppearance = editingTheme.appearance; |
| 844 | const variantAppearance = baseAppearance === "light" ? "dark" : "light"; |
| 845 | savedTheme = updateCustomTheme({ |
| 846 | ...parseThemeFile({ |
| 847 | version: THEME_FILE_VERSION, |
| 848 | id: editingTheme.id, |
| 849 | name, |
| 850 | appearance: baseAppearance, |
| 851 | colors: colorsForSave[baseAppearance], |
| 852 | ...(getThemeModes(editingTheme).length > 1 |
| 853 | ? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } } |
| 854 | : {}), |
| 855 | ...(isAdvanced ? {} : { managed: true }), |
| 856 | ...(cssForSave ? { css: cssForSave } : {}), |
| 857 | }), |
| 858 | ...(editingTheme.collection ? { collection: editingTheme.collection } : {}), |
| 859 | }); |
| 860 | } else if (mergeTarget) { |
| 861 | if (takenAppearances.includes(activeAppearance)) { |
| 862 | setError( |
| 863 | gt("“{label}” already has light and dark palettes. Pick another name.", { |
| 864 | label: mergeTarget.label, |
| 865 | }), |
| 866 | ); |
| 867 | return; |
| 868 | } |
| 869 | mergedAppearance = activeAppearance; |
| 870 | savedTheme = updateCustomTheme({ |
| 871 | ...parseThemeFile({ |
| 872 | version: THEME_FILE_VERSION, |
| 873 | id: mergeTarget.id, |
| 874 | name: mergeTarget.label, |
| 875 | appearance: mergeTarget.appearance, |
| 876 | colors: mergeTarget.colors, |
| 877 | variants: { |
| 878 | ...mergeTarget.variants, |
| 879 | [activeAppearance]: colorsForSave[activeAppearance], |
| 880 | }, |
| 881 | ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}), |
| 882 | ...(cssForSave ? { css: cssForSave } : {}), |
| 883 | }), |
| 884 | ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}), |
| 885 | }); |
| 886 | } else { |
| 887 | savedTheme = installCustomTheme( |
| 888 | parseThemeFile({ |
| 889 | version: THEME_FILE_VERSION, |
| 890 | name, |
| 891 | appearance: activeAppearance, |
| 892 | colors: colorsForSave[activeAppearance], |
| 893 | ...(isAdvanced ? {} : { managed: true }), |
| 894 | ...(cssForSave ? { css: cssForSave } : {}), |
| 895 | }), |
| 896 | ); |
| 897 | } |
| 898 | if ( |
| 899 | !onSaved(savedTheme, { |
| 900 | created: editingTheme === null && mergedAppearance === null, |
| 901 | ...(mergedAppearance ? { mergedAppearance } : {}), |
| 902 | }) |
| 903 | ) { |
| 904 | if (!editingTheme && mergedAppearance === null) { |
| 905 | try { |
| 906 | removeCustomTheme(savedTheme.id); |
| 907 | } catch {} |
| 908 | } else if (mergeTarget && mergedAppearance !== null) { |
| 909 | try { |
| 910 | updateCustomTheme(mergeTarget); |
| 911 | if (retiredTheme) installCustomTheme(retiredTheme); |
| 912 | } catch {} |
| 913 | } |
| 914 | setError(gt("Theme saved, but it could not be made active. Try again.")); |
| 915 | return; |
| 916 | } |
| 917 | onOpenChange(false); |
| 918 | } catch (cause) { |
| 919 | setError( |
| 920 | cause instanceof Error |
| 921 | ? (errorDisplayMessage(cause, m) ?? cause.message) |
| 922 | : isEditing |
| 923 | ? gt("Could not save the theme.") |
| 924 | : gt("Could not create the theme."), |
| 925 | ); |
| 926 | } |
| 927 | }; |
| 928 | |
| 929 | const renderNameField = () => ( |
| 930 | <label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3"> |
| 931 | <span className="text-sm font-medium"> |
| 932 | <T>Theme name</T> |
| 933 | </span> |
| 934 | <Input |
| 935 | autoFocus |
| 936 | size="sm" |
| 937 | onChange={(event) => { |
| 938 | setName(event.currentTarget.value); |
| 939 | setError(null); |
| 940 | }} |
| 941 | placeholder={isEditing ? gt("Theme name") : gt("e.g. Aurora")} |
| 942 | value={name} |
| 943 | /> |
| 944 | </label> |
| 945 | ); |
| 946 | |
| 947 | const renderAppearanceButton = (appearance: ThemeAppearance) => { |
| 948 | const lockReason = appearanceLockReason(appearance); |
| 949 | // Use aria-disabled so locked modes remain hoverable for explanatory tooltips. |
| 950 | const button = ( |
| 951 | <Toggle aria-disabled={lockReason !== null} value={appearance}> |
| 952 | {appearance === "light" ? gt("Light") : gt("Dark")} |
| 953 | </Toggle> |
| 954 | ); |
| 955 | if (lockReason === null) return button; |
| 956 | return ( |
| 957 | <Tooltip> |
| 958 | <TooltipTrigger render={button} /> |
| 959 | <TooltipPopup>{lockReason}</TooltipPopup> |
| 960 | </Tooltip> |
| 961 | ); |
| 962 | }; |
| 963 | |
| 964 | const renderAppearanceButtons = () => ( |
| 965 | <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3"> |
| 966 | <span className="text-sm font-medium"> |
| 967 | <T>Appearance</T> |
| 968 | </span> |
| 969 | <ToggleGroup |
| 970 | aria-label={gt("Theme appearance")} |
| 971 | variant="segmented" |
| 972 | value={[activeAppearance]} |
| 973 | onValueChange={(next) => { |
| 974 | const appearance = next[0]; |
| 975 | if ( |
| 976 | (appearance === "light" || appearance === "dark") && |
| 977 | appearanceLockReason(appearance) === null |
| 978 | ) { |
| 979 | setActiveAppearance(appearance); |
| 980 | } |
| 981 | }} |
| 982 | > |
| 983 | {renderAppearanceButton("light")} |
| 984 | {renderAppearanceButton("dark")} |
| 985 | </ToggleGroup> |
| 986 | </div> |
| 987 | ); |
| 988 | |
| 989 | const renderColorsHeader = () => ( |
| 990 | <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3"> |
| 991 | <div> |
| 992 | <h3 className="text-sm font-medium"> |
| 993 | <T>Colors</T> |
| 994 | </h3> |
| 995 | {isAdvanced ? null : ( |
| 996 | <p className="text-xs text-muted-foreground"> |
| 997 | <T>Two colors, rest derived</T> |
| 998 | </p> |
| 999 | )} |
| 1000 | </div> |
| 1001 | <div className="flex min-w-0 items-start gap-3"> |
| 1002 | {isAdvanced ? ( |
| 1003 | <Input |
| 1004 | aria-label={gt("Filter colors")} |
| 1005 | className="min-w-0 flex-1" |
| 1006 | onChange={(event) => setRoleQuery(event.currentTarget.value)} |
| 1007 | placeholder={gt("Filter colors")} |
| 1008 | size="sm" |
| 1009 | value={roleQuery} |
| 1010 | /> |
| 1011 | ) : null} |
| 1012 | <label className="ml-auto flex shrink-0 cursor-pointer items-center gap-2 pt-0.5 text-sm font-medium"> |
| 1013 | <span> |
| 1014 | <T>Advanced</T> |
| 1015 | </span> |
| 1016 | <Switch |
| 1017 | aria-label={gt("Use advanced theme colors")} |
| 1018 | checked={isAdvanced} |
| 1019 | onCheckedChange={(checked) => handleAdvancedChange(Boolean(checked))} |
| 1020 | /> |
| 1021 | </label> |
| 1022 | </div> |
| 1023 | </div> |
| 1024 | ); |
| 1025 | |
| 1026 | const renderRoleFields = ( |
| 1027 | families: ReadonlyArray<ThemeEditorColorFamily>, |
| 1028 | gridClassName = "grid gap-2 sm:grid-cols-2", |
| 1029 | ) => ( |
| 1030 | <div className={gridClassName}> |
| 1031 | {families.map((family) => ( |
| 1032 | <ThemeColorField |
| 1033 | key={family.id} |
| 1034 | label={messages(family.label)} |
| 1035 | onChange={updateColor} |
| 1036 | onEditCancel={cancelColorEdit} |
| 1037 | onEditStart={startColorEdit} |
| 1038 | onSelect={selectThemeRole} |
| 1039 | onToggleSelected={toggleThemeRole} |
| 1040 | role={family.role} |
| 1041 | selected={selectedRole === family.role} |
| 1042 | value={colorsByAppearance[activeAppearance][family.role]} |
| 1043 | /> |
| 1044 | ))} |
| 1045 | </div> |
| 1046 | ); |
| 1047 | |
| 1048 | const renderColorFields = () => { |
| 1049 | const query = roleQuery.trim().toLowerCase(); |
| 1050 | const groups = THEME_EDITOR_ROLE_GROUPS.map((group) => ({ |
| 1051 | ...group, |
| 1052 | families: group.families.filter( |
| 1053 | (family) => |
| 1054 | !query || |
| 1055 | [messages(family.label), ...family.roles.map((role) => getThemeRoleLabel(role, messages))] |
| 1056 | .join(" ") |
| 1057 | .toLowerCase() |
| 1058 | .includes(query), |
| 1059 | ), |
| 1060 | })).filter((group) => group.families.length > 0); |
| 1061 | return isAdvanced ? ( |
| 1062 | <div className="space-y-5"> |
| 1063 | {groups.map((group) => ( |
| 1064 | <section className="space-y-2" key={group.id}> |
| 1065 | <h4 className="text-sm font-medium text-foreground">{messages(group.title)}</h4> |
| 1066 | {renderRoleFields(group.families, "grid gap-1")} |
| 1067 | </section> |
| 1068 | ))} |
| 1069 | {groups.length === 0 ? ( |
| 1070 | <p className="text-xs text-muted-foreground"> |
| 1071 | <T>No matches.</T> |
| 1072 | </p> |
| 1073 | ) : null} |
| 1074 | </div> |
| 1075 | ) : ( |
| 1076 | <div className="grid gap-1"> |
| 1077 | {THEME_EDITOR_SIMPLE_ROLES.map((role) => ( |
| 1078 | <ThemeColorField |
| 1079 | key={role} |
| 1080 | onChange={updateColor} |
| 1081 | onEditCancel={cancelColorEdit} |
| 1082 | onEditStart={startColorEdit} |
| 1083 | onSelect={selectThemeRole} |
| 1084 | onToggleSelected={toggleThemeRole} |
| 1085 | role={role} |
| 1086 | label={role === "canvas" ? gt("Background") : gt("Accent")} |
| 1087 | selected={selectedRole === role} |
| 1088 | value={colorsByAppearance[activeAppearance][role]} |
| 1089 | /> |
| 1090 | ))} |
| 1091 | </div> |
| 1092 | ); |
| 1093 | }; |
| 1094 | |
| 1095 | // Geometry is stored as the user left it and fitted to the current viewport here, so a |
| 1096 | // window that shrinks and grows back returns the panel to where it was. |
| 1097 | const viewport = useViewportSize(); |
| 1098 | const shownSize = size && { |
| 1099 | width: Math.max(PANEL_MIN_WIDTH, Math.min(size.width, viewport.width - PANEL_MARGIN * 2)), |
| 1100 | height: Math.max(PANEL_MIN_HEIGHT, Math.min(size.height, viewport.height - PANEL_MARGIN * 2)), |
| 1101 | }; |
| 1102 | const shownPosition = |
| 1103 | position && |
| 1104 | clampPanelPosition(viewport, position.x, position.y, shownSize?.width ?? position.width); |
| 1105 | |
| 1106 | const handleDragPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1107 | if ((event.target as HTMLElement).closest("button, input, a")) return; |
| 1108 | const rect = panelRef.current?.getBoundingClientRect(); |
| 1109 | if (!rect) return; |
| 1110 | dragOffsetRef.current = { |
| 1111 | dx: event.clientX - rect.x, |
| 1112 | dy: event.clientY - rect.y, |
| 1113 | width: rect.width, |
| 1114 | }; |
| 1115 | event.currentTarget.setPointerCapture(event.pointerId); |
| 1116 | }; |
| 1117 | |
| 1118 | const handleDragPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1119 | const offset = dragOffsetRef.current; |
| 1120 | if (!offset) return; |
| 1121 | const next = clampPanelPosition( |
| 1122 | readWindowViewport(), |
| 1123 | event.clientX - offset.dx, |
| 1124 | event.clientY - offset.dy, |
| 1125 | offset.width, |
| 1126 | ); |
| 1127 | setPosition({ ...next, width: offset.width }); |
| 1128 | }; |
| 1129 | |
| 1130 | const endDrag = () => { |
| 1131 | dragOffsetRef.current = null; |
| 1132 | }; |
| 1133 | |
| 1134 | const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1135 | const rect = panelRef.current?.getBoundingClientRect(); |
| 1136 | if (!rect) return; |
| 1137 | event.preventDefault(); |
| 1138 | // Resize from where the panel is drawn, so a position clamped after the window shrank, or bottom-right |
| 1139 | // parking, can't make the top-left corner slide. |
| 1140 | const next = clampPanelPosition(readWindowViewport(), rect.x, rect.y, rect.width); |
| 1141 | setPosition({ ...next, width: rect.width }); |
| 1142 | resizeStartRef.current = { |
| 1143 | pointerX: event.clientX, |
| 1144 | pointerY: event.clientY, |
| 1145 | left: rect.x, |
| 1146 | top: rect.y, |
| 1147 | width: rect.width, |
| 1148 | height: rect.height, |
| 1149 | }; |
| 1150 | event.currentTarget.setPointerCapture(event.pointerId); |
| 1151 | }; |
| 1152 | |
| 1153 | const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => { |
| 1154 | const start = resizeStartRef.current; |
| 1155 | if (!start) return; |
| 1156 | const maxWidth = Math.max(PANEL_MIN_WIDTH, window.innerWidth - PANEL_MARGIN - start.left); |
| 1157 | const maxHeight = Math.max(PANEL_MIN_HEIGHT, window.innerHeight - PANEL_MARGIN - start.top); |
| 1158 | setSize({ |
| 1159 | width: Math.min( |
| 1160 | Math.max(start.width + event.clientX - start.pointerX, PANEL_MIN_WIDTH), |
| 1161 | maxWidth, |
| 1162 | ), |
| 1163 | height: Math.min( |
| 1164 | Math.max(start.height + event.clientY - start.pointerY, PANEL_MIN_HEIGHT), |
| 1165 | maxHeight, |
| 1166 | ), |
| 1167 | }); |
| 1168 | }; |
| 1169 | |
| 1170 | const endResize = () => { |
| 1171 | resizeStartRef.current = null; |
| 1172 | }; |
| 1173 | |
| 1174 | return ( |
| 1175 | <div |
| 1176 | aria-label={isEditing ? gt("Edit theme") : gt("Create theme")} |
| 1177 | className={cn( |
| 1178 | "dialog-glass fixed z-[110] flex max-h-[min(42rem,calc(100dvh-6rem))] w-[min(26rem,calc(100vw-2rem))] flex-col overflow-hidden rounded-xl border text-popover-foreground", |
| 1179 | position === null && "bottom-4 right-4", |
| 1180 | isMinimized && "max-h-none", |
| 1181 | )} |
| 1182 | data-theme-editor-panel |
| 1183 | onKeyDown={(event) => { |
| 1184 | // Popups opened from the editor are portaled outside it and handle their own Esc. |
| 1185 | if (event.key !== "Escape" || event.defaultPrevented) return; |
| 1186 | if (!event.currentTarget.contains(event.target as Node)) return; |
| 1187 | event.stopPropagation(); |
| 1188 | onOpenChange(false); |
| 1189 | }} |
| 1190 | ref={panelRef} |
| 1191 | role="dialog" |
| 1192 | style={{ |
| 1193 | ...(shownPosition ? { left: shownPosition.x, top: shownPosition.y } : {}), |
| 1194 | ...(shownSize ? { width: shownSize.width } : {}), |
| 1195 | ...(shownSize && !isMinimized |
| 1196 | ? { height: shownSize.height, maxHeight: "calc(100dvh - 1rem)" } |
| 1197 | : {}), |
| 1198 | }} |
| 1199 | > |
| 1200 | <div |
| 1201 | className="flex cursor-grab touch-none select-none items-center gap-1 border-b border-border/70 px-3 py-2 active:cursor-grabbing" |
| 1202 | onPointerCancel={endDrag} |
| 1203 | onPointerDown={handleDragPointerDown} |
| 1204 | onPointerMove={handleDragPointerMove} |
| 1205 | onPointerUp={endDrag} |
| 1206 | > |
| 1207 | <div className="flex min-w-0 flex-1 items-baseline gap-2"> |
| 1208 | <h2 className="shrink-0 truncate text-sm font-medium"> |
| 1209 | {isEditing ? gt("Edit theme") : gt("Create theme")} |
| 1210 | </h2> |
| 1211 | {isMinimized ? null : ( |
| 1212 | <p className="truncate text-xs text-muted-foreground"> |
| 1213 | {isInspecting |
| 1214 | ? gt("Select an element · Esc to cancel") |
| 1215 | : selectedRole |
| 1216 | ? gt("{label} · {count, plural, one {{count} use} other {{count} uses}}", { |
| 1217 | label: isAdvanced |
| 1218 | ? themeEditorRoleLabel(selectedRole, messages) |
| 1219 | : getThemeRoleLabel(selectedRole, messages), |
| 1220 | count: usageCount ?? 0, |
| 1221 | }) |
| 1222 | : gt("Select a color below")} |
| 1223 | </p> |
| 1224 | )} |
| 1225 | </div> |
| 1226 | <Tooltip> |
| 1227 | <TooltipTrigger |
| 1228 | render={ |
| 1229 | <Button |
| 1230 | aria-label={ |
| 1231 | isInspecting ? gt("Cancel inspecting app colors") : gt("Inspect app colors") |
| 1232 | } |
| 1233 | aria-pressed={isInspecting} |
| 1234 | size="xs" |
| 1235 | variant={isInspecting ? "secondary" : "ghost"} |
| 1236 | onClick={() => { |
| 1237 | if (isInspecting) { |
| 1238 | clearInspectorSelection(); |
| 1239 | return; |
| 1240 | } |
| 1241 | setIsInspecting(true); |
| 1242 | }} |
| 1243 | > |
| 1244 | <MousePointer2Icon /> |
| 1245 | {isInspecting ? gt("Cancel") : gt("Inspect")} |
| 1246 | </Button> |
| 1247 | } |
| 1248 | /> |
| 1249 | <TooltipPopup data-theme-editor-panel=""> |
| 1250 | {isInspecting ? gt("Cancel and clear the selection") : gt("Pick a color from the app")} |
| 1251 | </TooltipPopup> |
| 1252 | </Tooltip> |
| 1253 | <Button |
| 1254 | aria-label={isMinimized ? gt("Expand the theme editor") : gt("Minimize the theme editor")} |
| 1255 | size="icon-xs" |
| 1256 | variant="ghost" |
| 1257 | onClick={() => setIsMinimized(!isMinimized)} |
| 1258 | > |
| 1259 | {isMinimized ? <ChevronUpIcon /> : <ChevronDownIcon />} |
| 1260 | </Button> |
| 1261 | <Button |
| 1262 | aria-label={gt("Close the theme editor")} |
| 1263 | size="icon-xs" |
| 1264 | variant="ghost" |
| 1265 | onClick={() => onOpenChange(false)} |
| 1266 | > |
| 1267 | <XIcon /> |
| 1268 | </Button> |
| 1269 | </div> |
| 1270 | |
| 1271 | {isMinimized ? null : ( |
| 1272 | <> |
| 1273 | <div className="min-h-0 flex-1 space-y-3 overflow-y-auto py-3 pl-3 pr-1.5"> |
| 1274 | {renderNameField()} |
| 1275 | {error ? ( |
| 1276 | <p aria-live="polite" className="text-sm text-destructive"> |
| 1277 | {error} |
| 1278 | </p> |
| 1279 | ) : null} |
| 1280 | {renderAppearanceButtons()} |
| 1281 | <div className="space-y-3"> |
| 1282 | {renderColorsHeader()} |
| 1283 | {renderColorFields()} |
| 1284 | </div> |
| 1285 | <div className="space-y-2"> |
| 1286 | <Button |
| 1287 | aria-expanded={cssOpen} |
| 1288 | size="xs" |
| 1289 | variant="ghost" |
| 1290 | onClick={() => setCssOpen(!cssOpen)} |
| 1291 | > |
| 1292 | {cssOpen ? <ChevronDownIcon /> : <ChevronRightIcon />} |
| 1293 | <T>Custom CSS</T> |
| 1294 | </Button> |
| 1295 | {cssOpen ? ( |
| 1296 | <> |
| 1297 | <p className="text-xs text-muted-foreground"> |
| 1298 | <T> |
| 1299 | Saved with this theme and included when you export it. Web and desktop only. |
| 1300 | Rules that load remote files are ignored. |
| 1301 | </T> |
| 1302 | </p> |
| 1303 | <ThemeCssEditor value={css} onChange={setCss} /> |
| 1304 | </> |
| 1305 | ) : null} |
| 1306 | </div> |
| 1307 | </div> |
| 1308 | <div className="flex items-center justify-end gap-2 border-t border-border/70 px-3 py-2"> |
| 1309 | <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}> |
| 1310 | <T>Cancel</T> |
| 1311 | </Button> |
| 1312 | <Button disabled={!name.trim()} size="sm" onClick={handleSubmit}> |
| 1313 | {isEditing ? ( |
| 1314 | mergeTarget ? ( |
| 1315 | gt("Merge into “{label}”", { label: mergeTarget.label }) |
| 1316 | ) : ( |
| 1317 | gt("Save changes") |
| 1318 | ) |
| 1319 | ) : mergeTarget ? ( |
| 1320 | <> |
| 1321 | <PlusIcon /> |
| 1322 | {activeAppearance === "light" ? gt("Add light palette") : gt("Add dark palette")} |
| 1323 | </> |
| 1324 | ) : ( |
| 1325 | <> |
| 1326 | <PaintbrushIcon /> |
| 1327 | <T>Create theme</T> |
| 1328 | </> |
| 1329 | )} |
| 1330 | </Button> |
| 1331 | </div> |
| 1332 | <div |
| 1333 | aria-hidden |
| 1334 | className="absolute bottom-0 right-0 z-10 flex size-5 cursor-se-resize touch-none select-none items-end justify-end p-1 text-muted-foreground/70" |
| 1335 | onPointerCancel={endResize} |
| 1336 | onPointerDown={handleResizePointerDown} |
| 1337 | onPointerMove={handleResizePointerMove} |
| 1338 | onPointerUp={endResize} |
| 1339 | > |
| 1340 | <svg |
| 1341 | className="size-2.5" |
| 1342 | fill="none" |
| 1343 | stroke="currentColor" |
| 1344 | strokeLinecap="round" |
| 1345 | strokeWidth="1.2" |
| 1346 | viewBox="0 0 8 8" |
| 1347 | > |
| 1348 | <path d="M7 1 1 7M7 4.5 4.5 7" /> |
| 1349 | </svg> |
| 1350 | </div> |
| 1351 | </> |
| 1352 | )} |
| 1353 | </div> |
| 1354 | ); |
| 1355 | } |