跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

appearance-settings.jsx

797 行 · 24.5 KB历史下载
1import { InlineSelect } from "./inline-select";
2import React, { useEffect, useRef, useState } from "react";
3import {
4 Check,
5 ChevronDown,
6 Download,
7 LoaderCircle,
8 Monitor,
9 Moon,
10 Sun,
11 Upload,
12 RotateCcw,
13 CircleCheck,
14 TriangleAlert,
15 CircleX,
16} from "lucide-react";
17import { api, native, nativeAvailable } from "./api";
18import { useAppearance } from "./appearance";
19import {
20 colorGroups,
21 colorTokens,
22 terminalColorGroups,
23 terminalTheme,
24 customThemeLimit,
25 themeFileLimit,
26 parseThemeDocument,
27 themeDocument,
28 validateThemeName,
29 sameTheme,
30 presets,
31 presetNames,
32 presetInfo,
33 presetGroups,
34 themeCatalog,
35 applyThemePreset,
36 systemUIFont,
37 systemCodeFont,
38 themeVariables,
39} from "./appearance-state.mjs";
40
41function SettingRow({ label, description, children }) {
42 return (
43 <div className="appearance-row">
44 <div>
45 <span>{label}</span>
46 {description && <p>{description}</p>}
47 </div>
48 <div className="appearance-control">{children}</div>
49 </div>
50 );
51}
52function FontSizeInput({ label, value, min, onChange }) {
53 const [text, setText] = useState(String(value));
54 useEffect(() => setText(String(value)), [value]);
55 return (
56 <div className="font-size-control">
57 <input
58 aria-label={label}
59 type="number"
60 min={min}
61 max="24"
62 value={text}
63 onChange={(event) => {
64 setText(event.target.value);
65 const number = Number(event.target.value);
66 if (Number.isInteger(number) && number >= min && number <= 24)
67 onChange(number);
68 }}
69 onBlur={() => setText(String(value))}
70 />
71 <span>px</span>
72 </div>
73 );
74}
75function ColorField({ label, value, onChange, onReset }) {
76 const [text, setText] = useState(value);
77 useEffect(() => setText(value), [value]);
78 const invalid = !/^#[0-9a-fA-F]{6}$/.test(text);
79 const commit = () => {
80 if (!invalid && text !== value) onChange(text.toLowerCase());
81 };
82 return (
83 <div className="theme-color-field">
84 <span>{label.replace(/^(浅色|深色)主题(终端)?/, "")}</span>
85 <div className="theme-color-value">
86 <input
87 type="color"
88 aria-label={label + "取色"}
89 value={value}
90 onChange={(e) => onChange(e.target.value)}
91 />
92 <input
93 type="text"
94 aria-label={label}
95 aria-invalid={invalid}
96 value={text}
97 maxLength={7}
98 spellCheck={false}
99 onChange={(e) => setText(e.target.value)}
100 onBlur={commit}
101 onKeyDown={(e) => {
102 if (e.key === "Enter") {
103 e.preventDefault();
104 commit();
105 }
106 if (e.key === "Escape") {
107 e.stopPropagation();
108 setText(value);
109 }
110 }}
111 />
112 {onReset && (
113 <button
114 className="icon-button"
115 aria-label={label + "恢复自动"}
116 title="恢复自动颜色"
117 onClick={onReset}
118 >
119 <RotateCcw size={13} />
120 </button>
121 )}
122 </div>
123 {invalid && (
124 <small className="theme-color-error">请输入 # 加六位十六进制颜色</small>
125 )}
126 </div>
127 );
128}
129function ThemeCard({ variant, value, active, onChange }) {
130 const [advanced, setAdvanced] = useState(false);
131 const label = variant === "light" ? "浅色主题" : "深色主题";
132 const options = presets[variant];
133 const patch = (delta) => onChange({ ...value, preset: "custom", ...delta });
134 const vars = themeVariables(value, variant);
135 const terminal = terminalTheme(value, variant);
136 const setColor = (field, key, color) => {
137 const next = { ...value[field] };
138 if (color === undefined) delete next[key];
139 else next[key] = color;
140 patch({ [field]: next });
141 };
142 return (
143 <section
144 className={`appearance-theme-card ${active ? "current" : ""}`}
145 aria-label={label}
146 >
147 <div className="theme-card-heading">
148 <strong>{label}</strong>
149 {active && <small>当前使用</small>}
150 <InlineSelect
151 aria-label={label + "预设"}
152 value={value.preset}
153 onValueChange={(next) =>
154 onChange(applyThemePreset(value, variant, next))
155 }
156 >
157 {presetGroups.map((group) => (
158 <optgroup key={group} label={group}>
159 {themeCatalog
160 .filter((item) => item.group === group && options[item.id])
161 .map((item) => (
162 <option key={item.id} value={item.id}>
163 {item.name}
164 </option>
165 ))}
166 </optgroup>
167 ))}
168 {!options[value.preset] && (
169 <option value={value.preset} disabled>
170 {presetNames[value.preset] || "自定义"}
171 </option>
172 )}
173 </InlineSelect>
174 </div>
175 <div
176 className="theme-miniature"
177 aria-hidden="true"
178 style={{ ...vars, background: value.surface, color: value.ink }}
179 >
180 <div className="mini-sidebar" style={{ background: vars["--sidebar"] }}>
181 <i />
182 <i />
183 <i />
184 </div>
185 <div className="mini-content">
186 <span style={{ background: vars["--strong"] }} />
187 <span />
188 <div
189 style={{ borderColor: vars["--line"], background: vars["--input"] }}
190 >
191 <i />
192 <b style={{ background: value.accent }} />
193 </div>
194 </div>
195 </div>
196 <div className="theme-preset-summary">
197 <p>
198 {presetInfo[value.preset]?.description ||
199 "自定义配色,可另存为主题以便下次使用。"}
200 </p>
201 <div
202 className="theme-status-preview"
203 aria-label={label + "状态配色预览"}
204 style={{ background: value.surface }}
205 >
206 <span style={{ color: vars["--success"] }}>
207 <CircleCheck size={13} />
208 成功
209 </span>
210 <span style={{ color: vars["--warning"] }}>
211 <TriangleAlert size={13} />
212 警告
213 </span>
214 <span style={{ color: vars["--danger"] }}>
215 <CircleX size={13} />
216 错误
217 </span>
218 </div>
219 </div>
220 <div className="theme-base-colors">
221 {[
222 ["accent", "强调色"],
223 ["surface", "背景"],
224 ["ink", "文字"],
225 ].map(([key, name]) => (
226 <ColorField
227 key={key}
228 label={label + name}
229 value={value[key]}
230 onChange={(color) => patch({ [key]: color })}
231 />
232 ))}
233 </div>
234 <button
235 className="theme-customize"
236 onClick={() => setAdvanced(!advanced)}
237 aria-expanded={advanced}
238 >
239 自定义
240 <ChevronDown size={14} className={advanced ? "rotated" : ""} />
241 </button>
242 {advanced && (
243 <div className="theme-options">
244 <p className="theme-options-hint">
245 未单独设置的颜色随基础配色自动调整。
246 </p>
247 {colorGroups.map((group) => (
248 <details className="theme-color-group" key={group.label}>
249 <summary>{group.label}</summary>
250 {group.entries.map(([key, name]) => (
251 <ColorField
252 key={key}
253 label={label + name}
254 value={vars[colorTokens[key]]}
255 onChange={(color) => setColor("colors", key, color)}
256 onReset={
257 value.colors?.[key]
258 ? () => setColor("colors", key)
259 : undefined
260 }
261 />
262 ))}
263 </details>
264 ))}
265 {terminalColorGroups.map((group) => (
266 <details className="theme-color-group" key={group.label}>
267 <summary>{group.label}</summary>
268 {group.entries.map(([key, name]) => (
269 <ColorField
270 key={key}
271 label={label + "终端" + name}
272 value={terminal[key]}
273 onChange={(color) => setColor("terminal", key, color)}
274 onReset={
275 value.terminal?.[key]
276 ? () => setColor("terminal", key)
277 : undefined
278 }
279 />
280 ))}
281 </details>
282 ))}
283 <div
284 className="theme-terminal-preview"
285 style={{
286 background: terminal.background,
287 color: terminal.foreground,
288 }}
289 aria-label={label + "终端预览"}
290 >
291 <span style={{ color: terminal.green }}>~/cage</span> ${" "}
292 <span style={{ color: terminal.blue }}>echo</span> hello
293 <i style={{ background: terminal.cursor }} />
294 </div>
295 <button
296 className="theme-reset-colors"
297 disabled={
298 !Object.keys(value.colors || {}).length &&
299 !Object.keys(value.terminal || {}).length
300 }
301 onClick={() => patch({ colors: {}, terminal: {} })}
302 >
303 <RotateCcw size={13} />
304 恢复全部自动颜色
305 </button>
306 <label>
307 对比度 <output>{value.contrast}</output>
308 <input
309 aria-label={label + "对比度"}
310 type="range"
311 min="0"
312 max="100"
313 value={value.contrast}
314 onChange={(e) => patch({ contrast: Number(e.target.value) })}
315 />
316 </label>
317 <label>
318 界面字体
319 <InlineSelect editable
320 aria-label={label + "界面字体"}
321 value={value.fonts.ui}
322 placeholder="系统默认"
323 onValueChange={(next) =>
324 patch({ fonts: { ...value.fonts, ui: next } })
325 }
326 >
327 <option value="system-ui" />
328 <option value="PingFang SC" />
329 <option value="Helvetica Neue" />
330 <option value="Arial" />
331 </InlineSelect>
332 </label>
333 <label>
334 代码字体
335 <InlineSelect editable
336 aria-label={label + "代码字体"}
337 value={value.fonts.code}
338 placeholder="系统等宽字体"
339 onValueChange={(next) =>
340 patch({ fonts: { ...value.fonts, code: next } })
341 }
342 >
343 <option value="SF Mono" />
344 <option value="Menlo" />
345 <option value="Monaco" />
346 <option value="JetBrains Mono" />
347 </InlineSelect>
348 </label>
349 <label className="appearance-switch">
350 <span>半透明侧栏</span>
351 <input
352 type="checkbox"
353 role="switch"
354 aria-label={label + "半透明侧栏"}
355 checked={!value.opaqueWindows}
356 onChange={(e) => patch({ opaqueWindows: !e.target.checked })}
357 />
358 </label>
359 </div>
360 )}
361 </section>
362 );
363}
364function ThemeLibrary({ appearance, update, saving, onError }) {
365 const themes = appearance.customThemes;
366 const matching = themes.find((item) => sameTheme(item, appearance));
367 const [selectedId, setSelectedId] = useState(matching?.id || "");
368 const [name, setName] = useState(matching?.name || "");
369 const [busy, setBusy] = useState(false);
370 const [notice, setNotice] = useState("");
371 const input = useRef(null);
372 const selected = themes.find((item) => item.id === selectedId);
373 const current = selected || matching;
374 const dirty = current && !sameTheme(current, appearance);
375 const run = async (task) => {
376 setBusy(true);
377 setNotice("");
378 onError("");
379 try {
380 await task();
381 } catch (e) {
382 onError(e.message);
383 } finally {
384 setBusy(false);
385 }
386 };
387 const apply = (item) => {
388 setSelectedId(item.id);
389 setName(item.name);
390 setNotice("");
391 onError("");
392 void update((previous) => ({
393 ...previous,
394 lightTheme: structuredClone(item.lightTheme),
395 darkTheme: structuredClone(item.darkTheme),
396 }));
397 };
398 const save = (replace) =>
399 run(async () => {
400 const title = validateThemeName(name);
401 if (!replace && themes.length >= customThemeLimit)
402 throw new Error("最多保存 50 个自定义主题,请先删除不需要的主题");
403 const document = themeDocument(title, appearance);
404 const item = {
405 id: replace ? current.id : crypto.randomUUID(),
406 name: title,
407 lightTheme: document.lightTheme,
408 darkTheme: document.darkTheme,
409 };
410 if (
411 await update((previous) => ({
412 ...previous,
413 customThemes: replace
414 ? previous.customThemes.map((old) =>
415 old.id === item.id ? item : old,
416 )
417 : [...previous.customThemes, item],
418 }))
419 ) {
420 setSelectedId(item.id);
421 setName(title);
422 setNotice("主题已保存");
423 }
424 });
425 const importText = async (text) => {
426 const document = parseThemeDocument(text);
427 if (themes.length >= customThemeLimit)
428 throw new Error("最多保存 50 个自定义主题,请先删除不需要的主题");
429 const item = {
430 id: crypto.randomUUID(),
431 name: document.name,
432 lightTheme: document.lightTheme,
433 darkTheme: document.darkTheme,
434 };
435 if (
436 await update((previous) => ({
437 ...previous,
438 lightTheme: item.lightTheme,
439 darkTheme: item.darkTheme,
440 customThemes: [...previous.customThemes, item],
441 }))
442 ) {
443 setSelectedId(item.id);
444 setName(item.name);
445 setNotice("主题已导入并应用");
446 }
447 };
448 const importFile = () => {
449 if (!nativeAvailable()) {
450 input.current.click();
451 return;
452 }
453 void run(async () => {
454 const text = await native("importTheme");
455 if (text) await importText(text);
456 });
457 };
458 const exportFile = () =>
459 run(async () => {
460 const title = name.trim() || matching?.name || "我的主题";
461 const text =
462 JSON.stringify(themeDocument(title, appearance), null, 2) + "\n";
463 const filename =
464 title
465 .replace(/[<>:"/\\|?*\x00-\x1f]/g, "_")
466 .replace(/[. ]+$/, "")
467 .slice(0, 80) + ".cage-theme.json";
468 if (nativeAvailable()) {
469 if (await native("exportTheme", { text, filename }))
470 setNotice("主题已导出");
471 } else {
472 const url = URL.createObjectURL(
473 new Blob([text], { type: "application/json" }),
474 );
475 const link = document.createElement("a");
476 link.href = url;
477 link.download = filename;
478 document.body.append(link);
479 link.click();
480 link.remove();
481 setTimeout(() => URL.revokeObjectURL(url), 1000);
482 setNotice("已开始下载主题文件");
483 }
484 });
485 return (
486 <section className="theme-library" aria-label="我的主题">
487 <div className="theme-library-heading">
488 <div>
489 <h4>我的主题</h4>
490 <p>保存浅色、深色两套配色与字体,随时切换或分享。</p>
491 </div>
492 <div className="theme-file-actions">
493 <button disabled={busy || saving} onClick={importFile}>
494 <Upload size={14} />
495 导入主题
496 </button>
497 <button disabled={busy} onClick={exportFile}>
498 <Download size={14} />
499 导出主题
500 </button>
501 </div>
502 </div>
503 <input
504 ref={input}
505 type="file"
506 accept=".json,application/json"
507 hidden
508 aria-label="选择主题文件"
509 onChange={(e) => {
510 const file = e.target.files?.[0];
511 e.target.value = "";
512 if (file)
513 void run(async () => {
514 if (file.size > themeFileLimit)
515 throw new Error("主题文件不能超过 256 KB");
516 await importText(await file.text());
517 });
518 }}
519 />
520 <div className="theme-library-fields">
521 <InlineSelect
522 aria-label="已保存的主题"
523 value={current?.id || ""}
524 disabled={busy || saving}
525 onValueChange={(next) => {
526 const item = themes.find((theme) => theme.id === next);
527 if (item) apply(item);
528 }}
529 >
530 <option value="" disabled>
531 {themes.length ? "选择已保存的主题" : "尚无自定义主题"}
532 </option>
533 {themes.map((item) => (
534 <option key={item.id} value={item.id}>
535 {item.name}
536 {item.id === current?.id && dirty ? " · 已修改" : ""}
537 </option>
538 ))}
539 </InlineSelect>
540 <input
541 aria-label="主题名称"
542 placeholder="为当前配色命名"
543 value={name}
544 maxLength={80}
545 onChange={(e) => setName(e.target.value)}
546 />
547 <button
548 disabled={busy || saving || !name.trim()}
549 onClick={() => save(false)}
550 >
551 另存为主题
552 </button>
553 </div>
554 {current && (
555 <div className="theme-library-manage">
556 <span>
557 {dirty ? "当前配色有未存入主题的修改" : "当前配色与已保存主题一致"}
558 </span>
559 {dirty && (
560 <button disabled={busy || saving} onClick={() => apply(current)}>
561 恢复已保存配色
562 </button>
563 )}
564 <button
565 disabled={busy || saving || !name.trim()}
566 onClick={() => save(true)}
567 >
568 更新此主题
569 </button>
570 <button
571 disabled={busy || saving}
572 onClick={() =>
573 run(async () => {
574 if (!confirm(`删除主题“${current.name}”?当前配色会保留。`))
575 return;
576 if (
577 await update((previous) => ({
578 ...previous,
579 customThemes: previous.customThemes.filter(
580 (item) => item.id !== current.id,
581 ),
582 }))
583 ) {
584 setSelectedId("");
585 setName("");
586 setNotice("主题已删除,当前配色已保留");
587 }
588 })
589 }
590 >
591 删除
592 </button>
593 </div>
594 )}
595 {notice && (
596 <p className="theme-library-notice" role="status">
597 {notice}
598 </p>
599 )}
600 </section>
601 );
602}
603export function AppearanceSettings() {
604 const { appearance, theme, variant, loading, saving, error, update, retry } =
605 useAppearance();
606 const [syncing, setSyncing] = useState(false),
607 [syncError, setSyncError] = useState(""),
608 [synced, setSynced] = useState(false),
609 [themeError, setThemeError] = useState("");
610 const patch = (delta) => update((previous) => ({ ...previous, ...delta }));
611 const sync = async () => {
612 setSyncing(true);
613 setSyncError("");
614 setSynced(false);
615 try {
616 const value = await api("/appearance/codex");
617 if (
618 await update((previous) => ({
619 ...value,
620 customThemes: previous.customThemes,
621 }))
622 )
623 setSynced(true);
624 } catch (e) {
625 setSyncError(e.message);
626 } finally {
627 setSyncing(false);
628 }
629 };
630 return (
631 <div className="appearance-settings">
632 <div className="section-title">
633 <h3>外观</h3>
634 <p>更改自动保存并即时生效,无需重启项目。</p>
635 </div>
636 <fieldset disabled={loading || syncing} className="appearance-fields">
637 <SettingRow
638 label="主题"
639 description="跟随系统,或固定使用浅色、深色外观。"
640 >
641 <div className="appearance-mode" role="group" aria-label="主题模式">
642 {[
643 ["light", "浅色", Sun],
644 ["dark", "深色", Moon],
645 ["system", "跟随系统", Monitor],
646 ].map(([mode, label, Icon]) => (
647 <button
648 key={mode}
649 aria-pressed={appearance.mode === mode}
650 onClick={() => patch({ mode })}
651 >
652 <Icon size={15} />
653 {label}
654 </button>
655 ))}
656 </div>
657 </SettingRow>
658 <ThemeLibrary
659 key={String(loading)}
660 appearance={appearance}
661 update={update}
662 saving={saving}
663 onError={setThemeError}
664 />
665 {themeError && (
666 <div className="error-message" role="alert">
667 {themeError}
668 </div>
669 )}
670 <div className="theme-card-grid">
671 {["light", "dark"].map((key) => (
672 <ThemeCard
673 key={key}
674 variant={key}
675 value={appearance[key + "Theme"]}
676 active={variant === key}
677 onChange={(value) => patch({ [key + "Theme"]: value })}
678 />
679 ))}
680 </div>
681 <h4>字体</h4>
682 <SettingRow
683 label="界面字号"
684 description="调整导航、标签和设置中的文字大小。"
685 >
686 <FontSizeInput
687 label="界面字号"
688 value={appearance.uiFontSize}
689 min={12}
690 onChange={(value) => patch({ uiFontSize: value })}
691 />
692 </SettingRow>
693 <SettingRow
694 label="代码字号"
695 description="调整内置终端与代码预览的文字大小。"
696 >
697 <FontSizeInput
698 label="代码字号"
699 value={appearance.codeFontSize}
700 min={10}
701 onChange={(value) => patch({ codeFontSize: value })}
702 />
703 </SettingRow>
704 <div
705 className="appearance-sample"
706 style={{ fontFamily: theme.fonts.ui || systemUIFont }}
707 >
708 <span>在熟悉的工作区,专注下一步。</span>
709 <code
710 style={{
711 fontFamily: theme.fonts.code || systemCodeFont,
712 fontSize: appearance.codeFontSize,
713 }}
714 >
715 const workspace = "Cage";
716 </code>
717 </div>
718 <h4>显示与交互</h4>
719 <SettingRow
720 label="使用指针光标"
721 description="悬停在按钮等可交互元素上时显示手形。"
722 >
723 <label className="appearance-switch">
724 <input
725 type="checkbox"
726 role="switch"
727 aria-label="使用指针光标"
728 checked={appearance.pointerCursors}
729 onChange={(e) => patch({ pointerCursors: e.target.checked })}
730 />
731 </label>
732 </SettingRow>
733 <SettingRow label="字体平滑">
734 <label className="appearance-switch">
735 <input
736 type="checkbox"
737 role="switch"
738 aria-label="字体平滑"
739 checked={appearance.fontSmoothing}
740 onChange={(e) => patch({ fontSmoothing: e.target.checked })}
741 />
742 </label>
743 </SettingRow>
744 <SettingRow label="减少动态效果">
745 <InlineSelect
746 aria-label="减少动态效果"
747 value={appearance.reducedMotion}
748 onValueChange={(next) => patch({ reducedMotion: next })}
749 >
750 <option value="system">跟随系统</option>
751 <option value="on">开启</option>
752 <option value="off">关闭</option>
753 </InlineSelect>
754 </SettingRow>
755 <div className="appearance-import">
756 <div>
757 <strong>沿用 Codex 的外观</strong>
758 <p>导入本机 Codex 当前的主题、配色与字体偏好。</p>
759 </div>
760 <button onClick={sync}>
761 {syncing ? (
762 <LoaderCircle size={15} className="spin" />
763 ) : (
764 <Download size={15} />
765 )}
766 从本机 Codex 同步
767 </button>
768 </div>
769 </fieldset>
770 <div className="appearance-save-state" role="status">
771 {saving ? (
772 <>
773 <LoaderCircle size={13} className="spin" />
774 正在保存…
775 </>
776 ) : error ? (
777 <>
778 <span>未保存</span>
779 <button className="text-button" onClick={retry}>
780 重试保存
781 </button>
782 </>
783 ) : (
784 <>
785 <Check size={14} />
786 {synced ? "已同步 Codex 外观" : "更改自动保存,即时生效"}
787 </>
788 )}
789 </div>
790 {(error || syncError) && (
791 <div className="error-message" role="alert">
792 {syncError || error}
793 </div>
794 )}
795 </div>
796 );
797}