5 Commits

Author SHA1 Message Date
2679214cb9 refactor: rename loupe to preview, bind to E and Space, fix empty viewer
The loupe view is now called "preview" everywhere — file paths, type
names, store actions, and the contextual hint pill. There's a single
preview action bound to E and Space (Enter is gone); double-click on a
thumbnail still works. Both shortcuts toggle: open from grid, close
from preview.

This commit also folds in the fix for the "preview shows nothing" bug
the user just hit:

- Extract usePhotosQuery into frontend/src/hooks/usePhotosQuery.ts so
  Timeline, PreviewView, and App.tsx all share one query — and one
  cache entry. Previously PreviewView and App.tsx looked the cache up
  by ['photos'], but the Timeline query key gained the filter params
  (['photos', filterParams]) when the filter bar shipped, so the
  lookup returned undefined and the preview rendered "No photo to
  display". App.tsx's getFirstPhotoId callback had the same bug.

- Harden PreviewImage: render the <img> immediately and overlay the
  spinner with absolute positioning, instead of toggling opacity-0 →
  opacity-100 on load. The previous opacity-toggle could leave the
  image stuck invisible if the load event raced with a key change.

- Add { preventDefault: true } to every useHotkeys call so single
  letter shortcuts (1-5, P, X, U) no longer leak into Firefox quick-
  find, and Cmd/Ctrl+F no longer triggers the browser find toolbar.

Files renamed:
  components/loupe/LoupeView.tsx       -> components/preview/PreviewView.tsx
  components/loupe/LoupeImage.tsx      -> components/preview/PreviewImage.tsx
  components/loupe/LoupeFilmstrip.tsx  -> components/preview/PreviewFilmstrip.tsx
  components/loupe/loupeSrc.ts         -> components/preview/previewSrc.ts

Symbol renames: openLoupe→openPreview, closeLoupe→closePreview, the
viewMode 'loupe' tag → 'preview', and all the LoupeXxx component and
helper exports.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 22:47:52 +02:00
ce2cda0565 refactor: merge reject into trash as a single soft-trash concept
The Photo model previously had two near-identical "negative culling"
states: is_rejected (a flag) and is_trashed (a flag plus a file move).
Lightroom users typically use one or the other, never both, and the
file-move semantics of the old trash made it harder to undo. Merging
into a single soft is_trashed flag — file stays on disk, restore is a
flag flip, permanent deletion still happens via DELETE /trash/empty.

Backend
- Drop is_rejected from PhotoBase, PhotoResponse, PhotoUpdate, the
  list endpoint filter, and the bulk-action 'reject' branch.
- Add is_trashed to PhotoUpdate so the PATCH path can set it.
- Drop is_rejected Column declaration from the SQLAlchemy model. The
  legacy DB column may persist on existing installs but is no longer
  read or written; SQLAlchemy ignores extra columns.
- Rewrite DELETE /photos/{id} as a soft trash: just sets is_trashed=
  true and trashed_at=now, no shutil.move. Permanent deletion still
  goes through the trash router.

Frontend
- Photo TS type drops is_rejected, gains is_trashed.
- X keyboard shortcut now sets is_trashed=true (was is_rejected); U
  clears both is_picked and is_trashed.
- RightSidebar Reject button → Trash button (Trash2 icon).
- PhotoThumbnail flag overlay shows Trash2 icon for trashed photos
  instead of an X for rejected.
- KeyboardHints relabels X from "Reject" to "Trash".
- filterStore FlagFilter renames 'rejected' → 'trashed'; the params
  builder now sends is_trashed=true for the trashed filter (the list
  endpoint defaults to hiding trashed photos otherwise).
- FilterBar dropdown / URL sync allow-list updated accordingly.

No data migration: existing rejected photos remain as-is (flag stale)
and effectively become unflagged in the new model. Re-trash from the
UI to bring them into the new state.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 22:16:10 +02:00
f7bf22db29 chore(docker): add proxies_data volume for /proxy endpoint cache
The /photos/{id}/proxy endpoint (added in 1096854) caches transcoded
RAW/HEIC WebPs at /data/proxies/{id}.webp, but the compose file had no
volume mount for that path — files would be lost on every container
restart, forcing repeated full-resolution decodes. Adding a named
volume to both backend and worker so the cache survives restarts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 22:15:43 +02:00
3e322576f2 chore: drop static shortcut drawer; inline contextual hints
The bottom-left KeyboardShortcuts drawer duplicated information that
the contextual KeyboardHints pill already shows for the current
selection state. Removing it in favor of the contextual hints alone.

KeyboardHints was previously a fixed top-14 overlay, which collided
with the FilterBar when it was opened — the hints panel covered the
filter controls. Refactored it to render inline in the App header
stack (TopBar / FilterBar / ActiveFilterChips / KeyboardHints /
Timeline) so it flows naturally and never overlaps.

Also:
- Hide hints in loupe mode (the loupe has its own context)
- Replace the deleted shortcuts (Ctrl+A, Trash) with the newly wired
  ones (\\ Filters, / Search, E Loupe) so the hints surface them

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 22:15:31 +02:00
6e6672f225 fix: use square cells in timeline grid
PhotoThumbnail computed cell height as size * min(aspectRatio, 1.5),
so portrait photos overflowed their row. The TanStack Virtual row
estimate is a single fixed value (thumbnailSize + gap), so any cell
taller than that pushed into the row below — visible as overlapping
thumbnails whenever a portrait shared a row with landscapes.

Switching to square cells (Lightroom Library default) means every row
is exactly the estimated height. The image still fills via object-cover,
just cropped on the long axis.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 22:15:19 +02:00
21 changed files with 262 additions and 432 deletions

View File

@@ -55,7 +55,9 @@ class Photo(Base):
rating = Column(Integer, default=0) # 0-5 stars
color_label = Column(String) # 'red'|'orange'|'yellow'|'green'|'blue'|'purple'|NULL
is_picked = Column(Boolean, default=False)
is_rejected = Column(Boolean, default=False)
# Note: is_rejected was merged into is_trashed (a single soft "trashed"
# concept). The DB column may still exist on legacy installs but is no
# longer read or written.
# Duplicate detection
is_duplicate = Column(Boolean, default=False)

View File

@@ -33,7 +33,6 @@ async def list_photos(
rating_max: Optional[int] = Query(None, ge=0, le=5),
color_label: Optional[str] = None,
is_picked: Optional[bool] = None,
is_rejected: Optional[bool] = None,
is_trashed: Optional[bool] = False,
heap_id: Optional[str] = None,
sort: str = "taken_at",
@@ -93,10 +92,8 @@ async def list_photos(
# Flag filters
if is_picked is not None:
filters.append(Photo.is_picked == is_picked)
if is_rejected is not None:
filters.append(Photo.is_rejected == is_rejected)
# Trash filter
# Trash filter — defaults to hiding trashed photos
filters.append(Photo.is_trashed == is_trashed)
# Apply all filters
@@ -414,33 +411,22 @@ async def trash_photo(
photo_id: str,
db: AsyncSession = Depends(get_db)
):
"""Move photo to trash"""
"""Soft-trash a photo: sets is_trashed=true. The file stays on disk so
restore is just a flag flip. Permanent deletion happens via DELETE
/trash/{id} or DELETE /trash/empty.
"""
result = await db.execute(
select(Photo).where(Photo.id == photo_id)
)
photo = result.scalar_one_or_none()
if not photo:
raise HTTPException(status_code=404, detail="Photo not found")
# Move file to trash directory
import shutil
trash_dir = f"{settings.trash.path}/{photo_id}"
os.makedirs(trash_dir, exist_ok=True)
trash_path = f"{trash_dir}/original{Path(photo.filepath).suffix}"
try:
shutil.move(photo.filepath, trash_path)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to move file: {e}")
# Update database
photo.is_trashed = True
photo.trashed_at = datetime.utcnow()
await db.commit()
return {"status": "success", "message": "Photo moved to trash"}
@router.post("/bulk")
@@ -476,11 +462,7 @@ async def bulk_action(
elif action.action == 'pick':
for photo in photos:
photo.is_picked = True
photo.is_rejected = False
elif action.action == 'reject':
for photo in photos:
photo.is_rejected = True
photo.is_picked = False
photo.is_trashed = False
else:
raise HTTPException(status_code=400, detail="Invalid action")

View File

@@ -20,7 +20,6 @@ class PhotoBase(BaseModel):
rating: int = 0
color_label: Optional[str] = None
is_picked: bool = False
is_rejected: bool = False
class PhotoResponse(PhotoBase):
"""Photo response schema"""
@@ -53,7 +52,7 @@ class PhotoUpdate(BaseModel):
rating: Optional[int] = Field(None, ge=0, le=5)
color_label: Optional[str] = None
is_picked: Optional[bool] = None
is_rejected: Optional[bool] = None
is_trashed: Optional[bool] = None
taken_at: Optional[datetime] = None
class PhotoListResponse(BaseModel):

View File

@@ -26,6 +26,7 @@ services:
- ${PHOTO_DIRS:-./photos}:/photos:rw
- ~/Pictures:/host/Pictures:ro
- thumbs_data:/data/thumbs
- proxies_data:/data/proxies
- db_data:/data/db
- trash_data:/data/trash
environment:
@@ -51,6 +52,7 @@ services:
- ${PHOTO_DIRS:-./photos}:/photos:rw
- ~/Pictures:/host/Pictures:ro
- thumbs_data:/data/thumbs
- proxies_data:/data/proxies
- db_data:/data/db
- trash_data:/data/trash
environment:
@@ -85,6 +87,7 @@ networks:
volumes:
thumbs_data:
proxies_data:
db_data:
trash_data:
redis_data:

View File

@@ -1,43 +1,42 @@
import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { Timeline } from './components/timeline/Timeline'
import { LeftSidebar } from './components/layout/LeftSidebar'
import { RightSidebar } from './components/layout/RightSidebar'
import { TopBar } from './components/layout/TopBar'
import { ScanProgress } from './components/ScanProgress'
import { ToastContainer } from './components/ToastContainer'
import { KeyboardShortcuts } from './components/KeyboardShortcuts'
import { KeyboardHints } from './components/KeyboardHints'
import { LoupeView } from './components/loupe/LoupeView'
import { PreviewView } from './components/preview/PreviewView'
import { FilterBar } from './components/filter/FilterBar'
import { ActiveFilterChips } from './components/filter/ActiveFilterChips'
import { usePhotoStore } from './store/photoStore'
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts'
import { useFilterUrlSync } from './hooks/useFilterUrlSync'
import type { Photo } from './types/photo'
import { usePhotosQuery } from './hooks/usePhotosQuery'
function App() {
const [leftSidebarOpen, setLeftSidebarOpen] = useState(true)
const [rightSidebarOpen, setRightSidebarOpen] = useState(false)
const selectedPhotos = usePhotoStore((state) => state.selectedPhotos)
const viewMode = usePhotoStore((state) => state.viewMode)
const queryClient = useQueryClient()
// Bidirectional sync of filter store with URL query params.
useFilterUrlSync()
// Subscribe to the same photos query the Timeline uses, so the keyboard
// "open preview on first photo" path can read from the live cache regardless
// of what filter key it's stored under.
const { data: allPhotos } = usePhotosQuery()
// Set up global keyboard shortcuts
useKeyboardShortcuts({
onToggleLeftSidebar: () => setLeftSidebarOpen(!leftSidebarOpen),
onToggleRightSidebar: () => setRightSidebarOpen(!rightSidebarOpen),
getFirstPhotoId: () => {
const photos = queryClient.getQueryData<Photo[]>(['photos'])
return photos && photos.length > 0 ? photos[0].id : null
},
getFirstPhotoId: () => allPhotos?.[0]?.id ?? null,
})
// Auto-show right sidebar when photos are selected — but only in grid mode,
// so leaving loupe doesn't fight the user's prior sidebar state.
// so leaving the preview doesn't fight the user's prior sidebar state.
if (viewMode === 'grid') {
if (selectedPhotos.length > 0 && !rightSidebarOpen) {
setRightSidebarOpen(true)
@@ -53,6 +52,7 @@ function App() {
<TopBar />
<FilterBar />
<ActiveFilterChips />
<KeyboardHints />
<div className="flex flex-1 overflow-hidden">
{/* Left Sidebar */}
@@ -79,20 +79,14 @@ function App() {
</div>
</div>
{/* Contextual Keyboard Hints */}
<KeyboardHints />
{/* Keyboard Shortcuts Legend */}
<KeyboardShortcuts />
{/* Scan Progress Indicator */}
<ScanProgress />
{/* Toast Notifications */}
<ToastContainer />
{/* Loupe overlay — covers TopBar when active */}
{viewMode === 'loupe' && <LoupeView />}
{/* Preview overlay — covers TopBar when active */}
{viewMode === 'preview' && <PreviewView />}
</div>
)
}

View File

@@ -2,27 +2,35 @@ import { usePhotoStore } from '../store/photoStore'
export function KeyboardHints() {
const selectedCount = usePhotoStore((state) => state.selectedPhotos.length)
const viewMode = usePhotoStore((state) => state.viewMode)
const hints = selectedCount > 0 ? [
{ key: '1-5', action: 'Rate' },
{ key: 'P', action: 'Pick' },
{ key: 'X', action: 'Reject' },
{ key: 'Delete', action: 'Trash' },
{ key: 'Esc', action: 'Deselect' },
] : [
{ key: '↑↓←→', action: 'Navigate' },
{ key: 'Click', action: 'Select' },
{ key: 'Shift+Click', action: 'Range' },
{ key: 'Ctrl+A', action: 'Select All' },
{ key: 'Space', action: 'Preview' },
]
// In preview mode the viewer has its own context, so the grid hints
// would just be confusing. Hide them.
if (viewMode === 'preview') return null
const hints = selectedCount > 0
? [
{ key: '1-5', action: 'Rate' },
{ key: 'P', action: 'Pick' },
{ key: 'X', action: 'Trash' },
{ key: 'E / Space', action: 'Preview' },
{ key: 'Esc', action: 'Deselect' },
]
: [
{ key: '↑↓←→', action: 'Navigate' },
{ key: 'Click', action: 'Select' },
{ key: 'Shift+Click', action: 'Range' },
{ key: 'E / Space', action: 'Preview' },
{ key: '\\', action: 'Filters' },
{ key: '/', action: 'Search' },
]
return (
<div className="fixed top-14 left-1/2 z-20 -translate-x-1/2">
<div className="flex items-center gap-3 rounded-full border border-border bg-surface/90 px-4 py-2 shadow-lg backdrop-blur-sm">
<div className="flex justify-center border-b border-border bg-surface/60 px-4 py-1.5">
<div className="flex items-center gap-3">
{hints.map((hint, i) => (
<div key={i} className="flex items-center gap-1.5">
<kbd className="rounded bg-surface-offset px-2 py-0.5 text-xs font-medium text-text">
<kbd className="rounded bg-surface-offset px-2 py-0.5 text-[11px] font-medium text-text">
{hint.key}
</kbd>
<span className="text-xs text-text-muted">{hint.action}</span>
@@ -42,4 +50,4 @@ export function KeyboardHints() {
</div>
</div>
)
}
}

View File

@@ -1,143 +0,0 @@
import { useState } from 'react'
import { Keyboard, ChevronRight, ChevronDown, X } from 'lucide-react'
import clsx from 'clsx'
interface Shortcut {
keys: string[]
description: string
category: 'navigation' | 'selection' | 'actions' | 'view'
}
const shortcuts: Shortcut[] = [
// Navigation
{ keys: ['↑', '↓', '←', '→'], description: 'Navigate photos', category: 'navigation' },
{ keys: ['Space'], description: 'Quick preview', category: 'navigation' },
{ keys: ['Enter'], description: 'Open in loupe view', category: 'navigation' },
// Selection
{ keys: ['Click'], description: 'Select photo', category: 'selection' },
{ keys: ['Shift', 'Click'], description: 'Select range', category: 'selection' },
{ keys: ['Ctrl/Cmd', 'Click'], description: 'Add to selection', category: 'selection' },
{ keys: ['Ctrl/Cmd', 'A'], description: 'Select all', category: 'selection' },
{ keys: ['Escape'], description: 'Clear selection', category: 'selection' },
// Actions
{ keys: ['1-5'], description: 'Set rating', category: 'actions' },
{ keys: ['0'], description: 'Remove rating', category: 'actions' },
{ keys: ['P'], description: 'Pick photo', category: 'actions' },
{ keys: ['X'], description: 'Reject photo', category: 'actions' },
{ keys: ['U'], description: 'Unflag photo', category: 'actions' },
{ keys: ['Delete'], description: 'Move to trash', category: 'actions' },
// View
{ keys: ['Tab'], description: 'Toggle left sidebar', category: 'view' },
{ keys: ['I'], description: 'Toggle info panel', category: 'view' },
{ keys: ['G'], description: 'Grid view', category: 'view' },
{ keys: ['E'], description: 'Loupe view', category: 'view' },
{ keys: ['F'], description: 'Fullscreen', category: 'view' },
]
export function KeyboardShortcuts() {
const [isExpanded, setIsExpanded] = useState(true)
const [isMinimized, setIsMinimized] = useState(false)
const categories = {
navigation: { label: 'Navigation', color: 'text-primary' },
selection: { label: 'Selection', color: 'text-pick' },
actions: { label: 'Actions', color: 'text-star' },
view: { label: 'View', color: 'text-text' },
}
if (isMinimized) {
return (
<div className="fixed bottom-4 left-4 z-30">
<button
onClick={() => setIsMinimized(false)}
className="flex items-center gap-2 rounded-lg border border-border bg-surface/90 px-3 py-2 text-sm backdrop-blur-sm hover:bg-surface"
title="Show keyboard shortcuts"
>
<Keyboard className="h-4 w-4 text-primary" />
<span className="text-text-muted">Shortcuts</span>
</button>
</div>
)
}
return (
<div className="fixed bottom-4 left-4 z-30 w-80 overflow-hidden rounded-lg border border-border bg-surface/95 shadow-xl backdrop-blur-sm">
{/* Header */}
<div className="flex items-center justify-between bg-surface-2 px-3 py-2">
<div className="flex items-center gap-2">
<Keyboard className="h-4 w-4 text-primary" />
<span className="text-sm font-medium text-text">Keyboard Shortcuts</span>
</div>
<div className="flex items-center gap-1">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="rounded p-1 text-text-muted hover:bg-surface-offset hover:text-text"
title={isExpanded ? 'Collapse' : 'Expand'}
>
{isExpanded ? (
<ChevronDown className="h-3 w-3" />
) : (
<ChevronRight className="h-3 w-3" />
)}
</button>
<button
onClick={() => setIsMinimized(true)}
className="rounded p-1 text-text-muted hover:bg-surface-offset hover:text-text"
title="Minimize"
>
<X className="h-3 w-3" />
</button>
</div>
</div>
{/* Content */}
{isExpanded && (
<div className="max-h-96 overflow-y-auto p-2">
{Object.entries(categories).map(([category, { label, color }]) => (
<div key={category} className="mb-3">
<h3 className={clsx('mb-1.5 text-xs font-semibold uppercase', color)}>
{label}
</h3>
<div className="space-y-1">
{shortcuts
.filter(s => s.category === category)
.map((shortcut, i) => (
<div
key={i}
className="flex items-center justify-between rounded px-2 py-1 hover:bg-surface-2"
>
<span className="text-xs text-text-muted">
{shortcut.description}
</span>
<div className="flex items-center gap-1">
{shortcut.keys.map((key, j) => (
<span key={j} className="flex items-center">
<kbd className="rounded bg-surface-offset px-1.5 py-0.5 text-[10px] font-medium text-text">
{key}
</kbd>
{j < shortcut.keys.length - 1 && (
<span className="mx-0.5 text-[10px] text-text-muted">+</span>
)}
</span>
))}
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
{/* Footer Hint */}
{!isExpanded && (
<div className="px-3 pb-2 pt-1">
<p className="text-xs text-text-muted">Click to expand shortcuts list</p>
</div>
)}
</div>
)
}

View File

@@ -26,7 +26,7 @@ const COLOR_LABELS: { value: ColorLabel; className: string }[] = [
const FLAG_OPTIONS: { value: FlagFilter; label: string }[] = [
{ value: 'any', label: 'Any' },
{ value: 'picked', label: 'Picked' },
{ value: 'rejected', label: 'Rejected' },
{ value: 'trashed', label: 'Trashed' },
{ value: 'unflagged', label: 'Unflagged' },
]

View File

@@ -9,6 +9,7 @@ import {
ChevronDown,
ChevronRight,
Check,
Trash2,
} from 'lucide-react'
import clsx from 'clsx'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
@@ -26,7 +27,7 @@ interface PhotoDetails {
taken_at: string | null
rating: number
is_picked: boolean
is_rejected: boolean
is_trashed: boolean
exif_json: string | null
}
@@ -107,7 +108,7 @@ export function RightSidebar() {
mutationFn: (data: {
rating?: number
is_picked?: boolean
is_rejected?: boolean
is_trashed?: boolean
}) => photosApi.update(activePhotoId!, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['photo', activePhotoId] })
@@ -131,7 +132,7 @@ export function RightSidebar() {
const multipleSelected = selectedPhotos.length > 1
const rating = photo?.rating ?? 0
const isPicked = photo?.is_picked ?? false
const isRejected = photo?.is_rejected ?? false
const isTrashed = photo?.is_trashed ?? false
return (
<div className="flex h-full flex-col bg-surface">
@@ -186,7 +187,7 @@ export function RightSidebar() {
onClick={() =>
updateMutation.mutate({
is_picked: !isPicked,
is_rejected: false,
is_trashed: false,
})
}
className={clsx(
@@ -202,19 +203,19 @@ export function RightSidebar() {
<button
onClick={() =>
updateMutation.mutate({
is_rejected: !isRejected,
is_trashed: !isTrashed,
is_picked: false,
})
}
className={clsx(
'flex items-center gap-1 rounded px-2 py-1 text-sm transition-colors',
isRejected
isTrashed
? 'bg-reject/20 text-reject'
: 'bg-surface-2 text-text-muted hover:bg-surface-offset'
)}
>
<X className="h-3 w-3" />
Reject
<Trash2 className="h-3 w-3" />
Trash
</button>
</div>
</div>

View File

@@ -3,7 +3,7 @@ import clsx from 'clsx'
import type { Photo } from '../../types/photo'
import { photos as photosApi } from '../../services/api'
interface LoupeFilmstripProps {
interface PreviewFilmstripProps {
photos: Photo[]
currentIndex: number
onSelect: (id: string) => void
@@ -11,7 +11,7 @@ interface LoupeFilmstripProps {
const CELL_SIZE = 72
export function LoupeFilmstrip({ photos, currentIndex, onSelect }: LoupeFilmstripProps) {
export function PreviewFilmstrip({ photos, currentIndex, onSelect }: PreviewFilmstripProps) {
const activeRef = useRef<HTMLButtonElement>(null)
useEffect(() => {

View File

@@ -1,15 +1,14 @@
import { useState, useEffect, useRef, useCallback } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import clsx from 'clsx'
import type { Photo } from '../../types/photo'
import {
getLoupeImageSrc,
getLoupeFallbackSrc,
getPreviewImageSrc,
getPreviewFallbackSrc,
getVideoSrc,
isVideo,
} from './loupeSrc'
} from './previewSrc'
interface LoupeImageProps {
interface PreviewImageProps {
photo: Photo
}
@@ -17,14 +16,14 @@ const MIN_SCALE = 1
const MAX_SCALE = 8
const WHEEL_STEP = 1.15
export function LoupeImage({ photo }: LoupeImageProps) {
export function PreviewImage({ photo }: PreviewImageProps) {
if (isVideo(photo)) {
return <LoupeVideo photo={photo} />
return <PreviewVideo photo={photo} />
}
return <LoupeStillImage photo={photo} />
return <PreviewStillImage photo={photo} />
}
function LoupeVideo({ photo }: { photo: Photo }) {
function PreviewVideo({ photo }: { photo: Photo }) {
return (
<div className="flex flex-1 items-center justify-center bg-black">
<video
@@ -39,7 +38,7 @@ function LoupeVideo({ photo }: { photo: Photo }) {
)
}
function LoupeStillImage({ photo }: { photo: Photo }) {
function PreviewStillImage({ photo }: { photo: Photo }) {
const [loaded, setLoaded] = useState(false)
const [usingFallback, setUsingFallback] = useState(false)
@@ -58,8 +57,8 @@ function LoupeStillImage({ photo }: { photo: Photo }) {
setOffset({ x: 0, y: 0 })
}, [photo.id])
const primarySrc = getLoupeImageSrc(photo)
const fallbackSrc = getLoupeFallbackSrc(photo)
const primarySrc = getPreviewImageSrc(photo)
const fallbackSrc = getPreviewFallbackSrc(photo)
const src = usingFallback ? fallbackSrc : primarySrc
const handleError = () => {
@@ -83,10 +82,15 @@ function LoupeStillImage({ photo }: { photo: Photo }) {
setScale(Math.min(ratio, MAX_SCALE))
}, [scale])
useHotkeys('z', (e) => {
e.preventDefault()
toggleZoom()
}, [toggleZoom])
useHotkeys(
'z',
(e) => {
e.preventDefault()
toggleZoom()
},
{ preventDefault: true },
[toggleZoom]
)
const handleWheel = (e: React.WheelEvent) => {
e.preventDefault()
@@ -140,11 +144,6 @@ function LoupeStillImage({ photo }: { photo: Photo }) {
onMouseLeave={endDrag}
style={{ cursor }}
>
{!loaded && (
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-text-muted">
<div className="h-10 w-10 animate-spin rounded-full border-2 border-primary/30 border-t-primary" />
</div>
)}
<img
ref={imgRef}
key={`${photo.id}-${usingFallback}`}
@@ -155,18 +154,18 @@ function LoupeStillImage({ photo }: { photo: Photo }) {
draggable={false}
onLoad={() => setLoaded(true)}
onError={handleError}
className={clsx(
'max-h-full max-w-full object-contain transition-opacity duration-150',
loaded ? 'opacity-100' : 'opacity-0'
)}
className="max-h-full max-w-full object-contain"
style={{
transform: `translate(${offset.x}px, ${offset.y}px) scale(${scale})`,
transformOrigin: 'center center',
// Disable transition during pan/zoom — only fade-in is animated.
transition: 'opacity 150ms',
willChange: 'transform',
}}
/>
{!loaded && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center text-text-muted">
<div className="h-10 w-10 animate-spin rounded-full border-2 border-primary/30 border-t-primary" />
</div>
)}
{/* Zoom indicator */}
{isZoomed && (

View File

@@ -1,25 +1,24 @@
import { useCallback, useEffect, useRef } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useQueryClient } from '@tanstack/react-query'
import { X } from 'lucide-react'
import { usePhotoStore } from '../../store/photoStore'
import { usePhotosQuery } from '../../hooks/usePhotosQuery'
import type { Photo } from '../../types/photo'
import { LoupeImage } from './LoupeImage'
import { LoupeFilmstrip } from './LoupeFilmstrip'
import { getLoupeImageSrc, isVideo } from './loupeSrc'
import { PreviewImage } from './PreviewImage'
import { PreviewFilmstrip } from './PreviewFilmstrip'
import { getPreviewImageSrc, isVideo } from './previewSrc'
export function LoupeView() {
export function PreviewView() {
const activePhotoId = usePhotoStore((s) => s.activePhotoId)
const setActivePhoto = usePhotoStore((s) => s.setActivePhoto)
const closeLoupe = usePhotoStore((s) => s.closeLoupe)
const closePreview = usePhotoStore((s) => s.closePreview)
const containerRef = useRef<HTMLDivElement>(null)
const previouslyFocusedRef = useRef<HTMLElement | null>(null)
// Read photos from the TanStack Query cache populated by Timeline.
// Same query key so we share the cache and never refetch.
const queryClient = useQueryClient()
const photos = queryClient.getQueryData<Photo[]>(['photos']) ?? []
// Same hook Timeline uses, so we share one cache entry rather than looking
// it up by key (which broke when the key gained the filter params).
const { data: photos = [] } = usePhotosQuery()
const currentIndex = activePhotoId
? photos.findIndex((p) => p.id === activePhotoId)
@@ -39,21 +38,10 @@ export function LoupeView() {
setActivePhoto(photos[next].id)
}, [photos, safeIndex, setActivePhoto])
// Loupe-scoped hotkeys: only mounted while LoupeView is rendered.
useHotkeys('escape', (e) => {
e.preventDefault()
closeLoupe()
})
useHotkeys('left', (e) => {
e.preventDefault()
goPrev()
}, [goPrev])
useHotkeys('right', (e) => {
e.preventDefault()
goNext()
}, [goNext])
// Preview-scoped hotkeys: only mounted while PreviewView is rendered.
useHotkeys('escape', closePreview, { preventDefault: true })
useHotkeys('left', goPrev, { preventDefault: true }, [goPrev])
useHotkeys('right', goNext, { preventDefault: true }, [goNext])
// Preload the immediate neighbors so arrow nav feels instant. Skip videos
// (browsers can't preload them via Image()) and skip when at the edges.
@@ -64,13 +52,13 @@ export function LoupeView() {
for (const p of neighbors) {
if (isVideo(p)) continue
const img = new Image()
img.src = getLoupeImageSrc(p)
img.src = getPreviewImageSrc(p)
}
}, [safeIndex, photos])
// Focus trap: focus the loupe container on mount, restore focus on unmount.
// The container is keyboard-focusable (tabIndex=-1) so screen readers and
// tab navigation stay scoped here.
// Focus trap: focus the preview container on mount, restore focus on
// unmount. The container is keyboard-focusable (tabIndex=-1) so screen
// readers and tab navigation stay scoped here.
useEffect(() => {
previouslyFocusedRef.current = document.activeElement as HTMLElement | null
containerRef.current?.focus()
@@ -111,13 +99,13 @@ export function LoupeView() {
ref={containerRef}
role="dialog"
aria-modal="true"
aria-label="Photo viewer"
aria-label="Photo preview"
tabIndex={-1}
className="fixed inset-0 z-40 flex flex-col items-center justify-center bg-black text-text-muted outline-none"
>
<div>No photo to display</div>
<button
onClick={closeLoupe}
onClick={closePreview}
className="mt-4 rounded border border-border px-3 py-1 text-sm hover:bg-surface"
>
Close
@@ -131,17 +119,17 @@ export function LoupeView() {
ref={containerRef}
role="dialog"
aria-modal="true"
aria-label={`Photo viewer: ${currentPhoto.filename}`}
aria-label={`Photo preview: ${currentPhoto.filename}`}
tabIndex={-1}
onKeyDown={handleKeyDown}
className="fixed inset-0 z-40 flex flex-col bg-black outline-none"
>
{/* Close button */}
<button
onClick={closeLoupe}
onClick={closePreview}
className="absolute right-3 top-3 z-10 flex h-9 w-9 items-center justify-center rounded-full bg-black/60 text-white transition hover:bg-black/80"
title="Close (Esc)"
aria-label="Close photo viewer"
aria-label="Close preview"
>
<X className="h-5 w-5" />
</button>
@@ -154,9 +142,9 @@ export function LoupeView() {
</div>
</div>
<LoupeImage photo={currentPhoto} />
<PreviewImage photo={currentPhoto} />
<LoupeFilmstrip
<PreviewFilmstrip
photos={photos}
currentIndex={safeIndex}
onSelect={setActivePhoto}

View File

@@ -6,11 +6,11 @@ const VIDEO_EXTENSIONS = ['.mp4', '.mov', '.webm', '.mkv', '.m4v']
export function isVideo(photo: Photo): boolean {
if (photo.media_type === 'video') return true
const lower = photo.filepath.toLowerCase()
return VIDEO_EXTENSIONS.some(ext => lower.endsWith(ext))
return VIDEO_EXTENSIONS.some((ext) => lower.endsWith(ext))
}
/**
* Pick the best display URL for a still photo in the loupe view.
* Pick the best display URL for a still photo in the preview view.
*
* Always uses the /proxy endpoint, which the backend resolves to:
* - the original file for web-safe formats (JPEG/PNG/WebP/GIF)
@@ -18,13 +18,13 @@ export function isVideo(photo: Photo): boolean {
*
* Videos go through `getVideoSrc` instead and use /original directly.
*/
export function getLoupeImageSrc(photo: Photo): string {
export function getPreviewImageSrc(photo: Photo): string {
return photosApi.getProxyUrl(photo.id)
}
/** Fallback used when the proxy endpoint fails or 404s shows the 1280px
* large thumbnail so the user still sees something. */
export function getLoupeFallbackSrc(photo: Photo): string {
export function getPreviewFallbackSrc(photo: Photo): string {
return photosApi.getThumbnailUrl(photo.id, 'large')
}

View File

@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { Star, Check, X, RefreshCw } from 'lucide-react'
import { Star, Check, Trash2, RefreshCw } from 'lucide-react'
import clsx from 'clsx'
import { photos as photosApi } from '../../services/api'
import type { Photo } from '../../types/photo'
@@ -28,9 +28,11 @@ export function PhotoThumbnail({ photo, size, isSelected, onClick, onDoubleClick
const baseUrl = photosApi.getThumbnailUrl(photo.id, 'medium')
const thumbnailUrl = retryCount > 0 ? `${baseUrl}?retry=${retryCount}` : baseUrl
// Calculate aspect ratio for proper sizing (default to 1:1 if dimensions unknown)
const aspectRatio = (photo.height && photo.width) ? photo.height / photo.width : 1
const displayHeight = size * Math.min(aspectRatio, 1.5) // Cap height at 1.5x width
// Square cells (Lightroom-style grid). Variable-aspect cells previously
// overflowed their row because TanStack Virtual estimates row height as a
// single fixed value — portraits in a landscape row would overlap the row
// below. With object-cover the image still fills the cell, just cropped.
const displayHeight = size
const clearRetryTimer = () => {
if (retryTimerRef.current !== null) {
@@ -169,8 +171,8 @@ export function PhotoThumbnail({ photo, size, isSelected, onClick, onDoubleClick
{photo.is_picked && (
<Check className="h-4 w-4 text-pick" />
)}
{photo.is_rejected && (
<X className="h-4 w-4 text-reject" />
{photo.is_trashed && (
<Trash2 className="h-4 w-4 text-reject" />
)}
</div>

View File

@@ -1,10 +1,8 @@
import { useRef, useEffect, useMemo, useState } from 'react'
import { useVirtualizer } from '@tanstack/react-virtual'
import { usePhotoStore } from '../../store/photoStore'
import { useFilterStore, filtersToParams } from '../../store/filterStore'
import { PhotoThumbnail } from './PhotoThumbnail'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { usePhotosQuery } from '../../hooks/usePhotosQuery'
import type { Photo } from '../../types/photo'
export function Timeline() {
@@ -18,7 +16,7 @@ export function Timeline() {
selectPhoto,
togglePhotoSelection,
clearSelection,
openLoupe,
openPreview,
} = usePhotoStore()
// Helper function for range selection
@@ -46,51 +44,9 @@ export function Timeline() {
return Math.floor((containerWidth - padding * 2) / (thumbnailSize + gap))
}, [containerWidth, thumbnailSize, gap, padding])
// Filter state — included in the query key so the cache invalidates when
// any filter changes. Subscribing field-by-field keeps re-renders cheap.
const q = useFilterStore((s) => s.q)
const dateFrom = useFilterStore((s) => s.dateFrom)
const dateTo = useFilterStore((s) => s.dateTo)
const mediaTypes = useFilterStore((s) => s.mediaTypes)
const ratingMin = useFilterStore((s) => s.ratingMin)
const colorLabel = useFilterStore((s) => s.colorLabel)
const flag = useFilterStore((s) => s.flag)
const filterParams = useMemo(
() =>
filtersToParams({
q,
dateFrom,
dateTo,
mediaTypes,
ratingMin,
colorLabel,
flag,
}),
[q, dateFrom, dateTo, mediaTypes, ratingMin, colorLabel, flag]
)
// Fetch photos from backend. Note: backend uses page/per_page (max 500),
// not limit/offset — sending limit/offset previously was a silent no-op.
const { data: photos = [], isLoading } = useQuery({
queryKey: ['photos', filterParams],
queryFn: async () => {
const response = await axios.get<{ photos: Photo[]; total: number }>(
'http://localhost:8001/api/v1/photos',
{
params: {
page: 1,
per_page: 500,
sort: 'taken_at',
order: 'desc',
...filterParams,
},
}
)
return response.data.photos || []
},
staleTime: 30000,
})
// Shared photos query — both Timeline and PreviewView use the same hook so
// they share one cache entry, regardless of filter state.
const { data: photos = [], isLoading } = usePhotosQuery()
// Group photos into rows for grid layout
const rows = useMemo(() => {
@@ -265,7 +221,7 @@ export function Timeline() {
selectPhoto(photo.id, globalIndex)
}
}}
onDoubleClick={() => openLoupe(photo.id)}
onDoubleClick={() => openPreview(photo.id)}
/>
)
})}

View File

@@ -16,7 +16,7 @@ const ALLOWED_COLORS: ColorLabel[] = [
'blue',
'purple',
]
const ALLOWED_FLAGS: FlagFilter[] = ['any', 'picked', 'rejected', 'unflagged']
const ALLOWED_FLAGS: FlagFilter[] = ['any', 'picked', 'trashed', 'unflagged']
function parseUrl(): Partial<FilterState> {
const sp = new URLSearchParams(window.location.search)

View File

@@ -14,7 +14,7 @@ interface KeyboardShortcutsProps {
interface PhotoUpdate {
rating?: number
is_picked?: boolean
is_rejected?: boolean
is_trashed?: boolean
color_label?: string | null
}
@@ -26,15 +26,20 @@ const COLOR_LABELS: Record<string, string> = {
'9': 'green',
}
// Default options shared by every shortcut: preventDefault stops the browser
// from claiming the event (Firefox quick-find on letter keys, Cmd+F search,
// `/` quick-find, Tab focus traversal). enableOnFormTags is left default-off
// so typing in inputs doesn't fire culling shortcuts.
const HK_OPTS = { preventDefault: true } as const
export function useKeyboardShortcuts(props: KeyboardShortcutsProps) {
const { onToggleLeftSidebar, onToggleRightSidebar, getFirstPhotoId } = props
const viewMode = usePhotoStore((s) => s.viewMode)
const openLoupe = usePhotoStore((s) => s.openLoupe)
const closeLoupe = usePhotoStore((s) => s.closeLoupe)
const openPreview = usePhotoStore((s) => s.openPreview)
const closePreview = usePhotoStore((s) => s.closePreview)
const isGrid = viewMode === 'grid'
const isLoupe = viewMode === 'loupe'
const isPreview = viewMode === 'preview'
// Photo mutation shared by every culling shortcut. Reads the active photo
// id from the store at fire time so the closure stays fresh without forcing
@@ -55,96 +60,78 @@ export function useKeyboardShortcuts(props: KeyboardShortcutsProps) {
updateMutation.mutate({ id, data })
}
// Toggle sidebars (allowed in both modes; right sidebar is hidden in loupe
// by App-level CSS so toggling it is effectively grid-only.)
useHotkeys('tab', (e) => {
e.preventDefault()
onToggleLeftSidebar()
})
useHotkeys('i', (e) => {
e.preventDefault()
onToggleRightSidebar()
})
// Toggle sidebars
useHotkeys('tab', onToggleLeftSidebar, HK_OPTS)
useHotkeys('i', onToggleRightSidebar, HK_OPTS)
// Filter bar toggle (\) and search focus (/ or Cmd/Ctrl+F).
useHotkeys('\\', (e) => {
e.preventDefault()
useFilterStore.getState().toggleFilterBar()
})
useHotkeys('\\', () => useFilterStore.getState().toggleFilterBar(), HK_OPTS)
const focusSearch = (e: KeyboardEvent) => {
e.preventDefault()
const focusSearch = () => {
const el = document.getElementById('topbar-search') as HTMLInputElement | null
el?.focus()
el?.select()
}
useHotkeys('/', focusSearch)
useHotkeys('mod+f', focusSearch)
useHotkeys('/', focusSearch, HK_OPTS)
useHotkeys('mod+f', focusSearch, HK_OPTS)
// G always returns to grid (closes loupe if open).
useHotkeys('g', () => {
closeLoupe()
})
// E toggles loupe (open from grid, close from loupe). Enter opens from grid.
const openLoupeFromGrid = () => {
// E and Space both toggle the preview view (open from grid, close from
// preview). Double-click on a thumbnail does the same.
const openPreviewFromGrid = () => {
const id = usePhotoStore.getState().activePhotoId ?? getFirstPhotoId?.() ?? null
if (id) openLoupe(id)
if (id) openPreview(id)
}
useHotkeys(
'e',
() => {
if (isLoupe) {
closeLoupe()
} else {
openLoupeFromGrid()
}
},
[isLoupe, getFirstPhotoId]
)
const togglePreview = () => {
if (isPreview) closePreview()
else openPreviewFromGrid()
}
useHotkeys(
'enter',
(e) => {
if (isGrid) {
e.preventDefault()
openLoupeFromGrid()
}
},
{ enabled: isGrid },
[isGrid, getFirstPhotoId]
)
useHotkeys('e', togglePreview, HK_OPTS, [isPreview, getFirstPhotoId])
useHotkeys('space', togglePreview, HK_OPTS, [isPreview, getFirstPhotoId])
// ── Culling shortcuts (work in both grid and loupe) ──────────────────────
// ── Culling shortcuts (work in both grid and preview) ────────────────────
// Star rating: 1-5 set, 0 clears.
useHotkeys('1,2,3,4,5', (_e, handler) => {
const rating = parseInt(handler.keys![0])
if (Number.isFinite(rating)) updateActive({ rating })
})
useHotkeys(
'1,2,3,4,5',
(_e, handler) => {
const rating = parseInt(handler.keys![0])
if (Number.isFinite(rating)) updateActive({ rating })
},
HK_OPTS
)
useHotkeys('0', () => {
updateActive({ rating: 0 })
})
useHotkeys('0', () => updateActive({ rating: 0 }), HK_OPTS)
// Pick / reject / unflag.
useHotkeys('p', () => {
updateActive({ is_picked: true, is_rejected: false })
})
// Pick / trash / unflag. Trash is the merged "rejected" concept — a soft
// flag that hides the photo from the default timeline view; restore via
// the trash view (or the U shortcut).
useHotkeys(
'p',
() => updateActive({ is_picked: true, is_trashed: false }),
HK_OPTS
)
useHotkeys('x', () => {
updateActive({ is_rejected: true, is_picked: false })
})
useHotkeys(
'x',
() => updateActive({ is_trashed: true, is_picked: false }),
HK_OPTS
)
useHotkeys('u', () => {
updateActive({ is_picked: false, is_rejected: false })
})
useHotkeys(
'u',
() => updateActive({ is_picked: false, is_trashed: false }),
HK_OPTS
)
// Color labels 6-9 (red/orange/yellow/green per spec §6.4).
useHotkeys('6,7,8,9', (_e, handler) => {
const label = COLOR_LABELS[handler.keys![0]]
if (label) updateActive({ color_label: label })
})
useHotkeys(
'6,7,8,9',
(_e, handler) => {
const label = COLOR_LABELS[handler.keys![0]]
if (label) updateActive({ color_label: label })
},
HK_OPTS
)
}

View File

@@ -0,0 +1,55 @@
import { useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { useFilterStore, filtersToParams } from '../store/filterStore'
import type { Photo } from '../types/photo'
/**
* Single source of truth for the timeline photos query. Both Timeline and
* PreviewView call this so they share one cache entry — previously
* PreviewView looked the cache up by key directly, which broke the moment
* Timeline's key gained the filter params.
*/
export function usePhotosQuery() {
const q = useFilterStore((s) => s.q)
const dateFrom = useFilterStore((s) => s.dateFrom)
const dateTo = useFilterStore((s) => s.dateTo)
const mediaTypes = useFilterStore((s) => s.mediaTypes)
const ratingMin = useFilterStore((s) => s.ratingMin)
const colorLabel = useFilterStore((s) => s.colorLabel)
const flag = useFilterStore((s) => s.flag)
const filterParams = useMemo(
() =>
filtersToParams({
q,
dateFrom,
dateTo,
mediaTypes,
ratingMin,
colorLabel,
flag,
}),
[q, dateFrom, dateTo, mediaTypes, ratingMin, colorLabel, flag]
)
return useQuery({
queryKey: ['photos', filterParams],
queryFn: async () => {
const response = await axios.get<{ photos: Photo[]; total: number }>(
'http://localhost:8001/api/v1/photos',
{
params: {
page: 1,
per_page: 500,
sort: 'taken_at',
order: 'desc',
...filterParams,
},
}
)
return response.data.photos || []
},
staleTime: 30_000,
})
}

View File

@@ -2,7 +2,7 @@ import { create } from 'zustand'
export type MediaType = 'photo' | 'video' | 'raw' | 'heic'
export type ColorLabel = 'red' | 'orange' | 'yellow' | 'green' | 'blue' | 'purple'
export type FlagFilter = 'any' | 'picked' | 'rejected' | 'unflagged'
export type FlagFilter = 'any' | 'picked' | 'trashed' | 'unflagged'
export interface FilterState {
q: string
@@ -77,11 +77,8 @@ export function filtersToParams(f: FilterState): Record<string, string | number>
if (f.ratingMin > 0) params.rating_min = f.ratingMin
if (f.colorLabel) params.color_label = f.colorLabel
if (f.flag === 'picked') params.is_picked = 'true'
else if (f.flag === 'rejected') params.is_rejected = 'true'
else if (f.flag === 'unflagged') {
params.is_picked = 'false'
params.is_rejected = 'false'
}
else if (f.flag === 'trashed') params.is_trashed = 'true'
else if (f.flag === 'unflagged') params.is_picked = 'false'
return params
}

View File

@@ -1,7 +1,7 @@
import { create } from 'zustand'
import type { Photo } from '../types/photo'
type ViewMode = 'grid' | 'loupe'
type ViewMode = 'grid' | 'preview'
interface PhotoStore {
photos: Photo[]
@@ -19,8 +19,8 @@ interface PhotoStore {
clearSelection: () => void
setActivePhoto: (id: string | null) => void
setViewMode: (mode: ViewMode) => void
openLoupe: (id: string) => void
closeLoupe: () => void
openPreview: (id: string) => void
closePreview: () => void
}
export const usePhotoStore = create<PhotoStore>((set) => ({
@@ -73,7 +73,7 @@ export const usePhotoStore = create<PhotoStore>((set) => ({
setViewMode: (mode) => set({ viewMode: mode }),
openLoupe: (id) => set({ viewMode: 'loupe', activePhotoId: id }),
openPreview: (id) => set({ viewMode: 'preview', activePhotoId: id }),
closeLoupe: () => set({ viewMode: 'grid' }),
closePreview: () => set({ viewMode: 'grid' }),
}))

View File

@@ -8,7 +8,7 @@ export interface Photo {
taken_at: string | null
rating: number
is_picked: boolean
is_rejected: boolean
is_trashed: boolean
file_hash: string
thumb_small?: string
thumb_medium?: string