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:
2026-04-08 14:08:58 +02:00
parent b870084be0
commit 07b9660e92
6 changed files with 256 additions and 29 deletions

View File

@@ -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"

View File

@@ -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'] })
},

View File

@@ -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'] })