feat(editor): light mode

Follows the system theme, with a header button cycling system/light/dark
(remembered). The page colors are CSS variables for both palettes; the 3D
viewport (background, edges, grid, axes, vertex points, selection), the
code editor and the loading veil switch with it, in place.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-13 15:30:22 +08:00
parent 2f81fcdd18
commit d8a654c162
20 changed files with 385 additions and 85 deletions
+4
View File
@@ -8,6 +8,10 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and
### Added
- Editor: light mode. The editor follows the system theme and a button in the
header cycles system, light and dark (remembered); the 3D viewport, edges,
grid, axes and the code editor switch with it, in place, without reloading
the model or losing the camera and selection.
- `sca edit [WORKSPACE]`: the web editor, now part of the SDK
(`simplecadapi.editor`, UI sources in `editor-web/`; needs the `editor`
extra). It runs a workspace's notebooks in a marimo kernel with the SDK's
+15
View File
@@ -4,6 +4,21 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SimpleCAD Studio</title>
<script>
// Pick the theme before first paint (no flash): the saved choice, else the system.
// Keep in step with src/lib/theme.ts.
(function () {
var choice = "system";
try {
choice = localStorage.getItem("sca-theme") || "system";
} catch (e) {}
var dark =
choice === "dark" ||
(choice !== "light" && window.matchMedia("(prefers-color-scheme: dark)").matches);
document.documentElement.classList.toggle("dark", dark);
document.documentElement.style.colorScheme = dark ? "dark" : "light";
})();
</script>
</head>
<body>
<div id="root"></div>
+7 -2
View File
@@ -13,6 +13,7 @@ import { fetchPreview, getWorkspace, openNotebook, postViewport, type ModuleRow,
import { parsePreview } from "@/lib/preview";
import { EnvelopeSocket, type Envelope } from "@/lib/envelope";
import { useRunLog } from "@/lib/runlog";
import { useTheme } from "@/lib/theme";
import { selectionPayload, variableNames, type SelectionItem } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { Viewport, type PickResult, type SelectionMode } from "@/scene/Viewport";
@@ -63,6 +64,7 @@ export function App() {
const [loading, setLoading] = useState<string | null>("connecting");
const kind = notebooks.find((row) => row.path === currentPath)?.kind ?? null;
const theme = useTheme();
const log = useRunLog();
const running = cells.some((cell) => cell.status === "running" || cell.status === "queued");
const handleStop = useCallback(() => {
@@ -318,6 +320,8 @@ export function App() {
kernelAlive={kernelAlive}
status={status}
marimoUrl={marimoUrl}
themePreference={theme.preference}
onTheme={theme.cycle}
running={running}
onStop={handleStop}
onRunAll={() => {
@@ -376,7 +380,7 @@ export function App() {
className={cn(
"border-2 px-2 py-px text-[10px] font-semibold uppercase tracking-[0.1em] transition-colors",
selectionMode === mode
? "border-white bg-white text-black"
? "border-primary bg-primary text-primary-foreground"
: "border-transparent text-muted-foreground hover:border-input hover:text-foreground",
)}
onClick={() => setSelectionMode(mode)}
@@ -400,6 +404,7 @@ export function App() {
selectionMode={selectionMode}
selection={selection}
sceneVersion={sceneVersion}
theme={theme.resolved}
onPick={handlePick}
onClear={handleClear}
/>
@@ -411,7 +416,7 @@ export function App() {
<Inspector selection={selection} />
</ResizablePanel>
</ResizablePanelGroup>
<LoadingMask active={loading !== null} message={loading ?? ""} />
<LoadingMask active={loading !== null} message={loading ?? ""} theme={theme.resolved} />
</div>
<Dock
entries={log.entries}
+3 -3
View File
@@ -234,7 +234,7 @@ function CellGap({ after, onInsert }: { after: string | null; onInsert: (after:
<button
type="button"
title="Insert a cell here"
className="z-10 flex h-4 w-4 items-center justify-center border-2 border-input bg-black text-muted-foreground opacity-0 transition-opacity hover:border-focus hover:text-focus group-hover/gap:opacity-100"
className="z-10 flex h-4 w-4 items-center justify-center border-2 border-input bg-background text-muted-foreground opacity-0 transition-opacity hover:border-focus hover:text-focus group-hover/gap:opacity-100"
onClick={(event) => {
event.stopPropagation();
onInsert(after);
@@ -337,7 +337,7 @@ function CellBlock({
return (
<section
className={cn(
"border-2 bg-black transition-colors",
"border-2 bg-background transition-colors",
isSelection ? "border-focus/60" : failed ? "border-fail/70" : "border-border",
stale && !failed && "border-dashed",
armed && "border-fail",
@@ -397,7 +397,7 @@ function CellBlock({
title={armed ? "Click again to delete this cell" : "Delete this cell"}
onClick={onDelete}
data-delete-armed={cell.id}
className={armed ? "border-fail bg-fail text-black hover:border-fail hover:text-black" : "hover:text-fail"}
className={armed ? "border-fail bg-fail text-primary-foreground hover:border-fail hover:text-primary-foreground" : "hover:text-fail"}
>
<Trash2 className="h-3.5 w-3.5" />
</IconButton>
+1 -1
View File
@@ -61,7 +61,7 @@ export function Dock({
const percent = batch && batch.total > 0 ? Math.round((batch.done / batch.total) * 100) : 0;
return (
<section className="shrink-0 border-t-2 border-border bg-black" aria-label="log">
<section className="shrink-0 border-t-2 border-border bg-background" aria-label="log">
{open && (
<div ref={list} className="h-44 overflow-y-auto border-b-2 border-border px-3 py-1.5 text-[11px] leading-5">
{entries.length === 0 ? (
+20 -2
View File
@@ -1,4 +1,6 @@
import { ExternalLink, Play, Square } from "lucide-react";
import { ExternalLink, Monitor, Moon, Play, Square, Sun } from "lucide-react";
import type { ThemePreference } from "@/lib/theme";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -14,6 +16,8 @@ export function Header({
running,
onStop,
marimoUrl,
themePreference,
onTheme,
}: {
notebook: string | null;
kind: string | null;
@@ -24,10 +28,12 @@ export function Header({
running: boolean;
onStop: () => void;
marimoUrl: string | null;
themePreference: ThemePreference;
onTheme: () => void;
}) {
const failing = status.startsWith("error");
return (
<header className="flex h-11 shrink-0 items-center gap-3 border-b-2 border-border bg-black px-3">
<header className="flex h-11 shrink-0 items-center gap-3 border-b-2 border-border bg-background px-3">
<span className="text-[13px] font-bold uppercase tracking-[0.14em]">SimpleCAD</span>
<span className="h-5 w-[2px] bg-border" />
{notebook ? (
@@ -64,6 +70,18 @@ export function Header({
</a>
</Button>
)}
<Button
size="sm"
variant="ghost"
onClick={onTheme}
title={`Theme: ${themePreference} (click: ${NEXT_THEME[themePreference]})`}
aria-label={`Theme: ${themePreference}. Switch to ${NEXT_THEME[themePreference]}`}
>
{themePreference === "system" ? <Monitor /> : themePreference === "light" ? <Sun /> : <Moon />}
{themePreference}
</Button>
</header>
);
}
const NEXT_THEME: Record<ThemePreference, ThemePreference> = { system: "light", light: "dark", dark: "system" };
+25 -11
View File
@@ -18,7 +18,7 @@ const WAVE_SPEED = 0.0009;
* dot-matrix with a ripple that spreads from the middle, and a small retro
* window saying what is going on and for how long. It appears only after
* `DELAY_MS`, so quick operations do not flash it. */
export function LoadingMask({ active, message }: { active: boolean; message: string }) {
export function LoadingMask({ active, message, theme }: { active: boolean; message: string; theme: string }) {
const DELAY_MS = 250;
const [visible, setVisible] = useState(false);
const [elapsed, setElapsed] = useState(0);
@@ -45,11 +45,11 @@ export function LoadingMask({ active, message }: { active: boolean; message: str
<div
role="status"
aria-live="polite"
className="absolute inset-0 z-50 flex cursor-progress items-center justify-center bg-[#1b1b1b]/75"
className="absolute inset-0 z-50 flex cursor-progress items-center justify-center bg-overlay"
>
<Ripple />
<div className="relative w-[280px] border-2 border-white/80 bg-black shadow-[6px_6px_0_0_rgba(255,255,255,0.1)]">
<div className="flex h-6 items-center justify-between bg-white/85 px-2 text-[11px] font-bold uppercase tracking-[0.18em] text-black">
<Ripple theme={theme} />
<div className="relative w-[280px] border-2 border-foreground/80 bg-background shadow-[6px_6px_0_0_var(--shadow-hard)]">
<div className="flex h-6 items-center justify-between bg-foreground/85 px-2 text-[11px] font-bold uppercase tracking-[0.18em] text-background">
<span>loading</span>
<span className="tabular-nums">
{minutes}:{seconds}
@@ -58,7 +58,7 @@ export function LoadingMask({ active, message }: { active: boolean; message: str
<div className="flex items-center gap-4 px-4 py-4">
<Spinner />
<div className="min-w-0 flex-1">
<p className="truncate text-[12px] uppercase tracking-[0.1em] text-white" title={message}>
<p className="truncate text-[12px] uppercase tracking-[0.1em] text-foreground" title={message}>
{message}
</p>
<p className="mt-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground">
@@ -81,7 +81,7 @@ function Spinner() {
return (
<span
key={cell}
className={cn("block bg-white", order < 0 && "invisible", order >= 0 && "sca-chase")}
className={cn("block bg-foreground", order < 0 && "invisible", order >= 0 && "sca-chase")}
style={order >= 0 ? { animationDelay: `${order * 0.1}s` } : undefined}
/>
);
@@ -93,18 +93,32 @@ function Spinner() {
/** A strip of blocks filling and emptying: the load has no known length. */
function Progress() {
return (
<div className="flex gap-[3px] border-t-2 border-white px-2 py-1.5" aria-hidden>
<div className="flex gap-[3px] border-t-2 border-foreground px-2 py-1.5" aria-hidden>
{Array.from({ length: 20 }, (_, index) => (
<span key={index} className="sca-bar block h-[6px] flex-1 bg-white" style={{ animationDelay: `${index * 0.07}s` }} />
<span key={index} className="sca-bar block h-[6px] flex-1 bg-foreground" style={{ animationDelay: `${index * 0.07}s` }} />
))}
</div>
);
}
/** A CSS color variable of the page (a #rrggbb token) as "r,g,b", for drawing on a canvas. */
function cssRgb(name: string, fallback: string): string {
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
const match = /^#([0-9a-f]{6})$/i.exec(value);
if (!match) return fallback;
const n = parseInt(match[1], 16);
return `${(n >> 16) & 255},${(n >> 8) & 255},${n & 255}`;
}
/** The dot-matrix: square dots whose brightness follows a ring-shaped wave
* travelling out from the middle, quantised to four levels. */
function Ripple() {
function Ripple({ theme }: { theme: string }) {
const canvasRef = useRef<HTMLCanvasElement>(null);
// The dots take the theme's ink: the crest is the focus color, the rest the foreground.
const inks = useRef({ crest: "255,154,46", base: "255,255,255" });
useEffect(() => {
inks.current = { crest: cssRgb("--focus", "255,154,46"), base: cssRgb("--foreground", "255,255,255") };
}, [theme]);
useEffect(() => {
const canvas = canvasRef.current;
@@ -142,7 +156,7 @@ function Ripple() {
}
}
paths.forEach((path, level) => {
context.fillStyle = level === LEVELS.length - 1 ? `rgba(255,154,46,${LEVELS[level]})` : `rgba(255,255,255,${LEVELS[level]})`;
context.fillStyle = `rgba(${level === LEVELS.length - 1 ? inks.current.crest : inks.current.base},${LEVELS[level]})`;
context.fill(path);
});
};
+1 -1
View File
@@ -45,7 +45,7 @@ export function ParamControl({
onClick={() => forwardParam(param.id, !on)}
>
<span className={ink}>{label}</span>
<span className={cn("border-2 px-1.5 text-[10px] font-bold uppercase", on ? "border-white bg-white text-black" : "border-input text-muted-foreground")}>
<span className={cn("border-2 px-1.5 text-[10px] font-bold uppercase", on ? "border-primary bg-primary text-primary-foreground" : "border-input text-muted-foreground")}>
{on ? "on" : "off"}
</span>
</button>
+2 -2
View File
@@ -8,14 +8,14 @@ const badgeVariants = cva(
{
variants: {
variant: {
default: "border-white bg-white text-black",
default: "border-primary bg-primary text-primary-foreground",
secondary: "border-input text-muted-foreground",
outline: "border-input text-foreground",
focus: "border-focus text-focus",
pass: "border-pass text-pass",
fail: "border-fail text-fail",
name: "border-name text-name",
destructive: "border-fail bg-fail text-black",
destructive: "border-fail bg-fail text-primary-foreground",
},
},
defaultVariants: { variant: "default" },
+3 -3
View File
@@ -9,9 +9,9 @@ const buttonVariants = cva(
{
variants: {
variant: {
default: "border-white bg-white text-black hover:border-focus hover:bg-focus",
destructive: "border-fail bg-fail text-black hover:bg-transparent hover:text-fail",
outline: "border-input bg-transparent text-foreground hover:border-white",
default: "border-primary bg-primary text-primary-foreground hover:border-focus hover:bg-focus",
destructive: "border-fail bg-fail text-primary-foreground hover:bg-transparent hover:text-fail",
outline: "border-input bg-transparent text-foreground hover:border-primary",
secondary: "border-transparent bg-secondary text-secondary-foreground hover:border-input",
ghost: "border-transparent bg-transparent text-muted-foreground hover:text-foreground",
link: "border-transparent text-name underline-offset-4 hover:underline",
+1 -1
View File
@@ -24,7 +24,7 @@ function ScrollBar({ className, ...props }: React.ComponentProps<typeof ScrollAr
className={cn("flex w-[6px] touch-none select-none border-l border-transparent p-0 transition-opacity", className)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 bg-[#444] hover:bg-[#888]" />
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 bg-scrollbar hover:bg-scrollbar-hover" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
);
}
+3 -3
View File
@@ -16,12 +16,12 @@ function Slider({
{...props}
>
<SliderPrimitive.Track className="relative h-[2px] w-full grow overflow-hidden bg-input">
<SliderPrimitive.Range className={cn("absolute h-full", modified ? "bg-focus" : "bg-white")} />
<SliderPrimitive.Range className={cn("absolute h-full", modified ? "bg-focus" : "bg-primary")} />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb
className={cn(
"block h-3 w-2 border-2 bg-black transition-colors focus-visible:outline-none focus-visible:border-focus disabled:pointer-events-none disabled:opacity-50",
modified ? "border-focus" : "border-white",
"block h-3 w-2 border-2 bg-background transition-colors focus-visible:outline-none focus-visible:border-focus disabled:pointer-events-none disabled:opacity-50",
modified ? "border-focus" : "border-primary",
)}
/>
</SliderPrimitive.Root>
+1 -1
View File
@@ -20,7 +20,7 @@ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPr
return (
<TabsPrimitive.Trigger
className={cn(
"-mb-[2px] inline-flex items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-3 text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-[state=active]:border-white data-[state=active]:text-foreground",
"-mb-[2px] inline-flex items-center justify-center gap-1.5 whitespace-nowrap border-b-2 border-transparent px-3 text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 data-[state=active]:border-primary data-[state=active]:text-foreground",
className,
)}
{...props}
+55 -8
View File
@@ -6,8 +6,46 @@
/* Black and white, square, hard 2px rules (after the SimpleCAD landing page).
* Color is reserved for meaning: focus (selection, what is being edited),
* pass, fail, name (the names of steps and parameters). */
/* Light is the default; `html.dark` (set before first paint from the saved choice or
* the system, see index.html and lib/theme.ts) restores the dark palette. */
:root {
--radius: 0px;
--background: #ffffff;
--foreground: #000000;
--card: #f6f6f6;
--card-foreground: #000000;
--popover: #ffffff;
--popover-foreground: #000000;
--primary: #000000;
--primary-foreground: #ffffff;
--secondary: #eeeeee;
--secondary-foreground: #000000;
--muted: #eeeeee;
--muted-foreground: #555555;
--accent: #e4e4e4;
--accent-foreground: #000000;
--destructive: #d12b3c;
--destructive-foreground: #ffffff;
--border: #cfcfcf;
--input: #9a9a9a;
--ring: #d56a00;
--focus: #d56a00;
--pass: #12803f;
--fail: #d12b3c;
--name: #1a62c4;
--comment: #6b6b6b;
--code-selection: rgba(0, 0, 0, 0.15);
--scrollbar: #bdbdbd;
--scrollbar-hover: #7a7a7a;
--selection-bg: #000000;
--selection-fg: #ffffff;
--overlay: rgba(255, 255, 255, 0.78);
--shadow-hard: rgba(0, 0, 0, 0.14);
--rule: 2px;
--mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
}
:root.dark {
--background: #000000;
--foreground: #ffffff;
--card: #050505;
@@ -31,8 +69,14 @@
--pass: #3ddc84;
--fail: #ff4d5e;
--name: #4aa3ff;
--rule: 2px;
--mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;
--comment: #777777;
--code-selection: rgba(255, 255, 255, 0.2);
--scrollbar: #333333;
--scrollbar-hover: #777777;
--selection-bg: #ffffff;
--selection-fg: #000000;
--overlay: rgba(27, 27, 27, 0.75);
--shadow-hard: rgba(255, 255, 255, 0.1);
}
@theme inline {
@@ -59,6 +103,9 @@
--color-pass: var(--pass);
--color-fail: var(--fail);
--color-name: var(--name);
--color-scrollbar: var(--scrollbar);
--color-scrollbar-hover: var(--scrollbar-hover);
--color-overlay: var(--overlay);
--radius-sm: 0px;
--radius-md: 0px;
--radius-lg: 0px;
@@ -72,17 +119,17 @@
border-radius: 0;
/* Thin, square scrollbars everywhere; the thumb shows on hover. */
scrollbar-width: thin;
scrollbar-color: #333 transparent;
scrollbar-color: var(--scrollbar) transparent;
}
*::-webkit-scrollbar {
width: 6px;
height: 6px;
}
*::-webkit-scrollbar-thumb {
background: #333;
background: var(--scrollbar);
}
*::-webkit-scrollbar-thumb:hover {
background: #777;
background: var(--scrollbar-hover);
}
*::-webkit-scrollbar-track,
*::-webkit-scrollbar-corner {
@@ -90,7 +137,7 @@
}
html,
body {
background: #000;
background: var(--background);
}
body {
@apply bg-background text-foreground;
@@ -100,8 +147,8 @@
-webkit-font-smoothing: antialiased;
}
::selection {
background: #fff;
color: #000;
background: var(--selection-bg);
color: var(--selection-fg);
}
.font-mono,
code,
+26 -15
View File
@@ -2,32 +2,43 @@ import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import { tags } from "@lezer/highlight";
/** Black cell, white code; color only where it carries meaning:
* names (blue), literals (orange), strings (green), comments (dim). */
/** Code on the cell's own ground; color only where it carries meaning: names (blue),
* literals (orange), strings (green), comments (dim). Every color is a CSS variable of
* the page (index.css), so one theme serves light and dark and follows a switch live. */
const theme = EditorView.theme(
{
"&": { color: "#ffffff", backgroundColor: "transparent", fontSize: "12px" },
".cm-content": { caretColor: "#ff9a2e", padding: "6px 0" },
".cm-cursor, .cm-dropCursor": { borderLeftColor: "#ff9a2e", borderLeftWidth: "2px" },
"&": { color: "var(--foreground)", backgroundColor: "transparent", fontSize: "12px" },
".cm-content": { caretColor: "var(--focus)", padding: "6px 0" },
".cm-cursor, .cm-dropCursor": { borderLeftColor: "var(--focus)", borderLeftWidth: "2px" },
"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
backgroundColor: "#ffffff33",
backgroundColor: "var(--code-selection)",
},
".cm-activeLine": { backgroundColor: "transparent" },
".cm-gutters": { display: "none" },
".cm-line": { padding: "0 10px" },
// completion and lint popups sit on the page, not on the cell
".cm-tooltip": {
backgroundColor: "var(--popover)",
color: "var(--popover-foreground)",
border: "2px solid var(--border)",
},
".cm-tooltip-autocomplete ul li[aria-selected]": {
backgroundColor: "var(--primary)",
color: "var(--primary-foreground)",
},
},
{ dark: true },
{ dark: false },
);
const highlight = HighlightStyle.define([
{ tag: [tags.keyword, tags.controlKeyword, tags.definitionKeyword, tags.moduleKeyword], color: "#ffffff", fontWeight: "700" },
{ tag: [tags.function(tags.variableName), tags.function(tags.propertyName)], color: "#4aa3ff" },
{ tag: [tags.definition(tags.variableName), tags.className], color: "#4aa3ff" },
{ tag: [tags.number, tags.bool, tags.null, tags.atom], color: "#ff9a2e" },
{ tag: [tags.string, tags.special(tags.string)], color: "#3ddc84" },
{ tag: [tags.comment, tags.lineComment, tags.blockComment], color: "#777777", fontStyle: "italic" },
{ tag: [tags.operator, tags.punctuation, tags.bracket], color: "#a8a8a8" },
{ tag: tags.self, color: "#ffffff", fontStyle: "italic" },
{ tag: [tags.keyword, tags.controlKeyword, tags.definitionKeyword, tags.moduleKeyword], color: "var(--foreground)", fontWeight: "700" },
{ tag: [tags.function(tags.variableName), tags.function(tags.propertyName)], color: "var(--name)" },
{ tag: [tags.definition(tags.variableName), tags.className], color: "var(--name)" },
{ tag: [tags.number, tags.bool, tags.null, tags.atom], color: "var(--focus)" },
{ tag: [tags.string, tags.special(tags.string)], color: "var(--pass)" },
{ tag: [tags.comment, tags.lineComment, tags.blockComment], color: "var(--comment)", fontStyle: "italic" },
{ tag: [tags.operator, tags.punctuation, tags.bracket], color: "var(--muted-foreground)" },
{ tag: tags.self, color: "var(--foreground)", fontStyle: "italic" },
]);
export const cadTheme = [theme, syntaxHighlighting(highlight)];
+66
View File
@@ -0,0 +1,66 @@
import { useCallback, useEffect, useState } from "react";
/** What the person chose; `system` follows the operating system. */
export type ThemePreference = "system" | "light" | "dark";
/** What is on screen. */
export type ResolvedTheme = "light" | "dark";
const KEY = "sca-theme";
const ORDER: ThemePreference[] = ["system", "light", "dark"];
const systemDark = () => window.matchMedia("(prefers-color-scheme: dark)").matches;
function readPreference(): ThemePreference {
try {
const stored = window.localStorage.getItem(KEY);
if (stored === "light" || stored === "dark" || stored === "system") return stored;
} catch {
/* private mode: the choice just does not persist */
}
return "system";
}
const resolve = (preference: ThemePreference): ResolvedTheme =>
preference === "system" ? (systemDark() ? "dark" : "light") : preference;
/** Put the theme on the page: the `dark` class selects the dark tokens, `color-scheme`
* makes native controls and scrollbars follow. index.html does the same before first paint. */
function apply(theme: ResolvedTheme) {
const root = document.documentElement;
root.classList.toggle("dark", theme === "dark");
root.style.colorScheme = theme;
}
/** The theme: a remembered preference (system, light, dark) and the theme it resolves to.
* While the preference is `system` a change of the operating system's theme is followed live. */
export function useTheme() {
const [preference, setPreference] = useState<ThemePreference>(readPreference);
const [resolved, setResolved] = useState<ResolvedTheme>(() => resolve(readPreference()));
useEffect(() => {
const update = () => {
const next = resolve(preference);
setResolved(next);
apply(next);
};
update();
if (preference !== "system") return;
const query = window.matchMedia("(prefers-color-scheme: dark)");
query.addEventListener("change", update);
return () => query.removeEventListener("change", update);
}, [preference]);
const choose = useCallback((next: ThemePreference) => {
setPreference(next);
try {
window.localStorage.setItem(KEY, next);
} catch {
/* not persisted */
}
}, []);
/** system -> light -> dark -> system */
const cycle = useCallback(() => choose(ORDER[(ORDER.indexOf(preference) + 1) % ORDER.length]), [choose, preference]);
return { preference, resolved, choose, cycle };
}
+17 -5
View File
@@ -2,11 +2,10 @@ import { useEffect, useRef } from "react";
import * as THREE from "three";
import { SceneView, type PickResult, type SelectionMode } from "@/scene/scene-view";
import { PALETTES, type SceneTheme } from "@/scene/theme";
export type { PickResult, SelectionMode };
/** Selection highlight: the "focus" ink. */
const SELECTION_COLOR = "#ff9a2e";
/** What the viewport highlights: the picked entities. */
export type Highlight = { nodeId: string; entityId: string | null };
@@ -24,6 +23,7 @@ export function Viewport({
selectionMode,
selection,
sceneVersion,
theme,
onPick,
onClear,
}: {
@@ -31,6 +31,7 @@ export function Viewport({
selectionMode: SelectionMode;
selection: Highlight[];
sceneVersion: number;
theme: SceneTheme;
onPick: (pick: PickResult) => void;
onClear: () => void;
}) {
@@ -40,6 +41,9 @@ export function Viewport({
const clearRef = useRef(onClear);
clearRef.current = onClear;
const overlayRef = useRef<THREE.Object3D[]>([]);
// The theme the view was created with; later changes go through setTheme.
const themeRef = useRef(theme);
themeRef.current = theme;
const dropOverlays = () => {
for (const object of overlayRef.current) {
@@ -62,7 +66,7 @@ export function Viewport({
onPick: (result) => pickRef.current(result),
onClear: () => clearRef.current(),
selectionMode: "solid",
background: "#000000",
theme: themeRef.current,
});
viewRef.current = view;
// Debug/agent affordance: reach the imperative scene from the console.
@@ -84,12 +88,20 @@ export function Viewport({
if (!view) return;
dropOverlays();
for (const item of selection) {
overlayRef.current.push(...view.buildEntityOverlays(item.nodeId, item.entityId, SELECTION_COLOR, 0.8));
overlayRef.current.push(...view.buildEntityOverlays(item.nodeId, item.entityId, PALETTES[theme].selection, 0.8));
}
view.engine.invalidate();
document.documentElement.dataset.overlayCount = String(overlayRef.current.length);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selection, sceneVersion]);
}, [selection, sceneVersion, theme]);
// Another theme: recolor in place (camera, model and selection stay).
useEffect(() => {
const view = viewRef.current;
if (!view) return;
view.setTheme(theme);
view.engine.invalidate();
}, [theme, viewRef]);
return <div ref={hostRef} className="h-full w-full" />;
}
+79 -26
View File
@@ -23,7 +23,8 @@ import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
import { strFromU8 } from 'fflate';
import { DEFAULT_BASE_COLOR, CAD_EDGE_COLOR, CAD_EDGE_LINE_WIDTH, cadPointToGltf, disposeObject, materialFor, placementMatrix } from '../cad-three';
import { DEFAULT_BASE_COLOR, CAD_EDGE_LINE_WIDTH, cadPointToGltf, disposeObject, materialFor, placementMatrix } from '../cad-three';
import { PALETTES, type SceneTheme, type ScenePalette } from '../theme';
import type { PackageFiles } from '../product-package';
import type { PreviewData, PreviewPart } from '../../lib/preview';
import type { Entity, EntitySidecar, FaceGroup, SceneManifest, SceneNode, Vec3 } from '../scene2';
@@ -45,6 +46,9 @@ export type CameraState = {
};
export type BRepRendererOptions = {
/** The scene's theme (default dark); `setTheme` changes it later. */
theme?: SceneTheme;
/** Overrides the theme's background (sRGB). */
background?: string;
/** GTAO ambient occlusion pass (default on). */
ssao?: boolean;
@@ -85,8 +89,8 @@ function isHiddenEdge(entity: Entity | undefined): boolean {
*/
const EDGE_DEPTH_BIAS = 0.0004;
function createEdgeMaterial(): LineMaterial {
const material = new LineMaterial({ color: CAD_EDGE_COLOR, linewidth: CAD_EDGE_LINE_WIDTH, worldUnits: false, depthTest: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 });
function createEdgeMaterial(color: string): LineMaterial {
const material = new LineMaterial({ color, linewidth: CAD_EDGE_LINE_WIDTH, worldUnits: false, depthTest: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 });
material.onBeforeCompile = (shader) => {
shader.uniforms.edgeDepthBias = { value: EDGE_DEPTH_BIAS };
shader.vertexShader = shader.vertexShader
@@ -94,6 +98,7 @@ function createEdgeMaterial(): LineMaterial {
.replace('gl_Position = clip;', 'float biasedView = -clip.w + edgeDepthBias;\n\t\t\tclip.z = (projectionMatrix[2][2] * biasedView + projectionMatrix[3][2]) / -biasedView * clip.w;\n\t\t\tgl_Position = clip;');
};
material.customProgramCacheKey = () => 'edge-depth-bias';
material.userData.role = 'edge'; // setTheme recolors these, and only these
return material;
}
@@ -119,6 +124,9 @@ export class BRepRenderer {
private ssaoPass: GTAOPass | null = null;
private ssaoEnabled: boolean;
private rendererClearColor: THREE.Color;
private palette: ScenePalette;
/** The gizmo's per-axis parts, kept to recolor on a theme change. */
private gizmoAxes: { materials: THREE.MeshBasicMaterial[]; tail: THREE.MeshBasicMaterial; canvas: HTMLCanvasElement; texture: THREE.CanvasTexture; label: string }[] = [];
private blitScene: THREE.Scene | null = null;
private blitCamera: THREE.OrthographicCamera | null = null;
private copyMaterial: THREE.MeshBasicMaterial | null = null;
@@ -151,7 +159,8 @@ export class BRepRenderer {
// color is consumed raw as linear working-space values, so convert the
// sRGB design color first — otherwise the presented background is ~4x
// brighter than intended.
this.rendererClearColor = new THREE.Color(options.background ?? '#0b0e12').convertSRGBToLinear();
this.palette = PALETTES[options.theme ?? 'dark'];
this.rendererClearColor = this.clearColorFor(options.background);
this.renderer.setClearColor(this.rendererClearColor, 1);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
@@ -386,8 +395,8 @@ export class BRepRenderer {
const extent = count * step;
const positions: number[] = [];
const colors: number[] = [];
const minor = new THREE.Color('#262626');
const major = new THREE.Color('#444444');
const minor = new THREE.Color(this.palette.gridMinor);
const major = new THREE.Color(this.palette.gridMajor);
for (let index = -count; index <= count; index += 1) {
const color = index % 5 === 0 ? major : minor;
const at = index * step;
@@ -412,28 +421,23 @@ export class BRepRenderer {
/** The three axes as blocks and letters; drawn in a corner of the canvas. */
private buildGizmo(): void {
const axes: { dir: THREE.Vector3; color: string; label: string }[] = [
{ dir: new THREE.Vector3(1, 0, 0), color: '#ff4d5e', label: 'X' },
{ dir: new THREE.Vector3(0, 1, 0), color: '#3ddc84', label: 'Y' },
{ dir: new THREE.Vector3(0, 0, 1), color: '#4aa3ff', label: 'Z' },
];
const dirs = [new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1)];
const labels = ['X', 'Y', 'Z'];
const basic = (color: string) => new THREE.MeshBasicMaterial({ color, toneMapped: false });
for (const { dir, color, label } of axes) {
const shaft = new THREE.Mesh(new THREE.BoxGeometry(0.07, 0.07, 1), basic(color));
dirs.forEach((dir, index) => {
const color = this.palette.axes[index];
const shaftMaterial = basic(color);
const tipMaterial = basic(color);
const tailMaterial = basic(this.palette.axisTail);
const shaft = new THREE.Mesh(new THREE.BoxGeometry(0.07, 0.07, 1), shaftMaterial);
shaft.position.copy(dir).multiplyScalar(0.5);
shaft.lookAt(dir);
const tip = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), basic(color));
const tip = new THREE.Mesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), tipMaterial);
tip.position.copy(dir);
const tail = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.12), basic('#555555'));
const tail = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.12, 0.12), tailMaterial);
tail.position.copy(dir).multiplyScalar(-1);
const canvas = document.createElement('canvas');
canvas.width = canvas.height = 64;
const context = canvas.getContext('2d')!;
context.font = '700 44px ui-monospace, SFMono-Regular, Menlo, monospace';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = color;
context.fillText(label, 32, 34);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
@@ -441,8 +445,57 @@ export class BRepRenderer {
);
sprite.scale.set(0.42, 0.42, 1);
sprite.position.copy(dir).multiplyScalar(1.38);
this.gizmoAxes.push({ materials: [shaftMaterial, tipMaterial], tail: tailMaterial, canvas, texture, label: labels[index] });
this.paintGizmoLabel(this.gizmoAxes[index], color);
this.gizmoScene.add(shaft, tip, tail, sprite);
}
});
}
private vertexMaterial(): THREE.PointsMaterial {
const material = new THREE.PointsMaterial({ color: this.palette.vertex, size: 7, sizeAttenuation: false, depthWrite: false, transparent: true, opacity: 0.48 });
material.userData.role = 'vertex';
return material;
}
private paintGizmoLabel(axis: { canvas: HTMLCanvasElement; texture: THREE.CanvasTexture; label: string }, color: string): void {
const context = axis.canvas.getContext('2d')!;
context.clearRect(0, 0, 64, 64);
context.font = '700 44px ui-monospace, SFMono-Regular, Menlo, monospace';
context.textAlign = 'center';
context.textBaseline = 'middle';
context.fillStyle = color;
context.fillText(axis.label, 32, 34);
axis.texture.needsUpdate = true;
}
/** The viewport background as a linear color: sRGB design value, brightened by the
* theme's boost so the tone-mapped result is the page's own background. */
private clearColorFor(background?: string): THREE.Color {
const color = new THREE.Color(background ?? this.palette.clear).convertSRGBToLinear();
if (background === undefined) color.multiplyScalar(this.palette.clearBoost);
return color;
}
/** Switch the scene to another theme in place: background, edges, grid, gizmo, vertex
* points. The camera, the model and any selection overlay stay as they are. */
setTheme(theme: SceneTheme): void {
this.palette = PALETTES[theme];
this.rendererClearColor = this.clearColorFor();
this.renderer.setClearColor(this.rendererClearColor, 1);
this.modelRoot.traverse((object) => {
const material = (object as THREE.Mesh).material as THREE.Material | THREE.Material[] | undefined;
if (!material || Array.isArray(material)) return;
if (material.userData.role === 'edge') (material as LineMaterial).color.set(this.palette.edge);
else if (material.userData.role === 'vertex') (material as THREE.PointsMaterial).color.set(this.palette.vertex);
});
this.gizmoAxes.forEach((axis, index) => {
const color = this.palette.axes[index];
axis.materials.forEach((material) => material.color.set(color));
axis.tail.color.set(this.palette.axisTail);
this.paintGizmoLabel(axis, color);
});
this.updateGrid();
this.needsRender = true;
}
private renderGizmo(): void {
@@ -622,7 +675,7 @@ export class BRepRenderer {
this.previewGeometries.push(faces, pick, edges, ...(vertices ? [vertices] : []));
return { faces, pick, edges, vertices, sidecar };
};
const edgeMaterial = createEdgeMaterial();
const edgeMaterial = createEdgeMaterial(this.palette.edge);
const size = this.resolution();
edgeMaterial.resolution.set(Math.max(size.width, 1), Math.max(size.height, 1));
for (const item of preview.nodes) {
@@ -662,7 +715,7 @@ export class BRepRenderer {
}
group.add(pickEdges);
if (geometry.vertices) {
const points = new THREE.Points(geometry.vertices, new THREE.PointsMaterial({ color: '#d8ff83', size: 7, sizeAttenuation: false, depthWrite: false, transparent: true, opacity: 0.48 }));
const points = new THREE.Points(geometry.vertices, this.vertexMaterial());
points.visible = false;
points.userData.pickRole = 'vertex';
points.userData.pickable = true;
@@ -728,7 +781,7 @@ export class BRepRenderer {
});
const vertexGeometry = new THREE.BufferGeometry();
vertexGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const vertexPoints = new THREE.Points(vertexGeometry, new THREE.PointsMaterial({ color: '#d8ff83', size: 7, sizeAttenuation: false, depthWrite: false, transparent: true, opacity: 0.48 }));
const vertexPoints = new THREE.Points(vertexGeometry, this.vertexMaterial());
vertexPoints.visible = false;
vertexPoints.userData.pickRole = 'vertex';
vertexPoints.userData.pickable = true;
@@ -783,7 +836,7 @@ export class BRepRenderer {
geometry.setPositions(positions);
// Negative slope-scaled offset mirrors the faces' push (see materialFor):
// keeps silhouette edges continuous where a flat bias loses.
const material = createEdgeMaterial();
const material = createEdgeMaterial(this.palette.edge);
const size = this.resolution();
material.resolution.set(Math.max(size.width, 1), Math.max(size.height, 1));
const visual = new LineSegments2(geometry, material);
+9 -1
View File
@@ -4,6 +4,7 @@
// modes and annotation marks. All rendering — materials, edge display,
// lighting, ambient occlusion, camera — lives in the renderer component.
import type { SceneTheme } from './theme';
import * as THREE from 'three';
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
@@ -36,6 +37,8 @@ export type SceneViewOptions = {
onClear?: () => void;
selectionMode?: SelectionMode;
background?: string;
/** The scene's theme (default dark). */
theme?: SceneTheme;
interactive?: boolean;
/** GTAO ambient occlusion (default on). */
ssao?: boolean;
@@ -61,7 +64,7 @@ export class SceneView {
this.onPick = options.onPick ?? null;
this.onClear = options.onClear ?? null;
this.selectionMode = options.selectionMode ?? 'face';
this.engine = new BRepRenderer(host, { background: options.background, ssao: options.ssao, seams: options.seams });
this.engine = new BRepRenderer(host, { background: options.background, theme: options.theme, ssao: options.ssao, seams: options.seams });
if (options.interactive !== false) {
this.unbindClick = bindClickSelection({
element: this.engine.domElement,
@@ -339,6 +342,11 @@ export class SceneView {
this.engine.setSeamsVisible(visible);
}
/** Recolor the scene for another theme without reloading it. */
setTheme(theme: SceneTheme): void {
this.engine.setTheme(theme);
}
setSSAO(enabled: boolean): void {
this.engine.invalidate();
this.engine.setSSAO(enabled);
+47
View File
@@ -0,0 +1,47 @@
/** The colors of the 3D scene in each theme. The page's own colors are CSS variables
* (src/index.css); the scene is drawn by three.js and needs its own copy. */
export type SceneTheme = 'light' | 'dark';
export interface ScenePalette {
/** Viewport background, sRGB. */
clear: string;
/** Multiplier on the linear background: the present pass tone-maps it (ACES), which
* leaves a pure white at about 0.9; a brighter input lands on the page's white. */
clearBoost: number;
/** Outline color of the model's edges. */
edge: string;
gridMinor: string;
gridMajor: string;
/** X, Y, Z. */
axes: [string, string, string];
/** The negative end of each axis. */
axisTail: string;
vertex: string;
/** Highlight of picked entities. */
selection: string;
}
export const PALETTES: Record<SceneTheme, ScenePalette> = {
dark: {
clear: '#000000',
clearBoost: 1,
edge: '#3a414d',
gridMinor: '#262626',
gridMajor: '#444444',
axes: ['#ff4d5e', '#3ddc84', '#4aa3ff'],
axisTail: '#555555',
vertex: '#d8ff83',
selection: '#ff9a2e',
},
light: {
clear: '#ffffff',
clearBoost: 8,
edge: '#1b1f27',
gridMinor: '#e0e0e0',
gridMajor: '#bdbdbd',
axes: ['#d12b3c', '#12803f', '#1a62c4'],
axisTail: '#9a9a9a',
vertex: '#2a7a00',
selection: '#d56a00',
},
};