Compare commits
98 Commits
v0.1.1
..
aa3fe2062d
| Author | SHA1 | Date | |
|---|---|---|---|
| aa3fe2062d | |||
| af1a443a64 | |||
| 302a3151ef | |||
| d7c3cbd683 | |||
| 2d567c0810 | |||
| 5ff3ff53a6 | |||
| 827e1a8ecf | |||
| 32c6ae09d6 | |||
| 44179c83a7 | |||
| 4fcc42f356 | |||
| aa3d843a4b | |||
| 01faec9155 | |||
| 3242897a3b | |||
| 8f424773d2 | |||
| 2149b4cad5 | |||
| 2901425f42 | |||
| 1074c875a3 | |||
| 58ecb03070 | |||
| 2c0b928bf5 | |||
| fe312e7678 | |||
| 52ac2543ec | |||
| fbf8a7878c | |||
| 4d41f3744f | |||
| c27662dd74 | |||
| ee2a1b204e | |||
| 6806703363 | |||
| 90fd6f4fed | |||
| 053a2bd846 | |||
| 54016df830 | |||
| 5d46ee5b94 | |||
| 83081928f6 | |||
| e374ff6b02 | |||
| 3ab9357d6f | |||
| fe65bc6f38 | |||
| 68932b55c5 | |||
| f1116c6c26 | |||
| b92b850d02 | |||
| bf04df7484 | |||
| d29a779c13 | |||
| b7e82dbf91 | |||
| 749b23723a | |||
| 68d19d219e | |||
| 31b46327fd | |||
| 29d9106039 | |||
| a78111c8d4 | |||
| 4cdbc54d18 | |||
| d5b93b2e21 | |||
| 257b2b54e7 | |||
| d619b01f2e | |||
| 1a971899d1 | |||
| 8fe5daf25d | |||
| 619bd0c9d2 | |||
| 996bb71375 | |||
| 0d9229635b | |||
| cdb8aa20b9 | |||
| d2af84d9e8 | |||
| 68a9df5ab3 | |||
| 79ce458fd5 | |||
| a9a8f8422e | |||
| ab7022e118 | |||
| 23e9850c7a | |||
| c111032d99 | |||
| c13f78c68b | |||
| f2939d70ab | |||
| 8dbabc2d9e | |||
| 5bc397af01 | |||
| af3c8418ee | |||
| 9144be2518 | |||
| d81624573d | |||
| 949382f28c | |||
| e4a63c8bb0 | |||
| 1685134116 | |||
| 705f8c2e56 | |||
| 52d54d2404 | |||
| 3a2b134103 | |||
| 71ad7bf762 | |||
| 992417710f | |||
| 4c6da99507 | |||
| 24d4e82950 | |||
| 7a18011b0f | |||
| cebd709391 | |||
| d55e4c7502 | |||
| a40a2e8d12 | |||
| 2ce1547844 | |||
| 623aabbb51 | |||
| f65fd350cc | |||
| 86a1a53289 | |||
| ebf16e8cb9 | |||
| e7d9c39fd1 | |||
| 136d74a81b | |||
| bb0038e0a1 | |||
| 90dec3b212 | |||
| e3fde46e91 | |||
| a12e81d8bd | |||
| 6bef90b7fb | |||
| 55cd3b5aa7 | |||
| c878970180 | |||
| 1a95e31f78 |
@@ -0,0 +1,22 @@
|
||||
# Keep LF in the working copy for all text files (prettier enforces LF)
|
||||
* text=auto eol=lf
|
||||
|
||||
# Windows scripts that genuinely need CRLF
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
|
||||
# Binary assets — never touch line endings
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.webp binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.mp4 binary
|
||||
*.onnx binary
|
||||
@@ -35,5 +35,12 @@ dist-ssr
|
||||
*.pyc
|
||||
|
||||
# Bundled CUDA runtime DLLs for the CUDA build (copied from the toolkit
|
||||
# locally; ~600 MB, never committed). See RELEASE_PLAN.md "CUDA release variant".
|
||||
# locally; ~600 MB, never committed).
|
||||
src-tauri/cuda-redist/
|
||||
|
||||
# Playwright
|
||||
/test-results/
|
||||
/playwright-report/
|
||||
/blob-report/
|
||||
/playwright/.cache/
|
||||
/playwright/.auth/
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Tauri / Rust (handled by cargo fmt)
|
||||
src-tauri/
|
||||
|
||||
# Lock files & generated
|
||||
pnpm-lock.yaml
|
||||
*.lock
|
||||
|
||||
# Generated
|
||||
src/vite-env.d.ts
|
||||
|
||||
# Public assets
|
||||
public/
|
||||
|
||||
# Website subpackage (has its own config if needed)
|
||||
website/
|
||||
|
||||
# Markdown & docs (hand-written or tool-generated, keep diffs quiet)
|
||||
*.md
|
||||
docs/
|
||||
|
||||
# CI workflows
|
||||
.github/
|
||||
.gitea/
|
||||
|
||||
# Tool-managed config
|
||||
.claude/
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": false,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"bracketSpacing": true,
|
||||
"bracketSameLine": false,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"plugins": ["prettier-plugin-tailwindcss"]
|
||||
}
|
||||
@@ -5,6 +5,149 @@ All notable changes to Phokus are documented here. The format is based on
|
||||
aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
|
||||
(0.x: anything may change between minor versions).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- **What's New** — after updating, Phokus now greets you with a "What's new"
|
||||
toast that opens a tidy in-app tour of the new version. Added, Changed, and
|
||||
Fixed notes are grouped into collapsible sections, so you can skim the good
|
||||
bits without playing "spot the difference".
|
||||
- **Quick theme switch** — right-click the settings cog in the title bar to
|
||||
swap between Phokus, Subtle Light, and Conventional Dark instantly. No Settings
|
||||
detour required.
|
||||
- **Albums** — make your own cross-folder collections without moving a single
|
||||
file. Albums live in their own sidebar section with cover thumbnails, can be
|
||||
created, renamed, reordered, opened, and cleaned up in Manage mode, and deleting
|
||||
one only removes the grouping.
|
||||
- **Gallery multi-select** — hover a thumbnail's top-left corner to start
|
||||
selecting, then use the floating action bar to tag, rate, favorite, add to an
|
||||
album, or delete a whole batch at once. It also works in similar-image, region,
|
||||
and album views, because bulk work should not disappear the moment you need it.
|
||||
- **Colour search** — narrow the Gallery, Timeline, or tag results by dominant
|
||||
colour using toolbar swatches or a custom picker. Great for those "I know it
|
||||
was mostly blue" moments.
|
||||
- **Album-aware similar search** — similar-image and region searches started from
|
||||
an album can now stay inside that album, jump back to the source folder, or
|
||||
search everything.
|
||||
- **Tag manager** — Explore's Tag Cloud now has a Manage mode for renaming,
|
||||
merging, and deleting tags across the whole library.
|
||||
- **Camera info in the lightbox** — the info panel now shows EXIF details like
|
||||
camera, lens, aperture, shutter speed, ISO, and focal length. Geotagged photos
|
||||
also get a browser link for their GPS coordinates, and already-indexed images
|
||||
do not need a re-index.
|
||||
- **Build badge in Settings** — Settings -> Updates now shows whether you are
|
||||
running the CPU build or the CUDA build.
|
||||
- **Choose your tagging model** — Settings -> AI Workspace now lets you pick
|
||||
between the anime-focused WD tagger and JoyTag, which is better suited to photo
|
||||
libraries and stronger on NSFW concepts (if that's your thing, we don't judge).
|
||||
New users get the same choice during the welcome tour, and each model keeps its
|
||||
own confidence threshold instead of sharing one.
|
||||
- **Reset AI tags** — a new reset action in Settings -> AI Workspace and the Tag
|
||||
manager wipes AI-generated tags for a folder or the whole library, cancelling
|
||||
any tagging still in flight. Tag manager rows now show which tags came from the
|
||||
AI, so you know what you are about to lose before you lose it. Manually-added
|
||||
tags are never touched.
|
||||
- **Related tags in Explore** — Hover over a tag in the Tag Cloud to see the tags
|
||||
that most often appear with it, complete with connection lines and image counts.
|
||||
Handy for finding little clusters you did not know were there.
|
||||
- **Pause workers for longer** — Settings -> General can now remember per-folder
|
||||
worker pauses across app restarts, useful for folders you want to keep in the
|
||||
library but leave out of background processing for now.
|
||||
- **Editable folder path** — the folder picker now has an address bar, so you can
|
||||
paste a path directly while still using breadcrumbs for quick jumps.
|
||||
- **Slideshow mode** — turn the lightbox into a fullscreen, image-only slideshow
|
||||
from whatever collection you are already browsing.
|
||||
- **Add to album from the right-click menu** — right-click any image in the
|
||||
Gallery or Timeline and file it straight into an album from the new "Add to
|
||||
Album" submenu. One image, one click, zero ceremony.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Settings got a spring clean** — preferences are now organised into General,
|
||||
Media, Updates & Setup, Storage, and AI Workspace pages, so update and
|
||||
maintenance controls no longer hide at the bottom of unrelated sections.
|
||||
- **Menus got their act together** — right-click menus (images, folders,
|
||||
albums, the theme switcher) and every dropdown (sort, folder scope, settings,
|
||||
sidebar) now share one style with one set of manners: they stay on screen
|
||||
instead of wandering off the edge, all close on Escape, and right-click menus
|
||||
can do proper submenus now. Subtle Light dresses them all the same way too,
|
||||
instead of saving the nice outfit for one dropdown.
|
||||
- **Neater lightbox details** — image and video metadata now sits in two columns,
|
||||
so the info panel shows more at a glance with less scrolling.
|
||||
- **Faster Explore revisits** — returning to a folder's visual clusters should
|
||||
feel much faster now, even in big libraries.
|
||||
- **Calmer Tag Cloud during AI tagging** — Explore no longer keeps hammering the
|
||||
tag list while a folder is actively being tagged, so tagging stays smoother and
|
||||
the cloud catches up once the work settles.
|
||||
- **Faster first-time clustering** — large libraries build their first visual
|
||||
clusters much more quickly, while still keeping the groups nicely balanced.
|
||||
- **Better tag browsing** — the Tag manager now has live search, sorting
|
||||
(most-used, least-used, A-Z, and Z-A), smooth scrolling for huge tag lists, and
|
||||
it keeps your filter/sort in place while you edit.
|
||||
- **Safer deletion** — deleting media now asks for confirmation and clearly says
|
||||
the file is being removed from disk. This covers gallery bulk delete and the
|
||||
Duplicate Finder.
|
||||
- **Clearer update progress** — Settings -> Updates now shows a real download
|
||||
progress bar with a percentage instead of the old lonely "Downloading" label.
|
||||
- **Better narrow-window layout** — the toolbar, filters, search box, colour
|
||||
picker, sidebar, and lightbox info panel now adapt more gracefully when the
|
||||
window is short on space.
|
||||
- **Tidier Explore clusters** — busier clusters get more room, dense groups
|
||||
overlap less, and everything should stay easier to read and click.
|
||||
- **Faster CPU tagging** — CPU-only AI tagging can now use multiple cores while
|
||||
leaving some breathing room for the rest of the app. GPU tagging is unchanged.
|
||||
- **Smoother tooltips** — Phokus now uses its custom tooltip style across more of
|
||||
the app instead of falling back to the native browser tooltip.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Explore no longer flashes the last folder** — switching folders now clears
|
||||
the old clusters/tags and shows a loading state while the new folder catches
|
||||
up.
|
||||
- **Ratings keep your search order** — if you ever rated an image mid-search and
|
||||
watched your results reshuffle themselves, that's over. Similar-image, region,
|
||||
semantic, tag, and album results now stay put.
|
||||
- **Update progress comes back when you need it** — if you dismiss the update
|
||||
prompt and later start the update from the title bar or Settings, the progress
|
||||
toast now reappears instead of hiding away in Settings.
|
||||
- **Subtle Light cleanup** — fixed dark or hard-to-read surfaces, hover states,
|
||||
dialogs, updater buttons, onboarding controls, and green action buttons in the
|
||||
light theme.
|
||||
- **No more self-indexing loops** — adding a broad folder like your whole user
|
||||
profile used to send Phokus off indexing its own thumbnail cache, generating
|
||||
thumbnails of thumbnails until the end of time. It now skips its own app-data
|
||||
directory.
|
||||
- **Background tasks show the active work first** — when one folder is paused and
|
||||
another is processing, the active folder gets the main spot in the background
|
||||
tasks bar.
|
||||
- **First launch fits smaller screens** — on 1366x768-style displays, fresh
|
||||
installs used to open with part of the app tucked below the taskbar. The window
|
||||
now clamps itself to the usable monitor area.
|
||||
- **Explore is clearer in Subtle Light** — cluster captions, buttons, cloud
|
||||
words, hover glows, and the new connection lines now use stronger light-theme
|
||||
colours.
|
||||
- **Explore got a few sharp edges sanded down** — Cluster Cloud uses the in-app
|
||||
tooltip, singular counts now say "1 image", and the folder-scope dropdown no
|
||||
longer hides behind cluster cards.
|
||||
- **AI tagging stays responsive** — starting a big tagging job used to turn the
|
||||
rest of the app into a slideshow. GPU tagging now works in smaller bursts with
|
||||
brief pauses between them, so the UI keeps moving and the first results land
|
||||
sooner.
|
||||
- **Lightbox AI tags wake up on time** — the lightbox's AI tags action no longer
|
||||
stays disabled until you happen to open Settings, and it switches on as soon as
|
||||
a model download finishes.
|
||||
- **Noisy AI tags get cleaned up** — generic low-signal tags from WD and JoyTag
|
||||
are filtered before they are saved, and matching older generated tags are
|
||||
cleaned up on startup. Your manually-added tags are left alone.
|
||||
- **Selected Folders starts empty** — choosing "Selected Folders" for AI tagging
|
||||
no longer pre-selects the first folder. You decide exactly what gets queued.
|
||||
- **A handful of tiny UI papercuts are gone** — the zoom buttons now show the
|
||||
right tile size when you hover them, the folder picker no longer adds an odd
|
||||
trailing slash to Windows drive breadcrumbs, the search field's clear button
|
||||
no longer sits a few pixels too high, and menu labels no longer highlight like
|
||||
text when you drag across them.
|
||||
|
||||
## [0.1.1] — 2026-06-23
|
||||
|
||||
### Added
|
||||
|
||||
@@ -15,8 +15,11 @@ pnpm dev:app
|
||||
# Frontend only (no Tauri window)
|
||||
pnpm dev:vite
|
||||
|
||||
# Production build
|
||||
pnpm build:app
|
||||
# Production build (CPU)
|
||||
pnpm build:app:cpu
|
||||
|
||||
# Production build (CUDA / GPU-accelerated)
|
||||
pnpm build:app:cuda
|
||||
|
||||
# Type-check frontend
|
||||
pnpm build:vite
|
||||
@@ -30,9 +33,10 @@ There are no test suites configured.
|
||||
|
||||
### Frontend (`src/`)
|
||||
|
||||
- **`store.ts`** — single Zustand store (`useGalleryStore`) that owns all app state and all `invoke()` calls to the Tauri backend. Every feature (folders, images, search, similar images, tags, captions, tagger, duplicates) is implemented as store actions here. React components are thin consumers.
|
||||
- **`src/store/`** — single Zustand store (`useGalleryStore`) that owns all app state and all `invoke()` calls to the Tauri backend, split into per-feature slices combined in `index.ts` (which exports `useGalleryStore` and the `GalleryStore` type). `types.ts` holds all interfaces/type unions (including `ImageRecord`); `helpers.ts` holds pure functions and cross-slice module state (search parsing, image sort/merge, request-token guards). Slices: `librarySlice` (folders), `gallerySlice` (image paging/filters/bulk actions), `searchSlice` (search + similar-images), `exploreSlice` (visual clusters, tag cloud, tags), `albumSlice`, `duplicateSlice`, `taggerSlice`, `captionSlice`, `settingsSlice`, `appSlice` (updates, onboarding, ffmpeg, worker pauses); `events.ts` wires the Tauri event listeners (`subscribeToProgress`). Components still call `useGalleryStore(s => s.field)` against one flat state object — the slice split is internal. React components are thin consumers.
|
||||
- **`App.tsx`** — sets up Tauri event listeners (`subscribeToProgress`) and renders the top-level layout (sidebar + active view).
|
||||
- **`src/components/`** — UI components: `Gallery`, `Lightbox`, `Sidebar`, `Toolbar`, `TagCloud`, `DuplicateFinder`, `BackgroundTasks`, `SettingsModal`, `MenuBar`, `TitleBar`.
|
||||
- **`src/components/`** — UI components: `Gallery`, `Lightbox`, `Sidebar`, `Toolbar`, `Timeline`, `ExploreView`, `DuplicateFinder`, `BackgroundTasks`, `SettingsModal`, `TitleBar`.
|
||||
- **`src/components/menu/`** — shared floating-UI primitives: `useDismissable`, `MenuPanel`/`MenuItem`/`SubMenu`, the portal-based `ContextMenu`, and the app-wide `Dropdown`. Build menus, dropdowns, and popovers on these instead of hand-rolling.
|
||||
- State management: Zustand v5, no selectors library — components call `useGalleryStore(s => s.field)` directly.
|
||||
- Styling: Tailwind CSS v4 (Vite plugin, no config file).
|
||||
- Virtualized gallery grid: `@tanstack/react-virtual`.
|
||||
@@ -40,7 +44,7 @@ There are no test suites configured.
|
||||
|
||||
### Search modes
|
||||
|
||||
The search bar supports prefix syntax parsed by `parseSearchValue` in `store.ts`:
|
||||
The search bar supports prefix syntax parsed by `parseSearchValue` in `src/store/helpers.ts`:
|
||||
- No prefix / `f:` — filename search (paginated, DB-backed)
|
||||
- `/s <query>` or `s: <query>` — semantic (embedding) search
|
||||
- `/t <tag>` or `t: <tag>` — tag search
|
||||
@@ -84,7 +88,7 @@ Database: SQLite with WAL mode, stored in the Tauri app data directory as `galle
|
||||
|
||||
### Key types
|
||||
|
||||
`ImageRecord` (mirrored in `store.ts` and `db.rs`) is the central data type. It carries embedding status, tagging status, caption data, and media metadata. The frontend type must stay in sync with the Rust struct serialization.
|
||||
`ImageRecord` (mirrored in `src/store/types.ts` and `db.rs`) is the central data type. It carries embedding status, tagging status, caption data, and media metadata. The frontend type must stay in sync with the Rust struct serialization.
|
||||
|
||||
## Development notes
|
||||
|
||||
|
||||
@@ -109,13 +109,22 @@ pnpm dev:app
|
||||
# Frontend only
|
||||
pnpm dev:vite
|
||||
|
||||
# Production build
|
||||
pnpm build:app
|
||||
# Browser-only UI Lab with mocked Tauri APIs
|
||||
pnpm dev:ui
|
||||
|
||||
# Production build (CPU)
|
||||
pnpm build:app:cpu
|
||||
|
||||
# Production build (CUDA / GPU-accelerated)
|
||||
pnpm build:app:cuda
|
||||
|
||||
# Type-check the frontend
|
||||
pnpm build:vite
|
||||
```
|
||||
|
||||
For visual frontend work without launching Tauri or the Rust backend, see
|
||||
[Phokus UI Lab](docs/ui-lab.md).
|
||||
|
||||
## How it works
|
||||
|
||||
1. Add a folder from the sidebar — the Rust indexer walks it recursively.
|
||||
|
||||
@@ -59,6 +59,6 @@ for the full list.
|
||||
## Checksums
|
||||
|
||||
```
|
||||
SHA-256 (Phokus_0.1.1_x64-setup.exe) = <fill in>
|
||||
SHA-256 (Phokus_0.1.1_x64-cuda-setup.exe) = <fill in>
|
||||
SHA-256 (Phokus_0.1.1_x64-setup.exe) = 1c19cbeb77f38a44149380c42c76b633add65777d317e1f3ff7e45d96d12d287
|
||||
SHA-256 (Phokus_0.1.1_x64-cuda-setup.exe) = a7337ef5ee0478a785b48acc8012e8fc5c957341161d6103409213ad78eb845f
|
||||
```
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# Phokus UI Lab
|
||||
|
||||
Phokus UI Lab is a browser-only development mode for visual work on the real
|
||||
Phokus frontend. It runs the same `App.tsx`, Zustand store, components, and CSS
|
||||
as the Tauri app, but installs Tauri JavaScript mocks before the app imports.
|
||||
|
||||
This gives UI agents and contributors a stable browser target without launching
|
||||
the Rust backend or a Tauri window.
|
||||
|
||||
## Run It
|
||||
|
||||
```bash
|
||||
pnpm dev:ui
|
||||
```
|
||||
|
||||
Then open:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:1422
|
||||
```
|
||||
|
||||
The script runs Vite in the custom `ui` mode:
|
||||
|
||||
```bash
|
||||
vite --mode ui --host 127.0.0.1 --port 1422 --strictPort --open
|
||||
```
|
||||
|
||||
The normal app development commands are unchanged:
|
||||
|
||||
```bash
|
||||
pnpm dev:app # Tauri app + Rust backend
|
||||
pnpm dev:vite # frontend dev server for Tauri dev
|
||||
```
|
||||
|
||||
## Scenarios
|
||||
|
||||
UI Lab reads `?scenario=` from the URL. If no scenario is provided, it uses
|
||||
`rich`.
|
||||
|
||||
| URL | Purpose |
|
||||
| --- | --- |
|
||||
| `/?scenario=rich` | Default realistic library with folders, albums, ratings, favorites, tags, images, and videos |
|
||||
| `/?scenario=empty` | Empty library with no folders or media (onboarding already completed) |
|
||||
| `/?scenario=new-user` | True first run: onboarding tour open, empty library, no tagger model downloaded |
|
||||
| `/?scenario=just-updated` | Rich library that has just been updated — the "What's new" toast fires on launch |
|
||||
| `/?scenario=busy` | Background workers with pending thumbnail, metadata, embedding, caption, and tagging jobs |
|
||||
| `/?scenario=duplicates` | Duplicate Finder opened with duplicate groups already available |
|
||||
| `/?scenario=album` | Gallery opened directly into an album |
|
||||
| `/?scenario=errors` | Broken thumbnails, folder scan errors, failed embeddings, failed tagging, and metadata issues |
|
||||
| `/?scenario=huge` | Large mock library for virtualization and layout checks |
|
||||
|
||||
Examples:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
```
|
||||
|
||||
## Changelog Previews
|
||||
|
||||
The What's New modal adapts its layout to release size (compact single column
|
||||
for small releases, a two-pane section rail for large ones). UI Lab reads
|
||||
`?changelog=` to override which entry the modal shows:
|
||||
|
||||
| URL | Purpose |
|
||||
| --- | --- |
|
||||
| `/?changelog=unreleased` | The in-progress `[Unreleased]` notes — large release, rail layout |
|
||||
| `/?changelog=small` | Synthetic hotfix-sized entry — compact single-column layout |
|
||||
| `/?changelog=0.1.1` | Any specific released version |
|
||||
|
||||
Open the modal via the demo panel: `Ctrl+Shift+D` → Open "What's new" modal.
|
||||
|
||||
Combine with the scenario above to walk the whole post-update greeting for the
|
||||
next release: `/?scenario=just-updated&changelog=unreleased`.
|
||||
|
||||
## How It Works
|
||||
|
||||
`src/main.tsx` bootstraps the app asynchronously. In `ui` mode it imports
|
||||
`src/dev/setupMockTauri.ts` first, then imports the real `App`.
|
||||
|
||||
That order matters because static imports are hoisted. The Tauri mocks must be
|
||||
installed before `App`, the store, the title bar, or visual components import
|
||||
Tauri APIs.
|
||||
|
||||
The mock setup installs:
|
||||
|
||||
- `mockWindows("main")` for window APIs used by the title bar
|
||||
- `mockConvertFileSrc("windows")` as a baseline Tauri file URL mock
|
||||
- `mockIPC(..., { shouldMockEvents: true })` for `invoke`, `listen`, and `emit`
|
||||
|
||||
The in-memory backend lives in:
|
||||
|
||||
```text
|
||||
src/dev/mockBackend.ts
|
||||
src/dev/mockFixtures.ts
|
||||
src/dev/mockScenarios.ts
|
||||
src/dev/applyMockScenario.ts
|
||||
```
|
||||
|
||||
Happy-path fixture media is generated from existing onboarding images and
|
||||
website screenshots into:
|
||||
|
||||
```text
|
||||
public/dev-media/fixture-*.webp
|
||||
```
|
||||
|
||||
The pack is deliberately small and deterministic, but varied enough for browser
|
||||
screenshots: square, portrait, landscape, monochrome, tinted, framed, and
|
||||
interface-like crops. Synthetic or deliberately broken fixture paths can still
|
||||
use the `mock://` scheme described below.
|
||||
|
||||
## Mock Media
|
||||
|
||||
Visual components should use `mediaSrc(...)` instead of calling
|
||||
`convertFileSrc(...)` directly:
|
||||
|
||||
```ts
|
||||
import { mediaSrc } from "../lib/mediaSrc";
|
||||
|
||||
const src = mediaSrc(image.thumbnail_path);
|
||||
```
|
||||
|
||||
In normal Tauri modes, `mediaSrc` delegates to `convertFileSrc`. In UI Lab,
|
||||
root-relative asset URLs such as `/dev-media/fixture-01.webp` are returned
|
||||
as-is. Paths beginning with `mock://` are also served from `public/dev-media`:
|
||||
|
||||
```text
|
||||
mock://thumb-1.svg -> /dev-media/thumb-1.svg
|
||||
```
|
||||
|
||||
Use `mediaSrc` when adding components that render thumbnails, album covers,
|
||||
preview images, or video posters.
|
||||
|
||||
## Adding A Mock Command
|
||||
|
||||
If the browser console logs an unmocked command, add it to
|
||||
`src/dev/mockBackend.ts`.
|
||||
|
||||
Prefer returning realistic data for commands that affect visible UI. For actions
|
||||
that would touch the machine, return a safe no-op:
|
||||
|
||||
```ts
|
||||
case "open_app_data_folder":
|
||||
return null;
|
||||
```
|
||||
|
||||
When adding fixture data, keep it shaped like the real store/Rust contracts.
|
||||
Most frontend-facing types are exported from `src/store.ts`, so the mocks can
|
||||
stay type-checked against the real UI.
|
||||
|
||||
## Adding A Scenario
|
||||
|
||||
1. Add the scenario name to `MockScenario` and `SCENARIOS` in
|
||||
`src/dev/mockScenarios.ts`.
|
||||
2. Adjust fixture creation in `src/dev/mockFixtures.ts`.
|
||||
3. If the scenario should open a specific view, add that behavior in
|
||||
`src/dev/applyMockScenario.ts`.
|
||||
4. Visit `http://127.0.0.1:1422/?scenario=your-scenario` and check for console
|
||||
errors.
|
||||
|
||||
## What UI Lab Is For
|
||||
|
||||
UI Lab is intended for:
|
||||
|
||||
- visual iteration on the real app shell
|
||||
- layout and responsive checks
|
||||
- state-heavy views like Explore, Timeline, Duplicates, albums, and Settings
|
||||
- AI-agent screenshot/browser inspection
|
||||
- safe UI work without filesystem or Rust-side effects
|
||||
|
||||
It is not a replacement for Tauri app testing. Validate native behavior with
|
||||
`pnpm dev:app` when touching:
|
||||
|
||||
- file or folder pickers
|
||||
- filesystem permissions
|
||||
- real thumbnail/video loading
|
||||
- window drag, minimize, maximize, or close behavior
|
||||
- Rust backend performance
|
||||
- updater installation
|
||||
- WebView2-specific behavior
|
||||
|
||||
## Verification
|
||||
|
||||
Useful checks after changing UI Lab:
|
||||
|
||||
```bash
|
||||
pnpm exec tsc --noEmit
|
||||
pnpm build:vite
|
||||
pnpm dev:ui
|
||||
```
|
||||
|
||||
Then smoke-test at least:
|
||||
|
||||
```text
|
||||
http://127.0.0.1:1422/?scenario=rich
|
||||
http://127.0.0.1:1422/?scenario=empty
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
```
|
||||
@@ -5,17 +5,22 @@
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build:app": "tauri build",
|
||||
"build:app:cpu": "tauri build -- --no-default-features",
|
||||
"build:app:cuda": "tauri build --config src-tauri/tauri.cuda.conf.json",
|
||||
"build:vite": "tsc && vite build",
|
||||
"build:web": "cd website && tsc && vite build",
|
||||
"changelog:add": "node tools/changelog-add.mjs",
|
||||
"clean:app": "cd src-tauri && cargo clean",
|
||||
"dev:app": "tauri dev",
|
||||
"dev:app:cpu": "tauri dev -- --no-default-features",
|
||||
"dev:web": "cd website && pnpm dev",
|
||||
"build:app:cpu": "tauri build -- --no-default-features",
|
||||
"build:app:cuda": "tauri build --config src-tauri/tauri.cuda.conf.json",
|
||||
"changelog:add": "node tools/changelog-add.mjs",
|
||||
"dev:ui": "vite --mode ui --host 127.0.0.1 --port 1422 --strictPort --open",
|
||||
"dev:vite": "vite",
|
||||
"dev:web": "cd website && pnpm dev",
|
||||
"format": "prettier --write .",
|
||||
"format:all": "pnpm format && pnpm format:rust",
|
||||
"format:check": "prettier --check .",
|
||||
"format:rust": "cd src-tauri && cargo fmt",
|
||||
"format:rust:check": "cd src-tauri && cargo fmt --check",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
@@ -35,12 +40,16 @@
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.61.1",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@types/d3-force": "^3.0.10",
|
||||
"@types/node": "^26.0.1",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/react-dom": "^19.1.6",
|
||||
"@vitejs/plugin-react": "^4.6.0",
|
||||
"prettier": "^3.9.4",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^7.0.4"
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
* https://github.com/motdotla/dotenv
|
||||
*/
|
||||
// import dotenv from 'dotenv';
|
||||
// import path from 'path';
|
||||
// dotenv.config({ path: path.resolve(__dirname, '.env') });
|
||||
|
||||
/**
|
||||
* See https://playwright.dev/docs/test-configuration.
|
||||
*/
|
||||
export default defineConfig({
|
||||
testDir: './tests',
|
||||
/* Run tests in files in parallel */
|
||||
fullyParallel: true,
|
||||
/* Fail the build on CI if you accidentally left test.only in the source code. */
|
||||
forbidOnly: !!process.env.CI,
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
|
||||
reporter: 'html',
|
||||
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
|
||||
use: {
|
||||
/* Base URL to use in actions like `await page.goto('')`. */
|
||||
// baseURL: 'http://localhost:3000',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
|
||||
/* Configure projects for major browsers */
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
|
||||
{
|
||||
name: 'firefox',
|
||||
use: { ...devices['Desktop Firefox'] },
|
||||
},
|
||||
|
||||
{
|
||||
name: 'webkit',
|
||||
use: { ...devices['Desktop Safari'] },
|
||||
},
|
||||
|
||||
/* Test against mobile viewports. */
|
||||
// {
|
||||
// name: 'Mobile Chrome',
|
||||
// use: { ...devices['Pixel 5'] },
|
||||
// },
|
||||
// {
|
||||
// name: 'Mobile Safari',
|
||||
// use: { ...devices['iPhone 12'] },
|
||||
// },
|
||||
|
||||
/* Test against branded browsers. */
|
||||
// {
|
||||
// name: 'Microsoft Edge',
|
||||
// use: { ...devices['Desktop Edge'], channel: 'msedge' },
|
||||
// },
|
||||
// {
|
||||
// name: 'Google Chrome',
|
||||
// use: { ...devices['Desktop Chrome'], channel: 'chrome' },
|
||||
// },
|
||||
],
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
// webServer: {
|
||||
// command: 'npm run start',
|
||||
// url: 'http://localhost:3000',
|
||||
// reuseExistingServer: !process.env.CI,
|
||||
// },
|
||||
})
|
||||
@@ -48,15 +48,21 @@ importers:
|
||||
specifier: ^5.0.12
|
||||
version: 5.0.12(@types/react@19.2.14)(react@19.2.4)
|
||||
devDependencies:
|
||||
'@playwright/test':
|
||||
specifier: ^1.61.1
|
||||
version: 1.61.1
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
version: 4.2.2(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
'@tauri-apps/cli':
|
||||
specifier: ^2
|
||||
version: 2.10.1
|
||||
'@types/d3-force':
|
||||
specifier: ^3.0.10
|
||||
version: 3.0.10
|
||||
'@types/node':
|
||||
specifier: ^26.0.1
|
||||
version: 26.0.1
|
||||
'@types/react':
|
||||
specifier: ^19.1.8
|
||||
version: 19.2.14
|
||||
@@ -65,7 +71,13 @@ importers:
|
||||
version: 19.2.3(@types/react@19.2.14)
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^4.6.0
|
||||
version: 4.7.0(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
version: 4.7.0(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
prettier:
|
||||
specifier: ^3.9.4
|
||||
version: 3.9.4
|
||||
prettier-plugin-tailwindcss:
|
||||
specifier: ^0.8.0
|
||||
version: 0.8.0(prettier@3.9.4)
|
||||
tailwindcss:
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2
|
||||
@@ -74,7 +86,7 @@ importers:
|
||||
version: 5.8.3
|
||||
vite:
|
||||
specifier: ^7.0.4
|
||||
version: 7.3.1(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
version: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
|
||||
website:
|
||||
dependencies:
|
||||
@@ -96,7 +108,7 @@ importers:
|
||||
devDependencies:
|
||||
'@tailwindcss/vite':
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
version: 4.2.2(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
'@types/react':
|
||||
specifier: ^19.1.8
|
||||
version: 19.2.14
|
||||
@@ -105,7 +117,7 @@ importers:
|
||||
version: 19.2.3(@types/react@19.2.14)
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^4.6.0
|
||||
version: 4.7.0(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
version: 4.7.0(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
tailwindcss:
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2
|
||||
@@ -114,10 +126,10 @@ importers:
|
||||
version: 5.8.3
|
||||
vite:
|
||||
specifier: ^7.0.4
|
||||
version: 7.3.1(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
version: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
vite-imagetools:
|
||||
specifier: ^10.0.0
|
||||
version: 10.0.0(rollup@4.60.1)(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
version: 10.0.0(rollup@4.60.1)(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
|
||||
packages:
|
||||
|
||||
@@ -538,6 +550,11 @@ packages:
|
||||
'@jridgewell/trace-mapping@0.3.31':
|
||||
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
|
||||
|
||||
'@playwright/test@1.61.1':
|
||||
resolution: {integrity: sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
'@rolldown/pluginutils@1.0.0-beta.27':
|
||||
resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}
|
||||
|
||||
@@ -906,6 +923,9 @@ packages:
|
||||
'@types/estree@1.0.8':
|
||||
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
|
||||
|
||||
'@types/node@26.0.1':
|
||||
resolution: {integrity: sha512-fc3KiUoBt6kie0N9bIW3E47vZsuaMf0PM2AaUpLCLT0s/LvX1nxAim6Fc049cNxODPpGm6qRAuUOB86SkRuPQw==}
|
||||
|
||||
'@types/react-dom@19.2.3':
|
||||
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
|
||||
peerDependencies:
|
||||
@@ -1010,6 +1030,11 @@ packages:
|
||||
react-dom:
|
||||
optional: true
|
||||
|
||||
fsevents@2.3.2:
|
||||
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
os: [darwin]
|
||||
|
||||
fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
@@ -1147,10 +1172,80 @@ packages:
|
||||
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
playwright-core@1.61.1:
|
||||
resolution: {integrity: sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
playwright@1.61.1:
|
||||
resolution: {integrity: sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==}
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
postcss@8.5.8:
|
||||
resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
prettier-plugin-tailwindcss@0.8.0:
|
||||
resolution: {integrity: sha512-V8ITGH87yuBDF6JpEZTOVlUz/saAwqb8f3HRgUj8Lh+tGCcrmorhsLpYqzygwFwK0PE2Ib6Mv3M7T/uE2tZV1g==}
|
||||
engines: {node: '>=20.19'}
|
||||
peerDependencies:
|
||||
'@ianvs/prettier-plugin-sort-imports': '*'
|
||||
'@prettier/plugin-hermes': '*'
|
||||
'@prettier/plugin-oxc': '*'
|
||||
'@prettier/plugin-pug': '*'
|
||||
'@shopify/prettier-plugin-liquid': '*'
|
||||
'@trivago/prettier-plugin-sort-imports': '*'
|
||||
'@zackad/prettier-plugin-twig': '*'
|
||||
prettier: ^3.0
|
||||
prettier-plugin-astro: '*'
|
||||
prettier-plugin-css-order: '*'
|
||||
prettier-plugin-jsdoc: '*'
|
||||
prettier-plugin-marko: '*'
|
||||
prettier-plugin-multiline-arrays: '*'
|
||||
prettier-plugin-organize-attributes: '*'
|
||||
prettier-plugin-organize-imports: '*'
|
||||
prettier-plugin-sort-imports: '*'
|
||||
prettier-plugin-svelte: '*'
|
||||
peerDependenciesMeta:
|
||||
'@ianvs/prettier-plugin-sort-imports':
|
||||
optional: true
|
||||
'@prettier/plugin-hermes':
|
||||
optional: true
|
||||
'@prettier/plugin-oxc':
|
||||
optional: true
|
||||
'@prettier/plugin-pug':
|
||||
optional: true
|
||||
'@shopify/prettier-plugin-liquid':
|
||||
optional: true
|
||||
'@trivago/prettier-plugin-sort-imports':
|
||||
optional: true
|
||||
'@zackad/prettier-plugin-twig':
|
||||
optional: true
|
||||
prettier-plugin-astro:
|
||||
optional: true
|
||||
prettier-plugin-css-order:
|
||||
optional: true
|
||||
prettier-plugin-jsdoc:
|
||||
optional: true
|
||||
prettier-plugin-marko:
|
||||
optional: true
|
||||
prettier-plugin-multiline-arrays:
|
||||
optional: true
|
||||
prettier-plugin-organize-attributes:
|
||||
optional: true
|
||||
prettier-plugin-organize-imports:
|
||||
optional: true
|
||||
prettier-plugin-sort-imports:
|
||||
optional: true
|
||||
prettier-plugin-svelte:
|
||||
optional: true
|
||||
|
||||
prettier@3.9.4:
|
||||
resolution: {integrity: sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==}
|
||||
engines: {node: '>=14'}
|
||||
hasBin: true
|
||||
|
||||
react-dom@19.2.4:
|
||||
resolution: {integrity: sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==}
|
||||
peerDependencies:
|
||||
@@ -1208,6 +1303,9 @@ packages:
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
undici-types@8.3.0:
|
||||
resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
|
||||
|
||||
update-browserslist-db@1.2.3:
|
||||
resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
|
||||
hasBin: true
|
||||
@@ -1597,6 +1695,10 @@ snapshots:
|
||||
'@jridgewell/resolve-uri': 3.1.2
|
||||
'@jridgewell/sourcemap-codec': 1.5.5
|
||||
|
||||
'@playwright/test@1.61.1':
|
||||
dependencies:
|
||||
playwright: 1.61.1
|
||||
|
||||
'@rolldown/pluginutils@1.0.0-beta.27': {}
|
||||
|
||||
'@rollup/pluginutils@5.4.0(rollup@4.60.1)':
|
||||
@@ -1743,12 +1845,12 @@ snapshots:
|
||||
'@tailwindcss/oxide-win32-arm64-msvc': 4.2.2
|
||||
'@tailwindcss/oxide-win32-x64-msvc': 4.2.2
|
||||
|
||||
'@tailwindcss/vite@4.2.2(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))':
|
||||
'@tailwindcss/vite@4.2.2(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))':
|
||||
dependencies:
|
||||
'@tailwindcss/node': 4.2.2
|
||||
'@tailwindcss/oxide': 4.2.2
|
||||
tailwindcss: 4.2.2
|
||||
vite: 7.3.1(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
vite: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
|
||||
'@tanstack/react-virtual@3.13.23(react-dom@19.2.4(react@19.2.4))(react@19.2.4)':
|
||||
dependencies:
|
||||
@@ -1856,6 +1958,10 @@ snapshots:
|
||||
|
||||
'@types/estree@1.0.8': {}
|
||||
|
||||
'@types/node@26.0.1':
|
||||
dependencies:
|
||||
undici-types: 8.3.0
|
||||
|
||||
'@types/react-dom@19.2.3(@types/react@19.2.14)':
|
||||
dependencies:
|
||||
'@types/react': 19.2.14
|
||||
@@ -1864,7 +1970,7 @@ snapshots:
|
||||
dependencies:
|
||||
csstype: 3.2.3
|
||||
|
||||
'@vitejs/plugin-react@4.7.0(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0))':
|
||||
'@vitejs/plugin-react@4.7.0(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.0)
|
||||
@@ -1872,7 +1978,7 @@ snapshots:
|
||||
'@rolldown/pluginutils': 1.0.0-beta.27
|
||||
'@types/babel__core': 7.20.5
|
||||
react-refresh: 0.17.0
|
||||
vite: 7.3.1(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
vite: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -1963,6 +2069,9 @@ snapshots:
|
||||
react: 19.2.4
|
||||
react-dom: 19.2.4(react@19.2.4)
|
||||
|
||||
fsevents@2.3.2:
|
||||
optional: true
|
||||
|
||||
fsevents@2.3.3:
|
||||
optional: true
|
||||
|
||||
@@ -2053,12 +2162,26 @@ snapshots:
|
||||
|
||||
picomatch@4.0.4: {}
|
||||
|
||||
playwright-core@1.61.1: {}
|
||||
|
||||
playwright@1.61.1:
|
||||
dependencies:
|
||||
playwright-core: 1.61.1
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.2
|
||||
|
||||
postcss@8.5.8:
|
||||
dependencies:
|
||||
nanoid: 3.3.11
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
|
||||
prettier-plugin-tailwindcss@0.8.0(prettier@3.9.4):
|
||||
dependencies:
|
||||
prettier: 3.9.4
|
||||
|
||||
prettier@3.9.4: {}
|
||||
|
||||
react-dom@19.2.4(react@19.2.4):
|
||||
dependencies:
|
||||
react: 19.2.4
|
||||
@@ -2151,22 +2274,24 @@ snapshots:
|
||||
|
||||
typescript@5.8.3: {}
|
||||
|
||||
undici-types@8.3.0: {}
|
||||
|
||||
update-browserslist-db@1.2.3(browserslist@4.28.2):
|
||||
dependencies:
|
||||
browserslist: 4.28.2
|
||||
escalade: 3.2.0
|
||||
picocolors: 1.1.1
|
||||
|
||||
vite-imagetools@10.0.0(rollup@4.60.1)(vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0)):
|
||||
vite-imagetools@10.0.0(rollup@4.60.1)(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)):
|
||||
dependencies:
|
||||
'@rollup/pluginutils': 5.4.0(rollup@4.60.1)
|
||||
imagetools-core: 9.1.0
|
||||
sharp: 0.34.5
|
||||
vite: 7.3.1(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
vite: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
transitivePeerDependencies:
|
||||
- rollup
|
||||
|
||||
vite@7.3.1(jiti@2.6.1)(lightningcss@1.32.0):
|
||||
vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0):
|
||||
dependencies:
|
||||
esbuild: 0.27.7
|
||||
fdir: 6.5.0(picomatch@4.0.4)
|
||||
@@ -2175,6 +2300,7 @@ snapshots:
|
||||
rollup: 4.60.1
|
||||
tinyglobby: 0.2.15
|
||||
optionalDependencies:
|
||||
'@types/node': 26.0.1
|
||||
fsevents: 2.3.3
|
||||
jiti: 2.6.1
|
||||
lightningcss: 1.32.0
|
||||
|
||||
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 105 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 7.1 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 21 KiB |
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# Codex Cloud setup for Phokus.
|
||||
# Paste this script into the Codex Cloud environment setup field, or run it from
|
||||
# the repo root with: bash scripts/codex-cloud-setup.sh
|
||||
#
|
||||
# Goals:
|
||||
# - install Linux packages needed by Tauri/WebKit and native Rust crates
|
||||
# - install JS dependencies with pnpm using the lockfile
|
||||
# - pre-fetch Rust dependencies while setup still has internet access
|
||||
# - keep the environment CPU-safe by avoiding Phokus' default CUDA feature set
|
||||
# - leave Codex with clear verification commands for UI and Rust work
|
||||
|
||||
log() {
|
||||
printf '\n\033[1;36m[phokus-codex]\033[0m %s\n' "$*"
|
||||
}
|
||||
|
||||
warn() {
|
||||
printf '\n\033[1;33m[phokus-codex warning]\033[0m %s\n' "$*" >&2
|
||||
}
|
||||
|
||||
repo_root="$(pwd)"
|
||||
|
||||
if [[ ! -f "package.json" || ! -d "src-tauri" ]]; then
|
||||
warn "This script should be run from the Phokus repository root. Current directory: ${repo_root}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export CI=1
|
||||
export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"
|
||||
export PATH="$PNPM_HOME:$HOME/.cargo/bin:$PATH"
|
||||
|
||||
# Persist useful shell defaults for the later Codex agent phase. Codex setup runs
|
||||
# in a separate Bash session, so exports here alone would not survive.
|
||||
if ! grep -q "# Phokus Codex Cloud" "$HOME/.bashrc" 2>/dev/null; then
|
||||
cat >> "$HOME/.bashrc" <<'BASHRC'
|
||||
|
||||
# Phokus Codex Cloud
|
||||
export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"
|
||||
export PATH="$PNPM_HOME:$HOME/.cargo/bin:$PATH"
|
||||
export CI=1
|
||||
BASHRC
|
||||
fi
|
||||
|
||||
install_apt_packages() {
|
||||
if ! command -v apt-get >/dev/null 2>&1; then
|
||||
warn "apt-get not found; skipping system package installation."
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "Installing Linux system dependencies for Tauri, WebKit, SQLite/native crates, and browser tooling"
|
||||
|
||||
sudo apt-get update
|
||||
|
||||
# Tauri v2 Linux builds need the WebKitGTK/AppIndicator/Rsvg stack. Some base
|
||||
# images expose either the 4.1 or 4.0 WebKit development package, so try the
|
||||
# modern package first and gracefully fall back.
|
||||
local common_packages=(
|
||||
build-essential
|
||||
curl
|
||||
wget
|
||||
file
|
||||
pkg-config
|
||||
libssl-dev
|
||||
libgtk-3-dev
|
||||
libayatana-appindicator3-dev
|
||||
librsvg2-dev
|
||||
patchelf
|
||||
ca-certificates
|
||||
)
|
||||
|
||||
if apt-cache show libwebkit2gtk-4.1-dev >/dev/null 2>&1; then
|
||||
sudo apt-get install -y --no-install-recommends "${common_packages[@]}" libwebkit2gtk-4.1-dev
|
||||
else
|
||||
sudo apt-get install -y --no-install-recommends "${common_packages[@]}" libwebkit2gtk-4.0-dev
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_node_and_pnpm() {
|
||||
log "Preparing Node/pnpm"
|
||||
|
||||
if ! command -v node >/dev/null 2>&1; then
|
||||
warn "Node.js is not available in this image. Pin Node.js 20+ in the Codex environment settings or use a Codex universal image with Node installed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node_major="$(node -p "process.versions.node.split('.')[0]")"
|
||||
if [[ "$node_major" -lt 20 ]]; then
|
||||
warn "Phokus expects Node.js 20+. Current version: $(node --version). Pin Node.js 20+ in Codex environment settings."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$PNPM_HOME"
|
||||
|
||||
if command -v corepack >/dev/null 2>&1; then
|
||||
corepack enable
|
||||
corepack prepare pnpm@latest --activate
|
||||
fi
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
npm install -g pnpm
|
||||
fi
|
||||
|
||||
log "Node: $(node --version)"
|
||||
log "pnpm: $(pnpm --version)"
|
||||
}
|
||||
|
||||
ensure_rust() {
|
||||
log "Preparing Rust toolchain"
|
||||
|
||||
if ! command -v rustup >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
# shellcheck source=/dev/null
|
||||
source "$HOME/.cargo/env"
|
||||
fi
|
||||
|
||||
rustup toolchain install stable --profile minimal
|
||||
rustup default stable
|
||||
rustup component add rustfmt clippy
|
||||
|
||||
log "rustc: $(rustc --version)"
|
||||
log "cargo: $(cargo --version)"
|
||||
}
|
||||
|
||||
install_js_dependencies() {
|
||||
log "Installing frontend dependencies"
|
||||
pnpm install --frozen-lockfile
|
||||
}
|
||||
|
||||
prefetch_rust_dependencies() {
|
||||
log "Pre-fetching Rust dependencies for CPU-safe Tauri checks"
|
||||
|
||||
# Phokus enables candle-cuda by default in Cargo.toml. Codex Cloud usually runs
|
||||
# in a CPU Linux container, so use --no-default-features for checks/builds
|
||||
# unless you intentionally configure a CUDA-capable environment.
|
||||
cargo fetch --manifest-path src-tauri/Cargo.toml --locked
|
||||
|
||||
# This is intentionally a check, not a full release build. It warms the Cargo
|
||||
# cache and catches missing native packages without making setup painfully slow.
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --locked --no-default-features
|
||||
}
|
||||
|
||||
install_playwright_browsers() {
|
||||
log "Installing Playwright Chromium dependencies for UI Lab/browser screenshots"
|
||||
|
||||
# Safe even if no Playwright tests are present yet. Useful for Codex browser
|
||||
# inspection against `pnpm dev:ui`.
|
||||
pnpm exec playwright install --with-deps chromium || warn "Playwright browser install failed; UI work may still run, but browser automation/screenshots may need manual setup."
|
||||
}
|
||||
|
||||
print_next_steps() {
|
||||
cat <<'EOF'
|
||||
|
||||
[phokus-codex] Setup complete.
|
||||
|
||||
Recommended Codex verification commands:
|
||||
pnpm exec tsc --noEmit
|
||||
pnpm build:vite
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --locked --no-default-features
|
||||
|
||||
For visual UI work in Codex/browser environments:
|
||||
pnpm dev:ui
|
||||
open http://127.0.0.1:1422/?scenario=rich
|
||||
|
||||
Other useful UI Lab scenarios:
|
||||
http://127.0.0.1:1422/?scenario=empty
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
|
||||
Avoid the below in standard CPU-only Codex Cloud unless you have configured CUDA:
|
||||
pnpm dev:app
|
||||
pnpm build:app:cuda
|
||||
cargo check --manifest-path src-tauri/Cargo.toml
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
install_apt_packages
|
||||
ensure_node_and_pnpm
|
||||
ensure_rust
|
||||
install_js_dependencies
|
||||
prefetch_rust_dependencies
|
||||
install_playwright_browsers
|
||||
print_next_steps
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -0,0 +1,45 @@
|
||||
/// AI-generated tags that are too broad/noisy to be useful in this gallery.
|
||||
/// Edit this list to change what the tagger removes. Manual user tags are not
|
||||
/// affected.
|
||||
pub const AI_TAG_REMOVAL_LIST: &[&str] = &["1girl", "1boy", "no humans", "2girls", "2boys"];
|
||||
|
||||
fn normalize_tag_for_removal(tag: &str) -> String {
|
||||
tag.trim()
|
||||
.chars()
|
||||
.filter(|c| !matches!(c, ' ' | '_' | '-'))
|
||||
.flat_map(char::to_lowercase)
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn is_removed_ai_tag(tag: &str) -> bool {
|
||||
let normalized = normalize_tag_for_removal(tag);
|
||||
AI_TAG_REMOVAL_LIST
|
||||
.iter()
|
||||
.any(|blocked| normalize_tag_for_removal(blocked) == normalized)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn removed_ai_tags_match_common_spellings() {
|
||||
for tag in [
|
||||
"1girl",
|
||||
"1 girl",
|
||||
"1_girl",
|
||||
"1-girl",
|
||||
"NO_HUMANS",
|
||||
"no humans",
|
||||
] {
|
||||
assert!(is_removed_ai_tag(tag), "{tag} should be removed");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_ai_tags_do_not_match_unrelated_tags() {
|
||||
for tag in ["girl", "boy", "humans", "solo", "landscape"] {
|
||||
assert!(!is_removed_ai_tag(tag), "{tag} should be kept");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Dominant-color palette extraction for color search.
|
||||
//!
|
||||
//! Colors are sampled from the already-generated thumbnail (small, fast) rather
|
||||
//! than the full image. We coarse-quantize pixels into an RGB histogram, then
|
||||
//! return the most populated bins as representative colors with their weight
|
||||
//! (fraction of sampled pixels). Search then filters images whose palette has a
|
||||
//! color within a distance threshold of the query color.
|
||||
|
||||
use image::RgbImage;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct PaletteColor {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
/// Fraction of sampled pixels (0.0–1.0) that fell in this color's bin.
|
||||
pub weight: f32,
|
||||
}
|
||||
|
||||
/// Bits kept per channel when binning. 4 bits → 16 levels/channel → 4096 bins:
|
||||
/// coarse enough to group near-identical shades, fine enough to separate hues.
|
||||
const QUANT_BITS: u32 = 4;
|
||||
/// Cap on sampled pixels so very large frames stay cheap; thumbnails are tiny so
|
||||
/// this rarely bites, but the backfill may read arbitrary thumbnail sizes.
|
||||
const MAX_SAMPLES: usize = 50_000;
|
||||
|
||||
/// Extract up to `k` dominant colors from an RGB image, most-common first.
|
||||
pub fn extract_palette(img: &RgbImage, k: usize) -> Vec<PaletteColor> {
|
||||
let pixels = img.as_raw();
|
||||
let pixel_count = pixels.len() / 3;
|
||||
if pixel_count == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let step = (pixel_count / MAX_SAMPLES).max(1);
|
||||
let shift = 8 - QUANT_BITS;
|
||||
|
||||
// bin key → (sum_r, sum_g, sum_b, count); summing lets us return the bin's
|
||||
// average color rather than the quantized corner.
|
||||
let mut bins: HashMap<u16, (u64, u64, u64, u64)> = HashMap::new();
|
||||
let mut total: u64 = 0;
|
||||
for pixel in pixels.chunks_exact(3).step_by(step) {
|
||||
let (r, g, b) = (pixel[0], pixel[1], pixel[2]);
|
||||
let key = (((r as u16) >> shift) << (QUANT_BITS * 2))
|
||||
| (((g as u16) >> shift) << QUANT_BITS)
|
||||
| ((b as u16) >> shift);
|
||||
let entry = bins.entry(key).or_insert((0, 0, 0, 0));
|
||||
entry.0 += r as u64;
|
||||
entry.1 += g as u64;
|
||||
entry.2 += b as u64;
|
||||
entry.3 += 1;
|
||||
total += 1;
|
||||
}
|
||||
if total == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut entries: Vec<(u64, u64, u64, u64)> = bins.into_values().collect();
|
||||
entries.sort_unstable_by_key(|entry| std::cmp::Reverse(entry.3));
|
||||
entries
|
||||
.into_iter()
|
||||
.take(k)
|
||||
.map(|(sum_r, sum_g, sum_b, count)| PaletteColor {
|
||||
r: (sum_r / count) as u8,
|
||||
g: (sum_g / count) as u8,
|
||||
b: (sum_b / count) as u8,
|
||||
weight: count as f32 / total as f32,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Decode a thumbnail file and extract its palette. Used by the backfill pass.
|
||||
pub fn extract_palette_from_file(thumbnail_path: &Path, k: usize) -> Option<Vec<PaletteColor>> {
|
||||
let img = image::ImageReader::open(thumbnail_path)
|
||||
.ok()?
|
||||
.decode()
|
||||
.ok()?;
|
||||
Some(extract_palette(&img.into_rgb8(), k))
|
||||
}
|
||||
|
||||
/// Number of palette colors stored per image.
|
||||
pub const PALETTE_SIZE: usize = 5;
|
||||
|
||||
/// Max squared RGB distance for a palette color to count as matching a query
|
||||
/// color (~70 units in RGB space). Tunable feel/precision of color search.
|
||||
pub const MATCH_DISTANCE_SQ: i64 = 4900;
|
||||
|
||||
/// Minimum weight (fraction of pixels) a palette color must have to match, so
|
||||
/// trivial specks of a color don't trigger a match.
|
||||
pub const MATCH_MIN_WEIGHT: f64 = 0.05;
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::vector;
|
||||
use crate::{ai_tag_filter, vector};
|
||||
use anyhow::Result;
|
||||
use r2d2::Pool;
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
@@ -34,6 +34,18 @@ pub struct Folder {
|
||||
pub sort_order: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Album {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub cover_image_id: Option<i64>,
|
||||
pub cover_thumbnail_path: Option<String>,
|
||||
pub image_count: i64,
|
||||
pub sort_order: i64,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ImageRecord {
|
||||
pub id: i64,
|
||||
@@ -134,6 +146,8 @@ pub struct ExploreTagEntry {
|
||||
pub count: i64,
|
||||
pub representative_image_id: i64,
|
||||
pub thumbnail_path: Option<String>,
|
||||
pub has_ai_source: bool,
|
||||
pub has_user_source: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -255,12 +269,16 @@ pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
UNIQUE(image_id, tag)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tag_cloud_cache (
|
||||
CREATE TABLE IF NOT EXISTS visual_cluster_cache (
|
||||
folder_scope TEXT PRIMARY KEY,
|
||||
image_ids_hash INTEGER NOT NULL,
|
||||
entries_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
-- Renamed from the misnamed tag_cloud_cache (it caches visual clusters,
|
||||
-- not tags). The cache is disposable and was already invalidated by a
|
||||
-- cluster-algorithm version bump, so the old table is simply dropped.
|
||||
DROP TABLE IF EXISTS tag_cloud_cache;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS duplicate_scan_cache (
|
||||
folder_scope TEXT PRIMARY KEY,
|
||||
@@ -285,6 +303,42 @@ pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_source ON image_tags(source);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_tag ON image_tags(tag);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_tag_image_id ON image_tags(tag, image_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS albums (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
cover_image_id INTEGER REFERENCES images(id) ON DELETE SET NULL,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
-- Forward-compat for smart albums (saved searches); unused in v1.
|
||||
-- 'manual' = a curated set held in album_images.
|
||||
kind TEXT NOT NULL DEFAULT 'manual',
|
||||
query_json TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS album_images (
|
||||
album_id INTEGER NOT NULL REFERENCES albums(id) ON DELETE CASCADE,
|
||||
image_id INTEGER NOT NULL REFERENCES images(id) ON DELETE CASCADE,
|
||||
position INTEGER NOT NULL DEFAULT 0,
|
||||
added_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (album_id, image_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_album_images_album ON album_images(album_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_album_images_image ON album_images(image_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS image_colors (
|
||||
image_id INTEGER NOT NULL REFERENCES images(id) ON DELETE CASCADE,
|
||||
idx INTEGER NOT NULL,
|
||||
r INTEGER NOT NULL,
|
||||
g INTEGER NOT NULL,
|
||||
b INTEGER NOT NULL,
|
||||
weight REAL NOT NULL,
|
||||
PRIMARY KEY (image_id, idx)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_colors_image ON image_colors(image_id);
|
||||
",
|
||||
)?;
|
||||
|
||||
@@ -331,6 +385,42 @@ pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
)?;
|
||||
|
||||
vector::migrate(conn)?;
|
||||
remove_filtered_ai_tags(conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove_filtered_ai_tags(conn: &Connection) -> Result<()> {
|
||||
let mut stmt = conn.prepare("SELECT id, tag FROM image_tags WHERE source = 'ai'")?;
|
||||
let filtered_ids = stmt
|
||||
.query_map([], |row| {
|
||||
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
|
||||
})?
|
||||
.filter_map(|row| match row {
|
||||
Ok((id, tag)) if ai_tag_filter::is_removed_ai_tag(&tag) => Some(Ok(id)),
|
||||
Ok(_) => None,
|
||||
Err(error) => Some(Err(error)),
|
||||
})
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
drop(stmt);
|
||||
|
||||
if filtered_ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
{
|
||||
let mut delete_stmt = tx.prepare("DELETE FROM image_tags WHERE id = ?1")?;
|
||||
for id in &filtered_ids {
|
||||
delete_stmt.execute([id])?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
|
||||
log::info!(
|
||||
"Removed {} filtered AI tag(s) from existing library data",
|
||||
filtered_ids.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1586,6 +1676,309 @@ pub fn reorder_folders(conn: &Connection, folder_ids: &[i64]) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Albums ────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn map_album_row(row: &Row<'_>) -> rusqlite::Result<Album> {
|
||||
Ok(Album {
|
||||
id: row.get(0)?,
|
||||
name: row.get(1)?,
|
||||
cover_image_id: row.get(2)?,
|
||||
cover_thumbnail_path: row.get(3)?,
|
||||
image_count: row.get(4)?,
|
||||
sort_order: row.get(5)?,
|
||||
created_at: row.get(6)?,
|
||||
updated_at: row.get(7)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// SELECT that resolves each album's cover thumbnail (explicit cover, else the
|
||||
/// first member by position) and live image count. Shared by list/get-one.
|
||||
const ALBUM_SELECT: &str = "
|
||||
SELECT a.id, a.name, a.cover_image_id,
|
||||
(SELECT ci.thumbnail_path FROM images ci
|
||||
WHERE ci.id = COALESCE(
|
||||
a.cover_image_id,
|
||||
(SELECT ai.image_id FROM album_images ai
|
||||
WHERE ai.album_id = a.id
|
||||
ORDER BY ai.position, ai.added_at LIMIT 1)
|
||||
)) AS cover_thumbnail_path,
|
||||
(SELECT COUNT(*) FROM album_images ai WHERE ai.album_id = a.id) AS image_count,
|
||||
a.sort_order, a.created_at, a.updated_at
|
||||
FROM albums a";
|
||||
|
||||
pub fn list_albums(conn: &Connection) -> Result<Vec<Album>> {
|
||||
let sql = format!("{ALBUM_SELECT} ORDER BY a.sort_order, a.id");
|
||||
let mut stmt = conn.prepare(&sql)?;
|
||||
let rows = stmt.query_map([], map_album_row)?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn get_album(conn: &Connection, album_id: i64) -> Result<Album> {
|
||||
let sql = format!("{ALBUM_SELECT} WHERE a.id = ?1");
|
||||
conn.query_row(&sql, [album_id], map_album_row)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn create_album(conn: &Connection, name: &str) -> Result<Album> {
|
||||
let id: i64 = conn.query_row(
|
||||
"INSERT INTO albums (name, sort_order)
|
||||
VALUES (?1, COALESCE((SELECT MAX(sort_order) + 1 FROM albums), 1))
|
||||
RETURNING id",
|
||||
params![name],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
get_album(conn, id)
|
||||
}
|
||||
|
||||
pub fn rename_album(conn: &Connection, album_id: i64, new_name: &str) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE albums SET name = ?2, updated_at = datetime('now') WHERE id = ?1",
|
||||
params![album_id, new_name],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_album(conn: &Connection, album_id: i64) -> Result<()> {
|
||||
// album_images rows cascade away via the FK.
|
||||
conn.execute("DELETE FROM albums WHERE id = ?1", [album_id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete many albums at once (membership rows cascade away via the FK).
|
||||
pub fn delete_albums(conn: &Connection, album_ids: &[i64]) -> Result<()> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
for album_id in album_ids {
|
||||
tx.execute("DELETE FROM albums WHERE id = ?1", [album_id])?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn reorder_albums(conn: &Connection, album_ids: &[i64]) -> Result<()> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
for (index, album_id) in album_ids.iter().enumerate() {
|
||||
tx.execute(
|
||||
"UPDATE albums SET sort_order = ?2 WHERE id = ?1",
|
||||
params![album_id, index as i64 + 1],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Append images to an album (idempotent). Returns the number newly added.
|
||||
pub fn add_images_to_album(conn: &Connection, album_id: i64, image_ids: &[i64]) -> Result<i64> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
let mut next_position: i64 = tx.query_row(
|
||||
"SELECT COALESCE(MAX(position) + 1, 0) FROM album_images WHERE album_id = ?1",
|
||||
[album_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let mut added = 0i64;
|
||||
for image_id in image_ids {
|
||||
let changed = tx.execute(
|
||||
"INSERT INTO album_images (album_id, image_id, position)
|
||||
VALUES (?1, ?2, ?3)
|
||||
ON CONFLICT(album_id, image_id) DO NOTHING",
|
||||
params![album_id, image_id, next_position],
|
||||
)?;
|
||||
if changed > 0 {
|
||||
next_position += 1;
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE albums SET updated_at = datetime('now') WHERE id = ?1",
|
||||
[album_id],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
pub fn remove_images_from_album(conn: &Connection, album_id: i64, image_ids: &[i64]) -> Result<()> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
for image_id in image_ids {
|
||||
tx.execute(
|
||||
"DELETE FROM album_images WHERE album_id = ?1 AND image_id = ?2",
|
||||
params![album_id, image_id],
|
||||
)?;
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE albums SET updated_at = datetime('now') WHERE id = ?1",
|
||||
[album_id],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn count_album_images(conn: &Connection, album_id: i64) -> Result<i64> {
|
||||
let count = conn.query_row(
|
||||
"SELECT COUNT(*) FROM album_images WHERE album_id = ?1",
|
||||
[album_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub fn get_album_images(
|
||||
conn: &Connection,
|
||||
album_id: i64,
|
||||
sort: &str,
|
||||
offset: i64,
|
||||
limit: i64,
|
||||
) -> Result<Vec<ImageRecord>> {
|
||||
// Default to curated order (album_images.position); otherwise honor the same
|
||||
// sort vocabulary as get_images. Albums span folders, so no folder filter.
|
||||
let order = match sort {
|
||||
"name_asc" => "i.filename ASC",
|
||||
"name_desc" => "i.filename DESC",
|
||||
"date_asc" => "i.modified_at ASC NULLS LAST",
|
||||
"date_desc" => "i.modified_at DESC NULLS LAST",
|
||||
"size_asc" => "i.file_size ASC",
|
||||
"size_desc" => "i.file_size DESC",
|
||||
"rating_asc" => "i.rating ASC, i.modified_at DESC NULLS LAST",
|
||||
"rating_desc" => "i.rating DESC, i.modified_at DESC NULLS LAST",
|
||||
"duration_asc" => "i.duration_ms ASC NULLS LAST",
|
||||
"duration_desc" => "i.duration_ms DESC NULLS LAST",
|
||||
"taken_asc" => "COALESCE(i.taken_at, i.modified_at) ASC NULLS LAST",
|
||||
"taken_desc" => "COALESCE(i.taken_at, i.modified_at) DESC NULLS LAST",
|
||||
_ => "ai.position ASC",
|
||||
};
|
||||
let sql = format!(
|
||||
"SELECT i.id, i.folder_id, i.path, i.filename, i.thumbnail_path, i.width, i.height, i.file_size, i.created_at, i.modified_at, i.taken_at, i.mime_type,
|
||||
i.media_kind, i.duration_ms, i.video_codec, i.audio_codec, i.metadata_updated_at, i.metadata_error,
|
||||
i.favorite, i.rating, i.embedding_status, i.embedding_model, i.embedding_updated_at, i.embedding_error,
|
||||
i.generated_caption, i.caption_model, i.caption_updated_at, i.caption_error,
|
||||
i.ai_rating, i.ai_tagger_model, i.ai_tagged_at, i.ai_tagger_error
|
||||
FROM images i
|
||||
JOIN album_images ai ON ai.image_id = i.id
|
||||
WHERE ai.album_id = ?1
|
||||
ORDER BY {order}
|
||||
LIMIT ?2 OFFSET ?3"
|
||||
);
|
||||
let mut stmt = conn.prepare(&sql)?;
|
||||
let rows = stmt.query_map(params![album_id, limit, offset], map_image_row)?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
// ── Bulk image operations ──────────────────────────────────────────────────────
|
||||
|
||||
/// Apply favorite and/or rating to many images at once; returns the updated rows.
|
||||
pub fn bulk_update_details(
|
||||
conn: &Connection,
|
||||
image_ids: &[i64],
|
||||
favorite: Option<bool>,
|
||||
rating: Option<i64>,
|
||||
) -> Result<Vec<ImageRecord>> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
for image_id in image_ids {
|
||||
tx.execute(
|
||||
"UPDATE images
|
||||
SET favorite = COALESCE(?2, favorite),
|
||||
rating = COALESCE(?3, rating)
|
||||
WHERE id = ?1",
|
||||
params![image_id, favorite, rating],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
get_images_by_ids(conn, image_ids)
|
||||
}
|
||||
|
||||
/// Add one or more user tags to many images at once.
|
||||
pub fn bulk_add_tags(conn: &Connection, image_ids: &[i64], tags: &[String]) -> Result<()> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
for image_id in image_ids {
|
||||
for tag in tags {
|
||||
let trimmed = tag.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO image_tags (image_id, tag, source, ai_model, confidence, created_at)
|
||||
VALUES (?1, ?2, 'user', NULL, NULL, datetime('now'))
|
||||
ON CONFLICT(image_id, tag) DO UPDATE SET
|
||||
source = 'user',
|
||||
ai_model = NULL,
|
||||
confidence = NULL
|
||||
WHERE source = 'ai'",
|
||||
params![image_id, trimmed],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a tag (by name) from many images at once.
|
||||
pub fn bulk_remove_tag_by_name(conn: &Connection, image_ids: &[i64], tag: &str) -> Result<()> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
for image_id in image_ids {
|
||||
tx.execute(
|
||||
"DELETE FROM image_tags WHERE image_id = ?1 AND tag = ?2",
|
||||
params![image_id, tag],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ── Color palettes (color search) ──────────────────────────────────────────────
|
||||
|
||||
/// Replace an image's stored color palette. `colors` is `(r, g, b, weight)`.
|
||||
pub fn replace_image_colors(
|
||||
conn: &Connection,
|
||||
image_id: i64,
|
||||
colors: &[(u8, u8, u8, f32)],
|
||||
) -> Result<()> {
|
||||
conn.execute("DELETE FROM image_colors WHERE image_id = ?1", [image_id])?;
|
||||
for (idx, (r, g, b, weight)) in colors.iter().enumerate() {
|
||||
conn.execute(
|
||||
"INSERT INTO image_colors (image_id, idx, r, g, b, weight)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
|
||||
params![
|
||||
image_id,
|
||||
idx as i64,
|
||||
*r as i64,
|
||||
*g as i64,
|
||||
*b as i64,
|
||||
*weight as f64
|
||||
],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Images (with thumbnails) that have no stored palette yet — the backfill set.
|
||||
/// Returns `(image_id, thumbnail_path)`.
|
||||
pub fn get_images_missing_colors(conn: &Connection, limit: i64) -> Result<Vec<(i64, String)>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT i.id, i.thumbnail_path
|
||||
FROM images i
|
||||
WHERE i.media_kind = 'image'
|
||||
AND i.thumbnail_path IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM image_colors c WHERE c.image_id = i.id)
|
||||
LIMIT ?1",
|
||||
)?;
|
||||
let rows = stmt.query_map([limit], |row| {
|
||||
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
/// Count of images still awaiting palette extraction (for backfill progress).
|
||||
pub fn count_images_missing_colors(conn: &Connection) -> Result<i64> {
|
||||
let count = conn.query_row(
|
||||
"SELECT COUNT(*)
|
||||
FROM images i
|
||||
WHERE i.media_kind = 'image'
|
||||
AND i.thumbnail_path IS NOT NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM image_colors c WHERE c.image_id = i.id)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub fn repair_deferred_embedding_jobs(conn: &Connection) -> Result<usize> {
|
||||
let pattern = "No thumbnail available yet for%";
|
||||
let repaired = conn.execute(
|
||||
@@ -1713,6 +2106,7 @@ pub fn get_images(
|
||||
rating_min: i64,
|
||||
embedding_failed_only: bool,
|
||||
tagging_failed_only: bool,
|
||||
color: Option<(u8, u8, u8)>,
|
||||
sort: &str,
|
||||
offset: i64,
|
||||
limit: i64,
|
||||
@@ -1737,6 +2131,10 @@ pub fn get_images(
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let embedding_failed_flag = i64::from(embedding_failed_only);
|
||||
let tagging_failed_flag = i64::from(tagging_failed_only);
|
||||
let (color_flag, qr, qg, qb) = match color {
|
||||
Some((r, g, b)) => (1i64, r as i64, g as i64, b as i64),
|
||||
None => (0, 0, 0, 0),
|
||||
};
|
||||
let sql = format!(
|
||||
"SELECT id, folder_id, path, filename, thumbnail_path, width, height, file_size, created_at, modified_at, taken_at, mime_type,
|
||||
media_kind, duration_ms, video_codec, audio_codec, metadata_updated_at, metadata_error,
|
||||
@@ -1751,6 +2149,12 @@ pub fn get_images(
|
||||
AND rating >= ?5
|
||||
AND (?6 = 0 OR embedding_status = 'failed')
|
||||
AND (?7 = 0 OR ai_tagger_error IS NOT NULL)
|
||||
AND (?10 = 0 OR EXISTS (
|
||||
SELECT 1 FROM image_colors c
|
||||
WHERE c.image_id = images.id
|
||||
AND c.weight >= ?15
|
||||
AND ((c.r - ?11)*(c.r - ?11) + (c.g - ?12)*(c.g - ?12) + (c.b - ?13)*(c.b - ?13)) <= ?14
|
||||
))
|
||||
ORDER BY {order}
|
||||
LIMIT ?8 OFFSET ?9"
|
||||
);
|
||||
@@ -1765,7 +2169,13 @@ pub fn get_images(
|
||||
embedding_failed_flag,
|
||||
tagging_failed_flag,
|
||||
limit,
|
||||
offset
|
||||
offset,
|
||||
color_flag,
|
||||
qr,
|
||||
qg,
|
||||
qb,
|
||||
crate::color::MATCH_DISTANCE_SQ,
|
||||
crate::color::MATCH_MIN_WEIGHT
|
||||
],
|
||||
map_image_row,
|
||||
)?;
|
||||
@@ -1782,12 +2192,17 @@ pub fn count_images(
|
||||
rating_min: i64,
|
||||
embedding_failed_only: bool,
|
||||
tagging_failed_only: bool,
|
||||
color: Option<(u8, u8, u8)>,
|
||||
) -> Result<i64> {
|
||||
let search_pattern = search.map(|value| format!("%{value}%"));
|
||||
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let embedding_failed_flag = i64::from(embedding_failed_only);
|
||||
let tagging_failed_flag = i64::from(tagging_failed_only);
|
||||
let (color_flag, qr, qg, qb) = match color {
|
||||
Some((r, g, b)) => (1i64, r as i64, g as i64, b as i64),
|
||||
None => (0, 0, 0, 0),
|
||||
};
|
||||
let count = conn.query_row(
|
||||
"SELECT COUNT(*) FROM images
|
||||
WHERE (?1 IS NULL OR folder_id = ?1)
|
||||
@@ -1796,7 +2211,13 @@ pub fn count_images(
|
||||
AND (?4 = 0 OR favorite = 1)
|
||||
AND rating >= ?5
|
||||
AND (?6 = 0 OR embedding_status = 'failed')
|
||||
AND (?7 = 0 OR ai_tagger_error IS NOT NULL)",
|
||||
AND (?7 = 0 OR ai_tagger_error IS NOT NULL)
|
||||
AND (?8 = 0 OR EXISTS (
|
||||
SELECT 1 FROM image_colors c
|
||||
WHERE c.image_id = images.id
|
||||
AND c.weight >= ?13
|
||||
AND ((c.r - ?9)*(c.r - ?9) + (c.g - ?10)*(c.g - ?10) + (c.b - ?11)*(c.b - ?11)) <= ?12
|
||||
))",
|
||||
params![
|
||||
folder_id,
|
||||
search_pattern,
|
||||
@@ -1804,7 +2225,13 @@ pub fn count_images(
|
||||
favorites_flag,
|
||||
rating_min,
|
||||
embedding_failed_flag,
|
||||
tagging_failed_flag
|
||||
tagging_failed_flag,
|
||||
color_flag,
|
||||
qr,
|
||||
qg,
|
||||
qb,
|
||||
crate::color::MATCH_DISTANCE_SQ,
|
||||
crate::color::MATCH_MIN_WEIGHT
|
||||
],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
@@ -1820,6 +2247,7 @@ pub fn search_images_by_tag(
|
||||
media_kind: Option<&str>,
|
||||
favorites_only: bool,
|
||||
rating_min: i64,
|
||||
color: Option<(u8, u8, u8)>,
|
||||
limit: usize,
|
||||
offset: usize,
|
||||
) -> Result<(Vec<ImageRecord>, usize)> {
|
||||
@@ -1828,6 +2256,10 @@ pub fn search_images_by_tag(
|
||||
return Ok((Vec::new(), 0));
|
||||
}
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let (color_flag, qr, qg, qb) = match color {
|
||||
Some((r, g, b)) => (1i64, r as i64, g as i64, b as i64),
|
||||
None => (0, 0, 0, 0),
|
||||
};
|
||||
|
||||
// Total count (for pagination)
|
||||
let total: usize = conn.query_row(
|
||||
@@ -1838,13 +2270,25 @@ pub fn search_images_by_tag(
|
||||
AND (?2 IS NULL OR i.media_kind = ?2)
|
||||
AND (?3 = 0 OR i.favorite = 1)
|
||||
AND i.rating >= ?4
|
||||
AND LOWER(TRIM(t.tag)) = ?5",
|
||||
AND LOWER(TRIM(t.tag)) = ?5
|
||||
AND (?6 = 0 OR EXISTS (
|
||||
SELECT 1 FROM image_colors c
|
||||
WHERE c.image_id = i.id
|
||||
AND c.weight >= ?11
|
||||
AND ((c.r - ?7)*(c.r - ?7) + (c.g - ?8)*(c.g - ?8) + (c.b - ?9)*(c.b - ?9)) <= ?10
|
||||
))",
|
||||
params![
|
||||
folder_id,
|
||||
media_kind,
|
||||
favorites_flag,
|
||||
rating_min,
|
||||
normalized_query
|
||||
normalized_query,
|
||||
color_flag,
|
||||
qr,
|
||||
qg,
|
||||
qb,
|
||||
crate::color::MATCH_DISTANCE_SQ,
|
||||
crate::color::MATCH_MIN_WEIGHT
|
||||
],
|
||||
|row| row.get::<_, i64>(0),
|
||||
)? as usize;
|
||||
@@ -1858,8 +2302,14 @@ pub fn search_images_by_tag(
|
||||
AND (?3 = 0 OR i.favorite = 1)
|
||||
AND i.rating >= ?4
|
||||
AND LOWER(TRIM(t.tag)) = ?5
|
||||
AND (?6 = 0 OR EXISTS (
|
||||
SELECT 1 FROM image_colors c
|
||||
WHERE c.image_id = i.id
|
||||
AND c.weight >= ?11
|
||||
AND ((c.r - ?7)*(c.r - ?7) + (c.g - ?8)*(c.g - ?8) + (c.b - ?9)*(c.b - ?9)) <= ?10
|
||||
))
|
||||
ORDER BY i.rating DESC, i.modified_at DESC NULLS LAST, i.filename ASC
|
||||
LIMIT ?6 OFFSET ?7",
|
||||
LIMIT ?12 OFFSET ?13",
|
||||
)?;
|
||||
|
||||
let image_ids = stmt
|
||||
@@ -1870,6 +2320,12 @@ pub fn search_images_by_tag(
|
||||
favorites_flag,
|
||||
rating_min,
|
||||
normalized_query,
|
||||
color_flag,
|
||||
qr,
|
||||
qg,
|
||||
qb,
|
||||
crate::color::MATCH_DISTANCE_SQ,
|
||||
crate::color::MATCH_MIN_WEIGHT,
|
||||
limit as i64,
|
||||
offset as i64
|
||||
],
|
||||
@@ -1888,7 +2344,9 @@ pub fn search_tags_autocomplete(
|
||||
) -> Result<Vec<ExploreTagEntry>> {
|
||||
let pattern = format!("%{}%", query.to_lowercase());
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT t.tag, COUNT(DISTINCT t.image_id) AS tag_count, MIN(t.image_id) AS representative_image_id
|
||||
"SELECT t.tag, COUNT(DISTINCT t.image_id) AS tag_count, MIN(t.image_id) AS representative_image_id,
|
||||
MAX(CASE WHEN t.source = 'ai' THEN 1 ELSE 0 END) AS has_ai_source,
|
||||
MAX(CASE WHEN t.source = 'user' THEN 1 ELSE 0 END) AS has_user_source
|
||||
FROM image_tags t
|
||||
JOIN images i ON i.id = t.image_id
|
||||
WHERE (?1 IS NULL OR i.folder_id = ?1)
|
||||
@@ -1904,6 +2362,8 @@ pub fn search_tags_autocomplete(
|
||||
count: row.get(1)?,
|
||||
representative_image_id: row.get(2)?,
|
||||
thumbnail_path: None, // skip per-suggestion thumbnail for speed
|
||||
has_ai_source: row.get::<_, i64>(3)? != 0,
|
||||
has_user_source: row.get::<_, i64>(4)? != 0,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
@@ -1987,28 +2447,42 @@ pub fn get_explore_tags(
|
||||
limit: usize,
|
||||
) -> Result<Vec<ExploreTagEntry>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT t.tag, COUNT(DISTINCT t.image_id) AS tag_count, MIN(t.image_id) AS representative_image_id
|
||||
FROM image_tags t
|
||||
JOIN images i ON i.id = t.image_id
|
||||
WHERE (?1 IS NULL OR i.folder_id = ?1)
|
||||
GROUP BY t.tag
|
||||
HAVING COUNT(DISTINCT t.image_id) >= 1
|
||||
ORDER BY tag_count DESC, t.tag ASC
|
||||
LIMIT ?2",
|
||||
"WITH tag_counts AS (
|
||||
SELECT t.tag,
|
||||
COUNT(DISTINCT t.image_id) AS tag_count,
|
||||
MIN(t.image_id) AS representative_image_id,
|
||||
MAX(CASE WHEN t.source = 'ai' THEN 1 ELSE 0 END) AS has_ai_source,
|
||||
MAX(CASE WHEN t.source = 'user' THEN 1 ELSE 0 END) AS has_user_source
|
||||
FROM image_tags t
|
||||
JOIN images i ON i.id = t.image_id
|
||||
WHERE (?1 IS NULL OR i.folder_id = ?1)
|
||||
GROUP BY t.tag
|
||||
HAVING COUNT(DISTINCT t.image_id) >= 1
|
||||
ORDER BY tag_count DESC, t.tag ASC
|
||||
LIMIT ?2
|
||||
)
|
||||
SELECT c.tag,
|
||||
c.tag_count,
|
||||
c.representative_image_id,
|
||||
i.thumbnail_path,
|
||||
c.has_ai_source,
|
||||
c.has_user_source
|
||||
FROM tag_counts c
|
||||
JOIN images i ON i.id = c.representative_image_id
|
||||
ORDER BY c.tag_count DESC, c.tag ASC",
|
||||
)?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map(params![folder_id, limit as i64], |row| {
|
||||
let representative_image_id = row.get::<_, i64>(2)?;
|
||||
let thumbnail_path = get_image_by_id(conn, representative_image_id)
|
||||
.ok()
|
||||
.and_then(|image| image.thumbnail_path);
|
||||
|
||||
Ok(ExploreTagEntry {
|
||||
tag: row.get(0)?,
|
||||
count: row.get(1)?,
|
||||
representative_image_id,
|
||||
thumbnail_path,
|
||||
thumbnail_path: row.get(3)?,
|
||||
has_ai_source: row.get::<_, i64>(4)? != 0,
|
||||
has_user_source: row.get::<_, i64>(5)? != 0,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
@@ -2016,6 +2490,34 @@ pub fn get_explore_tags(
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
pub fn get_related_tags(
|
||||
conn: &Connection,
|
||||
tag: &str,
|
||||
folder_id: Option<i64>,
|
||||
limit: usize,
|
||||
) -> Result<Vec<(String, i64)>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT other.tag, COUNT(DISTINCT other.image_id) AS shared_count
|
||||
FROM image_tags base
|
||||
JOIN image_tags other ON other.image_id = base.image_id
|
||||
JOIN images i ON i.id = base.image_id
|
||||
WHERE base.tag = ?1
|
||||
AND other.tag != base.tag
|
||||
AND (?2 IS NULL OR i.folder_id = ?2)
|
||||
GROUP BY other.tag
|
||||
ORDER BY shared_count DESC, other.tag ASC
|
||||
LIMIT ?3",
|
||||
)?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map(params![tag, folder_id, limit as i64], |row| {
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
type FailedEmbeddingRow = (i64, String, String, Option<String>);
|
||||
|
||||
pub fn get_failed_embedding_images(
|
||||
@@ -2338,6 +2840,139 @@ pub fn remove_tag(conn: &Connection, tag_id: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rename a tag across the whole library, or merge it into an existing tag when
|
||||
/// `to` already exists. Images that already carry `to` keep a single instance
|
||||
/// (the colliding source row is dropped).
|
||||
pub fn rename_tag(conn: &Connection, from: &str, to: &str) -> Result<()> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
// Move rows where the target tag isn't already on that image; UNIQUE
|
||||
// collisions are skipped (OR IGNORE)…
|
||||
tx.execute(
|
||||
"UPDATE OR IGNORE image_tags SET tag = ?2 WHERE tag = ?1",
|
||||
params![from, to],
|
||||
)?;
|
||||
// …then drop the now-duplicate leftovers still under the old name.
|
||||
tx.execute("DELETE FROM image_tags WHERE tag = ?1", params![from])?;
|
||||
// The visual-cluster cache keys on image-id hashes, not tag text, so a rename
|
||||
// wouldn't invalidate it automatically — clear it.
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete a tag from every image in the library. Returns the number of rows removed.
|
||||
pub fn delete_tag(conn: &Connection, name: &str) -> Result<i64> {
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
let removed = tx.execute("DELETE FROM image_tags WHERE tag = ?1", params![name])? as i64;
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn reset_ai_tags(conn: &Connection, folder_id: Option<i64>) -> Result<usize> {
|
||||
let image_ids = match folder_id {
|
||||
Some(folder_id) => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT DISTINCT i.id
|
||||
FROM images i
|
||||
LEFT JOIN image_tags t ON t.image_id = i.id AND t.source = 'ai'
|
||||
LEFT JOIN tagging_jobs j ON j.image_id = i.id
|
||||
WHERE i.folder_id = ?1
|
||||
AND i.media_kind = 'image'
|
||||
AND (
|
||||
t.id IS NOT NULL
|
||||
OR i.ai_rating IS NOT NULL
|
||||
OR i.ai_tagger_model IS NOT NULL
|
||||
OR i.ai_tagged_at IS NOT NULL
|
||||
OR i.ai_tagger_error IS NOT NULL
|
||||
OR j.image_id IS NOT NULL
|
||||
)",
|
||||
)?;
|
||||
let rows = stmt.query_map([folder_id], |row| row.get::<_, i64>(0))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
}
|
||||
None => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT DISTINCT i.id
|
||||
FROM images i
|
||||
LEFT JOIN image_tags t ON t.image_id = i.id AND t.source = 'ai'
|
||||
LEFT JOIN tagging_jobs j ON j.image_id = i.id
|
||||
WHERE i.media_kind = 'image'
|
||||
AND (
|
||||
t.id IS NOT NULL
|
||||
OR i.ai_rating IS NOT NULL
|
||||
OR i.ai_tagger_model IS NOT NULL
|
||||
OR i.ai_tagged_at IS NOT NULL
|
||||
OR i.ai_tagger_error IS NOT NULL
|
||||
OR j.image_id IS NOT NULL
|
||||
)",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| row.get::<_, i64>(0))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
}
|
||||
};
|
||||
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
match folder_id {
|
||||
Some(folder_id) => {
|
||||
tx.execute(
|
||||
"DELETE FROM image_tags
|
||||
WHERE source = 'ai'
|
||||
AND image_id IN (SELECT id FROM images WHERE folder_id = ?1)",
|
||||
[folder_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE images
|
||||
SET ai_rating = NULL,
|
||||
ai_tagger_model = NULL,
|
||||
ai_tagged_at = NULL,
|
||||
ai_tagger_error = NULL
|
||||
WHERE folder_id = ?1
|
||||
AND media_kind = 'image'",
|
||||
[folder_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE tagging_jobs
|
||||
SET status = 'cancelled', last_error = NULL, updated_at = datetime('now')
|
||||
WHERE status = 'processing'
|
||||
AND image_id IN (SELECT id FROM images WHERE folder_id = ?1)",
|
||||
[folder_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"DELETE FROM tagging_jobs
|
||||
WHERE status NOT IN ('processing', 'cancelled')
|
||||
AND image_id IN (SELECT id FROM images WHERE folder_id = ?1)",
|
||||
[folder_id],
|
||||
)?;
|
||||
}
|
||||
None => {
|
||||
tx.execute("DELETE FROM image_tags WHERE source = 'ai'", [])?;
|
||||
tx.execute(
|
||||
"UPDATE images
|
||||
SET ai_rating = NULL,
|
||||
ai_tagger_model = NULL,
|
||||
ai_tagged_at = NULL,
|
||||
ai_tagger_error = NULL
|
||||
WHERE media_kind = 'image'",
|
||||
[],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE tagging_jobs
|
||||
SET status = 'cancelled', last_error = NULL, updated_at = datetime('now')
|
||||
WHERE status = 'processing'",
|
||||
[],
|
||||
)?;
|
||||
tx.execute(
|
||||
"DELETE FROM tagging_jobs WHERE status NOT IN ('processing', 'cancelled')",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
Ok(image_ids.len())
|
||||
}
|
||||
|
||||
pub fn enqueue_missing_tagging_jobs_for_folder(conn: &Connection, folder_id: i64) -> Result<usize> {
|
||||
let inserted = conn.execute(
|
||||
"INSERT INTO tagging_jobs (image_id, status, attempts, last_error, created_at, updated_at)
|
||||
@@ -2506,14 +3141,14 @@ fn map_image_row(row: &Row<'_>) -> rusqlite::Result<ImageRecord> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns cached tag-cloud entries if the stored hash matches `current_hash`.
|
||||
pub fn get_tag_cloud_cache(
|
||||
/// Returns cached visual-cluster entries if the stored hash matches `current_hash`.
|
||||
pub fn get_visual_cluster_cache(
|
||||
conn: &Connection,
|
||||
folder_scope: &str,
|
||||
current_hash: u64,
|
||||
) -> Result<Option<String>> {
|
||||
let result: rusqlite::Result<(i64, String)> = conn.query_row(
|
||||
"SELECT image_ids_hash, entries_json FROM tag_cloud_cache WHERE folder_scope = ?1",
|
||||
"SELECT image_ids_hash, entries_json FROM visual_cluster_cache WHERE folder_scope = ?1",
|
||||
params![folder_scope],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
);
|
||||
@@ -2525,15 +3160,15 @@ pub fn get_tag_cloud_cache(
|
||||
}
|
||||
}
|
||||
|
||||
/// Upserts the tag-cloud cache for the given scope.
|
||||
pub fn set_tag_cloud_cache(
|
||||
/// Upserts the visual-cluster cache for the given scope.
|
||||
pub fn set_visual_cluster_cache(
|
||||
conn: &Connection,
|
||||
folder_scope: &str,
|
||||
image_ids_hash: u64,
|
||||
entries_json: &str,
|
||||
) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT INTO tag_cloud_cache (folder_scope, image_ids_hash, entries_json, created_at)
|
||||
"INSERT INTO visual_cluster_cache (folder_scope, image_ids_hash, entries_json, created_at)
|
||||
VALUES (?1, ?2, ?3, datetime('now'))
|
||||
ON CONFLICT(folder_scope) DO UPDATE SET
|
||||
image_ids_hash = excluded.image_ids_hash,
|
||||
|
||||
@@ -92,6 +92,7 @@ pub fn find_similar_image_matches(
|
||||
conn: &Connection,
|
||||
image_id: i64,
|
||||
folder_id: Option<i64>,
|
||||
album_id: Option<i64>,
|
||||
threshold: f32,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
@@ -103,10 +104,17 @@ pub fn find_similar_image_matches(
|
||||
None => return Ok(Vec::new()),
|
||||
};
|
||||
|
||||
// Fetch folder image IDs *before* acquiring the read lock so we don't hold
|
||||
// Build the allowed-id set *before* acquiring the read lock so we don't hold
|
||||
// the lock across a potentially slow SQLite query, which would delay any
|
||||
// concurrent ensure_index call waiting for a write lock.
|
||||
let folder_image_ids: Option<Vec<i64>> = if let Some(folder_id) = folder_id {
|
||||
// concurrent ensure_index call waiting for a write lock. Album scope takes
|
||||
// precedence over folder scope; both reuse the HNSW filtered search.
|
||||
let allowed_image_ids: Option<Vec<i64>> = if let Some(album_id) = album_id {
|
||||
let mut stmt = conn.prepare("SELECT image_id FROM album_images WHERE album_id = ?1")?;
|
||||
let ids = stmt
|
||||
.query_map([album_id], |row| row.get::<_, i64>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Some(ids)
|
||||
} else if let Some(folder_id) = folder_id {
|
||||
let ids = vector::get_all_image_embeddings_with_ids(conn, Some(folder_id))?
|
||||
.into_iter()
|
||||
.map(|(id, _)| id)
|
||||
@@ -122,7 +130,7 @@ pub fn find_similar_image_matches(
|
||||
};
|
||||
|
||||
let knbn = (offset + limit).max(limit).saturating_add(32);
|
||||
let neighbours: Vec<Neighbour> = if let Some(image_ids) = folder_image_ids {
|
||||
let neighbours: Vec<Neighbour> = if let Some(image_ids) = allowed_image_ids {
|
||||
let mut allowed_ids = image_ids
|
||||
.into_iter()
|
||||
.filter_map(|allowed_image_id| {
|
||||
|
||||
@@ -3,18 +3,18 @@ use crate::db::{self, DbPool, EmbeddingJob, FolderJobProgress, ImageRecord, Inde
|
||||
use crate::embedder::{embedding_source_path, ClipImageEmbedder};
|
||||
use crate::media::{probe_video_metadata, MediaTools};
|
||||
use crate::storage::{detect_storage_profile, RuntimeAdaptiveProfile, StorageProfile};
|
||||
use crate::tagger::{self, WdTagger};
|
||||
use crate::tagger::{self, Tagger};
|
||||
use crate::thumbnail;
|
||||
use crate::vector;
|
||||
use anyhow::Result;
|
||||
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
|
||||
use rayon::prelude::*;
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
const IMAGE_EXTENSIONS: &[&str] = &[
|
||||
@@ -41,6 +41,14 @@ struct PausedWorkerFolders {
|
||||
tagging: HashSet<i64>,
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct PersistedPausedWorkerFolders {
|
||||
pub thumbnail: Vec<i64>,
|
||||
pub metadata: Vec<i64>,
|
||||
pub embedding: Vec<i64>,
|
||||
pub tagging: Vec<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct FolderWorkerPausedState {
|
||||
pub thumbnail: bool,
|
||||
@@ -50,6 +58,41 @@ pub struct FolderWorkerPausedState {
|
||||
pub tagging: bool,
|
||||
}
|
||||
|
||||
pub fn replace_worker_paused_states(states: PersistedPausedWorkerFolders) {
|
||||
if let Ok(mut paused_folders) = PAUSED_WORKER_FOLDERS
|
||||
.get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
|
||||
.lock()
|
||||
{
|
||||
paused_folders.thumbnail = states.thumbnail.into_iter().collect();
|
||||
paused_folders.metadata = states.metadata.into_iter().collect();
|
||||
paused_folders.embedding = states.embedding.into_iter().collect();
|
||||
paused_folders.caption = HashSet::new();
|
||||
paused_folders.tagging = states.tagging.into_iter().collect();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot_worker_paused_states() -> PersistedPausedWorkerFolders {
|
||||
let Ok(paused_folders) = PAUSED_WORKER_FOLDERS
|
||||
.get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
|
||||
.lock()
|
||||
else {
|
||||
return PersistedPausedWorkerFolders::default();
|
||||
};
|
||||
|
||||
let sorted = |set: &HashSet<i64>| {
|
||||
let mut ids = set.iter().copied().collect::<Vec<_>>();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
};
|
||||
|
||||
PersistedPausedWorkerFolders {
|
||||
thumbnail: sorted(&paused_folders.thumbnail),
|
||||
metadata: sorted(&paused_folders.metadata),
|
||||
embedding: sorted(&paused_folders.embedding),
|
||||
tagging: sorted(&paused_folders.tagging),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_worker_paused(worker: &str, folder_id: i64, paused: bool) {
|
||||
if let Ok(mut paused_folders) = PAUSED_WORKER_FOLDERS
|
||||
.get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
|
||||
@@ -190,6 +233,13 @@ pub struct MediaUpdateBatch {
|
||||
pub images: Vec<ImageRecord>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct ColorBackfillProgress {
|
||||
pub processed: i64,
|
||||
pub total: i64,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct MediaJobProgressEvent {
|
||||
pub progress: Vec<FolderJobProgress>,
|
||||
@@ -323,7 +373,7 @@ pub fn start_caption_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf)
|
||||
|
||||
pub fn start_tagging_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf) {
|
||||
std::thread::spawn(move || {
|
||||
let mut tagger_instance: Option<WdTagger> = None;
|
||||
let mut tagger_instance: Option<Box<dyn Tagger>> = None;
|
||||
log::info!("Tagging worker started.");
|
||||
loop {
|
||||
// If the acceleration setting changed, drop the cached session so
|
||||
@@ -347,7 +397,51 @@ pub fn start_tagging_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf)
|
||||
});
|
||||
}
|
||||
|
||||
/// True when `path` lives inside Phokus's own app-data directory (thumbnail
|
||||
/// cache, database, downloaded models). If a user indexes an ancestor of this
|
||||
/// directory — e.g. their whole `Users` folder — the app would otherwise index
|
||||
/// its own thumbnails, generate thumbnails of those thumbnails, and loop
|
||||
/// forever. The whole subtree is pruned from folder scans and ignored by the
|
||||
/// watcher to break that cycle.
|
||||
///
|
||||
/// Comparison is component-aware (so a sibling like `…/phokus-backup` never
|
||||
/// matches) and case-insensitive on Windows — the indexed root may report a
|
||||
/// different casing than `app_data_dir` (e.g. `c:\users\…` vs `C:\Users\…`),
|
||||
/// and a case-sensitive prefix check there would silently let the loop back in.
|
||||
fn is_within_app_data(path: &Path, app_data_dir: Option<&Path>) -> bool {
|
||||
let Some(dir) = app_data_dir else {
|
||||
return false;
|
||||
};
|
||||
let mut base = dir.components();
|
||||
let mut target = path.components();
|
||||
loop {
|
||||
let Some(base_component) = base.next() else {
|
||||
// Consumed every component of the app-data dir while still matching →
|
||||
// `path` is the app-data dir itself or a descendant.
|
||||
return true;
|
||||
};
|
||||
let Some(target_component) = target.next() else {
|
||||
// `path` is shorter than the app-data dir, so it cannot be inside it.
|
||||
return false;
|
||||
};
|
||||
let matches = if cfg!(windows) {
|
||||
base_component
|
||||
.as_os_str()
|
||||
.eq_ignore_ascii_case(target_component.as_os_str())
|
||||
} else {
|
||||
base_component == target_component
|
||||
};
|
||||
if !matches {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn do_index(app: AppHandle, pool: &DbPool, folder_id: i64, folder_path: PathBuf) -> Result<()> {
|
||||
// Resolve our own app-data directory so the walk can skip it (see
|
||||
// `is_within_app_data`). Resolution failure is non-fatal — we just lose the
|
||||
// guard, which only matters when indexing an ancestor of the app data dir.
|
||||
let app_data_dir = app.path().app_data_dir().ok();
|
||||
let existing_entries = {
|
||||
let conn = pool.get()?;
|
||||
db::get_folder_media_index(&conn, folder_id)?
|
||||
@@ -364,6 +458,9 @@ fn do_index(app: AppHandle, pool: &DbPool, folder_id: i64, folder_path: PathBuf)
|
||||
let media_paths: Vec<PathBuf> = WalkDir::new(&folder_path)
|
||||
.follow_links(true)
|
||||
.into_iter()
|
||||
// Prune our own app-data subtree before descending into it, so we never
|
||||
// scan (and re-thumbnail) the thumbnail cache.
|
||||
.filter_entry(|entry| !is_within_app_data(entry.path(), app_data_dir.as_deref()))
|
||||
.filter_map(|entry| match entry {
|
||||
Ok(e) if e.file_type().is_file() && is_supported_media(e.path()) => {
|
||||
Some(e.path().to_path_buf())
|
||||
@@ -737,6 +834,13 @@ fn persist_thumbnail_results(
|
||||
width,
|
||||
height,
|
||||
)?);
|
||||
|
||||
// Store the dominant-color palette sampled during resizing.
|
||||
if let Some(thumb) = &generated {
|
||||
if !thumb.palette.is_empty() {
|
||||
db::replace_image_colors(&tx, image_id, &thumb.palette)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tx.commit()?;
|
||||
@@ -767,6 +871,76 @@ fn is_avif_path(path: &Path) -> bool {
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("avif"))
|
||||
}
|
||||
|
||||
/// One-shot background pass that samples a color palette from the (already
|
||||
/// generated) thumbnails of images indexed before color search existed. New
|
||||
/// images get their palette during thumbnail generation, so this only fills the
|
||||
/// historical gap. Emits `color-backfill-progress` so the UI can show a count.
|
||||
pub fn start_color_backfill(app: AppHandle, pool: DbPool) {
|
||||
std::thread::spawn(move || {
|
||||
let total = match pool.get() {
|
||||
Ok(conn) => db::count_images_missing_colors(&conn).unwrap_or(0),
|
||||
Err(_) => return,
|
||||
};
|
||||
if total == 0 {
|
||||
return;
|
||||
}
|
||||
log::info!("Color backfill: sampling palettes for {total} images.");
|
||||
|
||||
let mut processed: i64 = 0;
|
||||
loop {
|
||||
let batch = match pool.get() {
|
||||
Ok(conn) => db::get_images_missing_colors(&conn, 64).unwrap_or_default(),
|
||||
Err(_) => break,
|
||||
};
|
||||
if batch.is_empty() {
|
||||
break;
|
||||
}
|
||||
|
||||
for (image_id, thumbnail_path) in batch {
|
||||
let palette = crate::color::extract_palette_from_file(
|
||||
Path::new(&thumbnail_path),
|
||||
crate::color::PALETTE_SIZE,
|
||||
);
|
||||
let colors: Vec<(u8, u8, u8, f32)> = match palette {
|
||||
Some(colors) if !colors.is_empty() => colors
|
||||
.into_iter()
|
||||
.map(|c| (c.r, c.g, c.b, c.weight))
|
||||
.collect(),
|
||||
// Unreadable thumbnail: store a zero-weight sentinel so the
|
||||
// image isn't reprocessed forever (it just won't match).
|
||||
_ => vec![(0, 0, 0, 0.0)],
|
||||
};
|
||||
let _ = with_db_write_lock(|| {
|
||||
let conn = pool.get()?;
|
||||
db::replace_image_colors(&conn, image_id, &colors)
|
||||
});
|
||||
processed += 1;
|
||||
}
|
||||
|
||||
let _ = app.emit(
|
||||
"color-backfill-progress",
|
||||
ColorBackfillProgress {
|
||||
processed,
|
||||
total,
|
||||
done: false,
|
||||
},
|
||||
);
|
||||
// Yield so the backfill stays in the background under active use.
|
||||
std::thread::sleep(Duration::from_millis(15));
|
||||
}
|
||||
|
||||
log::info!("Color backfill complete: {processed} images sampled.");
|
||||
let _ = app.emit(
|
||||
"color-backfill-progress",
|
||||
ColorBackfillProgress {
|
||||
processed,
|
||||
total,
|
||||
done: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Returns `Ok(true)` if a batch was claimed and processed, `Ok(false)` if
|
||||
/// the queue was empty.
|
||||
fn process_metadata_batch(
|
||||
@@ -1105,7 +1279,7 @@ fn process_tagging_batch(
|
||||
app: &AppHandle,
|
||||
pool: &DbPool,
|
||||
app_data_dir: &Path,
|
||||
tagger_instance: &mut Option<WdTagger>,
|
||||
tagger_instance: &mut Option<Box<dyn Tagger>>,
|
||||
) -> Result<bool> {
|
||||
if !tagger::tagger_model_status(app_data_dir).ready {
|
||||
return Ok(false);
|
||||
@@ -1117,20 +1291,23 @@ fn process_tagging_batch(
|
||||
|
||||
// Exclude actively-indexing folders for the same reason as the other
|
||||
// workers: don't compete with a running scan.
|
||||
let batch_started_at = Instant::now();
|
||||
let mut excluded_folders = paused_folder_ids("tagging");
|
||||
excluded_folders.extend(active_indexing_folders());
|
||||
let batch_size = crate::tagger::tagger_batch_size(app_data_dir);
|
||||
let claim_started_at = Instant::now();
|
||||
let jobs = with_db_write_lock(|| {
|
||||
let mut conn = pool.get()?;
|
||||
db::claim_tagging_jobs(&mut conn, &excluded_folders, batch_size)
|
||||
})?;
|
||||
let claim_elapsed = claim_started_at.elapsed();
|
||||
|
||||
if jobs.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
if tagger_instance.is_none() {
|
||||
match WdTagger::new(app_data_dir) {
|
||||
match tagger::create_active_tagger(app_data_dir) {
|
||||
Ok(model) => *tagger_instance = Some(model),
|
||||
Err(error) => {
|
||||
with_db_write_lock(|| {
|
||||
@@ -1157,21 +1334,45 @@ fn process_tagging_batch(
|
||||
.as_mut()
|
||||
.expect("tagger should be initialized before tagging batch processing");
|
||||
|
||||
let tag_results = jobs
|
||||
// Resolve each job's source image (AVIF can't be decoded directly, so it
|
||||
// falls back to its thumbnail), then tag the batch in small chunks (below).
|
||||
let source_paths: Vec<PathBuf> = jobs
|
||||
.iter()
|
||||
.map(|job| {
|
||||
let source_path = if is_avif_path(Path::new(&job.path)) {
|
||||
job.thumbnail_path.as_deref().unwrap_or(&job.path)
|
||||
if is_avif_path(Path::new(&job.path)) {
|
||||
PathBuf::from(job.thumbnail_path.as_deref().unwrap_or(&job.path))
|
||||
} else {
|
||||
&job.path
|
||||
};
|
||||
(
|
||||
job.clone(),
|
||||
tagger_ref.run(Path::new(source_path), tagger::DEFAULT_MAX_TAGS),
|
||||
)
|
||||
PathBuf::from(&job.path)
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
.collect();
|
||||
|
||||
// Tag in small micro-batches instead of one wide forward pass. On a shared
|
||||
// GPU every DirectML dispatch blocks the WebView2 compositor for its whole
|
||||
// duration, so a 16-wide batch freezes the UI for seconds; small chunks keep
|
||||
// each GPU lock short (and bound peak decode memory) while a brief yield
|
||||
// between them lets the UI and other workers grab the GPU/CPU. The model is
|
||||
// compute-bound here, so this costs almost no throughput.
|
||||
let infer_started_at = Instant::now();
|
||||
let mut outputs = Vec::with_capacity(source_paths.len());
|
||||
let mut chunks = source_paths.chunks(tagger::TAGGER_INFER_CHUNK).peekable();
|
||||
while let Some(chunk) = chunks.next() {
|
||||
outputs.extend(tagger_ref.run_batch(chunk, tagger::DEFAULT_MAX_TAGS));
|
||||
if chunks.peek().is_some() {
|
||||
std::thread::sleep(std::time::Duration::from_millis(
|
||||
tagger::TAGGER_INFER_YIELD_MS,
|
||||
));
|
||||
}
|
||||
}
|
||||
let infer_elapsed = infer_started_at.elapsed();
|
||||
|
||||
// Attribute the tags to the model that actually produced them, not a
|
||||
// hardcoded one (WD vs JoyTag are both possible).
|
||||
let tagger_model_name = tagger_ref.model_name();
|
||||
|
||||
let tag_results = jobs.iter().cloned().zip(outputs).collect::<Vec<_>>();
|
||||
|
||||
let write_started_at = Instant::now();
|
||||
let updated_images = with_db_write_lock(|| {
|
||||
let mut conn = pool.get()?;
|
||||
let tx = conn.transaction()?;
|
||||
@@ -1201,7 +1402,7 @@ fn process_tagging_batch(
|
||||
job.image_id,
|
||||
&tag_pairs,
|
||||
&output.rating,
|
||||
tagger::WD_TAGGER_MODEL_NAME,
|
||||
tagger_model_name,
|
||||
)?;
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -1223,6 +1424,7 @@ fn process_tagging_batch(
|
||||
db::requeue_tagging_jobs(&conn, &image_ids)
|
||||
});
|
||||
})?;
|
||||
let write_elapsed = write_started_at.elapsed();
|
||||
|
||||
if !updated_images.is_empty() {
|
||||
let folder_ids = updated_images
|
||||
@@ -1238,6 +1440,15 @@ fn process_tagging_batch(
|
||||
emit_folder_job_progress(app, pool, &folder_ids.into_iter().collect::<Vec<_>>(), true);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Tagging batch timing: {} items, claim {:?}, tag {:?}, write {:?}, total {:?}",
|
||||
jobs.len(),
|
||||
claim_elapsed,
|
||||
infer_elapsed,
|
||||
write_elapsed,
|
||||
batch_started_at.elapsed()
|
||||
);
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -1513,6 +1724,10 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
|
||||
|
||||
// Spawn the debounce loop on its own thread.
|
||||
let folder_map_thread = Arc::clone(&folder_map);
|
||||
// `thumb_dir` is `<app data>/thumbnails`; its parent is the app-data root.
|
||||
// Watched roots can be ancestors of it (e.g. a whole user profile), so we
|
||||
// drop any event inside that subtree to avoid re-indexing our own cache.
|
||||
let app_data_dir = thumb_dir.parent().map(Path::to_path_buf);
|
||||
std::thread::spawn(move || {
|
||||
// path → deadline: the earliest instant at which this path should be processed.
|
||||
let mut pending: HashMap<PathBuf, Instant> = HashMap::new();
|
||||
@@ -1555,7 +1770,22 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
|
||||
{
|
||||
let old = event.paths[0].clone();
|
||||
let new = event.paths[1].clone();
|
||||
if is_supported_media(&old) || is_supported_media(&new) {
|
||||
let old_in_app = is_within_app_data(&old, app_data_dir.as_deref());
|
||||
let new_in_app = is_within_app_data(&new, app_data_dir.as_deref());
|
||||
if old_in_app && new_in_app {
|
||||
// Internal app-data churn (e.g. thumbnail cache) — ignore.
|
||||
} else if old_in_app || new_in_app {
|
||||
// Only one side is app-data, so the rename pairing is
|
||||
// meaningless (we don't track app-data files). Handle the
|
||||
// legitimate side as an independent create/delete via the
|
||||
// normal debounce queue: a file moved out of app-data is
|
||||
// indexed as a create; one moved in is processed as a
|
||||
// delete (process_watcher_path sees it no longer exists).
|
||||
let legit = if old_in_app { new } else { old };
|
||||
if is_supported_media(&legit) {
|
||||
pending.insert(legit, now + WATCHER_DEBOUNCE);
|
||||
}
|
||||
} else if is_supported_media(&old) || is_supported_media(&new) {
|
||||
// Remove either side from regular pending so it isn't
|
||||
// processed as an independent delete/create.
|
||||
pending.remove(&old);
|
||||
@@ -1564,7 +1794,9 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
|
||||
}
|
||||
} else {
|
||||
for path in event.paths {
|
||||
if is_supported_media(&path) {
|
||||
if is_supported_media(&path)
|
||||
&& !is_within_app_data(&path, app_data_dir.as_deref())
|
||||
{
|
||||
pending.insert(path, now + WATCHER_DEBOUNCE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
mod ai_tag_filter;
|
||||
mod captioner;
|
||||
mod color;
|
||||
mod commands;
|
||||
mod db;
|
||||
mod embedder;
|
||||
@@ -45,6 +47,32 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_notification::init())
|
||||
.setup(|app| {
|
||||
// Fresh installs open at the fixed config size (1280×800) because the
|
||||
// window-state plugin has nothing saved yet — too tall for laptops
|
||||
// like 1366×768. Clamp the window to the monitor's work area (which
|
||||
// already excludes the taskbar) and re-center it there, but only when
|
||||
// it actually overflows, so a restored size/position on a roomier
|
||||
// display is left untouched. Sizes are physical pixels on both sides,
|
||||
// so this stays correct across display scaling.
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
if let Ok(Some(monitor)) = window.current_monitor() {
|
||||
let area = monitor.work_area();
|
||||
let max_w = area.size.width.saturating_sub(32);
|
||||
let max_h = area.size.height.saturating_sub(32);
|
||||
if let Ok(size) = window.outer_size() {
|
||||
if size.width > max_w || size.height > max_h {
|
||||
let new_w = size.width.min(max_w);
|
||||
let new_h = size.height.min(max_h);
|
||||
let _ = window.set_size(tauri::PhysicalSize::new(new_w, new_h));
|
||||
let _ = window.set_position(tauri::PhysicalPosition::new(
|
||||
area.position.x + (area.size.width as i32 - new_w as i32) / 2,
|
||||
area.position.y + (area.size.height as i32 - new_h as i32) / 2,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let app_dir = app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
@@ -91,6 +119,7 @@ pub fn run() {
|
||||
|
||||
let thumb_dir = app_dir.join("thumbnails");
|
||||
std::fs::create_dir_all(&thumb_dir).expect("Failed to create thumbnail dir");
|
||||
commands::restore_persisted_worker_pauses(&app_dir);
|
||||
|
||||
// The asset protocol scope is no longer a blanket "**": thumbnails
|
||||
// are allowed statically in tauri.conf.json, and each indexed
|
||||
@@ -122,6 +151,8 @@ pub fn run() {
|
||||
// Caption worker disabled — UI removed; keeping backend code intact for future use.
|
||||
// indexer::start_caption_worker(app.handle().clone(), pool.clone(), app_dir.clone());
|
||||
indexer::start_tagging_worker(app.handle().clone(), pool.clone(), app_dir.clone());
|
||||
// Backfill color palettes for images indexed before color search existed.
|
||||
indexer::start_color_backfill(app.handle().clone(), pool.clone());
|
||||
|
||||
let watcher_handle = indexer::start_watcher(app.handle().clone(), pool.clone(), thumb_dir.clone());
|
||||
|
||||
@@ -165,14 +196,19 @@ pub fn run() {
|
||||
commands::suggest_image_tags,
|
||||
commands::set_worker_paused,
|
||||
commands::get_worker_states,
|
||||
commands::get_tag_cloud,
|
||||
commands::get_worker_pauses_persist,
|
||||
commands::set_worker_pauses_persist,
|
||||
commands::get_visual_clusters,
|
||||
commands::get_explore_tags,
|
||||
commands::get_related_tags,
|
||||
commands::get_images_by_ids,
|
||||
commands::get_failed_embedding_images,
|
||||
commands::get_failed_tagging_images,
|
||||
commands::get_tagger_model_status,
|
||||
commands::get_tagger_acceleration,
|
||||
commands::set_tagger_acceleration,
|
||||
commands::get_tagger_model,
|
||||
commands::set_tagger_model,
|
||||
commands::probe_tagger_runtime,
|
||||
commands::get_tagger_threshold,
|
||||
commands::set_tagger_threshold,
|
||||
@@ -182,9 +218,26 @@ pub fn run() {
|
||||
commands::delete_tagger_model,
|
||||
commands::queue_tagging_jobs,
|
||||
commands::clear_tagging_jobs,
|
||||
commands::reset_ai_tags,
|
||||
commands::get_image_tags,
|
||||
commands::add_user_tag,
|
||||
commands::remove_tag,
|
||||
commands::rename_tag,
|
||||
commands::delete_tag,
|
||||
commands::get_image_exif,
|
||||
commands::list_albums,
|
||||
commands::create_album,
|
||||
commands::rename_album,
|
||||
commands::delete_album,
|
||||
commands::delete_albums,
|
||||
commands::reorder_albums,
|
||||
commands::add_images_to_album,
|
||||
commands::remove_images_from_album,
|
||||
commands::get_album_images,
|
||||
commands::bulk_update_details,
|
||||
commands::bulk_add_tags,
|
||||
commands::bulk_remove_tag,
|
||||
commands::get_build_variant,
|
||||
commands::search_tags_autocomplete,
|
||||
commands::find_duplicates,
|
||||
commands::load_duplicate_scan_cache,
|
||||
@@ -197,6 +250,8 @@ pub fn run() {
|
||||
commands::get_tagging_queue_folder_ids,
|
||||
commands::set_tagging_queue_folder_ids,
|
||||
commands::open_app_data_folder,
|
||||
commands::open_map_location,
|
||||
commands::open_changelog_url,
|
||||
commands::get_database_info,
|
||||
commands::vacuum_database,
|
||||
commands::rebuild_semantic_index,
|
||||
@@ -208,6 +263,8 @@ pub fn run() {
|
||||
commands::retry_ffmpeg_download,
|
||||
commands::get_onboarding_completed,
|
||||
commands::set_onboarding_completed,
|
||||
commands::get_last_seen_version,
|
||||
commands::set_last_seen_version,
|
||||
commands::get_notifications_paused,
|
||||
commands::set_notifications_paused,
|
||||
])
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
use crate::ai_tag_filter;
|
||||
use anyhow::Result;
|
||||
use hf_hub::{api::sync::Api, Repo, RepoType};
|
||||
use image::{imageops::FilterType, DynamicImage, ImageReader};
|
||||
use ort::ep;
|
||||
use ort::session::{builder::GraphOptimizationLevel, Session};
|
||||
use ort::value::Tensor;
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
@@ -14,16 +16,28 @@ pub const WD_TAGGER_MODEL_NAME: &str = "wd-swinv2-tagger-v3";
|
||||
|
||||
const TAGGER_ACCELERATION_FILE: &str = "settings/tagger_acceleration.txt";
|
||||
const TAGGER_THRESHOLD_FILE: &str = "settings/tagger_threshold.txt";
|
||||
const JOYTAG_THRESHOLD_FILE: &str = "settings/joytag_threshold.txt";
|
||||
const TAGGER_BATCH_SIZE_FILE: &str = "settings/tagger_batch_size.txt";
|
||||
const TAGGER_MODEL_FILE: &str = "settings/tagger_model.txt";
|
||||
|
||||
// Files required on disk before the tagger can run. The ONNX runtime DLLs
|
||||
// are shared with the captioner and live in the same `onnxruntime/` directory.
|
||||
const TAGGER_REQUIRED_FILES: &[&str] = &[
|
||||
pub const JOYTAG_MODEL_ID: &str = "fancyfeast/joytag";
|
||||
pub const JOYTAG_MODEL_NAME: &str = "joytag";
|
||||
|
||||
// JoyTag preprocessing differs from the WD tagger: it expects RGB (not BGR),
|
||||
// CLIP-style mean/std normalization on [0,1] values (not raw [0,255]), and an
|
||||
// NCHW layout (not NHWC). These are the OpenAI CLIP normalization constants.
|
||||
const JOYTAG_MEAN: [f32; 3] = [0.481_454_66, 0.457_827_5, 0.408_210_73];
|
||||
const JOYTAG_STD: [f32; 3] = [0.268_629_54, 0.261_302_6, 0.275_777_1];
|
||||
// JoyTag's recommended detection threshold.
|
||||
const JOYTAG_DEFAULT_THRESHOLD: f32 = 0.4;
|
||||
|
||||
// Shared ONNX Runtime DLLs (live in the caption model's `onnxruntime/` dir and
|
||||
// are reused by the tagger). The per-model weight + label files are listed by
|
||||
// `TaggerModel::download_files`.
|
||||
const TAGGER_RUNTIME_DLLS: &[&str] = &[
|
||||
"onnxruntime/onnxruntime.dll",
|
||||
"onnxruntime/onnxruntime_providers_shared.dll",
|
||||
"onnxruntime/DirectML.dll",
|
||||
"model.onnx",
|
||||
"selected_tags.csv",
|
||||
];
|
||||
|
||||
// Tags in these Danbooru categories are kept in the output.
|
||||
@@ -37,8 +51,21 @@ const RATING_CATEGORY: u8 = 9;
|
||||
pub const DEFAULT_THRESHOLD: f32 = 0.35;
|
||||
pub const DEFAULT_MAX_TAGS: usize = 30;
|
||||
|
||||
/// Set to `true` by `set_tagger_acceleration` so the tagging worker loop
|
||||
/// knows to drop its cached `WdTagger` and reload with the new EP.
|
||||
/// How many images are fed to the GPU in a single forward pass, regardless of
|
||||
/// how many the worker claims from the DB at once. The WD model is compute-
|
||||
/// bound on a shared GPU, so a wide batch buys little throughput but holds the
|
||||
/// GPU (and therefore the WebView2 compositor) hostage for its whole duration,
|
||||
/// freezing the UI. Small chunks keep each DirectML dispatch short — lower this
|
||||
/// for a smoother UI under heavy tagging, raise it for marginally higher
|
||||
/// throughput on a dedicated GPU.
|
||||
pub const TAGGER_INFER_CHUNK: usize = 4;
|
||||
|
||||
/// Brief pause between inference chunks so the compositor and other workers can
|
||||
/// claim the GPU/CPU between dispatches. Negligible against per-chunk inference.
|
||||
pub const TAGGER_INFER_YIELD_MS: u64 = 40;
|
||||
|
||||
/// Set to `true` by tagger setting changes so the tagging worker loop knows to
|
||||
/// drop its cached model session and reload with the current settings.
|
||||
pub static TAGGER_SESSION_DIRTY: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -64,6 +91,75 @@ impl TaggerAcceleration {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which tagging model is active. Both produce a `TaggerOutput` (tags + an
|
||||
/// explicitness rating); they differ in vocabulary, preprocessing, and how the
|
||||
/// rating is derived. WD is Danbooru-trained (anime-leaning); JoyTag uses the
|
||||
/// Danbooru schema but generalizes to photographic content and is stronger on
|
||||
/// NSFW concepts.
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum TaggerModel {
|
||||
#[default]
|
||||
Wd,
|
||||
JoyTag,
|
||||
}
|
||||
|
||||
impl TaggerModel {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Wd => "wd",
|
||||
Self::JoyTag => "joytag",
|
||||
}
|
||||
}
|
||||
|
||||
fn threshold_file(self) -> &'static str {
|
||||
match self {
|
||||
Self::Wd => TAGGER_THRESHOLD_FILE,
|
||||
Self::JoyTag => JOYTAG_THRESHOLD_FILE,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_threshold(self) -> f32 {
|
||||
match self {
|
||||
Self::Wd => DEFAULT_THRESHOLD,
|
||||
Self::JoyTag => JOYTAG_DEFAULT_THRESHOLD,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hugging Face repo the model files are fetched from.
|
||||
fn repo_id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Wd => WD_TAGGER_MODEL_ID,
|
||||
Self::JoyTag => JOYTAG_MODEL_ID,
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable display/identifier name.
|
||||
fn model_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Wd => WD_TAGGER_MODEL_NAME,
|
||||
Self::JoyTag => JOYTAG_MODEL_NAME,
|
||||
}
|
||||
}
|
||||
|
||||
/// Subdirectory under `models/` where this model's files live.
|
||||
fn dir_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Wd => "wd-swinv2-tagger-v3",
|
||||
Self::JoyTag => "joytag",
|
||||
}
|
||||
}
|
||||
|
||||
/// Files fetched from `repo_id` (the shared ONNX Runtime DLLs are handled
|
||||
/// separately). `model.onnx` is the weights; the second is the label list.
|
||||
fn download_files(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Wd => &["model.onnx", "selected_tags.csv"],
|
||||
Self::JoyTag => &["model.onnx", "top_tags.txt"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Status / probe types exposed to the frontend
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -138,14 +234,41 @@ struct TagEntry {
|
||||
// Path helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Directory of the *active* tagger model's files (driven by the
|
||||
/// `tagger_model` setting), e.g. `…/models/wd-swinv2-tagger-v3`.
|
||||
pub fn model_dir(app_data_dir: &Path) -> PathBuf {
|
||||
app_data_dir.join("models").join("wd-swinv2-tagger-v3")
|
||||
app_data_dir
|
||||
.join("models")
|
||||
.join(tagger_model(app_data_dir).dir_name())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Settings persistence
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn tagger_model(app_data_dir: &Path) -> TaggerModel {
|
||||
let path = app_data_dir.join(TAGGER_MODEL_FILE);
|
||||
let Ok(value) = std::fs::read_to_string(path) else {
|
||||
return TaggerModel::default();
|
||||
};
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"joytag" => TaggerModel::JoyTag,
|
||||
_ => TaggerModel::Wd,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_tagger_model(app_data_dir: &Path, model: TaggerModel) -> Result<TaggerModel> {
|
||||
let path = app_data_dir.join(TAGGER_MODEL_FILE);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::write(path, model.as_str())?;
|
||||
// Switching models means the cached session is for the wrong model; the
|
||||
// worker drops and rebuilds it on the next batch (same flag as an EP change).
|
||||
TAGGER_SESSION_DIRTY.store(true, Ordering::Relaxed);
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
pub fn tagger_acceleration(app_data_dir: &Path) -> TaggerAcceleration {
|
||||
let path = app_data_dir.join(TAGGER_ACCELERATION_FILE);
|
||||
let Ok(value) = std::fs::read_to_string(path) else {
|
||||
@@ -171,21 +294,33 @@ pub fn set_tagger_acceleration(
|
||||
Ok(acceleration)
|
||||
}
|
||||
|
||||
pub fn tagger_threshold(app_data_dir: &Path) -> f32 {
|
||||
let path = app_data_dir.join(TAGGER_THRESHOLD_FILE);
|
||||
fn tagger_threshold_for_model(app_data_dir: &Path, model: TaggerModel) -> f32 {
|
||||
let path = app_data_dir.join(model.threshold_file());
|
||||
let Ok(value) = std::fs::read_to_string(path) else {
|
||||
return DEFAULT_THRESHOLD;
|
||||
return model.default_threshold();
|
||||
};
|
||||
value
|
||||
.trim()
|
||||
.parse::<f32>()
|
||||
.unwrap_or(DEFAULT_THRESHOLD)
|
||||
.unwrap_or_else(|_| model.default_threshold())
|
||||
.clamp(0.01, 1.0)
|
||||
}
|
||||
|
||||
pub fn tagger_threshold(app_data_dir: &Path) -> f32 {
|
||||
tagger_threshold_for_model(app_data_dir, tagger_model(app_data_dir))
|
||||
}
|
||||
|
||||
pub fn set_tagger_threshold(app_data_dir: &Path, threshold: f32) -> Result<f32> {
|
||||
set_tagger_threshold_for_model(app_data_dir, tagger_model(app_data_dir), threshold)
|
||||
}
|
||||
|
||||
pub fn set_tagger_threshold_for_model(
|
||||
app_data_dir: &Path,
|
||||
model: TaggerModel,
|
||||
threshold: f32,
|
||||
) -> Result<f32> {
|
||||
let clamped = threshold.clamp(0.01, 1.0);
|
||||
let path = app_data_dir.join(TAGGER_THRESHOLD_FILE);
|
||||
let path = app_data_dir.join(model.threshold_file());
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -217,25 +352,27 @@ pub fn set_tagger_batch_size(app_data_dir: &Path, batch_size: usize) -> Result<u
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub fn tagger_model_status(app_data_dir: &Path) -> TaggerModelStatus {
|
||||
let model = tagger_model(app_data_dir);
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
// The ONNX runtime DLLs live in the caption model dir; reuse them.
|
||||
let caption_model_dir = app_data_dir.join("models").join("florence-2-base-ft");
|
||||
let missing_files = TAGGER_REQUIRED_FILES
|
||||
|
||||
let mut missing_files: Vec<String> = TAGGER_RUNTIME_DLLS
|
||||
.iter()
|
||||
.filter(|file| {
|
||||
let path = if file.starts_with("onnxruntime/") {
|
||||
caption_model_dir.join(file)
|
||||
} else {
|
||||
local_dir.join(file)
|
||||
};
|
||||
!path.exists()
|
||||
})
|
||||
.filter(|file| !caption_model_dir.join(file).exists())
|
||||
.map(|file| (*file).to_string())
|
||||
.collect::<Vec<_>>();
|
||||
.collect();
|
||||
missing_files.extend(
|
||||
model
|
||||
.download_files()
|
||||
.iter()
|
||||
.filter(|file| !local_dir.join(file).exists())
|
||||
.map(|file| (*file).to_string()),
|
||||
);
|
||||
|
||||
TaggerModelStatus {
|
||||
model_id: WD_TAGGER_MODEL_ID,
|
||||
model_name: WD_TAGGER_MODEL_NAME,
|
||||
model_id: model.repo_id(),
|
||||
model_name: model.model_name(),
|
||||
local_dir: local_dir.to_string_lossy().to_string(),
|
||||
ready: missing_files.is_empty(),
|
||||
missing_files,
|
||||
@@ -246,19 +383,20 @@ pub fn prepare_tagger_model_with_progress(
|
||||
app_data_dir: &Path,
|
||||
emit_progress: impl Fn(TaggerModelProgress),
|
||||
) -> Result<TaggerModelStatus> {
|
||||
let model = tagger_model(app_data_dir);
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
std::fs::create_dir_all(&local_dir)?;
|
||||
|
||||
// The tagger shares the ONNX runtime DLLs with the captioner; download
|
||||
// them here so the tagger works even on a clean install where the caption
|
||||
// model has never been fetched (ensure_onnx_runtime only initializes).
|
||||
const DOWNLOAD_FILES: &[&str] = &["model.onnx", "selected_tags.csv"];
|
||||
let download_files = model.download_files();
|
||||
let caption_model_dir = crate::captioner::model_dir(app_data_dir);
|
||||
std::fs::create_dir_all(&caption_model_dir)?;
|
||||
|
||||
// Unified step count across DLLs and tagger files so the bar is coherent.
|
||||
let dll_count = crate::captioner::missing_onnx_runtime_count(&caption_model_dir);
|
||||
let model_pending = DOWNLOAD_FILES
|
||||
let model_pending = download_files
|
||||
.iter()
|
||||
.filter(|file| !local_dir.join(file).exists())
|
||||
.count();
|
||||
@@ -304,9 +442,9 @@ pub fn prepare_tagger_model_with_progress(
|
||||
// (timeout + resume), rather than hf-hub's download_with_progress, whose
|
||||
// agent has no read timeout and would hang on a stalled connection.
|
||||
let api = Api::new()?;
|
||||
let repo = api.repo(Repo::new(WD_TAGGER_MODEL_ID.to_string(), RepoType::Model));
|
||||
let repo = api.repo(Repo::new(model.repo_id().to_string(), RepoType::Model));
|
||||
|
||||
for file in DOWNLOAD_FILES {
|
||||
for file in download_files {
|
||||
let destination = local_dir.join(file);
|
||||
if destination.exists() {
|
||||
continue;
|
||||
@@ -354,7 +492,8 @@ pub fn probe_tagger_runtime(app_data_dir: &Path) -> Result<TaggerRuntimeProbe> {
|
||||
let status = tagger_model_status(app_data_dir);
|
||||
if !status.ready {
|
||||
anyhow::bail!(
|
||||
"WD Tagger model is missing {} required file(s): {}",
|
||||
"{} is missing {} required file(s): {}",
|
||||
status.model_name,
|
||||
status.missing_files.len(),
|
||||
status.missing_files.join(", ")
|
||||
);
|
||||
@@ -410,11 +549,96 @@ pub fn probe_tagger_runtime(app_data_dir: &Path) -> Result<TaggerRuntimeProbe> {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Top-level inference entry point
|
||||
// Tagger trait + shared batch skeleton
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// A loaded tagging model. Implementations differ in vocabulary, preprocessing,
|
||||
/// and how the explicitness rating is derived, but all turn a batch of image
|
||||
/// paths into one `TaggerOutput` per path (in order), with per-image failures
|
||||
/// reflected in the individual `Result`s. Built for the active model by
|
||||
/// [`create_active_tagger`].
|
||||
pub trait Tagger {
|
||||
fn run_batch(&mut self, image_paths: &[PathBuf], max_tags: usize) -> Vec<Result<TaggerOutput>>;
|
||||
|
||||
/// Stable name of this model, written to the DB as `ai_tagger_model` so
|
||||
/// tags can be attributed to (and re-tagged across) models.
|
||||
fn model_name(&self) -> &'static str;
|
||||
}
|
||||
|
||||
/// Build the tagger for the currently-selected model.
|
||||
pub fn create_active_tagger(app_data_dir: &Path) -> Result<Box<dyn Tagger>> {
|
||||
match tagger_model(app_data_dir) {
|
||||
TaggerModel::Wd => Ok(Box::new(WdTagger::new(app_data_dir)?)),
|
||||
TaggerModel::JoyTag => Ok(Box::new(JoyTagger::new(app_data_dir)?)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared batch skeleton: pack the successfully-preprocessed images into one
|
||||
/// contiguous buffer, run a single batched forward pass via `infer`, and fall
|
||||
/// back to per-image inference if the batch fails (e.g. a model pinned to
|
||||
/// batch=1). Returns one result per input slot, in order — a decode failure
|
||||
/// stays attached to its own slot. `infer(pixels, count)` runs `count`
|
||||
/// contiguous images (`count * stride` floats) and returns `count` outputs.
|
||||
fn assemble_batch(
|
||||
preprocessed: Vec<Result<Vec<f32>>>,
|
||||
stride: usize,
|
||||
model_label: &str,
|
||||
mut infer: impl FnMut(&[f32], usize) -> Result<Vec<TaggerOutput>>,
|
||||
) -> Vec<Result<TaggerOutput>> {
|
||||
let mut batch_slots: Vec<usize> = Vec::new();
|
||||
let mut batch_pixels: Vec<f32> = Vec::with_capacity(preprocessed.len() * stride);
|
||||
for (i, result) in preprocessed.iter().enumerate() {
|
||||
if let Ok(pixels) = result {
|
||||
batch_slots.push(i);
|
||||
batch_pixels.extend_from_slice(pixels);
|
||||
}
|
||||
}
|
||||
|
||||
// Seed each slot with its decode error; inference overwrites decoded slots.
|
||||
let mut results: Vec<Result<TaggerOutput>> = preprocessed
|
||||
.into_iter()
|
||||
.map(|r| match r {
|
||||
Ok(_) => Err(anyhow::anyhow!(
|
||||
"tagging inference did not run for this image"
|
||||
)),
|
||||
Err(error) => Err(error),
|
||||
})
|
||||
.collect();
|
||||
|
||||
if batch_slots.is_empty() {
|
||||
return results; // nothing decoded
|
||||
}
|
||||
|
||||
match infer(&batch_pixels, batch_slots.len()) {
|
||||
Ok(outputs) => {
|
||||
// `infer` must return exactly one output per packed image; the zip
|
||||
// below would otherwise silently leave trailing slots as errors.
|
||||
debug_assert_eq!(outputs.len(), batch_slots.len());
|
||||
for (&slot, output) in batch_slots.iter().zip(outputs) {
|
||||
results[slot] = Ok(output);
|
||||
}
|
||||
}
|
||||
Err(batch_error) => {
|
||||
log::warn!(
|
||||
"{model_label} batch inference failed for {} images, falling back to per-image: {batch_error}",
|
||||
batch_slots.len()
|
||||
);
|
||||
for (k, &slot) in batch_slots.iter().enumerate() {
|
||||
let one = &batch_pixels[k * stride..(k + 1) * stride];
|
||||
results[slot] = infer(one, 1).and_then(|mut out| {
|
||||
out.drain(..)
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("tagger produced no output for image"))
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tagger implementation
|
||||
// WD tagger implementation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub struct WdTagger {
|
||||
@@ -456,33 +680,34 @@ impl WdTagger {
|
||||
|
||||
let session = create_tagger_session(&model_path, acceleration)?;
|
||||
|
||||
// Determine the input spatial size from the ONNX model graph.
|
||||
// WD v3 models use (1, H, W, 3) where H == W, typically 448.
|
||||
let input_size = {
|
||||
// Determine the input spatial size (and batch axis, for diagnostics) from
|
||||
// the ONNX model graph. WD v3 models use (N, H, W, 3) with H == W,
|
||||
// typically 448, and a dynamic batch dimension (reported as -1/0) which
|
||||
// batched inference relies on.
|
||||
let (input_size, batch_axis) = {
|
||||
let inputs = session.inputs();
|
||||
let dim = inputs
|
||||
inputs
|
||||
.first()
|
||||
.and_then(|inp| {
|
||||
if let ort::value::ValueType::Tensor { shape, .. } = inp.dtype() {
|
||||
shape
|
||||
.get(1)
|
||||
.and_then(|&d| if d > 0 { Some(d as usize) } else { None })
|
||||
let size = shape.get(1).copied().filter(|&d| d > 0).map(|d| d as usize);
|
||||
Some((size.unwrap_or(448), shape.first().copied()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or(448);
|
||||
dim
|
||||
.unwrap_or((448, None))
|
||||
};
|
||||
|
||||
let labels = load_labels(&labels_path)?;
|
||||
|
||||
log::info!(
|
||||
"WD tagger loaded in {:?} ({} labels, input {}x{}, {:?} acceleration)",
|
||||
"WD tagger loaded in {:?} ({} labels, input {}x{}, batch axis {:?}, {:?} acceleration)",
|
||||
started_at.elapsed(),
|
||||
labels.len(),
|
||||
input_size,
|
||||
input_size,
|
||||
batch_axis,
|
||||
acceleration,
|
||||
);
|
||||
|
||||
@@ -494,14 +719,17 @@ impl WdTagger {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn run(&mut self, image_path: &Path, max_tags: usize) -> Result<TaggerOutput> {
|
||||
let started_at = Instant::now();
|
||||
|
||||
let image_array = preprocess_image(image_path, self.input_size)?;
|
||||
let batch_size = 1usize;
|
||||
/// Run `count` already-preprocessed images (contiguous `[count, H, W, 3]`
|
||||
/// pixels) through the model in one forward pass.
|
||||
fn infer_batch(
|
||||
&mut self,
|
||||
pixels: &[f32],
|
||||
count: usize,
|
||||
max_tags: usize,
|
||||
) -> Result<Vec<TaggerOutput>> {
|
||||
let input = Tensor::from_array((
|
||||
[batch_size, self.input_size, self.input_size, 3usize],
|
||||
image_array.into_boxed_slice(),
|
||||
[count, self.input_size, self.input_size, 3usize],
|
||||
pixels.to_vec().into_boxed_slice(),
|
||||
))
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
@@ -511,23 +739,40 @@ impl WdTagger {
|
||||
.run(ort::inputs! { input_name.as_str() => input })
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
let (_, probabilities) = outputs[0]
|
||||
let (_, probs) = outputs[0]
|
||||
.try_extract_tensor::<f32>()
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
let probs: &[f32] = probabilities;
|
||||
|
||||
if probs.len() != self.labels.len() {
|
||||
let n_labels = self.labels.len();
|
||||
if probs.len() != count * n_labels {
|
||||
anyhow::bail!(
|
||||
"Model output length {} does not match label count {}",
|
||||
"Model output length {} does not match {} images x {} labels",
|
||||
probs.len(),
|
||||
self.labels.len()
|
||||
count,
|
||||
n_labels
|
||||
);
|
||||
}
|
||||
|
||||
// Collect rating scores (category 9) - pick the argmax as the rating.
|
||||
let rating = self
|
||||
.labels
|
||||
// Borrow disjoint fields (not all of `self`) so this doesn't conflict
|
||||
// with the mutable session borrow `outputs` still holds.
|
||||
let labels = &self.labels;
|
||||
let threshold = self.threshold;
|
||||
Ok(probs
|
||||
.chunks_exact(n_labels)
|
||||
.map(|row| Self::tags_from_probs(labels, threshold, row, max_tags))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Convert one image's class probabilities into its rating + sorted tags.
|
||||
/// Associated (not `&self`) so callers can hold a disjoint session borrow.
|
||||
fn tags_from_probs(
|
||||
labels: &[TagEntry],
|
||||
threshold: f32,
|
||||
probs: &[f32],
|
||||
max_tags: usize,
|
||||
) -> TaggerOutput {
|
||||
// Rating (category 9): pick the argmax label as the rating.
|
||||
let rating = labels
|
||||
.iter()
|
||||
.zip(probs.iter())
|
||||
.filter(|(entry, _)| entry.category == RATING_CATEGORY)
|
||||
@@ -535,14 +780,14 @@ impl WdTagger {
|
||||
.map(|(entry, _)| entry.name.clone())
|
||||
.unwrap_or_else(|| "general".to_string());
|
||||
|
||||
// Collect general + character tags above threshold, sorted by confidence.
|
||||
let mut tags: Vec<TagResult> = self
|
||||
.labels
|
||||
// General + character tags above threshold, sorted by confidence.
|
||||
let mut tags: Vec<TagResult> = labels
|
||||
.iter()
|
||||
.zip(probs.iter())
|
||||
.filter(|(entry, prob)| {
|
||||
(entry.category == GENERAL_CATEGORY || entry.category == CHARACTER_CATEGORY)
|
||||
&& **prob >= self.threshold
|
||||
&& **prob >= threshold
|
||||
&& !ai_tag_filter::is_removed_ai_tag(&entry.name)
|
||||
})
|
||||
.map(|(entry, prob)| TagResult {
|
||||
tag: entry.name.clone(),
|
||||
@@ -553,16 +798,178 @@ impl WdTagger {
|
||||
tags.sort_by(|a, b| b.confidence.total_cmp(&a.confidence));
|
||||
tags.truncate(max_tags);
|
||||
|
||||
TaggerOutput { tags, rating }
|
||||
}
|
||||
}
|
||||
|
||||
impl Tagger for WdTagger {
|
||||
fn run_batch(&mut self, image_paths: &[PathBuf], max_tags: usize) -> Vec<Result<TaggerOutput>> {
|
||||
if image_paths.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let input_size = self.input_size;
|
||||
let preprocessed: Vec<Result<Vec<f32>>> = image_paths
|
||||
.par_iter()
|
||||
.map(|path| preprocess_image(path, input_size))
|
||||
.collect();
|
||||
assemble_batch(
|
||||
preprocessed,
|
||||
input_size * input_size * 3,
|
||||
"WD tagger",
|
||||
|pixels, count| self.infer_batch(pixels, count, max_tags),
|
||||
)
|
||||
}
|
||||
|
||||
fn model_name(&self) -> &'static str {
|
||||
WD_TAGGER_MODEL_NAME
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// JoyTag implementation
|
||||
// JoyTag uses the Danbooru tag schema but generalizes to photographic content
|
||||
// and is strong on NSFW concepts. It has no rating output, so the explicitness
|
||||
// rating is derived from its NSFW tags (see `joytag_rating`). Input is NCHW,
|
||||
// RGB, CLIP-normalized — see `preprocess_joytag`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub struct JoyTagger {
|
||||
session: Session,
|
||||
labels: Vec<String>,
|
||||
threshold: f32,
|
||||
input_size: usize,
|
||||
}
|
||||
|
||||
impl JoyTagger {
|
||||
pub fn new(app_data_dir: &Path) -> Result<Self> {
|
||||
let started_at = Instant::now();
|
||||
|
||||
let status = tagger_model_status(app_data_dir);
|
||||
if !status.ready {
|
||||
anyhow::bail!(
|
||||
"JoyTag model is missing {} required file(s): {}",
|
||||
status.missing_files.len(),
|
||||
status.missing_files.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
|
||||
// Shared ONNX runtime DLLs (see WdTagger::new).
|
||||
let caption_model_dir = app_data_dir.join("models").join("florence-2-base-ft");
|
||||
crate::captioner::ensure_onnx_runtime(&caption_model_dir).map_err(|e| {
|
||||
anyhow::anyhow!(
|
||||
"ONNX Runtime not initialised — download the Florence-2 caption model first \
|
||||
to get the shared runtime DLLs. Original error: {e}"
|
||||
)
|
||||
})?;
|
||||
|
||||
let acceleration = tagger_acceleration(app_data_dir);
|
||||
let threshold = joytag_threshold(app_data_dir);
|
||||
let model_path = local_dir.join("model.onnx");
|
||||
let labels_path = local_dir.join("top_tags.txt");
|
||||
|
||||
let session = create_tagger_session(&model_path, acceleration)?;
|
||||
|
||||
// JoyTag uses NCHW (N, 3, H, W); the spatial size lives at axis 2.
|
||||
let (input_size, batch_axis) = {
|
||||
let inputs = session.inputs();
|
||||
inputs
|
||||
.first()
|
||||
.and_then(|inp| {
|
||||
if let ort::value::ValueType::Tensor { shape, .. } = inp.dtype() {
|
||||
let size = shape.get(2).copied().filter(|&d| d > 0).map(|d| d as usize);
|
||||
Some((size.unwrap_or(448), shape.first().copied()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or((448, None))
|
||||
};
|
||||
|
||||
let labels = load_joytag_labels(&labels_path)?;
|
||||
|
||||
log::info!(
|
||||
"WD tagger: {} tags (threshold={}, rating={}) in {:?} for {}",
|
||||
tags.len(),
|
||||
self.threshold,
|
||||
rating,
|
||||
"JoyTag loaded in {:?} ({} tags, input {}x{}, batch axis {:?}, {:?} acceleration)",
|
||||
started_at.elapsed(),
|
||||
image_path.display(),
|
||||
labels.len(),
|
||||
input_size,
|
||||
input_size,
|
||||
batch_axis,
|
||||
acceleration,
|
||||
);
|
||||
|
||||
Ok(TaggerOutput { tags, rating })
|
||||
Ok(Self {
|
||||
session,
|
||||
labels,
|
||||
threshold,
|
||||
input_size,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run `count` already-preprocessed images (contiguous `[count, 3, H, W]`
|
||||
/// pixels) through the model in one forward pass.
|
||||
fn infer_batch(
|
||||
&mut self,
|
||||
pixels: &[f32],
|
||||
count: usize,
|
||||
max_tags: usize,
|
||||
) -> Result<Vec<TaggerOutput>> {
|
||||
let input = Tensor::from_array((
|
||||
[count, 3usize, self.input_size, self.input_size],
|
||||
pixels.to_vec().into_boxed_slice(),
|
||||
))
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
let input_name: String = self.session.inputs()[0].name().to_string();
|
||||
let outputs = self
|
||||
.session
|
||||
.run(ort::inputs! { input_name.as_str() => input })
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
let (_, logits) = outputs[0]
|
||||
.try_extract_tensor::<f32>()
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
let n_labels = self.labels.len();
|
||||
if logits.len() != count * n_labels {
|
||||
anyhow::bail!(
|
||||
"Model output length {} does not match {} images x {} labels",
|
||||
logits.len(),
|
||||
count,
|
||||
n_labels
|
||||
);
|
||||
}
|
||||
|
||||
let labels = &self.labels;
|
||||
let threshold = self.threshold;
|
||||
Ok(logits
|
||||
.chunks_exact(n_labels)
|
||||
.map(|row| joytag_tags_from_logits(labels, threshold, row, max_tags))
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
impl Tagger for JoyTagger {
|
||||
fn run_batch(&mut self, image_paths: &[PathBuf], max_tags: usize) -> Vec<Result<TaggerOutput>> {
|
||||
if image_paths.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let input_size = self.input_size;
|
||||
let preprocessed: Vec<Result<Vec<f32>>> = image_paths
|
||||
.par_iter()
|
||||
.map(|path| preprocess_joytag(path, input_size))
|
||||
.collect();
|
||||
assemble_batch(
|
||||
preprocessed,
|
||||
input_size * input_size * 3,
|
||||
"JoyTag",
|
||||
|pixels, count| self.infer_batch(pixels, count, max_tags),
|
||||
)
|
||||
}
|
||||
|
||||
fn model_name(&self) -> &'static str {
|
||||
JOYTAG_MODEL_NAME
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,6 +988,22 @@ fn create_tagger_session(path: &Path, acceleration: TaggerAcceleration) -> Resul
|
||||
TaggerAcceleration::Auto | TaggerAcceleration::Directml
|
||||
);
|
||||
|
||||
// Intra-op thread count. For DirectML the matmuls run on the GPU, so a
|
||||
// single CPU thread for the few CPU-side ops avoids needlessly contending
|
||||
// with the other workers. The CPU EP, however, is compute-bound and would
|
||||
// otherwise be pinned to one core (~15x slower than it needs to be), so give
|
||||
// it most of the logical cores while leaving a couple free for the UI and a
|
||||
// possible concurrent scan. Tagging is the lowest-priority worker, so when
|
||||
// it runs the heavier workers are idle. (Auto only lands on CPU when
|
||||
// DirectML is unavailable — rare on Windows — and stays single-threaded;
|
||||
// CPU-bound users can select the CPU provider explicitly for the speedup.)
|
||||
let intra_threads = match acceleration {
|
||||
TaggerAcceleration::Cpu => std::thread::available_parallelism()
|
||||
.map(|p| p.get().saturating_sub(2).max(1))
|
||||
.unwrap_or(2),
|
||||
TaggerAcceleration::Auto | TaggerAcceleration::Directml => 1,
|
||||
};
|
||||
|
||||
let builder = builder
|
||||
.with_memory_pattern(!use_directml)
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
@@ -588,18 +1011,18 @@ fn create_tagger_session(path: &Path, acceleration: TaggerAcceleration) -> Resul
|
||||
.with_parallel_execution(false)
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
let builder = builder
|
||||
.with_intra_threads(1)
|
||||
.with_intra_threads(intra_threads)
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
|
||||
let mut builder = match acceleration {
|
||||
TaggerAcceleration::Cpu => {
|
||||
log::info!("WD tagger: using CPU execution provider");
|
||||
log::info!("Tagger: using CPU execution provider ({intra_threads} intra-op threads)");
|
||||
builder
|
||||
}
|
||||
TaggerAcceleration::Auto => builder
|
||||
.with_execution_providers([ep::DirectML::default().build().fail_silently()])
|
||||
.unwrap_or_else(|error| {
|
||||
log::info!("WD tagger: DirectML unavailable, falling back to CPU");
|
||||
log::info!("Tagger: DirectML unavailable, falling back to CPU");
|
||||
error.recover()
|
||||
}),
|
||||
TaggerAcceleration::Directml => builder
|
||||
@@ -641,12 +1064,127 @@ fn load_labels(path: &Path) -> Result<Vec<TagEntry>> {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Image preprocessing
|
||||
// WD tagger expects: (1, H, W, 3) float32, raw [0,255] values, BGR channel
|
||||
// order, padded to square with white (255,255,255).
|
||||
// JoyTag: label loading, threshold, rating derivation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn preprocess_image(image_path: &Path, target_size: usize) -> Result<Vec<f32>> {
|
||||
/// JoyTag labels: one tag per line, index == output position. Underscores are
|
||||
/// replaced with spaces to match the display style used elsewhere.
|
||||
fn load_joytag_labels(path: &Path) -> Result<Vec<String>> {
|
||||
let content = std::fs::read_to_string(path)?;
|
||||
let labels: Vec<String> = content
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty())
|
||||
.map(|line| line.replace('_', " "))
|
||||
.collect();
|
||||
if labels.is_empty() {
|
||||
anyhow::bail!("top_tags.txt is empty or could not be parsed");
|
||||
}
|
||||
Ok(labels)
|
||||
}
|
||||
|
||||
/// JoyTag detection threshold. Uses JoyTag's own setting so WD tuning does not
|
||||
/// leak into the general/photo-friendly model.
|
||||
fn joytag_threshold(app_data_dir: &Path) -> f32 {
|
||||
tagger_threshold_for_model(app_data_dir, TaggerModel::JoyTag)
|
||||
}
|
||||
|
||||
fn sigmoid(x: f32) -> f32 {
|
||||
1.0 / (1.0 + (-x).exp())
|
||||
}
|
||||
|
||||
// Explicitness buckets for deriving a rating from JoyTag's tags (highest match
|
||||
// wins). Names use spaces, since underscores are stripped on load. Tunable.
|
||||
const JOYTAG_EXPLICIT_TAGS: &[&str] = &[
|
||||
"sex",
|
||||
"vaginal",
|
||||
"anal",
|
||||
"oral",
|
||||
"fellatio",
|
||||
"cunnilingus",
|
||||
"penis",
|
||||
"pussy",
|
||||
"cum",
|
||||
"ejaculation",
|
||||
"erection",
|
||||
"handjob",
|
||||
"paizuri",
|
||||
"masturbation",
|
||||
];
|
||||
const JOYTAG_QUESTIONABLE_TAGS: &[&str] = &[
|
||||
"nude",
|
||||
"completely nude",
|
||||
"nipples",
|
||||
"topless",
|
||||
"bottomless",
|
||||
"pubic hair",
|
||||
"areola",
|
||||
"areolae",
|
||||
];
|
||||
const JOYTAG_SENSITIVE_TAGS: &[&str] = &[
|
||||
"lingerie",
|
||||
"underwear",
|
||||
"panties",
|
||||
"swimsuit",
|
||||
"bikini",
|
||||
"cleavage",
|
||||
"bra",
|
||||
"midriff",
|
||||
];
|
||||
|
||||
/// Derive an explicitness rating from JoyTag's tags. JoyTag has no rating
|
||||
/// output, so this maps its NSFW-content tags onto the WD-style buckets.
|
||||
fn joytag_rating(tags: &[TagResult]) -> String {
|
||||
let has = |bucket: &[&str]| tags.iter().any(|t| bucket.contains(&t.tag.as_str()));
|
||||
if has(JOYTAG_EXPLICIT_TAGS) {
|
||||
"explicit".to_string()
|
||||
} else if has(JOYTAG_QUESTIONABLE_TAGS) {
|
||||
"questionable".to_string()
|
||||
} else if has(JOYTAG_SENSITIVE_TAGS) {
|
||||
"sensitive".to_string()
|
||||
} else {
|
||||
"general".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert one image's JoyTag logits into sorted tags + a derived rating.
|
||||
fn joytag_tags_from_logits(
|
||||
labels: &[String],
|
||||
threshold: f32,
|
||||
logits: &[f32],
|
||||
max_tags: usize,
|
||||
) -> TaggerOutput {
|
||||
let mut tags: Vec<TagResult> = labels
|
||||
.iter()
|
||||
.zip(logits.iter())
|
||||
.filter_map(|(name, logit)| {
|
||||
let confidence = sigmoid(*logit);
|
||||
(confidence >= threshold && !ai_tag_filter::is_removed_ai_tag(name)).then(|| {
|
||||
TagResult {
|
||||
tag: name.clone(),
|
||||
confidence,
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
tags.sort_by(|a, b| b.confidence.total_cmp(&a.confidence));
|
||||
|
||||
// Derive the rating from all kept tags before truncating to max_tags.
|
||||
let rating = joytag_rating(&tags);
|
||||
tags.truncate(max_tags);
|
||||
|
||||
TaggerOutput { tags, rating }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Image preprocessing
|
||||
// Both taggers pad to square with white and resize to the model input size;
|
||||
// they differ only in channel order, value range, and tensor layout.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Decode an image, composite any alpha onto white, pad to a centered square,
|
||||
/// and resize to `target_size`. Shared by both taggers.
|
||||
fn decode_pad_resize(image_path: &Path, target_size: usize) -> Result<image::RgbImage> {
|
||||
let image = ImageReader::open(image_path)?.decode()?;
|
||||
|
||||
// Composite any alpha channel onto a white background.
|
||||
@@ -657,22 +1195,25 @@ fn preprocess_image(image_path: &Path, target_size: usize) -> Result<Vec<f32>> {
|
||||
image::imageops::overlay(&mut canvas_rgba, &image_rgba, 0, 0);
|
||||
let image_rgb = DynamicImage::ImageRgba8(canvas_rgba).to_rgb8();
|
||||
|
||||
// Pad to square.
|
||||
// Pad to a centered square.
|
||||
let max_dim = width.max(height);
|
||||
let pad_left = (max_dim - width) / 2;
|
||||
let pad_top = (max_dim - height) / 2;
|
||||
let mut square = image::RgbImage::from_pixel(max_dim, max_dim, image::Rgb([255, 255, 255]));
|
||||
image::imageops::overlay(&mut square, &image_rgb, pad_left as i64, pad_top as i64);
|
||||
|
||||
// Resize to model input size.
|
||||
let resized = image::imageops::resize(
|
||||
// Resize to model input size (CatmullRom ≈ PIL BICUBIC).
|
||||
Ok(image::imageops::resize(
|
||||
&square,
|
||||
target_size as u32,
|
||||
target_size as u32,
|
||||
FilterType::CatmullRom,
|
||||
);
|
||||
))
|
||||
}
|
||||
|
||||
// Flatten to (H, W, 3) float32 in BGR order, values in [0, 255].
|
||||
/// WD tagger input: (N, H, W, 3) float32, raw [0,255] values, BGR order.
|
||||
fn preprocess_image(image_path: &Path, target_size: usize) -> Result<Vec<f32>> {
|
||||
let resized = decode_pad_resize(image_path, target_size)?;
|
||||
let mut pixel_values = vec![0.0f32; target_size * target_size * 3];
|
||||
for (x, y, pixel) in resized.enumerate_pixels() {
|
||||
let base = (y as usize * target_size + x as usize) * 3;
|
||||
@@ -681,6 +1222,21 @@ fn preprocess_image(image_path: &Path, target_size: usize) -> Result<Vec<f32>> {
|
||||
pixel_values[base + 1] = f32::from(pixel[1]); // G
|
||||
pixel_values[base + 2] = f32::from(pixel[0]); // R
|
||||
}
|
||||
|
||||
Ok(pixel_values)
|
||||
}
|
||||
|
||||
/// JoyTag input: (N, 3, H, W) float32, RGB, CLIP-normalized ((x/255 − mean)/std).
|
||||
fn preprocess_joytag(image_path: &Path, target_size: usize) -> Result<Vec<f32>> {
|
||||
let resized = decode_pad_resize(image_path, target_size)?;
|
||||
let plane = target_size * target_size;
|
||||
let mut pixel_values = vec![0.0f32; 3 * plane];
|
||||
for (x, y, pixel) in resized.enumerate_pixels() {
|
||||
let idx = y as usize * target_size + x as usize;
|
||||
// Channel-major (NCHW): R plane, then G, then B.
|
||||
for c in 0..3 {
|
||||
pixel_values[c * plane + idx] =
|
||||
(f32::from(pixel[c]) / 255.0 - JOYTAG_MEAN[c]) / JOYTAG_STD[c];
|
||||
}
|
||||
}
|
||||
Ok(pixel_values)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ pub struct GeneratedThumbnail {
|
||||
pub path: PathBuf,
|
||||
pub width: Option<i64>,
|
||||
pub height: Option<i64>,
|
||||
/// Dominant-color palette `(r, g, b, weight)` sampled while resizing. Empty
|
||||
/// when the thumbnail already existed (the color backfill handles those).
|
||||
pub palette: Vec<(u8, u8, u8, f32)>,
|
||||
}
|
||||
|
||||
pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<GeneratedThumbnail> {
|
||||
@@ -28,6 +31,7 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,6 +51,12 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
let thumb = image::RgbImage::from_raw(dst_width, dst_height, dst.buffer().to_vec())
|
||||
.ok_or_else(|| anyhow!("failed to construct resized thumbnail buffer"))?;
|
||||
|
||||
// Sample the dominant-color palette from the resized buffer before encoding.
|
||||
let palette = crate::color::extract_palette(&thumb, crate::color::PALETTE_SIZE)
|
||||
.into_iter()
|
||||
.map(|color| (color.r, color.g, color.b, color.weight))
|
||||
.collect();
|
||||
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -58,6 +68,7 @@ pub fn generate_image_thumbnail(image_path: &Path, cache_dir: &Path) -> Result<G
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -166,6 +177,7 @@ pub fn generate_video_thumbnail(
|
||||
path: out_path,
|
||||
width: None,
|
||||
height: None,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -231,6 +243,7 @@ pub fn generate_video_thumbnail(
|
||||
path: out_path,
|
||||
width: None,
|
||||
height: None,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
last_error = String::from_utf8_lossy(&output.stderr).to_string();
|
||||
@@ -255,6 +268,7 @@ pub fn generate_avif_thumbnail(
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -282,10 +296,19 @@ pub fn generate_avif_thumbnail(
|
||||
.output()?;
|
||||
|
||||
if output.status.success() && out_path.exists() {
|
||||
// AVIF is decoded by FFmpeg, so there's no in-memory RGB buffer here;
|
||||
// sample the palette by reading the JPEG thumbnail we just wrote.
|
||||
let palette =
|
||||
crate::color::extract_palette_from_file(&out_path, crate::color::PALETTE_SIZE)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|color| (color.r, color.g, color.b, color.weight))
|
||||
.collect();
|
||||
return Ok(GeneratedThumbnail {
|
||||
path: out_path,
|
||||
width: original_dimensions.0,
|
||||
height: original_dimensions.1,
|
||||
palette,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -263,6 +263,44 @@ pub fn get_embedding_revision(conn: &Connection) -> Result<String> {
|
||||
|
||||
/// Returns all stored image embeddings with their image IDs, optionally filtered to one folder.
|
||||
/// Each entry is `(image_id, normalized_f32_embedding)`.
|
||||
/// Returns `(count, hash)` over the stored embedding image IDs for the scope in a
|
||||
/// single ordered pass, without loading any embedding blobs. The hash covers the
|
||||
/// exact set of IDs, so it is membership-sensitive: adding, removing, or moving an
|
||||
/// image between folders changes it even when the count happens to stay the same.
|
||||
/// Used (together with the embedding revision, which catches an image being
|
||||
/// re-embedded in place) as the cheap visual-cluster cache key so a cache hit doesn't
|
||||
/// have to read and unpack hundreds of MB of embeddings just to validate freshness.
|
||||
pub fn embedding_ids_signature(conn: &Connection, folder_id: Option<i64>) -> Result<(i64, u64)> {
|
||||
use xxhash_rust::xxh3::Xxh3;
|
||||
let mut hasher = Xxh3::new();
|
||||
let mut count: i64 = 0;
|
||||
let mut hash_row = |id: i64| {
|
||||
hasher.update(&id.to_le_bytes());
|
||||
count += 1;
|
||||
};
|
||||
match folder_id {
|
||||
Some(fid) => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT image_id FROM image_vec
|
||||
WHERE image_id IN (SELECT id FROM images WHERE folder_id = ?1)
|
||||
ORDER BY image_id",
|
||||
)?;
|
||||
let mut rows = stmt.query([fid])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
hash_row(row.get(0)?);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut stmt = conn.prepare("SELECT image_id FROM image_vec ORDER BY image_id")?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
hash_row(row.get(0)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((count, hasher.digest()))
|
||||
}
|
||||
|
||||
pub fn get_all_image_embeddings_with_ids(
|
||||
conn: &Connection,
|
||||
folder_id: Option<i64>,
|
||||
@@ -372,6 +410,41 @@ pub fn search_image_ids_by_embedding_in_folder(
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
/// Brute-force cosine search scoped to a single album (membership via
|
||||
/// `album_images`), ordered by ascending distance. Mirrors the folder-scoped
|
||||
/// variant for region-based similarity search.
|
||||
pub fn search_image_ids_by_embedding_in_album(
|
||||
conn: &Connection,
|
||||
embedding: &[f32],
|
||||
album_id: i64,
|
||||
exclude_image_id: Option<i64>,
|
||||
limit: usize,
|
||||
) -> Result<Vec<i64>> {
|
||||
if embedding.len() != CLIP_VECTOR_DIM {
|
||||
return Err(anyhow!(
|
||||
"expected {}-dimensional embedding, got {}",
|
||||
CLIP_VECTOR_DIM,
|
||||
embedding.len()
|
||||
));
|
||||
}
|
||||
|
||||
let packed = pack_f32(embedding);
|
||||
let exclude_id = exclude_image_id.unwrap_or(-1);
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT v.image_id
|
||||
FROM image_vec v
|
||||
JOIN album_images ai ON ai.image_id = v.image_id
|
||||
WHERE ai.album_id = ?2
|
||||
AND v.image_id != ?3
|
||||
ORDER BY vec_distance_cosine(v.embedding, vec_f32(?1)) ASC
|
||||
LIMIT ?4",
|
||||
)?;
|
||||
let rows = stmt.query_map((&packed, album_id, exclude_id, limit as i64), |row| {
|
||||
row.get::<_, i64>(0)
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn search_caption_ids_by_embedding(
|
||||
conn: &Connection,
|
||||
|
||||
@@ -1,83 +1,100 @@
|
||||
import { useEffect } from "react";
|
||||
import { useGalleryStore } from "./store";
|
||||
import { Sidebar } from "./components/Sidebar";
|
||||
import { BackgroundTasks } from "./components/BackgroundTasks";
|
||||
import { Toolbar } from "./components/Toolbar";
|
||||
import { Gallery } from "./components/Gallery";
|
||||
import { Lightbox } from "./components/Lightbox";
|
||||
import { TagCloud } from "./components/TagCloud";
|
||||
import { DuplicateFinder } from "./components/DuplicateFinder";
|
||||
import { Timeline } from "./components/Timeline";
|
||||
import { TitleBar } from "./components/TitleBar";
|
||||
import { SettingsModal } from "./components/SettingsModal";
|
||||
import { FolderPickerModal } from "./components/FolderPickerModal";
|
||||
import { UpdateToast } from "./components/UpdateToast";
|
||||
import { OnboardingOverlay } from "./components/onboarding/OnboardingOverlay";
|
||||
import { DemoPanel } from "./components/DemoPanel";
|
||||
import { initializeNotifications } from "./notifications";
|
||||
import { useEffect } from 'react'
|
||||
import { useGalleryStore } from './store'
|
||||
import { Sidebar } from './components/Sidebar'
|
||||
import { BackgroundTasks } from './components/BackgroundTasks'
|
||||
import { Toolbar } from './components/Toolbar'
|
||||
import { Gallery } from './components/Gallery'
|
||||
import { Lightbox } from './components/Lightbox'
|
||||
import { ExploreView } from './components/ExploreView'
|
||||
import { DuplicateFinder } from './components/DuplicateFinder'
|
||||
import { Timeline } from './components/Timeline'
|
||||
import { TitleBar } from './components/TitleBar'
|
||||
import { SettingsModal } from './components/SettingsModal'
|
||||
import { FolderPickerModal } from './components/FolderPickerModal'
|
||||
import { UpdateToast } from './components/UpdateToast'
|
||||
import { WhatsNewToast } from './components/WhatsNewToast'
|
||||
import { WhatsNewModal } from './components/WhatsNewModal'
|
||||
import { OnboardingOverlay } from './components/onboarding/OnboardingOverlay'
|
||||
import { DemoPanel } from './components/DemoPanel'
|
||||
import { initializeNotifications } from './notifications'
|
||||
|
||||
export default function App() {
|
||||
const loadFolders = useGalleryStore((state) => state.loadFolders);
|
||||
const loadBackgroundJobProgress = useGalleryStore((state) => state.loadBackgroundJobProgress);
|
||||
const loadImages = useGalleryStore((state) => state.loadImages);
|
||||
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus);
|
||||
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache);
|
||||
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds);
|
||||
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused);
|
||||
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress);
|
||||
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion);
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates);
|
||||
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus);
|
||||
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
const loadFolders = useGalleryStore((state) => state.loadFolders)
|
||||
const loadBackgroundJobProgress = useGalleryStore((state) => state.loadBackgroundJobProgress)
|
||||
const loadImages = useGalleryStore((state) => state.loadImages)
|
||||
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus)
|
||||
const loadTaggerModelStatus = useGalleryStore((state) => state.loadTaggerModelStatus)
|
||||
const loadTaggerModel = useGalleryStore((state) => state.loadTaggerModel)
|
||||
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache)
|
||||
const loadAlbums = useGalleryStore((state) => state.loadAlbums)
|
||||
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds)
|
||||
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused)
|
||||
const loadWorkerPausesPersist = useGalleryStore((state) => state.loadWorkerPausesPersist)
|
||||
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress)
|
||||
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion)
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates)
|
||||
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus)
|
||||
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted)
|
||||
const initWhatsNew = useGalleryStore((state) => state.initWhatsNew)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
|
||||
useEffect(() => {
|
||||
void initializeNotifications();
|
||||
void loadMutedFolderIds();
|
||||
void loadNotificationsPaused();
|
||||
void loadAppVersion();
|
||||
void loadFfmpegStatus();
|
||||
void loadOnboardingCompleted();
|
||||
void initializeNotifications()
|
||||
void loadMutedFolderIds()
|
||||
void loadNotificationsPaused()
|
||||
void loadWorkerPausesPersist()
|
||||
void loadFfmpegStatus()
|
||||
void loadOnboardingCompleted()
|
||||
// Load the app version first so the What's New toast/modal (which read
|
||||
// appVersion from the store) have it before the greeting can appear.
|
||||
void loadAppVersion().then(() => initWhatsNew())
|
||||
// Quiet launch check — dev builds have no signed artifacts to update to.
|
||||
if (import.meta.env.PROD) {
|
||||
void checkForUpdates({ quiet: true });
|
||||
void checkForUpdates({ quiet: true })
|
||||
}
|
||||
loadFolders().then(() => {
|
||||
void loadBackgroundJobProgress();
|
||||
void loadCaptionModelStatus();
|
||||
void loadDuplicateScanCache();
|
||||
return loadImages(true);
|
||||
});
|
||||
let unlisten: (() => void) | undefined;
|
||||
loadFolders().then(async () => {
|
||||
void loadBackgroundJobProgress()
|
||||
void loadCaptionModelStatus()
|
||||
void loadTaggerModel()
|
||||
void loadTaggerModelStatus()
|
||||
void loadDuplicateScanCache()
|
||||
await loadAlbums()
|
||||
await loadImages(true)
|
||||
if (import.meta.env.MODE === 'ui') {
|
||||
const { applyMockScenario } = await import('./dev/applyMockScenario')
|
||||
applyMockScenario()
|
||||
}
|
||||
})
|
||||
let unlisten: (() => void) | undefined
|
||||
subscribeToProgress().then((fn) => {
|
||||
unlisten = fn;
|
||||
});
|
||||
unlisten = fn
|
||||
})
|
||||
return () => {
|
||||
unlisten?.();
|
||||
};
|
||||
}, []);
|
||||
unlisten?.()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-gray-950 text-white overflow-hidden select-none">
|
||||
<div className="flex h-screen flex-col overflow-hidden bg-gray-950 text-white select-none">
|
||||
{/* Custom title bar — sits at the very top */}
|
||||
<TitleBar />
|
||||
|
||||
{/* Main app content below the title bar */}
|
||||
<div className="flex flex-1 min-h-0">
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<Sidebar />
|
||||
<main className="flex-1 flex flex-col min-w-0">
|
||||
{activeView === "timeline" ? (
|
||||
<main className="flex min-w-0 flex-1 flex-col">
|
||||
{activeView === 'timeline' ? (
|
||||
<>
|
||||
<Toolbar />
|
||||
<BackgroundTasks />
|
||||
<Timeline />
|
||||
</>
|
||||
) : activeView === "explore" ? (
|
||||
) : activeView === 'explore' ? (
|
||||
<>
|
||||
<BackgroundTasks />
|
||||
<TagCloud />
|
||||
<ExploreView />
|
||||
</>
|
||||
) : activeView === "duplicates" ? (
|
||||
) : activeView === 'duplicates' ? (
|
||||
<>
|
||||
<BackgroundTasks />
|
||||
<DuplicateFinder />
|
||||
@@ -96,8 +113,10 @@ export default function App() {
|
||||
<SettingsModal />
|
||||
<FolderPickerModal />
|
||||
<UpdateToast />
|
||||
<WhatsNewToast />
|
||||
<WhatsNewModal />
|
||||
<OnboardingOverlay />
|
||||
{import.meta.env.DEV && <DemoPanel />}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
// Parses the project CHANGELOG.md (imported raw at build time) into structured
|
||||
// data so the "What's New" UI can render it nicely instead of dumping markdown.
|
||||
// Keeping the changelog as the single source of truth means there's no separate
|
||||
// per-release copy to maintain — whatever ships in CHANGELOG.md is what users see.
|
||||
import changelogRaw from '../CHANGELOG.md?raw'
|
||||
|
||||
export interface ChangelogItem {
|
||||
/** The bold lead-in at the start of a bullet (e.g. "Custom multi-folder picker"), if any. */
|
||||
lead: string | null
|
||||
/** The remaining descriptive text. May still contain inline `code` / **bold** markers. */
|
||||
body: string
|
||||
}
|
||||
|
||||
export interface ChangelogSection {
|
||||
/** "Added" | "Changed" | "Fixed" | "Removed" | "Deprecated" | "Security" */
|
||||
title: string
|
||||
items: ChangelogItem[]
|
||||
}
|
||||
|
||||
export interface ChangelogEntry {
|
||||
version: string
|
||||
date: string | null
|
||||
sections: ChangelogSection[]
|
||||
}
|
||||
|
||||
// "## [0.1.1] — 2026-06-23" / "## [Unreleased]"
|
||||
const VERSION_HEADING = /^##\s+\[([^\]]+)\]\s*(?:[—–-]\s*(.+?)\s*)?$/
|
||||
// "### Added"
|
||||
const SECTION_HEADING = /^###\s+(.+?)\s*$/
|
||||
// "- bullet text"
|
||||
const BULLET = /^[-*]\s+(.*)$/
|
||||
// Leading "**Title**" optionally followed by an em dash, used as the item's lead-in.
|
||||
// (Item text is whitespace-collapsed before matching, so no dotAll flag needed.)
|
||||
const LEAD = /^\*\*(.+?)\*\*\s*(?:[—–-]\s*)?(.*)$/
|
||||
|
||||
function toItem(text: string): ChangelogItem {
|
||||
const collapsed = text.replace(/\s+/g, ' ').trim()
|
||||
const match = collapsed.match(LEAD)
|
||||
if (match) {
|
||||
return { lead: match[1].trim(), body: match[2].trim() }
|
||||
}
|
||||
return { lead: null, body: collapsed }
|
||||
}
|
||||
|
||||
function parseChangelog(raw: string): ChangelogEntry[] {
|
||||
const lines = raw.split(/\r?\n/)
|
||||
const entries: ChangelogEntry[] = []
|
||||
|
||||
let entry: ChangelogEntry | null = null
|
||||
let section: ChangelogSection | null = null
|
||||
let buffer: string[] = []
|
||||
|
||||
const flushItem = () => {
|
||||
if (section && buffer.length > 0) {
|
||||
section.items.push(toItem(buffer.join(' ')))
|
||||
}
|
||||
buffer = []
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const versionMatch = line.match(VERSION_HEADING)
|
||||
if (versionMatch) {
|
||||
flushItem()
|
||||
section = null
|
||||
entry = {
|
||||
version: versionMatch[1].trim(),
|
||||
date: versionMatch[2]?.trim() ?? null,
|
||||
sections: [],
|
||||
}
|
||||
entries.push(entry)
|
||||
continue
|
||||
}
|
||||
|
||||
// Stop collecting once we leave the changelog body (e.g. link-reference defs at EOF).
|
||||
if (!entry) continue
|
||||
|
||||
const sectionMatch = line.match(SECTION_HEADING)
|
||||
if (sectionMatch) {
|
||||
flushItem()
|
||||
section = { title: sectionMatch[1].trim(), items: [] }
|
||||
entry.sections.push(section)
|
||||
continue
|
||||
}
|
||||
|
||||
const bulletMatch = line.match(BULLET)
|
||||
if (bulletMatch) {
|
||||
flushItem()
|
||||
buffer.push(bulletMatch[1])
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.trim() === '') {
|
||||
// A blank line ends a (possibly wrapped) multi-line bullet.
|
||||
flushItem()
|
||||
continue
|
||||
}
|
||||
|
||||
// Indented continuation of the current wrapped bullet.
|
||||
if (buffer.length > 0) {
|
||||
buffer.push(line.trim())
|
||||
}
|
||||
}
|
||||
|
||||
flushItem()
|
||||
return entries.map((e) => ({ ...e, sections: e.sections.filter((s) => s.items.length > 0) }))
|
||||
}
|
||||
|
||||
const ENTRIES = parseChangelog(changelogRaw)
|
||||
|
||||
// Synthetic small release for UI Lab (`?changelog=small`). The What's New modal
|
||||
// switches layout by release size, and every real entry in CHANGELOG.md is
|
||||
// large — so the compact single-column layout can't be exercised from real
|
||||
// data. This stays below the modal's rail threshold on purpose.
|
||||
const SMALL_PREVIEW_ENTRY: ChangelogEntry = {
|
||||
version: '0.0.0-preview',
|
||||
date: '2026-01-01',
|
||||
sections: [
|
||||
{
|
||||
title: 'Added',
|
||||
items: [
|
||||
{
|
||||
lead: 'Sample setting',
|
||||
body: 'a small toggle that exists purely so this preview has an Added section.',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Changed',
|
||||
items: [
|
||||
{
|
||||
lead: 'Snappier previews',
|
||||
body: 'the preview fixture now loads instantly, because it is made up.',
|
||||
},
|
||||
{ lead: null, body: 'A plain full-sentence bullet without a bold lead, for coverage.' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Fixed',
|
||||
items: [
|
||||
{
|
||||
lead: 'Hotfix-sized fix',
|
||||
body: 'a believable one-liner about a bug that never shipped.',
|
||||
},
|
||||
{
|
||||
lead: 'Another small fix',
|
||||
body: 'keeps the total item count comfortably under the rail threshold.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
// UI Lab affordance (browser-only `ui` mode): `?changelog=` previews an entry
|
||||
// other than the running version's, mirroring the `?scenario=` pattern.
|
||||
// ?changelog=unreleased — the in-progress [Unreleased] notes (large release)
|
||||
// ?changelog=small — synthetic hotfix-sized entry (compact layout)
|
||||
// ?changelog=0.1.1 — any specific released version
|
||||
function previewOverride(): ChangelogEntry | null {
|
||||
if (import.meta.env.MODE !== 'ui') return null
|
||||
const preview = new URLSearchParams(window.location.search).get('changelog')
|
||||
if (!preview) return null
|
||||
if (preview === 'small') return SMALL_PREVIEW_ENTRY
|
||||
return ENTRIES.find((e) => e.version.toLowerCase() === preview.toLowerCase()) ?? null
|
||||
}
|
||||
|
||||
export function getChangelogForVersion(version: string | null | undefined): ChangelogEntry | null {
|
||||
const override = previewOverride()
|
||||
if (override) return override
|
||||
if (!version) return null
|
||||
// Strip leading "v" and any build suffix (e.g. "-ui", "-dev", "-beta.1") so
|
||||
// dev/UI-lab builds still resolve to the correct changelog entry.
|
||||
const normalized = version.replace(/^v/, '').replace(/-[a-z].*/i, '')
|
||||
// Never surface the in-progress [Unreleased] section to users.
|
||||
if (normalized.toLowerCase() === 'unreleased') return null
|
||||
return ENTRIES.find((e) => e.version.replace(/^v/, '') === normalized) ?? null
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
|
||||
/**
|
||||
* Album list plus a create-new-album form. The host decides what picking
|
||||
* means — the bulk bar adds the current selection; a newly created album is
|
||||
* picked immediately.
|
||||
*/
|
||||
export function AlbumPicker({ onPick }: { onPick: (albumId: number) => Promise<void> | void }) {
|
||||
const albums = useGalleryStore((state) => state.albums)
|
||||
const createAlbum = useGalleryStore((state) => state.createAlbum)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newAlbumName, setNewAlbumName] = useState('')
|
||||
|
||||
const handleCreate = async () => {
|
||||
const name = newAlbumName.trim()
|
||||
if (!name || creating) return
|
||||
setCreating(true)
|
||||
try {
|
||||
const album = await createAlbum(name)
|
||||
setNewAlbumName('')
|
||||
await onPick(album.id)
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="max-h-48 overflow-y-auto">
|
||||
{albums.length === 0 ? (
|
||||
<p className="px-2 py-2 text-[11px] text-gray-600">No albums yet — create one below.</p>
|
||||
) : (
|
||||
albums.map((album) => (
|
||||
<button
|
||||
key={album.id}
|
||||
className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
|
||||
onClick={() => void onPick(album.id)}
|
||||
>
|
||||
<span className="truncate">{album.name}</span>
|
||||
<span className="shrink-0 text-[10px] text-gray-600">{album.image_count}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className="mt-1 flex gap-1 border-t border-white/[0.06] pt-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void handleCreate()
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className="min-w-0 flex-1 rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-white placeholder-gray-600 focus:border-white/20 focus:outline-none"
|
||||
placeholder="New album…"
|
||||
value={newAlbumName}
|
||||
onChange={(event) => setNewAlbumName(event.target.value)}
|
||||
disabled={creating}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-50"
|
||||
disabled={creating || !newAlbumName.trim()}
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,589 +1,155 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { revealItemInDir } from "@tauri-apps/plugin-opener";
|
||||
import { useGalleryStore, WorkerKey } from "../store";
|
||||
|
||||
const WORKER_FOR_STAGE: Record<string, WorkerKey> = {
|
||||
Thumbnails: "thumbnail",
|
||||
Metadata: "metadata",
|
||||
Embeddings: "embedding",
|
||||
Tags: "tagging",
|
||||
};
|
||||
|
||||
interface TaskStage {
|
||||
label: string;
|
||||
detail: string;
|
||||
progress: number | null; // 0–100, or null for indeterminate
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
interface Task {
|
||||
id: number;
|
||||
name: string;
|
||||
stages: TaskStage[];
|
||||
hasFailedEmbeddings: boolean;
|
||||
hasFailedTagging: boolean;
|
||||
hasFailedCaptions: boolean;
|
||||
pendingMediaWork: number;
|
||||
embeddingProcessed: number;
|
||||
embeddingTotal: number;
|
||||
currentFile: string | null;
|
||||
snapshot: string;
|
||||
}
|
||||
|
||||
interface FailedWorkerItem {
|
||||
image_id: number;
|
||||
filename: string;
|
||||
path: string;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
function FailedWorkerItemRow({ item }: { item: FailedWorkerItem }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-start gap-1.5">
|
||||
<svg className="mt-px h-2.5 w-2.5 shrink-0 text-amber-500 light-theme:text-amber-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5}
|
||||
d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||
</svg>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-[10px] font-medium text-amber-400/80 light-theme:text-amber-700">{item.filename}</p>
|
||||
{item.error && (
|
||||
<p className="truncate text-[9px] text-gray-600">{item.error}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className="shrink-0 text-gray-700 transition-colors hover:text-gray-300 light-theme:text-gray-600 light-theme:hover:text-gray-100"
|
||||
title="Reveal in Explorer"
|
||||
onClick={() => void revealItemInDir(item.path)}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { useGalleryStore, type WorkerKey } from '../store'
|
||||
import { BackgroundTaskSummary } from './backgroundTasks/BackgroundTaskSummary'
|
||||
import { ExpandedTaskPanel } from './backgroundTasks/ExpandedTaskPanel'
|
||||
import {
|
||||
buildDuplicateScanTask,
|
||||
buildFolderTasks,
|
||||
taskHasTerminalFailure,
|
||||
taskProgress,
|
||||
} from './backgroundTasks/taskModel'
|
||||
import type { BackgroundTask, FailedWorkerItem } from './backgroundTasks/types'
|
||||
|
||||
export function BackgroundTasks() {
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress);
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
|
||||
const retryFailedEmbeddings = useGalleryStore((state) => state.retryFailedEmbeddings);
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs);
|
||||
const showFailedTagging = useGalleryStore((state) => state.showFailedTagging);
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning);
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [dismissed, setDismissed] = useState<Record<number, string>>({});
|
||||
const [failedEmbeddingItems, setFailedEmbeddingItems] = useState<Record<number, FailedWorkerItem[]>>({});
|
||||
const [failedTaggingItems, setFailedTaggingItems] = useState<Record<number, FailedWorkerItem[]>>({});
|
||||
|
||||
const workerPaused = useGalleryStore((state) => state.workerPaused);
|
||||
const loadWorkerStates = useGalleryStore((state) => state.loadWorkerStates);
|
||||
const setWorkerPaused = useGalleryStore((state) => state.setWorkerPaused);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress)
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress)
|
||||
const retryFailedEmbeddings = useGalleryStore((state) => state.retryFailedEmbeddings)
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs)
|
||||
const showFailedTagging = useGalleryStore((state) => state.showFailedTagging)
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning)
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress)
|
||||
const workerPaused = useGalleryStore((state) => state.workerPaused)
|
||||
const loadWorkerStates = useGalleryStore((state) => state.loadWorkerStates)
|
||||
const setWorkerPaused = useGalleryStore((state) => state.setWorkerPaused)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [dismissed, setDismissed] = useState<Record<number, string>>({})
|
||||
const [failedEmbeddingItems, setFailedEmbeddingItems] = useState<
|
||||
Record<number, FailedWorkerItem[]>
|
||||
>({})
|
||||
const [failedTaggingItems, setFailedTaggingItems] = useState<Record<number, FailedWorkerItem[]>>(
|
||||
{}
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void loadWorkerStates();
|
||||
}, [folders, loadWorkerStates]);
|
||||
void loadWorkerStates()
|
||||
}, [folders, loadWorkerStates])
|
||||
|
||||
// Fetch failed filenames whenever the expanded panel opens or failure counts change.
|
||||
const failedEmbeddingCounts = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(mediaJobProgress).map(([id, p]) => [id, p?.embedding_failed ?? 0]),
|
||||
Object.entries(mediaJobProgress).map(([id, progress]) => [
|
||||
id,
|
||||
progress?.embedding_failed ?? 0,
|
||||
])
|
||||
),
|
||||
[mediaJobProgress],
|
||||
);
|
||||
[mediaJobProgress]
|
||||
)
|
||||
const failedTaggingCounts = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(mediaJobProgress).map(([id, p]) => [id, p?.tagging_failed ?? 0]),
|
||||
Object.entries(mediaJobProgress).map(([id, progress]) => [
|
||||
id,
|
||||
progress?.tagging_failed ?? 0,
|
||||
])
|
||||
),
|
||||
[mediaJobProgress],
|
||||
);
|
||||
[mediaJobProgress]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!expanded) return;
|
||||
if (!expanded) return
|
||||
for (const [folderId, count] of Object.entries(failedEmbeddingCounts)) {
|
||||
if (count > 0) {
|
||||
invoke<FailedWorkerItem[]>("get_failed_embedding_images", {
|
||||
invoke<FailedWorkerItem[]>('get_failed_embedding_images', {
|
||||
folderId: Number(folderId),
|
||||
})
|
||||
.then((items) => setFailedEmbeddingItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined);
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
for (const [folderId, count] of Object.entries(failedTaggingCounts)) {
|
||||
if (count > 0) {
|
||||
invoke<FailedWorkerItem[]>("get_failed_tagging_images", {
|
||||
invoke<FailedWorkerItem[]>('get_failed_tagging_images', {
|
||||
folderId: Number(folderId),
|
||||
})
|
||||
.then((items) => setFailedTaggingItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined);
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}, [expanded, failedEmbeddingCounts, failedTaggingCounts]);
|
||||
}, [expanded, failedEmbeddingCounts, failedTaggingCounts])
|
||||
|
||||
const isWorkerPaused = (folderId: number, worker: WorkerKey) => {
|
||||
return workerPaused[folderId]?.[worker] ?? false;
|
||||
};
|
||||
const folderTasks = useMemo(
|
||||
() =>
|
||||
buildFolderTasks({
|
||||
dismissed,
|
||||
folders,
|
||||
indexingProgress,
|
||||
mediaJobProgress,
|
||||
workerPaused,
|
||||
}),
|
||||
[dismissed, folders, indexingProgress, mediaJobProgress, workerPaused]
|
||||
)
|
||||
|
||||
const duplicateScanTask = useMemo(
|
||||
() => buildDuplicateScanTask(duplicateScanning, duplicateScanProgress),
|
||||
[duplicateScanning, duplicateScanProgress]
|
||||
)
|
||||
const allTasks = duplicateScanTask ? [duplicateScanTask, ...folderTasks] : folderTasks
|
||||
|
||||
if (allTasks.length === 0) return null
|
||||
|
||||
const isWorkerPaused = (folderId: number, worker: WorkerKey) =>
|
||||
workerPaused[folderId]?.[worker] ?? false
|
||||
|
||||
const toggleWorker = (folderId: number, worker: WorkerKey) => {
|
||||
setWorkerPaused(folderId, worker, !isWorkerPaused(folderId, worker));
|
||||
};
|
||||
setWorkerPaused(folderId, worker, !isWorkerPaused(folderId, worker))
|
||||
}
|
||||
|
||||
const dismissTask = (id: number, snapshot: string) => {
|
||||
if (id < 0) return; // system tasks (duplicate scan) cannot be dismissed
|
||||
setDismissed((prev) => ({ ...prev, [id]: snapshot }));
|
||||
setExpanded(false);
|
||||
};
|
||||
const dismissTask = (task: BackgroundTask) => {
|
||||
if (task.id < 0) return
|
||||
setDismissed((prev) => ({ ...prev, [task.id]: task.snapshot }))
|
||||
setExpanded(false)
|
||||
}
|
||||
|
||||
const tasks = useMemo<Task[]>(() => {
|
||||
return folders
|
||||
.map((folder): Task | null => {
|
||||
const index = indexingProgress[folder.id];
|
||||
const jobs = mediaJobProgress[folder.id];
|
||||
const retryTask = (task: BackgroundTask) => {
|
||||
if (task.hasFailedEmbeddings) void retryFailedEmbeddings(task.id)
|
||||
if (task.hasFailedTagging) void queueTaggingJobs(task.id)
|
||||
}
|
||||
|
||||
const thumbnailPending = jobs?.thumbnail_pending ?? 0;
|
||||
const metadataPending = jobs?.metadata_pending ?? 0;
|
||||
const embeddingPending = jobs?.embedding_pending ?? 0;
|
||||
const embeddingReady = jobs?.embedding_ready ?? 0;
|
||||
const embeddingFailed = jobs?.embedding_failed ?? 0;
|
||||
const taggingPending = jobs?.tagging_pending ?? 0;
|
||||
const taggingReady = jobs?.tagging_ready ?? 0;
|
||||
const taggingFailed = jobs?.tagging_failed ?? 0;
|
||||
const captionPending = jobs?.caption_pending ?? 0;
|
||||
const captionReady = jobs?.caption_ready ?? 0;
|
||||
const captionFailed = jobs?.caption_failed ?? 0;
|
||||
|
||||
const pendingMediaWork = thumbnailPending + metadataPending + embeddingPending + taggingPending + captionPending;
|
||||
const embeddingProcessed = embeddingReady + embeddingFailed;
|
||||
const embeddingTotal = embeddingProcessed + embeddingPending;
|
||||
const taggingProcessed = taggingReady + taggingFailed;
|
||||
const taggingTotal = taggingProcessed + taggingPending;
|
||||
const captionProcessed = captionReady + captionFailed;
|
||||
const captionTotal = captionProcessed + captionPending;
|
||||
const hasFailedEmbeddings = embeddingFailed > 0;
|
||||
const hasFailedTagging = taggingFailed > 0;
|
||||
const hasFailedCaptions = captionFailed > 0;
|
||||
|
||||
if (!index && pendingMediaWork === 0 && !hasFailedEmbeddings && !hasFailedTagging && !hasFailedCaptions) return null;
|
||||
|
||||
const stages: TaskStage[] = [];
|
||||
|
||||
if (index && !index.done) {
|
||||
const pct = index.total > 0 ? (index.indexed / index.total) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Scanning",
|
||||
detail: `${index.indexed.toLocaleString()} / ${index.total.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (thumbnailPending > 0) {
|
||||
stages.push({
|
||||
label: "Thumbnails",
|
||||
detail: thumbnailPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (metadataPending > 0) {
|
||||
stages.push({
|
||||
label: "Metadata",
|
||||
detail: metadataPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (embeddingPending > 0) {
|
||||
const pct = embeddingTotal > 0 ? (embeddingProcessed / embeddingTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Embeddings",
|
||||
detail: `${embeddingProcessed.toLocaleString()} / ${embeddingTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (taggingPending > 0) {
|
||||
const pct = taggingTotal > 0 ? (taggingProcessed / taggingTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Tags",
|
||||
detail: `${taggingProcessed.toLocaleString()} / ${taggingTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (captionPending > 0) {
|
||||
const pct = captionTotal > 0 ? (captionProcessed / captionTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Captions",
|
||||
detail: `${captionProcessed.toLocaleString()} / ${captionTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedEmbeddings && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${embeddingFailed.toLocaleString()} embeddings`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedTagging && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${taggingFailed.toLocaleString()} tags`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedCaptions && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${captionFailed.toLocaleString()} captions`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
const snapshot = `${pendingMediaWork}:${embeddingFailed}:${taggingFailed}:${captionFailed}`;
|
||||
|
||||
return {
|
||||
id: folder.id,
|
||||
name: folder.name,
|
||||
stages,
|
||||
hasFailedEmbeddings,
|
||||
hasFailedTagging,
|
||||
hasFailedCaptions,
|
||||
pendingMediaWork,
|
||||
embeddingProcessed,
|
||||
embeddingTotal,
|
||||
currentFile: index && !index.done ? (index.current_file || null) : null,
|
||||
snapshot,
|
||||
};
|
||||
})
|
||||
.filter((t): t is Task => t !== null)
|
||||
.filter((t) => dismissed[t.id] !== t.snapshot);
|
||||
}, [folders, indexingProgress, mediaJobProgress, dismissed]);
|
||||
|
||||
// Synthetic task for duplicate scanning — negative id so dismiss/retry are suppressed
|
||||
const duplicateScanTask: Task | null = duplicateScanning ? {
|
||||
id: -1,
|
||||
name: "Duplicate Scan",
|
||||
stages: [{
|
||||
label: duplicateScanProgress?.phase === "checking"
|
||||
? "Checking"
|
||||
: duplicateScanProgress?.phase === "confirming"
|
||||
? "Confirming"
|
||||
: "Hashing",
|
||||
detail: duplicateScanProgress
|
||||
? `${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ""}`
|
||||
: "Starting…",
|
||||
progress: duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? (duplicateScanProgress.processed / duplicateScanProgress.total) * 100
|
||||
: null,
|
||||
failed: false,
|
||||
}],
|
||||
hasFailedEmbeddings: false,
|
||||
hasFailedTagging: false,
|
||||
hasFailedCaptions: false,
|
||||
pendingMediaWork: 1,
|
||||
embeddingProcessed: 0,
|
||||
embeddingTotal: 0,
|
||||
currentFile: null,
|
||||
snapshot: "",
|
||||
} : null;
|
||||
|
||||
const allTasks = duplicateScanTask ? [duplicateScanTask, ...tasks] : tasks;
|
||||
|
||||
if (allTasks.length === 0) return null;
|
||||
|
||||
const primary = allTasks[0];
|
||||
const extraCount = allTasks.length - 1;
|
||||
const hasFailed = tasks.some((t) => (t.hasFailedEmbeddings || t.hasFailedTagging || t.hasFailedCaptions) && t.pendingMediaWork === 0);
|
||||
|
||||
// Best progress bar value: use embedding progress if available (most informative),
|
||||
// otherwise tagging progress, otherwise fall back to scanning progress, otherwise indeterminate.
|
||||
const embeddingStage = primary.stages.find((s) => s.label === "Embeddings");
|
||||
const taggingStage = primary.stages.find((s) => s.label === "Tags");
|
||||
const scanningStage = primary.stages.find((s) => s.label === "Scanning");
|
||||
const duplicateStage = primary.id === -1 ? primary.stages[0] : null;
|
||||
const barProgress = embeddingStage?.progress ?? taggingStage?.progress ?? scanningStage?.progress ?? duplicateStage?.progress ?? null;
|
||||
const primary = allTasks[0]
|
||||
const hasFailed = folderTasks.some(taskHasTerminalFailure)
|
||||
const barProgress = taskProgress(primary)
|
||||
|
||||
return (
|
||||
<div className="shrink-0 border-b border-white/[0.06]">
|
||||
{/* Slim bar */}
|
||||
<div
|
||||
className={`group flex items-center gap-3 px-5 h-11 cursor-pointer select-none transition-colors ${
|
||||
expanded ? "bg-white/[0.03]" : "hover:bg-white/[0.02]"
|
||||
}`}
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
>
|
||||
{/* Pulse dot */}
|
||||
<div className="relative shrink-0">
|
||||
<div className={`h-1.5 w-1.5 rounded-full ${hasFailed ? "bg-amber-400" : "bg-blue-400"}`} />
|
||||
<div className={`absolute inset-0 h-1.5 w-1.5 rounded-full animate-ping opacity-60 ${hasFailed ? "bg-amber-400" : "bg-blue-400"}`} />
|
||||
</div>
|
||||
<BackgroundTaskSummary
|
||||
expanded={expanded}
|
||||
extraCount={allTasks.length - 1}
|
||||
hasFailed={hasFailed}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onDismiss={dismissTask}
|
||||
onLocate={showFailedTagging}
|
||||
onRetry={retryTask}
|
||||
onToggleExpanded={() => setExpanded((value) => !value)}
|
||||
onToggleWorker={toggleWorker}
|
||||
primary={primary}
|
||||
progress={barProgress}
|
||||
taskCount={allTasks.length}
|
||||
/>
|
||||
|
||||
{/* Folder name */}
|
||||
<span className="text-[13px] font-medium text-white/60 shrink-0">{primary.name}</span>
|
||||
|
||||
{/* Stage tags — all active stages visible simultaneously */}
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0 overflow-hidden">
|
||||
{primary.stages.map((stage) => {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label];
|
||||
const isPaused = workerKey ? isWorkerPaused(primary.id, workerKey) : false;
|
||||
return (
|
||||
<span
|
||||
key={stage.label}
|
||||
className={`flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] shrink-0 ${
|
||||
stage.failed
|
||||
? "bg-amber-500/10 text-amber-400 light-theme:border light-theme:border-amber-500/40 light-theme:bg-amber-100 light-theme:text-amber-700"
|
||||
: isPaused
|
||||
? "bg-white/4 text-gray-600"
|
||||
: "bg-white/5 text-gray-400"
|
||||
}`}
|
||||
>
|
||||
<span>{stage.label}</span>
|
||||
<span className={`tabular-nums ${stage.failed ? "text-amber-500 light-theme:text-amber-700" : isPaused ? "text-gray-700" : "text-gray-600"}`}>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey && (
|
||||
<button
|
||||
className="ml-0.5 opacity-0 group-hover:opacity-100 hover:text-white transition-opacity"
|
||||
title={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); toggleWorker(primary.id, workerKey); }}
|
||||
>
|
||||
{isPaused ? (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Progress bar — embedding or scanning progress, pulsing if indeterminate */}
|
||||
<div className="w-24 h-px bg-white/8 rounded-full overflow-hidden shrink-0">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
hasFailed
|
||||
? "bg-amber-400/60"
|
||||
: barProgress === null
|
||||
? "bg-blue-500/40 animate-pulse w-full"
|
||||
: "bg-blue-500"
|
||||
}`}
|
||||
style={barProgress !== null ? { width: `${barProgress}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Extra folders badge */}
|
||||
{extraCount > 0 && (
|
||||
<span className="rounded-full bg-white/8 px-2 py-0.5 text-[10px] text-gray-500 shrink-0">
|
||||
+{extraCount}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{primary.pendingMediaWork === 0 && (primary.hasFailedEmbeddings || primary.hasFailedTagging) && (
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{primary.hasFailedTagging ? (
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={(e) => { e.stopPropagation(); showFailedTagging(primary.id); }}
|
||||
>
|
||||
Locate
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (primary.hasFailedEmbeddings) void retryFailedEmbeddings(primary.id);
|
||||
if (primary.hasFailedTagging) void queueTaggingJobs(primary.id);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Expand chevron (only when multiple tasks) */}
|
||||
{allTasks.length > 1 && (
|
||||
<svg
|
||||
className={`h-3.5 w-3.5 text-gray-600 transition-transform duration-200 shrink-0 ${expanded ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
)}
|
||||
|
||||
{/* Dismiss — hidden for system tasks like duplicate scan */}
|
||||
{primary.id >= 0 && (
|
||||
<button
|
||||
className="p-1 rounded-md text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors shrink-0"
|
||||
title="Dismiss"
|
||||
onClick={(e) => { e.stopPropagation(); dismissTask(primary.id, primary.snapshot); }}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expanded panel — one row per folder */}
|
||||
{expanded && (
|
||||
<div className="border-t border-white/[0.06] bg-white/[0.02] px-5 py-3 space-y-3">
|
||||
{allTasks.map((task) => {
|
||||
const taskEmbeddingStage = task.stages.find((s) => s.label === "Embeddings");
|
||||
const taskTaggingStage = task.stages.find((s) => s.label === "Tags");
|
||||
const taskScanningStage = task.stages.find((s) => s.label === "Scanning");
|
||||
const taskDuplicateStage = task.id === -1 ? task.stages[0] : null;
|
||||
const taskBarProgress = taskEmbeddingStage?.progress ?? taskTaggingStage?.progress ?? taskScanningStage?.progress ?? taskDuplicateStage?.progress ?? null;
|
||||
const taskHasFailed = (task.hasFailedEmbeddings || task.hasFailedTagging || task.hasFailedCaptions) && task.pendingMediaWork === 0;
|
||||
|
||||
return (
|
||||
<div key={task.id}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-[12px] text-white/50 w-28 truncate shrink-0">{task.name}</span>
|
||||
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0 overflow-hidden">
|
||||
{task.stages.map((stage) => {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label];
|
||||
const isPaused = workerKey ? isWorkerPaused(task.id, workerKey) : false;
|
||||
return (
|
||||
<span
|
||||
key={stage.label}
|
||||
className={`flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] shrink-0 ${
|
||||
stage.failed
|
||||
? "bg-amber-500/10 text-amber-400 light-theme:border light-theme:border-amber-500/40 light-theme:bg-amber-100 light-theme:text-amber-700"
|
||||
: isPaused
|
||||
? "bg-white/4 text-gray-600"
|
||||
: "bg-white/5 text-gray-500"
|
||||
}`}
|
||||
>
|
||||
{isPaused && (
|
||||
<svg className="h-2 w-2 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
<span>{stage.label}</span>
|
||||
<span className={`tabular-nums ${stage.failed ? "text-amber-500 light-theme:text-amber-700" : "text-gray-600"}`}>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey && (
|
||||
<button
|
||||
className="ml-0.5 text-gray-600 hover:text-white transition-colors"
|
||||
title={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`}
|
||||
onClick={() => toggleWorker(task.id, workerKey)}
|
||||
>
|
||||
{isPaused ? (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-20 h-px bg-white/8 rounded-full overflow-hidden shrink-0">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
taskHasFailed
|
||||
? "bg-amber-400/60"
|
||||
: taskBarProgress === null
|
||||
? "bg-blue-500/40 animate-pulse w-full"
|
||||
: "bg-blue-500"
|
||||
}`}
|
||||
style={taskBarProgress !== null ? { width: `${taskBarProgress}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{taskHasFailed && (
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{task.hasFailedTagging ? (
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={() => showFailedTagging(task.id)}
|
||||
>
|
||||
Locate
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={() => {
|
||||
if (task.hasFailedEmbeddings) void retryFailedEmbeddings(task.id);
|
||||
if (task.hasFailedTagging) void queueTaggingJobs(task.id);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{task.id >= 0 && (
|
||||
<button
|
||||
className="p-1 rounded-md text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors shrink-0"
|
||||
title="Dismiss"
|
||||
onClick={() => dismissTask(task.id, task.snapshot)}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{task.currentFile && (
|
||||
<p className="text-[10px] text-gray-600 truncate mt-1 pl-[calc(7rem+0.75rem)]">
|
||||
{task.currentFile}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Failed worker file lists */}
|
||||
{taskHasFailed && failedEmbeddingItems[task.id] && failedEmbeddingItems[task.id].length > 0 && (
|
||||
<div className="mt-2 pl-[calc(7rem+0.75rem)] space-y-0.5">
|
||||
{failedEmbeddingItems[task.id].map((item) => (
|
||||
<FailedWorkerItemRow key={item.image_id} item={item} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{taskHasFailed && failedTaggingItems[task.id] && failedTaggingItems[task.id].length > 0 && (
|
||||
<div className="mt-2 pl-[calc(7rem+0.75rem)] space-y-0.5">
|
||||
{failedTaggingItems[task.id].map((item) => (
|
||||
<FailedWorkerItemRow key={item.image_id} item={item} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{expanded ? (
|
||||
<ExpandedTaskPanel
|
||||
failedEmbeddingItems={failedEmbeddingItems}
|
||||
failedTaggingItems={failedTaggingItems}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onDismiss={dismissTask}
|
||||
onLocate={showFailedTagging}
|
||||
onRetry={retryTask}
|
||||
onToggleWorker={toggleWorker}
|
||||
tasks={allTasks}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { BulkAlbumPopover } from './bulk/BulkAlbumPopover'
|
||||
import { BulkDeleteConfirm } from './bulk/BulkDeleteConfirm'
|
||||
import { BulkRatingPopover } from './bulk/BulkRatingPopover'
|
||||
import { BulkSelectionSummary } from './bulk/BulkSelectionSummary'
|
||||
import { BulkTagPopover } from './bulk/BulkTagPopover'
|
||||
import { type BulkPanel } from './bulk/types'
|
||||
import { useDismissable } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
|
||||
export function BulkActionBar() {
|
||||
const selectedCount = useGalleryStore((state) => state.gallerySelectedIds.size)
|
||||
const selectedIds = useGalleryStore((state) => state.gallerySelectedIds)
|
||||
const clearGallerySelection = useGalleryStore((state) => state.clearGallerySelection)
|
||||
const selectAllGallery = useGalleryStore((state) => state.selectAllGallery)
|
||||
const loadedCount = useGalleryStore((state) => state.loadedCount)
|
||||
const totalImages = useGalleryStore((state) => state.totalImages)
|
||||
const bulkSetFavorite = useGalleryStore((state) => state.bulkSetFavorite)
|
||||
const bulkSetRating = useGalleryStore((state) => state.bulkSetRating)
|
||||
const bulkDeleteSelected = useGalleryStore((state) => state.bulkDeleteSelected)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
const selectedAlbumId = useGalleryStore((state) => state.selectedAlbumId)
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum)
|
||||
const removeFromAlbum = useGalleryStore((state) => state.removeFromAlbum)
|
||||
|
||||
const [panel, setPanel] = useState<BulkPanel>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const barRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Close any open popover when clicking outside the bar or pressing Escape.
|
||||
useDismissable(barRef, () => setPanel(null), panel !== null)
|
||||
|
||||
// Reset transient UI whenever the selection empties.
|
||||
useEffect(() => {
|
||||
if (selectedCount === 0) setPanel(null)
|
||||
}, [selectedCount])
|
||||
|
||||
if (selectedCount === 0) return null
|
||||
|
||||
const ids = Array.from(selectedIds)
|
||||
const inAlbumView = activeView === 'album' && selectedAlbumId !== null
|
||||
const togglePanel = (next: Exclude<BulkPanel, null>) =>
|
||||
setPanel((current) => (current === next ? null : next))
|
||||
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true)
|
||||
try {
|
||||
await bulkDeleteSelected()
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
setPanel(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePickAlbum = async (albumId: number) => {
|
||||
await addToAlbum(albumId, ids)
|
||||
setPanel(null)
|
||||
}
|
||||
|
||||
const btn = 'rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors'
|
||||
const btnIdle = `${btn} text-gray-300 hover:bg-white/10 hover:text-white`
|
||||
const btnActive = `${btn} bg-white/10 text-white`
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={barRef}
|
||||
className="pointer-events-auto absolute bottom-6 left-1/2 z-30 flex -translate-x-1/2 items-center gap-1 rounded-xl border border-white/10 bg-gray-950/95 px-2 py-1.5 shadow-2xl shadow-black/50 backdrop-blur"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<BulkSelectionSummary
|
||||
loadedCount={loadedCount}
|
||||
selectedCount={selectedCount}
|
||||
totalImages={totalImages}
|
||||
onSelectAll={selectAllGallery}
|
||||
/>
|
||||
|
||||
<div className="h-5 w-px bg-white/10" />
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
className={panel === 'tag' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('tag')}
|
||||
>
|
||||
Tag
|
||||
</button>
|
||||
{panel === 'tag' ? <BulkTagPopover onClose={() => setPanel(null)} /> : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<button
|
||||
className={panel === 'rating' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('rating')}
|
||||
>
|
||||
Rating
|
||||
</button>
|
||||
{panel === 'rating' ? (
|
||||
<BulkRatingPopover onSetRating={bulkSetRating} onClose={() => setPanel(null)} />
|
||||
) : null}
|
||||
</div>
|
||||
<Tooltip label="Mark as favorite" followCursor>
|
||||
<button className={btnIdle} onClick={() => void bulkSetFavorite(true)}>
|
||||
Favorite
|
||||
</button>
|
||||
</Tooltip>
|
||||
<div className="relative">
|
||||
<button
|
||||
className={panel === 'album' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('album')}
|
||||
>
|
||||
Add to album
|
||||
</button>
|
||||
{panel === 'album' ? <BulkAlbumPopover onPick={handlePickAlbum} /> : null}
|
||||
</div>
|
||||
|
||||
{inAlbumView ? (
|
||||
<button
|
||||
className={`${btn} text-amber-300/90 hover:bg-amber-500/10 hover:text-amber-200`}
|
||||
onClick={() => void removeFromAlbum(selectedAlbumId, ids)}
|
||||
>
|
||||
Remove from album
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
<div className="h-5 w-px bg-white/10" />
|
||||
|
||||
<div className="relative">
|
||||
<Tooltip label="Delete files from disk" followCursor>
|
||||
<button
|
||||
className={
|
||||
panel === 'delete'
|
||||
? `${btn} bg-red-500/15 text-red-300`
|
||||
: `${btn} text-gray-300 hover:bg-red-500/10 hover:text-red-300`
|
||||
}
|
||||
onClick={() => togglePanel('delete')}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? 'Deleting…' : 'Delete'}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{panel === 'delete' ? (
|
||||
<BulkDeleteConfirm
|
||||
deleting={deleting}
|
||||
selectedCount={selectedCount}
|
||||
onCancel={() => setPanel(null)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<Tooltip label="Clear selection" followCursor>
|
||||
<button
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={clearGallerySelection}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { useDismissable } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
type Rgb = [number, number, number]
|
||||
|
||||
// Representative colors for the quick-pick swatches. Each is just an RGB the
|
||||
// distance filter matches against — not a hard bucket.
|
||||
const SWATCHES: { name: string; rgb: Rgb }[] = [
|
||||
{ name: 'Red', rgb: [226, 59, 59] },
|
||||
{ name: 'Orange', rgb: [232, 134, 46] },
|
||||
{ name: 'Yellow', rgb: [242, 207, 46] },
|
||||
{ name: 'Green', rgb: [76, 175, 80] },
|
||||
{ name: 'Teal', rgb: [31, 182, 166] },
|
||||
{ name: 'Blue', rgb: [59, 125, 216] },
|
||||
{ name: 'Purple', rgb: [139, 92, 246] },
|
||||
{ name: 'Pink', rgb: [236, 72, 153] },
|
||||
{ name: 'Brown', rgb: [139, 90, 43] },
|
||||
{ name: 'Black', rgb: [26, 26, 26] },
|
||||
{ name: 'White', rgb: [245, 245, 245] },
|
||||
{ name: 'Gray', rgb: [154, 160, 166] },
|
||||
]
|
||||
|
||||
function rgbEquals(a: Rgb | null, b: Rgb): boolean {
|
||||
return a !== null && a[0] === b[0] && a[1] === b[1] && a[2] === b[2]
|
||||
}
|
||||
|
||||
function toHex([r, g, b]: Rgb): string {
|
||||
return `#${[r, g, b].map((n) => n.toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
function fromHex(hex: string): Rgb {
|
||||
const n = parseInt(hex.slice(1), 16)
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
|
||||
}
|
||||
|
||||
export function ColorFilter() {
|
||||
const colorFilter = useGalleryStore((state) => state.colorFilter)
|
||||
const setColorFilter = useGalleryStore((state) => state.setColorFilter)
|
||||
const colorBackfill = useGalleryStore((state) => state.colorBackfill)
|
||||
const [open, setOpen] = useState(false)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
const isActive = colorFilter !== null
|
||||
const isCustom = isActive && !SWATCHES.some((swatch) => rgbEquals(colorFilter, swatch.rgb))
|
||||
|
||||
// Collapse the panel when clicking elsewhere or pressing Escape.
|
||||
useDismissable(ref, () => setOpen(false), open)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="relative ml-1 flex shrink-0 items-center border-l border-white/6 pl-2"
|
||||
>
|
||||
{/* Trigger — a single palette icon; shows the active color as a dot when a
|
||||
filter is applied so the collapsed state still communicates it. */}
|
||||
<Tooltip
|
||||
label={isActive ? 'Color filter active' : 'Filter by color'}
|
||||
delay={400}
|
||||
anchorToCursor
|
||||
>
|
||||
<button
|
||||
className={`relative flex items-center gap-1.5 rounded-lg px-2 py-1.5 transition-colors ${
|
||||
open || isActive
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:bg-white/5 hover:text-gray-200'
|
||||
}`}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
aria-label="Filter by color"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.6}
|
||||
d="M12 3a9 9 0 100 18c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.39-.61-.39-1 0-.83.67-1.5 1.5-1.5H16a5 5 0 005-5c0-4.42-4.03-8-9-8z"
|
||||
/>
|
||||
<circle cx="7.5" cy="11.5" r="1" fill="currentColor" stroke="none" />
|
||||
<circle cx="11.5" cy="7.5" r="1" fill="currentColor" stroke="none" />
|
||||
<circle cx="15.5" cy="9.5" r="1" fill="currentColor" stroke="none" />
|
||||
</svg>
|
||||
{isActive ? (
|
||||
<span
|
||||
className="h-3 w-3 rounded-full border border-white/30"
|
||||
style={{ backgroundColor: toHex(colorFilter as Rgb) }}
|
||||
/>
|
||||
) : null}
|
||||
</button>
|
||||
</Tooltip>
|
||||
|
||||
<AnimatePresence initial={false}>
|
||||
{open ? (
|
||||
// Right-aligned popover so it never widens the toolbar row or gets
|
||||
// pushed off-screen on narrow windows. Swatches wrap into a compact
|
||||
// grid instead of a single long horizontal strip.
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
exit={{ opacity: 0, y: -4, scale: 0.98 }}
|
||||
transition={{ duration: 0.14, ease: 'easeOut' }}
|
||||
className="light-theme:border-gray-700/50 absolute top-full right-0 z-30 mt-2 w-max rounded-xl border border-white/10 bg-gray-950/98 p-2.5 shadow-2xl backdrop-blur"
|
||||
>
|
||||
<div className="grid grid-cols-7 gap-1.5">
|
||||
{SWATCHES.map((swatch) => {
|
||||
const active = rgbEquals(colorFilter, swatch.rgb)
|
||||
return (
|
||||
<Tooltip label={swatch.name} followCursor>
|
||||
<button
|
||||
key={swatch.name}
|
||||
aria-label={`Filter by ${swatch.name}`}
|
||||
className={`h-5 w-5 shrink-0 rounded-full border transition-transform ${
|
||||
active
|
||||
? 'scale-110 border-white/40 ring-2 ring-white/70'
|
||||
: 'border-white/15 hover:scale-110'
|
||||
}`}
|
||||
style={{ backgroundColor: toHex(swatch.rgb) }}
|
||||
onClick={() => setColorFilter(active ? null : swatch.rgb)}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
<Tooltip label="Custom Colour" followCursor>
|
||||
{/* Custom color picker — rainbow until a custom color is chosen. */}
|
||||
<label
|
||||
className={`relative h-5 w-5 shrink-0 cursor-pointer overflow-hidden rounded-full border ${
|
||||
isCustom
|
||||
? 'border-white/40 ring-2 ring-white/70'
|
||||
: 'border-white/15 hover:scale-110'
|
||||
}`}
|
||||
style={
|
||||
isCustom
|
||||
? { backgroundColor: toHex(colorFilter as Rgb) }
|
||||
: {
|
||||
background:
|
||||
'conic-gradient(red, orange, yellow, lime, cyan, blue, magenta, red)',
|
||||
}
|
||||
}
|
||||
>
|
||||
<input
|
||||
type="color"
|
||||
className="absolute inset-0 cursor-pointer opacity-0"
|
||||
value={colorFilter ? toHex(colorFilter) : '#3b7dd8'}
|
||||
onChange={(event) => setColorFilter(fromHex(event.target.value))}
|
||||
/>
|
||||
</label>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{isActive || (colorBackfill && colorBackfill.total > 0) ? (
|
||||
<div className="light-theme:border-gray-700/40 mt-2 flex items-center justify-between gap-3 border-t border-white/6 pt-2">
|
||||
{colorBackfill && colorBackfill.total > 0 ? (
|
||||
<Tooltip
|
||||
label="Sampling colours from existing thumbnails — colour search fills in as this runs"
|
||||
anchorToCursor
|
||||
>
|
||||
<span className="text-[10px] text-gray-600">
|
||||
sampling {colorBackfill.processed.toLocaleString()}/
|
||||
{colorBackfill.total.toLocaleString()}
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
{isActive ? (
|
||||
<Tooltip label="Clear colour filter" anchorToCursor>
|
||||
<button
|
||||
className="shrink-0 rounded px-1 text-[11px] text-gray-500 transition-colors hover:text-gray-200"
|
||||
onClick={() => setColorFilter(null)}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { FolderJobProgress, useGalleryStore } from "../store";
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { FolderJobProgress, useGalleryStore } from '../store'
|
||||
|
||||
// Dev-only screenshot/demo helper. Injects frozen UI states that are otherwise
|
||||
// too transient (or unreachable) to capture: the background-worker pipeline,
|
||||
@@ -25,7 +25,7 @@ function emptyProgress(folderId: number): FolderJobProgress {
|
||||
tagging_pending: 0,
|
||||
tagging_ready: 0,
|
||||
tagging_failed: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// A believable multi-folder "busy pipeline" — three folders at different stages.
|
||||
@@ -36,55 +36,56 @@ const BUSY_PRESETS: Partial<FolderJobProgress>[] = [
|
||||
{ thumbnail_pending: 11, embedding_pending: 50, tagging_pending: 50 },
|
||||
// Late stage: embeddings done, tagging running.
|
||||
{ embedding_ready: 40, tagging_ready: 18, tagging_pending: 22 },
|
||||
];
|
||||
]
|
||||
|
||||
const DEMO_UPDATE_VERSION = "0.2.0";
|
||||
const DEMO_UPDATE_VERSION = '0.2.0'
|
||||
|
||||
export function DemoPanel() {
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const [open, setOpen] = useState(false);
|
||||
const downloadTimer = useRef<number | null>(null);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const appVersion = useGalleryStore((state) => state.appVersion)
|
||||
const [open, setOpen] = useState(false)
|
||||
const downloadTimer = useRef<number | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey && event.shiftKey && event.key.toLowerCase() === "d") {
|
||||
event.preventDefault();
|
||||
setOpen((value) => !value);
|
||||
if (event.ctrlKey && event.shiftKey && event.key.toLowerCase() === 'd') {
|
||||
event.preventDefault()
|
||||
setOpen((value) => !value)
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [])
|
||||
|
||||
const stopTimer = () => {
|
||||
if (downloadTimer.current !== null) {
|
||||
window.clearInterval(downloadTimer.current);
|
||||
downloadTimer.current = null;
|
||||
window.clearInterval(downloadTimer.current)
|
||||
downloadTimer.current = null
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Stop any running download animation when the panel unmounts.
|
||||
useEffect(() => stopTimer, []);
|
||||
useEffect(() => stopTimer, [])
|
||||
|
||||
const injectBusy = () => {
|
||||
const progress: Record<number, FolderJobProgress> = {};
|
||||
const progress: Record<number, FolderJobProgress> = {}
|
||||
folders.slice(0, BUSY_PRESETS.length).forEach((folder, index) => {
|
||||
progress[folder.id] = { ...emptyProgress(folder.id), ...BUSY_PRESETS[index] };
|
||||
});
|
||||
useGalleryStore.setState({ mediaJobProgress: progress });
|
||||
};
|
||||
progress[folder.id] = { ...emptyProgress(folder.id), ...BUSY_PRESETS[index] }
|
||||
})
|
||||
useGalleryStore.setState({ mediaJobProgress: progress })
|
||||
}
|
||||
|
||||
const injectSingleEmbedding = () => {
|
||||
const folder = folders[0];
|
||||
if (!folder) return;
|
||||
const folder = folders[0]
|
||||
if (!folder) return
|
||||
useGalleryStore.setState({
|
||||
mediaJobProgress: {
|
||||
[folder.id]: { ...emptyProgress(folder.id), embedding_ready: 27, embedding_pending: 23 },
|
||||
},
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
const clear = () => useGalleryStore.setState({ mediaJobProgress: {} });
|
||||
const clear = () => useGalleryStore.setState({ mediaJobProgress: {} })
|
||||
|
||||
// --- Updater flow ---------------------------------------------------------
|
||||
// These drive the real UpdateToast + Settings "About" row. The Install button
|
||||
@@ -92,88 +93,106 @@ export function DemoPanel() {
|
||||
// presentation only — see DemoPanel's header note for the real e2e path.
|
||||
|
||||
const updateAvailable = () => {
|
||||
stopTimer();
|
||||
stopTimer()
|
||||
useGalleryStore.setState({
|
||||
updateStatus: "available",
|
||||
updateStatus: 'available',
|
||||
updateVersion: DEMO_UPDATE_VERSION,
|
||||
updateProgress: null,
|
||||
updateError: null,
|
||||
updateDismissed: false,
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
// Indeterminate pulse, then climb 0 → 100%, then flip to "installing".
|
||||
const simulateDownload = () => {
|
||||
stopTimer();
|
||||
stopTimer()
|
||||
useGalleryStore.setState({
|
||||
updateStatus: "downloading",
|
||||
updateStatus: 'downloading',
|
||||
updateVersion: DEMO_UPDATE_VERSION,
|
||||
updateProgress: null,
|
||||
updateError: null,
|
||||
updateDismissed: false,
|
||||
});
|
||||
let progress = 0;
|
||||
})
|
||||
let progress = 0
|
||||
window.setTimeout(() => {
|
||||
downloadTimer.current = window.setInterval(() => {
|
||||
progress = Math.min(progress + 0.07, 1);
|
||||
useGalleryStore.setState({ updateProgress: progress });
|
||||
progress = Math.min(progress + 0.07, 1)
|
||||
useGalleryStore.setState({ updateProgress: progress })
|
||||
if (progress >= 1) {
|
||||
stopTimer();
|
||||
useGalleryStore.setState({ updateStatus: "installing" });
|
||||
stopTimer()
|
||||
useGalleryStore.setState({ updateStatus: 'installing' })
|
||||
}
|
||||
}, 200);
|
||||
}, 700);
|
||||
};
|
||||
}, 200)
|
||||
}, 700)
|
||||
}
|
||||
|
||||
const updateInstalling = () => {
|
||||
stopTimer();
|
||||
stopTimer()
|
||||
useGalleryStore.setState({
|
||||
updateStatus: "installing",
|
||||
updateStatus: 'installing',
|
||||
updateVersion: DEMO_UPDATE_VERSION,
|
||||
updateProgress: 1,
|
||||
updateDismissed: false,
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
const updateError = () => {
|
||||
stopTimer();
|
||||
stopTimer()
|
||||
useGalleryStore.setState({
|
||||
updateStatus: "error",
|
||||
updateError: "Could not reach the update server (connection timed out).",
|
||||
updateStatus: 'error',
|
||||
updateError: 'Could not reach the update server (connection timed out).',
|
||||
updateDismissed: false,
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
const updateUpToDate = () => {
|
||||
stopTimer();
|
||||
useGalleryStore.setState({ updateStatus: "upToDate", updateVersion: null, updateError: null });
|
||||
};
|
||||
stopTimer()
|
||||
useGalleryStore.setState({ updateStatus: 'upToDate', updateVersion: null, updateError: null })
|
||||
}
|
||||
|
||||
const resetUpdate = () => {
|
||||
stopTimer();
|
||||
stopTimer()
|
||||
useGalleryStore.setState({
|
||||
updateStatus: "idle",
|
||||
updateStatus: 'idle',
|
||||
updateVersion: null,
|
||||
updateProgress: null,
|
||||
updateError: null,
|
||||
updateDismissed: false,
|
||||
});
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
// --- What's New flow ------------------------------------------------------
|
||||
// Drives the post-update greeting without needing a real version change. The
|
||||
// toast + modal pull their content from the bundled changelog for the running
|
||||
// app version, so the current release's notes are what render.
|
||||
|
||||
const showWhatsNewToast = () =>
|
||||
useGalleryStore.setState({
|
||||
whatsNewToast: appVersion ?? DEMO_UPDATE_VERSION,
|
||||
whatsNewOpen: false,
|
||||
})
|
||||
|
||||
const openWhatsNewModal = () =>
|
||||
useGalleryStore.setState({ whatsNewOpen: true, whatsNewToast: null })
|
||||
|
||||
const resetWhatsNew = () => useGalleryStore.setState({ whatsNewOpen: false, whatsNewToast: null })
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const injectBtn =
|
||||
"rounded-md border border-amber-400/30 bg-amber-500/15 px-2 py-1.5 text-left hover:bg-amber-500/25";
|
||||
'rounded-md border border-amber-400/30 bg-amber-500/15 px-2 py-1.5 text-left hover:bg-amber-500/25'
|
||||
const neutralBtn =
|
||||
"rounded-md border border-white/10 bg-white/[0.06] px-2 py-1.5 text-left text-gray-300 hover:bg-white/10";
|
||||
'rounded-md border border-white/10 bg-white/[0.06] px-2 py-1.5 text-left text-gray-300 hover:bg-white/10'
|
||||
|
||||
return (
|
||||
<div className="fixed bottom-4 left-4 z-[100] max-h-[calc(100vh-2rem)] w-56 overflow-y-auto rounded-lg border border-amber-400/40 bg-amber-950/90 p-3 text-xs text-amber-100 shadow-xl backdrop-blur">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<span className="font-semibold uppercase tracking-wide">Demo · Ctrl+Shift+D</span>
|
||||
<span className="font-semibold tracking-wide uppercase">Demo · Ctrl+Shift+D</span>
|
||||
</div>
|
||||
|
||||
<p className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-200/60">Pipeline</p>
|
||||
<p className="mb-1.5 text-[11px] font-semibold tracking-wide text-amber-200/60 uppercase">
|
||||
Pipeline
|
||||
</p>
|
||||
<p className="mb-2 text-[11px] leading-snug text-amber-200/70">
|
||||
Inject a frozen worker-bar state, hide this panel, then screenshot.
|
||||
</p>
|
||||
@@ -191,7 +210,9 @@ export function DemoPanel() {
|
||||
|
||||
<div className="my-3 h-px bg-amber-400/20" />
|
||||
|
||||
<p className="mb-1.5 text-[11px] font-semibold uppercase tracking-wide text-amber-200/60">Update flow</p>
|
||||
<p className="mb-1.5 text-[11px] font-semibold tracking-wide text-amber-200/60 uppercase">
|
||||
Update flow
|
||||
</p>
|
||||
<p className="mb-2 text-[11px] leading-snug text-amber-200/70">
|
||||
Drives the real toast (bottom-right) + Settings → About row. Install is inert here.
|
||||
</p>
|
||||
@@ -215,6 +236,26 @@ export function DemoPanel() {
|
||||
Reset updater state
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="my-3 h-px bg-amber-400/20" />
|
||||
|
||||
<p className="mb-1.5 text-[11px] font-semibold tracking-wide text-amber-200/60 uppercase">
|
||||
What's new
|
||||
</p>
|
||||
<p className="mb-2 text-[11px] leading-snug text-amber-200/70">
|
||||
Post-update greeting for v{appVersion ?? '—'}, sourced from the bundled changelog.
|
||||
</p>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<button className={injectBtn} onClick={showWhatsNewToast}>
|
||||
Show "What's new" toast
|
||||
</button>
|
||||
<button className={injectBtn} onClick={openWhatsNewModal}>
|
||||
Open "What's new" modal
|
||||
</button>
|
||||
<button className={neutralBtn} onClick={resetWhatsNew}>
|
||||
Reset What's New state
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,321 +1,125 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { DuplicateGroup, useGalleryStore } from "../store";
|
||||
import { FolderScopeDropdown } from "./FolderScopeDropdown";
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toFixed(1)} GB`;
|
||||
if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
|
||||
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||
return `${bytes} B`;
|
||||
}
|
||||
|
||||
function DuplicateGroupCard({ group }: { group: DuplicateGroup }) {
|
||||
const selectedIds = useGalleryStore((state) => state.duplicateSelectedIds);
|
||||
const toggleDuplicateSelected = useGalleryStore((state) => state.toggleDuplicateSelected);
|
||||
const selectAllDuplicates = useGalleryStore((state) => state.selectAllDuplicates);
|
||||
const groupSelectedCount = group.images.filter((img) => selectedIds.has(img.id)).length;
|
||||
const noneSelected = groupSelectedCount === 0;
|
||||
|
||||
// "Keep all but the first" — a common quick action
|
||||
const handleKeepFirst = () => {
|
||||
const toDelete = group.images.slice(1).map((img) => img.id);
|
||||
// Clear any selection for this group first, then add the ones to delete
|
||||
for (const img of group.images) {
|
||||
if (selectedIds.has(img.id)) toggleDuplicateSelected(img.id);
|
||||
}
|
||||
selectAllDuplicates(toDelete);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/[0.07] bg-white/[0.02] p-4">
|
||||
{/* Group header */}
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-400">
|
||||
{group.images.length} copies
|
||||
</span>
|
||||
<span className="text-[11px] text-white/30">{formatBytes(group.file_size)} each</span>
|
||||
<span className="text-[11px] text-white/20">
|
||||
{formatBytes(group.file_size * (group.images.length - 1))} wasted
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{noneSelected ? (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={handleKeepFirst}
|
||||
>
|
||||
Keep first
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={() => {
|
||||
for (const img of group.images) {
|
||||
if (selectedIds.has(img.id)) toggleDuplicateSelected(img.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image grid */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{group.images.map((image) => {
|
||||
const isSelected = selectedIds.has(image.id);
|
||||
const src = image.thumbnail_path ? convertFileSrc(image.thumbnail_path) : null;
|
||||
return (
|
||||
<button
|
||||
key={image.id}
|
||||
className={`media-dark-surface group relative overflow-hidden rounded-xl border transition-all ${
|
||||
isSelected
|
||||
? "border-red-400/50 ring-1 ring-red-400/30"
|
||||
: "border-white/8 hover:border-white/20"
|
||||
}`}
|
||||
style={{ width: 140, height: 105 }}
|
||||
onClick={() => toggleDuplicateSelected(image.id)}
|
||||
title={image.path}
|
||||
>
|
||||
{src ? (
|
||||
<img src={src} alt="" className="h-full w-full object-cover" draggable={false} />
|
||||
) : (
|
||||
<div className="h-full w-full bg-white/[0.03]" />
|
||||
)}
|
||||
{/* Delete overlay */}
|
||||
{isSelected ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-red-950/60">
|
||||
<svg className="h-6 w-6 text-red-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</div>
|
||||
) : null}
|
||||
{/* Path tooltip on hover */}
|
||||
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/90 to-transparent px-2 pb-1.5 pt-4 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<p className="truncate text-[9px] text-white/60">{image.path.split(/[\\/]/).slice(-2).join("/")}</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatRelativeTime(unixSecs: number): string {
|
||||
const diff = Math.floor(Date.now() / 1000) - unixSecs;
|
||||
if (diff < 60) return "just now";
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||
return `${Math.floor(diff / 86400)}d ago`;
|
||||
}
|
||||
import { useRef, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { useGalleryStore } from '../store'
|
||||
import {
|
||||
DuplicateScanEmptyState,
|
||||
DuplicateScanIntroState,
|
||||
DuplicateScanLoadingState,
|
||||
} from './duplicateFinder/DuplicateFinderEmptyStates'
|
||||
import { DuplicateFinderHeader } from './duplicateFinder/DuplicateFinderHeader'
|
||||
import { DuplicateGroupCard } from './duplicateFinder/DuplicateGroupCard'
|
||||
import { duplicateProgressLabel } from './duplicateFinder/format'
|
||||
|
||||
export function DuplicateFinder() {
|
||||
const duplicateGroups = useGalleryStore((state) => state.duplicateGroups);
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning);
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress);
|
||||
const duplicateScanError = useGalleryStore((state) => state.duplicateScanError);
|
||||
const duplicateScanWarning = useGalleryStore((state) => state.duplicateScanWarning);
|
||||
const duplicateSelectedIds = useGalleryStore((state) => state.duplicateSelectedIds);
|
||||
const duplicateLastScanned = useGalleryStore((state) => state.duplicateLastScanned);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const scanDuplicates = useGalleryStore((state) => state.scanDuplicates);
|
||||
const clearDuplicateSelection = useGalleryStore((state) => state.clearDuplicateSelection);
|
||||
const selectKeepFirstAllGroups = useGalleryStore((state) => state.selectKeepFirstAllGroups);
|
||||
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates);
|
||||
const duplicateGroups = useGalleryStore((state) => state.duplicateGroups)
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning)
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress)
|
||||
const duplicateScanError = useGalleryStore((state) => state.duplicateScanError)
|
||||
const duplicateScanWarning = useGalleryStore((state) => state.duplicateScanWarning)
|
||||
const duplicateSelectedIds = useGalleryStore((state) => state.duplicateSelectedIds)
|
||||
const duplicateLastScanned = useGalleryStore((state) => state.duplicateLastScanned)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const scanDuplicates = useGalleryStore((state) => state.scanDuplicates)
|
||||
const clearDuplicateSelection = useGalleryStore((state) => state.clearDuplicateSelection)
|
||||
const selectKeepFirstAllGroups = useGalleryStore((state) => state.selectKeepFirstAllGroups)
|
||||
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates)
|
||||
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [deleteResult, setDeleteResult] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false)
|
||||
const [deleteResult, setDeleteResult] = useState<string | null>(null)
|
||||
|
||||
// Virtualize the group list so a large result set (e.g. thousands of pairs)
|
||||
// only mounts the on-screen cards. Group cards vary in height (number of
|
||||
// copies wraps across rows), so heights are measured dynamically.
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const virtualizer = useVirtualizer({
|
||||
count: duplicateGroups.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 220,
|
||||
overscan: 4,
|
||||
});
|
||||
|
||||
const selectedCount = duplicateSelectedIds.size;
|
||||
const hasResults = duplicateGroups.length > 0;
|
||||
const hasScanned = hasResults || duplicateLastScanned !== null || (!duplicateScanning && duplicateScanProgress !== null);
|
||||
const totalWasted = duplicateGroups.reduce(
|
||||
(sum, g) => sum + g.file_size * (g.images.length - 1),
|
||||
0,
|
||||
);
|
||||
const totalDuplicateImages = duplicateGroups.reduce((sum, g) => sum + g.images.length - 1, 0);
|
||||
})
|
||||
|
||||
const selectedCount = duplicateSelectedIds.size
|
||||
const hasResults = duplicateGroups.length > 0
|
||||
const hasScanned =
|
||||
hasResults ||
|
||||
duplicateLastScanned !== null ||
|
||||
(!duplicateScanning && duplicateScanProgress !== null)
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
setDeleteResult(null);
|
||||
setDeleting(true)
|
||||
setConfirmingDelete(false)
|
||||
setDeleteResult(null)
|
||||
try {
|
||||
const deleted = await deleteSelectedDuplicates();
|
||||
setDeleteResult(`Deleted ${deleted} file${deleted === 1 ? "" : "s"}.`);
|
||||
const deleted = await deleteSelectedDuplicates()
|
||||
setDeleteResult(`Deleted ${deleted} file${deleted === 1 ? '' : 's'}.`)
|
||||
} catch (e) {
|
||||
setDeleteResult(String(e));
|
||||
setDeleteResult(String(e))
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setDeleting(false)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const progressPercent =
|
||||
duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? Math.round((duplicateScanProgress.processed / duplicateScanProgress.total) * 100)
|
||||
: 0;
|
||||
const progressLabel = duplicateScanProgress
|
||||
? duplicateScanProgress.phase === "checking"
|
||||
? "Checking file sizes"
|
||||
: duplicateScanProgress.phase === "hashing"
|
||||
? "Hashing duplicate candidates"
|
||||
: "Confirming exact matches"
|
||||
: null;
|
||||
const progressLabel = duplicateProgressLabel(duplicateScanProgress)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-gray-950">
|
||||
{/* Header */}
|
||||
<div className="shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-[15px] font-semibold text-white">Duplicate Finder</h2>
|
||||
<p className="mt-0.5 text-[11px] text-white/30">
|
||||
{duplicateScanning
|
||||
? duplicateScanProgress
|
||||
? `${progressLabel}… ${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ""}`
|
||||
: "Starting scan…"
|
||||
: hasResults
|
||||
? `${duplicateGroups.length} group${duplicateGroups.length === 1 ? "" : "s"} · ${formatBytes(totalWasted)} reclaimable`
|
||||
: duplicateLastScanned !== null
|
||||
? "No duplicates found"
|
||||
: "Scan your library for identical files"}
|
||||
</p>
|
||||
{!duplicateScanning && duplicateLastScanned !== null && (
|
||||
<p className="mt-0.5 text-[10px] text-white/20">
|
||||
Last scanned {formatRelativeTime(duplicateLastScanned)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderScopeDropdown />
|
||||
{/* Batch select — only shown when there are groups and nothing is selected yet */}
|
||||
{hasResults && selectedCount === 0 && !deleting && (
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={selectKeepFirstAllGroups}
|
||||
title={`Mark ${totalDuplicateImages} duplicate${totalDuplicateImages === 1 ? "" : "s"} for deletion across all groups (keeps first in each)`}
|
||||
>
|
||||
Select all duplicates
|
||||
</button>
|
||||
)}
|
||||
{selectedCount > 0 ? (
|
||||
<>
|
||||
<span className="text-[11px] text-white/40">{selectedCount} marked for deletion</span>
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white disabled:opacity-40 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={clearDuplicateSelection}
|
||||
disabled={deleting}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
<button
|
||||
className="rounded-lg border border-red-400/25 bg-red-500/10 px-3 py-1.5 text-xs text-red-300 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? "Deleting…" : `Delete ${selectedCount} file${selectedCount === 1 ? "" : "s"}`}
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-40 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => { setDeleteResult(null); void scanDuplicates(selectedFolderId); }}
|
||||
disabled={duplicateScanning}
|
||||
>
|
||||
{duplicateScanning ? "Scanning…" : hasScanned ? "Rescan" : "Scan for duplicates"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<DuplicateFinderHeader
|
||||
confirmingDelete={confirmingDelete}
|
||||
deleteResult={deleteResult}
|
||||
deleting={deleting}
|
||||
duplicateGroups={duplicateGroups}
|
||||
duplicateLastScanned={duplicateLastScanned}
|
||||
duplicateScanError={duplicateScanError}
|
||||
duplicateScanning={duplicateScanning}
|
||||
duplicateScanProgress={duplicateScanProgress}
|
||||
duplicateScanWarning={duplicateScanWarning}
|
||||
hasResults={hasResults}
|
||||
hasScanned={hasScanned}
|
||||
onClearSelection={clearDuplicateSelection}
|
||||
onConfirmDelete={() => setConfirmingDelete(false)}
|
||||
onDelete={handleDelete}
|
||||
onScan={() => {
|
||||
setDeleteResult(null)
|
||||
void scanDuplicates(selectedFolderId)
|
||||
}}
|
||||
onSelectKeepFirstAll={selectKeepFirstAllGroups}
|
||||
selectedCount={selectedCount}
|
||||
setConfirmingDelete={setConfirmingDelete}
|
||||
/>
|
||||
|
||||
{/* Progress bar */}
|
||||
{duplicateScanning && duplicateScanProgress ? (
|
||||
<div className="mt-3 h-px overflow-hidden rounded-full bg-white/[0.07]">
|
||||
<div
|
||||
className="h-full rounded-full bg-blue-500/60 transition-[width] duration-200"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{duplicateScanError ? (
|
||||
<p className="mt-2 text-[11px] text-red-400/80">{duplicateScanError}</p>
|
||||
) : null}
|
||||
{duplicateScanWarning ? (
|
||||
<p className="mt-2 text-[11px] text-amber-300/70">{duplicateScanWarning}</p>
|
||||
) : null}
|
||||
{deleteResult ? (
|
||||
<p className="mt-2 text-[11px] text-white/40">{deleteResult}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
{duplicateScanning && !hasResults ? (
|
||||
<div className="flex flex-1 items-center justify-center gap-3 text-white/25">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/15 border-t-white/50" />
|
||||
<span className="text-sm">{progressLabel ? `${progressLabel}…` : "Preparing scan…"}</span>
|
||||
</div>
|
||||
<DuplicateScanLoadingState progressLabel={progressLabel} />
|
||||
) : !hasScanned ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<div className="max-w-sm text-center">
|
||||
<svg className="mx-auto mb-4 h-10 w-10 text-white/10" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1}
|
||||
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p className="text-sm text-white/30">
|
||||
Finds files with identical content regardless of filename or location.
|
||||
Click <strong className="text-white/50">Scan for duplicates</strong> to begin.
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-white/20">
|
||||
Large libraries may take a minute — files are hashed from disk.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DuplicateScanIntroState />
|
||||
) : duplicateGroups.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-white/25">No duplicate files found.</p>
|
||||
</div>
|
||||
<DuplicateScanEmptyState />
|
||||
) : (
|
||||
<div ref={scrollRef} className="overflow-y-auto px-6 py-5">
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const group = duplicateGroups[virtualItem.index];
|
||||
if (!group) return null;
|
||||
const group = duplicateGroups[virtualItem.index]
|
||||
if (!group) return null
|
||||
return (
|
||||
<div
|
||||
key={group.file_hash}
|
||||
data-index={virtualItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
style={{
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
width: '100%',
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
paddingBottom: 16,
|
||||
}}
|
||||
>
|
||||
<DuplicateGroupCard group={group} />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { FolderScopeDropdown } from './FolderScopeDropdown'
|
||||
import { ClusterCloud } from './explore/ClusterCloud'
|
||||
import { ExploreLoadingPanel } from './explore/ExploreLoadingPanel'
|
||||
import { TagAtlas, TAG_ATLAS_MAX_VISIBLE } from './explore/TagAtlas'
|
||||
import { TagManageList } from './explore/TagManageList'
|
||||
|
||||
export function ExploreView() {
|
||||
const exploreMode = useGalleryStore((state) => state.exploreMode)
|
||||
const setExploreMode = useGalleryStore((state) => state.setExploreMode)
|
||||
const visualClusterEntries = useGalleryStore((state) => state.visualClusterEntries)
|
||||
const visualClusterLoading = useGalleryStore((state) => state.visualClusterLoading)
|
||||
const loadVisualClusters = useGalleryStore((state) => state.loadVisualClusters)
|
||||
const exploreTagEntries = useGalleryStore((state) => state.exploreTagEntries)
|
||||
const exploreTagLoading = useGalleryStore((state) => state.exploreTagLoading)
|
||||
const loadExploreTags = useGalleryStore((state) => state.loadExploreTags)
|
||||
const loadRelatedTags = useGalleryStore((state) => state.loadRelatedTags)
|
||||
const showVisualCluster = useGalleryStore((state) => state.showVisualCluster)
|
||||
const searchForTag = useGalleryStore((state) => state.searchForTag)
|
||||
const renameTag = useGalleryStore((state) => state.renameTag)
|
||||
const deleteTag = useGalleryStore((state) => state.deleteTag)
|
||||
const resetAiTags = useGalleryStore((state) => state.resetAiTags)
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
// Manage mode lives in the store so it can be opened from elsewhere (Settings).
|
||||
const manageTags = useGalleryStore((state) => state.tagManagerOpen)
|
||||
const setManageTags = useGalleryStore((state) => state.setTagManagerOpen)
|
||||
const handleDeleteTag = async (tag: string) => {
|
||||
await deleteTag(tag)
|
||||
}
|
||||
const tagManagerScopeLabel =
|
||||
selectedFolderId === null
|
||||
? 'all media'
|
||||
: (folders.find((folder) => folder.id === selectedFolderId)?.name ?? 'the current folder')
|
||||
const handleResetAiTags = async () => {
|
||||
const count = await resetAiTags(selectedFolderId)
|
||||
await loadExploreTags({ force: true })
|
||||
return count
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (exploreMode === 'visual') void loadVisualClusters()
|
||||
else void loadExploreTags()
|
||||
}, [exploreMode, selectedFolderId, loadVisualClusters, loadExploreTags])
|
||||
|
||||
const loading = exploreMode === 'visual' ? visualClusterLoading : exploreTagLoading
|
||||
const hasEntries =
|
||||
exploreMode === 'visual' ? visualClusterEntries.length > 0 : exploreTagEntries.length > 0
|
||||
const entryCount =
|
||||
exploreMode === 'visual' ? visualClusterEntries.length : exploreTagEntries.length
|
||||
const visibleTagCount = Math.min(exploreTagEntries.length, TAG_ATLAS_MAX_VISIBLE)
|
||||
|
||||
return (
|
||||
<div className="explore-view flex min-h-0 flex-1 flex-col overflow-hidden bg-[radial-gradient(ellipse_at_top,rgba(59,130,246,0.08),transparent_50%),radial-gradient(ellipse_at_80%_75%,rgba(168,85,247,0.07),transparent_40%),#07080f]">
|
||||
{/* Header — `relative z-10` keeps the folder-scope dropdown above the
|
||||
cluster canvas, whose cards use a high z-index of their own. */}
|
||||
<div className="explore-header relative z-10 shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<h2 className="explore-title text-[15px] font-semibold text-white">Explore</h2>
|
||||
<p className="explore-subtitle mt-0.5 truncate text-[11px] text-white/30">
|
||||
{loading
|
||||
? exploreMode === 'visual'
|
||||
? 'Computing visual clusters…'
|
||||
: 'Loading tags…'
|
||||
: hasEntries
|
||||
? exploreMode === 'visual'
|
||||
? `${entryCount} cluster${entryCount !== 1 ? 's' : ''} — click any to open`
|
||||
: manageTags
|
||||
? `${entryCount} tag${entryCount !== 1 ? 's' : ''} available to manage`
|
||||
: visibleTagCount < entryCount
|
||||
? `${visibleTagCount} of ${entryCount} tags shown — click any to search`
|
||||
: `${entryCount} tag${entryCount !== 1 ? 's' : ''} — click any to search`
|
||||
: exploreMode === 'visual'
|
||||
? 'No clusters — images need embeddings first'
|
||||
: 'No tags — run the AI tagger or add tags manually'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{exploreMode === 'tags' && hasEntries ? (
|
||||
<button
|
||||
className={`rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
manageTags
|
||||
? 'border-white/15 bg-white/10 text-white'
|
||||
: 'border-white/8 bg-white/[0.03] text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setManageTags(!manageTags)}
|
||||
>
|
||||
{manageTags ? 'Done' : 'Manage'}
|
||||
</button>
|
||||
) : null}
|
||||
<FolderScopeDropdown />
|
||||
<div className="explore-mode-toggle flex rounded-lg border border-white/8 bg-white/[0.03] p-0.5">
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === 'visual'
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setExploreMode('visual')}
|
||||
>
|
||||
Clusters
|
||||
</button>
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === 'tags'
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setExploreMode('tags')}
|
||||
>
|
||||
Tag Cloud
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && !hasEntries ? (
|
||||
<ExploreLoadingPanel mode={exploreMode} />
|
||||
) : !hasEntries ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<p className="explore-empty max-w-xs text-center text-sm leading-relaxed text-white/25">
|
||||
{exploreMode === 'visual'
|
||||
? 'No visual clusters yet. Images need embeddings before they can be grouped. Check indexing progress in the sidebar.'
|
||||
: 'No tags yet. Run the AI tagger from Settings, or add tags manually in the image preview.'}
|
||||
</p>
|
||||
</div>
|
||||
) : exploreMode === 'visual' ? (
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">
|
||||
<ClusterCloud entries={visualClusterEntries} onOpen={showVisualCluster} />
|
||||
</div>
|
||||
) : manageTags ? (
|
||||
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<TagManageList
|
||||
entries={exploreTagEntries}
|
||||
onSearch={searchForTag}
|
||||
onRename={renameTag}
|
||||
onDelete={handleDeleteTag}
|
||||
onResetAiTags={handleResetAiTags}
|
||||
scopeLabel={tagManagerScopeLabel}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<TagAtlas
|
||||
entries={exploreTagEntries}
|
||||
onSearch={searchForTag}
|
||||
loadRelatedTags={loadRelatedTags}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,342 +1,50 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { DirEntry, DirListing, FolderAddResult, useGalleryStore } from "../store";
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
return path.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
||||
}
|
||||
|
||||
function folderName(path: string): string {
|
||||
const trimmed = path.replace(/[\\/]+$/, "");
|
||||
const parts = trimmed.split(/[\\/]+/).filter(Boolean);
|
||||
return parts.length > 0 ? parts[parts.length - 1] : path;
|
||||
}
|
||||
|
||||
function buildBreadcrumbs(path: string | null): { label: string; path: string | null }[] {
|
||||
if (!path) return [{ label: "This PC / Home", path: null }];
|
||||
|
||||
const separator = path.includes("\\") ? "\\" : "/";
|
||||
const normalized = path.replace(/[\\/]+$/, "");
|
||||
const windowsDrive = normalized.match(/^[A-Za-z]:/);
|
||||
|
||||
if (windowsDrive) {
|
||||
const drive = windowsDrive[0] + "\\";
|
||||
const rest = normalized.slice(2).split(/[\\/]+/).filter(Boolean);
|
||||
let current = drive;
|
||||
return [
|
||||
{ label: "This PC", path: null },
|
||||
{ label: drive, path: drive },
|
||||
...rest.map((part) => {
|
||||
current = current.endsWith("\\") ? `${current}${part}` : `${current}\\${part}`;
|
||||
return { label: part, path: current };
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
const parts = normalized.split(/[\\/]+/).filter(Boolean);
|
||||
let current = separator === "/" ? "" : "";
|
||||
return [
|
||||
{ label: "/", path: null },
|
||||
...parts.map((part) => {
|
||||
current = `${current}/${part}`;
|
||||
return { label: part, path: current };
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function StatusLine({ results }: { results: FolderAddResult[] | null }) {
|
||||
if (!results) return null;
|
||||
const added = results.filter((result) => result.status === "added").length;
|
||||
const skipped = results.filter((result) => result.status === "skipped").length;
|
||||
const failed = results.filter((result) => result.status === "error").length;
|
||||
return (
|
||||
<p className="text-xs text-gray-500 light-theme:text-gray-600">
|
||||
Added {added}, skipped {skipped}, failed {failed}.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function FolderRow({
|
||||
entry,
|
||||
selected,
|
||||
alreadyAdded,
|
||||
onToggle,
|
||||
onNavigate,
|
||||
}: {
|
||||
entry: DirEntry;
|
||||
selected: boolean;
|
||||
alreadyAdded: boolean;
|
||||
onToggle: () => void;
|
||||
onNavigate: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`group flex h-11 items-center gap-3 rounded-md border px-3 transition-colors ${
|
||||
alreadyAdded
|
||||
? "border-transparent bg-white/[0.025] text-gray-600 light-theme:bg-gray-900 light-theme:text-gray-500"
|
||||
: selected
|
||||
? "border-white/15 bg-white/[0.085] text-white shadow-[inset_0_0_0_1px_rgb(255_255_255_/_0.035)] light-theme:border-gray-700/45 light-theme:bg-gray-800/55 light-theme:text-white"
|
||||
: "border-transparent text-gray-300 hover:bg-white/[0.055] hover:text-white light-theme:text-gray-500 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={`grid h-5 w-5 shrink-0 place-items-center rounded border transition-colors ${
|
||||
selected
|
||||
? "border-white/30 bg-gray-200 text-gray-950 light-theme:border-gray-700/55 light-theme:bg-gray-700 light-theme:text-white"
|
||||
: "border-white/15 bg-white/[0.035] text-transparent hover:border-white/30 light-theme:border-gray-700/50 light-theme:bg-gray-950"
|
||||
} ${alreadyAdded ? "cursor-not-allowed opacity-40" : ""}`}
|
||||
onClick={onToggle}
|
||||
disabled={alreadyAdded}
|
||||
aria-label={selected ? `Remove ${entry.name} from folders to add` : `Choose ${entry.name}`}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-2 text-left"
|
||||
onClick={onNavigate}
|
||||
title={entry.path}
|
||||
>
|
||||
<svg className="h-4 w-4 shrink-0 text-amber-300/90" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M3 6.5A2.5 2.5 0 015.5 4h4.1l2 2H18.5A2.5 2.5 0 0121 8.5v9A2.5 2.5 0 0118.5 20h-13A2.5 2.5 0 013 17.5v-11z" />
|
||||
</svg>
|
||||
<span className="truncate text-sm">{entry.name}</span>
|
||||
</button>
|
||||
|
||||
{alreadyAdded ? (
|
||||
<span className="rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-500 light-theme:border-gray-700/40 light-theme:bg-gray-950">
|
||||
Added
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
onClick={onNavigate}
|
||||
title={entry.has_children ? "Open folder" : "No subfolders"}
|
||||
>
|
||||
<svg className={`h-4 w-4 ${entry.has_children ? "" : "opacity-45"}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StagedFoldersPanel({
|
||||
stagedPaths,
|
||||
onRemove,
|
||||
onClear,
|
||||
}: {
|
||||
stagedPaths: string[];
|
||||
onRemove: (path: string) => void;
|
||||
onClear: () => void;
|
||||
}) {
|
||||
return (
|
||||
<aside className="flex min-h-0 w-full flex-col border-t border-white/[0.07] bg-white/[0.018] light-theme:border-gray-300/70 light-theme:bg-gray-900/35 lg:w-80 lg:border-l lg:border-t-0">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-white/[0.07] px-5 py-4 light-theme:border-gray-300/70">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-gray-500">
|
||||
Folders to add ({stagedPaths.length})
|
||||
</p>
|
||||
{stagedPaths.length > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-3">
|
||||
{stagedPaths.length === 0 ? (
|
||||
<div className="flex h-full min-h-40 flex-col items-center justify-center rounded-md border border-dashed border-white/[0.08] px-5 text-center light-theme:border-gray-700/35">
|
||||
<p className="text-sm text-gray-500">No folders selected.</p>
|
||||
<p className="mt-1 max-w-52 text-xs leading-relaxed text-gray-600 light-theme:text-gray-500">
|
||||
Choose folders on the left and they will collect here.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{stagedPaths.map((path) => (
|
||||
<div
|
||||
key={path}
|
||||
className="group flex min-h-12 items-center gap-2 rounded-md border border-white/[0.07] bg-white/[0.045] px-3 py-2 text-gray-200 transition-colors hover:border-white/15 hover:bg-white/[0.07] light-theme:border-gray-700/40 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
title={path}
|
||||
>
|
||||
<svg className="h-4 w-4 shrink-0 text-amber-300/90" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M3 6.5A2.5 2.5 0 015.5 4h4.1l2 2H18.5A2.5 2.5 0 0121 8.5v9A2.5 2.5 0 0118.5 20h-13A2.5 2.5 0 013 17.5v-11z" />
|
||||
</svg>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{folderName(path)}</p>
|
||||
<p className="mt-0.5 truncate text-[11px] text-gray-600 light-theme:text-gray-500">{path}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1 text-gray-500 opacity-80 transition-colors hover:bg-white/[0.08] hover:text-white group-hover:opacity-100 light-theme:hover:bg-gray-700"
|
||||
onClick={() => onRemove(path)}
|
||||
aria-label={`Remove ${path} from folders to add`}
|
||||
title="Remove from folders to add"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
import { FolderRow } from './folderPicker/FolderRow'
|
||||
import { StagedFoldersPanel } from './folderPicker/StagedFoldersPanel'
|
||||
import { StatusLine } from './folderPicker/StatusLine'
|
||||
import { normalizePath } from './folderPicker/pathUtils'
|
||||
import { useFolderPicker } from './folderPicker/useFolderPicker'
|
||||
|
||||
export function FolderPickerModal() {
|
||||
const folderPickerOpen = useGalleryStore((state) => state.folderPickerOpen);
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen);
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const listDirectories = useGalleryStore((state) => state.listDirectories);
|
||||
const addFolders = useGalleryStore((state) => state.addFolders);
|
||||
|
||||
const [listing, setListing] = useState<DirListing | null>(null);
|
||||
const [currentPath, setCurrentPath] = useState<string | null>(null);
|
||||
const [stagedPaths, setStagedPaths] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [results, setResults] = useState<FolderAddResult[] | null>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const libraryPaths = useMemo(() => new Set(folders.map((folder) => normalizePath(folder.path))), [folders]);
|
||||
const stagedSet = useMemo(() => new Set(stagedPaths.map(normalizePath)), [stagedPaths]);
|
||||
const breadcrumbs = useMemo(() => buildBreadcrumbs(listing?.current ?? null), [listing?.current]);
|
||||
const folderPicker = useFolderPicker()
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: listing?.entries.length ?? 0,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
count: folderPicker.entries.length,
|
||||
getScrollElement: () => folderPicker.scrollRef.current,
|
||||
estimateSize: () => 48,
|
||||
overscan: 8,
|
||||
});
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderPickerOpen) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void listDirectories(currentPath)
|
||||
.then((nextListing) => {
|
||||
if (cancelled) return;
|
||||
setListing(nextListing);
|
||||
scrollRef.current?.scrollTo({ top: 0, left: 0 });
|
||||
})
|
||||
.catch((loadError) => {
|
||||
if (cancelled) return;
|
||||
setListing({ current: currentPath, parent: null, entries: [] });
|
||||
setError(loadError instanceof Error ? loadError.message : String(loadError));
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [currentPath, folderPickerOpen, listDirectories]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderPickerOpen) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setFolderPickerOpen(false);
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [folderPickerOpen, setFolderPickerOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (folderPickerOpen) return;
|
||||
setCurrentPath(null);
|
||||
setListing(null);
|
||||
setStagedPaths([]);
|
||||
setError(null);
|
||||
setResults(null);
|
||||
setAdding(false);
|
||||
}, [folderPickerOpen]);
|
||||
|
||||
if (!folderPickerOpen) return null;
|
||||
|
||||
const entries = listing?.entries ?? [];
|
||||
|
||||
const togglePath = (path: string) => {
|
||||
const normalized = normalizePath(path);
|
||||
if (libraryPaths.has(normalized)) return;
|
||||
setResults(null);
|
||||
setStagedPaths((current) => {
|
||||
const exists = current.some((staged) => normalizePath(staged) === normalized);
|
||||
return exists ? current.filter((staged) => normalizePath(staged) !== normalized) : [...current, path];
|
||||
});
|
||||
};
|
||||
|
||||
const removeStagedPath = (path: string) => {
|
||||
const normalized = normalizePath(path);
|
||||
setResults(null);
|
||||
setStagedPaths((current) => current.filter((staged) => normalizePath(staged) !== normalized));
|
||||
};
|
||||
|
||||
const clearStagedPaths = () => {
|
||||
setResults(null);
|
||||
setStagedPaths([]);
|
||||
};
|
||||
|
||||
const confirmAdd = async () => {
|
||||
if (stagedPaths.length === 0 || adding) return;
|
||||
setAdding(true);
|
||||
setError(null);
|
||||
try {
|
||||
const addResults = await addFolders(stagedPaths);
|
||||
const failed = addResults.filter((result) => result.status === "error");
|
||||
setResults(addResults);
|
||||
if (failed.length > 0) {
|
||||
setStagedPaths(stagedPaths.filter((_, i) => addResults[i]?.status === "error"));
|
||||
setError(failed.map((failure) => failure.data).join("; "));
|
||||
return;
|
||||
}
|
||||
setFolderPickerOpen(false);
|
||||
} catch (addError) {
|
||||
setError(addError instanceof Error ? addError.message : String(addError));
|
||||
} finally {
|
||||
setAdding(false);
|
||||
}
|
||||
};
|
||||
if (!folderPicker.folderPickerOpen) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/65 px-6 backdrop-blur-sm"
|
||||
onClick={() => setFolderPickerOpen(false)}
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
<div
|
||||
className="relative flex h-[min(82vh,760px)] w-[min(90vw,1180px)] flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60 light-theme:border-gray-300/70"
|
||||
className="light-theme:border-gray-300/70 relative flex h-[min(82vh,760px)] w-[min(90vw,1180px)] flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<header className="border-b border-white/[0.07] px-5 py-4 light-theme:border-gray-200">
|
||||
<header className="light-theme:border-gray-200 border-b border-white/[0.07] px-5 py-4">
|
||||
<div className="flex items-start justify-between gap-6">
|
||||
<div className="min-w-0">
|
||||
<p className="text-base font-semibold text-white">Add media folders</p>
|
||||
<p className="mt-1 text-xs text-gray-500 light-theme:text-gray-600">Choose folders from any location, then add them together.</p>
|
||||
<p className="light-theme:text-gray-600 mt-1 text-xs text-gray-500">
|
||||
Choose folders from any location, then add them together.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
onClick={() => setFolderPickerOpen(false)}
|
||||
title="Close folder picker"
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<Tooltip label="Close folder picker" anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:hover:bg-gray-900 light-theme:hover:text-white rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -345,52 +53,118 @@ export function FolderPickerModal() {
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
onClick={() => setCurrentPath(listing?.parent ?? null)}
|
||||
disabled={!listing?.current}
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={() => folderPicker.setCurrentPath(folderPicker.listing?.parent ?? null)}
|
||||
disabled={!folderPicker.listing?.current}
|
||||
>
|
||||
Up
|
||||
</button>
|
||||
<nav className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden rounded-md border border-white/10 bg-white/[0.025] px-2 py-1.5 light-theme:border-gray-300/70 light-theme:bg-gray-900">
|
||||
{breadcrumbs.map((crumb, index) => (
|
||||
<span key={`${crumb.path ?? "root"}-${index}`} className="flex min-w-0 items-center gap-1">
|
||||
{index > 0 ? <span className="text-gray-700 light-theme:text-gray-400">/</span> : null}
|
||||
<button
|
||||
type="button"
|
||||
className="max-w-40 truncate rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => setCurrentPath(crumb.path)}
|
||||
title={crumb.path ?? "Roots"}
|
||||
>
|
||||
{crumb.label}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
{folderPicker.addressEditing ? (
|
||||
<form
|
||||
className="flex min-w-0 flex-1 items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
folderPicker.navigateToAddress()
|
||||
}}
|
||||
>
|
||||
<label className="sr-only" htmlFor="folder-picker-address">
|
||||
Folder path
|
||||
</label>
|
||||
<input
|
||||
ref={folderPicker.addressInputRef}
|
||||
id="folder-picker-address"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:placeholder-gray-500 light-theme:focus:bg-gray-800 min-w-0 flex-1 rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 font-mono text-xs text-gray-200 placeholder-gray-600 transition-colors outline-none focus:border-white/25 focus:bg-white/[0.055]"
|
||||
value={folderPicker.addressDraft}
|
||||
onChange={(event) => folderPicker.updateAddressDraft(event.target.value)}
|
||||
placeholder="Paste or type a folder path"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={folderPicker.loading}
|
||||
>
|
||||
Go
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="light-theme:border-gray-300/70 light-theme:bg-gray-900 flex min-w-0 flex-1 items-center gap-1 overflow-hidden rounded-md border border-white/10 bg-white/[0.025] px-2 py-1.5">
|
||||
<nav className="flex min-w-0 items-center gap-1 overflow-hidden">
|
||||
{folderPicker.breadcrumbs.map((crumb, index) => (
|
||||
<span
|
||||
key={`${crumb.path ?? 'root'}-${index}`}
|
||||
className="flex min-w-0 items-center gap-1"
|
||||
>
|
||||
{index > 0 ? (
|
||||
<span className="light-theme:text-gray-400 text-gray-700">/</span>
|
||||
) : null}
|
||||
<Tooltip label={crumb.path ?? 'Roots'} anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white max-w-40 truncate rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
folderPicker.setCurrentPath(crumb.path)
|
||||
}}
|
||||
>
|
||||
{crumb.label}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-10 flex-1 cursor-text self-stretch rounded px-1"
|
||||
onClick={folderPicker.beginAddressEdit}
|
||||
aria-label="Edit folder path"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-2.5 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25 disabled:cursor-not-allowed disabled:opacity-45"
|
||||
onClick={() => folderPicker.stagePath(folderPicker.addressPath)}
|
||||
disabled={
|
||||
!folderPicker.addressPath ||
|
||||
folderPicker.addressAlreadyAdded ||
|
||||
folderPicker.addressAlreadyStaged
|
||||
}
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="mb-3 rounded-md border border-amber-400/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-200 light-theme:border-amber-600/40 light-theme:bg-amber-100 light-theme:text-amber-800">
|
||||
{error}
|
||||
{folderPicker.error ? (
|
||||
<div className="light-theme:border-amber-600/40 light-theme:bg-amber-100 light-theme:text-amber-800 mb-3 rounded-md border border-amber-400/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-200">
|
||||
{folderPicker.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div ref={scrollRef} className="min-h-0 flex-1 overflow-auto rounded-md border border-white/[0.07] bg-white/[0.018] p-2 light-theme:border-gray-300/70 light-theme:bg-gray-900/50">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">Loading folders...</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">No folders found here.</div>
|
||||
<div
|
||||
ref={folderPicker.scrollRef}
|
||||
className="light-theme:border-gray-300/70 light-theme:bg-gray-900/50 min-h-0 flex-1 overflow-auto rounded-md border border-white/[0.07] bg-white/[0.018] p-2"
|
||||
>
|
||||
{folderPicker.loading ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">
|
||||
Loading folders...
|
||||
</div>
|
||||
) : folderPicker.entries.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">
|
||||
No folders found here.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ height: `${virtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const entry = entries[virtualItem.index];
|
||||
const normalized = normalizePath(entry.path);
|
||||
const entry = folderPicker.entries[virtualItem.index]
|
||||
const normalized = normalizePath(entry.path)
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
className="absolute left-0 top-0 w-full px-0.5"
|
||||
className="absolute top-0 left-0 w-full px-0.5"
|
||||
style={{
|
||||
height: `${virtualItem.size}px`,
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
@@ -398,13 +172,13 @@ export function FolderPickerModal() {
|
||||
>
|
||||
<FolderRow
|
||||
entry={entry}
|
||||
selected={stagedSet.has(normalized)}
|
||||
alreadyAdded={libraryPaths.has(normalized)}
|
||||
onToggle={() => togglePath(entry.path)}
|
||||
onNavigate={() => setCurrentPath(entry.path)}
|
||||
selected={folderPicker.stagedSet.has(normalized)}
|
||||
alreadyAdded={folderPicker.libraryPaths.has(normalized)}
|
||||
onToggle={() => folderPicker.togglePath(entry.path)}
|
||||
onNavigate={() => folderPicker.setCurrentPath(entry.path)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
@@ -412,38 +186,38 @@ export function FolderPickerModal() {
|
||||
</main>
|
||||
|
||||
<StagedFoldersPanel
|
||||
stagedPaths={stagedPaths}
|
||||
onRemove={removeStagedPath}
|
||||
onClear={clearStagedPaths}
|
||||
stagedPaths={folderPicker.stagedPaths}
|
||||
onRemove={folderPicker.removeStagedPath}
|
||||
onClear={folderPicker.clearStagedPaths}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<footer className="border-t border-white/[0.07] px-5 py-4 light-theme:border-gray-200">
|
||||
<footer className="light-theme:border-gray-200 border-t border-white/[0.07] px-5 py-4">
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<StatusLine results={results} />
|
||||
<StatusLine results={folderPicker.results} />
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
onClick={() => setFolderPickerOpen(false)}
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/15 bg-white/[0.08] px-3 py-1.5 text-xs text-white transition-colors hover:bg-white/[0.12] disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
onClick={() => void confirmAdd()}
|
||||
disabled={stagedPaths.length === 0 || adding}
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/15 bg-white/[0.08] px-3 py-1.5 text-xs text-white transition-colors hover:bg-white/[0.12] disabled:cursor-not-allowed disabled:opacity-45"
|
||||
onClick={() => void folderPicker.confirmAdd()}
|
||||
disabled={folderPicker.stagedPaths.length === 0 || folderPicker.adding}
|
||||
>
|
||||
{adding ? "Adding..." : `Add ${stagedPaths.length}`}
|
||||
{folderPicker.adding ? 'Adding...' : `Add ${folderPicker.stagedPaths.length}`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { useMemo } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { Dropdown, DropdownOption } from './menu'
|
||||
|
||||
/**
|
||||
* In-view folder scope picker for feature views (Timeline / Explore /
|
||||
@@ -7,92 +8,48 @@ import { useGalleryStore } from "../store";
|
||||
* current view active — unlike sidebar folder clicks, which jump to Gallery.
|
||||
*/
|
||||
export function FolderScopeDropdown() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const setViewFolderScope = useGalleryStore((state) => state.setViewFolderScope)
|
||||
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const setViewFolderScope = useGalleryStore((state) => state.setViewFolderScope);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: MouseEvent) => {
|
||||
if (!ref.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
const currentLabel =
|
||||
selectedFolderId === null
|
||||
? "All Media"
|
||||
: folders.find((folder) => folder.id === selectedFolderId)?.name ?? "All Media";
|
||||
|
||||
const select = (folderId: number | null) => {
|
||||
setViewFolderScope(folderId);
|
||||
setOpen(false);
|
||||
};
|
||||
const options = useMemo<DropdownOption<number | null>[]>(
|
||||
() => [
|
||||
{ value: null, label: 'All Media' },
|
||||
...folders.map((folder) => ({
|
||||
value: folder.id,
|
||||
label: folder.name,
|
||||
hint: <span className="tabular-nums">{folder.image_count.toLocaleString()}</span>,
|
||||
})),
|
||||
],
|
||||
[folders]
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={ref} className="feature-scope-dropdown relative">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className={`feature-scope-trigger flex max-w-56 items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
open
|
||||
? "border-white/15 bg-white/8 text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "border-white/8 bg-transparent text-gray-400 hover:border-white/15 hover:text-gray-200 light-theme:border-gray-700/40 light-theme:text-gray-600 light-theme:hover:border-gray-700 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
title="Change folder scope"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5 shrink-0 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
<span className="truncate">{currentLabel}</span>
|
||||
<Dropdown
|
||||
value={selectedFolderId}
|
||||
options={options}
|
||||
onChange={setViewFolderScope}
|
||||
ariaLabel="Folder scope"
|
||||
trigger="ghost"
|
||||
size="md"
|
||||
triggerTooltip="Change folder scope"
|
||||
triggerClassName="max-w-56"
|
||||
panelClassName="min-w-52 max-h-80 overflow-y-auto"
|
||||
triggerIcon={
|
||||
<svg
|
||||
className={`h-3 w-3 shrink-0 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
className="h-3.5 w-3.5 shrink-0 text-gray-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="feature-scope-menu absolute right-0 top-full z-30 mt-1.5 max-h-80 min-w-52 overflow-y-auto rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur light-theme:border-gray-700/50">
|
||||
<button
|
||||
className={`feature-scope-option flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
selectedFolderId === null ? "bg-white/6 text-white light-theme:bg-gray-900 light-theme:text-white" : "text-gray-400 hover:bg-white/5 hover:text-white light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => select(null)}
|
||||
>
|
||||
All Media
|
||||
{selectedFolderId === null ? (
|
||||
<svg className="h-3.5 w-3.5 shrink-0 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
{folders.map((folder) => {
|
||||
const active = selectedFolderId === folder.id;
|
||||
return (
|
||||
<button
|
||||
key={folder.id}
|
||||
className={`feature-scope-option flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
active ? "bg-white/6 text-white light-theme:bg-gray-900 light-theme:text-white" : "text-gray-400 hover:bg-white/5 hover:text-white light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => select(folder.id)}
|
||||
>
|
||||
<span className="min-w-0 truncate">{folder.name}</span>
|
||||
<span className="flex shrink-0 items-center gap-2">
|
||||
<span className="text-[11px] tabular-nums text-gray-600">{folder.image_count.toLocaleString()}</span>
|
||||
{active ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,292 +1,54 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from "../store";
|
||||
import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from '../store'
|
||||
import { BulkActionBar } from './BulkActionBar'
|
||||
import { ImageContextMenu } from './ImageContextMenu'
|
||||
import { GalleryEmptyState, GalleryLoadingState } from './gallery/GalleryEmptyState'
|
||||
import { ImageTile } from './gallery/ImageTile'
|
||||
|
||||
const GAP = 6;
|
||||
|
||||
function formatDuration(durationMs: number | null): string | null {
|
||||
if (!durationMs || durationMs <= 0) return null;
|
||||
const totalSeconds = Math.floor(durationMs / 1000);
|
||||
const seconds = totalSeconds % 60;
|
||||
const minutes = Math.floor(totalSeconds / 60) % 60;
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
if (hours > 0) {
|
||||
return `${hours}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function ContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number;
|
||||
y: number;
|
||||
image: ImageRecord;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const openImage = useGalleryStore((state) => state.openImage);
|
||||
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails);
|
||||
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages);
|
||||
const similarScope = useGalleryStore((state) => state.similarScope);
|
||||
const canFindSimilar = image.embedding_status === "ready";
|
||||
|
||||
return (
|
||||
<div
|
||||
data-gallery-context-menu
|
||||
className="fixed z-40 min-w-52 rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur"
|
||||
style={{ left: x, top: y }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="w-full rounded-lg px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5 hover:text-white transition-colors"
|
||||
onClick={() => { openImage(image); onClose(); }}
|
||||
>
|
||||
Open Preview
|
||||
</button>
|
||||
<button
|
||||
className="w-full rounded-lg px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5 hover:text-white transition-colors"
|
||||
onClick={async () => { await updateImageDetails(image.id, { favorite: !image.favorite }); onClose(); }}
|
||||
>
|
||||
{image.favorite ? "Remove Favorite" : "Add to Favorites"}
|
||||
</button>
|
||||
<button
|
||||
className={`w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
canFindSimilar
|
||||
? "text-gray-200 hover:bg-white/5 hover:text-white"
|
||||
: "text-gray-600 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={async () => {
|
||||
if (!canFindSimilar) return;
|
||||
await loadSimilarImages(image.id, similarScope === "current_folder" ? image.folder_id : null, true, image.folder_id);
|
||||
onClose();
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
{canFindSimilar ? "Find Similar" : "Embeddings not ready"}
|
||||
</button>
|
||||
<div className="my-1 h-px bg-white/[0.06]" />
|
||||
<div className="px-3 py-1 text-[10px] uppercase tracking-[0.18em] text-gray-600">Rating</div>
|
||||
<div className="flex items-center gap-0.5 px-2 pb-1.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1;
|
||||
return (
|
||||
<button
|
||||
key={rating}
|
||||
className="rounded-md p-1 transition-colors hover:bg-white/5"
|
||||
onClick={async () => { await updateImageDetails(image.id, { rating }); onClose(); }}
|
||||
title={`Set ${rating} star rating`}
|
||||
>
|
||||
<svg
|
||||
className={`h-4 w-4 ${rating <= image.rating ? "text-amber-300" : "text-white/20 hover:text-white/40"}`}
|
||||
fill="currentColor" viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{image.rating > 0 ? (
|
||||
<button
|
||||
className="ml-1 rounded-md p-1 text-gray-600 hover:bg-white/5 hover:text-gray-300 transition-colors"
|
||||
onClick={async () => { await updateImageDetails(image.id, { rating: 0 }); onClose(); }}
|
||||
title="Remove rating"
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ImageTile({
|
||||
image,
|
||||
onClick,
|
||||
onContextMenu,
|
||||
}: {
|
||||
image: ImageRecord;
|
||||
onClick: () => void;
|
||||
onContextMenu: (event: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [errored, setErrored] = useState(false);
|
||||
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages);
|
||||
const similarScope = useGalleryStore((state) => state.similarScope);
|
||||
const canFindSimilar = image.embedding_status === "ready";
|
||||
|
||||
const src = image.thumbnail_path ? convertFileSrc(image.thumbnail_path) : null;
|
||||
|
||||
return (
|
||||
<button
|
||||
className="media-dark-surface group relative overflow-hidden rounded-xl bg-white/[0.04] text-left focus:outline-none"
|
||||
style={{ width: "100%", aspectRatio: "1 / 1" }}
|
||||
onClick={onClick}
|
||||
onContextMenu={onContextMenu}
|
||||
title={image.filename}
|
||||
>
|
||||
{/* Image / placeholder */}
|
||||
{src && !errored ? (
|
||||
<>
|
||||
{!loaded && <div className="absolute inset-0 animate-pulse bg-white/[0.04]" />}
|
||||
<img
|
||||
src={src}
|
||||
alt={image.filename}
|
||||
className={`h-full w-full object-cover transition-all duration-300 ${
|
||||
loaded ? "opacity-100 scale-100" : "opacity-0 scale-[1.02]"
|
||||
} group-hover:scale-[1.03]`}
|
||||
loading="lazy"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setErrored(true)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/[0.03] text-white/20">
|
||||
{image.media_kind === "video" ? (
|
||||
<svg className="h-7 w-7" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Video play icon — subtle at rest, visible on hover */}
|
||||
{image.media_kind === "video" && (
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<div className="rounded-full bg-black/40 p-3 text-white backdrop-blur-sm opacity-50 group-hover:opacity-90 transition-opacity duration-200">
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persistent badges — only shown when meaningful */}
|
||||
<div className="absolute top-2 right-2 flex flex-col items-end gap-1 pointer-events-none">
|
||||
{image.favorite && (
|
||||
<div className="rounded-full bg-black/50 p-1 text-rose-400 backdrop-blur-sm">
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
{image.rating > 0 && (
|
||||
<div className="flex items-center gap-0.5 rounded-md bg-black/60 px-1.5 py-1 text-amber-300 backdrop-blur-sm">
|
||||
{Array.from({ length: image.rating }, (_, index) => (
|
||||
<svg key={index} className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{image.media_kind === "video" && image.duration_ms && (
|
||||
<div className="rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-white/80 backdrop-blur-sm">
|
||||
{formatDuration(image.duration_ms)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Embedding failed badge — top-left */}
|
||||
{image.embedding_status === "failed" && (
|
||||
<div
|
||||
className="absolute top-2 left-2 pointer-events-none"
|
||||
title={image.embedding_error ?? "Embedding failed"}
|
||||
>
|
||||
<div className="flex items-center gap-1 rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-amber-400 backdrop-blur-sm">
|
||||
<svg className="h-2.5 w-2.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5}
|
||||
d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Hover overlay — slides up from bottom */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none" />
|
||||
|
||||
{/* Hover info — appears with overlay */}
|
||||
<div className="absolute bottom-0 left-0 right-0 p-2.5 translate-y-1 group-hover:translate-y-0 opacity-0 group-hover:opacity-100 transition-all duration-200">
|
||||
<p className="truncate text-[12px] font-medium text-white leading-tight">{image.filename}</p>
|
||||
<div className="mt-1.5 flex items-center justify-between gap-2">
|
||||
{image.rating > 0 ? (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{Array.from({ length: image.rating }, (_, i) => (
|
||||
<svg key={i} className="h-2.5 w-2.5 text-amber-300" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<button
|
||||
className={`rounded-md px-2 py-0.5 text-[10px] transition-colors pointer-events-auto backdrop-blur-sm ${
|
||||
canFindSimilar
|
||||
? "bg-white/10 text-white/80 hover:bg-white/20 hover:text-white"
|
||||
: "bg-white/5 text-white/30 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (!canFindSimilar) return;
|
||||
void loadSimilarImages(image.id, similarScope === "current_folder" ? image.folder_id : null, true, image.folder_id);
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
Similar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
const GAP = 6
|
||||
|
||||
export function Gallery() {
|
||||
const images = useGalleryStore((state) => state.images);
|
||||
const loadMoreImages = useGalleryStore((state) => state.loadMoreImages);
|
||||
const openImage = useGalleryStore((state) => state.openImage);
|
||||
const totalImages = useGalleryStore((state) => state.totalImages);
|
||||
const loadingImages = useGalleryStore((state) => state.loadingImages);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const search = useGalleryStore((state) => state.search);
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle);
|
||||
const imageLoadError = useGalleryStore((state) => state.imageLoadError);
|
||||
const galleryScrollResetKey = useGalleryStore((state) => state.galleryScrollResetKey);
|
||||
const isSimilarResults = collectionTitle === "Similar Images";
|
||||
const parsedSearch = parseSearchValue(search);
|
||||
const images = useGalleryStore((state) => state.images)
|
||||
const loadMoreImages = useGalleryStore((state) => state.loadMoreImages)
|
||||
const openImage = useGalleryStore((state) => state.openImage)
|
||||
const totalImages = useGalleryStore((state) => state.totalImages)
|
||||
const loadingImages = useGalleryStore((state) => state.loadingImages)
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset)
|
||||
const search = useGalleryStore((state) => state.search)
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle)
|
||||
const imageLoadError = useGalleryStore((state) => state.imageLoadError)
|
||||
const galleryScrollResetKey = useGalleryStore((state) => state.galleryScrollResetKey)
|
||||
const isSimilarResults = collectionTitle === 'Similar Images'
|
||||
const parsedSearch = parseSearchValue(search)
|
||||
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; image: ImageRecord } | null>(null);
|
||||
const parentRef = useRef<HTMLDivElement>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
} | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
setContainerWidth(el.clientWidth);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
setContainerWidth(el.clientWidth)
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
setContainerWidth(entries[0].contentRect.width);
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
setContainerWidth(entries[0].contentRect.width)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
const tileSize = tileSizeForZoom(zoomPreset)
|
||||
const cols = useMemo(
|
||||
() => Math.max(1, Math.floor((containerWidth - GAP) / (tileSize + GAP))),
|
||||
[containerWidth, tileSize],
|
||||
);
|
||||
const rowCount = Math.ceil(images.length / cols);
|
||||
[containerWidth, tileSize]
|
||||
)
|
||||
const rowCount = Math.ceil(images.length / cols)
|
||||
|
||||
const estimateSize = useCallback(() => tileSize + GAP, [tileSize]);
|
||||
const estimateSize = useCallback(() => tileSize + GAP, [tileSize])
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rowCount,
|
||||
@@ -294,159 +56,105 @@ export function Gallery() {
|
||||
estimateSize,
|
||||
overscan: 3,
|
||||
paddingStart: GAP,
|
||||
});
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
virtualizer.measure();
|
||||
}, [cols, virtualizer]);
|
||||
virtualizer.measure()
|
||||
}, [cols, virtualizer])
|
||||
|
||||
useEffect(() => {
|
||||
parentRef.current?.scrollTo({ top: 0, left: 0 });
|
||||
}, [galleryScrollResetKey]);
|
||||
parentRef.current?.scrollTo({ top: 0, left: 0 })
|
||||
}, [galleryScrollResetKey])
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
if (el.scrollTop < 24) return;
|
||||
const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 600;
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
if (el.scrollTop < 24) return
|
||||
const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 600
|
||||
if (nearBottom && !loadingImages && images.length < totalImages) {
|
||||
void loadMoreImages();
|
||||
void loadMoreImages()
|
||||
}
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages]);
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages])
|
||||
|
||||
useEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (event: PointerEvent) => {
|
||||
if ((event.target as HTMLElement | null)?.closest("[data-gallery-context-menu]")) return;
|
||||
setContextMenu(null);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setContextMenu(null);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", close);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
el.addEventListener('scroll', handleScroll, { passive: true })
|
||||
return () => el.removeEventListener('scroll', handleScroll)
|
||||
}, [handleScroll])
|
||||
|
||||
return (
|
||||
<div ref={parentRef} className="relative flex-1 overflow-y-auto overflow-x-hidden min-h-0 bg-gray-950">
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 min-w-72">
|
||||
<div className="h-5 w-5 mx-auto rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<p className="mt-4 text-sm text-white/40 font-medium">
|
||||
{isSimilarResults
|
||||
? "Finding similar images"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? `Searching for matches to "${parsedSearch.query}"`
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? `Searching tags for "${parsedSearch.query}"`
|
||||
: "Loading media"}
|
||||
</p>
|
||||
<p className="text-xs text-white/20 mt-1">
|
||||
{isSimilarResults
|
||||
? "Comparing visual embeddings"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "Semantic search can take a little longer than filename search"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "Matching against AI and user tags"
|
||||
: "Fetching results"}
|
||||
</p>
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<div
|
||||
ref={parentRef}
|
||||
className="absolute inset-0 overflow-x-hidden overflow-y-auto bg-gray-950"
|
||||
>
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<GalleryLoadingState isSimilarResults={isSimilarResults} parsedSearch={parsedSearch} />
|
||||
) : images.length === 0 && !loadingImages ? (
|
||||
<GalleryEmptyState
|
||||
imageLoadError={imageLoadError}
|
||||
isSimilarResults={isSimilarResults}
|
||||
parsedSearch={parsedSearch}
|
||||
/>
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const startIndex = virtualRow.index * cols
|
||||
const rowImages = images.slice(startIndex, startIndex + cols)
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: virtualRow.start,
|
||||
width: '100%',
|
||||
height: virtualRow.size,
|
||||
display: 'grid',
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
{rowImages.map((image) => (
|
||||
<ImageTile
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault()
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : images.length === 0 && !loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<svg className="h-12 w-12 mx-auto text-white/10 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={0.75}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p className="text-sm text-white/30 font-medium">
|
||||
{imageLoadError
|
||||
? "Could not load results"
|
||||
: isSimilarResults
|
||||
? "No similar images found"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "No semantic matches found"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "No tag matches found"
|
||||
: "No media found"}
|
||||
</p>
|
||||
<p className="text-xs text-white/15 mt-1">
|
||||
{imageLoadError
|
||||
? imageLoadError
|
||||
: isSimilarResults
|
||||
? "This item may be visually isolated, or more embeddings may need to finish processing"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "Try a broader phrase, or wait for more embeddings to finish processing"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "Try a shorter tag, or wait for more tagging jobs to finish"
|
||||
: "Try adjusting your filters or add a new folder"}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
|
||||
{virtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const startIndex = virtualRow.index * cols;
|
||||
const rowImages = images.slice(startIndex, startIndex + cols);
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: virtualRow.start,
|
||||
width: "100%",
|
||||
height: virtualRow.size,
|
||||
display: "grid",
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
>
|
||||
{rowImages.map((image) => (
|
||||
<ImageTile
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
</div>
|
||||
) : null}
|
||||
{contextMenu ? (
|
||||
<ImageContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
onClose={() => setContextMenu(null)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{contextMenu ? (
|
||||
<ContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
onClose={() => setContextMenu(null)}
|
||||
/>
|
||||
) : null}
|
||||
{/* Pinned to the bottom of the gallery viewport — outside the scroll
|
||||
container so it stays put while the grid scrolls. */}
|
||||
<BulkActionBar />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { ImageRecord, useGalleryStore } from '../store'
|
||||
import { ContextMenu, MenuItem, MenuLabel, MenuSeparator, SubMenu } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon, StarIcon } from './icons'
|
||||
|
||||
/** Right-click menu for an image tile. Shared by the Gallery grid and the Timeline. */
|
||||
export function ImageContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
onClose: () => void
|
||||
}) {
|
||||
const openImage = useGalleryStore((state) => state.openImage)
|
||||
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails)
|
||||
const findSimilar = useGalleryStore((state) => state.findSimilar)
|
||||
const albums = useGalleryStore((state) => state.albums)
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum)
|
||||
const canFindSimilar = image.embedding_status === 'ready'
|
||||
|
||||
return (
|
||||
<ContextMenu x={x} y={y} onClose={onClose}>
|
||||
<MenuItem label="Open Preview" onSelect={() => openImage(image)} />
|
||||
<MenuItem
|
||||
label={image.favorite ? 'Remove Favorite' : 'Add to Favorites'}
|
||||
onSelect={() => void updateImageDetails(image.id, { favorite: !image.favorite })}
|
||||
/>
|
||||
<MenuItem
|
||||
label={canFindSimilar ? 'Find Similar' : 'Embeddings not ready'}
|
||||
disabled={!canFindSimilar}
|
||||
onSelect={() => findSimilar(image.id, image.folder_id)}
|
||||
/>
|
||||
<SubMenu label="Add to Album" panelClassName="max-h-64 overflow-y-auto">
|
||||
{albums.length === 0 ? (
|
||||
<MenuItem label="No albums yet" disabled />
|
||||
) : (
|
||||
albums.map((album) => (
|
||||
<MenuItem
|
||||
key={album.id}
|
||||
label={album.name}
|
||||
hint={album.image_count.toLocaleString()}
|
||||
onSelect={() => void addToAlbum(album.id, [image.id])}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</SubMenu>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>Rating</MenuLabel>
|
||||
<div className="flex items-center gap-0.5 px-2 pb-1.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1
|
||||
return (
|
||||
<Tooltip key={rating} label={`Set ${rating} star rating`} followCursor>
|
||||
<button
|
||||
className="rounded-md p-1 transition-colors hover:bg-white/5"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating })
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<StarIcon
|
||||
className={`h-4 w-4 ${rating <= image.rating ? 'text-amber-300' : 'text-white/20 hover:text-white/40'}`}
|
||||
/>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
{image.rating > 0 ? (
|
||||
<Tooltip label="Remove rating" followCursor>
|
||||
<button
|
||||
className="ml-1 rounded-md p-1 text-gray-600 transition-colors hover:bg-white/5 hover:text-gray-300"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating: 0 })
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<CloseIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Compact Confirm/Cancel pair for destructive row actions (remove folder,
|
||||
* delete album). Swap it in where the hover actions normally sit.
|
||||
*/
|
||||
export function InlineConfirm({
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-1" onClick={(event) => event.stopPropagation()}>
|
||||
<button
|
||||
className="rounded bg-red-500/20 px-1.5 py-0.5 text-[10px] text-red-400 transition-colors hover:bg-red-500/30 hover:text-red-300"
|
||||
onClick={onConfirm}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-gray-500 transition-colors hover:bg-white/10 hover:text-gray-300"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
/**
|
||||
* In-place rename input for sidebar rows (folders, albums). Mount it in
|
||||
* place of the row label while renaming: commits on Enter or blur (only when
|
||||
* the trimmed name is non-empty and actually changed), cancels on Escape.
|
||||
*/
|
||||
export function InlineRename({
|
||||
name,
|
||||
onRename,
|
||||
onClose,
|
||||
}: {
|
||||
name: string
|
||||
onRename: (next: string) => Promise<void> | void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [value, setValue] = useState(name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus()
|
||||
inputRef.current?.select()
|
||||
}, [])
|
||||
|
||||
const commit = async () => {
|
||||
const trimmed = value.trim()
|
||||
if (trimmed && trimmed !== name) {
|
||||
await onRename(trimmed)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="w-full rounded bg-white/10 px-1 py-0 text-[13px] leading-tight font-medium text-white ring-1 ring-blue-500/60 outline-none"
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
void commit()
|
||||
}
|
||||
if (event.key === 'Escape') onClose()
|
||||
}}
|
||||
onBlur={() => void commit()}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { MediaFilter, ZoomPreset, useGalleryStore } from "../store";
|
||||
|
||||
type MenuKey = "library" | "view" | "filter";
|
||||
|
||||
function MenuButton({
|
||||
label,
|
||||
active,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`rounded-md px-2.5 py-1 text-xs transition-colors ${
|
||||
active ? "bg-white/10 text-white" : "text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function MenuPanel({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="absolute left-0 top-full z-30 mt-2 min-w-56 rounded-xl border border-white/10 bg-gray-950/95 p-2 shadow-2xl backdrop-blur">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MenuItem({
|
||||
label,
|
||||
hint,
|
||||
active = false,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
active?: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
active ? "bg-blue-500/15 text-white" : "text-gray-300 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
<span>{label}</span>
|
||||
{hint ? <span className="text-xs text-gray-500">{hint}</span> : null}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const ZOOM_OPTIONS: { value: ZoomPreset; label: string }[] = [
|
||||
{ value: "compact", label: "Compact Grid" },
|
||||
{ value: "comfortable", label: "Comfortable Grid" },
|
||||
{ value: "detail", label: "Detail Grid" },
|
||||
];
|
||||
|
||||
const FILTER_OPTIONS: { value: MediaFilter; label: string }[] = [
|
||||
{ value: "all", label: "All Media" },
|
||||
{ value: "image", label: "Images" },
|
||||
{ value: "video", label: "Videos" },
|
||||
];
|
||||
|
||||
export function MenuBar() {
|
||||
const [openMenu, setOpenMenu] = useState<MenuKey | null>(null);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen);
|
||||
const reindexFolder = useGalleryStore((state) => state.reindexFolder);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const setZoomPreset = useGalleryStore((state) => state.setZoomPreset);
|
||||
const mediaFilter = useGalleryStore((state) => state.mediaFilter);
|
||||
const setMediaFilter = useGalleryStore((state) => state.setMediaFilter);
|
||||
const favoritesOnly = useGalleryStore((state) => state.favoritesOnly);
|
||||
const setFavoritesOnly = useGalleryStore((state) => state.setFavoritesOnly);
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerDown = (event: MouseEvent) => {
|
||||
if (!rootRef.current?.contains(event.target as Node)) {
|
||||
setOpenMenu(null);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("pointerdown", handlePointerDown);
|
||||
return () => window.removeEventListener("pointerdown", handlePointerDown);
|
||||
}, []);
|
||||
|
||||
const handleAddFolder = () => {
|
||||
setFolderPickerOpen(true);
|
||||
setOpenMenu(null);
|
||||
};
|
||||
|
||||
const handleReindex = async () => {
|
||||
if (selectedFolderId !== null) {
|
||||
await reindexFolder(selectedFolderId);
|
||||
}
|
||||
setOpenMenu(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="relative z-20 flex items-center gap-1 border-b border-white/5 bg-gray-950/90 px-4 py-2 backdrop-blur">
|
||||
<div className="relative">
|
||||
<MenuButton
|
||||
label="Library"
|
||||
active={openMenu === "library"}
|
||||
onClick={() => setOpenMenu((current) => (current === "library" ? null : "library"))}
|
||||
/>
|
||||
{openMenu === "library" ? (
|
||||
<MenuPanel>
|
||||
<MenuItem label="Add Folder" hint="Ctrl+O soon" onClick={handleAddFolder} />
|
||||
<MenuItem
|
||||
label="Re-index Current Folder"
|
||||
hint={selectedFolderId === null ? "Select folder" : undefined}
|
||||
onClick={handleReindex}
|
||||
active={selectedFolderId !== null}
|
||||
/>
|
||||
</MenuPanel>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<MenuButton
|
||||
label="View"
|
||||
active={openMenu === "view"}
|
||||
onClick={() => setOpenMenu((current) => (current === "view" ? null : "view"))}
|
||||
/>
|
||||
{openMenu === "view" ? (
|
||||
<MenuPanel>
|
||||
{ZOOM_OPTIONS.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
label={option.label}
|
||||
active={zoomPreset === option.value}
|
||||
onClick={() => {
|
||||
setZoomPreset(option.value);
|
||||
setOpenMenu(null);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</MenuPanel>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<MenuButton
|
||||
label="Filter"
|
||||
active={openMenu === "filter"}
|
||||
onClick={() => setOpenMenu((current) => (current === "filter" ? null : "filter"))}
|
||||
/>
|
||||
{openMenu === "filter" ? (
|
||||
<MenuPanel>
|
||||
{FILTER_OPTIONS.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
label={option.label}
|
||||
active={mediaFilter === option.value}
|
||||
onClick={() => {
|
||||
setMediaFilter(option.value);
|
||||
setOpenMenu(null);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<div className="my-2 h-px bg-white/5" />
|
||||
<MenuItem
|
||||
label={favoritesOnly ? "Hide Favorites Only" : "Show Favorites Only"}
|
||||
active={favoritesOnly}
|
||||
onClick={() => {
|
||||
setFavoritesOnly(!favoritesOnly);
|
||||
setOpenMenu(null);
|
||||
}}
|
||||
/>
|
||||
</MenuPanel>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,14 +6,14 @@
|
||||
//
|
||||
// Pass dotClassName (e.g. "fill-amber-400") to light up the central focal point —
|
||||
// used in the titlebar as the "update available" indicator.
|
||||
const BLADE = "M0,-4.18 A10,10 0 0 1 6.43,-7.66";
|
||||
const BLADE = 'M0,-4.18 A10,10 0 0 1 6.43,-7.66'
|
||||
|
||||
export function PhokusMark({
|
||||
className,
|
||||
dotClassName,
|
||||
}: {
|
||||
className?: string;
|
||||
dotClassName?: string;
|
||||
className?: string
|
||||
dotClassName?: string
|
||||
}) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="none" className={className}>
|
||||
@@ -33,7 +33,9 @@ export function PhokusMark({
|
||||
<path d={BLADE} transform="rotate(240)" />
|
||||
<path d={BLADE} transform="rotate(300)" />
|
||||
</g>
|
||||
{dotClassName ? <circle cx="12" cy="12" r="2.6" stroke="none" className={dotClassName} /> : null}
|
||||
{dotClassName ? (
|
||||
<circle cx="12" cy="12" r="2.6" stroke="none" className={dotClassName} />
|
||||
) : null}
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,323 +1,80 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { AppTheme, CleanupOrphanedThumbnailsResult, DatabaseInfo, OrphanedThumbnailsInfo, TaggerAcceleration, TaggingQueueScope, VacuumResult, useGalleryStore } from "../store";
|
||||
import { FfmpegStatusRow } from "./onboarding/StepWelcome";
|
||||
import { ThemedDropdown } from "./ThemedDropdown";
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
import { AiWorkspaceSettingsSection } from './settings/AiWorkspaceSettingsSection'
|
||||
import { GeneralSettingsSection } from './settings/GeneralSettingsSection'
|
||||
import { MediaSettingsSection } from './settings/MediaSettingsSection'
|
||||
import { StorageSettingsSection } from './settings/StorageSettingsSection'
|
||||
import { UpdatesSettingsSection } from './settings/UpdatesSettingsSection'
|
||||
import { SETTINGS_SECTIONS, SettingsSection } from './settings/shared'
|
||||
|
||||
type SettingsSection = "workspace" | "general";
|
||||
|
||||
const SECTIONS: { id: SettingsSection; label: string; detail: string }[] = [
|
||||
{ id: "general", label: "General", detail: "App data and diagnostics" },
|
||||
{ id: "workspace", label: "AI Workspace", detail: "Tagging models and queue targets" },
|
||||
];
|
||||
|
||||
function formatBytesShort(bytes: number): string {
|
||||
if (bytes >= 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(0)} MB`;
|
||||
return `${(bytes / 1024).toFixed(0)} KB`;
|
||||
}
|
||||
|
||||
function StatusPill({ children, tone }: { children: React.ReactNode; tone: "ready" | "muted" | "busy" }) {
|
||||
const className =
|
||||
tone === "ready"
|
||||
? "border-emerald-400/25 bg-emerald-500/10 text-emerald-300 light-theme:border-emerald-600/40 light-theme:bg-emerald-100 light-theme:text-emerald-700"
|
||||
: tone === "busy"
|
||||
? "border-sky-400/25 bg-sky-500/10 text-sky-300 light-theme:border-sky-600/40 light-theme:bg-sky-100 light-theme:text-sky-700"
|
||||
: "border-white/10 bg-white/[0.04] text-gray-500";
|
||||
|
||||
return <span className={`inline-flex rounded-md border px-2 py-0.5 text-[11px] font-medium ${className}`}>{children}</span>;
|
||||
}
|
||||
|
||||
function SettingsGroup({ title, description, children }: {
|
||||
title: string;
|
||||
description?: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section>
|
||||
<h4 className="text-[12px] font-semibold uppercase tracking-[0.08em] text-gray-400">{title}</h4>
|
||||
{description ? <p className="mt-1 text-xs leading-relaxed text-gray-600">{description}</p> : null}
|
||||
<div className="mt-1 divide-y divide-white/[0.05]">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function SettingsItem({ label, description, children, vertical = false }: {
|
||||
label: React.ReactNode;
|
||||
description?: React.ReactNode;
|
||||
children?: React.ReactNode;
|
||||
vertical?: boolean;
|
||||
}) {
|
||||
if (vertical) {
|
||||
return (
|
||||
<div className="py-4">
|
||||
<p className="text-sm text-white">{label}</p>
|
||||
{description ? <div className="mt-1 text-xs leading-relaxed text-gray-500">{description}</div> : null}
|
||||
{children ? <div className="mt-3">{children}</div> : null}
|
||||
</div>
|
||||
);
|
||||
function ActiveSettingsSection({ section }: { section: SettingsSection }) {
|
||||
switch (section) {
|
||||
case 'workspace':
|
||||
return <AiWorkspaceSettingsSection />
|
||||
case 'media':
|
||||
return <MediaSettingsSection />
|
||||
case 'updates':
|
||||
return <UpdatesSettingsSection />
|
||||
case 'storage':
|
||||
return <StorageSettingsSection />
|
||||
case 'general':
|
||||
default:
|
||||
return <GeneralSettingsSection />
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-start justify-between gap-6 py-4">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm text-white">{label}</p>
|
||||
{description ? <div className="mt-1 max-w-xl text-xs leading-relaxed text-gray-500">{description}</div> : null}
|
||||
</div>
|
||||
<div className="shrink-0">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatPair({ label, value, accent = false }: { label: string; value: string; accent?: boolean }) {
|
||||
return (
|
||||
<span className="inline-flex items-baseline gap-2">
|
||||
<span className="text-[10px] uppercase tracking-[0.14em] text-gray-600">{label}</span>
|
||||
<span className={`text-sm font-semibold tabular-nums ${accent ? "text-emerald-300" : "text-white"}`}>{value}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ScopeButton({ scope, current, onSelect, children }: {
|
||||
scope: TaggingQueueScope;
|
||||
current: TaggingQueueScope;
|
||||
onSelect: (scope: TaggingQueueScope) => void;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const active = scope === current;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md border px-3 py-1.5 text-xs transition-colors ${
|
||||
active
|
||||
? "border-emerald-400/35 bg-emerald-500/15 text-emerald-200 light-theme:border-emerald-600/50 light-theme:bg-emerald-100 light-theme:text-emerald-700"
|
||||
: "border-transparent text-gray-500 hover:bg-white/[0.06] hover:text-gray-200 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => onSelect(scope)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function TaggerAccelerationButton({ acceleration, current, onSelect, children }: {
|
||||
acceleration: TaggerAcceleration;
|
||||
current: TaggerAcceleration;
|
||||
onSelect: (acceleration: TaggerAcceleration) => void;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const active = acceleration === current;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`rounded-md border px-3 py-1.5 text-xs transition-colors ${
|
||||
active
|
||||
? "border-emerald-400/35 bg-emerald-500/15 text-emerald-200 light-theme:border-emerald-600/50 light-theme:bg-emerald-100 light-theme:text-emerald-700"
|
||||
: "border-transparent text-gray-500 hover:bg-white/[0.06] hover:text-gray-200 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => onSelect(acceleration)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsModal() {
|
||||
const [activeSection, setActiveSection] = useState<SettingsSection>("general");
|
||||
const [taggerQueueStatus, setTaggerQueueStatus] = useState<string | null>(null);
|
||||
const [taggerQueueing, setTaggerQueueing] = useState(false);
|
||||
const [taggerClearing, setTaggerClearing] = useState(false);
|
||||
const [taggerAccelerationSaving, setTaggerAccelerationSaving] = useState(false);
|
||||
const [taggerAccelerationError, setTaggerAccelerationError] = useState<string | null>(null);
|
||||
const [taggerThresholdDraft, setTaggerThresholdDraft] = useState<string | null>(null);
|
||||
const [taggerThresholdSaving, setTaggerThresholdSaving] = useState(false);
|
||||
const [taggerThresholdError, setTaggerThresholdError] = useState<string | null>(null);
|
||||
const [taggerBatchSizeDraft, setTaggerBatchSizeDraft] = useState<string | null>(null);
|
||||
const [taggerBatchSizeSaving, setTaggerBatchSizeSaving] = useState(false);
|
||||
const [taggerBatchSizeError, setTaggerBatchSizeError] = useState<string | null>(null);
|
||||
const [openingDataFolder, setOpeningDataFolder] = useState(false);
|
||||
const [dbInfo, setDbInfo] = useState<DatabaseInfo | null>(null);
|
||||
const [vacuuming, setVacuuming] = useState(false);
|
||||
const [vacuumResult, setVacuumResult] = useState<VacuumResult | null>(null);
|
||||
const [rebuildingIndex, setRebuildingIndex] = useState(false);
|
||||
const [rebuildIndexResult, setRebuildIndexResult] = useState<string | null>(null);
|
||||
const [thumbnailInfo, setThumbnailInfo] = useState<OrphanedThumbnailsInfo | null>(null);
|
||||
const [cleaningThumbnails, setCleaningThumbnails] = useState(false);
|
||||
const [thumbnailCleanupResult, setThumbnailCleanupResult] = useState<CleanupOrphanedThumbnailsResult | null>(null);
|
||||
const [activeSection, setActiveSection] = useState<SettingsSection>('general')
|
||||
|
||||
const thresholdErrorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const batchSizeErrorTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const settingsOpen = useGalleryStore((state) => state.settingsOpen);
|
||||
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen);
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
|
||||
const taggingQueueScope = useGalleryStore((state) => state.taggingQueueScope);
|
||||
const taggingQueueFolderIds = useGalleryStore((state) => state.taggingQueueFolderIds);
|
||||
const loadTaggingQueueScope = useGalleryStore((state) => state.loadTaggingQueueScope);
|
||||
const setTaggingQueueScope = useGalleryStore((state) => state.setTaggingQueueScope);
|
||||
const toggleTaggingQueueFolder = useGalleryStore((state) => state.toggleTaggingQueueFolder);
|
||||
const setTaggingQueueFolderIds = useGalleryStore((state) => state.setTaggingQueueFolderIds);
|
||||
const loadTaggingQueueFolderIds = useGalleryStore((state) => state.loadTaggingQueueFolderIds);
|
||||
const taggerModelStatus = useGalleryStore((state) => state.taggerModelStatus);
|
||||
const taggerModelPreparing = useGalleryStore((state) => state.taggerModelPreparing);
|
||||
const taggerModelProgress = useGalleryStore((state) => state.taggerModelProgress);
|
||||
const taggerModelError = useGalleryStore((state) => state.taggerModelError);
|
||||
const taggerAcceleration = useGalleryStore((state) => state.taggerAcceleration);
|
||||
const taggerThreshold = useGalleryStore((state) => state.taggerThreshold);
|
||||
const taggerBatchSize = useGalleryStore((state) => state.taggerBatchSize);
|
||||
const taggerRuntimeProbe = useGalleryStore((state) => state.taggerRuntimeProbe);
|
||||
const taggerRuntimeChecking = useGalleryStore((state) => state.taggerRuntimeChecking);
|
||||
const loadTaggerModelStatus = useGalleryStore((state) => state.loadTaggerModelStatus);
|
||||
const prepareTaggerModel = useGalleryStore((state) => state.prepareTaggerModel);
|
||||
const deleteTaggerModel = useGalleryStore((state) => state.deleteTaggerModel);
|
||||
const loadTaggerAcceleration = useGalleryStore((state) => state.loadTaggerAcceleration);
|
||||
const setTaggerAcceleration = useGalleryStore((state) => state.setTaggerAcceleration);
|
||||
const loadTaggerThreshold = useGalleryStore((state) => state.loadTaggerThreshold);
|
||||
const setTaggerThreshold = useGalleryStore((state) => state.setTaggerThreshold);
|
||||
const loadTaggerBatchSize = useGalleryStore((state) => state.loadTaggerBatchSize);
|
||||
const setTaggerBatchSize = useGalleryStore((state) => state.setTaggerBatchSize);
|
||||
const probeTaggerRuntime = useGalleryStore((state) => state.probeTaggerRuntime);
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs);
|
||||
const queueTaggingJobsForFolders = useGalleryStore((state) => state.queueTaggingJobsForFolders);
|
||||
const clearTaggingJobs = useGalleryStore((state) => state.clearTaggingJobs);
|
||||
const clearTaggingJobsForFolders = useGalleryStore((state) => state.clearTaggingJobsForFolders);
|
||||
const openAppDataFolder = useGalleryStore((state) => state.openAppDataFolder);
|
||||
const notificationsPaused = useGalleryStore((state) => state.notificationsPaused);
|
||||
const setNotificationsPaused = useGalleryStore((state) => state.setNotificationsPaused);
|
||||
const getDatabaseInfo = useGalleryStore((state) => state.getDatabaseInfo);
|
||||
const vacuumDatabase = useGalleryStore((state) => state.vacuumDatabase);
|
||||
const rebuildSemanticIndex = useGalleryStore((state) => state.rebuildSemanticIndex);
|
||||
const getOrphanedThumbnailsInfo = useGalleryStore((state) => state.getOrphanedThumbnailsInfo);
|
||||
const cleanupOrphanedThumbnails = useGalleryStore((state) => state.cleanupOrphanedThumbnails);
|
||||
const appVersion = useGalleryStore((state) => state.appVersion);
|
||||
const updateStatus = useGalleryStore((state) => state.updateStatus);
|
||||
const updateVersion = useGalleryStore((state) => state.updateVersion);
|
||||
const updateError = useGalleryStore((state) => state.updateError);
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates);
|
||||
const installUpdate = useGalleryStore((state) => state.installUpdate);
|
||||
const openOnboarding = useGalleryStore((state) => state.openOnboarding);
|
||||
const theme = useGalleryStore((state) => state.theme);
|
||||
const setTheme = useGalleryStore((state) => state.setTheme);
|
||||
const lightboxAutoplay = useGalleryStore((state) => state.lightboxAutoplay);
|
||||
const setLightboxAutoplay = useGalleryStore((state) => state.setLightboxAutoplay);
|
||||
const lightboxAutoMute = useGalleryStore((state) => state.lightboxAutoMute);
|
||||
const setLightboxAutoMute = useGalleryStore((state) => state.setLightboxAutoMute);
|
||||
const settingsOpen = useGalleryStore((state) => state.settingsOpen)
|
||||
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen)
|
||||
const loadTaggingQueueScope = useGalleryStore((state) => state.loadTaggingQueueScope)
|
||||
const loadTaggingQueueFolderIds = useGalleryStore((state) => state.loadTaggingQueueFolderIds)
|
||||
const loadTaggerModelStatus = useGalleryStore((state) => state.loadTaggerModelStatus)
|
||||
const loadTaggerAcceleration = useGalleryStore((state) => state.loadTaggerAcceleration)
|
||||
const loadTaggerModel = useGalleryStore((state) => state.loadTaggerModel)
|
||||
const loadTaggerThreshold = useGalleryStore((state) => state.loadTaggerThreshold)
|
||||
const loadTaggerBatchSize = useGalleryStore((state) => state.loadTaggerBatchSize)
|
||||
|
||||
useEffect(() => {
|
||||
if (!settingsOpen) return;
|
||||
void loadTaggerModelStatus();
|
||||
void loadTaggerAcceleration();
|
||||
void loadTaggerThreshold();
|
||||
void loadTaggerBatchSize();
|
||||
void loadTaggingQueueScope();
|
||||
void loadTaggingQueueFolderIds();
|
||||
if (!settingsOpen) return
|
||||
void loadTaggerModelStatus()
|
||||
void loadTaggerModel()
|
||||
void loadTaggerAcceleration()
|
||||
void loadTaggerThreshold()
|
||||
void loadTaggerBatchSize()
|
||||
void loadTaggingQueueScope()
|
||||
void loadTaggingQueueFolderIds()
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setSettingsOpen(false);
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [settingsOpen, loadTaggerModelStatus, loadTaggerAcceleration, loadTaggerThreshold, loadTaggerBatchSize, loadTaggingQueueScope, loadTaggingQueueFolderIds, setSettingsOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!settingsOpen || activeSection !== "general") return;
|
||||
setVacuumResult(null);
|
||||
setThumbnailCleanupResult(null);
|
||||
void getDatabaseInfo().then(setDbInfo).catch(() => {});
|
||||
void getOrphanedThumbnailsInfo().then(setThumbnailInfo).catch(() => {});
|
||||
}, [settingsOpen, activeSection, getDatabaseInfo, getOrphanedThumbnailsInfo]);
|
||||
|
||||
// Clean up error timers on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (thresholdErrorTimerRef.current) clearTimeout(thresholdErrorTimerRef.current);
|
||||
if (batchSizeErrorTimerRef.current) clearTimeout(batchSizeErrorTimerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const selectedFolders = useMemo(
|
||||
() => folders.filter((folder) => taggingQueueFolderIds.includes(folder.id)),
|
||||
[folders, taggingQueueFolderIds],
|
||||
);
|
||||
|
||||
if (!settingsOpen) return null;
|
||||
|
||||
const taggerReady = taggerModelStatus?.ready ?? false;
|
||||
const queueScopeLabel =
|
||||
taggingQueueScope === "all"
|
||||
? "all media"
|
||||
: selectedFolders.length > 0
|
||||
? `${selectedFolders.length} selected folder${selectedFolders.length === 1 ? "" : "s"}`
|
||||
: "no folders selected";
|
||||
const thresholdDisplay = taggerThresholdDraft ?? String(taggerThreshold);
|
||||
const batchSizeDisplay = taggerBatchSizeDraft ?? String(taggerBatchSize);
|
||||
const taggerBytesKnown =
|
||||
taggerModelProgress?.downloaded_bytes != null &&
|
||||
taggerModelProgress.total_bytes != null &&
|
||||
taggerModelProgress.total_bytes > 0;
|
||||
const taggerDownloadLabel = taggerBytesKnown
|
||||
? `Downloading ${formatBytesShort(taggerModelProgress!.downloaded_bytes!)} / ${formatBytesShort(taggerModelProgress!.total_bytes!)}`
|
||||
: taggerModelProgress
|
||||
? `Downloading ${taggerModelProgress.completed_files}/${taggerModelProgress.total_files}`
|
||||
: taggerModelPreparing
|
||||
? "Preparing WD Tagger..."
|
||||
: taggerReady
|
||||
? "Installed"
|
||||
: "Install model";
|
||||
const taggerDownloadPercent = taggerBytesKnown
|
||||
? Math.round((taggerModelProgress!.downloaded_bytes! / taggerModelProgress!.total_bytes!) * 100)
|
||||
: taggerModelProgress
|
||||
? Math.round((taggerModelProgress.completed_files / Math.max(taggerModelProgress.total_files, 1)) * 100)
|
||||
: 0;
|
||||
|
||||
const runQueueAction = (action: "queue" | "clear") => {
|
||||
const selectedIds = taggingQueueFolderIds;
|
||||
const perform =
|
||||
taggingQueueScope === "all"
|
||||
? action === "queue"
|
||||
? queueTaggingJobs(null)
|
||||
: clearTaggingJobs(null)
|
||||
: selectedIds.length > 0
|
||||
? action === "queue"
|
||||
? queueTaggingJobsForFolders(selectedIds)
|
||||
: clearTaggingJobsForFolders(selectedIds)
|
||||
: Promise.resolve(0);
|
||||
|
||||
if (action === "queue") {
|
||||
setTaggerQueueing(true);
|
||||
} else {
|
||||
setTaggerClearing(true);
|
||||
if (event.key === 'Escape') setSettingsOpen(false)
|
||||
}
|
||||
setTaggerQueueStatus(null);
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [
|
||||
settingsOpen,
|
||||
loadTaggerModelStatus,
|
||||
loadTaggerModel,
|
||||
loadTaggerAcceleration,
|
||||
loadTaggerThreshold,
|
||||
loadTaggerBatchSize,
|
||||
loadTaggingQueueScope,
|
||||
loadTaggingQueueFolderIds,
|
||||
setSettingsOpen,
|
||||
])
|
||||
|
||||
void perform
|
||||
.then((count) => {
|
||||
if (taggingQueueScope === "selected" && selectedIds.length === 0) {
|
||||
setTaggerQueueStatus("Choose at least one folder before running tagging jobs.");
|
||||
return;
|
||||
}
|
||||
setTaggerQueueStatus(
|
||||
count === 0
|
||||
? action === "queue"
|
||||
? "No missing tags found for the current target."
|
||||
: "No queued tagging jobs to clear for the current target."
|
||||
: action === "queue"
|
||||
? `Queued ${count.toLocaleString()} image${count === 1 ? "" : "s"} for tagging.`
|
||||
: `Cleared ${count.toLocaleString()} queued tagging job${count === 1 ? "" : "s"}.`,
|
||||
);
|
||||
})
|
||||
.catch((error) => setTaggerQueueStatus(String(error)))
|
||||
.finally(() => {
|
||||
if (action === "queue") {
|
||||
setTaggerQueueing(false);
|
||||
} else {
|
||||
setTaggerClearing(false);
|
||||
}
|
||||
});
|
||||
};
|
||||
if (!settingsOpen) return null
|
||||
|
||||
const activeSectionMeta =
|
||||
SETTINGS_SECTIONS.find((section) => section.id === activeSection) ?? SETTINGS_SECTIONS[0]
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/65 px-6 backdrop-blur-sm" onClick={() => setSettingsOpen(false)}>
|
||||
<div
|
||||
className="fixed inset-0 z-[60] flex items-center justify-center bg-black/65 px-6 backdrop-blur-sm"
|
||||
onClick={() => setSettingsOpen(false)}
|
||||
>
|
||||
<div
|
||||
className="relative flex h-[min(85vh,900px)] w-[min(85vw,1400px)] overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
@@ -325,14 +82,15 @@ export function SettingsModal() {
|
||||
<aside className="flex w-64 shrink-0 flex-col border-r border-white/[0.07] bg-white/[0.025]">
|
||||
<div className="border-b border-white/[0.07] px-5 py-5">
|
||||
<p className="text-base font-semibold text-white">Settings</p>
|
||||
<p className="mt-1 text-xs text-gray-600">Operational controls for AI workflows</p>
|
||||
</div>
|
||||
<div className="flex-1 space-y-1 overflow-y-auto p-2">
|
||||
{SECTIONS.map((section) => (
|
||||
{SETTINGS_SECTIONS.map((section) => (
|
||||
<button
|
||||
key={section.id}
|
||||
className={`w-full rounded-md px-3 py-2.5 text-left transition-colors ${
|
||||
activeSection === section.id ? "bg-white/10 text-white" : "text-gray-500 hover:bg-white/[0.055] hover:text-gray-200"
|
||||
activeSection === section.id
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:bg-white/[0.055] hover:text-gray-200'
|
||||
}`}
|
||||
onClick={() => setActiveSection(section.id)}
|
||||
>
|
||||
@@ -343,566 +101,25 @@ export function SettingsModal() {
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<button
|
||||
className="absolute right-4 top-4 z-10 rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={() => setSettingsOpen(false)}
|
||||
title="Close settings"
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="absolute top-4 right-4 z-10">
|
||||
<Tooltip label="Close settings" anchorToCursor>
|
||||
<button
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={() => setSettingsOpen(false)}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<main className="min-w-0 flex-1 overflow-y-auto">
|
||||
<div className="px-10 py-8">
|
||||
<h3 className="text-lg font-semibold text-white">{activeSection === "workspace" ? "AI Workspace" : "General"}</h3>
|
||||
<p className="mt-1 text-xs text-gray-600">{activeSection === "workspace" ? "Model setup and queue targets" : "App data and diagnostics"}</p>
|
||||
|
||||
{activeSection === "workspace" ? (
|
||||
<div className="mt-8 space-y-9">
|
||||
<SettingsGroup title="Model">
|
||||
<SettingsItem
|
||||
label={
|
||||
<>
|
||||
WD SwinV2 Tagger v3{" "}
|
||||
<span className="ml-1.5 align-middle">
|
||||
<StatusPill tone={taggerReady ? "ready" : taggerModelPreparing ? "busy" : "muted"}>
|
||||
{taggerReady ? "Installed" : taggerModelPreparing ? "Preparing" : "Not installed"}
|
||||
</StatusPill>
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
description="Anime-focused vision model by SmilingWolf. Generates booru-style tags with configurable confidence thresholds."
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{taggerReady ? (
|
||||
<>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => void probeTaggerRuntime()}
|
||||
disabled={taggerRuntimeChecking}
|
||||
>
|
||||
{taggerRuntimeChecking ? "Checking runtime..." : "Check runtime"}
|
||||
</button>
|
||||
<button
|
||||
className="rounded-md border border-red-400/20 bg-red-500/10 px-3 py-1.5 text-xs text-red-200 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-red-400/50 light-theme:bg-red-50 light-theme:text-red-700 light-theme:hover:bg-red-100"
|
||||
onClick={() => void deleteTaggerModel()}
|
||||
disabled={taggerModelPreparing}
|
||||
>
|
||||
Delete model files
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
className="relative overflow-hidden rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => void prepareTaggerModel()}
|
||||
disabled={taggerModelPreparing}
|
||||
>
|
||||
{taggerModelProgress ? <span className="absolute inset-y-0 left-0 bg-emerald-400/15 transition-[width] duration-200" style={{ width: `${taggerDownloadPercent}%` }} /> : null}
|
||||
<span className="relative">{taggerDownloadLabel}</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem label="Tagger acceleration" description="Use DirectML when available, or fall back to CPU for reliability.">
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
<div className="flex rounded-lg border border-white/[0.07] p-0.5 light-theme:border-gray-300/80">
|
||||
{(["auto", "directml", "cpu"] as const).map((acceleration) => (
|
||||
<TaggerAccelerationButton
|
||||
key={acceleration}
|
||||
acceleration={acceleration}
|
||||
current={taggerAcceleration}
|
||||
onSelect={(nextAcceleration) => {
|
||||
setTaggerAccelerationSaving(true);
|
||||
setTaggerAccelerationError(null);
|
||||
void setTaggerAcceleration(nextAcceleration)
|
||||
.catch((error: unknown) => setTaggerAccelerationError(String(error)))
|
||||
.finally(() => setTaggerAccelerationSaving(false));
|
||||
}}
|
||||
>
|
||||
{acceleration === "directml" ? "DirectML" : acceleration === "cpu" ? "CPU" : "Auto"}
|
||||
</TaggerAccelerationButton>
|
||||
))}
|
||||
</div>
|
||||
{taggerAccelerationError ? (
|
||||
<p className="text-[11px] text-amber-300">{taggerAccelerationError}</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-gray-600">{taggerAccelerationSaving ? "Saving..." : `Current: ${taggerAcceleration}`}</p>
|
||||
)}
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem label="Confidence threshold" description="Lower values keep more tags. Higher values are stricter and usually cleaner.">
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
<input
|
||||
type="number"
|
||||
min="0.05"
|
||||
max="0.99"
|
||||
step="0.05"
|
||||
className="w-20 rounded-md border border-white/10 bg-white/5 px-2 py-1.5 text-xs text-white focus:border-white/20 focus:outline-none"
|
||||
value={thresholdDisplay}
|
||||
onChange={(event) => setTaggerThresholdDraft(event.target.value)}
|
||||
onBlur={() => {
|
||||
const value = parseFloat(thresholdDisplay);
|
||||
if (!isNaN(value) && value >= 0.05 && value <= 0.99) {
|
||||
setTaggerThresholdError(null);
|
||||
setTaggerThresholdSaving(true);
|
||||
void setTaggerThreshold(value)
|
||||
.catch((error: unknown) => setTaggerThresholdError(String(error)))
|
||||
.finally(() => {
|
||||
setTaggerThresholdDraft(null);
|
||||
setTaggerThresholdSaving(false);
|
||||
});
|
||||
} else {
|
||||
setTaggerThresholdDraft(null);
|
||||
setTaggerThresholdError("Must be 0.05 – 0.99");
|
||||
if (thresholdErrorTimerRef.current) clearTimeout(thresholdErrorTimerRef.current);
|
||||
thresholdErrorTimerRef.current = setTimeout(() => setTaggerThresholdError(null), 2000);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{taggerThresholdError ? (
|
||||
<p className="text-[11px] text-amber-300">{taggerThresholdError}</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-gray-600">{taggerThresholdSaving ? "Saving..." : "Default: 0.35"}</p>
|
||||
)}
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem label="Tagging batch size" description="Number of images processed concurrently during tag generation.">
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
step="1"
|
||||
className="w-20 rounded-md border border-white/10 bg-white/5 px-2 py-1.5 text-xs text-white focus:border-white/20 focus:outline-none"
|
||||
value={batchSizeDisplay}
|
||||
onChange={(event) => setTaggerBatchSizeDraft(event.target.value)}
|
||||
onBlur={() => {
|
||||
const value = parseInt(batchSizeDisplay, 10);
|
||||
if (!isNaN(value) && value >= 1 && value <= 100) {
|
||||
setTaggerBatchSizeError(null);
|
||||
setTaggerBatchSizeSaving(true);
|
||||
void setTaggerBatchSize(value)
|
||||
.catch((error: unknown) => setTaggerQueueStatus(String(error)))
|
||||
.finally(() => {
|
||||
setTaggerBatchSizeDraft(null);
|
||||
setTaggerBatchSizeSaving(false);
|
||||
});
|
||||
} else {
|
||||
setTaggerBatchSizeDraft(null);
|
||||
setTaggerBatchSizeError("Must be 1 – 100");
|
||||
if (batchSizeErrorTimerRef.current) clearTimeout(batchSizeErrorTimerRef.current);
|
||||
batchSizeErrorTimerRef.current = setTimeout(() => setTaggerBatchSizeError(null), 2000);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{taggerBatchSizeError ? (
|
||||
<p className="text-[11px] text-amber-300">{taggerBatchSizeError}</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-gray-600">{taggerBatchSizeSaving ? "Saving..." : "Default: 8"}</p>
|
||||
)}
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem label="Model location" vertical>
|
||||
<div>
|
||||
<p className="break-all font-mono text-xs text-gray-600">
|
||||
{taggerReady ? taggerModelStatus?.local_dir : "Not downloaded"}
|
||||
</p>
|
||||
{taggerModelProgress?.current_file ? <p className="mt-2 break-all text-xs text-gray-500">{taggerModelProgress.current_file}</p> : null}
|
||||
{taggerModelError ? <p className="mt-2 text-xs text-amber-300">{taggerModelError}</p> : null}
|
||||
{taggerRuntimeProbe ? (
|
||||
<div className="mt-3">
|
||||
<p className="text-xs text-gray-400">
|
||||
Runtime check <span className="ml-1.5 align-middle"><StatusPill tone="ready">Ready</StatusPill></span>
|
||||
<span className="ml-2 text-gray-600">acceleration: {taggerRuntimeProbe.acceleration}</span>
|
||||
</p>
|
||||
<p className="mt-1.5 break-all font-mono text-xs text-gray-600">{taggerRuntimeProbe.session.file}</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup title="Queue targets" description="Choose which folders to include when queuing tagging jobs.">
|
||||
<SettingsItem label="Target scope" description="Queue across the full library, or choose a specific folder set and keep the modal open while you work through it.">
|
||||
<div className="flex rounded-lg border border-white/[0.07] p-0.5 light-theme:border-gray-300/80">
|
||||
<ScopeButton scope="all" current={taggingQueueScope} onSelect={setTaggingQueueScope}>All media</ScopeButton>
|
||||
<ScopeButton scope="selected" current={taggingQueueScope} onSelect={setTaggingQueueScope}>Selected folders</ScopeButton>
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
<div className="py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm text-white">Folder selection</p>
|
||||
<p className="mt-1 text-xs leading-relaxed text-gray-500">Current target: {queueScopeLabel}.</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.045] px-2.5 py-1 text-[11px] text-gray-400 transition-colors hover:bg-white/[0.075] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => setTaggingQueueFolderIds(folders.map((folder) => folder.id))}
|
||||
disabled={taggingQueueScope === "all" || folders.length === 0}
|
||||
>
|
||||
Select all
|
||||
</button>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.045] px-2.5 py-1 text-[11px] text-gray-400 transition-colors hover:bg-white/[0.075] hover:text-white disabled:opacity-40 disabled:cursor-not-allowed light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => setTaggingQueueFolderIds([])}
|
||||
disabled={taggingQueueScope === "all" || taggingQueueFolderIds.length === 0}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`mt-2 max-h-64 divide-y divide-white/[0.04] overflow-y-auto pr-1 ${taggingQueueScope === "selected" ? "opacity-100" : "opacity-60"}`}>
|
||||
{folders.map((folder) => {
|
||||
const active = taggingQueueFolderIds.includes(folder.id);
|
||||
const progress = mediaJobProgress[folder.id];
|
||||
return (
|
||||
<button
|
||||
key={folder.id}
|
||||
type="button"
|
||||
className={`flex w-full items-center justify-between gap-3 px-1 py-2 text-left transition-colors disabled:cursor-not-allowed ${
|
||||
active ? "text-white" : "text-gray-400 hover:text-gray-200"
|
||||
}`}
|
||||
onClick={() => toggleTaggingQueueFolder(folder.id)}
|
||||
disabled={taggingQueueScope === "all"}
|
||||
>
|
||||
<p className="min-w-0 truncate text-sm">{folder.name}</p>
|
||||
<div className="flex shrink-0 items-center gap-3">
|
||||
{(progress?.tagging_pending ?? 0) > 0 ? <StatusPill tone="busy">{progress?.tagging_pending} queued</StatusPill> : null}
|
||||
<span className="text-[11px] tabular-nums text-gray-600">{folder.image_count.toLocaleString()} items</span>
|
||||
<span className={`h-4 w-4 rounded-full border ${active ? "border-emerald-300 bg-emerald-300" : "border-white/15 bg-transparent"}`} />
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{folders.length === 0 ? <p className="py-2 text-sm text-gray-500">Add a folder first to enable targeted tagging queues.</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<SettingsItem label="Queue tagging jobs" description="Generate missing AI tags for the current target. Results flow back into the library as the background worker finishes.">
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => runQueueAction("queue")}
|
||||
disabled={!taggerReady || taggerQueueing || taggerClearing || (taggingQueueScope === "selected" && taggingQueueFolderIds.length === 0)}
|
||||
>
|
||||
{taggerQueueing ? "Queueing..." : "Queue tagging"}
|
||||
</button>
|
||||
<button
|
||||
className="rounded-md border border-amber-400/20 bg-amber-500/10 px-3 py-1.5 text-xs text-amber-200 transition-colors hover:bg-amber-500/15 disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-amber-500/50 light-theme:bg-amber-50 light-theme:text-amber-700 light-theme:hover:bg-amber-100"
|
||||
onClick={() => runQueueAction("clear")}
|
||||
disabled={taggerQueueing || taggerClearing || (taggingQueueScope === "selected" && taggingQueueFolderIds.length === 0)}
|
||||
>
|
||||
{taggerClearing ? "Clearing..." : "Clear queued jobs"}
|
||||
</button>
|
||||
</div>
|
||||
</SettingsItem>
|
||||
|
||||
{taggerQueueStatus ? <p className="pt-3 text-xs text-gray-500">{taggerQueueStatus}</p> : null}
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-8 space-y-9">
|
||||
<SettingsGroup title="Appearance">
|
||||
<SettingsItem label="Theme" description="Choose the app palette. Subtle Light uses a warm, low-glare background.">
|
||||
<ThemedDropdown
|
||||
value={theme}
|
||||
onChange={(value) => setTheme(value as AppTheme)}
|
||||
ariaLabel="App theme"
|
||||
options={[
|
||||
{ value: "phokus", label: "Phokus" },
|
||||
{ value: "subtle-light", label: "Subtle Light" },
|
||||
{ value: "conventional-dark", label: "Conventional Dark" },
|
||||
]}
|
||||
/>
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup title="Video playback">
|
||||
<SettingsItem
|
||||
label="Autoplay in lightbox"
|
||||
description="Start playing videos automatically when opened in the lightbox."
|
||||
>
|
||||
<button
|
||||
role="switch"
|
||||
aria-checked={lightboxAutoplay}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none ${lightboxAutoplay ? "bg-sky-500" : "bg-white/15"}`}
|
||||
onClick={() => setLightboxAutoplay(!lightboxAutoplay)}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${lightboxAutoplay ? "translate-x-4" : "translate-x-0"}`} />
|
||||
</button>
|
||||
</SettingsItem>
|
||||
<SettingsItem
|
||||
label="Start muted"
|
||||
description="Open videos with their audio muted — unmute from the player controls."
|
||||
>
|
||||
<button
|
||||
role="switch"
|
||||
aria-checked={lightboxAutoMute}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none ${lightboxAutoMute ? "bg-sky-500" : "bg-white/15"}`}
|
||||
onClick={() => setLightboxAutoMute(!lightboxAutoMute)}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${lightboxAutoMute ? "translate-x-4" : "translate-x-0"}`} />
|
||||
</button>
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup title="Updates">
|
||||
<SettingsItem
|
||||
label={
|
||||
<span className="inline-flex items-center gap-2.5">
|
||||
<span>Phokus {appVersion ? `v${appVersion}` : "—"}</span>
|
||||
{updateStatus === "available" || updateStatus === "downloading" || updateStatus === "installing" ? (
|
||||
<StatusPill tone="busy">v{updateVersion} available</StatusPill>
|
||||
) : updateStatus === "upToDate" ? (
|
||||
<StatusPill tone="ready">Up to date</StatusPill>
|
||||
) : null}
|
||||
</span>
|
||||
}
|
||||
description={
|
||||
updateStatus === "error" ? (
|
||||
<span className="text-amber-300/90">Update check failed: {updateError}</span>
|
||||
) : updateStatus === "downloading" || updateStatus === "installing" ? (
|
||||
"Downloading update — the app will restart when it finishes."
|
||||
) : (
|
||||
"Updates are checked quietly at launch and installed only when you choose."
|
||||
)
|
||||
}
|
||||
>
|
||||
{updateStatus === "available" ? (
|
||||
<button
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-3 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25 light-theme:border-emerald-600/50 light-theme:bg-emerald-100 light-theme:text-emerald-700 light-theme:hover:bg-emerald-200"
|
||||
onClick={() => void installUpdate()}
|
||||
>
|
||||
Install & restart
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => void checkForUpdates()}
|
||||
disabled={updateStatus === "checking" || updateStatus === "downloading" || updateStatus === "installing"}
|
||||
>
|
||||
{updateStatus === "checking" ? "Checking..." : "Check for updates"}
|
||||
</button>
|
||||
)}
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup title="Setup">
|
||||
<FfmpegStatusRow />
|
||||
<SettingsItem
|
||||
label="Welcome tour"
|
||||
description="Replay the guided first-run tour — library setup, the background pipeline, search modes, and AI features."
|
||||
>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => {
|
||||
setSettingsOpen(false);
|
||||
openOnboarding();
|
||||
}}
|
||||
>
|
||||
Show welcome tour
|
||||
</button>
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup title="Storage & notifications">
|
||||
<SettingsItem
|
||||
label="App data folder"
|
||||
description="Open the folder in Explorer to inspect or back up the database, thumbnails, and models."
|
||||
>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => {
|
||||
setOpeningDataFolder(true);
|
||||
void openAppDataFolder().finally(() => setOpeningDataFolder(false));
|
||||
}}
|
||||
disabled={openingDataFolder}
|
||||
>
|
||||
{openingDataFolder ? "Opening..." : "Open data folder"}
|
||||
</button>
|
||||
</SettingsItem>
|
||||
<SettingsItem
|
||||
label="Pause all notifications"
|
||||
description="Notifications are batched per folder — a single alert fires once activity settles. Mute individual folders from their right-click menu."
|
||||
>
|
||||
<button
|
||||
role="switch"
|
||||
aria-checked={notificationsPaused}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none ${notificationsPaused ? "bg-sky-500" : "bg-white/15"}`}
|
||||
onClick={() => setNotificationsPaused(!notificationsPaused)}
|
||||
>
|
||||
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${notificationsPaused ? "translate-x-4" : "translate-x-0"}`} />
|
||||
</button>
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup title="Maintenance">
|
||||
<SettingsItem
|
||||
label="Compact database"
|
||||
description={
|
||||
<>
|
||||
<span>Reclaims wasted space left behind when images or tags are deleted. Safe to run at any time.</span>
|
||||
<span className="mt-2.5 flex flex-wrap items-center gap-x-5 gap-y-1">
|
||||
<StatPair
|
||||
label="Size"
|
||||
value={
|
||||
vacuumResult
|
||||
? `${vacuumResult.after_mb.toFixed(1)} MB`
|
||||
: dbInfo
|
||||
? `${dbInfo.size_mb.toFixed(1)} MB`
|
||||
: "—"
|
||||
}
|
||||
/>
|
||||
<StatPair
|
||||
label="Reclaimable"
|
||||
accent={vacuumResult !== null}
|
||||
value={
|
||||
vacuumResult
|
||||
? `${vacuumResult.freed_mb.toFixed(1)} MB freed`
|
||||
: dbInfo
|
||||
? `${dbInfo.reclaimable_mb.toFixed(1)} MB`
|
||||
: "—"
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
<span className="mt-2 block text-gray-600">
|
||||
{vacuumResult
|
||||
? `Compacted from ${vacuumResult.before_mb.toFixed(1)} MB to ${vacuumResult.after_mb.toFixed(1)} MB.`
|
||||
: dbInfo && dbInfo.reclaimable_mb < 0.5
|
||||
? "Database is already compact."
|
||||
: "Run this after removing folders or bulk-deleting images."}
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => {
|
||||
setVacuuming(true);
|
||||
setVacuumResult(null);
|
||||
void vacuumDatabase()
|
||||
.then((result) => {
|
||||
setVacuumResult(result);
|
||||
setDbInfo({ size_mb: result.after_mb, reclaimable_mb: 0 });
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setVacuuming(false));
|
||||
}}
|
||||
disabled={vacuuming || (dbInfo !== null && dbInfo.reclaimable_mb < 0.5)}
|
||||
>
|
||||
{vacuuming ? "Compacting..." : "Compact now"}
|
||||
</button>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
label="Rebuild semantic index"
|
||||
description={
|
||||
<>
|
||||
<span>
|
||||
Recreates the visual-embedding index and re-embeds every image in the
|
||||
background. Use this if semantic or similar-image search reports a
|
||||
dimension-mismatch error (for example after experimenting with a
|
||||
different embedding model).
|
||||
</span>
|
||||
{rebuildIndexResult !== null ? (
|
||||
<span className="mt-2 block text-gray-600">{rebuildIndexResult}</span>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => {
|
||||
setRebuildingIndex(true);
|
||||
setRebuildIndexResult(null);
|
||||
void rebuildSemanticIndex()
|
||||
.then((count) =>
|
||||
setRebuildIndexResult(
|
||||
`Re-queued ${count.toLocaleString()} image${count === 1 ? "" : "s"} for embedding.`,
|
||||
),
|
||||
)
|
||||
.catch((error) => setRebuildIndexResult(String(error)))
|
||||
.finally(() => setRebuildingIndex(false));
|
||||
}}
|
||||
disabled={rebuildingIndex}
|
||||
>
|
||||
{rebuildingIndex ? "Rebuilding…" : "Rebuild index"}
|
||||
</button>
|
||||
</SettingsItem>
|
||||
|
||||
<SettingsItem
|
||||
label="Thumbnail cache"
|
||||
description={
|
||||
<>
|
||||
<span>Thumbnails left behind when folders or images are removed. Safe to delete — they are regenerated if the originals are re-indexed.</span>
|
||||
<span className="mt-2.5 flex flex-wrap items-center gap-x-5 gap-y-1">
|
||||
<StatPair
|
||||
label="Orphaned files"
|
||||
value={
|
||||
thumbnailCleanupResult
|
||||
? "0"
|
||||
: thumbnailInfo
|
||||
? thumbnailInfo.count.toLocaleString()
|
||||
: "—"
|
||||
}
|
||||
/>
|
||||
<StatPair
|
||||
label="Reclaimable"
|
||||
accent={thumbnailCleanupResult !== null}
|
||||
value={
|
||||
thumbnailCleanupResult
|
||||
? `${thumbnailCleanupResult.freed_mb.toFixed(1)} MB freed`
|
||||
: thumbnailInfo
|
||||
? `${thumbnailInfo.size_mb.toFixed(1)} MB`
|
||||
: "—"
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
<span className="mt-2 block text-gray-600">
|
||||
{cleaningThumbnails
|
||||
? "Scanning and removing orphaned thumbnails…"
|
||||
: thumbnailCleanupResult
|
||||
? `Removed ${thumbnailCleanupResult.deleted_count.toLocaleString()} file${thumbnailCleanupResult.deleted_count === 1 ? "" : "s"}, freed ${thumbnailCleanupResult.freed_mb.toFixed(1)} MB.`
|
||||
: thumbnailInfo && thumbnailInfo.count === 0
|
||||
? "No orphaned thumbnails found."
|
||||
: thumbnailInfo && thumbnailInfo.count > 1000
|
||||
? "May take a few minutes for large collections."
|
||||
: "Remove thumbnails no longer associated with any indexed image."}
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<button
|
||||
className="rounded-md border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => {
|
||||
setCleaningThumbnails(true);
|
||||
cleanupOrphanedThumbnails()
|
||||
.then((result) => {
|
||||
setThumbnailCleanupResult(result);
|
||||
setThumbnailInfo(null);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setCleaningThumbnails(false));
|
||||
}}
|
||||
disabled={cleaningThumbnails || thumbnailCleanupResult !== null || (thumbnailInfo !== null && thumbnailInfo.count === 0)}
|
||||
>
|
||||
{cleaningThumbnails ? "Cleaning…" : "Clean up"}
|
||||
</button>
|
||||
</SettingsItem>
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
)}
|
||||
<h3 className="text-lg font-semibold text-white">{activeSectionMeta.label}</h3>
|
||||
<p className="mt-1 text-xs text-gray-600">{activeSectionMeta.detail}</p>
|
||||
<ActiveSettingsSection section={activeSection} />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,606 +1,60 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Reorder, useDragControls } from "framer-motion";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { useGalleryStore, Folder, IndexProgress } from "../store";
|
||||
import { ThemedDropdown } from "./ThemedDropdown";
|
||||
|
||||
interface ContextMenuState {
|
||||
folderId: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
type LibrarySort = "az" | "za" | "custom";
|
||||
const LIBRARY_SORT_KEY = "phokus-library-sort";
|
||||
|
||||
function FolderContextMenu({
|
||||
menu,
|
||||
folder,
|
||||
isMuted,
|
||||
isPausedAll,
|
||||
onClose,
|
||||
onRename,
|
||||
onReindex,
|
||||
onLocate,
|
||||
onToggleMute,
|
||||
onTogglePauseAll,
|
||||
onRemove,
|
||||
}: {
|
||||
menu: ContextMenuState;
|
||||
folder: Folder;
|
||||
isMuted: boolean;
|
||||
isPausedAll: boolean;
|
||||
onClose: () => void;
|
||||
onRename: () => void;
|
||||
onReindex: () => void;
|
||||
onLocate: () => void;
|
||||
onToggleMute: () => void;
|
||||
onTogglePauseAll: () => void;
|
||||
onRemove: () => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const handleDown = (e: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(e.target as Node)) onClose();
|
||||
};
|
||||
const handleKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
document.addEventListener("mousedown", handleDown);
|
||||
document.addEventListener("keydown", handleKey);
|
||||
return () => {
|
||||
document.removeEventListener("mousedown", handleDown);
|
||||
document.removeEventListener("keydown", handleKey);
|
||||
};
|
||||
}, [onClose]);
|
||||
|
||||
const item = (label: string, onClick: () => void, danger = false) => (
|
||||
<button
|
||||
className={`w-full text-left px-3 py-1.5 text-[12px] rounded-md transition-colors ${
|
||||
danger
|
||||
? "text-red-400 hover:bg-red-500/15 hover:text-red-300"
|
||||
: "text-gray-300 hover:bg-white/8 hover:text-white"
|
||||
}`}
|
||||
onClick={() => { onClick(); onClose(); }}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="fixed z-50 min-w-[160px] py-1 px-1 rounded-lg bg-gray-900 border border-white/10 shadow-xl shadow-black/50"
|
||||
style={{ left: menu.x, top: menu.y }}
|
||||
>
|
||||
{item("Reindex", onReindex)}
|
||||
{item("Rename", onRename)}
|
||||
{item(isPausedAll ? "Resume background work" : "Pause background work", onTogglePauseAll)}
|
||||
{item(isMuted ? "Unmute notifications" : "Mute notifications", onToggleMute)}
|
||||
{folder.scan_error && item("Locate Folder", onLocate)}
|
||||
<div className="my-1 border-t border-white/[0.06]" />
|
||||
{item("Remove from app", onRemove, true)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FolderItem({
|
||||
folder,
|
||||
selected,
|
||||
progress,
|
||||
customOrdering,
|
||||
dragging,
|
||||
onDragStart,
|
||||
onDragEnd,
|
||||
onKeyboardMove,
|
||||
}: {
|
||||
folder: Folder;
|
||||
selected: boolean;
|
||||
progress: IndexProgress | undefined;
|
||||
customOrdering: boolean;
|
||||
dragging: boolean;
|
||||
onDragStart: (pointerY: number) => void;
|
||||
onDragEnd: () => void;
|
||||
onKeyboardMove: (direction: -1 | 1) => void;
|
||||
}) {
|
||||
const dragControls = useDragControls();
|
||||
const { selectFolder, removeFolder, reindexFolder, renameFolder, updateFolderPath, toggleMutedFolder } = useGalleryStore();
|
||||
const mutedFolderIds = useGalleryStore((state) => state.mutedFolderIds);
|
||||
const setAllWorkersPaused = useGalleryStore((state) => state.setAllWorkersPaused);
|
||||
const folderWorkers = useGalleryStore((state) => state.workerPaused[folder.id]);
|
||||
const isMuted = mutedFolderIds.includes(folder.id);
|
||||
// "Fully paused" only when every worker for this folder is paused.
|
||||
const isPausedAll = !!folderWorkers &&
|
||||
folderWorkers.thumbnail && folderWorkers.metadata && folderWorkers.embedding && folderWorkers.tagging;
|
||||
const isIndexing = progress && !progress.done;
|
||||
const isMissing = !!folder.scan_error && !isIndexing;
|
||||
|
||||
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const [renameValue, setRenameValue] = useState(folder.name);
|
||||
const [confirmingRemoval, setConfirmingRemoval] = useState(false);
|
||||
const renameInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (renaming) {
|
||||
setRenameValue(folder.name);
|
||||
setTimeout(() => renameInputRef.current?.select(), 0);
|
||||
}
|
||||
}, [renaming, folder.name]);
|
||||
|
||||
const handleContextMenu = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
// Keep menu inside viewport
|
||||
const x = Math.min(e.clientX, window.innerWidth - 180);
|
||||
const y = Math.min(e.clientY, window.innerHeight - 160);
|
||||
setContextMenu({ folderId: folder.id, x, y });
|
||||
};
|
||||
|
||||
const handleLocateFolder = async () => {
|
||||
const picked = await open({ directory: true, multiple: false, title: `Locate "${folder.name}"` });
|
||||
if (picked && typeof picked === "string") {
|
||||
await updateFolderPath(folder.id, picked);
|
||||
}
|
||||
};
|
||||
|
||||
const commitRename = async () => {
|
||||
const trimmed = renameValue.trim();
|
||||
if (trimmed && trimmed !== folder.name) {
|
||||
await renameFolder(folder.id, trimmed);
|
||||
}
|
||||
setRenaming(false);
|
||||
};
|
||||
|
||||
const handleRenameKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === "Enter") { e.preventDefault(); void commitRename(); }
|
||||
if (e.key === "Escape") { setRenaming(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<Reorder.Item
|
||||
as="div"
|
||||
value={folder.id}
|
||||
drag={customOrdering ? "y" : false}
|
||||
dragControls={dragControls}
|
||||
dragListener={false}
|
||||
dragElastic={0.08}
|
||||
onDragEnd={onDragEnd}
|
||||
layout
|
||||
transition={{ layout: { type: "spring", stiffness: 520, damping: 38, mass: 0.55 } }}
|
||||
className={`relative z-0 ${dragging ? "z-20" : ""}`}
|
||||
style={{ position: "relative" }}
|
||||
>
|
||||
<div
|
||||
className={`group relative flex items-center gap-2.5 px-3 py-2 rounded-lg cursor-pointer transition-all duration-150 ${
|
||||
selected
|
||||
? "bg-white/8 text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5"
|
||||
} ${dragging ? "scale-[1.02] bg-white/[0.11] text-white shadow-xl shadow-black/25 ring-1 ring-white/15" : ""}`}
|
||||
onClick={() => !renaming && selectFolder(folder.id)}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
{customOrdering ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Reorder ${folder.name}`}
|
||||
title={`Drag to reorder ${folder.name}`}
|
||||
className={`-ml-1 flex h-7 w-5 shrink-0 touch-none items-center justify-center rounded-md transition-colors ${
|
||||
dragging
|
||||
? "cursor-grabbing bg-white/10 text-gray-300"
|
||||
: "cursor-grab text-gray-700 hover:bg-white/[0.06] hover:text-gray-400"
|
||||
}`}
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
onDragStart(event.clientY);
|
||||
dragControls.start(event);
|
||||
}}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onKeyboardMove(event.key === "ArrowUp" ? -1 : 1);
|
||||
}}
|
||||
>
|
||||
<svg className="h-3 w-3" viewBox="0 0 12 12" fill="currentColor">
|
||||
<circle cx="3" cy="3" r="1" /><circle cx="9" cy="3" r="1" />
|
||||
<circle cx="3" cy="9" r="1" /><circle cx="9" cy="9" r="1" />
|
||||
</svg>
|
||||
</button>
|
||||
) : null}
|
||||
{isMissing ? (
|
||||
<span className="shrink-0 text-amber-400">
|
||||
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
|
||||
</svg>
|
||||
</span>
|
||||
) : (
|
||||
<svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M3 7a2 2 0 012-2h3.586a1 1 0 01.707.293l1.414 1.414A1 1 0 0011.414 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" />
|
||||
</svg>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
{renaming ? (
|
||||
<input
|
||||
ref={renameInputRef}
|
||||
className="w-full bg-white/10 text-white text-[13px] font-medium rounded px-1 py-0 outline-none ring-1 ring-blue-500/60 leading-tight"
|
||||
value={renameValue}
|
||||
onChange={(e) => setRenameValue(e.target.value)}
|
||||
onKeyDown={handleRenameKey}
|
||||
onBlur={() => void commitRename()}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
) : (
|
||||
<div className={`truncate text-[13px] font-medium leading-tight ${selected ? "text-white" : ""}`}>
|
||||
{folder.name}
|
||||
</div>
|
||||
)}
|
||||
{isIndexing ? (
|
||||
<>
|
||||
<div className="text-[11px] text-gray-600 mt-0.5">{progress.indexed}/{progress.total}</div>
|
||||
<div className="h-px bg-white/10 rounded mt-1.5 overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-blue-500 transition-all duration-300"
|
||||
style={{ width: `${progress.total > 0 ? (progress.indexed / progress.total) * 100 : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="text-[11px] text-gray-600 mt-0.5">{folder.image_count.toLocaleString()}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Hover action buttons */}
|
||||
{!renaming && (
|
||||
confirmingRemoval ? (
|
||||
<div className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
|
||||
<button
|
||||
className="px-1.5 py-0.5 text-[10px] rounded bg-red-500/20 text-red-400 hover:bg-red-500/30 hover:text-red-300 transition-colors"
|
||||
onClick={() => { void removeFolder(folder.id); setConfirmingRemoval(false); }}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
className="px-1.5 py-0.5 text-[10px] rounded bg-white/5 text-gray-500 hover:bg-white/10 hover:text-gray-300 transition-colors"
|
||||
onClick={() => setConfirmingRemoval(false)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button
|
||||
className="p-1 rounded text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors"
|
||||
title="Reindex"
|
||||
onClick={(e) => { e.stopPropagation(); void reindexFolder(folder.id); }}
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.75}
|
||||
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className="p-1 rounded text-gray-600 hover:text-red-400 hover:bg-red-500/10 transition-colors"
|
||||
title="Remove from app"
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmingRemoval(true); }}
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.75}
|
||||
d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isMissing && (
|
||||
<div className="mx-2 mb-1 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/20">
|
||||
<p className="text-[11px] text-amber-400 font-medium mb-1.5">Folder not found</p>
|
||||
<p className="text-[10px] text-gray-500 mb-2 leading-snug">
|
||||
This folder may have been moved or renamed. Locate it to resume, or remove it from the app.
|
||||
</p>
|
||||
<div className="flex gap-1.5">
|
||||
<button
|
||||
className="flex-1 px-2 py-1 rounded-md text-[10px] font-medium bg-amber-500/20 text-amber-300 hover:bg-amber-500/30 hover:text-amber-200 transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); void handleLocateFolder(); }}
|
||||
>
|
||||
Locate Folder
|
||||
</button>
|
||||
<button
|
||||
className="flex-1 px-2 py-1 rounded-md text-[10px] font-medium bg-white/5 text-gray-400 hover:bg-red-500/15 hover:text-red-400 transition-colors"
|
||||
onClick={(e) => { e.stopPropagation(); setConfirmingRemoval(true); }}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{contextMenu && contextMenu.folderId === folder.id && (
|
||||
<FolderContextMenu
|
||||
menu={contextMenu}
|
||||
folder={folder}
|
||||
isMuted={isMuted}
|
||||
isPausedAll={isPausedAll}
|
||||
onClose={() => setContextMenu(null)}
|
||||
onRename={() => setRenaming(true)}
|
||||
onReindex={() => void reindexFolder(folder.id)}
|
||||
onLocate={() => void handleLocateFolder()}
|
||||
onToggleMute={() => toggleMutedFolder(folder.id)}
|
||||
onTogglePauseAll={() => setAllWorkersPaused(folder.id, !isPausedAll)}
|
||||
onRemove={() => setConfirmingRemoval(true)}
|
||||
/>
|
||||
)}
|
||||
</Reorder.Item>
|
||||
);
|
||||
}
|
||||
import { useGalleryStore } from '../store'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { PlusIcon } from './icons'
|
||||
import { AlbumSection } from './sidebar/AlbumSection'
|
||||
import { LibrarySection } from './sidebar/LibrarySection'
|
||||
import { NavItem } from './sidebar/NavItem'
|
||||
|
||||
export function Sidebar() {
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen);
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress);
|
||||
const selectFolder = useGalleryStore((state) => state.selectFolder);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
const setView = useGalleryStore((state) => state.setView);
|
||||
const reorderFolders = useGalleryStore((state) => state.reorderFolders);
|
||||
const [librarySort, setLibrarySortState] = useState<LibrarySort>(() => {
|
||||
const saved = window.localStorage.getItem(LIBRARY_SORT_KEY);
|
||||
return saved === "za" || saved === "custom" ? saved : "az";
|
||||
});
|
||||
const [customFolders, setCustomFolders] = useState(folders);
|
||||
const [draggedFolderId, setDraggedFolderId] = useState<number | null>(null);
|
||||
const folderListRef = useRef<HTMLDivElement>(null);
|
||||
const customFoldersRef = useRef(folders);
|
||||
const pointerYRef = useRef(0);
|
||||
const autoScrollFrameRef = useRef<number | null>(null);
|
||||
const keyboardPersistRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (keyboardPersistRef.current) clearTimeout(keyboardPersistRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (draggedFolderId !== null) return;
|
||||
setCustomFolders(folders);
|
||||
customFoldersRef.current = folders;
|
||||
}, [folders, draggedFolderId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (draggedFolderId === null) return;
|
||||
|
||||
const handlePointerMove = (event: PointerEvent) => {
|
||||
pointerYRef.current = event.clientY;
|
||||
};
|
||||
|
||||
const autoScroll = () => {
|
||||
const list = folderListRef.current;
|
||||
if (list) {
|
||||
const rect = list.getBoundingClientRect();
|
||||
const edgeSize = Math.min(64, rect.height * 0.2);
|
||||
const topDistance = pointerYRef.current - rect.top;
|
||||
const bottomDistance = rect.bottom - pointerYRef.current;
|
||||
let velocity = 0;
|
||||
|
||||
if (topDistance < edgeSize) {
|
||||
velocity = -Math.pow((edgeSize - Math.max(0, topDistance)) / edgeSize, 1.6) * 14;
|
||||
} else if (bottomDistance < edgeSize) {
|
||||
velocity = Math.pow((edgeSize - Math.max(0, bottomDistance)) / edgeSize, 1.6) * 14;
|
||||
}
|
||||
|
||||
if (velocity !== 0) list.scrollTop += velocity;
|
||||
}
|
||||
autoScrollFrameRef.current = requestAnimationFrame(autoScroll);
|
||||
};
|
||||
|
||||
window.addEventListener("pointermove", handlePointerMove, { passive: true });
|
||||
autoScrollFrameRef.current = requestAnimationFrame(autoScroll);
|
||||
return () => {
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
if (autoScrollFrameRef.current !== null) cancelAnimationFrame(autoScrollFrameRef.current);
|
||||
autoScrollFrameRef.current = null;
|
||||
};
|
||||
}, [draggedFolderId]);
|
||||
|
||||
const displayedFolders = useMemo(() => {
|
||||
if (librarySort === "custom") return customFolders;
|
||||
return [...folders].sort((a, b) => {
|
||||
const result = a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" });
|
||||
return librarySort === "az" ? result : -result;
|
||||
});
|
||||
}, [customFolders, folders, librarySort]);
|
||||
|
||||
const setLibrarySort = (sort: LibrarySort) => {
|
||||
window.localStorage.setItem(LIBRARY_SORT_KEY, sort);
|
||||
setLibrarySortState(sort);
|
||||
};
|
||||
|
||||
const handleReorder = (orderedIds: number[]) => {
|
||||
const byId = new Map(customFoldersRef.current.map((folder) => [folder.id, folder]));
|
||||
const next = orderedIds
|
||||
.map((id) => byId.get(id))
|
||||
.filter((folder): folder is Folder => folder !== undefined);
|
||||
customFoldersRef.current = next;
|
||||
setCustomFolders(next);
|
||||
};
|
||||
|
||||
const finishReorder = () => {
|
||||
const nextIds = customFoldersRef.current.map((folder) => folder.id);
|
||||
setDraggedFolderId(null);
|
||||
const currentIds = folders.map((folder) => folder.id);
|
||||
if (nextIds.some((id, index) => id !== currentIds[index])) {
|
||||
void reorderFolders(nextIds);
|
||||
}
|
||||
};
|
||||
|
||||
const moveFolderByKeyboard = (folderId: number, direction: -1 | 1) => {
|
||||
const current = customFoldersRef.current;
|
||||
const currentIndex = current.findIndex((folder) => folder.id === folderId);
|
||||
const nextIndex = currentIndex + direction;
|
||||
if (currentIndex < 0 || nextIndex < 0 || nextIndex >= current.length) return;
|
||||
|
||||
const next = [...current];
|
||||
[next[currentIndex], next[nextIndex]] = [next[nextIndex], next[currentIndex]];
|
||||
customFoldersRef.current = next;
|
||||
setCustomFolders(next);
|
||||
// Debounce the DB write so a held arrow key doesn't fire one per keystroke;
|
||||
// the local order updates immediately, only the persist waits to settle.
|
||||
if (keyboardPersistRef.current) clearTimeout(keyboardPersistRef.current);
|
||||
keyboardPersistRef.current = setTimeout(() => {
|
||||
keyboardPersistRef.current = null;
|
||||
void reorderFolders(customFoldersRef.current.map((folder) => folder.id));
|
||||
}, 400);
|
||||
};
|
||||
|
||||
const handleAddFolder = () => {
|
||||
setFolderPickerOpen(true);
|
||||
};
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const selectFolder = useGalleryStore((state) => state.selectFolder)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
const setView = useGalleryStore((state) => state.setView)
|
||||
|
||||
return (
|
||||
<aside className="w-60 shrink-0 flex flex-col bg-gray-950 border-r border-white/[0.06]">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 h-12 border-b border-white/[0.06] shrink-0">
|
||||
<span className="text-[13px] font-semibold text-white/80 tracking-wide">Phokus</span>
|
||||
<button
|
||||
onClick={handleAddFolder}
|
||||
className="p-1.5 rounded-lg text-gray-500 hover:text-gray-200 hover:bg-white/8 transition-colors"
|
||||
title="Add Media Folder"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.75} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
</button>
|
||||
<aside className="flex w-52 shrink-0 flex-col border-r border-white/[0.06] bg-gray-950 lg:w-60">
|
||||
<div className="flex h-12 shrink-0 items-center justify-between border-b border-white/[0.06] px-4">
|
||||
<span className="text-[13px] font-semibold tracking-wide text-white/80">Phokus</span>
|
||||
<Tooltip label="Add Media Folder" anchorToCursor>
|
||||
<button
|
||||
onClick={() => setFolderPickerOpen(true)}
|
||||
className="rounded-lg p-1.5 text-gray-500 transition-colors hover:bg-white/8 hover:text-gray-200"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{/* Nav */}
|
||||
<div className="px-2 pt-2 pb-1 space-y-px">
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-lg cursor-pointer transition-all duration-150 ${
|
||||
activeView === "gallery" && selectedFolderId === null
|
||||
? "bg-white/8 text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5"
|
||||
}`}
|
||||
<div className="space-y-px px-2 pt-2 pb-1">
|
||||
<NavItem
|
||||
label="All Media"
|
||||
active={activeView === 'gallery' && selectedFolderId === null}
|
||||
onClick={() => selectFolder(null)}
|
||||
>
|
||||
<svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className={`text-[13px] font-medium ${activeView === "gallery" && selectedFolderId === null ? "text-white" : ""}`}>
|
||||
All Media
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-lg cursor-pointer transition-all duration-150 ${
|
||||
activeView === "explore"
|
||||
? "bg-white/8 text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5"
|
||||
}`}
|
||||
onClick={() => setView("explore")}
|
||||
>
|
||||
<svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
|
||||
</svg>
|
||||
<span className={`text-[13px] font-medium ${activeView === "explore" ? "text-white" : ""}`}>
|
||||
Explore
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-lg cursor-pointer transition-all duration-150 ${
|
||||
activeView === "timeline"
|
||||
? "bg-white/8 text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5"
|
||||
}`}
|
||||
onClick={() => setView("timeline")}
|
||||
>
|
||||
<svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className={`text-[13px] font-medium ${activeView === "timeline" ? "text-white" : ""}`}>
|
||||
Timeline
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-lg cursor-pointer transition-all duration-150 ${
|
||||
activeView === "duplicates"
|
||||
? "bg-white/8 text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5"
|
||||
}`}
|
||||
onClick={() => setView("duplicates")}
|
||||
>
|
||||
<svg className="w-3.5 h-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className={`text-[13px] font-medium ${activeView === "duplicates" ? "text-white" : ""}`}>
|
||||
Duplicates
|
||||
</span>
|
||||
</div>
|
||||
iconPath="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
<NavItem
|
||||
label="Explore"
|
||||
active={activeView === 'explore'}
|
||||
onClick={() => setView('explore')}
|
||||
iconPath="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"
|
||||
/>
|
||||
<NavItem
|
||||
label="Timeline"
|
||||
active={activeView === 'timeline'}
|
||||
onClick={() => setView('timeline')}
|
||||
iconPath="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
<NavItem
|
||||
label="Duplicates"
|
||||
active={activeView === 'duplicates'}
|
||||
onClick={() => setView('duplicates')}
|
||||
iconPath="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Section label */}
|
||||
{folders.length > 0 && (
|
||||
<div className="flex items-center justify-between gap-2 px-5 pt-3 pb-1">
|
||||
<span className="text-[10px] font-semibold uppercase tracking-[0.15em] text-gray-600">Libraries</span>
|
||||
<ThemedDropdown
|
||||
value={librarySort}
|
||||
onChange={(value) => setLibrarySort(value as LibrarySort)}
|
||||
ariaLabel="Library order"
|
||||
compact
|
||||
options={[
|
||||
{ value: "az", label: "A-Z" },
|
||||
{ value: "za", label: "Z-A" },
|
||||
{ value: "custom", label: "Custom" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Folder list */}
|
||||
<Reorder.Group
|
||||
ref={folderListRef}
|
||||
as="div"
|
||||
axis="y"
|
||||
values={displayedFolders.map((folder) => folder.id)}
|
||||
onReorder={librarySort === "custom" ? handleReorder : () => {}}
|
||||
layoutScroll
|
||||
className="flex-1 overflow-y-auto px-2 pb-2 space-y-px min-h-0"
|
||||
>
|
||||
{folders.length === 0 ? (
|
||||
<p className="text-gray-700 text-xs px-3 py-6 text-center leading-relaxed">
|
||||
Add a folder to get started
|
||||
</p>
|
||||
) : (
|
||||
displayedFolders.map((folder) => (
|
||||
<FolderItem
|
||||
key={folder.id}
|
||||
folder={folder}
|
||||
selected={selectedFolderId === folder.id}
|
||||
progress={indexingProgress[folder.id]}
|
||||
customOrdering={librarySort === "custom"}
|
||||
dragging={draggedFolderId === folder.id}
|
||||
onDragStart={(pointerY) => {
|
||||
pointerYRef.current = pointerY;
|
||||
setDraggedFolderId(folder.id);
|
||||
}}
|
||||
onDragEnd={finishReorder}
|
||||
onKeyboardMove={(direction) => moveFolderByKeyboard(folder.id, direction)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</Reorder.Group>
|
||||
<LibrarySection />
|
||||
<AlbumSection />
|
||||
</aside>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,402 +0,0 @@
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { motion, useReducedMotion } from "framer-motion";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { ExploreTagEntry, TagCloudEntry, useGalleryStore } from "../store";
|
||||
import { FolderScopeDropdown } from "./FolderScopeDropdown";
|
||||
|
||||
const ACCENTS = [
|
||||
"#60a5fa",
|
||||
"#c084fc",
|
||||
"#4ade80",
|
||||
"#fbbf24",
|
||||
"#f472b4",
|
||||
"#2dd4bf",
|
||||
"#fb923c",
|
||||
"#a78bfa",
|
||||
"#34d399",
|
||||
"#f87171",
|
||||
];
|
||||
|
||||
const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
|
||||
|
||||
function seeded(n: number): number {
|
||||
const x = Math.sin(n * 9301 + 49297) * 233280;
|
||||
return x - Math.floor(x);
|
||||
}
|
||||
|
||||
interface PlacedNode {
|
||||
entry: TagCloudEntry;
|
||||
index: number;
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
accent: string;
|
||||
driftX: number;
|
||||
driftY: number;
|
||||
driftDuration: number;
|
||||
rotateSeed: number;
|
||||
}
|
||||
|
||||
function buildCloud(entries: TagCloudEntry[], containerW: number, containerH: number): PlacedNode[] {
|
||||
if (!entries.length || containerW <= 0 || containerH <= 0) return [];
|
||||
|
||||
const maxCount = Math.max(...entries.map((e) => e.count));
|
||||
const cx = containerW / 2;
|
||||
const cy = containerH / 2;
|
||||
// Spread ellipse shrinks slightly to leave room for card half-widths at the edges
|
||||
const spreadX = containerW * 0.42;
|
||||
const spreadY = containerH * 0.36;
|
||||
const n = entries.length;
|
||||
|
||||
// 1. Build initial positions using phyllotaxis spiral
|
||||
const nodes: PlacedNode[] = entries.map((entry, i) => {
|
||||
const ratio = Math.max(entry.count / maxCount, 0.08);
|
||||
// Cards scale from 110px to 230px wide; height is 3/4 of width
|
||||
const w = 110 + Math.sqrt(ratio) * 120;
|
||||
const h = w * 0.75;
|
||||
const radialRatio = Math.sqrt((i + 0.5) / n);
|
||||
const angle = i * GOLDEN_ANGLE;
|
||||
|
||||
return {
|
||||
entry,
|
||||
index: i,
|
||||
x: cx + Math.cos(angle) * radialRatio * spreadX,
|
||||
y: cy + Math.sin(angle) * radialRatio * spreadY,
|
||||
w,
|
||||
h,
|
||||
accent: ACCENTS[i % ACCENTS.length],
|
||||
driftX: (seeded(i + 11) - 0.5) * 18,
|
||||
driftY: (seeded(i + 17) - 0.5) * 14,
|
||||
driftDuration: 8 + seeded(i + 23) * 7,
|
||||
rotateSeed: (seeded(i + 31) - 0.5) * 4,
|
||||
};
|
||||
});
|
||||
|
||||
// 2. Iterative overlap resolution — no physics, just push apart
|
||||
const PAD = 24;
|
||||
for (let iter = 0; iter < 80; iter++) {
|
||||
for (let a = 0; a < nodes.length; a++) {
|
||||
const na = nodes[a];
|
||||
for (let b = a + 1; b < nodes.length; b++) {
|
||||
const nb = nodes[b];
|
||||
const dx = nb.x - na.x;
|
||||
const dy = nb.y - na.y;
|
||||
const overlapX = (na.w + nb.w) / 2 + PAD - Math.abs(dx);
|
||||
const overlapY = (na.h + nb.h) / 2 + PAD - Math.abs(dy);
|
||||
if (overlapX <= 0 || overlapY <= 0) continue;
|
||||
// Push along the smaller overlap axis
|
||||
if (overlapX < overlapY) {
|
||||
const push = overlapX * 0.5 * (dx >= 0 ? 1 : -1);
|
||||
nb.x += push;
|
||||
na.x -= push;
|
||||
} else {
|
||||
const push = overlapY * 0.5 * (dy >= 0 ? 1 : -1);
|
||||
nb.y += push;
|
||||
na.y -= push;
|
||||
}
|
||||
}
|
||||
// Pull gently back toward anchor to prevent runaway drift
|
||||
na.x += (cx + Math.cos(na.index * GOLDEN_ANGLE) * Math.sqrt((na.index + 0.5) / n) * spreadX - na.x) * 0.05;
|
||||
na.y += (cy + Math.sin(na.index * GOLDEN_ANGLE) * Math.sqrt((na.index + 0.5) / n) * spreadY - na.y) * 0.05;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Clamp so cards never poke outside the container
|
||||
return nodes.map((node) => ({
|
||||
...node,
|
||||
x: Math.min(Math.max(node.x, node.w / 2 + 16), containerW - node.w / 2 - 16),
|
||||
y: Math.min(Math.max(node.y, node.h / 2 + 16), containerH - node.h / 2 - 16),
|
||||
}));
|
||||
}
|
||||
|
||||
function CloudCard({ node, onOpen, animated }: { node: PlacedNode; onOpen: (imageIds: number[]) => void; animated: boolean }) {
|
||||
const src = node.entry.thumbnail_path ? convertFileSrc(node.entry.thumbnail_path) : null;
|
||||
const { w, h, accent } = node;
|
||||
const driftTransition = {
|
||||
duration: node.driftDuration,
|
||||
ease: "easeInOut" as const,
|
||||
delay: seeded(node.index + 41) * 1.6,
|
||||
repeat: 1,
|
||||
repeatType: "reverse" as const,
|
||||
};
|
||||
|
||||
return (
|
||||
<motion.button
|
||||
className="explore-cluster-card group absolute overflow-hidden rounded-2xl border border-white/8 bg-white/[0.04] text-left shadow-[0_8px_28px_rgba(0,0,0,0.38)] focus:outline-none focus-visible:ring-2 focus-visible:ring-white/30"
|
||||
style={{ width: w, height: h, left: node.x - w / 2, top: node.y - h / 2 }}
|
||||
initial={animated ? { opacity: 0, scale: 0.82, rotate: node.rotateSeed } : { opacity: 0, scale: 0.96 }}
|
||||
animate={
|
||||
animated
|
||||
? {
|
||||
opacity: 1,
|
||||
scale: 1,
|
||||
x: [0, node.driftX * 0.65, 0],
|
||||
y: [0, node.driftY * 0.65, 0],
|
||||
rotate: [node.rotateSeed, node.rotateSeed + 0.8, node.rotateSeed],
|
||||
}
|
||||
: { opacity: 1, scale: 1, rotate: node.rotateSeed }
|
||||
}
|
||||
transition={
|
||||
animated
|
||||
? {
|
||||
opacity: { duration: 0.24, delay: Math.min(node.index * 0.024, 0.45) },
|
||||
scale: { duration: 0.24, delay: Math.min(node.index * 0.024, 0.45) },
|
||||
x: driftTransition,
|
||||
y: { ...driftTransition, duration: node.driftDuration + 1.2, delay: seeded(node.index + 51) * 1.6 },
|
||||
rotate: { ...driftTransition, duration: node.driftDuration + 0.8, delay: seeded(node.index + 61) * 1.2 },
|
||||
}
|
||||
: { opacity: { duration: 0.18, delay: Math.min(node.index * 0.016, 0.28) }, scale: { duration: 0.18, delay: Math.min(node.index * 0.016, 0.28) } }
|
||||
}
|
||||
whileHover={{ scale: 1.06, rotate: 0, transition: { duration: 0.18 } }}
|
||||
onClick={() => onOpen(node.entry.image_ids)}
|
||||
title={`Open cluster — ${node.entry.count.toLocaleString()} images`}
|
||||
>
|
||||
{src ? (
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className="absolute inset-0 h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
|
||||
draggable={false}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
) : (
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-white/[0.07] to-transparent" />
|
||||
)}
|
||||
<div className="explore-cluster-overlay absolute inset-0 bg-gradient-to-t from-black/85 via-black/20 to-transparent" />
|
||||
{/* Accent glow on hover */}
|
||||
<div
|
||||
className="absolute inset-0 opacity-0 transition-opacity duration-300 group-hover:opacity-100"
|
||||
style={{ background: `radial-gradient(ellipse at bottom, ${accent}25, transparent 70%)` }}
|
||||
/>
|
||||
<div className="absolute inset-x-0 bottom-0 p-3">
|
||||
<div className="explore-cluster-rule mb-2 h-px rounded-full" style={{ background: `linear-gradient(to right, ${accent}80, transparent)` }} />
|
||||
<div className="flex items-end justify-between gap-2">
|
||||
<div>
|
||||
<p className="explore-cluster-label text-[9px] uppercase tracking-[0.18em] text-white/35">Cluster</p>
|
||||
<p className="explore-cluster-count text-base font-semibold leading-none text-white">{node.entry.count.toLocaleString()}</p>
|
||||
</div>
|
||||
<span
|
||||
className="rounded-full border px-2 py-0.5 text-[9px] uppercase tracking-[0.1em] opacity-0 transition-opacity duration-200 group-hover:opacity-100"
|
||||
style={{ borderColor: `${accent}50`, color: accent, backgroundColor: `${accent}12` }}
|
||||
>
|
||||
Open
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.button>
|
||||
);
|
||||
}
|
||||
|
||||
// Actual tag cloud — word size driven by log-scaled frequency
|
||||
function TagWord({
|
||||
entry,
|
||||
index,
|
||||
logMin,
|
||||
logRange,
|
||||
onSearch,
|
||||
}: {
|
||||
entry: ExploreTagEntry;
|
||||
index: number;
|
||||
logMin: number;
|
||||
logRange: number;
|
||||
onSearch: (tag: string) => void;
|
||||
}) {
|
||||
const ratio = logRange > 0 ? (Math.log(Math.max(entry.count, 1)) - logMin) / logRange : 0.5;
|
||||
const fontSize = 11 + ratio * 28; // 11px – 39px
|
||||
const accent = ACCENTS[index % ACCENTS.length];
|
||||
const tilt = (seeded(index + 5) - 0.5) * 7;
|
||||
|
||||
return (
|
||||
<motion.button
|
||||
initial={{ opacity: 0, scale: 0.6 }}
|
||||
animate={{ opacity: 0.4 + ratio * 0.6, scale: 1 }}
|
||||
transition={{ delay: Math.min(index * 0.008, 0.55), duration: 0.22 }}
|
||||
whileHover={{ scale: 1.2, opacity: 1, rotate: 0, transition: { duration: 0.14 } }}
|
||||
className="explore-tag-word group inline-flex items-center gap-1 rounded-full px-2 py-1 transition-colors hover:bg-white/[0.07]"
|
||||
style={{ fontSize, rotate: tilt }}
|
||||
onClick={() => onSearch(entry.tag)}
|
||||
title={`${entry.tag} — ${entry.count.toLocaleString()} images`}
|
||||
>
|
||||
<span
|
||||
className="font-medium leading-none"
|
||||
style={{ color: ratio > 0.55 ? accent : "rgba(255,255,255,0.82)" }}
|
||||
>
|
||||
{entry.tag}
|
||||
</span>
|
||||
<span
|
||||
className="rounded-full px-1.5 py-0.5 text-[9px] tabular-nums opacity-0 transition-opacity group-hover:opacity-100"
|
||||
style={{ backgroundColor: `${accent}22`, color: accent }}
|
||||
>
|
||||
{entry.count.toLocaleString()}
|
||||
</span>
|
||||
</motion.button>
|
||||
);
|
||||
}
|
||||
|
||||
function Spinner() {
|
||||
return (
|
||||
<motion.div
|
||||
className="explore-spinner h-5 w-5 rounded-full border-2 border-white/15 border-t-white/50"
|
||||
animate={{ rotate: 360 }}
|
||||
transition={{ duration: 0.85, repeat: Infinity, ease: "linear" }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Separate component so its useLayoutEffect fires when the canvas is actually
|
||||
// mounted — not at TagCloud mount time when the container may still be hidden
|
||||
// behind a loading state.
|
||||
function ClusterCloud({
|
||||
entries,
|
||||
onOpen,
|
||||
}: {
|
||||
entries: TagCloudEntry[];
|
||||
onOpen: (imageIds: number[]) => void;
|
||||
}) {
|
||||
const reducedMotion = useReducedMotion();
|
||||
const canvasRef = useRef<HTMLDivElement>(null);
|
||||
const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 });
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = canvasRef.current;
|
||||
if (!el) return;
|
||||
const update = () => {
|
||||
const r = el.getBoundingClientRect();
|
||||
setCanvasSize({ w: r.width, h: r.height });
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
const nodes = useMemo(
|
||||
() => buildCloud(entries, canvasSize.w, canvasSize.h),
|
||||
[entries, canvasSize.w, canvasSize.h],
|
||||
);
|
||||
|
||||
return (
|
||||
<div ref={canvasRef} className="relative min-h-0 flex-1 overflow-hidden">
|
||||
<div className="explore-cluster-grid pointer-events-none absolute inset-0 opacity-[0.07] [background-image:radial-gradient(circle,rgba(255,255,255,0.6)_1px,transparent_1px)] [background-size:28px_28px]" />
|
||||
{nodes.map((node) => (
|
||||
<CloudCard
|
||||
key={`${node.entry.representative_image_id}:${node.index}`}
|
||||
node={node}
|
||||
onOpen={onOpen}
|
||||
animated={!reducedMotion && node.index < 12}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function TagCloud() {
|
||||
const exploreMode = useGalleryStore((state) => state.exploreMode);
|
||||
const setExploreMode = useGalleryStore((state) => state.setExploreMode);
|
||||
const tagCloudEntries = useGalleryStore((state) => state.tagCloudEntries);
|
||||
const tagCloudLoading = useGalleryStore((state) => state.tagCloudLoading);
|
||||
const loadTagCloud = useGalleryStore((state) => state.loadTagCloud);
|
||||
const exploreTagEntries = useGalleryStore((state) => state.exploreTagEntries);
|
||||
const exploreTagLoading = useGalleryStore((state) => state.exploreTagLoading);
|
||||
const loadExploreTags = useGalleryStore((state) => state.loadExploreTags);
|
||||
const showVisualCluster = useGalleryStore((state) => state.showVisualCluster);
|
||||
const searchForTag = useGalleryStore((state) => state.searchForTag);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
|
||||
useEffect(() => {
|
||||
if (exploreMode === "visual") void loadTagCloud();
|
||||
else void loadExploreTags();
|
||||
}, [exploreMode, selectedFolderId, loadTagCloud, loadExploreTags]);
|
||||
|
||||
const { logMin, logRange } = useMemo(() => {
|
||||
if (!exploreTagEntries.length) return { logMin: 0, logRange: 1 };
|
||||
const logs = exploreTagEntries.map((e) => Math.log(Math.max(e.count, 1)));
|
||||
const lo = Math.min(...logs);
|
||||
const hi = Math.max(...logs);
|
||||
return { logMin: lo, logRange: hi - lo || 1 };
|
||||
}, [exploreTagEntries]);
|
||||
|
||||
const loading = exploreMode === "visual" ? tagCloudLoading : exploreTagLoading;
|
||||
const hasEntries = exploreMode === "visual" ? tagCloudEntries.length > 0 : exploreTagEntries.length > 0;
|
||||
const entryCount = exploreMode === "visual" ? tagCloudEntries.length : exploreTagEntries.length;
|
||||
|
||||
return (
|
||||
<div className="explore-view flex min-h-0 flex-1 flex-col overflow-hidden bg-[radial-gradient(ellipse_at_top,rgba(59,130,246,0.08),transparent_50%),radial-gradient(ellipse_at_80%_75%,rgba(168,85,247,0.07),transparent_40%),#07080f]">
|
||||
{/* Header */}
|
||||
<div className="explore-header shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<h2 className="explore-title text-[15px] font-semibold text-white">Explore</h2>
|
||||
<p className="explore-subtitle mt-0.5 truncate text-[11px] text-white/30">
|
||||
{loading
|
||||
? exploreMode === "visual" ? "Computing visual clusters…" : "Loading tags…"
|
||||
: hasEntries
|
||||
? exploreMode === "visual"
|
||||
? `${entryCount} cluster${entryCount !== 1 ? "s" : ""} — click any to open`
|
||||
: `${entryCount} tag${entryCount !== 1 ? "s" : ""} — click any to search`
|
||||
: exploreMode === "visual"
|
||||
? "No clusters — images need embeddings first"
|
||||
: "No tags — run the AI tagger or add tags manually"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<FolderScopeDropdown />
|
||||
<div className="explore-mode-toggle flex rounded-lg border border-white/8 bg-white/[0.03] p-0.5">
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === "visual" ? "bg-white/10 text-white" : "text-gray-500 hover:text-gray-300"
|
||||
}`}
|
||||
onClick={() => setExploreMode("visual")}
|
||||
>
|
||||
Clusters
|
||||
</button>
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === "tags" ? "bg-white/10 text-white" : "text-gray-500 hover:text-gray-300"
|
||||
}`}
|
||||
onClick={() => setExploreMode("tags")}
|
||||
>
|
||||
Tag Cloud
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="explore-empty flex flex-1 items-center justify-center gap-3 text-white/25">
|
||||
<Spinner />
|
||||
<span className="text-sm">{exploreMode === "visual" ? "Computing clusters…" : "Loading tags…"}</span>
|
||||
</div>
|
||||
) : !hasEntries ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<p className="explore-empty max-w-xs text-center text-sm leading-relaxed text-white/25">
|
||||
{exploreMode === "visual"
|
||||
? "No visual clusters yet. Images need embeddings before they can be grouped. Check indexing progress in the sidebar."
|
||||
: "No tags yet. Run the AI tagger from Settings, or add tags manually in the image preview."}
|
||||
</p>
|
||||
</div>
|
||||
) : exploreMode === "visual" ? (
|
||||
<ClusterCloud entries={tagCloudEntries} onOpen={showVisualCluster} />
|
||||
) : (
|
||||
/* Tag cloud — words sized by log-scaled frequency, wrapped freely */
|
||||
<div className="overflow-y-auto px-8 py-8">
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-0.5 gap-y-1 leading-none">
|
||||
{exploreTagEntries.map((entry, index) => (
|
||||
<TagWord
|
||||
key={entry.tag}
|
||||
entry={entry}
|
||||
index={index}
|
||||
logMin={logMin}
|
||||
logRange={logRange}
|
||||
onSearch={searchForTag}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
export interface DropdownOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function ThemedDropdown({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
ariaLabel,
|
||||
compact = false,
|
||||
align = "right",
|
||||
}: {
|
||||
value: string;
|
||||
options: DropdownOption[];
|
||||
onChange: (value: string) => void;
|
||||
ariaLabel: string;
|
||||
compact?: boolean;
|
||||
align?: "left" | "right";
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const current = options.find((option) => option.value === value) ?? options[0];
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
if (!ref.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", handlePointerDown);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", handlePointerDown);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={ariaLabel}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((currentOpen) => !currentOpen)}
|
||||
className={`flex items-center justify-between gap-2 rounded-md border transition-colors ${
|
||||
compact
|
||||
? "border-white/10 bg-white/[0.04] px-1.5 py-0.5 text-[10px] font-medium light-theme:border-gray-700/50 light-theme:bg-gray-900"
|
||||
: "min-w-40 border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs light-theme:border-gray-700/50 light-theme:bg-gray-900"
|
||||
} ${open ? "border-white/20 text-white light-theme:border-gray-700 light-theme:text-white" : "text-gray-400 hover:border-white/15 hover:text-gray-200 light-theme:text-white light-theme:hover:border-gray-700 light-theme:hover:bg-gray-800 light-theme:hover:text-white"}`}
|
||||
>
|
||||
<span>{current?.label}</span>
|
||||
<svg
|
||||
className={`h-3 w-3 shrink-0 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label={ariaLabel}
|
||||
className={`absolute top-full z-50 mt-1.5 min-w-full rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl shadow-black/30 backdrop-blur-xl light-theme:border-gray-700/50 ${
|
||||
align === "right" ? "right-0" : "left-0"
|
||||
}`}
|
||||
>
|
||||
{options.map((option) => {
|
||||
const selected = option.value === value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
className={`flex w-full items-center justify-between gap-4 whitespace-nowrap rounded-lg px-3 py-2 text-left text-xs transition-colors ${
|
||||
selected
|
||||
? "bg-white/[0.08] text-white light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "text-gray-400 hover:bg-white/[0.055] hover:text-gray-200 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => {
|
||||
onChange(option.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<span>{option.label}</span>
|
||||
{selected ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,159 +1,69 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { ImageRecord, tileSizeForZoom, useGalleryStore } from "../store";
|
||||
import { ContextMenu, ImageTile } from "./Gallery";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { ImageRecord, tileSizeForZoom, useGalleryStore } from '../store'
|
||||
import { ImageTile } from './gallery/ImageTile'
|
||||
import { ImageContextMenu } from './ImageContextMenu'
|
||||
import { ScrubberYearBlock } from './timeline/ScrubberYearBlock'
|
||||
import { TimelineEmptyState, TimelineLoadingState } from './timeline/TimelineEmptyState'
|
||||
import { buildScrubberYears, buildTimelineRows, groupImages } from './timeline/timelineModel'
|
||||
|
||||
const GAP = 6;
|
||||
const HEADER_HEIGHT = 52;
|
||||
const SCRUBBER_WIDTH = 48;
|
||||
const MONTH_SHORT = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] as const;
|
||||
|
||||
interface TimelineGroup {
|
||||
key: string;
|
||||
label: string;
|
||||
images: ImageRecord[];
|
||||
}
|
||||
|
||||
// One virtualized row: either a month header or a row of up to `cols` tiles.
|
||||
type TimelineRow =
|
||||
| { type: "header"; group: TimelineGroup }
|
||||
| { type: "tiles"; images: ImageRecord[] };
|
||||
|
||||
interface ScrubberMonth {
|
||||
monthNum: number;
|
||||
label: string;
|
||||
groupIndex: number;
|
||||
}
|
||||
|
||||
interface ScrubberYear {
|
||||
year: string;
|
||||
firstGroupIndex: number;
|
||||
months: ScrubberMonth[];
|
||||
}
|
||||
|
||||
function buildLabel(key: string): string {
|
||||
if (key === "unknown") return "Unknown Date";
|
||||
const [yearStr, monthStr] = key.split("-");
|
||||
const year = Number(yearStr);
|
||||
const month = Number(monthStr);
|
||||
if (!isFinite(year) || !isFinite(month) || month < 1 || month > 12) return "Unknown Date";
|
||||
const date = new Date(year, month - 1);
|
||||
if (isNaN(date.getTime())) return "Unknown Date";
|
||||
return date.toLocaleDateString(undefined, { month: "long", year: "numeric" });
|
||||
}
|
||||
|
||||
function groupImages(images: ImageRecord[]): TimelineGroup[] {
|
||||
const map = new Map<string, ImageRecord[]>();
|
||||
for (const img of images) {
|
||||
const ds = img.taken_at ?? img.modified_at;
|
||||
const key = ds ? ds.substring(0, 7) : "unknown";
|
||||
let bucket = map.get(key);
|
||||
if (bucket === undefined) {
|
||||
bucket = [];
|
||||
map.set(key, bucket);
|
||||
}
|
||||
bucket.push(img);
|
||||
}
|
||||
return Array.from(map.entries())
|
||||
.sort(([a], [b]) => {
|
||||
if (a === "unknown") return 1;
|
||||
if (b === "unknown") return -1;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
})
|
||||
.map(([key, imgs]) => ({ key, label: buildLabel(key), images: imgs }));
|
||||
}
|
||||
|
||||
function buildScrubberYears(groups: TimelineGroup[]): ScrubberYear[] {
|
||||
const byYear = new Map<string, ScrubberYear>();
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
const group = groups[i];
|
||||
if (group.key === "unknown") continue;
|
||||
const year = group.key.substring(0, 4);
|
||||
const monthNum = Number(group.key.substring(5, 7));
|
||||
if (!byYear.has(year)) {
|
||||
byYear.set(year, { year, firstGroupIndex: i, months: [] });
|
||||
}
|
||||
byYear.get(year)!.months.push({
|
||||
monthNum,
|
||||
label: MONTH_SHORT[monthNum - 1] ?? "",
|
||||
groupIndex: i,
|
||||
});
|
||||
}
|
||||
// Keep insertion order so the scrubber runs the same direction as the scrolled
|
||||
// content (oldest at top with taken_asc), keeping the active highlight aligned.
|
||||
return Array.from(byYear.values());
|
||||
}
|
||||
const GAP = 6
|
||||
const HEADER_HEIGHT = 52
|
||||
const SCRUBBER_WIDTH = 48
|
||||
|
||||
export function Timeline() {
|
||||
const images = useGalleryStore((s) => s.images);
|
||||
const loadMoreImages = useGalleryStore((s) => s.loadMoreImages);
|
||||
const openImage = useGalleryStore((s) => s.openImage);
|
||||
const totalImages = useGalleryStore((s) => s.totalImages);
|
||||
const loadingImages = useGalleryStore((s) => s.loadingImages);
|
||||
const imageLoadError = useGalleryStore((s) => s.imageLoadError);
|
||||
const zoomPreset = useGalleryStore((s) => s.zoomPreset);
|
||||
const images = useGalleryStore((s) => s.images)
|
||||
const loadMoreImages = useGalleryStore((s) => s.loadMoreImages)
|
||||
const openImage = useGalleryStore((s) => s.openImage)
|
||||
const totalImages = useGalleryStore((s) => s.totalImages)
|
||||
const loadingImages = useGalleryStore((s) => s.loadingImages)
|
||||
const imageLoadError = useGalleryStore((s) => s.imageLoadError)
|
||||
const zoomPreset = useGalleryStore((s) => s.zoomPreset)
|
||||
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const [activeGroupIndex, setActiveGroupIndex] = useState(0);
|
||||
const parentRef = useRef<HTMLDivElement>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [activeGroupIndex, setActiveGroupIndex] = useState(0)
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
x: number;
|
||||
y: number;
|
||||
image: ImageRecord;
|
||||
} | null>(null);
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
} | null>(null)
|
||||
|
||||
// parentRef is the scroll container. Its clientWidth already excludes the
|
||||
// scrubber because they are flex siblings, so no further adjustment is needed.
|
||||
useLayoutEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
setContainerWidth(el.clientWidth);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
setContainerWidth(el.clientWidth)
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
setContainerWidth(entries[0].contentRect.width);
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
setContainerWidth(entries[0].contentRect.width)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
const groups = useMemo(() => groupImages(images), [images]);
|
||||
const scrubberYears = useMemo(() => buildScrubberYears(groups), [groups]);
|
||||
const tileSize = tileSizeForZoom(zoomPreset)
|
||||
const groups = useMemo(() => groupImages(images), [images])
|
||||
const scrubberYears = useMemo(() => buildScrubberYears(groups), [groups])
|
||||
// Show as soon as there's more than one month to jump between — not gated on
|
||||
// a full year. With taken_asc sort the loaded set is oldest-first, so this
|
||||
// reflects whatever range is currently loaded.
|
||||
const showScrubber = groups.length > 1;
|
||||
const showScrubber = groups.length > 1
|
||||
|
||||
const cols = useMemo(
|
||||
() => Math.max(1, Math.floor((containerWidth - GAP) / (tileSize + GAP))),
|
||||
[containerWidth, tileSize],
|
||||
);
|
||||
[containerWidth, tileSize]
|
||||
)
|
||||
|
||||
// Flatten the month groups into a single list of fixed-height rows — one
|
||||
// header row per group, then one tile-row per `cols` images. This lets the
|
||||
// virtualizer render only the on-screen rows, exactly like the Gallery.
|
||||
// Previously each *group* was one virtual item that rendered ALL of its
|
||||
// images, so scrolling into a busy month mounted thousands of tiles at once.
|
||||
const { rows, rowToGroupIndex, groupFirstRow } = useMemo(() => {
|
||||
const rows: TimelineRow[] = [];
|
||||
const rowToGroupIndex: number[] = [];
|
||||
const groupFirstRow: number[] = [];
|
||||
groups.forEach((group, groupIndex) => {
|
||||
groupFirstRow[groupIndex] = rows.length;
|
||||
rows.push({ type: "header", group });
|
||||
rowToGroupIndex.push(groupIndex);
|
||||
for (let i = 0; i < group.images.length; i += cols) {
|
||||
rows.push({ type: "tiles", images: group.images.slice(i, i + cols) });
|
||||
rowToGroupIndex.push(groupIndex);
|
||||
}
|
||||
});
|
||||
return { rows, rowToGroupIndex, groupFirstRow };
|
||||
}, [groups, cols]);
|
||||
const { rows, rowToGroupIndex, groupFirstRow } = useMemo(
|
||||
() => buildTimelineRows(groups, cols),
|
||||
[groups, cols]
|
||||
)
|
||||
|
||||
const estimateSize = useCallback(
|
||||
(index: number): number =>
|
||||
rows[index]?.type === "header" ? HEADER_HEIGHT : tileSize + GAP,
|
||||
[rows, tileSize],
|
||||
);
|
||||
(index: number): number => (rows[index]?.type === 'header' ? HEADER_HEIGHT : tileSize + GAP),
|
||||
[rows, tileSize]
|
||||
)
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
@@ -161,151 +71,101 @@ export function Timeline() {
|
||||
estimateSize,
|
||||
overscan: 6,
|
||||
paddingStart: GAP,
|
||||
});
|
||||
})
|
||||
|
||||
// Refs so the scroll handler can read the latest mappings without re-binding.
|
||||
const rowToGroupIndexRef = useRef(rowToGroupIndex);
|
||||
rowToGroupIndexRef.current = rowToGroupIndex;
|
||||
const groupFirstRowRef = useRef(groupFirstRow);
|
||||
groupFirstRowRef.current = groupFirstRow;
|
||||
const rowToGroupIndexRef = useRef(rowToGroupIndex)
|
||||
rowToGroupIndexRef.current = rowToGroupIndex
|
||||
const groupFirstRowRef = useRef(groupFirstRow)
|
||||
groupFirstRowRef.current = groupFirstRow
|
||||
|
||||
useEffect(() => {
|
||||
virtualizer.measure();
|
||||
}, [cols, virtualizer]);
|
||||
virtualizer.measure()
|
||||
}, [cols, virtualizer])
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
|
||||
// Active month = the group owning the first row still visible at the top.
|
||||
const scrollTop = el.scrollTop;
|
||||
const items = virtualizer.getVirtualItems();
|
||||
let activeRow = items.length > 0 ? items[0].index : 0;
|
||||
const scrollTop = el.scrollTop
|
||||
const items = virtualizer.getVirtualItems()
|
||||
let activeRow = items.length > 0 ? items[0].index : 0
|
||||
for (const item of items) {
|
||||
if (item.start + item.size > scrollTop + HEADER_HEIGHT / 2) {
|
||||
activeRow = item.index;
|
||||
break;
|
||||
activeRow = item.index
|
||||
break
|
||||
}
|
||||
}
|
||||
setActiveGroupIndex(rowToGroupIndexRef.current[activeRow] ?? 0);
|
||||
setActiveGroupIndex(rowToGroupIndexRef.current[activeRow] ?? 0)
|
||||
|
||||
if (scrollTop < 24) return;
|
||||
const nearBottom = scrollTop + el.clientHeight >= el.scrollHeight - 600;
|
||||
if (scrollTop < 24) return
|
||||
const nearBottom = scrollTop + el.clientHeight >= el.scrollHeight - 600
|
||||
if (nearBottom && !loadingImages && images.length < totalImages) {
|
||||
void loadMoreImages();
|
||||
void loadMoreImages()
|
||||
}
|
||||
}, [virtualizer, images.length, loadMoreImages, loadingImages, totalImages]);
|
||||
}, [virtualizer, images.length, loadMoreImages, loadingImages, totalImages])
|
||||
|
||||
useEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: PointerEvent) => {
|
||||
if ((e.target as HTMLElement | null)?.closest("[data-gallery-context-menu]")) return;
|
||||
setContextMenu(null);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setContextMenu(null);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", close);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, []);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
el.addEventListener('scroll', handleScroll, { passive: true })
|
||||
return () => el.removeEventListener('scroll', handleScroll)
|
||||
}, [handleScroll])
|
||||
|
||||
const scrollToGroup = useCallback(
|
||||
(groupIndex: number) => {
|
||||
const row = groupFirstRowRef.current[groupIndex] ?? 0;
|
||||
virtualizer.scrollToIndex(row, { align: "start" });
|
||||
const row = groupFirstRowRef.current[groupIndex] ?? 0
|
||||
virtualizer.scrollToIndex(row, { align: 'start' })
|
||||
},
|
||||
[virtualizer],
|
||||
);
|
||||
[virtualizer]
|
||||
)
|
||||
|
||||
return (
|
||||
// Outer flex-row: fills remaining height in <main>'s flex-col, then
|
||||
// splits horizontally between the scroll area and the scrubber.
|
||||
<div className="flex flex-1 min-h-0 bg-gray-950">
|
||||
<div className="flex min-h-0 flex-1 bg-gray-950">
|
||||
{/* Scroll container — flex-1 takes all width except the scrubber */}
|
||||
<div
|
||||
ref={parentRef}
|
||||
className="relative flex-1 overflow-y-auto overflow-x-hidden min-h-0"
|
||||
>
|
||||
<div ref={parentRef} className="relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 min-w-72">
|
||||
<div className="h-5 w-5 mx-auto rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<p className="mt-4 text-sm text-white/40 font-medium">Loading timeline</p>
|
||||
<p className="text-xs text-white/20 mt-1">Fetching results</p>
|
||||
</div>
|
||||
</div>
|
||||
<TimelineLoadingState />
|
||||
) : images.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<svg
|
||||
className="h-12 w-12 mx-auto text-white/10 mb-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={0.75}
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-white/30 font-medium">
|
||||
{imageLoadError ? "Could not load timeline" : "No media found"}
|
||||
</p>
|
||||
<p className="text-xs text-white/15 mt-1">
|
||||
{imageLoadError ?? "Add a folder to see your timeline"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<TimelineEmptyState imageLoadError={imageLoadError} />
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const row = rows[virtualItem.index];
|
||||
if (!row) return null;
|
||||
const row = rows[virtualItem.index]
|
||||
if (!row) return null
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
style={{
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
top: virtualItem.start,
|
||||
width: "100%",
|
||||
width: '100%',
|
||||
height: virtualItem.size,
|
||||
}}
|
||||
>
|
||||
{row.type === "header" ? (
|
||||
<div
|
||||
className="flex items-center gap-3 px-4"
|
||||
style={{ height: HEADER_HEIGHT }}
|
||||
>
|
||||
<span className="text-sm font-semibold text-white/80 shrink-0">
|
||||
{row.type === 'header' ? (
|
||||
<div className="flex items-center gap-3 px-4" style={{ height: HEADER_HEIGHT }}>
|
||||
<span className="shrink-0 text-sm font-semibold text-white/80">
|
||||
{row.group.label}
|
||||
</span>
|
||||
<span className="text-xs text-white/25 shrink-0 tabular-nums">
|
||||
<span className="shrink-0 text-xs text-white/25 tabular-nums">
|
||||
{row.group.images.length}
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-white/[0.06]" />
|
||||
<div className="h-px flex-1 bg-white/[0.06]" />
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
display: 'grid',
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: "border-box",
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
{row.images.map((image) => (
|
||||
@@ -314,22 +174,22 @@ export function Timeline() {
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image });
|
||||
event.preventDefault()
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -337,7 +197,7 @@ export function Timeline() {
|
||||
{/* Scrubber — flex sibling so it stays visible while the left panel scrolls */}
|
||||
{showScrubber ? (
|
||||
<div
|
||||
className="overflow-y-auto border-l border-white/[0.04] py-2 flex flex-col items-center gap-0.5"
|
||||
className="flex flex-col items-center gap-0.5 overflow-y-auto border-l border-white/[0.04] py-2"
|
||||
style={{ width: SCRUBBER_WIDTH }}
|
||||
>
|
||||
{scrubberYears.map((yearEntry) => (
|
||||
@@ -352,7 +212,7 @@ export function Timeline() {
|
||||
) : null}
|
||||
|
||||
{contextMenu ? (
|
||||
<ContextMenu
|
||||
<ImageContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
@@ -360,53 +220,5 @@ export function Timeline() {
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ScrubberYearBlockProps {
|
||||
yearEntry: ScrubberYear;
|
||||
activeGroupIndex: number;
|
||||
onScrollTo: (index: number) => void;
|
||||
}
|
||||
|
||||
function ScrubberYearBlock({ yearEntry, activeGroupIndex, onScrollTo }: ScrubberYearBlockProps) {
|
||||
const isYearActive = yearEntry.months.some((m) => m.groupIndex === activeGroupIndex);
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col items-center">
|
||||
<button
|
||||
className={`w-full text-center py-0.5 text-[10px] font-semibold tracking-wide transition-colors ${
|
||||
isYearActive ? "text-white/80" : "text-white/30 hover:text-white/55"
|
||||
}`}
|
||||
onClick={() => onScrollTo(yearEntry.firstGroupIndex)}
|
||||
title={yearEntry.year}
|
||||
>
|
||||
{yearEntry.year}
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="grid gap-[3px] pb-1.5"
|
||||
style={{ gridTemplateColumns: "repeat(3, 10px)" }}
|
||||
>
|
||||
{Array.from({ length: 12 }, (_, i) => {
|
||||
const monthNum = i + 1;
|
||||
const monthEntry = yearEntry.months.find((m) => m.monthNum === monthNum);
|
||||
const isActive = monthEntry !== undefined && monthEntry.groupIndex === activeGroupIndex;
|
||||
if (!monthEntry) {
|
||||
return <span key={monthNum} className="h-[10px] w-[10px]" />;
|
||||
}
|
||||
return (
|
||||
<button
|
||||
key={monthNum}
|
||||
title={`${monthEntry.label} ${yearEntry.year}`}
|
||||
onClick={() => onScrollTo(monthEntry.groupIndex)}
|
||||
className={`h-[10px] w-[10px] rounded-full transition-colors ${
|
||||
isActive ? "bg-white/70" : "bg-white/15 hover:bg-white/40"
|
||||
}`}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { PhokusMark } from "./PhokusMark";
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { useGalleryStore, AppTheme } from '../store'
|
||||
import { ContextMenu, MenuItem, MenuLabel } from './menu'
|
||||
import { PhokusMark } from './PhokusMark'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
const THEME_OPTIONS: { value: AppTheme; label: string }[] = [
|
||||
{ value: 'phokus', label: 'Phokus' },
|
||||
{ value: 'subtle-light', label: 'Subtle Light' },
|
||||
{ value: 'conventional-dark', label: 'Conventional Dark' },
|
||||
]
|
||||
|
||||
// SVG icons for window controls
|
||||
function MinimizeIcon() {
|
||||
@@ -9,7 +17,7 @@ function MinimizeIcon() {
|
||||
<svg width="10" height="2" viewBox="0 0 10 2" fill="none">
|
||||
<rect y="0.5" width="10" height="1" rx="0.5" fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function MaximizeIcon() {
|
||||
@@ -17,16 +25,25 @@ function MaximizeIcon() {
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<rect x="0.5" y="0.5" width="9" height="9" rx="1.5" stroke="currentColor" strokeWidth="1" />
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function RestoreIcon() {
|
||||
return (
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<rect x="2.5" y="0.5" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1" />
|
||||
<rect x="0.5" y="2.5" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1" fill="var(--color-gray-950)" />
|
||||
<rect
|
||||
x="0.5"
|
||||
y="2.5"
|
||||
width="7"
|
||||
height="7"
|
||||
rx="1.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
fill="var(--color-gray-950)"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function CloseIcon() {
|
||||
@@ -34,38 +51,52 @@ function CloseIcon() {
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<path d="M1 1L9 9M9 1L1 9" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export function TitleBar() {
|
||||
const [isMaximized, setIsMaximized] = useState(false);
|
||||
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen);
|
||||
const updateStatus = useGalleryStore((state) => state.updateStatus);
|
||||
const updateVersion = useGalleryStore((state) => state.updateVersion);
|
||||
const installUpdate = useGalleryStore((state) => state.installUpdate);
|
||||
const appWindow = getCurrentWindow();
|
||||
const [isMaximized, setIsMaximized] = useState(false)
|
||||
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen)
|
||||
const theme = useGalleryStore((state) => state.theme)
|
||||
const setTheme = useGalleryStore((state) => state.setTheme)
|
||||
const updateStatus = useGalleryStore((state) => state.updateStatus)
|
||||
const updateVersion = useGalleryStore((state) => state.updateVersion)
|
||||
const installUpdate = useGalleryStore((state) => state.installUpdate)
|
||||
const appWindow = getCurrentWindow()
|
||||
|
||||
// Right-clicking the settings cog opens a quick theme switcher, anchored under
|
||||
// the cog so it never overflows the right edge of the window.
|
||||
const settingsBtnRef = useRef<HTMLButtonElement>(null)
|
||||
const [themeMenu, setThemeMenu] = useState<{ x: number; y: number } | null>(null)
|
||||
|
||||
const handleSettingsContextMenu = (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
const rect = settingsBtnRef.current?.getBoundingClientRect()
|
||||
if (!rect) return
|
||||
setThemeMenu({ x: rect.right, y: rect.bottom + 4 })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Get initial maximized state
|
||||
appWindow.isMaximized().then(setIsMaximized);
|
||||
appWindow.isMaximized().then(setIsMaximized)
|
||||
|
||||
// Listen for resize events to update maximized state
|
||||
const unlisten = appWindow.onResized(() => {
|
||||
appWindow.isMaximized().then(setIsMaximized);
|
||||
});
|
||||
appWindow.isMaximized().then(setIsMaximized)
|
||||
})
|
||||
|
||||
return () => {
|
||||
unlisten.then((fn) => fn());
|
||||
};
|
||||
}, []);
|
||||
unlisten.then((fn) => fn())
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleMinimize = () => appWindow.minimize();
|
||||
const handleMaximize = () => appWindow.toggleMaximize();
|
||||
const handleClose = () => appWindow.close();
|
||||
const handleMinimize = () => appWindow.minimize()
|
||||
const handleMaximize = () => appWindow.toggleMaximize()
|
||||
const handleClose = () => appWindow.close()
|
||||
|
||||
// An update is waiting for the user to act. Covers the "clicked Later" case too,
|
||||
// since dismissing the toast doesn't change updateStatus.
|
||||
const updatePending = updateStatus === "available";
|
||||
const updatePending = updateStatus === 'available'
|
||||
|
||||
return (
|
||||
// data-tauri-drag-region is the recommended Tauri approach for drag regions.
|
||||
@@ -73,35 +104,31 @@ export function TitleBar() {
|
||||
<div
|
||||
data-tauri-drag-region
|
||||
className="titlebar relative z-50 flex h-9 shrink-0 items-center bg-gray-950 select-none"
|
||||
style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
|
||||
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
|
||||
>
|
||||
{/* App icon + name — left side. When an update is waiting, the iris lights
|
||||
up its focal point and the chip becomes a button that re-opens the prompt. */}
|
||||
<div className="flex items-center gap-2 pl-3 pr-4">
|
||||
<div className="flex items-center gap-2 pr-4 pl-3">
|
||||
{updatePending ? (
|
||||
<div
|
||||
className="group relative"
|
||||
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
|
||||
>
|
||||
<button
|
||||
onClick={() => void installUpdate()}
|
||||
aria-label={`Update available — click to update to Phokus v${updateVersion}`}
|
||||
className="relative flex h-5 w-5 items-center justify-center rounded-md bg-white/8 overflow-hidden text-gray-300 transition-colors hover:bg-white/12"
|
||||
>
|
||||
<span className="pointer-events-none absolute left-1/2 top-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 rounded-full bg-amber-400/60 animate-ping" />
|
||||
<PhokusMark className="relative h-4 w-4" dotClassName="fill-amber-400" />
|
||||
</button>
|
||||
{/* Custom tooltip — fades in ~100ms instead of the native ~500ms delay. */}
|
||||
<span className="pointer-events-none absolute left-0 top-full z-50 mt-1.5 whitespace-nowrap rounded-md border border-white/10 bg-gray-800 px-2 py-1 text-[11px] text-gray-200 opacity-0 shadow-lg transition-opacity duration-100 group-hover:opacity-100">
|
||||
Click to update — v{updateVersion}
|
||||
</span>
|
||||
<div style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}>
|
||||
{/* Instant tooltip (delay 0) — this affordance should read immediately. */}
|
||||
<Tooltip label={`Click to update — v${updateVersion}`} delay={0} align="start">
|
||||
<button
|
||||
onClick={() => void installUpdate()}
|
||||
aria-label={`Update available — click to update to Phokus v${updateVersion}`}
|
||||
className="relative flex h-5 w-5 items-center justify-center overflow-hidden rounded-md bg-white/8 text-gray-300 transition-colors hover:bg-white/12"
|
||||
>
|
||||
<span className="pointer-events-none absolute top-1/2 left-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 animate-ping rounded-full bg-amber-400/60" />
|
||||
<PhokusMark className="relative h-4 w-4" dotClassName="fill-amber-400" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-5 w-5 items-center justify-center rounded-md bg-white/8 overflow-hidden text-gray-300">
|
||||
<div className="flex h-5 w-5 items-center justify-center overflow-hidden rounded-md bg-white/8 text-gray-300">
|
||||
<PhokusMark className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<span className="text-[11px] font-semibold text-gray-400 tracking-wide">Phokus</span>
|
||||
<span className="text-[11px] font-semibold tracking-wide text-gray-400">Phokus</span>
|
||||
</div>
|
||||
|
||||
{/* Spacer — draggable region fills here */}
|
||||
@@ -109,20 +136,33 @@ export function TitleBar() {
|
||||
|
||||
{/* Window control buttons — right side, non-draggable */}
|
||||
<div
|
||||
className="flex items-stretch h-full"
|
||||
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
|
||||
className="flex h-full items-stretch"
|
||||
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
|
||||
>
|
||||
<button
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
title="Settings"
|
||||
className="group flex h-full w-10 items-center justify-center text-gray-600 transition-colors duration-100 hover:bg-white/6 hover:text-gray-300"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.607 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<Tooltip label="Settings (right-click to switch theme)" anchorToCursor>
|
||||
<button
|
||||
ref={settingsBtnRef}
|
||||
aria-label="Settings"
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
onContextMenu={handleSettingsContextMenu}
|
||||
className="group flex h-full w-10 items-center justify-center text-gray-600 transition-colors duration-100 hover:bg-white/6 hover:text-gray-300"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.8}
|
||||
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.607 2.296.07 2.572-1.065z"
|
||||
/>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.8}
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/* Minimize */}
|
||||
<button
|
||||
onClick={handleMinimize}
|
||||
@@ -135,7 +175,7 @@ export function TitleBar() {
|
||||
{/* Maximize / Restore */}
|
||||
<button
|
||||
onClick={handleMaximize}
|
||||
title={isMaximized ? "Restore" : "Maximize"}
|
||||
title={isMaximized ? 'Restore' : 'Maximize'}
|
||||
className="group flex h-full w-10 items-center justify-center text-gray-600 transition-colors duration-100 hover:bg-white/6 hover:text-gray-300"
|
||||
>
|
||||
{isMaximized ? <RestoreIcon /> : <MaximizeIcon />}
|
||||
@@ -150,6 +190,27 @@ export function TitleBar() {
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Quick theme switcher — opened by right-clicking the settings cog. */}
|
||||
{themeMenu && (
|
||||
<ContextMenu
|
||||
x={themeMenu.x}
|
||||
y={themeMenu.y}
|
||||
size="sm"
|
||||
align="end"
|
||||
onClose={() => setThemeMenu(null)}
|
||||
>
|
||||
<MenuLabel>Theme</MenuLabel>
|
||||
{THEME_OPTIONS.map((opt) => (
|
||||
<MenuItem
|
||||
key={opt.value}
|
||||
label={opt.label}
|
||||
checked={theme === opt.value}
|
||||
onSelect={() => setTheme(opt.value)}
|
||||
/>
|
||||
))}
|
||||
</ContextMenu>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,475 +1,24 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { tileSizeForZoom, useGalleryStore, SortOrder, MediaFilter, SearchCommand, parseSearchValue, searchModeLabel, ExploreTagEntry } from "../store";
|
||||
import { FolderScopeDropdown } from "./FolderScopeDropdown";
|
||||
|
||||
const BASE_SORT_OPTIONS: { value: SortOrder; label: string }[] = [
|
||||
{ value: "date_desc", label: "Newest first" },
|
||||
{ value: "date_asc", label: "Oldest first" },
|
||||
{ value: "taken_desc", label: "Taken: newest" },
|
||||
{ value: "taken_asc", label: "Taken: oldest" },
|
||||
{ value: "name_asc", label: "Name A–Z" },
|
||||
{ value: "name_desc", label: "Name Z–A" },
|
||||
{ value: "rating_desc", label: "Highest rated" },
|
||||
{ value: "rating_asc", label: "Lowest rated" },
|
||||
{ value: "size_desc", label: "Largest first" },
|
||||
{ value: "size_asc", label: "Smallest first" },
|
||||
];
|
||||
|
||||
const VIDEO_SORT_OPTIONS: { value: SortOrder; label: string }[] = [
|
||||
{ value: "duration_desc", label: "Longest first" },
|
||||
{ value: "duration_asc", label: "Shortest first" },
|
||||
];
|
||||
|
||||
function getSortOptions(mediaFilter: MediaFilter) {
|
||||
if (mediaFilter === "video") {
|
||||
return [...BASE_SORT_OPTIONS, ...VIDEO_SORT_OPTIONS];
|
||||
}
|
||||
return BASE_SORT_OPTIONS;
|
||||
}
|
||||
|
||||
function SortDropdown({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
}: {
|
||||
value: SortOrder;
|
||||
onChange: (v: SortOrder) => void;
|
||||
options: { value: SortOrder; label: string }[];
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const current = options.find((o) => o.value === value) ?? BASE_SORT_OPTIONS[0];
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: MouseEvent) => {
|
||||
if (!ref.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className={`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
open
|
||||
? "border-white/15 bg-white/8 text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "border-white/8 bg-transparent text-gray-400 hover:border-white/15 hover:text-gray-200 light-theme:border-gray-700/40 light-theme:text-gray-600 light-theme:hover:border-gray-700 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<span>{current?.label ?? "Sort"}</span>
|
||||
<svg
|
||||
className={`h-3 w-3 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="absolute right-0 top-full z-30 mt-1.5 min-w-44 rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur light-theme:border-gray-700/50">
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
className={`flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
option.value === value
|
||||
? "bg-white/6 text-white light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "text-gray-400 hover:bg-white/5 hover:text-white light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => { onChange(option.value); setOpen(false); }}
|
||||
>
|
||||
{option.label}
|
||||
{option.value === value ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FilterPill({
|
||||
label,
|
||||
active,
|
||||
onClick,
|
||||
variant = "default",
|
||||
}: {
|
||||
label: string;
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
variant?: "default" | "amber";
|
||||
}) {
|
||||
const activeClass =
|
||||
variant === "amber"
|
||||
? "bg-amber-500/15 text-amber-300 border border-amber-500/30 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:border-amber-500/50"
|
||||
: "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white";
|
||||
return (
|
||||
<button
|
||||
className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-150 ${
|
||||
active
|
||||
? activeClass
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function commandPrefix(command: SearchCommand | null): string | null {
|
||||
switch (command) {
|
||||
case "semantic":
|
||||
return "/s";
|
||||
case "tag":
|
||||
return "/t";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function composeSearchValue(command: SearchCommand | null, query: string): string {
|
||||
const prefix = commandPrefix(command);
|
||||
if (!prefix) return query;
|
||||
return query.length > 0 ? `${prefix} ${query}` : prefix;
|
||||
}
|
||||
import { SortControl } from './toolbar/SortControl'
|
||||
import { ToolbarFilters } from './toolbar/ToolbarFilters'
|
||||
import { ToolbarSearch } from './toolbar/ToolbarSearch'
|
||||
import { ToolbarTitle } from './toolbar/ToolbarTitle'
|
||||
import { useToolbarSearch } from './toolbar/useToolbarSearch'
|
||||
import { ZoomControl } from './toolbar/ZoomControl'
|
||||
|
||||
export function Toolbar() {
|
||||
const search = useGalleryStore((state) => state.search);
|
||||
const setSearch = useGalleryStore((state) => state.setSearch);
|
||||
const clearSearch = useGalleryStore((state) => state.clearSearch);
|
||||
const sort = useGalleryStore((state) => state.sort);
|
||||
const setSort = useGalleryStore((state) => state.setSort);
|
||||
const totalImages = useGalleryStore((state) => state.totalImages);
|
||||
const loadedCount = useGalleryStore((state) => state.loadedCount);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle);
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const mediaFilter = useGalleryStore((state) => state.mediaFilter);
|
||||
const setMediaFilter = useGalleryStore((state) => state.setMediaFilter);
|
||||
const favoritesOnly = useGalleryStore((state) => state.favoritesOnly);
|
||||
const setFavoritesOnly = useGalleryStore((state) => state.setFavoritesOnly);
|
||||
const minimumRating = useGalleryStore((state) => state.minimumRating);
|
||||
const setMinimumRating = useGalleryStore((state) => state.setMinimumRating);
|
||||
const failedEmbeddingsOnly = useGalleryStore((state) => state.failedEmbeddingsOnly);
|
||||
const setFailedEmbeddingsOnly = useGalleryStore((state) => state.setFailedEmbeddingsOnly);
|
||||
const failedTaggingOnly = useGalleryStore((state) => state.failedTaggingOnly);
|
||||
const setFailedTaggingOnly = useGalleryStore((state) => state.setFailedTaggingOnly);
|
||||
const similarScope = useGalleryStore((state) => state.similarScope);
|
||||
const setSimilarScope = useGalleryStore((state) => state.setSimilarScope);
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const setZoomPreset = useGalleryStore((state) => state.setZoomPreset);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
|
||||
const hasAnyFailedEmbeddings = Object.values(mediaJobProgress).some((p) => p.embedding_failed > 0);
|
||||
const hasAnyFailedTagging = Object.values(mediaJobProgress).some((p) => p.tagging_failed > 0);
|
||||
|
||||
const [searchCommand, setSearchCommand] = useState<SearchCommand | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState(search);
|
||||
const [searchPanelOpen, setSearchPanelOpen] = useState(false);
|
||||
const [tagSuggestions, setTagSuggestions] = useState<ExploreTagEntry[]>([]);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const suggestDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const searchShellRef = useRef<HTMLDivElement>(null);
|
||||
const userHasTyped = useRef(false);
|
||||
|
||||
const selectedFolder = folders.find((folder) => folder.id === selectedFolderId);
|
||||
const title = collectionTitle ?? (selectedFolder ? selectedFolder.name : "All Media");
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
const sortOptions = getSortOptions(mediaFilter);
|
||||
const hasActiveSearch = search.trim().length > 0;
|
||||
const parsedSearch = parseSearchValue(composeSearchValue(searchCommand, searchQuery));
|
||||
const isSimilarResults = collectionTitle === "Similar Images";
|
||||
|
||||
// If current sort is video-only but we switched away from video filter, reset to date_desc
|
||||
useEffect(() => {
|
||||
if (mediaFilter !== "video" && (sort === "duration_asc" || sort === "duration_desc")) {
|
||||
setSort("date_desc");
|
||||
}
|
||||
}, [mediaFilter, sort, setSort]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userHasTyped.current) return;
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => { setSearch(composeSearchValue(searchCommand, searchQuery)); }, 200);
|
||||
return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
|
||||
}, [searchCommand, searchQuery, setSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
const parsed = parseSearchValue(search);
|
||||
setSearchCommand(parsed.prefix && parsed.mode !== "filename" ? parsed.mode : null);
|
||||
setSearchQuery(parsed.prefix ? parsed.query : search);
|
||||
}, [search]);
|
||||
|
||||
// Fetch tag suggestions when in tag mode
|
||||
useEffect(() => {
|
||||
if (searchCommand !== "tag") {
|
||||
setTagSuggestions([]);
|
||||
return;
|
||||
}
|
||||
if (suggestDebounceRef.current) clearTimeout(suggestDebounceRef.current);
|
||||
suggestDebounceRef.current = setTimeout(async () => {
|
||||
try {
|
||||
const results = await invoke<ExploreTagEntry[]>("search_tags_autocomplete", {
|
||||
params: { query: searchQuery.trim(), folder_id: selectedFolderId ?? null, limit: 10 },
|
||||
});
|
||||
setTagSuggestions(results);
|
||||
} catch {
|
||||
setTagSuggestions([]);
|
||||
}
|
||||
}, 120);
|
||||
return () => { if (suggestDebounceRef.current) clearTimeout(suggestDebounceRef.current); };
|
||||
}, [searchCommand, searchQuery, selectedFolderId]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
const activeElement = document.activeElement;
|
||||
const searchFocused = activeElement === searchInputRef.current;
|
||||
if (event.key === "Escape" && (searchFocused || hasActiveSearch)) {
|
||||
event.preventDefault();
|
||||
setSearchCommand(null);
|
||||
setSearchQuery("");
|
||||
clearSearch();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [clearSearch, hasActiveSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (event: PointerEvent) => {
|
||||
if (searchShellRef.current?.contains(event.target as Node)) return;
|
||||
setSearchPanelOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
const showTagSuggestions = searchCommand === "tag" && searchPanelOpen;
|
||||
const showCommandHints = !searchCommand && searchPanelOpen;
|
||||
const searchState = useToolbarSearch()
|
||||
|
||||
return (
|
||||
<div className="relative z-20 shrink-0 border-b border-white/[0.06] bg-gray-950/80 backdrop-blur-xl">
|
||||
{/* Primary row */}
|
||||
<div className="flex items-center gap-3 px-5 h-12">
|
||||
{/* Title + count */}
|
||||
<div className="flex items-baseline gap-2.5 min-w-0 shrink-0">
|
||||
<h2 className="text-[15px] font-semibold text-white truncate max-w-48">{title}</h2>
|
||||
<span className="text-xs text-gray-600 shrink-0">
|
||||
{loadedCount < totalImages
|
||||
? `${loadedCount.toLocaleString()} / ${totalImages.toLocaleString()}`
|
||||
: totalImages.toLocaleString()}
|
||||
</span>
|
||||
{hasActiveSearch && (
|
||||
<span className="rounded-md border border-blue-500/20 bg-blue-500/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-blue-300 shrink-0">
|
||||
{searchModeLabel(parsedSearch.mode)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeView === "timeline" ? <FolderScopeDropdown /> : null}
|
||||
|
||||
<div className="relative z-40 shrink-0 border-b border-white/[0.06] bg-gray-950/80 backdrop-blur-xl">
|
||||
<div className="flex h-12 items-center gap-2 px-3 lg:gap-3 lg:px-5">
|
||||
<ToolbarTitle parsedSearch={searchState.parsedSearch} />
|
||||
<div className="flex-1" />
|
||||
|
||||
{/* Search */}
|
||||
<div ref={searchShellRef} className="relative">
|
||||
<div className="flex items-center rounded-lg border border-white/8 bg-white/5 overflow-hidden">
|
||||
<div className="relative">
|
||||
<svg className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-600"
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||
d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z" />
|
||||
</svg>
|
||||
<input
|
||||
ref={searchInputRef}
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(event) => {
|
||||
userHasTyped.current = true;
|
||||
const nextValue = event.target.value;
|
||||
if (!searchCommand) {
|
||||
const parsed = parseSearchValue(nextValue);
|
||||
if (parsed.prefix) {
|
||||
setSearchCommand(parsed.mode === "filename" ? null : parsed.mode);
|
||||
setSearchQuery(parsed.query);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSearchQuery(nextValue);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Backspace" && searchQuery.length === 0 && searchCommand !== null) {
|
||||
event.preventDefault();
|
||||
setSearchCommand(null);
|
||||
}
|
||||
}}
|
||||
onFocus={() => setSearchPanelOpen(true)}
|
||||
placeholder="Search files, or use /s /t"
|
||||
className={`w-64 bg-transparent py-1.5 pr-9 text-sm text-white placeholder:text-gray-600 focus:outline-none transition-colors ${searchCommand !== null ? "pl-16" : "pl-8"}`}
|
||||
/>
|
||||
{searchCommand !== null ? (
|
||||
<div className="absolute left-8 top-1/2 -translate-y-1/2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/10 bg-white/[0.05] px-1.5 py-0.5 font-mono text-[11px] text-gray-300 transition-colors hover:bg-white/[0.08] hover:text-white"
|
||||
onClick={() => { setSearchCommand(null); setTagSuggestions([]); }}
|
||||
title="Remove search command"
|
||||
>
|
||||
{commandPrefix(searchCommand)}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{searchQuery.trim().length > 0 || searchCommand !== null ? (
|
||||
<button
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-gray-500 hover:bg-white/5 hover:text-gray-200 transition-colors"
|
||||
title="Clear search"
|
||||
onClick={() => {
|
||||
setSearchCommand(null);
|
||||
setSearchQuery("");
|
||||
setTagSuggestions([]);
|
||||
clearSearch();
|
||||
}}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tag autocomplete suggestions */}
|
||||
{showTagSuggestions && tagSuggestions.length > 0 ? (
|
||||
<div className="absolute left-0 top-full z-30 mt-1.5 w-72 rounded-xl border border-white/10 bg-gray-950/98 py-1 shadow-2xl backdrop-blur">
|
||||
{tagSuggestions.map((entry) => (
|
||||
<button
|
||||
key={entry.tag}
|
||||
className="flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors hover:bg-white/[0.05]"
|
||||
onMouseDown={(e) => {
|
||||
// mousedown fires before input blur, so we prevent losing focus
|
||||
e.preventDefault();
|
||||
userHasTyped.current = true;
|
||||
setSearchQuery(entry.tag);
|
||||
setSearch(`/t ${entry.tag}`);
|
||||
setSearchPanelOpen(false);
|
||||
searchInputRef.current?.blur();
|
||||
}}
|
||||
>
|
||||
<span className="text-sm text-white/88">{entry.tag}</span>
|
||||
<span className="shrink-0 text-[11px] tabular-nums text-white/30">{entry.count.toLocaleString()}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Tag mode with no suggestions yet — show a brief hint */}
|
||||
{showTagSuggestions && tagSuggestions.length === 0 && searchQuery.trim().length > 0 ? (
|
||||
<div className="absolute left-0 top-full z-30 mt-1.5 w-72 rounded-xl border border-white/10 bg-gray-950/98 px-3 py-2.5 shadow-2xl backdrop-blur">
|
||||
<p className="text-xs text-white/25">No matching tags</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Semantic mode hint */}
|
||||
{searchCommand === "semantic" && searchPanelOpen ? (
|
||||
<div className="absolute left-0 top-full z-30 mt-1.5 w-72 rounded-xl border border-white/10 bg-gray-950/98 px-3 py-2.5 shadow-2xl backdrop-blur">
|
||||
<p className="text-xs text-white/40">Search by meaning and visual concepts</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Command hints — only shown when no command is active */}
|
||||
{showCommandHints ? (
|
||||
<div className="absolute left-0 top-full z-30 mt-1.5 w-64 rounded-xl border border-white/10 bg-gray-950/98 py-1 shadow-2xl backdrop-blur">
|
||||
{(
|
||||
[
|
||||
{ command: "tag" as SearchCommand, prefix: "/t", label: "Tags", description: "Search AI and user tags" },
|
||||
{ command: "semantic" as SearchCommand, prefix: "/s", label: "Semantic", description: "Search by meaning" },
|
||||
] as const
|
||||
).map((option) => (
|
||||
<button
|
||||
key={option.prefix}
|
||||
className="flex w-full items-center gap-3 px-3 py-2 text-left transition-colors hover:bg-white/[0.05]"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
userHasTyped.current = true;
|
||||
setSearchCommand(option.command);
|
||||
searchInputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<span className="rounded border border-white/10 bg-white/[0.04] px-1.5 py-0.5 font-mono text-[11px] text-gray-400">
|
||||
{option.prefix}
|
||||
</span>
|
||||
<div>
|
||||
<p className="text-sm text-gray-200">{option.label}</p>
|
||||
<p className="text-xs text-gray-500">{option.description}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Sort */}
|
||||
<SortDropdown value={sort} onChange={setSort} options={sortOptions} />
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-4 w-px bg-white/10 shrink-0" />
|
||||
|
||||
{/* Zoom */}
|
||||
<div className="flex items-center rounded-lg border border-white/8 overflow-hidden light-theme:border-gray-700/40">
|
||||
{(["compact", "comfortable", "detail"] as const).map((preset, i) => (
|
||||
<button
|
||||
key={preset}
|
||||
className={`px-2.5 py-1.5 text-xs font-medium transition-colors ${
|
||||
i > 0 ? "border-l border-white/8" : ""
|
||||
} ${
|
||||
zoomPreset === preset
|
||||
? "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
title={`${tileSize}px tiles`}
|
||||
onClick={() => setZoomPreset(preset)}
|
||||
>
|
||||
{preset === "compact" ? "S" : preset === "comfortable" ? "M" : "L"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter row */}
|
||||
<div className="flex items-center gap-1 px-4 pb-1.5">
|
||||
<FilterPill label="All" active={mediaFilter === "all" && !favoritesOnly && !failedEmbeddingsOnly && !failedTaggingOnly && minimumRating === 0} onClick={() => { setMediaFilter("all"); setFavoritesOnly(false); setMinimumRating(0); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Images" active={mediaFilter === "image" && !favoritesOnly && !failedEmbeddingsOnly && !failedTaggingOnly} onClick={() => { setMediaFilter("image"); setFavoritesOnly(false); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Videos" active={mediaFilter === "video" && !favoritesOnly && !failedEmbeddingsOnly && !failedTaggingOnly} onClick={() => { setMediaFilter("video"); setFavoritesOnly(false); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Favorites" active={favoritesOnly} onClick={() => { setFavoritesOnly(!favoritesOnly); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Rated" active={minimumRating === 1} onClick={() => { setMinimumRating(minimumRating === 1 ? 0 : 1); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="4★+" active={minimumRating === 4} onClick={() => { setMinimumRating(minimumRating === 4 ? 0 : 4); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Similar: Folder" active={similarScope === "current_folder"} onClick={() => setSimilarScope("current_folder")} />
|
||||
<FilterPill label="Similar: All" active={similarScope === "all_media"} onClick={() => setSimilarScope("all_media")} />
|
||||
{hasAnyFailedEmbeddings ? (
|
||||
<FilterPill
|
||||
label="Failed Embeddings"
|
||||
active={failedEmbeddingsOnly}
|
||||
variant="amber"
|
||||
onClick={() => setFailedEmbeddingsOnly(!failedEmbeddingsOnly)}
|
||||
/>
|
||||
) : null}
|
||||
{hasAnyFailedTagging ? (
|
||||
<FilterPill
|
||||
label="Failed Tags"
|
||||
active={failedTaggingOnly}
|
||||
variant="amber"
|
||||
onClick={() => setFailedTaggingOnly(!failedTaggingOnly)}
|
||||
/>
|
||||
) : null}
|
||||
{isSimilarResults ? <span className="ml-2 text-[11px] text-gray-500">Current similar scope: {similarScope === "current_folder" ? "current folder" : "all media"}</span> : null}
|
||||
<ToolbarSearch searchState={searchState} />
|
||||
<SortControl />
|
||||
<div className="h-4 w-px shrink-0 bg-white/10" />
|
||||
<ZoomControl />
|
||||
</div>
|
||||
<ToolbarFilters />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { MouseEvent, ReactNode, useEffect, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { motion } from 'framer-motion'
|
||||
|
||||
type TooltipSide = 'top' | 'bottom' | 'left' | 'right'
|
||||
type TooltipAlign = 'center' | 'start' | 'end'
|
||||
|
||||
// Horizontal alignment only applies to top/bottom; left/right center vertically.
|
||||
function positionClasses(side: TooltipSide, align: TooltipAlign): string {
|
||||
if (side === 'left') return 'right-full top-1/2 mr-1.5 -translate-y-1/2'
|
||||
if (side === 'right') return 'left-full top-1/2 ml-1.5 -translate-y-1/2'
|
||||
const vertical = side === 'top' ? 'bottom-full mb-1.5' : 'top-full mt-1.5'
|
||||
const horizontal =
|
||||
align === 'start' ? 'left-0' : align === 'end' ? 'right-0' : 'left-1/2 -translate-x-1/2'
|
||||
return `${vertical} ${horizontal}`
|
||||
}
|
||||
|
||||
const BASE_CLASSES =
|
||||
'pointer-events-none z-50 whitespace-nowrap rounded-md border border-white/10 bg-gray-800 px-2 py-1 text-[11px] text-gray-200 shadow-lg'
|
||||
const STATIC_CLASSES = `${BASE_CLASSES} transition-opacity duration-100`
|
||||
|
||||
/**
|
||||
* Lightweight custom tooltip — fades in (faster than the native one) after a
|
||||
* tunable hover `delay`, and hides instantly on leave or click. By default it
|
||||
* anchors to a `side` of the wrapper. `anchorToCursor` shows at the pointer's
|
||||
* entry position; `followCursor` keeps tracking the pointer.
|
||||
*/
|
||||
export function Tooltip({
|
||||
label,
|
||||
delay = 400,
|
||||
side = 'bottom',
|
||||
align = 'center',
|
||||
block = false,
|
||||
anchorToCursor = false,
|
||||
followCursor = false,
|
||||
disabled = false,
|
||||
className = '',
|
||||
children,
|
||||
}: {
|
||||
label: ReactNode
|
||||
/** Milliseconds the pointer must hover before the tooltip appears (0 = instant). */
|
||||
delay?: number
|
||||
side?: TooltipSide
|
||||
/** Horizontal alignment for top/bottom tooltips. */
|
||||
align?: TooltipAlign
|
||||
/** Full-width block wrapper (e.g. wrapping a grid cell) instead of inline. */
|
||||
block?: boolean
|
||||
/** Position at the cursor when shown, without following subsequent movement. */
|
||||
anchorToCursor?: boolean
|
||||
/** Track the cursor (fixed position) instead of anchoring to a side. */
|
||||
followCursor?: boolean
|
||||
/** Render the wrapper but suppress tooltip display. */
|
||||
disabled?: boolean
|
||||
/** Extra classes for the wrapper (e.g. layout). */
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const [visible, setVisible] = useState(false)
|
||||
const [coords, setCoords] = useState({ x: 0, y: 0 })
|
||||
const [mounted, setMounted] = useState(false)
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
|
||||
const frame = useRef<number | undefined>(undefined)
|
||||
const tooltipRef = useRef<HTMLSpanElement>(null)
|
||||
|
||||
// Resolve a viewport-safe position near the cursor: below-right by default,
|
||||
// but flipped above the cursor if it would overflow the bottom edge, and
|
||||
// clamped so it never runs off the right/left.
|
||||
const place = (clientX: number, clientY: number) => {
|
||||
const tip = tooltipRef.current
|
||||
const tipWidth = tip?.offsetWidth ?? 0
|
||||
const tipHeight = tip?.offsetHeight ?? 24
|
||||
const gap = 16
|
||||
let top = clientY + gap
|
||||
if (top + tipHeight > window.innerHeight - 4) {
|
||||
top = clientY - gap - tipHeight
|
||||
}
|
||||
let left = clientX + 14
|
||||
if (left + tipWidth > window.innerWidth - 4) left = window.innerWidth - 4 - tipWidth
|
||||
if (left < 4) left = 4
|
||||
setCoords({ x: left, y: top })
|
||||
}
|
||||
|
||||
const clear = () => {
|
||||
if (timer.current) clearTimeout(timer.current)
|
||||
timer.current = undefined
|
||||
if (frame.current !== undefined) cancelAnimationFrame(frame.current)
|
||||
frame.current = undefined
|
||||
}
|
||||
const show = (event: MouseEvent<HTMLElement>) => {
|
||||
if (disabled) return
|
||||
clear()
|
||||
if (anchorToCursor || followCursor) place(event.clientX, event.clientY)
|
||||
if (delay <= 0) {
|
||||
setVisible(true)
|
||||
return
|
||||
}
|
||||
timer.current = setTimeout(() => setVisible(true), delay)
|
||||
}
|
||||
const hide = () => {
|
||||
clear()
|
||||
setVisible(false)
|
||||
}
|
||||
const move = (event: MouseEvent<HTMLElement>) => {
|
||||
if (!followCursor) return
|
||||
const { clientX, clientY } = event
|
||||
if (frame.current !== undefined) cancelAnimationFrame(frame.current)
|
||||
frame.current = requestAnimationFrame(() => {
|
||||
frame.current = undefined
|
||||
place(clientX, clientY)
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true)
|
||||
return clear
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled) hide()
|
||||
}, [disabled])
|
||||
|
||||
const Wrapper = block ? 'div' : 'span'
|
||||
const cursorTooltip = (
|
||||
<motion.span
|
||||
ref={tooltipRef}
|
||||
role="tooltip"
|
||||
aria-hidden={!visible}
|
||||
// Portaled + fixed so transformed parents and scroll containers cannot
|
||||
// distort cursor-anchored tooltip coordinates.
|
||||
className={`fixed ${BASE_CLASSES}`}
|
||||
initial={false}
|
||||
animate={{ left: coords.x, top: coords.y, opacity: visible ? 1 : 0 }}
|
||||
transition={{
|
||||
left: followCursor
|
||||
? { type: 'spring', stiffness: 700, damping: 45, mass: 0.35 }
|
||||
: { duration: 0 },
|
||||
top: followCursor
|
||||
? { type: 'spring', stiffness: 520, damping: 34, mass: 0.45 }
|
||||
: { duration: 0 },
|
||||
opacity: { duration: visible ? 0.1 : 0.05 },
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</motion.span>
|
||||
)
|
||||
|
||||
return (
|
||||
<Wrapper
|
||||
className={`${block ? 'relative block w-full' : 'relative inline-flex'} ${className}`}
|
||||
onMouseEnter={show}
|
||||
onMouseMove={followCursor ? move : undefined}
|
||||
onMouseLeave={hide}
|
||||
onPointerDown={hide}
|
||||
>
|
||||
{children}
|
||||
{disabled ? null : anchorToCursor || followCursor ? (
|
||||
mounted ? (
|
||||
createPortal(cursorTooltip, document.body)
|
||||
) : null
|
||||
) : (
|
||||
<span
|
||||
role="tooltip"
|
||||
aria-hidden={!visible}
|
||||
className={`absolute ${STATIC_CLASSES} ${positionClasses(side, align)} ${visible ? 'opacity-100' : 'opacity-0'}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
</Wrapper>
|
||||
)
|
||||
}
|
||||
@@ -1,17 +1,19 @@
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useGalleryStore } from '../store'
|
||||
|
||||
export function UpdateToast() {
|
||||
const updateStatus = useGalleryStore((s) => s.updateStatus);
|
||||
const updateVersion = useGalleryStore((s) => s.updateVersion);
|
||||
const updateProgress = useGalleryStore((s) => s.updateProgress);
|
||||
const updateDismissed = useGalleryStore((s) => s.updateDismissed);
|
||||
const installUpdate = useGalleryStore((s) => s.installUpdate);
|
||||
const dismissUpdate = useGalleryStore((s) => s.dismissUpdate);
|
||||
const updateStatus = useGalleryStore((s) => s.updateStatus)
|
||||
const updateVersion = useGalleryStore((s) => s.updateVersion)
|
||||
const updateProgress = useGalleryStore((s) => s.updateProgress)
|
||||
const updateDismissed = useGalleryStore((s) => s.updateDismissed)
|
||||
const installUpdate = useGalleryStore((s) => s.installUpdate)
|
||||
const dismissUpdate = useGalleryStore((s) => s.dismissUpdate)
|
||||
|
||||
const visible =
|
||||
!updateDismissed &&
|
||||
(updateStatus === "available" || updateStatus === "downloading" || updateStatus === "installing");
|
||||
(updateStatus === 'available' ||
|
||||
updateStatus === 'downloading' ||
|
||||
updateStatus === 'installing')
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
@@ -21,9 +23,9 @@ export function UpdateToast() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 12 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className="fixed bottom-4 right-4 z-50 w-80 rounded-lg border border-white/10 bg-gray-900 p-4 shadow-xl"
|
||||
className="fixed right-4 bottom-4 z-50 w-80 rounded-lg border border-white/10 bg-gray-900 p-4 shadow-xl"
|
||||
>
|
||||
{updateStatus === "available" ? (
|
||||
{updateStatus === 'available' ? (
|
||||
<>
|
||||
<p className="text-sm font-medium text-white">Update available</p>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
@@ -31,7 +33,7 @@ export function UpdateToast() {
|
||||
</p>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<button
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-3 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25 light-theme:border-emerald-600/50 light-theme:bg-emerald-100 light-theme:text-emerald-700 light-theme:hover:bg-emerald-200"
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-3 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25"
|
||||
onClick={() => void installUpdate()}
|
||||
>
|
||||
Install & restart
|
||||
@@ -47,14 +49,18 @@ export function UpdateToast() {
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm font-medium text-white">
|
||||
{updateStatus === "installing" ? "Installing update..." : "Downloading update..."}
|
||||
{updateStatus === 'installing' ? 'Installing update...' : 'Downloading update...'}
|
||||
</p>
|
||||
<div className="mt-3 h-1 overflow-hidden rounded-full bg-white/10">
|
||||
<div
|
||||
className={`h-full rounded-full bg-emerald-400/80 transition-[width] duration-200 ${
|
||||
updateProgress === null ? "w-full animate-pulse" : ""
|
||||
updateProgress === null ? 'w-full animate-pulse' : ''
|
||||
}`}
|
||||
style={updateProgress !== null ? { width: `${Math.round(updateProgress * 100)}%` } : undefined}
|
||||
style={
|
||||
updateProgress !== null
|
||||
? { width: `${Math.round(updateProgress * 100)}%` }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-600">The app will restart when it finishes.</p>
|
||||
@@ -63,5 +69,5 @@ export function UpdateToast() {
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,456 +1,64 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useGalleryStore } from "../store";
|
||||
|
||||
const SPEED_OPTIONS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2];
|
||||
const CONTROLS_HIDE_DELAY_MS = 2500;
|
||||
const SEEK_STEP_SECONDS = 5;
|
||||
const VOLUME_STEP = 0.1;
|
||||
|
||||
// Session-wide playback preferences shared across player instances.
|
||||
let persistedVolume = 1;
|
||||
let persistedMuted = false;
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
|
||||
const total = Math.floor(seconds);
|
||||
const s = total % 60;
|
||||
const m = Math.floor(total / 60) % 60;
|
||||
const h = Math.floor(total / 3600);
|
||||
if (h > 0) return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
|
||||
return `${m}:${s.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
interface BufferedRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
function ControlButton({ onClick, title, active = false, children }: {
|
||||
onClick: () => void;
|
||||
title: string;
|
||||
active?: boolean;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`rounded-md p-1.5 transition-colors ${active ? "text-white" : "text-gray-300 hover:text-white"} hover:bg-white/10`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onClick();
|
||||
}}
|
||||
title={title}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
import { VideoControls } from './videoPlayer/VideoControls'
|
||||
import { useVideoPlayer } from './videoPlayer/useVideoPlayer'
|
||||
|
||||
export function VideoPlayer({ src }: { src: string }) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const trackRef = useRef<HTMLDivElement>(null);
|
||||
const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrubbingRef = useRef(false);
|
||||
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
const [duration, setDuration] = useState(0);
|
||||
const [buffered, setBuffered] = useState<BufferedRange[]>([]);
|
||||
const [volume, setVolume] = useState(persistedVolume);
|
||||
const [muted, setMuted] = useState(
|
||||
() => useGalleryStore.getState().lightboxAutoMute || persistedMuted,
|
||||
);
|
||||
const [playbackRate, setPlaybackRate] = useState(1);
|
||||
const [loop, setLoop] = useState(false);
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
const [controlsVisible, setControlsVisible] = useState(true);
|
||||
const [speedMenuOpen, setSpeedMenuOpen] = useState(false);
|
||||
|
||||
const speedMenuOpenRef = useRef(speedMenuOpen);
|
||||
speedMenuOpenRef.current = speedMenuOpen;
|
||||
|
||||
// ── Controls visibility ────────────────────────────────────────────────────
|
||||
const showControls = useCallback(() => {
|
||||
setControlsVisible(true);
|
||||
if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
|
||||
hideTimerRef.current = setTimeout(() => {
|
||||
const video = videoRef.current;
|
||||
if (video && !video.paused && !scrubbingRef.current && !speedMenuOpenRef.current) {
|
||||
setControlsVisible(false);
|
||||
}
|
||||
}, CONTROLS_HIDE_DELAY_MS);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ── Video element wiring ───────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
// Read playback prefs fresh for each opened video — not reactive, so a
|
||||
// settings change applies to the next video rather than the current one.
|
||||
const { lightboxAutoplay, lightboxAutoMute } = useGalleryStore.getState();
|
||||
const startMuted = lightboxAutoMute || persistedMuted;
|
||||
video.volume = persistedVolume;
|
||||
video.muted = startMuted;
|
||||
setMuted(startMuted);
|
||||
// Autoplay when enabled; if the webview blocks it the catch leaves us paused
|
||||
// with controls visible, which is a fine fallback.
|
||||
if (lightboxAutoplay) video.play().catch(() => {});
|
||||
}, [src]);
|
||||
|
||||
const readBuffered = useCallback(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !Number.isFinite(video.duration) || video.duration <= 0) return;
|
||||
const ranges: BufferedRange[] = [];
|
||||
for (let i = 0; i < video.buffered.length; i++) {
|
||||
ranges.push({
|
||||
start: video.buffered.start(i) / video.duration,
|
||||
end: video.buffered.end(i) / video.duration,
|
||||
});
|
||||
}
|
||||
setBuffered(ranges);
|
||||
}, []);
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
if (video.paused) {
|
||||
void video.play().catch(() => {});
|
||||
} else {
|
||||
video.pause();
|
||||
}
|
||||
showControls();
|
||||
}, [showControls]);
|
||||
|
||||
const seekBy = useCallback(
|
||||
(deltaSeconds: number) => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !Number.isFinite(video.duration)) return;
|
||||
video.currentTime = Math.min(video.duration, Math.max(0, video.currentTime + deltaSeconds));
|
||||
showControls();
|
||||
},
|
||||
[showControls],
|
||||
);
|
||||
|
||||
const applyVolume = useCallback(
|
||||
(nextVolume: number, nextMuted?: boolean) => {
|
||||
const video = videoRef.current;
|
||||
const clamped = Math.min(1, Math.max(0, nextVolume));
|
||||
setVolume(clamped);
|
||||
persistedVolume = clamped;
|
||||
if (nextMuted !== undefined) {
|
||||
setMuted(nextMuted);
|
||||
persistedMuted = nextMuted;
|
||||
if (video) video.muted = nextMuted;
|
||||
}
|
||||
if (video) video.volume = clamped;
|
||||
showControls();
|
||||
},
|
||||
[showControls],
|
||||
);
|
||||
|
||||
const toggleMute = useCallback(() => {
|
||||
const next = !muted;
|
||||
setMuted(next);
|
||||
persistedMuted = next;
|
||||
const video = videoRef.current;
|
||||
if (video) video.muted = next;
|
||||
showControls();
|
||||
}, [muted, showControls]);
|
||||
|
||||
const toggleLoop = useCallback(() => {
|
||||
setLoop((value) => {
|
||||
const video = videoRef.current;
|
||||
if (video) video.loop = !value;
|
||||
return !value;
|
||||
});
|
||||
showControls();
|
||||
}, [showControls]);
|
||||
|
||||
const toggleFullscreen = useCallback(() => {
|
||||
if (document.fullscreenElement) {
|
||||
void document.exitFullscreen().catch(() => {});
|
||||
} else {
|
||||
void containerRef.current?.requestFullscreen().catch(() => {});
|
||||
}
|
||||
showControls();
|
||||
}, [showControls]);
|
||||
|
||||
useEffect(() => {
|
||||
const onChange = () => setFullscreen(document.fullscreenElement !== null);
|
||||
document.addEventListener("fullscreenchange", onChange);
|
||||
return () => document.removeEventListener("fullscreenchange", onChange);
|
||||
}, []);
|
||||
|
||||
const setSpeed = useCallback(
|
||||
(rate: number) => {
|
||||
setPlaybackRate(rate);
|
||||
const video = videoRef.current;
|
||||
if (video) video.playbackRate = rate;
|
||||
setSpeedMenuOpen(false);
|
||||
showControls();
|
||||
},
|
||||
[showControls],
|
||||
);
|
||||
|
||||
// ── Scrubber ───────────────────────────────────────────────────────────────
|
||||
const seekToPointer = useCallback((clientX: number) => {
|
||||
const video = videoRef.current;
|
||||
const track = trackRef.current;
|
||||
if (!video || !track || !Number.isFinite(video.duration) || video.duration <= 0) return;
|
||||
const bounds = track.getBoundingClientRect();
|
||||
const fraction = Math.min(1, Math.max(0, (clientX - bounds.left) / bounds.width));
|
||||
video.currentTime = fraction * video.duration;
|
||||
setCurrentTime(video.currentTime);
|
||||
}, []);
|
||||
|
||||
const handleTrackPointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.stopPropagation();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
scrubbingRef.current = true;
|
||||
seekToPointer(event.clientX);
|
||||
},
|
||||
[seekToPointer],
|
||||
);
|
||||
|
||||
const handleTrackPointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!scrubbingRef.current) return;
|
||||
seekToPointer(event.clientX);
|
||||
},
|
||||
[seekToPointer],
|
||||
);
|
||||
|
||||
const handleTrackPointerUp = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
scrubbingRef.current = false;
|
||||
}, []);
|
||||
|
||||
// ── Keyboard ───────────────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) {
|
||||
return;
|
||||
}
|
||||
switch (event.key) {
|
||||
case " ":
|
||||
event.preventDefault();
|
||||
togglePlay();
|
||||
break;
|
||||
case "m":
|
||||
case "M":
|
||||
toggleMute();
|
||||
break;
|
||||
case "f":
|
||||
case "F":
|
||||
toggleFullscreen();
|
||||
break;
|
||||
case "l":
|
||||
case "L":
|
||||
toggleLoop();
|
||||
break;
|
||||
case "ArrowLeft":
|
||||
if (event.shiftKey) {
|
||||
event.preventDefault();
|
||||
seekBy(-SEEK_STEP_SECONDS);
|
||||
}
|
||||
break;
|
||||
case "ArrowRight":
|
||||
if (event.shiftKey) {
|
||||
event.preventDefault();
|
||||
seekBy(SEEK_STEP_SECONDS);
|
||||
}
|
||||
break;
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
// Adjusting volume always unmutes, matching the slider behavior.
|
||||
applyVolume(persistedVolume + VOLUME_STEP, false);
|
||||
break;
|
||||
case "ArrowDown":
|
||||
event.preventDefault();
|
||||
applyVolume(persistedVolume - VOLUME_STEP, false);
|
||||
break;
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [togglePlay, toggleMute, toggleFullscreen, toggleLoop, seekBy, applyVolume]);
|
||||
|
||||
const playedFraction = duration > 0 ? currentTime / duration : 0;
|
||||
const effectiveVolume = muted ? 0 : volume;
|
||||
const player = useVideoPlayer(src)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`media-dark-surface relative flex h-full w-full items-center justify-center bg-black ${controlsVisible ? "" : "cursor-none"}`}
|
||||
onPointerMove={showControls}
|
||||
ref={player.containerRef}
|
||||
className={`media-dark-surface relative flex h-full w-full items-center justify-center bg-black ${player.controlsVisible ? '' : 'cursor-none'}`}
|
||||
onPointerMove={player.showControls}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<video
|
||||
ref={videoRef}
|
||||
ref={player.videoRef}
|
||||
src={src}
|
||||
className="h-full w-full object-contain"
|
||||
onClick={togglePlay}
|
||||
onDoubleClick={toggleFullscreen}
|
||||
onClick={player.togglePlay}
|
||||
onDoubleClick={player.toggleFullscreen}
|
||||
onPlay={() => {
|
||||
setPlaying(true);
|
||||
showControls();
|
||||
player.setPlaying(true)
|
||||
player.showControls()
|
||||
}}
|
||||
onPause={() => {
|
||||
setPlaying(false);
|
||||
setControlsVisible(true);
|
||||
player.setPlaying(false)
|
||||
player.setControlsVisible(true)
|
||||
}}
|
||||
onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)}
|
||||
onTimeUpdate={(event) => player.setCurrentTime(event.currentTarget.currentTime)}
|
||||
onLoadedMetadata={(event) => {
|
||||
setDuration(event.currentTarget.duration);
|
||||
readBuffered();
|
||||
player.setDuration(event.currentTarget.duration)
|
||||
player.readBuffered()
|
||||
}}
|
||||
onDurationChange={(event) => setDuration(event.currentTarget.duration)}
|
||||
onProgress={readBuffered}
|
||||
onDurationChange={(event) => player.setDuration(event.currentTarget.duration)}
|
||||
onProgress={player.readBuffered}
|
||||
/>
|
||||
|
||||
<AnimatePresence>
|
||||
{controlsVisible ? (
|
||||
<motion.div
|
||||
className="absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/80 via-black/40 to-transparent px-4 pb-2.5 pt-12"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
{/* Scrubber */}
|
||||
<div
|
||||
ref={trackRef}
|
||||
className="group/track relative flex h-4 cursor-pointer items-center"
|
||||
onPointerDown={handleTrackPointerDown}
|
||||
onPointerMove={handleTrackPointerMove}
|
||||
onPointerUp={handleTrackPointerUp}
|
||||
>
|
||||
<div className="relative h-1 w-full overflow-hidden rounded-full bg-white/15 transition-[height] group-hover/track:h-1.5">
|
||||
{buffered.map((range, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="absolute inset-y-0 bg-white/20"
|
||||
style={{ left: `${range.start * 100}%`, width: `${(range.end - range.start) * 100}%` }}
|
||||
/>
|
||||
))}
|
||||
<div className="absolute inset-y-0 left-0 bg-white/90" style={{ width: `${playedFraction * 100}%` }} />
|
||||
</div>
|
||||
<div
|
||||
className="pointer-events-none absolute h-3 w-3 -translate-x-1/2 rounded-full bg-white opacity-0 shadow transition-opacity group-hover/track:opacity-100"
|
||||
style={{ left: `${playedFraction * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Control row */}
|
||||
<div className="mt-1 flex items-center gap-1.5">
|
||||
<ControlButton onClick={togglePlay} title={playing ? "Pause (Space)" : "Play (Space)"}>
|
||||
{playing ? (
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M7 5h4v14H7zM13 5h4v14h-4z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5.14v13.72L19 12 8 5.14z" />
|
||||
</svg>
|
||||
)}
|
||||
</ControlButton>
|
||||
|
||||
<span className="ml-1 text-xs tabular-nums text-gray-300">
|
||||
{formatTime(currentTime)} <span className="text-gray-500">/ {formatTime(duration)}</span>
|
||||
</span>
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
{/* Volume */}
|
||||
<ControlButton onClick={toggleMute} title={muted ? "Unmute (M)" : "Mute (M)"}>
|
||||
{effectiveVolume === 0 ? (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M17 9l4 6m0-6l-4 6" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15.536 8.464a5 5 0 010 7.072M18.364 5.636a9 9 0 010 12.728" />
|
||||
</svg>
|
||||
)}
|
||||
</ControlButton>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.02}
|
||||
value={effectiveVolume}
|
||||
className="h-1 w-20 cursor-pointer accent-white"
|
||||
onChange={(event) => applyVolume(parseFloat(event.target.value), false)}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
title="Volume (↑/↓)"
|
||||
/>
|
||||
|
||||
{/* Playback speed */}
|
||||
<div className="relative">
|
||||
<button
|
||||
className={`min-w-12 rounded-md px-2 py-1.5 text-xs tabular-nums transition-colors hover:bg-white/10 ${playbackRate !== 1 ? "text-white" : "text-gray-300 hover:text-white"}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setSpeedMenuOpen((value) => !value);
|
||||
}}
|
||||
title="Playback speed"
|
||||
>
|
||||
{playbackRate}×
|
||||
</button>
|
||||
{speedMenuOpen ? (
|
||||
<div className="absolute bottom-full right-0 z-20 mb-2 min-w-20 rounded-lg border border-white/10 bg-gray-950/95 p-1 shadow-2xl backdrop-blur">
|
||||
{SPEED_OPTIONS.map((rate) => (
|
||||
<button
|
||||
key={rate}
|
||||
className={`flex w-full items-center justify-between gap-2 rounded-md px-2.5 py-1.5 text-left text-xs tabular-nums transition-colors ${
|
||||
rate === playbackRate ? "bg-white/10 text-white" : "text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setSpeed(rate);
|
||||
}}
|
||||
>
|
||||
{rate}×
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Loop */}
|
||||
<ControlButton onClick={toggleLoop} title={loop ? "Loop on (L)" : "Loop off (L)"} active={loop}>
|
||||
<svg className={`h-4.5 w-4.5 ${loop ? "text-emerald-300" : ""}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h5M20 20v-5h-5M4 9a8 8 0 0114-3M20 15a8 8 0 01-14 3" />
|
||||
</svg>
|
||||
</ControlButton>
|
||||
|
||||
{/* Fullscreen */}
|
||||
<ControlButton onClick={toggleFullscreen} title={fullscreen ? "Exit fullscreen (F)" : "Fullscreen (F)"}>
|
||||
{fullscreen ? (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M9 9H4m5 0V4m6 5h5m-5 0V4M9 15H4m5 0v5m6-5h5m-5 0v5" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 8V4h4M20 8V4h-4M4 16v4h4M20 16v4h-4" />
|
||||
</svg>
|
||||
)}
|
||||
</ControlButton>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
<VideoControls
|
||||
applyVolume={player.applyVolume}
|
||||
buffered={player.buffered}
|
||||
controlsVisible={player.controlsVisible}
|
||||
currentTime={player.currentTime}
|
||||
duration={player.duration}
|
||||
effectiveVolume={player.effectiveVolume}
|
||||
fullscreen={player.fullscreen}
|
||||
handleTrackPointerDown={player.handleTrackPointerDown}
|
||||
handleTrackPointerMove={player.handleTrackPointerMove}
|
||||
handleTrackPointerUp={player.handleTrackPointerUp}
|
||||
loop={player.loop}
|
||||
muted={player.muted}
|
||||
playbackRate={player.playbackRate}
|
||||
playedFraction={player.playedFraction}
|
||||
playing={player.playing}
|
||||
setSpeed={player.setSpeed}
|
||||
setSpeedMenuOpen={player.setSpeedMenuOpen}
|
||||
speedMenuOpen={player.speedMenuOpen}
|
||||
toggleFullscreen={player.toggleFullscreen}
|
||||
toggleLoop={player.toggleLoop}
|
||||
toggleMute={player.toggleMute}
|
||||
togglePlay={player.togglePlay}
|
||||
trackRef={player.trackRef}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { useGalleryStore } from '../store'
|
||||
import {
|
||||
getChangelogForVersion,
|
||||
type ChangelogEntry,
|
||||
type ChangelogItem,
|
||||
type ChangelogSection,
|
||||
} from '../changelog'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { ChevronRightIcon, CloseIcon } from './icons'
|
||||
|
||||
// The modal adapts its layout to the size of the release: small releases keep
|
||||
// the compact single-column list, while big ones switch to a two-pane layout
|
||||
// with a section nav rail so no one pane is a marathon scroll. Preview both in
|
||||
// UI Lab via `?changelog=unreleased` + the demo panel's "Open What's new modal".
|
||||
type WhatsNewLayout = 'single' | 'rail'
|
||||
|
||||
// Above this many total bullets, the single column gets unpleasantly long.
|
||||
const RAIL_THRESHOLD = 20
|
||||
|
||||
function chooseLayout(entry: ChangelogEntry | null): WhatsNewLayout {
|
||||
if (!entry || entry.sections.length < 2) return 'single'
|
||||
const total = entry.sections.reduce((sum, section) => sum + section.items.length, 0)
|
||||
return total > RAIL_THRESHOLD ? 'rail' : 'single'
|
||||
}
|
||||
|
||||
// Shown in the tooltip so the user can see the link's destination before
|
||||
// clicking. The actual navigation is handled by the open_changelog_url command.
|
||||
const CHANGELOG_URL = 'https://github.com/JezzWTF/phokus/blob/main/CHANGELOG.md'
|
||||
|
||||
// Per-section accent. These all use the standard colour scale, which the
|
||||
// subtle-light theme re-maps to readable dark shades via CSS variables — so no
|
||||
// `light-theme:` overrides are needed (or wanted) here. See the theme note in
|
||||
// index.css: `bg-white`/`text-white` deliberately become *dark* in light mode,
|
||||
// so neutral surfaces must use the gray scale and trust the remap.
|
||||
const SECTION_STYLES: Record<string, { label: string; dot: string }> = {
|
||||
Added: { label: 'text-emerald-300', dot: 'bg-emerald-400/80' },
|
||||
Changed: { label: 'text-sky-300', dot: 'bg-sky-300/80' },
|
||||
Fixed: { label: 'text-amber-300', dot: 'bg-amber-400/80' },
|
||||
Removed: { label: 'text-rose-300', dot: 'bg-rose-400/80' },
|
||||
Security: { label: 'text-violet-300', dot: 'bg-violet-400/80' },
|
||||
}
|
||||
|
||||
const NEUTRAL_STYLE = { label: 'text-gray-300', dot: 'bg-gray-400/70' }
|
||||
|
||||
function sectionStyle(title: string) {
|
||||
return SECTION_STYLES[title] ?? NEUTRAL_STYLE
|
||||
}
|
||||
|
||||
// Render the small amount of inline markdown the changelog uses: **bold** and
|
||||
// `code`. Anything else passes through as plain text.
|
||||
function renderInline(text: string): ReactNode[] {
|
||||
const nodes: ReactNode[] = []
|
||||
const regex = /\*\*(.+?)\*\*|`([^`]+)`/g
|
||||
let lastIndex = 0
|
||||
let key = 0
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = regex.exec(text)) !== null) {
|
||||
if (match.index > lastIndex) {
|
||||
nodes.push(text.slice(lastIndex, match.index))
|
||||
}
|
||||
if (match[1] !== undefined) {
|
||||
nodes.push(
|
||||
<strong key={key++} className="font-semibold text-white">
|
||||
{match[1]}
|
||||
</strong>
|
||||
)
|
||||
} else if (match[2] !== undefined) {
|
||||
nodes.push(
|
||||
<code key={key++} className="rounded bg-white/10 px-1 py-0.5 text-[12px] text-gray-200">
|
||||
{match[2]}
|
||||
</code>
|
||||
)
|
||||
}
|
||||
lastIndex = regex.lastIndex
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
nodes.push(text.slice(lastIndex))
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
function Item({ item, dot }: { item: ChangelogItem; dot: string }) {
|
||||
return (
|
||||
<li className="flex gap-3">
|
||||
<span className={`mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full ${dot}`} />
|
||||
<p className="text-[13px] leading-relaxed text-gray-400">
|
||||
{item.lead ? (
|
||||
<>
|
||||
<span className="font-semibold text-gray-100">{item.lead}</span>
|
||||
{item.body ? <span> — {renderInline(item.body)}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
renderInline(item.body)
|
||||
)}
|
||||
</p>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemList({
|
||||
items,
|
||||
dot,
|
||||
className = '',
|
||||
}: {
|
||||
items: ChangelogItem[]
|
||||
dot: string
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<ul className={`space-y-2.5 ${className}`}>
|
||||
{items.map((item, index) => (
|
||||
<Item key={index} item={item} dot={dot} />
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleSection({ section }: { section: ChangelogSection }) {
|
||||
const style = sectionStyle(section.title)
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
return (
|
||||
<section>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
className="flex w-full items-center gap-2 text-left"
|
||||
aria-expanded={open}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
className={`h-3 w-3 shrink-0 text-gray-600 transition-transform ${open ? 'rotate-90' : ''}`}
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
<span className={`text-[11px] font-semibold tracking-[0.1em] uppercase ${style.label}`}>
|
||||
{section.title}
|
||||
</span>
|
||||
<span className="text-[11px] font-medium text-gray-600">{section.items.length}</span>
|
||||
</button>
|
||||
<AnimatePresence initial={false}>
|
||||
{open ? (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: 'auto', opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<ItemList items={section.items} dot={style.dot} className="mt-2.5 pl-5" />
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// 'rail' layout — a section nav rail on the left, the selected section's items
|
||||
// on the right.
|
||||
function RailSections({ sections }: { sections: ChangelogSection[] }) {
|
||||
const [active, setActive] = useState(0)
|
||||
const section = sections[Math.min(active, sections.length - 1)]
|
||||
const style = sectionStyle(section.title)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<nav className="flex w-44 shrink-0 flex-col gap-1 border-r border-white/[0.07] px-3 py-4">
|
||||
{sections.map((s, index) => {
|
||||
const navStyle = sectionStyle(s.title)
|
||||
const isActive = index === active
|
||||
return (
|
||||
<button
|
||||
key={s.title}
|
||||
type="button"
|
||||
onClick={() => setActive(index)}
|
||||
className={`flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-[12px] font-medium transition-colors ${
|
||||
isActive
|
||||
? 'bg-white/[0.07] text-white'
|
||||
: 'text-gray-500 hover:bg-white/[0.04] hover:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<span className={`h-1.5 w-1.5 shrink-0 rounded-full ${navStyle.dot}`} />
|
||||
<span className="flex-1">{s.title}</span>
|
||||
<span className="text-[11px] font-medium text-gray-600">{s.items.length}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
|
||||
<p
|
||||
className={`mb-3 text-[11px] font-semibold tracking-[0.1em] uppercase ${style.label}`}
|
||||
>
|
||||
{section.title}
|
||||
</p>
|
||||
<ItemList items={section.items} dot={style.dot} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const MODAL_WIDTHS: Record<WhatsNewLayout, string> = {
|
||||
single: 'w-[min(88vw,560px)]',
|
||||
rail: 'w-[min(90vw,780px)]',
|
||||
}
|
||||
|
||||
export function WhatsNewModal() {
|
||||
const whatsNewOpen = useGalleryStore((s) => s.whatsNewOpen)
|
||||
const closeWhatsNew = useGalleryStore((s) => s.closeWhatsNew)
|
||||
const appVersion = useGalleryStore((s) => s.appVersion)
|
||||
|
||||
const entry = getChangelogForVersion(appVersion)
|
||||
const layout = chooseLayout(entry)
|
||||
|
||||
useEffect(() => {
|
||||
if (!whatsNewOpen) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') closeWhatsNew()
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [whatsNewOpen, closeWhatsNew])
|
||||
|
||||
const hasSections = entry !== null && entry.sections.length > 0
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{whatsNewOpen ? (
|
||||
<motion.div
|
||||
className="fixed inset-0 z-[90] flex items-center justify-center bg-black/65 px-6 backdrop-blur-sm"
|
||||
onClick={closeWhatsNew}
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
<motion.div
|
||||
className={`relative flex max-h-[min(82vh,760px)] ${MODAL_WIDTHS[layout]} flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60`}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
initial={{ opacity: 0, scale: 0.97, y: 8 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
exit={{ opacity: 0, scale: 0.98, y: 6 }}
|
||||
transition={{ duration: 0.16 }}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-4 border-b border-white/[0.07] px-6 py-5">
|
||||
<div>
|
||||
<p className="text-[11px] font-semibold tracking-[0.12em] text-emerald-300 uppercase">
|
||||
What's new
|
||||
</p>
|
||||
<h3 className="mt-1 text-lg font-semibold text-white">
|
||||
Phokus v{entry?.version ?? appVersion ?? '—'}
|
||||
</h3>
|
||||
{entry?.date ? (
|
||||
<p className="mt-0.5 text-xs text-gray-600">Released {entry.date}</p>
|
||||
) : null}
|
||||
</div>
|
||||
<Tooltip label="Close" anchorToCursor>
|
||||
<button
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={closeWhatsNew}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{hasSections && layout === 'rail' ? (
|
||||
<RailSections sections={entry.sections} />
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-6 py-5">
|
||||
{hasSections ? (
|
||||
entry.sections.map((section) => (
|
||||
<CollapsibleSection key={section.title} section={section} />
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
Release notes for this version aren't available in-app. See the full changelog
|
||||
on GitHub.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-4 border-t border-white/[0.07] px-6 py-4">
|
||||
<Tooltip label={CHANGELOG_URL} side="top" align="start">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void invoke('open_changelog_url')}
|
||||
className="text-xs text-gray-500 transition-colors hover:text-gray-300"
|
||||
>
|
||||
Full changelog ↗
|
||||
</button>
|
||||
</Tooltip>
|
||||
<button
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-3.5 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25"
|
||||
onClick={closeWhatsNew}
|
||||
>
|
||||
Got it
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||