Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
feat(editor): curated backgrounds first, one-colour gradient behind Custom
EtienneLescotc71646e4f498
diff --git a/src/components/ai-edition/ColorField.tsx b/src/components/ai-edition/ColorField.tsxindex 2b2d2aae6..12f433010 100644--- a/src/components/ai-edition/ColorField.tsx+++ b/src/components/ai-edition/ColorField.tsx@@ -54,6 +54,8 @@ interface ColorFieldProps {label: string;disabled?: boolean;presets?: readonly string[];+ /** What the closed swatch shows, when it is not the colour itself (a gradient made from it). */+ swatch?: string;}export function ColorField({@@ -63,6 +65,7 @@ export function ColorField({label,disabled,presets = COLOR_PRESETS,+ swatch = value,}: ColorFieldProps) {const ts = useScopedT("settings");const te = useScopedT("editor");@@ -111,7 +114,7 @@ export function ColorField({width: "100%",height: "100%",borderRadius: 7,- background: value,+ background: swatch,boxShadow: "inset 0 0 0 1px rgb(0 0 0 / 0.25)",}}/>diff --git a/src/components/ai-edition/NewEditorShell.module.css b/src/components/ai-edition/NewEditorShell.module.cssindex c901ed8b0..1384776eb 100644--- a/src/components/ai-edition/NewEditorShell.module.css+++ b/src/components/ai-edition/NewEditorShell.module.css@@ -1313,21 +1313,6 @@ textarea.control {border-color: var(--accent);color: var(--accent);}-.bgDisclosure {- display: inline-flex;- align-items: center;- gap: 4px;- margin: 0 var(--sp-4) 12px;- padding: 0;- border: 0;- background: transparent;- color: var(--fg-2);- font: 500 13px/1.2 var(--font-body);- cursor: pointer;-}-.bgDisclosure:hover { color: var(--fg); }-.bgDisclosure svg { transition: transform var(--motion-fast) var(--ease); }-.bgDisclosure[aria-expanded="true"] svg { transform: rotate(180deg); }/* The export dialog's "Advanced" disclosure. Its own class: it must not ride on a pane's. */.exportAdvanced {display: inline-flex;@@ -1350,27 +1335,6 @@ textarea.control {box-shadow: 0 0 0 2px color-mix(in oklab, var(--brand), transparent 70%);}-/* Remove Chromium's built-in inset so the selected colour fills the rounded control. */-.bgColorInput {- box-sizing: border-box;- width: 48px;- height: 34px;- padding: 0;- border: 1px solid var(--border);- border-radius: 10px;- background: var(--surface);- cursor: pointer;-}-.bgColorInput::-webkit-color-swatch-wrapper { padding: 0; }-.bgColorInput::-webkit-color-swatch {- border: 0;- border-radius: 9px;-}-.bgColorInput::-moz-color-swatch {- border: 0;- border-radius: 9px;-}-.captionsPopover {width: 310px;display: flex;diff --git a/src/components/ai-edition/RightPanes.backgroundPicker.test.tsx b/src/components/ai-edition/RightPanes.backgroundPicker.test.tsxnew file mode 100644index 000000000..617bdda8c--- /dev/null+++ b/src/components/ai-edition/RightPanes.backgroundPicker.test.tsx@@ -0,0 +1,96 @@+// @vitest-environment jsdom+// The background picker offers the curated set first. The free choice sits behind one "Custom"+// swatch per tab, and on the gradient tab that choice is ONE colour, turned into a two-stop+// gradient the compositor draws exactly as the swatch shows it.++import "@testing-library/jest-dom";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@/contexts/I18nContext";+import { LOCALE_STORAGE_KEY } from "@/i18n/config";+import { parseCssGradient } from "@/lib/exporter/gradientParser";+import { WallpaperPicker } from "./RightPanes";++beforeAll(() => {+ // The Radix popover measures its anchor; jsdom has no ResizeObserver.+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe = () => undefined;+ unobserve = () => undefined;+ disconnect = () => undefined;+ },+ );+});++beforeEach(() => {+ localStorage.clear();+ localStorage.setItem(LOCALE_STORAGE_KEY, "en");+});++afterEach(() => {+ cleanup();+ localStorage.clear();+});++function renderPicker(value: string) {+ const onChange = vi.fn();+ const onLiveChange = vi.fn();+ const onCommit = vi.fn();+ render(+ <I18nProvider>+ <WallpaperPicker+ value={value}+ hasDocument+ onChange={onChange}+ onLiveChange={onLiveChange}+ onCommit={onCommit}+ onPickFile={() => undefined}+ updateNativeBackground={false}+ />+ </I18nProvider>,+ );+ return { onChange, onLiveChange, onCommit };+}++/** True when `a` comes before `b` in the document. */+function precedes(a: Element, b: Element): boolean {+ return Boolean(a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING);+}++describe("gradient tab", () => {+ const current = "linear-gradient(135deg, #3b82f6, #8b5cf6)";++ it("shows the curated gradients before the custom one", () => {+ renderPicker(current);+ const custom = screen.getByRole("button", { name: "Gradient from one color" });+ const presets = screen.getAllByRole("button", { name: /^Gradient \d+$/ });+ expect(presets.length).toBeGreaterThan(0);+ for (const preset of presets) expect(precedes(preset, custom)).toBe(true);+ });++ it("turns one picked colour into a two-stop gradient", () => {+ const { onLiveChange, onCommit } = renderPicker(current);+ fireEvent.click(screen.getByRole("button", { name: "Gradient from one color" }));+ fireEvent.click(screen.getByRole("button", { name: /#ec4899/ }));++ const written = onLiveChange.mock.calls.at(-1)?.[0] as string;+ const stops = parseCssGradient(written)?.stops.map((s) => s.color);+ expect(stops).toHaveLength(2);+ expect(stops?.[0]).toBe("#ec4899");+ expect(onCommit).toHaveBeenCalled();+ });+});++describe("color tab", () => {+ it("shows the palette before the custom colour, and writes what is picked there", () => {+ const { onLiveChange } = renderPicker("#16171d");+ const custom = screen.getByRole("button", { name: "Custom color" });+ for (const swatch of screen.getAllByRole("button", { name: /^Color #/ })) {+ expect(precedes(swatch, custom)).toBe(true);+ }+ fireEvent.click(custom);+ fireEvent.click(screen.getByRole("button", { name: /#0ea5e9/ }));+ expect(onLiveChange).toHaveBeenLastCalledWith("#0ea5e9");+ });+});diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsxindex 86f837e2c..588c20f7e 100644--- a/src/components/ai-edition/RightPanes.tsx+++ b/src/components/ai-edition/RightPanes.tsx@@ -43,7 +43,6 @@ import {} from "react";import { toast } from "sonner";import defaultCursorPreviewUrl from "@/assets/cursors/Cursor=Default.svg";-import GradientEditor, { type GradientEditorState } from "@/components/ui/gradient-editor";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { toFileUrl } from "@/components/video-editor/projectPersistence";import { WALLPAPER_MOTIONS, type WallpaperMotion } from "@/components/video-editor/types";@@ -104,7 +103,7 @@ import {DEFAULT_CURSOR_THEME_ID,themePickerPreviewAssets,} from "@/lib/cursor/cursorThemes";-import { buildGradientFromEditor } from "@/lib/gradientBuilder";+import { gradientSeedColor, oneColorGradient } from "@/lib/gradientBuilder";import {FRAME_THEMES,type FrameTheme,@@ -134,6 +133,7 @@ import {} from "@/utils/aspectRatioUtils";import { useCanSegmentCamera } from "../../native/hooks/useSegmentationSupport";import { CaptionsPane } from "./CaptionsPane";+import { ColorField } from "./ColorField";import { insertionsEnabled } from "./insertionsEnabled";import styles from "./NewEditorShell.module.css";import { useTranscriptionLabel } from "./TranscriptionStatus";@@ -439,12 +439,43 @@ function useMemoCustomWallpapers(current: string): string[] {return cached;}-function normaliseHex(raw: string): string | null {- const trimmed = raw.trim();- if (!trimmed) return null;- const withHash = trimmed.startsWith("#") ? trimmed : `#${trimmed}`;- if (!/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(withHash)) return null;- return withHash.toLowerCase();+/** The seed the one-colour gradient starts from when the wallpaper is not one of its own. */+const GRADIENT_SEED_FALLBACK = "#3b82f6";++/**+ * The free choice, folded behind the curated set: a "Custom" row under the swatches whose+ * picker holds the wheel, the hex value and the shared presets, like every other colour in+ * the inspector. Reachable in one click, never the first thing offered.+ */+function CustomBackgroundRow({+ label,+ value,+ swatch,+ hasDocument,+ onChange,+ onCommit,+}: {+ label: string;+ value: string;+ swatch?: string;+ hasDocument: boolean;+ onChange: (hex: string) => void;+ onCommit: () => void;+}) {+ const ts = useScopedT("settings");+ return (+ <div className={styles.paneRow}>+ <span className={styles.label}>{ts("background.custom")}</span>+ <ColorField+ label={label}+ value={value}+ swatch={swatch}+ disabled={!hasDocument}+ onChange={onChange}+ onCommit={onCommit}+ />+ </div>+ );}function BackgroundColorTab({@@ -452,28 +483,25 @@ function BackgroundColorTab({hasDocument,isSelected,onPick,+ onLive,+ onCommit,updateNative = true,}: {value: string;hasDocument: boolean;isSelected: (v: string) => boolean;onPick: (next: string) => void;+ onLive: (next: string) => void;+ onCommit: () => void;updateNative?: boolean;}) {const ts = useScopedT("settings");- const [hexDraft, setHexDraft] = useState(value.startsWith("#") ? value : "#000000");- useEffect(() => {- if (value.startsWith("#")) setHexDraft(value);- }, [value]);- const commitHex = () => {- const next = normaliseHex(hexDraft);- if (next) {- onPick(next);- if (updateNative && isNativeCompositorActive()) {- setNativeParam("backgroundColor", next);- }+ const pushNative = (color: string) => {+ if (updateNative && isNativeCompositorActive()) {+ setNativeParam("backgroundColor", color);}};+ const current = /^#[0-9a-f]{6}$/i.test(value) ? value : "#000000";return (<><div className={styles.bgGrid} style={{ margin: "0 var(--sp-4) 12px" }}>@@ -487,43 +515,21 @@ function BackgroundColorTab({disabled={!hasDocument}onClick={() => {onPick(c);- if (updateNative && isNativeCompositorActive()) {- setNativeParam("backgroundColor", c);- }+ pushNative(c);}}/>))}</div>- <div- style={{- margin: "0 var(--sp-4) 12px",- display: "flex",- alignItems: "center",- gap: 8,+ <CustomBackgroundRow+ label={ts("background.customColor")}+ value={current}+ hasDocument={hasDocument}+ onChange={onLive}+ onCommit={() => {+ onCommit();+ if (value.startsWith("#")) pushNative(value);}}- >- <input- type="color"- className={styles.bgColorInput}- value={hexDraft}- disabled={!hasDocument}- onChange={(e) => setHexDraft(e.target.value)}- onBlur={commitHex}- />- {/* Mono stays: a hex code. */}- <input- type="text"- className={styles.control}- value={hexDraft}- disabled={!hasDocument}- onChange={(e) => setHexDraft(e.target.value)}- onBlur={commitHex}- onKeyDown={(e) => {- if (e.key === "Enter") commitHex();- }}- style={{ flex: 1, minWidth: 0, fontFamily: "var(--font-mono)" }}- />- </div>+ /></>);}@@ -555,35 +561,11 @@ export function WallpaperPicker({const [tab, setTab] = useState<"image" | "color" | "gradient">(() => classifyWallpaper(value).kind,);- // The editor is a colour wheel and two stops, taller than the rest of the tab together:- // shown on demand, so the presets stay in view.- const [gradientEditorOpen, setGradientEditorOpen] = useState(false);+ // A drag in the colour wheel previews live; the write happens when the picker closes.+ const live = onLiveChange ?? onChange;+ const commit = () => void onCommit?.();const customUrls = useMemoCustomWallpapers(value);-- const gradientCommitTimer = useRef<number | null>(null);- const handleGradientChange = useCallback(- (state: GradientEditorState) => {- const grad = buildGradientFromEditor(state);- if (onLiveChange) onLiveChange(grad);- else onChange(grad);- if (gradientCommitTimer.current !== null) {- window.clearTimeout(gradientCommitTimer.current);- }- gradientCommitTimer.current = window.setTimeout(() => {- gradientCommitTimer.current = null;- if (onCommit) void onCommit();- }, 400);- },- [onChange, onLiveChange, onCommit],- );- useEffect(- () => () => {- if (gradientCommitTimer.current !== null) {- window.clearTimeout(gradientCommitTimer.current);- }- },- [],- );+ const seed = gradientSeedColor(value) ?? GRADIENT_SEED_FALLBACK;const isSelected = (candidate: string) => value === candidate;const tabs = [@@ -656,6 +638,8 @@ export function WallpaperPicker({hasDocument={hasDocument}isSelected={isSelected}onPick={(color) => onChange(color)}+ onLive={live}+ onCommit={commit}updateNative={updateNativeBackground}/>) : (@@ -673,20 +657,14 @@ export function WallpaperPicker({/>))}</div>- {hasDocument ? (- <>- <button- type="button"- className={styles.bgDisclosure}- aria-expanded={gradientEditorOpen}- onClick={() => setGradientEditorOpen((open) => !open)}- >- {ts("background.custom")}- <ChevronDown size={14} />- </button>- {gradientEditorOpen ? <GradientEditor onChange={handleGradientChange} /> : null}- </>- ) : null}+ <CustomBackgroundRow+ label={ts("background.customGradient")}+ value={seed}+ swatch={oneColorGradient(seed)}+ hasDocument={hasDocument}+ onChange={(hex) => live(oneColorGradient(hex))}+ onCommit={commit}+ /></>)}</>diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.jsonindex cc2a43be1..fdfc06d22 100644--- a/src/i18n/locales/ar/settings.json+++ b/src/i18n/locales/ar/settings.json@@ -11,6 +11,8 @@"title": "الخلفية","imageLabel": "الخلفية {{index}}","custom": "مخصص",+ "customColor": "لون مخصص",+ "customGradient": "تدرج من لون واحد","help": "اختر ما يظهر خلف التسجيل: صورة خلفية مضمّنة، أو لون خالص، أو تدرّج لوني، أو صورة خاصة بك من القرص.","gradient": "تدرج لوني","colorLabel": "اللون {{color}}",diff --git a/src/i18n/locales/cs/settings.json b/src/i18n/locales/cs/settings.jsonindex 423226410..a0ba401c0 100644--- a/src/i18n/locales/cs/settings.json+++ b/src/i18n/locales/cs/settings.json@@ -11,6 +11,8 @@"title": "Pozadí","imageLabel": "Pozadí {{index}}","custom": "Vlastní",+ "customColor": "Vlastní barva",+ "customGradient": "Přechod z jedné barvy","help": "Vyberte, co se zobrazí za nahrávkou: přibalený obrázek pozadí, plná barva, přechod nebo vlastní obrázek z disku.","gradient": "Přechod","colorLabel": "Barva {{color}}",diff --git a/src/i18n/locales/de/settings.json b/src/i18n/locales/de/settings.jsonindex 241e25fea..1d2cd095b 100644--- a/src/i18n/locales/de/settings.json+++ b/src/i18n/locales/de/settings.json@@ -11,6 +11,8 @@"title": "Hintergrund","imageLabel": "Hintergrund {{index}}","custom": "Eigenes",+ "customColor": "Eigene Farbe",+ "customGradient": "Verlauf aus einer Farbe","help": "Wähle, was hinter der Aufnahme zu sehen ist: ein mitgeliefertes Hintergrundbild, eine Volltonfarbe, einen Verlauf oder ein eigenes Bild von der Festplatte.","gradient": "Verlauf","colorLabel": "Farbe {{color}}",diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.jsonindex c870e3b98..553a7a000 100644--- a/src/i18n/locales/en/settings.json+++ b/src/i18n/locales/en/settings.json@@ -11,6 +11,8 @@"title": "Background","imageLabel": "Background {{index}}","custom": "Custom",+ "customColor": "Custom color",+ "customGradient": "Gradient from one color","help": "Choose what appears behind the recording: a bundled wallpaper image, a solid color, a gradient, or a custom image from disk.","gradient": "Gradient","colorLabel": "Color {{color}}",diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.jsonindex ffea51645..b38f75eac 100644--- a/src/i18n/locales/es/settings.json+++ b/src/i18n/locales/es/settings.json@@ -11,6 +11,8 @@"title": "Fondo","imageLabel": "Fondo {{index}}","custom": "Personalizado",+ "customColor": "Color personalizado",+ "customGradient": "Degradado a partir de un color","help": "Elige qué aparece detrás de la grabación: un fondo incluido, un color sólido, un degradado o una imagen propia del disco.","gradient": "Degradado","colorLabel": "Color {{color}}",diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.jsonindex 43c1f38af..4b414ed75 100644--- a/src/i18n/locales/fr/settings.json+++ b/src/i18n/locales/fr/settings.json@@ -11,6 +11,8 @@"title": "Arrière-plan","imageLabel": "Fond {{index}}","custom": "Personnalisé",+ "customColor": "Couleur personnalisée",+ "customGradient": "Dégradé à partir d'une couleur","help": "Choisissez ce qui apparaît derrière l'enregistrement : un fond d'écran fourni, une couleur unie, un dégradé, ou une image personnelle depuis le disque.","gradient": "Dégradé","colorLabel": "Couleur {{color}}",diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.jsonindex 55b6b0f3f..05fce4a59 100644--- a/src/i18n/locales/it/settings.json+++ b/src/i18n/locales/it/settings.json@@ -11,6 +11,8 @@"title": "Sfondo","imageLabel": "Sfondo {{index}}","custom": "Personalizzato",+ "customColor": "Colore personalizzato",+ "customGradient": "Sfumatura da un colore","help": "Scegli cosa appare dietro la registrazione: uno sfondo incluso, un colore pieno, un gradiente o un'immagine personale dal disco.","gradient": "Sfumatura","colorLabel": "Colore {{color}}",diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.jsonindex def54d603..33456679e 100644--- a/src/i18n/locales/ja-JP/settings.json+++ b/src/i18n/locales/ja-JP/settings.json@@ -11,6 +11,8 @@"title": "背景","imageLabel": "背景 {{index}}","custom": "カスタム",+ "customColor": "カスタムカラー",+ "customGradient": "1色から作るグラデーション","help": "録画の背景に表示するものを選びます。同梱の壁紙画像、単色、グラデーション、またはディスク上の任意の画像から選べます。","gradient": "グラデーション","colorLabel": "色 {{color}}",diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.jsonindex f4aeb6916..f938a625b 100644--- a/src/i18n/locales/ko-KR/settings.json+++ b/src/i18n/locales/ko-KR/settings.json@@ -11,6 +11,8 @@"title": "배경","imageLabel": "배경 {{index}}","custom": "사용자 지정",+ "customColor": "사용자 지정 색상",+ "customGradient": "한 가지 색상으로 만든 그라데이션","help": "녹화 뒤에 표시할 항목을 선택하세요. 기본 제공 배경 이미지, 단색, 그라데이션 또는 디스크의 사용자 이미지를 사용할 수 있습니다.","gradient": "그라디언트","colorLabel": "색상 {{color}}",diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.jsonindex 03e871546..1b9c883cc 100644--- a/src/i18n/locales/pt-BR/settings.json+++ b/src/i18n/locales/pt-BR/settings.json@@ -11,6 +11,8 @@"title": "Fundo","imageLabel": "Fundo {{index}}","custom": "Personalizado",+ "customColor": "Cor personalizada",+ "customGradient": "Gradiente a partir de uma cor","help": "Escolha o que aparece atrás da gravação: um papel de parede incluído, uma cor sólida, um gradiente ou uma imagem sua do disco.","gradient": "Gradiente","colorLabel": "Cor {{color}}",diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.jsonindex 93a5decdc..a06902c22 100644--- a/src/i18n/locales/ru/settings.json+++ b/src/i18n/locales/ru/settings.json@@ -11,6 +11,8 @@"title": "Фон","imageLabel": "Фон {{index}}","custom": "Свой",+ "customColor": "Свой цвет",+ "customGradient": "Градиент из одного цвета","help": "Выберите, что будет за записью: встроенное изображение, сплошной цвет, градиент или собственная картинка с диска.","gradient": "Градиент","colorLabel": "Цвет {{color}}",diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.jsonindex 5cf718750..2c42629d0 100644--- a/src/i18n/locales/tr/settings.json+++ b/src/i18n/locales/tr/settings.json@@ -11,6 +11,8 @@"title": "Arka Plan","imageLabel": "Arka plan {{index}}","custom": "Özel",+ "customColor": "Özel renk",+ "customGradient": "Tek renkten gradyan","help": "Kaydın arkasında ne görüneceğini seçin: yerleşik bir duvar kâğıdı, düz renk, gradyan veya diskinizdeki özel bir görsel.","gradient": "Gradyan","colorLabel": "Renk {{color}}",diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.jsonindex 786a0ec51..33ba830b5 100644--- a/src/i18n/locales/vi/settings.json+++ b/src/i18n/locales/vi/settings.json@@ -11,6 +11,8 @@"title": "Nền","imageLabel": "Nền {{index}}","custom": "Tùy chỉnh",+ "customColor": "Màu tùy chỉnh",+ "customGradient": "Chuyển sắc từ một màu","help": "Chọn nội dung hiển thị phía sau bản ghi: ảnh nền có sẵn, màu đơn sắc, dải màu chuyển sắc, hoặc ảnh riêng của bạn từ ổ đĩa.","gradient": "Dải màu","colorLabel": "Màu {{color}}",diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.jsonindex a6d0d60ea..80db1f9f7 100644--- a/src/i18n/locales/zh-CN/settings.json+++ b/src/i18n/locales/zh-CN/settings.json@@ -11,6 +11,8 @@"title": "背景","imageLabel": "背景 {{index}}","custom": "自定义",+ "customColor": "自定义颜色",+ "customGradient": "单色渐变","help": "选择录制内容背后显示的元素:内置壁纸图片、纯色、渐变,或来自磁盘的自定义图片。","gradient": "渐变","colorLabel": "颜色 {{color}}",diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.jsonindex 642e13008..233c5cb93 100644--- a/src/i18n/locales/zh-TW/settings.json+++ b/src/i18n/locales/zh-TW/settings.json@@ -11,6 +11,8 @@"title": "背景","imageLabel": "背景 {{index}}","custom": "自訂",+ "customColor": "自訂顏色",+ "customGradient": "單色漸層","help": "選擇錄製內容背後顯示的元素:內建桌布圖片、純色、漸層,或來自磁碟的自訂圖片。","gradient": "漸層","colorLabel": "顏色 {{color}}",diff --git a/src/lib/gradientBuilder.test.ts b/src/lib/gradientBuilder.test.tsindex d8f530cbb..b749e39f8 100644--- a/src/lib/gradientBuilder.test.ts+++ b/src/lib/gradientBuilder.test.ts@@ -1,69 +1,57 @@import { describe, expect, it } from "vitest";-import type { GradientEditorState } from "@/components/ui/gradient-editor";-import { buildGradientFromEditor } from "./gradientBuilder";+import { parseCssGradient } from "@/lib/exporter/gradientParser";+import { gradientSeedColor, oneColorGradient } from "./gradientBuilder";-const baseState = (overrides: Partial<GradientEditorState> = {}): GradientEditorState => ({- points: [{ id: "main", x: 30, y: 40, color: "rgb(255, 0, 0)" }],- mainX: 30,- mainY: 40,- mainColor: "rgb(255, 0, 0)",- brightness: 100,- angle: 135,- harmonyType: "splitComplementary",- ...overrides,-});+function lightness(hex: string): number {+ const n = Number.parseInt(hex.slice(1), 16);+ const channels = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((c) => c / 255);+ return ((Math.max(...channels) + Math.min(...channels)) / 2) * 100;+}++function stopsOf(css: string): string[] {+ return parseCssGradient(css)?.stops.map((s) => s.color) ?? [];+}-const threePoints = (brightness: number): GradientEditorState =>- baseState({- brightness,- points: [- { id: "main", x: 30, y: 40, color: "rgb(255, 0, 0)" },- { id: "o1", x: 70, y: 20, color: "rgb(0, 255, 0)" },- { id: "o2", x: 50, y: 80, color: "rgb(0, 0, 255)" },- ],+describe("oneColorGradient", () => {+ it("makes two hex stops, the shape the compositor and the presets share", () => {+ const css = oneColorGradient("#3b82f6");+ expect(css).toMatch(/^linear-gradient\(135deg, #[0-9a-f]{6}, #[0-9a-f]{6}\)$/);+ expect(stopsOf(css)).toHaveLength(2);});-describe("buildGradientFromEditor", () => {- it("emits a 3-stop linear gradient at 135deg", () => {- const css = buildGradientFromEditor(threePoints(100));- expect(css).toBe(- "linear-gradient(135deg, rgb(255, 0, 0) 0%, rgb(0, 255, 0) 50%, rgb(0, 0, 255) 100%)",- );+ it("keeps a mid-tone colour as the first stop", () => {+ expect(stopsOf(oneColorGradient("#3b82f6"))[0]).toBe("#3b82f6");});- it("scales every stop's color with the brightness slider", () => {- const full = buildGradientFromEditor(threePoints(100));- const half = buildGradientFromEditor(threePoints(50));- expect(half).toBe(- "linear-gradient(135deg, rgb(128, 0, 0) 0%, rgb(0, 128, 0) 50%, rgb(0, 0, 128) 100%)",- );- expect(full).not.toBe(half);+ it("holds both ends between 35% and 85% lightness, whatever is picked", () => {+ for (const pick of ["#000000", "#ffffff", "#ff0000", "#0a0a2a", "#fffde0", "#777", "#10b981"]) {+ for (const stop of stopsOf(oneColorGradient(pick))) {+ const l = lightness(stop);+ // One unit of slack for the rounding to 8-bit channels.+ expect(l).toBeGreaterThanOrEqual(34.5);+ expect(l).toBeLessThanOrEqual(85.5);+ }+ }});- it("handles one and two point states", () => {- const one = buildGradientFromEditor(baseState({ brightness: 100 }));- expect(one).toBe("linear-gradient(135deg, rgb(255, 0, 0) 0%, rgb(255, 0, 0) 100%)");+ it("gives two different stops, so the gradient is visible", () => {+ for (const pick of ["#000000", "#ffffff", "#3b82f6"]) {+ const [a, b] = stopsOf(oneColorGradient(pick));+ expect(a).not.toBe(b);+ }+ });+});- const two = buildGradientFromEditor(- baseState({- brightness: 100,- points: [- { id: "main", x: 30, y: 40, color: "rgb(10, 20, 30)" },- { id: "o1", x: 70, y: 20, color: "rgb(40, 50, 60)" },- ],- }),- );- expect(two).toBe(- "linear-gradient(135deg, rgb(10, 20, 30) 0%, rgb(40, 50, 60) 50%, rgb(40, 50, 60) 100%)",- );+describe("gradientSeedColor", () => {+ it("reads the first stop back from a gradient it made", () => {+ expect(gradientSeedColor(oneColorGradient("#3b82f6"))).toBe("#3b82f6");});- it("falls back to a brightness-driven base color when there are no points", () => {- expect(buildGradientFromEditor(baseState({ points: [], brightness: 0 }))).toBe(- "hsl(0, 0%, 0%)",- );- expect(buildGradientFromEditor(baseState({ points: [], brightness: 100 }))).toBe(- "hsl(0, 0%, 18%)",- );+ it("has nothing to offer for a colour, an image or an rgb() stop", () => {+ expect(gradientSeedColor("#3b82f6")).toBeNull();+ expect(gradientSeedColor("/wallpapers/wallpaper1.jpg")).toBeNull();+ expect(+ gradientSeedColor("linear-gradient(135deg, rgb(1, 2, 3) 0%, rgb(4, 5, 6) 100%)"),+ ).toBeNull();});});diff --git a/src/lib/gradientBuilder.ts b/src/lib/gradientBuilder.tsindex b45da7975..05fdbfd63 100644--- a/src/lib/gradientBuilder.ts+++ b/src/lib/gradientBuilder.ts@@ -1,38 +1,63 @@-import type { GradientEditorState } from "@/components/ui/gradient-editor";+import { parseCssGradient } from "@/lib/exporter/gradientParser";import { clamp } from "@/utils/math";-/* ---------- editor state -> CSS background ----------- The editor produces a clean 3-stop LINEAR gradient - the same shape- as a "real" 3-color gradient picker, not clustered blobs. Brightness- is a per-channel multiplier (0 = black, 100 = full color). */-export function buildGradientFromEditor(state: GradientEditorState): string {- const { points, brightness, angle = 135 } = state;- const colors = points.slice(0, 3).map((p) => applyBrightness(p.color, brightness));+/* ---------- one colour -> a gradient that cannot clash ----------+ The user picks ONE colour and gets two stops of the same family: a small hue turn and a+ lightness step, never a harmony of unrelated hues. Lightness is held between 35% and 85%+ so neither end reaches black or white, which is what made free gradients look muddy or+ blown out behind a recording. Two stops, hex, the same shape as the curated presets. */- if (colors.length === 0) {- return baseForBrightness(brightness);- }- if (colors.length === 1) {- return `linear-gradient(${angle}deg, ${colors[0]} 0%, ${colors[0]} 100%)`;- }- if (colors.length === 2) {- return `linear-gradient(${angle}deg, ${colors[0]} 0%, ${colors[1]} 50%, ${colors[1]} 100%)`;- }+const ANGLE_DEG = 135;+const L_MIN = 35;+const L_MAX = 85;+const HUE_TURN = 18;+const LIGHTNESS_STEP = 12;- return `linear-gradient(${angle}deg, ${colors[0]} 0%, ${colors[1]} 50%, ${colors[2]} 100%)`;+export function oneColorGradient(hex: string): string {+ const [h, s, l] = hexToHsl(hex);+ const from = clamp(l, L_MIN, L_MAX);+ // Step down when there is room, up otherwise: both ends stay inside the band.+ const to = from - LIGHTNESS_STEP >= L_MIN ? from - LIGHTNESS_STEP : from + LIGHTNESS_STEP;+ return `linear-gradient(${ANGLE_DEG}deg, ${hslToHex(h, s, from)}, ${hslToHex(h + HUE_TURN, s, to)})`;}-function applyBrightness(color: string, brightness: number): string {- const match = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);- if (!match) return color;- const k = brightness / 100;- const r = Math.round(Number(match[1]) * k);- const g = Math.round(Number(match[2]) * k);- const b = Math.round(Number(match[3]) * k);- return `rgb(${r}, ${g}, ${b})`;+/** The colour a gradient starts from, for the picker to show: its first stop when that is hex. */+export function gradientSeedColor(wallpaper: string): string | null {+ const first = parseCssGradient(wallpaper)?.stops[0]?.color;+ return first && /^#[0-9a-f]{6}$/i.test(first) ? first.toLowerCase() : null;}-function baseForBrightness(brightness: number): string {- const l = Math.round((brightness / 100) * 18);- return `hsl(0, 0%, ${clamp(l, 0, 22)}%)`;+function hexToHsl(hex: string): [number, number, number] {+ const full = hex.length === 4 ? `#${[...hex.slice(1)].map((c) => c + c).join("")}` : hex;+ const n = Number.parseInt(full.slice(1), 16);+ const r = ((n >> 16) & 255) / 255;+ const g = ((n >> 8) & 255) / 255;+ const b = (n & 255) / 255;+ const max = Math.max(r, g, b);+ const min = Math.min(r, g, b);+ const l = (max + min) / 2;+ const d = max - min;+ if (d === 0) return [0, 0, l * 100];+ const s = d / (1 - Math.abs(2 * l - 1));+ const h =+ max === r+ ? ((g - b) / d + (g < b ? 6 : 0)) * 60+ : max === g+ ? ((b - r) / d + 2) * 60+ : ((r - g) / d + 4) * 60;+ return [h, s * 100, l * 100];+}++function hslToHex(h: number, s: number, l: number): string {+ const sat = s / 100;+ const lig = l / 100;+ const a = sat * Math.min(lig, 1 - lig);+ const channel = (k: number) => {+ const p = (k + h / 30) % 12;+ const v = lig - a * Math.max(-1, Math.min(p - 3, 9 - p, 1));+ return Math.round(v * 255)+ .toString(16)+ .padStart(2, "0");+ };+ return `#${channel(0)}${channel(8)}${channel(4)}`;}