Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(queries): simple undo primitive for queries (#1301)
teo23a3d9ae515b
diff --git a/js/app/packages/queries/undo.test.ts b/js/app/packages/queries/undo.test.tsnew file mode 100644index 0000000000..eb254ea3ca--- /dev/null+++ b/js/app/packages/queries/undo.test.ts@@ -0,0 +1,223 @@+import { describe, expect, it } from 'vitest';+import { createRoot } from 'solid-js';+import { MutationUndoProvider, useMutationUndoContext } from './undo';++describe('MutationUndoProvider', () => {+ it('pushes, undoes, and redoes entries', async () => {+ await createRoot(async (dispose) => {+ let ctx!: ReturnType<typeof useMutationUndoContext>;++ MutationUndoProvider({+ get children() {+ ctx = useMutationUndoContext();+ return null;+ },+ });++ let undoCalls = 0;+ let redoCalls = 0;++ ctx.pushUndo({+ undo: () => {+ undoCalls += 1;+ },+ redo: () => {+ redoCalls += 1;+ },+ });++ expect(ctx.canUndo()).toBe(true);+ expect(ctx.canRedo()).toBe(false);++ await ctx.undo();++ expect(undoCalls).toBe(1);+ expect(ctx.canUndo()).toBe(false);+ expect(ctx.canRedo()).toBe(true);++ await ctx.redo();++ expect(redoCalls).toBe(1);+ expect(ctx.canUndo()).toBe(true);+ expect(ctx.canRedo()).toBe(false);++ dispose();+ });+ });++ it('clears redo history when a new undo is pushed', async () => {+ await createRoot(async (dispose) => {+ let ctx!: ReturnType<typeof useMutationUndoContext>;++ MutationUndoProvider({+ get children() {+ ctx = useMutationUndoContext();+ return null;+ },+ });++ let redoCalls = 0;++ ctx.pushUndo({+ undo: () => {},+ redo: () => {+ redoCalls += 1;+ },+ });++ await ctx.undo();+ expect(ctx.canRedo()).toBe(true);++ ctx.pushUndo({+ undo: () => {},+ });++ expect(ctx.canRedo()).toBe(false);+ await ctx.redo();+ expect(redoCalls).toBe(0);++ dispose();+ });+ });++ it('no-ops when stacks are empty', async () => {+ await createRoot(async (dispose) => {+ let ctx!: ReturnType<typeof useMutationUndoContext>;++ MutationUndoProvider({+ get children() {+ ctx = useMutationUndoContext();+ return null;+ },+ });++ await ctx.undo();+ await ctx.redo();++ expect(ctx.canUndo()).toBe(false);+ expect(ctx.canRedo()).toBe(false);++ dispose();+ });+ });++ it('throws when useMutationUndoContext is called outside provider', () => {+ expect(() => {+ createRoot(() => {+ useMutationUndoContext();+ });+ }).toThrow('MutationUndo must be used within <MutationUndoProvider />');+ });++ it('calls onSuccess and onSettled callbacks on successful undo', async () => {+ await createRoot(async (dispose) => {+ let ctx!: ReturnType<typeof useMutationUndoContext>;++ MutationUndoProvider({+ get children() {+ ctx = useMutationUndoContext();+ return null;+ },+ });++ let successCalled = false;+ let settledCalled = false;++ ctx.pushUndo({ undo: () => {} });++ await ctx.undo({+ onSuccess: () => {+ successCalled = true;+ },+ onSettled: () => {+ settledCalled = true;+ },+ });++ expect(successCalled).toBe(true);+ expect(settledCalled).toBe(true);++ dispose();+ });+ });++ it('calls onError and onSettled callbacks on failed undo and restores stack', async () => {+ await createRoot(async (dispose) => {+ let ctx!: ReturnType<typeof useMutationUndoContext>;++ MutationUndoProvider({+ get children() {+ ctx = useMutationUndoContext();+ return null;+ },+ });++ let errorCalled = false;+ let settledCalled = false;+ let capturedError: Error | undefined;++ ctx.pushUndo({+ undo: () => {+ throw new Error('undo failed');+ },+ });++ expect(ctx.canUndo()).toBe(true);++ await ctx.undo({+ onError: (err) => {+ errorCalled = true;+ capturedError = err;+ },+ onSettled: () => {+ settledCalled = true;+ },+ });++ expect(errorCalled).toBe(true);+ expect(settledCalled).toBe(true);+ expect(capturedError?.message).toBe('undo failed');+ // Stack should be restored after failure+ expect(ctx.canUndo()).toBe(true);++ dispose();+ });+ });++ it('calls onError on failed redo and restores stack', async () => {+ await createRoot(async (dispose) => {+ let ctx!: ReturnType<typeof useMutationUndoContext>;++ MutationUndoProvider({+ get children() {+ ctx = useMutationUndoContext();+ return null;+ },+ });++ let errorCalled = false;++ ctx.pushUndo({+ undo: () => {},+ redo: () => {+ throw new Error('redo failed');+ },+ });++ await ctx.undo();+ expect(ctx.canRedo()).toBe(true);++ await ctx.redo({+ onError: () => {+ errorCalled = true;+ },+ });++ expect(errorCalled).toBe(true);+ // Stack should be restored after failure+ expect(ctx.canRedo()).toBe(true);++ dispose();+ });+ });+});diff --git a/js/app/packages/queries/undo.ts b/js/app/packages/queries/undo.tsnew file mode 100644index 0000000000..99f6972b43--- /dev/null+++ b/js/app/packages/queries/undo.ts@@ -0,0 +1,153 @@+/**+ * Undo/redo support for mutations.+ *+ * @example+ * // 1. Wrap your app with the provider+ * <MutationUndoProvider>+ * <App />+ * </MutationUndoProvider>+ *+ * // 2. Use undoable mutations+ * const updateItem = useUndoableMutation(() => ({+ * mutationFn: (data) => api.update(data.id, data.value),+ * undoFn: (variables) => api.update(variables.id, variables.previousValue),+ * redoFn: (variables) => api.update(variables.id, variables.value),+ * }));+ *+ * // 3. Trigger undo/redo with callbacks+ * const { undo, redo, canUndo, canRedo } = useMutationUndoContext();+ * await undo({+ * onSuccess: () => toast.success('Undone'),+ * onError: (err) => toast.error(err.message),+ * });+ */++import { type MutationOptions, useMutation } from '@tanstack/solid-query';+import { createSignal } from 'solid-js';+import { createAssertedContextProvider } from '@core/context/createContext';++type UndoHandler<TVariables, TContext> = (+ variables: TVariables,+ context: TContext | undefined+) => Promise<void> | void;++type UndoEntry = {+ undo: () => Promise<void> | void;+ redo?: () => Promise<void> | void;+ label?: string;+};++type UndoCallbacks = {+ onSuccess?: () => void;+ onError?: (error: Error) => void;+ onSettled?: () => void;+};++type MutationUndoContextValue = {+ pushUndo: (entry: UndoEntry) => void;+ canUndo: () => boolean;+ canRedo: () => boolean;+ clear: () => void;+ undo: (callbacks?: UndoCallbacks) => Promise<void>;+ redo: (callbacks?: UndoCallbacks) => Promise<void>;+};++export const [MutationUndoProvider, useMutationUndoContext] =+ createAssertedContextProvider(+ 'MutationUndo',+ (): MutationUndoContextValue => {+ const [undoStack, setUndoStack] = createSignal<UndoEntry[]>([]);+ const [redoStack, setRedoStack] = createSignal<UndoEntry[]>([]);++ return {+ pushUndo: (entry) => {+ setUndoStack((prev) => [...prev, entry]);+ setRedoStack([]);+ },++ canUndo: () => undoStack().length > 0,+ canRedo: () => redoStack().length > 0,++ clear: () => {+ setUndoStack([]);+ setRedoStack([]);+ },++ undo: async (callbacks?: UndoCallbacks) => {+ const stack = undoStack();+ const entry = stack.at(-1);+ if (!entry) return;++ setUndoStack(stack.slice(0, -1));+ try {+ await entry.undo();+ if (entry.redo) {+ setRedoStack((prev) => [...prev, entry]);+ }+ callbacks?.onSuccess?.();+ } catch (err) {+ setUndoStack((prev) => [...prev, entry]);+ callbacks?.onError?.(+ err instanceof Error ? err : new Error(String(err))+ );+ } finally {+ callbacks?.onSettled?.();+ }+ },++ redo: async (callbacks?: UndoCallbacks) => {+ const stack = redoStack();+ const entry = stack.at(-1);+ if (!entry) return;++ setRedoStack(stack.slice(0, -1));+ try {+ if (entry.redo) {+ await entry.redo();+ }+ setUndoStack((prev) => [...prev, entry]);+ callbacks?.onSuccess?.();+ } catch (err) {+ setRedoStack((prev) => [...prev, entry]);+ callbacks?.onError?.(+ err instanceof Error ? err : new Error(String(err))+ );+ } finally {+ callbacks?.onSettled?.();+ }+ },+ };+ }+ );++export function useUndoableMutation<+ TData = unknown,+ TError = Error,+ TVariables = void,+ TContext = unknown,+>(+ options: () => MutationOptions<TData, TError, TVariables, TContext> & {+ undoFn?: UndoHandler<TVariables, TContext>;+ redoFn?: UndoHandler<TVariables, TContext>;+ undoLabel?: string;+ }+) {+ const { pushUndo } = useMutationUndoContext();++ return useMutation(() => {+ const { undoFn, redoFn, undoLabel, onSuccess, ...opts } = options();+ return {+ ...opts,+ onSuccess: (data, variables, context, mutation) => {+ if (undoFn) {+ pushUndo({+ undo: () => undoFn(variables, context),+ redo: redoFn ? () => redoFn(variables, context) : undefined,+ label: undoLabel,+ });+ }+ onSuccess?.(data, variables, context, mutation);+ },+ };+ });+}