Skip to content

Commit 5561403

Browse files
committed
fix(studio): let the colour hex field be edited and commit it on outside press
Split hex-draft ownership so the hex input is the sole author of its own text while editing (updateColorDraft no longer stamps a canonical hex back over every keystroke), fixing snap-back on backspace and the silent wrong-colour clobber on non-repeating hex values. Route hex typing through the shared gesture transaction so outside-click and Escape settle/cancel it like the other inspector fields, instead of relying on a private onBlur commit that never fires once the panel unmounts on outside-click.
1 parent b825063 commit 5561403

2 files changed

Lines changed: 187 additions & 38 deletions

File tree

Lines changed: 158 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,85 @@
11
// @vitest-environment happy-dom
22

33
import React, { act } from "react";
4-
import { createRoot } from "react-dom/client";
5-
import { afterEach, describe, expect, it, vi } from "vitest";
4+
import { createRoot, type Root } from "react-dom/client";
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
import { __resetDesignInputThrottle } from "../../utils/designInputTracking";
67
import { ColorField } from "./propertyPanelColor";
78

9+
const trackStudioEvent = vi.hoisted(() => vi.fn());
10+
11+
vi.mock("../../utils/studioTelemetry", () => ({
12+
trackStudioEvent: (...args: unknown[]) => trackStudioEvent(...args),
13+
}));
14+
815
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
916

17+
const roots: Root[] = [];
18+
19+
beforeEach(() => {
20+
trackStudioEvent.mockReset();
21+
__resetDesignInputThrottle();
22+
});
23+
1024
afterEach(() => {
25+
for (const root of roots) act(() => root.unmount());
26+
roots.length = 0;
1127
document.body.innerHTML = "";
1228
});
1329

14-
function renderColorField(onCommit: (value: string) => void): void {
30+
function renderColorField({
31+
value = "#333333",
32+
onPreview,
33+
onCommit = vi.fn(),
34+
}: {
35+
value?: string;
36+
onPreview?: (value: string) => void;
37+
onCommit?: (value: string) => void;
38+
} = {}): HTMLElement {
1539
const host = document.createElement("div");
1640
document.body.append(host);
1741
const root = createRoot(host);
42+
roots.push(root);
1843
act(() => {
19-
root.render(<ColorField flat label="Color" value="rgb(255, 176, 32)" onCommit={onCommit} />);
44+
root.render(
45+
<ColorField flat label="Color" value={value} onPreview={onPreview} onCommit={onCommit} />,
46+
);
2047
});
48+
return host;
49+
}
50+
51+
function changeInput(input: HTMLInputElement, value: string): void {
52+
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set;
53+
if (!setter) throw new Error("expected native input value setter");
54+
setter.call(input, value);
55+
input.dispatchEvent(new Event("input", { bubbles: true }));
56+
}
57+
58+
function openHexInput(host: HTMLElement): HTMLInputElement {
59+
const trigger = host.querySelector<HTMLButtonElement>('[data-flat-color-trigger="true"]');
60+
if (!trigger) throw new Error("Color trigger was not rendered");
61+
act(() => trigger.click());
62+
const input = document.querySelector<HTMLInputElement>('input[spellcheck="false"]');
63+
if (!input) throw new Error("Hex input was not rendered");
64+
return input;
65+
}
66+
67+
function clickOutside(): void {
68+
document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }));
2169
}
2270

2371
describe("ColorField flat trigger", () => {
2472
it("renders label and value inline with a small swatch, no boxed border", () => {
25-
const host = document.createElement("div");
26-
document.body.append(host);
27-
const root = createRoot(host);
28-
act(() => {
29-
root.render(<ColorField flat label="Color" value="rgb(255, 176, 32)" onCommit={vi.fn()} />);
30-
});
73+
const host = renderColorField({ value: "rgb(255, 176, 32)" });
3174
const trigger = host.querySelector<HTMLButtonElement>('[data-flat-color-trigger="true"]');
3275
expect(trigger).not.toBeNull();
3376
expect(trigger?.className).not.toContain("border-neutral-800");
3477
expect(host.textContent).toContain("Color");
35-
act(() => root.unmount());
3678
});
3779

3880
it("persists one keyboard slider gesture on keyup", () => {
3981
const onCommit = vi.fn();
40-
renderColorField(onCommit);
82+
renderColorField({ value: "rgb(255, 176, 32)", onCommit });
4183
const trigger = document.querySelector<HTMLButtonElement>('[data-flat-color-trigger="true"]');
4284
if (!trigger) throw new Error("Color trigger was not rendered");
4385
act(() => {
@@ -57,3 +99,107 @@ describe("ColorField flat trigger", () => {
5799
expect(onCommit).toHaveBeenCalledOnce();
58100
});
59101
});
102+
103+
describe("ColorField hex editing", () => {
104+
it("allows #333333 to be backspaced to #3 without snapping", () => {
105+
const input = openHexInput(renderColorField());
106+
107+
for (const value of ["#33333", "#3333", "#333", "#33", "#3"]) {
108+
act(() => changeInput(input, value));
109+
expect(input.value).toBe(value);
110+
}
111+
});
112+
113+
it("does not silently change #22CC66 to #2222CC while backspacing", () => {
114+
const input = openHexInput(renderColorField({ value: "#22CC66" }));
115+
116+
for (const value of ["#22CC6", "#22CC", "#22C"]) {
117+
act(() => changeInput(input, value));
118+
expect(input.value).toBe(value);
119+
expect(input.value).not.toBe("#2222CC");
120+
}
121+
});
122+
123+
it("commits a full replacement after selecting the existing value", () => {
124+
const onCommit = vi.fn();
125+
const input = openHexInput(renderColorField({ onCommit }));
126+
input.focus();
127+
input.select();
128+
129+
act(() => changeInput(input, "#12AB34"));
130+
act(() => input.blur());
131+
132+
expect(onCommit).toHaveBeenCalledOnce();
133+
expect(onCommit).toHaveBeenCalledWith("rgb(18, 171, 52)");
134+
});
135+
136+
it("commits a complete pending hex on outside-click", () => {
137+
const onCommit = vi.fn();
138+
const input = openHexInput(renderColorField({ onCommit }));
139+
140+
act(() => changeInput(input, "#12AB34"));
141+
act(clickOutside);
142+
143+
expect(onCommit).toHaveBeenCalledOnce();
144+
expect(onCommit).toHaveBeenCalledWith("rgb(18, 171, 52)");
145+
});
146+
147+
it("does not commit an incomplete pending hex on outside-click", () => {
148+
const onCommit = vi.fn();
149+
const input = openHexInput(renderColorField({ onCommit }));
150+
151+
act(() => changeInput(input, "#12AB3"));
152+
act(clickOutside);
153+
154+
expect(onCommit).not.toHaveBeenCalled();
155+
});
156+
157+
it("cancels a pending hex edit on Escape and restores the previous value", () => {
158+
const onPreview = vi.fn();
159+
const onCommit = vi.fn();
160+
const host = renderColorField({ value: "#224466", onPreview, onCommit });
161+
const input = openHexInput(host);
162+
163+
act(() => changeInput(input, "#12AB34"));
164+
act(() => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })));
165+
166+
expect(onCommit).not.toHaveBeenCalled();
167+
expect(onPreview).toHaveBeenLastCalledWith("rgb(34, 68, 102)");
168+
expect(openHexInput(host).value).toBe("#224466");
169+
});
170+
171+
it("still commits a complete hex on Tab-blur", () => {
172+
const onCommit = vi.fn();
173+
const input = openHexInput(renderColorField({ onCommit }));
174+
input.focus();
175+
176+
act(() => changeInput(input, "#12AB34"));
177+
act(() => input.blur());
178+
179+
expect(onCommit).toHaveBeenCalledOnce();
180+
expect(onCommit).toHaveBeenCalledWith("rgb(18, 171, 52)");
181+
});
182+
183+
it("live-previews only a complete six-digit hex", () => {
184+
const onPreview = vi.fn();
185+
const input = openHexInput(renderColorField({ value: "#112233", onPreview }));
186+
187+
act(() => changeInput(input, "#333"));
188+
expect(onPreview).not.toHaveBeenCalled();
189+
190+
act(() => changeInput(input, "#333333"));
191+
expect(onPreview).toHaveBeenCalledOnce();
192+
expect(onPreview).toHaveBeenCalledWith("rgb(51, 51, 51)");
193+
});
194+
195+
it("tracks exactly once per completed edit, not once per keystroke", () => {
196+
const input = openHexInput(renderColorField());
197+
198+
for (const value of ["#", "#1", "#12", "#12A", "#12AB", "#12AB3", "#12AB34"]) {
199+
act(() => changeInput(input, value));
200+
}
201+
act(clickOutside);
202+
203+
expect(trackStudioEvent).toHaveBeenCalledOnce();
204+
});
205+
});

‎packages/studio/src/components/editor/propertyPanelColor.tsx‎

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -184,11 +184,24 @@ export function ColorField({
184184
const brightnessPercent = Math.round(hsv.value * 100);
185185
const alphaPercent = Math.round(draftColor.alpha * 100);
186186

187-
const updateColorDraft = useCallback((nextValue: string) => {
187+
const updateColorDraft = useCallback((nextValue: string, source: "hex" | "picker") => {
188188
const nextColor = parseCssColor(nextValue);
189189
if (!nextColor) return;
190190
setDraftColor(nextColor);
191-
setHexDraft(toHexColor(nextColor).toUpperCase());
191+
if (source === "picker") setHexDraft(toHexColor(nextColor).toUpperCase());
192+
}, []);
193+
const resolveColorGestureValue = useCallback((nextValue: string) => {
194+
const source = nextValue.startsWith("#") ? "hex" : "picker";
195+
if (source === "hex" && !/^#[0-9a-f]{6}$/i.test(nextValue)) return null;
196+
const nextColor = parseCssColor(nextValue);
197+
if (!nextColor) return null;
198+
return {
199+
source,
200+
value: formatCssColor({
201+
...nextColor,
202+
alpha: source === "hex" ? draftColorRef.current.alpha : nextColor.alpha,
203+
}),
204+
} as const;
192205
}, []);
193206
const persistColorValue = useCallback(
194207
(nextValue: string) => {
@@ -203,12 +216,17 @@ export function ColorField({
203216
settle: settleColorGesture,
204217
cancel: cancelColorGesture,
205218
} = useInspectorGestureTransaction({
206-
sourceValue: value,
219+
sourceValue: formatCssColor(colorFromCss(value)),
207220
onPreview: (nextValue) => {
208-
updateColorDraft(nextValue);
209-
onPreview?.(nextValue);
221+
const resolved = resolveColorGestureValue(nextValue);
222+
if (!resolved) return;
223+
updateColorDraft(resolved.value, resolved.source);
224+
onPreview?.(resolved.value);
225+
},
226+
onCommit: (nextValue) => {
227+
const resolved = resolveColorGestureValue(nextValue);
228+
if (resolved) persistColorValue(resolved.value);
210229
},
211-
onCommit: persistColorValue,
212230
});
213231

214232
useEffect(() => {
@@ -288,13 +306,11 @@ export function ColorField({
288306
commitHsv({ saturation, value: nextValue });
289307
};
290308

291-
const handleHexCommit = (nextHex: string) => {
309+
const handleHexChange = (nextHex: string) => {
292310
setHexDraft(nextHex);
293311
const normalized = nextHex.trim().startsWith("#") ? nextHex.trim() : `#${nextHex.trim()}`;
294-
const parsed = parseCssColor(normalized);
295-
if (!parsed) return;
296-
const nextValue = formatCssColor({ ...parsed, alpha: draftColorRef.current.alpha });
297-
updateColorDraft(nextValue);
312+
beginColorGesture();
313+
previewColorGesture(normalized);
298314
};
299315

300316
const picker = open
@@ -413,21 +429,8 @@ export function ColorField({
413429
<span className={LABEL}>Hex</span>
414430
<input
415431
value={hexDraft}
416-
onChange={(event) => handleHexCommit(event.target.value)}
417-
onBlur={() => {
418-
const normalized = hexDraft.trim().startsWith("#")
419-
? hexDraft.trim()
420-
: `#${hexDraft.trim()}`;
421-
const parsed = parseCssColor(normalized);
422-
if (parsed) {
423-
const nextValue = formatCssColor({
424-
...parsed,
425-
alpha: draftColorRef.current.alpha,
426-
});
427-
persistColorValue(nextValue);
428-
}
429-
setHexDraft(toHexColor(draftColorRef.current).toUpperCase());
430-
}}
432+
onChange={(event) => handleHexChange(event.target.value)}
433+
onBlur={settleColorGesture}
431434
className={`${FIELD} h-10 w-full text-[11px] font-medium outline-none`}
432435
spellCheck={false}
433436
/>

0 commit comments

Comments
 (0)