Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix: keep gradient stop drags in one undo step
Richie McIlroyc6365f9bf961
diff --git a/apps/desktop-gpui/src/editor_sidebar/animated_gradient.rs b/apps/desktop-gpui/src/editor_sidebar/animated_gradient.rsindex 8fa60dab8..ffda5323b 100644--- a/apps/desktop-gpui/src/editor_sidebar/animated_gradient.rs+++ b/apps/desktop-gpui/src/editor_sidebar/animated_gradient.rs@@ -590,19 +590,22 @@ impl EditorWindow {let Some(fraction) = ui::fraction_from_x(event.position.x, bounds) else {return;};- let mut inserted = None;self.close_color_picker(cx);+ let Some(mut updated) = self.animated_gradient_config().cloned() else {+ return;+ };+ let Some(index) = insert_stop(&mut updated, fraction * 100.) else {+ return;+ };+ self.begin_animated_gradient_stop_drag(index, cx);self.edit_animated_gradient(|config| {- inserted = insert_stop(config, fraction * 100.);- inserted.is_some()+ *config = updated;+ true},window,cx,);- if let Some(index) = inserted {- self.begin_animated_gradient_stop_drag(index, cx);- }}fn add_animated_gradient_stop(&mut self, window: &mut Window, cx: &mut Context<Self>) {@@ -1406,6 +1409,36 @@ mod tests {assert_eq!(stop_limits(&config, 4), (75., 100.));}+ #[test]+ fn adding_and_dragging_a_colour_is_one_history_entry() {+ let mut config = AnimatedGradientConfig::default();+ assert!(remove_stop(&mut config, 2));+ let mut project = ProjectConfiguration::default();+ project.background.source = BackgroundSource::AnimatedGradient { config };+ let initial = project.clone();+ let mut history = crate::editor_edits::ProjectHistory::new(initial.clone());+ let mut drag = ui::SliderDrag::new();+ let BackgroundSource::AnimatedGradient { config } = &mut project.background.source else {+ panic!("expected animated gradient");+ };+ let mut updated = config.clone();+ let index = insert_stop(&mut updated, 40.).unwrap();+ drag.begin(SliderKey::AnimatedGradientStop(index), || history.pause());+ *config = updated;+ history.record(&project);+ let BackgroundSource::AnimatedGradient { config } = &mut project.background.source else {+ panic!("expected animated gradient");+ };+ config.color_stops[index].position = 50.;+ history.record(&project);+ drag.end(|| history.resume(&project));+ assert_eq!(+ serde_json::to_value(history.undo().unwrap()).unwrap(),+ serde_json::to_value(&initial).unwrap()+ );+ assert!(!history.can_undo());+ }+#[test]fn control_values_read_like_the_solid_editor() {let direction = AnimatedGradientParameter::Direction.control();diff --git a/apps/desktop/src/routes/editor/AnimatedGradientEditor.tsx b/apps/desktop/src/routes/editor/AnimatedGradientEditor.tsxindex 4ddb7d6a2..910586401 100644--- a/apps/desktop/src/routes/editor/AnimatedGradientEditor.tsx+++ b/apps/desktop/src/routes/editor/AnimatedGradientEditor.tsx@@ -26,6 +26,10 @@ import IconLucideSave from "~icons/lucide/save";import IconLucideShuffle from "~icons/lucide/shuffle";import IconLucideTrash2 from "~icons/lucide/trash-2";import IconLucideX from "~icons/lucide/x";+import {+ type PointerDragSession,+ startPointerDrag,+} from "./animated-gradient-drag";import { BrandColorsDropdown } from "./BrandColorsDropdown";import { hexToRgb, RgbInput } from "./color-utils";import { useEditorContext } from "./context";@@ -189,8 +193,11 @@ export function AnimatedGradientEditor(props: {let disposed = false;let revision = 0;let barRef!: HTMLDivElement;+ let activeDrag: PointerDragSession | null = null;onCleanup(() => {disposed = true;+ activeDrag?.cleanup();+ activeDrag = null;});const config = createMemo(() => {@@ -297,26 +304,26 @@ export function AnimatedGradientEditor(props: {);};- const dragStop = (index: number, event: PointerEvent) => {+ const dragStop = (+ index: () => number | null,+ event: PointerEvent,+ options?: { pauseImmediately?: boolean; onStart?: () => void },+ ) => {const target = event.currentTarget as HTMLElement;- target.setPointerCapture(event.pointerId);- let resume: (() => void) | null = null;- const move = (moveEvent: PointerEvent) => {- const position = barPosition(moveEvent);- if (position === null) return;- if (!resume) resume = projectHistory.pause();- moveStop(index, position);- };- const end = () => {- target.removeEventListener("pointermove", move);- target.removeEventListener("pointerup", end);- target.removeEventListener("pointercancel", end);- resume?.();- resume = null;- };- target.addEventListener("pointermove", move);- target.addEventListener("pointerup", end);- target.addEventListener("pointercancel", end);+ activeDrag?.cleanup();+ activeDrag = startPointerDrag({+ target,+ pointerId: event.pointerId,+ pauseHistory: projectHistory.pause,+ pauseImmediately: options?.pauseImmediately,+ onStart: options?.onStart,+ onMove: (moveEvent) => {+ const position = barPosition(moveEvent);+ const stopIndex = index();+ if (position !== null && stopIndex !== null)+ moveStop(stopIndex, position);+ },+ });};const resetFineTune = () => {@@ -550,9 +557,18 @@ export function AnimatedGradientEditor(props: {onPointerDown={(event) => {if (event.button !== 0) return;const position = barPosition(event);- if (position === null) return;- const index = addStop(position);- if (index !== null) dragStop(index, event);+ if (+ position === null ||+ current().colorStops.length >= MAX_STOPS+ )+ return;+ let index: number | null = null;+ dragStop(() => index, event, {+ pauseImmediately: true,+ onStart: () => {+ index = addStop(position);+ },+ });}}><div@@ -576,7 +592,7 @@ export function AnimatedGradientEditor(props: {if (event.button !== 0) return;event.stopPropagation();setSelectedStop(index);- dragStop(index, event);+ dragStop(() => index, event);}}onKeyDown={(event) => {const step = event.shiftKey ? 10 : 1;diff --git a/apps/desktop/src/routes/editor/animated-gradient-drag.test.ts b/apps/desktop/src/routes/editor/animated-gradient-drag.test.tsnew file mode 100644index 000000000..f57879a67--- /dev/null+++ b/apps/desktop/src/routes/editor/animated-gradient-drag.test.ts@@ -0,0 +1,197 @@+import { describe, expect, it, vi } from "vitest";+import { startPointerDrag } from "./animated-gradient-drag";++type GradientState = {+ stops: number[];+};++function createHistory(initial: GradientState) {+ let state = structuredClone(initial);+ let pauseDepth = 0;+ const snapshots = [structuredClone(state)];+ const commit = () => {+ if (+ JSON.stringify(snapshots[snapshots.length - 1]) !== JSON.stringify(state)+ )+ snapshots.push(structuredClone(state));+ };++ return {+ get state() {+ return state;+ },+ get snapshotCount() {+ return snapshots.length;+ },+ get paused() {+ return pauseDepth > 0;+ },+ mutate(update: (value: GradientState) => void) {+ update(state);+ if (pauseDepth === 0) commit();+ },+ pause() {+ pauseDepth += 1;+ let resumed = false;+ return () => {+ if (resumed) return;+ resumed = true;+ pauseDepth -= 1;+ if (pauseDepth === 0) commit();+ };+ },+ undo() {+ if (snapshots.length > 1) snapshots.pop();+ state = structuredClone(snapshots[snapshots.length - 1]);+ },+ };+}++function createTarget() {+ const target = new EventTarget() as EventTarget & {+ setPointerCapture: ReturnType<typeof vi.fn>;+ };+ target.setPointerCapture = vi.fn();+ return target;+}++function pointerEvent(type: string, clientX = 0, pointerId = 7) {+ const event = new Event(type);+ Object.defineProperties(event, {+ clientX: { value: clientX },+ pointerId: { value: pointerId },+ });+ return event;+}++function asElement(target: EventTarget) {+ return target as unknown as HTMLElement;+}++describe("startPointerDrag", () => {+ it("groups adding and dragging a stop into one undo entry", () => {+ const target = createTarget();+ const history = createHistory({ stops: [0, 100] });+ let stopIndex = -1;+ startPointerDrag({+ target: asElement(target),+ pointerId: 7,+ pauseHistory: history.pause,+ pauseImmediately: true,+ onStart: () =>+ history.mutate((state) => {+ stopIndex = 1;+ state.stops.splice(stopIndex, 0, 30);+ }),+ onMove: (event) =>+ history.mutate((state) => {+ state.stops[stopIndex] = event.clientX;+ }),+ });++ target.dispatchEvent(pointerEvent("pointermove", 40));+ target.dispatchEvent(pointerEvent("pointerup", 40));++ expect(history.state.stops).toEqual([0, 40, 100]);+ expect(history.snapshotCount).toBe(2);+ history.undo();+ expect(history.state.stops).toEqual([0, 100]);+ });++ it("groups dragging an existing stop into one undo entry", () => {+ const target = createTarget();+ const history = createHistory({ stops: [0, 30, 100] });+ startPointerDrag({+ target: asElement(target),+ pointerId: 7,+ pauseHistory: history.pause,+ onMove: (event) =>+ history.mutate((state) => {+ state.stops[1] = event.clientX;+ }),+ });++ target.dispatchEvent(pointerEvent("pointermove", 40));+ target.dispatchEvent(pointerEvent("pointermove", 50));+ target.dispatchEvent(pointerEvent("pointerup", 50));++ expect(history.snapshotCount).toBe(2);+ history.undo();+ expect(history.state.stops).toEqual([0, 30, 100]);+ });++ it("keeps a click without movement atomic", () => {+ const addTarget = createTarget();+ const addHistory = createHistory({ stops: [0, 100] });+ startPointerDrag({+ target: asElement(addTarget),+ pointerId: 7,+ pauseHistory: addHistory.pause,+ pauseImmediately: true,+ onStart: () => addHistory.mutate((state) => state.stops.splice(1, 0, 30)),+ onMove: () => undefined,+ });+ addTarget.dispatchEvent(pointerEvent("pointerup", 30));++ expect(addHistory.snapshotCount).toBe(2);+ addHistory.undo();+ expect(addHistory.state.stops).toEqual([0, 100]);++ const existingTarget = createTarget();+ const existingHistory = createHistory({ stops: [0, 30, 100] });+ startPointerDrag({+ target: asElement(existingTarget),+ pointerId: 7,+ pauseHistory: existingHistory.pause,+ onMove: () => undefined,+ });+ existingTarget.dispatchEvent(pointerEvent("pointerup", 30));+ expect(existingHistory.snapshotCount).toBe(1);+ });++ it.each(["pointercancel", "lostpointercapture"])(+ "resumes history and removes listeners on %s",+ (endEvent) => {+ const target = createTarget();+ const history = createHistory({ stops: [0, 30, 100] });+ startPointerDrag({+ target: asElement(target),+ pointerId: 7,+ pauseHistory: history.pause,+ onMove: (event) =>+ history.mutate((state) => {+ state.stops[1] = event.clientX;+ }),+ });++ target.dispatchEvent(pointerEvent("pointermove", 40));+ target.dispatchEvent(pointerEvent(endEvent, 40));+ target.dispatchEvent(pointerEvent("pointermove", 50));++ expect(history.paused).toBe(false);+ expect(history.state.stops).toEqual([0, 40, 100]);+ },+ );++ it("resumes history and removes listeners on unmount cleanup", () => {+ const target = createTarget();+ const history = createHistory({ stops: [0, 30, 100] });+ const session = startPointerDrag({+ target: asElement(target),+ pointerId: 7,+ pauseHistory: history.pause,+ onMove: (event) =>+ history.mutate((state) => {+ state.stops[1] = event.clientX;+ }),+ });++ target.dispatchEvent(pointerEvent("pointermove", 40));+ session.cleanup();+ session.cleanup();+ target.dispatchEvent(pointerEvent("pointermove", 50));++ expect(history.paused).toBe(false);+ expect(history.state.stops).toEqual([0, 40, 100]);+ });+});diff --git a/apps/desktop/src/routes/editor/animated-gradient-drag.ts b/apps/desktop/src/routes/editor/animated-gradient-drag.tsnew file mode 100644index 000000000..ddfa65267--- /dev/null+++ b/apps/desktop/src/routes/editor/animated-gradient-drag.ts@@ -0,0 +1,52 @@+export type PointerDragSession = {+ cleanup: () => void;+};++export function startPointerDrag(options: {+ target: HTMLElement;+ pointerId: number;+ pauseHistory: () => () => void;+ pauseImmediately?: boolean;+ onStart?: () => void;+ onMove: (event: PointerEvent) => void;+}): PointerDragSession {+ let active = true;+ let resumeHistory: (() => void) | null = null;++ const pauseHistory = () => {+ if (!resumeHistory) resumeHistory = options.pauseHistory();+ };+ const move = (event: PointerEvent) => {+ if (event.pointerId !== options.pointerId) return;+ pauseHistory();+ options.onMove(event);+ };+ const cleanup = () => {+ if (!active) return;+ active = false;+ options.target.removeEventListener("pointermove", move);+ options.target.removeEventListener("pointerup", end);+ options.target.removeEventListener("pointercancel", end);+ options.target.removeEventListener("lostpointercapture", end);+ resumeHistory?.();+ resumeHistory = null;+ };+ const end = (event: PointerEvent) => {+ if (event.pointerId === options.pointerId) cleanup();+ };++ options.target.addEventListener("pointermove", move);+ options.target.addEventListener("pointerup", end);+ options.target.addEventListener("pointercancel", end);+ options.target.addEventListener("lostpointercapture", end);+ try {+ options.target.setPointerCapture(options.pointerId);+ if (options.pauseImmediately) pauseHistory();+ options.onStart?.();+ } catch (error) {+ cleanup();+ throw error;+ }++ return { cleanup };+}