Skip to content

Commit 6f40e03

Browse files
committed
fix(studio): resolve the 4 cumulative blockers from the #2416 tip re-review
Fixes the Deepwork tip re-review's four remaining blockers plus its additive findings: - selectionIdentityKey: add sourceFile as a 5th identity component. The same local id/selector can legitimately recur across different composition files (host vs. an inlined sub-composition, or two unrelated sub-comps) — without sourceFile, those collided onto the same identity key and reused stale controller state across a selection change that should have reset it. - useColorGradingController: flush (not discard) a pending Grade edit when selection changes before the 350ms debounce fires. The prior fix correctly stopped it from landing on the WRONG (new) target, but cancelling outright silently dropped the user's in-flight edit instead of writing it to the element it was authored for — using the onSetAttributeLive closure captured for the outgoing render, which (via commitDataAttribute's own useCallback deps) is still bound to the outgoing selection. - useColorGradingController: revert to the last confirmed-good grading when a persist rejects, instead of leaving the optimistic (never-actually- saved) value showing indefinitely. Tracks a separate confirmedGradingRef, updated only on a successful persist. - FlatSelectRow: disable the reset button when the row itself is disabled (it previously ignored disabled entirely, same class of bug as the FlatSlider reset button fixed earlier) and give the underlying <select> an aria-label from the row's label text. - FlatSlider: handle lostpointercapture the same as pointercancel — capture can be lost without either firing first (another element steals it, or the browser reclaims it for a scroll/touch gesture), which previously left the dragging flag stuck and the knob permanently unable to sync to external value changes. New regression tests for all of the above; full studio suite still at the known pre-existing baseline (55 failures unrelated to this stack).
1 parent 267cdfc commit 6f40e03

5 files changed

Lines changed: 196 additions & 15 deletions

File tree

‎packages/studio/src/components/editor/propertyPanelFlatPrimitives.test.tsx‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -774,6 +774,54 @@ describe("FlatSlider — Grade extensions", () => {
774774
expect(track.getAttribute("aria-valuenow")).toBe("80");
775775
act(() => root.unmount());
776776
});
777+
778+
it("resets the dragging state on lostpointercapture even without a prior pointerup/pointercancel", () => {
779+
const { host, root } = renderInto(
780+
<FlatSlider
781+
label="Opacity"
782+
value={10}
783+
min={0}
784+
max={100}
785+
tier="explicitCustom"
786+
displayValue="10%"
787+
onCommit={vi.fn()}
788+
/>,
789+
);
790+
const track = host.querySelector<HTMLElement>('[data-flat-slider-track="true"]');
791+
if (!track) throw new Error("expected a track element");
792+
Object.defineProperty(track, "getBoundingClientRect", {
793+
value: () => ({ left: 0, width: 100, top: 0, height: 20, right: 100, bottom: 20 }),
794+
});
795+
act(() => {
796+
track.dispatchEvent(
797+
new PointerEvent("pointerdown", { bubbles: true, clientX: 30, pointerId: 1 }),
798+
);
799+
});
800+
expect(track.getAttribute("aria-valuenow")).toBe("30");
801+
act(() => {
802+
// Capture lost WITHOUT a pointerup/pointercancel first — e.g. another
803+
// element steals it, or the browser reclaims it for a scroll gesture.
804+
track.dispatchEvent(new Event("lostpointercapture", { bubbles: true }));
805+
});
806+
act(() => {
807+
root.render(
808+
<FlatSlider
809+
label="Opacity"
810+
value={99}
811+
min={0}
812+
max={100}
813+
tier="explicitCustom"
814+
displayValue="99%"
815+
onCommit={vi.fn()}
816+
/>,
817+
);
818+
});
819+
// If lostpointercapture hadn't cleared the dragging flag, this external
820+
// value change would be silently ignored (mid-drag echo suppression)
821+
// forever — the knob would be stuck at 30.
822+
expect(track.getAttribute("aria-valuenow")).toBe("99");
823+
act(() => root.unmount());
824+
});
777825
});
778826

779827
describe("FlatSelectRow", () => {
@@ -813,6 +861,28 @@ describe("FlatSelectRow", () => {
813861
act(() => root.unmount());
814862
});
815863

864+
it("disables the reset button (and gives the select an accessible name) when the row itself is disabled", () => {
865+
const onReset = vi.fn();
866+
const { host, root } = renderInto(
867+
<FlatSelectRow
868+
label="Shadow"
869+
value="soft"
870+
options={["none", "soft", "lift", "glow"]}
871+
tier="explicitCustom"
872+
disabled
873+
onChange={vi.fn()}
874+
onReset={onReset}
875+
/>,
876+
);
877+
const select = host.querySelector<HTMLSelectElement>("select");
878+
expect(select?.getAttribute("aria-label")).toBe("Shadow");
879+
const reset = host.querySelector<HTMLButtonElement>('[data-flat-select-reset="true"]');
880+
expect(reset?.disabled).toBe(true);
881+
act(() => reset?.dispatchEvent(new MouseEvent("click", { bubbles: true })));
882+
expect(onReset).not.toHaveBeenCalled();
883+
act(() => root.unmount());
884+
});
885+
816886
it("fires onChange when the select value changes", () => {
817887
const onChange = vi.fn();
818888
const { host, root } = renderInto(

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,14 @@ export function FlatSlider({
404404
e.currentTarget.releasePointerCapture(e.pointerId);
405405
}
406406
}}
407+
onLostPointerCapture={() => {
408+
// Capture can be lost without either pointerup or pointercancel
409+
// firing first (e.g. another element steals it, or the browser
410+
// reclaims it for a scroll/touch gesture) — without this,
411+
// draggingRef stays stuck true and the knob permanently stops
412+
// syncing to the committed value prop.
413+
draggingRef.current = false;
414+
}}
407415
onKeyDown={(e) => {
408416
if (disabled) return;
409417
const next = sliderKeyTarget(e.key, draft, min, max, step);
@@ -507,6 +515,7 @@ export function FlatSelectRow({
507515
<select
508516
value={value}
509517
disabled={disabled}
518+
aria-label={label || undefined}
510519
onChange={(e) => onChange(e.target.value)}
511520
className={`appearance-none bg-transparent text-right font-mono text-[11px] outline-none disabled:cursor-not-allowed ${VALUE_TIER_VALUE_CLASS[tier]}`}
512521
>
@@ -531,8 +540,9 @@ export function FlatSelectRow({
531540
type="button"
532541
data-flat-select-reset="true"
533542
title="Remove — fall back to default"
543+
disabled={disabled}
534544
onClick={onReset}
535-
className="flex-shrink-0 text-panel-text-3 opacity-0 transition-opacity hover:text-panel-text-1 group-hover:opacity-100"
545+
className="flex-shrink-0 text-panel-text-3 opacity-0 transition-opacity hover:text-panel-text-1 group-hover:opacity-100 disabled:cursor-not-allowed disabled:opacity-40"
536546
>
537547
<RotateCcw size={11} />
538548
</button>

‎packages/studio/src/components/editor/propertyPanelHelpers.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,18 +30,22 @@ export function isSelectedElementHidden(
3030
}
3131

3232
/**
33-
* 4-part element identity for keying panel remounts on selection change —
33+
* 5-part element identity for keying panel remounts on selection change —
3434
* id or selector alone collides for id-less same-selector siblings, leaving
35-
* mount-initialized state pointed at the previous element.
35+
* mount-initialized state pointed at the previous element. sourceFile is
36+
* required too: the same local id/selector can legitimately recur across
37+
* different composition files (host vs. an inlined sub-composition, or two
38+
* unrelated sub-comps), and without it those collide onto the same key.
3639
*/
3740
export function selectionIdentityKey(
38-
element: Pick<DomEditSelection, "id" | "hfId" | "selector" | "selectorIndex">,
41+
element: Pick<DomEditSelection, "id" | "hfId" | "selector" | "selectorIndex" | "sourceFile">,
3942
): string {
4043
return [
4144
element.id ?? "",
4245
element.hfId ?? "",
4346
element.selector ?? "",
4447
String(element.selectorIndex ?? ""),
48+
element.sourceFile ?? "",
4549
].join("|");
4650
}
4751

‎packages/studio/src/components/editor/useColorGradingController.test.ts‎

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,30 @@ describe("useColorGradingController", () => {
129129
vi.useRealTimers();
130130
});
131131

132+
it("reverts to the last confirmed-good grading when a persist rejects", async () => {
133+
vi.useFakeTimers();
134+
const onSetAttributeLive = vi.fn().mockRejectedValue(new Error("disk full"));
135+
const { root, getState } = renderHook(onSetAttributeLive);
136+
act(() => {
137+
getState().commitColorGrading(freshPopGrading());
138+
});
139+
expect(getState().grading.preset).toBe("fresh-pop");
140+
act(() => {
141+
vi.advanceTimersByTime(400);
142+
});
143+
// The rejection settles on a microtask, not a timer — flush it.
144+
await act(async () => {
145+
await Promise.resolve();
146+
await Promise.resolve();
147+
});
148+
// Reverted to "neutral" (the last confirmed-good value, from before this
149+
// commit) instead of permanently showing "fresh-pop" as if it had saved.
150+
expect(getState().grading.preset).toBe("neutral");
151+
expect(getState().runtimeStatus.state).toBe("unavailable");
152+
act(() => root.unmount());
153+
vi.useRealTimers();
154+
});
155+
132156
it("resetGrading returns to the neutral preset", () => {
133157
const { root, getState } = renderHook(vi.fn());
134158
act(() => {
@@ -159,7 +183,25 @@ describe("useColorGradingController", () => {
159183
act(() => root.unmount());
160184
});
161185

162-
it("cancels a pending persist scheduled for the previous element when selection changes before it flushes", () => {
186+
it("also resets when the same local id/selector recurs in a different source file", () => {
187+
// Same id, same selector, same selectorIndex — only sourceFile differs.
188+
// Without sourceFile in the identity key, this would collide with the
189+
// first element (e.g. host composition vs. an inlined sub-composition,
190+
// or two unrelated sub-comps that happen to share a local id).
191+
const { root, getState, rerenderWithElement } = renderHook(
192+
vi.fn(),
193+
makeElement({ id: "bg", sourceFile: "index.html" }),
194+
);
195+
act(() => {
196+
getState().commitColorGrading(freshPopGrading());
197+
});
198+
expect(getState().grading.preset).toBe("fresh-pop");
199+
rerenderWithElement(makeElement({ id: "bg", sourceFile: "sub-comp.html" }));
200+
expect(getState().grading.preset).toBe("neutral");
201+
act(() => root.unmount());
202+
});
203+
204+
it("flushes — rather than discards — a pending persist for the previous element when selection changes before it fires", () => {
163205
vi.useFakeTimers();
164206
const onSetAttributeLive = vi.fn();
165207
const { root, getState, rerenderWithElement } = renderHook(
@@ -169,16 +211,24 @@ describe("useColorGradingController", () => {
169211
act(() => {
170212
getState().commitColorGrading(freshPopGrading());
171213
});
172-
// Switch selection before the 350ms debounce flushes — the queued write
173-
// targeted the OLD element and must not land on whatever is selected now.
214+
// Switch selection before the 350ms debounce fires — the in-flight edit
215+
// must be written immediately (targeting the OUTGOING element's own
216+
// commit callback), not silently dropped just because a debounce timer
217+
// hadn't elapsed yet.
174218
act(() => {
175219
vi.advanceTimersByTime(200);
176220
});
177221
rerenderWithElement(makeElement({ id: "s2-bg" }));
222+
expect(onSetAttributeLive).toHaveBeenCalledTimes(1);
223+
const [attr, value] = onSetAttributeLive.mock.calls[0] as [string, string];
224+
expect(attr).toBe("color-grading");
225+
expect(value).toContain("fresh-pop");
226+
// And it must not ALSO fire again once the (now-cleared) original timer
227+
// window would have elapsed.
178228
act(() => {
179229
vi.advanceTimersByTime(400);
180230
});
181-
expect(onSetAttributeLive).not.toHaveBeenCalled();
231+
expect(onSetAttributeLive).toHaveBeenCalledTimes(1);
182232
act(() => root.unmount());
183233
vi.useRealTimers();
184234
});

‎packages/studio/src/components/editor/useColorGradingController.ts‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -189,10 +189,22 @@ export function useColorGradingController({
189189
const [mediaMetadata, setMediaMetadata] = useState<MediaMetadata | null>(null);
190190
const persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
191191
const pendingPersistValueRef = useRef<string | null | undefined>(undefined);
192+
const pendingPersistGradingRef = useRef<NormalizedHfColorGrading | null>(null);
193+
// The last grading value actually confirmed saved — distinct from `grading`
194+
// (the optimistic value shown immediately on commit). A rejected persist
195+
// reverts to this instead of leaving the UI permanently showing a value
196+
// that was never written.
197+
const confirmedGradingRef = useRef(grading);
192198
const statusTimersRef = useRef<number[]>([]);
193199
const onSetAttributeLiveRef = useRef(onSetAttributeLive);
194200
const latestGradingRef = useRef(grading);
195201
const compareEnabledRef = useRef(compareEnabled);
202+
// Captured before reassignment below — still bound to whatever selection
203+
// was current on the PREVIOUS render. `commitDataAttribute` (the eventual
204+
// callee) closes over `domEditSelection` in its own useCallback deps, so a
205+
// selection change mints an entirely new `onSetAttributeLive` closure; this
206+
// stale reference is exactly what still targets the outgoing element.
207+
const previousOnSetAttributeLive = onSetAttributeLiveRef.current;
196208
onSetAttributeLiveRef.current = onSetAttributeLive;
197209
latestGradingRef.current = grading;
198210
compareEnabledRef.current = compareEnabled;
@@ -214,11 +226,22 @@ export function useColorGradingController({
214226
clearTimeout(persistTimerRef.current);
215227
persistTimerRef.current = null;
216228
}
229+
// Flush — don't discard — a still-pending edit for the OUTGOING element.
230+
// Cancelling the debounce without writing would silently drop whatever
231+
// the user just changed; targeting it at the callback bound to the OLD
232+
// selection (captured above) keeps it from landing on the new element.
233+
if (pendingPersistValueRef.current !== undefined) {
234+
trackStudioPendingEdit(
235+
previousOnSetAttributeLive(COLOR_GRADING_DATA_KEY, pendingPersistValueRef.current),
236+
);
237+
}
217238
pendingPersistValueRef.current = undefined;
239+
pendingPersistGradingRef.current = null;
218240
for (const timer of statusTimersRef.current) clearTimeout(timer);
219241
statusTimersRef.current = [];
220242
const freshGrading = readColorGradingFromElement(element);
221243
latestGradingRef.current = freshGrading;
244+
confirmedGradingRef.current = freshGrading;
222245
setGrading(freshGrading);
223246
setCompareEnabled(false);
224247
compareEnabledRef.current = false;
@@ -300,11 +323,30 @@ export function useColorGradingController({
300323
refreshRuntimeStatus();
301324
}, [refreshRuntimeStatus]);
302325

303-
const persistColorGradingValue = useCallback((value: string | null) => {
304-
return trackStudioPendingEdit(
305-
onSetAttributeLiveRef.current(COLOR_GRADING_DATA_KEY, value ?? null),
306-
);
307-
}, []);
326+
const persistColorGradingValue = useCallback(
327+
(value: string | null, attemptedGrading: NormalizedHfColorGrading) => {
328+
const result = onSetAttributeLiveRef.current(COLOR_GRADING_DATA_KEY, value ?? null);
329+
return trackStudioPendingEdit(
330+
Promise.resolve(result).then(
331+
() => {
332+
confirmedGradingRef.current = attemptedGrading;
333+
},
334+
() => {
335+
// Persist failed — the optimistic grading was never actually
336+
// saved. Revert to the last confirmed-good value instead of
337+
// leaving the control showing an unsaved state as if it succeeded.
338+
// Handled here (not rethrown) — nothing downstream awaits this
339+
// promise's rejection; callers fire it with `void`.
340+
const reverted = confirmedGradingRef.current;
341+
latestGradingRef.current = reverted;
342+
setGrading(reverted);
343+
setRuntimeStatus({ state: "unavailable", message: "Save failed — reverted" });
344+
},
345+
),
346+
);
347+
},
348+
[],
349+
);
308350

309351
const flushPendingPersist = useCallback(() => {
310352
if (persistTimerRef.current) {
@@ -313,8 +355,10 @@ export function useColorGradingController({
313355
}
314356
if (pendingPersistValueRef.current === undefined) return undefined;
315357
const value = pendingPersistValueRef.current;
358+
const attemptedGrading = pendingPersistGradingRef.current ?? latestGradingRef.current;
316359
pendingPersistValueRef.current = undefined;
317-
return persistColorGradingValue(value);
360+
pendingPersistGradingRef.current = null;
361+
return persistColorGradingValue(value, attemptedGrading);
318362
}, [persistColorGradingValue]);
319363

320364
useEffect(() => addStudioPendingEditFlushListener(flushPendingPersist), [flushPendingPersist]);
@@ -399,11 +443,14 @@ export function useColorGradingController({
399443
pendingPersistValueRef.current = isHfColorGradingActive(nextGrading)
400444
? serializeHfColorGrading(nextGrading)
401445
: null;
446+
pendingPersistGradingRef.current = nextGrading;
402447
persistTimerRef.current = setTimeout(() => {
403448
const value = pendingPersistValueRef.current;
449+
const attemptedGrading = pendingPersistGradingRef.current ?? nextGrading;
404450
pendingPersistValueRef.current = undefined;
451+
pendingPersistGradingRef.current = null;
405452
persistTimerRef.current = null;
406-
void persistColorGradingValue(value ?? null);
453+
void persistColorGradingValue(value ?? null, attemptedGrading);
407454
}, 350);
408455
},
409456
[persistColorGradingValue, postColorGrading, postCompare, scheduleRuntimeStatusRefresh],

0 commit comments

Comments
 (0)