Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(undo): bind cmd+z / shift+cmd+z to the mutation undo stack (#2714)

gbirman27082c3174a7
diff --git a/js/app/packages/app/component/GlobalHotkeys.tsx b/js/app/packages/app/component/GlobalHotkeys.tsx
index 548142982a..d98facd22d 100644
--- a/js/app/packages/app/component/GlobalHotkeys.tsx
+++ b/js/app/packages/app/component/GlobalHotkeys.tsx
@@ -1,8 +1,10 @@
import { useOpenInstructionsMd } from '@core/component/AI/util/instructions';
+import { toast } from '@core/component/Toast/Toast';
import { useSettingsState } from '@core/constant/SettingsState';
import { TOKENS } from '@core/hotkey/tokens';
import type { ValidHotkey } from '@core/hotkey/types';
import { AiInstructionsIcon } from '@queries/storage/instructions-md';
+import { useMutationUndoContext } from '@queries/undo';
import { registerHotkey } from 'core/hotkey/hotkeys';
import { createMemo, onCleanup } from 'solid-js';
import { useLogout } from '@core/auth/logout';
@@ -93,6 +95,7 @@ export default function GlobalShortcuts() {
const canFit = () => globalSplitManager()?.canAppendSplit() ?? true;
const analytics = useAnalytics();
+ const undoCtx = useMutationUndoContext();
useHotkeyAnalytics();
@@ -404,5 +407,33 @@ export default function GlobalShortcuts() {
},
});
+ registerHotkey({
+ hotkeyToken: TOKENS.global.undo,
+ hotkey: 'cmd+z',
+ scopeId: 'global',
+ description: 'Undo',
+ keyDownHandler: (e) => {
+ if (!undoCtx.canUndo()) return false;
+ e?.preventDefault();
+ undoCtx.undo({ onError: () => toast.failure('Failed to undo') });
+ return true;
+ },
+ condition: () => undoCtx.canUndo(),
+ });
+
+ registerHotkey({
+ hotkeyToken: TOKENS.global.redo,
+ hotkey: 'shift+cmd+z',
+ scopeId: 'global',
+ description: 'Redo',
+ keyDownHandler: (e) => {
+ if (!undoCtx.canRedo()) return false;
+ e?.preventDefault();
+ undoCtx.redo({ onError: () => toast.failure('Failed to redo') });
+ return true;
+ },
+ condition: () => undoCtx.canRedo(),
+ });
+
return null;
}
diff --git a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
index 1561fd85ee..123d77483d 100644
--- a/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
+++ b/js/app/packages/app/component/next-soup/actions/make-mark-done-action.ts
@@ -2,7 +2,7 @@ import ArrowCounterClockwise from '@phosphor-icons/core/regular/arrow-counter-cl
import { toast } from '@core/component/Toast/Toast';
import { type EntityData, isTaskEntity } from '@entity';
import type { NotificationSource } from '@notifications';
-import { useMutationUndoContext, useUndoableMutation } from '@queries/undo';
+import { useUndoableMutation } from '@queries/undo';
import {
applyEntitiesDoneOptimistic,
executeMarkEntitiesDone,
@@ -30,7 +30,6 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
const { notificationSource } = options;
const previewPanel = useMaybePreviewPanel();
const inPreview = previewPanel !== undefined;
- const undoCtx = useMutationUndoContext();
const mutation = useUndoableMutation<
void,
@@ -43,36 +42,11 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
emailIds: variables.emailIds,
notificationIds: variables.notificationIds,
}),
- mutationFn: async (variables) =>
- await executeMarkEntitiesDone({
+ mutationFn: (variables) =>
+ executeMarkEntitiesDone({
emailIds: variables.emailIds,
notificationIds: variables.notificationIds,
}),
- onSuccess: (_data, variables) => {
- const count = variables.entities.length;
- const firstEntityId = variables.entities[0]?.id;
- const toastId = toast.success(
- count > 1 ? `Marked ${count} items as done` : 'Marked as done',
- undefined,
- [
- {
- label: 'Undo',
- icon: ArrowCounterClockwise,
- onClick: () => {
- if (toastId != null) toast.dismiss(toastId);
- // Route through the undo stack so the entry is popped and
- // Cmd+Z / shift+Cmd+Z stay in sync with the toast action.
- undoCtx.undo({
- onError: () => toast.failure('Failed to undo'),
- });
- restoreSoupFocus(firstEntityId, inPreview);
- },
- },
- ],
- 10_000,
- true
- );
- },
onError: (_err, _variables, context) => {
context?.rollback();
toast.failure('Failed to mark as done');
@@ -102,6 +76,43 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
}
},
undoLabel: 'Mark Done',
+ onPushed: (handle, variables) => {
+ const firstEntityId = variables.entities[0]?.id;
+ const count = variables.entities.length;
+ const message =
+ count > 1 ? `Marked ${count} items as done` : 'Marked as done';
+ let toastId: number | undefined;
+
+ const showToast = () => {
+ toastId = toast.success(
+ message,
+ undefined,
+ [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: () => {
+ handle.undo({
+ onError: () => toast.failure('Failed to undo'),
+ });
+ restoreSoupFocus(firstEntityId, inPreview);
+ },
+ },
+ ],
+ 10_000,
+ true
+ );
+ };
+
+ showToast();
+
+ return {
+ onUndone: () => {
+ if (toastId !== undefined) toast.dismiss(toastId);
+ },
+ onRedone: showToast,
+ };
+ },
}));
const canExecute = (entity: EntityData): boolean => {
@@ -137,7 +148,6 @@ export const makeMarkDoneAction = (options: MakeMarkDoneOptions) => {
const nextEntity =
soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
- // Run collapse animation if conditions are met (touch modality + not-done filter active)
if (soup.collapseEntity.shouldCollapse()) {
const collapse = soup.collapseEntity.callback();
if (collapse) {
diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.ts
index 465f3221b5..92687d054c 100644
--- a/js/app/packages/core/hotkey/tokens.ts
+++ b/js/app/packages/core/hotkey/tokens.ts
@@ -77,6 +77,8 @@ export const TOKENS = {
createNewSplit: 'global.createNewSplit',
toggleVisor: 'global.toggleVisor',
inviteTeam: 'global.inviteTeam',
+ undo: 'global.undo',
+ redo: 'global.redo',
},
// email
diff --git a/js/app/packages/entity/src/extractors-notification/notification-actions.tsx b/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
index 75f98e3319..b6e89f71b0 100644
--- a/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
+++ b/js/app/packages/entity/src/extractors-notification/notification-actions.tsx
@@ -6,7 +6,7 @@ import {
executeMarkNotificationsUndone,
getAllNotificationsFromGroup,
} from '@notifications';
-import { useMutationUndoContext, useUndoableMutation } from '@queries/undo';
+import { useUndoableMutation } from '@queries/undo';
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import { restoreSoupFocus } from '@app/component/next-soup/utils';
@@ -26,42 +26,50 @@ type MarkStackDoneVariables = { notificationIds: string[] };
export function useNotificationStackActions(props: NotificationActionsProps) {
const notificationSource = useGlobalNotificationSource();
- const undoCtx = useMutationUndoContext();
const mutation = useUndoableMutation<void, Error, MarkStackDoneVariables>(
() => ({
- mutationFn: async (vars) =>
- await executeMarkNotificationsDone(vars.notificationIds),
- onSuccess: () => {
- const toastId = toast.success(
- 'Marked as done',
- undefined,
- [
- {
- label: 'Undo',
- icon: ArrowCounterClockwise,
- onClick: () => {
- if (toastId != null) toast.dismiss(toastId);
- undoCtx.undo({
- onError: () => toast.failure('Failed to undo'),
- });
- restoreSoupFocus();
- },
- },
- ],
- 10_000,
- true
- );
- props.onMarkAsDone?.();
- },
+ mutationFn: (vars) => executeMarkNotificationsDone(vars.notificationIds),
onError: () => {
toast.failure('Failed to mark as done');
},
- undoFn: async (vars) =>
- await executeMarkNotificationsUndone(vars.notificationIds),
- redoFn: async (vars) =>
- await executeMarkNotificationsDone(vars.notificationIds),
+ undoFn: (vars) => executeMarkNotificationsUndone(vars.notificationIds),
+ redoFn: (vars) => executeMarkNotificationsDone(vars.notificationIds),
undoLabel: 'Mark Done',
+ onPushed: (handle) => {
+ let toastId: number | undefined;
+
+ const showToast = () => {
+ toastId = toast.success(
+ 'Marked as done',
+ undefined,
+ [
+ {
+ label: 'Undo',
+ icon: ArrowCounterClockwise,
+ onClick: () => {
+ handle.undo({
+ onError: () => toast.failure('Failed to undo'),
+ });
+ restoreSoupFocus();
+ },
+ },
+ ],
+ 10_000,
+ true
+ );
+ };
+
+ showToast();
+ props.onMarkAsDone?.();
+
+ return {
+ onUndone: () => {
+ if (toastId !== undefined) toast.dismiss(toastId);
+ },
+ onRedone: showToast,
+ };
+ },
})
);
diff --git a/js/app/packages/queries/undo.ts b/js/app/packages/queries/undo.ts
index 99f6972b43..e159ee3d2e 100644
--- a/js/app/packages/queries/undo.ts
+++ b/js/app/packages/queries/undo.ts
@@ -7,19 +7,21 @@
* <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),
- * }));
+ * // 2. Push an entry directly and bind side effects (toast, highlight, etc.)
+ * // to its lifecycle hooks.
+ * const { pushUndo } = useMutationUndoContext();
+ * const handle = pushUndo({
+ * undo: async () => api.update(id, previousValue),
+ * redo: async () => api.update(id, nextValue),
+ * onUndone: () => toast.dismiss(toastId),
+ * onRedone: () => showToast(),
+ * });
+ *
+ * // 3. Target this specific entry from UI (e.g. an Undo button):
+ * handle.undo({ onError: (e) => toast.failure(e.message) });
*
- * // 3. Trigger undo/redo with callbacks
+ * // 4. Global LIFO shortcuts (cmd+z / shift+cmd+z) use the stack top:
* 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';
@@ -32,9 +34,23 @@ type UndoHandler<TVariables, TContext> = (
) => Promise<void> | void;
type UndoEntry = {
+ id: string;
undo: () => Promise<void> | void;
redo?: () => Promise<void> | void;
label?: string;
+ /** Fires after `undo` resolves, regardless of whether it was triggered by
+ * `handle.undo()` or the global `ctx.undo()` LIFO call. */
+ onUndone?: () => void;
+ /** Fires after `redo` resolves. */
+ onRedone?: () => void;
+};
+
+export type UndoEntryInput = Omit<UndoEntry, 'id'>;
+
+export type UndoHandle = {
+ id: string;
+ /** Undo this specific entry, even if it is not at the top of the stack. */
+ undo: (callbacks?: UndoCallbacks) => Promise<void>;
};
type UndoCallbacks = {
@@ -44,7 +60,7 @@ type UndoCallbacks = {
};
type MutationUndoContextValue = {
- pushUndo: (entry: UndoEntry) => void;
+ pushUndo: (entry: UndoEntryInput) => UndoHandle;
canUndo: () => boolean;
canRedo: () => boolean;
clear: () => void;
@@ -52,6 +68,11 @@ type MutationUndoContextValue = {
redo: (callbacks?: UndoCallbacks) => Promise<void>;
};
+const genId = (): string =>
+ typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
+ ? crypto.randomUUID()
+ : `undo-${Date.now()}-${Math.random().toString(36).slice(2)}`;
+
export const [MutationUndoProvider, useMutationUndoContext] =
createAssertedContextProvider(
'MutationUndo',
@@ -59,10 +80,70 @@ export const [MutationUndoProvider, useMutationUndoContext] =
const [undoStack, setUndoStack] = createSignal<UndoEntry[]>([]);
const [redoStack, setRedoStack] = createSignal<UndoEntry[]>([]);
+ const runUndo = async (
+ entry: UndoEntry,
+ callbacks?: UndoCallbacks
+ ): Promise<void> => {
+ const current = undoStack();
+ const prevPos = current.indexOf(entry);
+ // Already removed (e.g. handle.undo() called twice, or entry was
+ // cleared by a new pushUndo after redoStack reset).
+ if (prevPos < 0) return;
+
+ setUndoStack(current.filter((e) => e !== entry));
+ try {
+ await entry.undo();
+ if (entry.redo) {
+ setRedoStack((prev) => [...prev, entry]);
+ }
+ entry.onUndone?.();
+ callbacks?.onSuccess?.();
+ } catch (err) {
+ // Restore at original position so a non-top undo that fails doesn't
+ // reorder the stack.
+ setUndoStack((prev) => {
+ const next = [...prev];
+ next.splice(Math.min(prevPos, next.length), 0, entry);
+ return next;
+ });
+ callbacks?.onError?.(
+ err instanceof Error ? err : new Error(String(err))
+ );
+ } finally {
+ callbacks?.onSettled?.();
+ }
+ };
+
+ const runRedo = async (
+ entry: UndoEntry,
+ callbacks?: UndoCallbacks
+ ): Promise<void> => {
+ try {
+ if (entry.redo) {
+ await entry.redo();
+ }
+ setUndoStack((prev) => [...prev, entry]);
+ entry.onRedone?.();
+ callbacks?.onSuccess?.();
+ } catch (err) {
+ setRedoStack((prev) => [...prev, entry]);
+ callbacks?.onError?.(
+ err instanceof Error ? err : new Error(String(err))
+ );
+ } finally {
+ callbacks?.onSettled?.();
+ }
+ };
+
return {
- pushUndo: (entry) => {
+ pushUndo: (input) => {
+ const entry: UndoEntry = { ...input, id: genId() };
setUndoStack((prev) => [...prev, entry]);
setRedoStack([]);
+ return {
+ id: entry.id,
+ undo: (callbacks) => runUndo(entry, callbacks),
+ };
},
canUndo: () => undoStack().length > 0,
@@ -73,53 +154,28 @@ export const [MutationUndoProvider, useMutationUndoContext] =
setRedoStack([]);
},
- undo: async (callbacks?: UndoCallbacks) => {
- const stack = undoStack();
- const entry = stack.at(-1);
+ undo: async (callbacks) => {
+ const entry = undoStack().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?.();
- }
+ await runUndo(entry, callbacks);
},
- redo: async (callbacks?: UndoCallbacks) => {
+ redo: async (callbacks) => {
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?.();
- }
+ await runRedo(entry, callbacks);
},
};
}
);
+export type UndoLifecycle = {
+ onUndone?: () => void;
+ onRedone?: () => void;
+};
+
export function useUndoableMutation<
TData = unknown,
TError = Error,
@@ -130,21 +186,36 @@ export function useUndoableMutation<
undoFn?: UndoHandler<TVariables, TContext>;
redoFn?: UndoHandler<TVariables, TContext>;
undoLabel?: string;
+ /** Fires after the entry is pushed onto the undo stack. Returned
+ * lifecycle hooks (onUndone/onRedone) will run on this specific
+ * entry — regardless of whether it is undone via the returned
+ * handle, the global LIFO `ctx.undo()`, or by a later `ctx.redo()`. */
+ onPushed?: (
+ handle: UndoHandle,
+ variables: TVariables,
+ context: TContext | undefined
+ ) => UndoLifecycle | void;
}
) {
const { pushUndo } = useMutationUndoContext();
return useMutation(() => {
- const { undoFn, redoFn, undoLabel, onSuccess, ...opts } = options();
+ const { undoFn, redoFn, undoLabel, onPushed, onSuccess, ...opts } =
+ options();
return {
...opts,
onSuccess: (data, variables, context, mutation) => {
if (undoFn) {
- pushUndo({
+ const lifecycleRef: { current?: UndoLifecycle } = {};
+ const handle = pushUndo({
undo: () => undoFn(variables, context),
redo: redoFn ? () => redoFn(variables, context) : undefined,
label: undoLabel,
+ onUndone: () => lifecycleRef.current?.onUndone?.(),
+ onRedone: () => lifecycleRef.current?.onRedone?.(),
});
+ lifecycleRef.current =
+ onPushed?.(handle, variables, context) ?? undefined;
}
onSuccess?.(data, variables, context, mutation);
},