feat: undo for destructive photo actions
Add a global last-action stack with toast-based "Undo" buttons and a Cmd/Ctrl+Z hotkey for the destructive photo operations. Reversible: - X (discard) → bulkRestore - U (restore) → bulkDiscard - Drag-onto-Discarded → bulkRestore - Drag-onto-folder (move) → move back to per-photo source folders. The source folder ids are snapshotted from the photos cache before the move runs, then grouped so multi-source moves restore correctly. - Restore button in the discard action bar → bulkDiscard Toast gains an optional action button (label + onClick); toasts with an action stay visible longer so the user has time to click. The undo store caps at 20 entries; failed undo re-pushes the entry so the user can try again. Not reversible (call out, document later): rating, color label, copy, permanent delete from trash, tag changes. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -2,12 +2,18 @@ import { useEffect, useState } from 'react'
|
||||
import { CheckCircle, XCircle, Info, AlertCircle, X } from 'lucide-react'
|
||||
import clsx from 'clsx'
|
||||
|
||||
export interface ToastAction {
|
||||
label: string
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
export interface Toast {
|
||||
id: string
|
||||
type: 'success' | 'error' | 'info' | 'warning'
|
||||
title: string
|
||||
message?: string
|
||||
duration?: number
|
||||
action?: ToastAction
|
||||
}
|
||||
|
||||
// Global toast state (in production, use Zustand or Context)
|
||||
@@ -15,22 +21,34 @@ let toastListeners: ((toasts: Toast[]) => void)[] = []
|
||||
let toastList: Toast[] = []
|
||||
|
||||
export const toast = {
|
||||
success: (title: string, message?: string) => addToast('success', title, message),
|
||||
error: (title: string, message?: string) => addToast('error', title, message),
|
||||
info: (title: string, message?: string) => addToast('info', title, message),
|
||||
warning: (title: string, message?: string) => addToast('warning', title, message),
|
||||
success: (title: string, message?: string, action?: ToastAction) =>
|
||||
addToast('success', title, message, 5000, action),
|
||||
error: (title: string, message?: string, action?: ToastAction) =>
|
||||
addToast('error', title, message, 5000, action),
|
||||
info: (title: string, message?: string, action?: ToastAction) =>
|
||||
addToast('info', title, message, 5000, action),
|
||||
warning: (title: string, message?: string, action?: ToastAction) =>
|
||||
addToast('warning', title, message, 5000, action),
|
||||
}
|
||||
|
||||
function addToast(type: Toast['type'], title: string, message?: string, duration = 5000) {
|
||||
const id = Date.now().toString()
|
||||
const newToast: Toast = { id, type, title, message, duration }
|
||||
function addToast(
|
||||
type: Toast['type'],
|
||||
title: string,
|
||||
message?: string,
|
||||
duration = 5000,
|
||||
action?: ToastAction
|
||||
) {
|
||||
const id = Date.now().toString() + Math.random().toString(36).slice(2, 6)
|
||||
const newToast: Toast = { id, type, title, message, duration, action }
|
||||
toastList = [...toastList, newToast]
|
||||
toastListeners.forEach(listener => listener(toastList))
|
||||
|
||||
// Auto-remove after duration
|
||||
|
||||
// Auto-remove after duration. Toasts with an action get a longer window
|
||||
// so the user has time to actually click Undo.
|
||||
const removeAfter = action ? Math.max(duration, 8000) : duration
|
||||
setTimeout(() => {
|
||||
removeToast(id)
|
||||
}, duration)
|
||||
}, removeAfter)
|
||||
}
|
||||
|
||||
function removeToast(id: string) {
|
||||
@@ -82,6 +100,17 @@ export function ToastContainer() {
|
||||
<div className="mt-0.5 text-sm text-text-muted">{toast.message}</div>
|
||||
)}
|
||||
</div>
|
||||
{toast.action && (
|
||||
<button
|
||||
onClick={() => {
|
||||
toast.action!.onClick()
|
||||
removeToast(toast.id)
|
||||
}}
|
||||
className="pointer-events-auto self-center rounded border border-border bg-surface px-2 py-1 text-xs font-medium text-text hover:bg-surface-2"
|
||||
>
|
||||
{toast.action.label}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => removeToast(toast.id)}
|
||||
className="pointer-events-auto rounded p-0.5 text-text-muted hover:bg-surface-offset hover:text-text"
|
||||
|
||||
@@ -4,9 +4,10 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { usePhotoStore } from '../../store/photoStore'
|
||||
import { useFilterStore } from '../../store/filterStore'
|
||||
import { usePhotosQuery } from '../../hooks/usePhotosQuery'
|
||||
import { discard as discardApi } from '../../services/api'
|
||||
import { discard as discardApi, photos as photosApi } from '../../services/api'
|
||||
import { toast } from '../ToastContainer'
|
||||
import { ConfirmDialog } from '../dialogs/ConfirmDialog'
|
||||
import { registerUndoable } from '../../store/undoStore'
|
||||
|
||||
/**
|
||||
* Top-of-timeline bar visible only when the discarded filter is active.
|
||||
@@ -26,7 +27,13 @@ export function DiscardActionBar() {
|
||||
const restoreMutation = useMutation({
|
||||
mutationFn: (ids: string[]) => discardApi.restore(ids),
|
||||
onSuccess: (_, ids) => {
|
||||
toast.success('Restored', `${ids.length} photo${ids.length > 1 ? 's' : ''} restored`)
|
||||
registerUndoable(
|
||||
`Restored ${ids.length} photo${ids.length === 1 ? '' : 's'}`,
|
||||
async () => {
|
||||
await photosApi.bulkDiscard(ids)
|
||||
queryClient.invalidateQueries({ queryKey: ['photos'] })
|
||||
}
|
||||
)
|
||||
clearSelection()
|
||||
queryClient.invalidateQueries({ queryKey: ['photos'] })
|
||||
},
|
||||
|
||||
@@ -21,6 +21,8 @@ import { HeapsPanel } from '../heaps/HeapsPanel'
|
||||
import { PHOTO_DRAG_MIME } from '../timeline/PhotoThumbnail'
|
||||
import { useFolderTreeQuery } from '../../hooks/useFolderTreeQuery'
|
||||
import { useTagsQuery } from '../../hooks/useTagsQuery'
|
||||
import { registerUndoable } from '../../store/undoStore'
|
||||
import type { Photo } from '../../types/photo'
|
||||
|
||||
interface TreeItem {
|
||||
id: string
|
||||
@@ -49,9 +51,12 @@ export function LeftSidebar() {
|
||||
const discardDropMutation = useMutation({
|
||||
mutationFn: (photoIds: string[]) => photosApi.bulkDiscard(photoIds),
|
||||
onSuccess: (_data, photoIds) => {
|
||||
toast.success(
|
||||
'Discarded',
|
||||
`${photoIds.length} photo${photoIds.length > 1 ? 's' : ''}`
|
||||
registerUndoable(
|
||||
`Discarded ${photoIds.length} photo${photoIds.length === 1 ? '' : 's'}`,
|
||||
async () => {
|
||||
await photosApi.bulkRestore(photoIds)
|
||||
queryClient.invalidateQueries({ queryKey: ['photos'] })
|
||||
}
|
||||
)
|
||||
queryClient.invalidateQueries({ queryKey: ['photos'] })
|
||||
},
|
||||
@@ -59,20 +64,71 @@ export function LeftSidebar() {
|
||||
toast.error('Discard failed', e?.message || 'Unknown error'),
|
||||
})
|
||||
|
||||
// Bulk move mutation for the drag-onto-folder interaction.
|
||||
// Bulk move mutation for the drag-onto-folder interaction. The mutation
|
||||
// captures each photo's source folder before issuing the move so the
|
||||
// undo path can put them back exactly where they came from (different
|
||||
// sources end up in different undo subgroups).
|
||||
const moveDropMutation = useMutation({
|
||||
mutationFn: ({ targetId, photoIds }: { targetId: string; photoIds: string[] }) =>
|
||||
photosApi.move(photoIds, targetId),
|
||||
onSuccess: (data) => {
|
||||
const moved = data?.moved ?? 0
|
||||
const errCount = (data?.errors?.length ?? 0)
|
||||
mutationFn: async ({
|
||||
targetId,
|
||||
photoIds,
|
||||
}: {
|
||||
targetId: string
|
||||
photoIds: string[]
|
||||
}) => {
|
||||
// Snapshot per-photo source folder ids from the photos cache. We
|
||||
// walk every cached ['photos', ...] entry because the user could
|
||||
// be in any section / filter combination, and we don't know the
|
||||
// exact key offhand.
|
||||
const sourceMap = new Map<string, string>()
|
||||
const photoCaches = queryClient.getQueriesData<Photo[]>({ queryKey: ['photos'] })
|
||||
for (const [, list] of photoCaches) {
|
||||
if (!list) continue
|
||||
for (const p of list) {
|
||||
if (photoIds.includes(p.id) && p.folder_id && !sourceMap.has(p.id)) {
|
||||
sourceMap.set(p.id, p.folder_id)
|
||||
}
|
||||
}
|
||||
}
|
||||
const result = await photosApi.move(photoIds, targetId)
|
||||
return { result, sourceMap }
|
||||
},
|
||||
onSuccess: ({ result, sourceMap }) => {
|
||||
const moved = result?.moved ?? 0
|
||||
const errCount = result?.errors?.length ?? 0
|
||||
if (moved > 0) {
|
||||
toast.success(
|
||||
'Moved',
|
||||
`${moved} photo${moved > 1 ? 's' : ''}${errCount ? ` (${errCount} skipped)` : ''}`
|
||||
)
|
||||
// Group photos by their source folder so we can issue one move
|
||||
// call per group when undoing. Photos whose source folder we
|
||||
// couldn't recover get dropped from the undo (they'll just stay
|
||||
// where the move put them).
|
||||
const groups = new Map<string, string[]>()
|
||||
for (const [photoId, src] of sourceMap.entries()) {
|
||||
const arr = groups.get(src) ?? []
|
||||
arr.push(photoId)
|
||||
groups.set(src, arr)
|
||||
}
|
||||
if (groups.size > 0) {
|
||||
registerUndoable(
|
||||
`Moved ${moved} photo${moved === 1 ? '' : 's'}`,
|
||||
async () => {
|
||||
for (const [src, ids] of groups.entries()) {
|
||||
await photosApi.move(ids, src)
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['photos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
}
|
||||
)
|
||||
} else {
|
||||
toast.success(
|
||||
'Moved',
|
||||
`${moved} photo${moved > 1 ? 's' : ''}${errCount ? ` (${errCount} skipped)` : ''}`
|
||||
)
|
||||
}
|
||||
} else if (errCount > 0) {
|
||||
toast.error('Move failed', `${errCount} file${errCount > 1 ? 's' : ''} could not be moved`)
|
||||
toast.error(
|
||||
'Move failed',
|
||||
`${errCount} file${errCount > 1 ? 's' : ''} could not be moved`
|
||||
)
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['photos'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['folders'] })
|
||||
|
||||
@@ -4,6 +4,7 @@ import { usePhotoStore } from '../store/photoStore'
|
||||
import { photos as photosApi, heaps as heapsApi, type Heap } from '../services/api'
|
||||
import { HEAPS_QUERY_KEY } from './useHeapsQuery'
|
||||
import { toast } from '../components/ToastContainer'
|
||||
import { registerUndoable, useUndoStore } from '../store/undoStore'
|
||||
|
||||
interface KeyboardShortcutsProps {
|
||||
onToggleLeftSidebar: () => void
|
||||
@@ -106,7 +107,29 @@ export function useKeyboardShortcuts(props: KeyboardShortcutsProps) {
|
||||
if (ids.length === 0) return
|
||||
|
||||
if (ids.length === 1) {
|
||||
updateMutation.mutate({ id: ids[0], data })
|
||||
const id = ids[0]
|
||||
updateMutation.mutate(
|
||||
{ id, data },
|
||||
{
|
||||
onSuccess: () => {
|
||||
// Only the discard/restore subset of single-photo updates is
|
||||
// undoable today — rating and color round-trip cleanly enough
|
||||
// that the manual fix is faster than maintaining per-photo
|
||||
// previous-value snapshots.
|
||||
if (data.is_discarded === true) {
|
||||
registerUndoable('Discarded 1 photo', async () => {
|
||||
await photosApi.bulkRestore([id])
|
||||
invalidatePhotoQueries()
|
||||
})
|
||||
} else if (data.is_discarded === false) {
|
||||
registerUndoable('Restored 1 photo', async () => {
|
||||
await photosApi.bulkDiscard([id])
|
||||
invalidatePhotoQueries()
|
||||
})
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -118,9 +141,29 @@ export function useKeyboardShortcuts(props: KeyboardShortcutsProps) {
|
||||
bulkColorMutation.mutate({ ids, color: data.color_label })
|
||||
}
|
||||
if (data.is_discarded === true) {
|
||||
bulkDiscardMutation.mutate(ids)
|
||||
bulkDiscardMutation.mutate(ids, {
|
||||
onSuccess: () => {
|
||||
registerUndoable(
|
||||
`Discarded ${ids.length} photo${ids.length === 1 ? '' : 's'}`,
|
||||
async () => {
|
||||
await photosApi.bulkRestore(ids)
|
||||
invalidatePhotoQueries()
|
||||
}
|
||||
)
|
||||
},
|
||||
})
|
||||
} else if (data.is_discarded === false) {
|
||||
bulkRestoreMutation.mutate(ids)
|
||||
bulkRestoreMutation.mutate(ids, {
|
||||
onSuccess: () => {
|
||||
registerUndoable(
|
||||
`Restored ${ids.length} photo${ids.length === 1 ? '' : 's'}`,
|
||||
async () => {
|
||||
await photosApi.bulkDiscard(ids)
|
||||
invalidatePhotoQueries()
|
||||
}
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,6 +266,26 @@ export function useKeyboardShortcuts(props: KeyboardShortcutsProps) {
|
||||
useHotkeys('tab', onToggleLeftSidebar, HK_OPTS)
|
||||
useHotkeys('i', onToggleRightSidebar, { ...HK_OPTS, enabled: !isPreview })
|
||||
|
||||
// Cmd/Ctrl+Z → pop the most recent undoable action and reverse it.
|
||||
// Bound at the global level so it works in both grid and preview modes.
|
||||
useHotkeys(
|
||||
'mod+z',
|
||||
async () => {
|
||||
const entry = useUndoStore.getState().pop()
|
||||
if (!entry) {
|
||||
toast.info('Nothing to undo')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await entry.undo()
|
||||
} catch (e: any) {
|
||||
useUndoStore.getState().push({ label: entry.label, undo: entry.undo })
|
||||
toast.error('Undo failed', e?.message || 'Unknown error')
|
||||
}
|
||||
},
|
||||
HK_OPTS
|
||||
)
|
||||
|
||||
// Search focus (/ or Cmd/Ctrl+F).
|
||||
const focusSearch = () => {
|
||||
const el = document.getElementById('topbar-search') as HTMLInputElement | null
|
||||
|
||||
71
frontend/src/store/undoStore.ts
Normal file
71
frontend/src/store/undoStore.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { create } from 'zustand'
|
||||
import { toast } from '../components/ToastContainer'
|
||||
|
||||
const MAX_STACK = 20
|
||||
|
||||
export interface UndoEntry {
|
||||
id: string
|
||||
/** Short description of what happened, e.g. "Discarded 12 photos". */
|
||||
label: string
|
||||
/** Function that reverses the action. May be async; errors should be
|
||||
* surfaced via toast.error from inside the function. */
|
||||
undo: () => void | Promise<void>
|
||||
}
|
||||
|
||||
interface UndoStore {
|
||||
stack: UndoEntry[]
|
||||
/** Push a new entry. Caps the stack at MAX_STACK by dropping the oldest. */
|
||||
push: (entry: Omit<UndoEntry, 'id'>) => void
|
||||
/** Pop the most recent entry. Returns null when the stack is empty. */
|
||||
pop: () => UndoEntry | null
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
export const useUndoStore = create<UndoStore>((set, get) => ({
|
||||
stack: [],
|
||||
|
||||
push: (entry) => {
|
||||
const id = Date.now().toString() + Math.random().toString(36).slice(2, 6)
|
||||
set((s) => {
|
||||
const next = [...s.stack, { ...entry, id }]
|
||||
if (next.length > MAX_STACK) next.shift()
|
||||
return { stack: next }
|
||||
})
|
||||
},
|
||||
|
||||
pop: () => {
|
||||
const stack = get().stack
|
||||
if (stack.length === 0) return null
|
||||
const last = stack[stack.length - 1]
|
||||
set({ stack: stack.slice(0, -1) })
|
||||
return last
|
||||
},
|
||||
|
||||
clear: () => set({ stack: [] }),
|
||||
}))
|
||||
|
||||
/**
|
||||
* Convenience: register an undoable action AND show the user a success
|
||||
* toast with an inline Undo button. The toast and Cmd+Z hotkey both pop
|
||||
* from the same stack so either path works.
|
||||
*/
|
||||
export function registerUndoable(label: string, undo: () => void | Promise<void>) {
|
||||
useUndoStore.getState().push({ label, undo })
|
||||
toast.success(label, 'Press ⌘Z to undo', {
|
||||
label: 'Undo',
|
||||
onClick: async () => {
|
||||
// Pop the entry we just pushed (or whatever is now on top, if the
|
||||
// user fired multiple actions in quick succession — Undo always
|
||||
// reverses the most recent thing).
|
||||
const entry = useUndoStore.getState().pop()
|
||||
if (!entry) return
|
||||
try {
|
||||
await entry.undo()
|
||||
} catch (e) {
|
||||
// Re-push so the user can try again, and surface the failure.
|
||||
useUndoStore.getState().push({ label: entry.label, undo: entry.undo })
|
||||
toast.error('Undo failed', e instanceof Error ? e.message : String(e))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -16,6 +16,7 @@ export interface Photo {
|
||||
is_discarded: boolean
|
||||
is_duplicate: boolean
|
||||
file_hash: string
|
||||
folder_id?: string | null
|
||||
thumb_small?: string
|
||||
thumb_medium?: string
|
||||
thumb_large?: string
|
||||
|
||||
Reference in New Issue
Block a user