47 Commits

Author SHA1 Message Date
LyAhn 619bd0c9d2 Merge: rename 'tag cloud' to 'visual clusters' across the stack
github/actions/ci GitHub Actions CI finished: success
Disambiguate the Explore feature naming: the visual k-means cluster view was
named tag_cloud/tagCloud/TagCloud everywhere while the actual tag list is
explore_tags, which was easy to confuse. The cluster side is now
visual_cluster/visualCluster/VisualCluster (command, types, store, DB cache
table, and the ExploreView component); the tags side and the user-facing
"Tag Cloud" label are unchanged. Includes a mock-fixture fix so the dev
"huge" scenario surfaces a realistic field of clusters.
2026-06-30 10:01:25 +01:00
LyAhn 996bb71375 fix(mock): scale visual-cluster fixtures to the scenario
The mock Explore clusters were a fixed 10 regardless of scenario, so the "huge"
dev scenario looked sparse next to its large tag vocabulary. Mirror the backend's
k = (n / 20).clamp(5, 30): the huge scenario now surfaces ~30 clusters with a
long-tailed, big-library-sized count distribution, so Explore looks realistic.
2026-06-30 09:59:50 +01:00
LyAhn 0d9229635b refactor(explore): rename misnamed "tag cloud" to "visual clusters"
The visual k-means cluster feature was confusingly named tag_cloud / tagCloud /
TagCloud across the whole stack, while the actual tag list is explore_tags — the
two were trivially easy to mix up (and did cause confusion). Rename the cluster
side to visual_cluster / visualCluster / VisualCluster everywhere: command
get_tag_cloud -> get_visual_clusters (+ lib.rs registration and the invoke
string), VisualClusterEntry, the store fields/actions/tokens, and the mock
backend. Old names are retired rather than reused, so any missed reference fails
loudly instead of silently resolving to the wrong concept.

The tags side keeps its accurate explore_tags naming, and the user-facing
"Tag Cloud" UI label is unchanged.

Also rename the SQLite tag_cloud_cache table -> visual_cluster_cache (the old
table is dropped during schema setup — it is a disposable cache already
invalidated by the clustering version bump) and the TagCloud.tsx component file
-> ExploreView.tsx, since it is the Explore container hosting both the cluster
and tag views.
2026-06-30 09:48:38 +01:00
LyAhn cdb8aa20b9 Merge: faster Explore visual clustering on large libraries
Sampled, parallel k-means with density-aware k-means++ seeding makes first-time
visual clustering on large libraries fast, without a single cluster swallowing
tens of thousands of generic images. Together with the earlier cache-hit
optimization, the Explore tab no longer stalls for several seconds on 80k+
libraries.
2026-06-30 09:10:15 +01:00
LyAhn d2af84d9e8 perf(explore): sampled, parallel visual clustering for large libraries
Computing visual clusters was O(n·k·dim) per Lloyd iteration over the whole
library, single-threaded — several seconds on an 80k-image library on first
view. Find centroids on a deterministic, evenly-strided sample (<=3000
embeddings) and then assign every image to its nearest centroid in one parallel
rayon pass. Libraries at or below the sample cap are unchanged.

Replace the greedy farthest-point seeding (which seeds outliers, leaving the
dense core under-represented on a sample so one centroid absorbed tens of
thousands of generic images) with proper density-aware k-means++ D² seeding,
made deterministic via a small fixed-seed SplitMix64 PRNG. This keeps clusters
balanced on large libraries.

A CLUSTER_CACHE_VERSION is folded into the tag-cloud cache key so existing
caches computed by the old algorithm are invalidated and recomputed. The
clustering timing line and the cache-write failure now go through the `log`
facade (debug/warn) instead of eprintln.
2026-06-30 09:08:48 +01:00
LyAhn 68a9df5ab3 feat(lightbox): two-column metadata layout
github/actions/ci GitHub Actions CI finished: failure
Lay the lightbox info-panel metadata out in a two-column grid: paired fields
(Dimensions/Duration, Video codec/Audio codec, Type/File size) sit side by side
while Rating, Modified, and Embedding span the full width. More compact panel
with less scrolling. Tags and EXIF sections are unchanged.
2026-06-29 20:35:13 +01:00
LyAhn 79ce458fd5 feat(tags): open the tag manager from Settings
Add an "Open tag manager" button under a new Tag library group in Settings →
AI Workspace. It closes Settings and jumps to Explore's tag Manage mode.

To make manage mode reachable from outside the Explore view, lift its flag out
of TagCloud's local state into the store (tagManagerOpen / setTagManagerOpen)
behind an openTagManager() action. Manage mode is reset whenever Explore is
entered normally or the visual-cluster view is selected, so openTagManager()
stays the only path that opens it programmatically.
2026-06-29 20:26:49 +01:00
LyAhn a9a8f8422e feat(ui): quick theme switch from the settings cog
Right-clicking the settings cog in the title bar opens a small theme menu
(Phokus / Subtle Light / Conventional Dark) with the active theme checked,
anchored under the cog and dismissed on outside-click or Escape. Left-click
still opens Settings. Keeps theme switching one gesture away without cluttering
the title bar with another icon.
2026-06-29 20:26:08 +01:00
LyAhn ab7022e118 perf(explore): instant tag-cloud cache hits + fix stale-on-switch loading
The get_tag_cloud cache key was built by loading and hashing every embedding
blob for the scope *before* checking the cache, so even a cache hit re-read
hundreds of MB on large libraries and stalled Explore for several seconds.
Validate the cache from a lightweight image-ID-set signature plus the embedding
revision instead, so a hit never loads embeddings. The ID-set hash keeps the key
membership-sensitive (add/remove/move between folders) and the revision covers
an image being re-embedded in place. Cache write failures are now logged rather
than silently ignored.

On the frontend, switching folders (or re-entering Explore) no longer leaves the
previous folder's clusters/tags on screen with no loading indicator:
loadTagCloud/loadExploreTags clear stale entries on a real folder switch. The
displayed folder is tracked separately (exploreTagsShownFolderId) from the
cache-dirty marker so a same-folder invalidation (tag edits, new AI tags) does
not masquerade as a switch and wipe the visible list mid-refresh.
2026-06-29 20:25:38 +01:00
LyAhn 23e9850c7a Merge feat/tagging-ux: tagging model choice, related tags, tag manager, and UX polish
github/actions/ci GitHub Actions CI finished: failure
- JoyTag added as a second selectable tagger alongside WD; model switches on demand, tags attributed per-model

- Related tags atlas in Explore: clicking a tag shows co-occurring tags with animated connection lines and image counts

- Persist worker pauses across restarts via a Settings toggle

- Tag manager gains live filter, sort (most-used / least-used / A–Z / Z–A), and virtualisation for large libraries

- Tooltip portal with anchorToCursor mode for precise hover positioning

- Noisy AI tags (e.g. generic background descriptors) filtered at store time; existing tags cleaned on migration

- Fix: tag cloud hover glow and atlas gradient now adapt to Subtle Light theme

- Fix: AI Workspace 'Selected Folders' scope no longer pre-selects the first folder

- Fix: changelog version lookup strips build suffixes so What's New works in UI Lab
2026-06-29 18:36:01 +01:00
LyAhn c111032d99 fix(changelog): strip build suffixes before version lookup
UI-lab builds append a suffix to the version string (e.g.
"0.1.1-ui") which caused getChangelogForVersion to find no match and
fall back to the "not available in-app" message. A regex now strips any
hyphen-and-letter suffix before the lookup so the What's New modal
renders correctly in all build modes.
2026-06-29 18:06:45 +01:00
LyAhn c13f78c68b docs(changelog): add unreleased entries for feat/tagging-ux
Adds the user-facing changes introduced on this branch that were missing
from the [Unreleased] section:

Added:
- Related tags in Explore (tag atlas connection lines + co-occurrence counts)
- Persist worker pauses across restarts (Settings toggle)

Changed:
- Tag manager search/sort/virtualisation

Fixed:
- Noisy AI tags filtered automatically (removal list applied at store time)
- Explore Tag Cloud hover glow and atlas gradient in Subtle Light theme
- AI Workspace "Selected Folders" scope no longer pre-selects a folder
2026-06-29 17:23:20 +01:00
LyAhn f2939d70ab fix: atlas glow and AI Workspace scope pre-selection in light theme
Two targeted fixes:

- Tag Cloud atlas SVG radial gradient now switches its inner stop from white
  to a warm dark tone (rgba 60 50 30) when the Subtle Light theme is active,
  matching the explore-tag hover glow style used elsewhere in light mode.
- Switching the AI Workspace tagging queue scope to "Selected Folders" no
  longer auto-selects the first folder in the list; the selection now starts
  empty so the user can choose exactly which folders to target.
2026-06-29 17:23:03 +01:00
LyAhn 8dbabc2d9e fix: match tag cloud hover glow to dark mode in light theme
Replace the flat background hover override with a dark warm radial
gradient on the ::before pseudo-element, mirroring the same elliptical
glow effect used in dark mode.
2026-06-29 17:06:50 +01:00
LyAhn 5bc397af01 chore: add Playwright test scaffolding
Adds @playwright/test and @types/node as dev dependencies, playwright.config.ts
with a localhost:1420 base URL targeting the Vite dev server, an example
spec, and the standard Playwright output directories to .gitignore.
2026-06-29 16:30:05 +01:00
LyAhn af3c8418ee feat: virtualized tag manager with filter, sort, and light-theme support
Replaces the flat TagManageRow list with a virtualized grid of
TagManageTile cards using @tanstack/react-virtual and dynamic measured
heights (46px idle, 82px when editing/confirming). Adds a filter input
and a sort dropdown (most-used / least-used / A-Z / Z-A). renameTag and
deleteTag no longer clear exploreTagEntries on invalidation so the
manager keeps its filter/sort state during the background refresh.
Light-theme overrides cover all new tag-manager class names.
2026-06-29 16:29:12 +01:00
LyAhn 9144be2518 feat: Tooltip portal with anchorToCursor mode
Tooltip now portals cursor-anchored variants into document.body via a
`mounted` guard, preventing transformed parents and scroll-container
overflow from distorting coordinates. New `anchorToCursor` prop locks
position at hover entry without tracking; `followCursor` retains the
spring-animated tracking behaviour. Color swatches (ColorFilter),
timeline scrubber dots/labels (Timeline), and toolbar dropdowns (Toolbar)
are updated to use the appropriate cursor mode. Toolbar z-index bumped
z-20→z-40 (dropdowns z-30→z-50) to layer above portaled content; tag
autocomplete result guard added (Array.isArray).
2026-06-29 16:28:35 +01:00
LyAhn d81624573d feat: persist worker-pause state across restarts
Worker pause states can optionally survive app restarts. A new toggle in
Settings saves the current pause map to settings/worker_pauses.json; on
startup lib.rs restores it before workers are spawned. Backend: new
snapshot/replace helpers in indexer.rs, persist functions in commands.rs
(get/set_worker_pauses_persist). Frontend: workerPausesPersist store
field, load/setWorkerPausesPersist actions, toggle in SettingsModal.
2026-06-29 13:21:53 +01:00
LyAhn 949382f28c feat: related-tags atlas in Explore view
Hovering a tag in Explore now loads and displays co-occurring tags as a
weighted cloud. New `get_related_tags` SQL self-join (db.rs/commands.rs),
`loadRelatedTags` store action with per-folder keyed cache, and TagCloud
atlas UI with ResizeObserver-driven layout and RAF animation. Explore tag
limit raised to 180; tag cloud auto-refreshes 700ms after new AI tagging
completes.
2026-06-29 13:21:43 +01:00
LyAhn e4a63c8bb0 fix: filter noisy AI tags
Add an editable AI tag removal list and apply it to WD/JoyTag output before tags are stored. Clean existing generated AI tags during database migration while leaving manual user tags untouched.
2026-06-29 11:24:21 +01:00
LyAhn 1685134116 fix(tagger): model-neutral session log; changelog for JoyTag
create_tagger_session is shared by both models but logged "WD tagger: using
CPU execution provider" even when loading JoyTag. Make the CPU/DirectML
session logs model-neutral. Add the JoyTag tagging-model picker to the
changelog now that it's runtime-verified.
2026-06-29 10:26:51 +01:00
LyAhn 705f8c2e56 feat(tagger): Settings picker to switch tagging model (WD / JoyTag)
Adds a "Tagging model" control to Settings → AI Workspace that calls
get/set_tagger_model, alongside the existing acceleration/threshold/batch
controls. Switching refreshes the model status so the download/ready row and
the model name/description reflect the selected model, and the threshold hint
shows the model-appropriate default (0.4 for JoyTag, 0.35 for WD).

Frontend only; mirrors the existing acceleration toggle pattern. End-to-end
JoyTag tagging still needs the model files on disk to verify.
2026-06-29 09:51:30 +01:00
LyAhn 52d54d2404 feat(tagger): add JoyTag provider behind a tagger-model abstraction
Introduces a selectable tagging model so Phokus isn't locked to the
anime-leaning WD tagger. JoyTag uses the Danbooru schema but generalizes to
photographic content and is strong on NSFW concepts — a better fit for a photo
manager while keeping the explicitness range.

- `TaggerModel` enum (wd | joytag) persisted as a `tagger_model` setting;
  `model_dir`, status, and download now follow the active model (per-model
  repo/dir/file list). WD stays the default.
- `Tagger` trait implemented by `WdTagger` and the new `JoyTagger`;
  `create_active_tagger` builds the selected one. The worker holds
  `Box<dyn Tagger>` and rebuilds on model change (TAGGER_SESSION_DIRTY).
- Shared `assemble_batch` skeleton (pack -> one forward pass -> per-image
  fallback, results in input order); both providers and the shared
  decode/pad/resize are de-duped onto common helpers.
- JoyTag specifics: NCHW + RGB + CLIP-normalized input (vs WD's NHWC/BGR/raw),
  flat top_tags.txt labels, logits -> sigmoid -> threshold (default 0.4). It has
  no native rating, so the explicitness rating is derived from its NSFW tags.
- Tags are attributed to the model that produced them (ai_tagger_model),
  via Tagger::model_name, instead of a hardcoded WD constant.
- New get/set_tagger_model commands.

Backend only; the Settings model picker and end-to-end testing against the
JoyTag model files come next.
2026-06-29 09:40:12 +01:00
LyAhn 3a2b134103 Merge perf/tagging: faster, non-freezing AI tagging
github/actions/ci GitHub Actions CI finished: success
Tagging inference no longer monopolises the GPU. It now runs in small
chunked forward passes with a brief yield between them, so a tagging run
keeps the UI responsive instead of freezing the whole app for seconds at a
time — worst on first launch with a cold batch. Throughput is also steadier
(the old wide batches caused periodic slowdowns).

CPU-provider tagging is multi-threaded instead of pinned to a single core
(~2.7x faster on a representative machine), leaving headroom so the rest of
the app stays responsive. DirectML/GPU tagging behaviour is unchanged.
2026-06-29 09:19:40 +01:00
LyAhn 71ad7bf762 perf(tagger): multi-thread CPU inference instead of pinning to one core
The ONNX session was built with intra_threads(1) unconditionally. That's
correct for DirectML (compute is on the GPU), but on the CPU execution
provider it pinned all matmul/conv work to a single core — ~1.78s/image,
~14s for an 8-image batch.

Derive the intra-op thread count from available_parallelism() for the CPU EP
(leaving 2 logical cores free for the UI and a possible concurrent scan;
tagging is the lowest-priority worker, so heavier workers are idle when it
runs). DirectML/Auto keep a single thread. Measured ~2.7x on a representative
machine (14s -> 5.3s per 8-image batch); sublinear because swinv2 inference is
memory-bandwidth-bound. The selected thread count is logged at load.
2026-06-29 09:09:29 +01:00
LyAhn 992417710f perf(tagger): chunked, yielding inference so tagging stops freezing the UI
The tagging worker claimed a batch from the DB but ran the model one image
at a time, so `tagger_batch_size` had no effect on inference. Batching the
whole claim into a single DirectML forward pass fixed that but introduced a
worse problem: on a shared GPU each wide dispatch locks the device (and the
WebView2 compositor with it) for 1-3.7s, freezing the entire app while
tagging runs — worst of all on first launch with a cold graph compile.

The WD model is compute-bound here (~50-230ms/image of actual GPU work), so
a wide batch buys almost no throughput; it only lengthens each uninterruptible
GPU lock. So decouple DB claim size from GPU granularity: claim
`tagger_batch_size` for DB efficiency, but feed the GPU in TAGGER_INFER_CHUNK
(4) images per forward pass with a brief yield between chunks. Each dispatch
now lasts ~200-900ms, the UI gets windows to paint, peak decode memory is
bounded, and the cold compile is for a smaller shape. As a bonus the wide-batch
throughput spikes disappear — steady ~1.6-1.8s/16 vs the old 0.8-3.7s swings.

- run_batch: parallel (rayon) decode + single forward pass per chunk, with
  per-image fallback and decode failures kept attached to their input slot.
- Worker iterates source_paths.chunks(TAGGER_INFER_CHUNK), yielding 40ms
  between chunks; outputs zip back to jobs 1:1, write tx unchanged.
- Remove now-dead WdTagger::run() (fallback uses infer_one directly).
2026-06-29 01:09:47 +01:00
LyAhn 4c6da99507 Merge feat/ui-lab: Add browser-only UI Lab
github/actions/ci GitHub Actions CI finished: success
- Adds a Vite UI Lab mode that boots the real Phokus frontend with mocked
  Tauri APIs.
- Introduces deterministic mock backend scenarios for rich, empty, busy,
  duplicate, album, error, and large-library states.
- Adds fixture media plus a mediaSrc helper so browser previews and Tauri file
  URLs share one rendering path.
- Documents the UI Lab workflow and exposes it through pnpm dev:ui.
2026-06-29 00:12:51 +01:00
LyAhn 24d4e82950 feat: expand UI Lab media fixtures
Add a derived dev-media fixture pack and wire UI Lab scenarios to use the broader image set for more useful browser screenshots.
2026-06-29 00:06:58 +01:00
LyAhn 7a18011b0f feat: add Phokus UI Lab
Add a dev-only Vite UI mode with Tauri API mocks, in-memory fixture scenarios, reusable media source handling, and documentation for browser-based visual testing.
2026-06-29 00:04:48 +01:00
LyAhn cebd709391 fix: anchor cluster Open pill to corner so it stays on small cards
github/actions/ci GitHub Actions CI finished: success
2026-06-28 21:19:32 +01:00
LyAhn d55e4c7502 docs: changelog for unreleased fixes
github/actions/ci GitHub Actions CI finished: success
2026-06-28 21:13:12 +01:00
LyAhn a40a2e8d12 chore: split production build into CPU and CUDA scripts 2026-06-28 21:13:12 +01:00
LyAhn 2ce1547844 fix: improve Explore cluster layout and light-theme readability 2026-06-28 21:12:26 +01:00
LyAhn 623aabbb51 fix: surface actively-processing folder over paused one in background tasks bar 2026-06-28 21:12:24 +01:00
LyAhn f65fd350cc fix: make toolbar, sidebar, and lightbox responsive on small screens 2026-06-28 21:12:22 +01:00
LyAhn 86a1a53289 fix: clamp window to monitor work area so it fits small screens on first launch 2026-06-28 21:12:21 +01:00
LyAhn ebf16e8cb9 fix: skip Phokus's own app-data dir when indexing to break self-indexing loop 2026-06-28 21:12:21 +01:00
LyAhn e7d9c39fd1 docs: regroup unreleased changelog Added entries
github/actions/ci GitHub Actions CI finished: success
2026-06-28 14:56:00 +01:00
LyAhn 136d74a81b Merge feat/smart-albums-multiselect: albums, multi-select, EXIF, tag management, color search
- Manual albums (create/rename/delete/reorder; multi-select bulk add/remove) in a distinct sidebar section
- Gallery multi-select + bulk actions (tag, rate, favorite, add-to-album, delete with disk-delete confirmation)
- Lightbox EXIF/camera panel (on-demand) with a GPS map link
- Tag management in Explore (rename/merge/delete, library-wide)
- Album-scoped similar-image search
- Color search — filter the gallery by dominant color (swatches + custom picker), with background backfill
- Reusable tooltip component, duplicate-finder delete confirmation, CPU/CUDA build badge
- Post-review security/accessibility hardening (validated URL-open commands, etc.)
2026-06-28 14:45:31 +01:00
LyAhn bb0038e0a1 chore: post-review hardening + changelog link tooltip
Security / robustness / a11y polish on top of the color-search + tooltips work:

- URL opening: route through validated backend commands (open_map_location
  with lat/lon bounds-checking, open_changelog_url with a fixed URL) instead
  of the frontend opener:allow-open-url capability, which is now removed.
- EXIF GPS parsing: validate coordinate ranges and require the correct
  N/S/E/W hemisphere ref byte, then clamp.
- Guard double-submit on album create / add-to-album (Lightbox, BulkActionBar,
  Sidebar) and discard stale autocomplete responses in the bulk tag editor.
- Gallery tile: stop nesting <button>s — non-interactive tile div with an
  overlay button for open/toggle; checkbox and Similar promoted with z-index
  + focus rings.
- Accessibility: keyboard handlers, focus-visible rings, and aria on album
  rows, tag-manage actions, and tile controls; Tooltip uses a block <div>
  wrapper in block mode and aria-hidden when hidden.
- Show the destination URL in a tooltip on the "Full changelog" link so the
  user can see where it goes before clicking.
- Toolbar "All" filter also clears the color filter; color-filtered views no
  longer get unfiltered newly-indexed images injected.
- Sidebar reorder: bail if the album set changed mid-drag.
- Tooling: add cargo fmt scripts; alphabetize package.json scripts.
2026-06-28 14:39:21 +01:00
LyAhn 90dec3b212 feat: add color search and reusable tooltips
Add dominant-color palette extraction, storage, filtering, and startup backfill so the gallery and Timeline can be filtered from the toolbar color picker.

Introduce a reusable tooltip component and migrate the color filter, update indicator, and gallery filename hover affordances to it.
2026-06-28 11:04:33 +01:00
LyAhn e3fde46e91 feat: add album scope for similar image search
Similar search scoping:
- Add current_album as a similar-scope option and remember the source album when similar or region searches are launched from an album.
- Route gallery and lightbox similar actions through scope-aware store helpers so Album/Folder/All choices are applied consistently.
- Keep pagination and scope toggles working for both whole-image and region-search result sets.

Backend filtering:
- Extend find_similar_images and find_similar_by_region params with album_id, giving album scope precedence over folder scope.
- Add album_membership filtering for HNSW whole-image search and brute-force crop embedding search.
2026-06-28 01:21:31 +01:00
LyAhn a12e81d8bd feat: lightbox EXIF panel, tag management, reorderable albums
EXIF info panel:
- New on-demand get_image_exif command (kamadak-exif) returning camera/lens/
  aperture/shutter/ISO/focal-length and decimal GPS; read from the file when the
  lightbox opens (no DB schema change, works on already-indexed images).
- Lightbox shows a Camera panel; GPS opens the location in the browser via
  OpenStreetMap (adds opener:allow-open-url capability).

Tag management:
- Backend rename_tag (rename, or merge when the target exists) and delete_tag
  (library-wide), both clearing the tag-cloud cache; store actions invalidate
  tag caches, refresh Explore, and re-point/refresh an active tag-search.
- Explore -> Tag Cloud gains a Manage mode: a flat list with per-tag rename/
  merge/delete.

Albums:
- Drag-to-reorder in the sidebar via framer-motion Reorder with a hover handle;
  order persists through the existing reorder_albums command.

Reads live store order on drag end and robustly derives GPS hemisphere from raw
EXIF ref bytes (review follow-ups). CHANGELOG updated.
2026-06-27 23:50:44 +01:00
LyAhn 6bef90b7fb feat: manual albums + gallery multi-select with bulk actions
Albums (manual collections):
- New albums/album_images tables with FK cascades; DB functions and Tauri
  commands for create/rename/delete/delete-many/reorder/list, add/remove
  images, and paginated get_album_images.
- Distinct sidebar "ALBUMS" section with cover thumbnails, create/rename/
  delete, and a Manage multi-select mode for bulk album deletion.
- Album view reuses the gallery grid (activeView "album" + selectedAlbumId);
  spans folders; add from the bulk bar or the lightbox, remove from within.

Gallery multi-select + bulk actions:
- gallerySelectedIds selection model with a top-left corner checkbox that
  reveals on corner hover; click-to-toggle in selection mode, double-click
  to open.
- Floating BulkActionBar: tag (inline autocomplete popover), rating,
  favorite, add-to-album, and a delete with an explicit "from disk"
  confirmation. Batch commands bulk_update_details/bulk_add_tags/
  bulk_remove_tag.

Also:
- Duplicate Finder delete now requires confirmation with clear "from disk"
  wording (was single-click fire-and-forget).
- CPU/CUDA build-variant badge in Settings (get_build_variant).
- Rating/favorite no longer re-sorts derived collections (similar/region/
  semantic/tag/album results); single and bulk paths replace in place there.
- Album-aware indexed-images/media-updated handlers so thumbnails paint and
  newly-indexed files don't leak into an album view.
- CHANGELOG updated.
2026-06-27 15:23:54 +01:00
LyAhn 55cd3b5aa7 Merge feat/whats-new-updater-ux: What's New screen + updater UX + light-theme fixes
github/actions/ci GitHub Actions CI finished: success
Post-0.1.1 polish queued for the next release (0.1.2):

- What's New: post-update toast that opens an in-app, offline release-notes
  screen (collapsible Added/Changed/Fixed sections) sourced from the bundled
  CHANGELOG.md, reopenable from Settings -> Updates. Backed by a
  last_seen_version settings file that tells upgrades from fresh installs.
- Updater: the progress toast reappears when an update is started from the
  title-bar indicator or Settings after the prompt was dismissed; Settings
  gains a real download progress bar with a percentage.
- Light theme: fix the recurring subtle-light breakage — neutral surfaces rely
  on the CSS-variable remap instead of light-theme:bg-white, and the green
  action buttons drop the broken light-theme:hover:bg-emerald-200 for an
  override-free emerald tint that auto-themes (updater, What's New, onboarding).
- Debug panel: What's New triggers.
2026-06-23 21:36:35 +01:00
LyAhn c878970180 feat: What's New screen + updater progress, plus light-theme fixes
Post-update UX for the next release (0.1.2):

- What's New: after a version change, greet the user with a toast that opens
  an in-app release-notes screen (collapsible Added/Changed/Fixed sections)
  sourced from the bundled CHANGELOG.md, reopenable from Settings -> Updates.
  Backed by a last_seen_version settings file (get/set_last_seen_version
  commands) that distinguishes upgrades from fresh installs.
- Updater: the download/install progress toast now reappears when an update is
  started from the title-bar indicator or Settings after the prompt was
  dismissed; Settings -> Updates gains a real progress bar with a percentage.
- Light theme: fix the recurring subtle-light breakage. Neutral surfaces now
  rely on the CSS-variable remap instead of light-theme:bg-white (which forced
  surfaces dark because --color-white is remapped dark); the green action
  buttons drop the broken light-theme:hover:bg-emerald-200 (remapped dark,
  unreadable on hover) for an override-free emerald-500 tint that auto-themes,
  across the updater, What's New, and onboarding.
- Debug panel: add What's New triggers (toast / modal / reset).
2026-06-23 21:33:08 +01:00
LyAhn 1a95e31f78 docs: fill in 0.1.1 release checksums
Add the SHA-256s for the published CPU and CUDA installers to the
0.1.1 release-notes draft.
2026-06-23 20:26:25 +01:00
105 changed files with 8122 additions and 857 deletions
+8 -1
View File
@@ -35,5 +35,12 @@ dist-ssr
*.pyc *.pyc
# Bundled CUDA runtime DLLs for the CUDA build (copied from the toolkit # 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/ src-tauri/cuda-redist/
# Playwright
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
/playwright/.auth/
+152
View File
@@ -5,6 +5,158 @@ 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) aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
(0.x: anything may change between minor versions). (0.x: anything may change between minor versions).
## [Unreleased]
### Added
- **Quick theme switch** — right-click the settings cog in the title bar to
switch theme (Phokus / Subtle Light / Conventional Dark) on the spot, without
opening Settings.
- **Albums** — curate your own collections. A new Albums section in the sidebar
(with cover thumbnails, kept visually distinct from Libraries) lets you create,
rename, reorder (drag the row), and open albums; albums can span multiple
folders. Add images from the gallery's bulk action bar or from the lightbox,
remove them from within an album, and use Manage mode to multi-select and
delete albums in one go. Deleting an album never touches your files — only the
grouping is removed.
- **Multi-select & bulk actions in the gallery** — hover a thumbnail's top-left
corner to reveal a selection checkbox (click it to start selecting); while
selecting, click tiles to toggle and double-click to open. A floating action
bar then lets you tag (with autocomplete), rate, favorite, add to an album, or
delete the whole selection at once. Works in similar-image, region, and album
views too.
- **Colour search** — filter the gallery (and Timeline) by dominant colour via a
collapsible swatch palette plus a custom colour picker in the toolbar; existing
libraries are backfilled automatically in the background.
- **Album-scoped similar search** — when finding visually similar images or
searching by a selected region from an album, you can now keep results scoped
to that album, switch back to the source folder, or search all media.
- **Tag management** — Explore → Tag Cloud gains a Manage mode with a flat tag
list where you can rename a tag, merge it into another (rename it to an
existing tag's name), or delete it from every image. Changes apply across the
whole library. Settings → AI Workspace also has an "Open tag manager" button
that jumps straight into it.
- **Camera info in the lightbox** — the image info panel now shows EXIF details
(camera, lens, aperture, shutter, ISO, focal length) and, when a photo is
geotagged, its GPS coordinates as a link that opens the location in your
browser. Read on demand from the file, so it works on already-indexed images
without re-indexing.
- **What's New** — after updating, Phokus now greets you with a "What's new"
toast that opens an in-app release-notes screen for the new version, with the
changes grouped into collapsible Added / Changed / Fixed sections.
- **Build badge in Settings** — the version line in Settings → Updates now shows
whether the running build is the CPU or CUDA (GPU-accelerated) variant.
- **Choose your tagging model** — Settings → AI Workspace now lets you switch the
AI tagger between the WD tagger (anime-focused) and **JoyTag**, which also
handles photographic content and is stronger on NSFW concepts — a better fit
for real-photo libraries. Each model downloads on demand, and tags are
attributed to the model that produced them. JoyTag has no built-in rating, so
its explicitness rating is derived from its tags.
- **Related tags in Explore** — clicking a tag in the Tag Cloud atlas now reveals
its most co-occurring tags with animated connection lines and per-tag image
counts, so you can quickly see how tags cluster together and jump to a refined
search.
- **Persist worker pauses across restarts** — a new toggle in Settings → General
lets you save per-folder worker pause states so they survive an app restart;
useful when you want a folder permanently excluded from background processing
without having to re-pause it every launch.
### Changed
- **Two-column lightbox details** — the image info panel now lays metadata out in
two columns (Dimensions/Duration, Video codec/Audio codec, Type/File size sit
side by side), so the panel is more compact and less scrolling.
- **Faster Explore on large libraries** — revisiting a folder's visual clusters
is now near-instant. The cluster cache is validated from a lightweight
image-ID signature instead of re-reading every embedding, so big libraries no
longer stall for several seconds even when the cached result is reused.
- **Faster first-time visual clustering** — computing clusters for a large
library is now much quicker: centroids are found on a representative sample and
every image is then assigned across all CPU cores, instead of iterating over
the whole library single-threaded. Density-aware seeding keeps the groupings
balanced, so no single cluster swallows a huge share of images.
- **Tag manager search and sort** — the Manage mode tag list now has a live
filter input and a sort dropdown (most-used / least-used / AZ / ZA). The
list is virtualised so libraries with thousands of tags scroll without lag,
and renaming or deleting a tag no longer clears the current filter/sort state
mid-edit.
- **Safer deletion** — deleting media now asks for confirmation and spells out
that it permanently removes the file(s) from disk. This covers the new gallery
bulk delete and the Duplicate Finder, which previously deleted on a single
click with no confirmation or warning.
- The updater now shows a real download progress bar with a percentage in
Settings → Updates (previously it only said "Downloading").
- **Smaller-screen layout** — the toolbar adapts on narrow windows: the filter
chips scroll horizontally instead of squashing (so "Similar: Folder/All" no
longer stack), the search box shrinks, and the colour-search swatches now open
in a compact popover rather than expanding inline and running off-screen. The
sidebar and the lightbox info panel also narrow to give the gallery more room.
- **Explore cluster layout** — clusters are now sized by image count (busier
clusters are larger and stack on top) and repositioned to avoid overlapping, so
every cluster stays viewable and clickable even in dense libraries.
- **Faster CPU tagging** — when AI tagging runs on the CPU provider (no usable
GPU) it now uses multiple cores instead of being pinned to one, several times
faster on multi-core machines. A couple of cores are left free so the rest of
the app stays responsive. GPU (DirectML) tagging is unchanged.
### Fixed
- **Stale Explore results on folder switch** — switching folders (or re-entering
Explore) no longer briefly shows the previous folder's clusters/tags with no
loading indicator; the view now clears and shows a loading state until the new
folder's data arrives.
- **Rating no longer scrambles search results** — rating or favoriting an image
while viewing similar-image, region, semantic, tag, or album results no longer
re-sorts the view back into the default order; the current result ordering is
preserved.
- The update download/install progress toast now reappears when you start an
update from the title-bar indicator or Settings after dismissing the earlier
"Update available" prompt — previously progress only showed in Settings.
- Subtle Light theme — fixed several surfaces and buttons that stayed dark or
became unreadable on hover, including new dialogs and the green action buttons
across the updater and onboarding.
- **Endless self-indexing loop** — adding a folder that contains Phokus's own
app-data directory (for example, your whole user profile) no longer makes the
app index its own thumbnail cache, generate thumbnails of those thumbnails, and
loop forever. That directory is now skipped by both the folder scanner and the
filesystem watcher.
- **Background tasks now lead with the active folder** — when one folder's
workers are paused while another is actively processing, the active folder
takes the main slot in the background-tasks bar instead of the paused one.
- **Oversized window on smaller screens** — on a fresh install the window opened
at a fixed size that was taller than the usable area on displays like
1366×768, leaving part of it off-screen. It now clamps to the monitor's work
area (excluding the taskbar) and centres there when it would overflow; larger
displays and any remembered size/position are left untouched.
- **Explore readability in Subtle Light** — fixed washed-out and unreadable
elements in the Explore view on the light theme. Cluster cards now use a soft
dark caption scrim (the previous cream overlay fogged the photos), with a
legible label, count, and "Open" button; Tag Cloud words use darker accents and
a higher opacity floor instead of near-invisible pale text.
- **Explore polish** — the Tag Cloud now uses the in-app tooltip instead of the
native browser one (and reads "1 image", not "1 images"), and the folder-scope
dropdown no longer opens behind the cluster cards.
- **AI tagging no longer freezes the app** — tagging now runs inference in small
GPU micro-batches with a brief yield between them, instead of one wide batch
that monopolised the GPU (and with it the whole UI) for seconds at a time. The
app stays responsive while tagging runs, throughput is steadier (the old wide
batches caused periodic slowdowns), and the first batch after launch starts
faster.
- **Noisy AI tags filtered automatically** — a built-in removal list strips
generic or low-signal tags (e.g. "simple background") from WD and JoyTag
output before they are stored. Previously-generated tags matching the list are
cleaned up at startup. Manual user-added tags are never touched.
- **Explore Tag Cloud hover glow in Subtle Light** — the radial glow that
appears under a tag word on hover was invisible on the light background
(white on cream). It now uses a warm dark tone matching the rest of the
light-theme palette, and the atlas connection-line gradient adapts to the
theme as well.
- **AI Workspace "Selected Folders" no longer pre-selects a folder** — switching
the tagging queue scope to "Selected Folders" previously auto-selected the
first folder in the list. It now starts with nothing selected so you can
choose exactly which folders to target.
## [0.1.1] — 2026-06-23 ## [0.1.1] — 2026-06-23
### Added ### Added
+5 -2
View File
@@ -15,8 +15,11 @@ pnpm dev:app
# Frontend only (no Tauri window) # Frontend only (no Tauri window)
pnpm dev:vite pnpm dev:vite
# Production build # Production build (CPU)
pnpm build:app pnpm build:app:cpu
# Production build (CUDA / GPU-accelerated)
pnpm build:app:cuda
# Type-check frontend # Type-check frontend
pnpm build:vite pnpm build:vite
+11 -2
View File
@@ -109,13 +109,22 @@ pnpm dev:app
# Frontend only # Frontend only
pnpm dev:vite pnpm dev:vite
# Production build # Browser-only UI Lab with mocked Tauri APIs
pnpm build:app pnpm dev:ui
# Production build (CPU)
pnpm build:app:cpu
# Production build (CUDA / GPU-accelerated)
pnpm build:app:cuda
# Type-check the frontend # Type-check the frontend
pnpm build:vite 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 ## How it works
1. Add a folder from the sidebar — the Rust indexer walks it recursively. 1. Add a folder from the sidebar — the Rust indexer walks it recursively.
+2 -2
View File
@@ -59,6 +59,6 @@ for the full list.
## Checksums ## Checksums
``` ```
SHA-256 (Phokus_0.1.1_x64-setup.exe) = <fill in> SHA-256 (Phokus_0.1.1_x64-setup.exe) = 1c19cbeb77f38a44149380c42c76b633add65777d317e1f3ff7e45d96d12d287
SHA-256 (Phokus_0.1.1_x64-cuda-setup.exe) = <fill in> SHA-256 (Phokus_0.1.1_x64-cuda-setup.exe) = a7337ef5ee0478a785b48acc8012e8fc5c957341161d6103409213ad78eb845f
``` ```
+182
View File
@@ -0,0 +1,182 @@
# 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` | First-run state with no folders or media |
| `/?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
```
## 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
```
+9 -5
View File
@@ -5,17 +5,19 @@
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
"scripts": { "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:vite": "tsc && vite build",
"build:web": "cd website && tsc && vite build", "build:web": "cd website && tsc && vite build",
"changelog:add": "node tools/changelog-add.mjs",
"clean:app": "cd src-tauri && cargo clean", "clean:app": "cd src-tauri && cargo clean",
"dev:app": "tauri dev", "dev:app": "tauri dev",
"dev:app:cpu": "tauri dev -- --no-default-features", "dev:app:cpu": "tauri dev -- --no-default-features",
"dev:web": "cd website && pnpm dev", "dev:ui": "vite --mode ui --host 127.0.0.1 --port 1422 --strictPort --open",
"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:vite": "vite", "dev:vite": "vite",
"dev:web": "cd website && pnpm dev",
"format:app": "cd src-tauri && cargo fmt",
"format:check": "cd src-tauri && cargo fmt --check",
"preview": "vite preview", "preview": "vite preview",
"tauri": "tauri" "tauri": "tauri"
}, },
@@ -35,9 +37,11 @@
"zustand": "^5.0.12" "zustand": "^5.0.12"
}, },
"devDependencies": { "devDependencies": {
"@playwright/test": "^1.61.1",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.2.2",
"@tauri-apps/cli": "^2", "@tauri-apps/cli": "^2",
"@types/d3-force": "^3.0.10", "@types/d3-force": "^3.0.10",
"@types/node": "^26.0.1",
"@types/react": "^19.1.8", "@types/react": "^19.1.8",
"@types/react-dom": "^19.1.6", "@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.6.0", "@vitejs/plugin-react": "^4.6.0",
+79
View File
@@ -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,
// },
});
+68 -14
View File
@@ -48,15 +48,21 @@ importers:
specifier: ^5.0.12 specifier: ^5.0.12
version: 5.0.12(@types/react@19.2.14)(react@19.2.4) version: 5.0.12(@types/react@19.2.14)(react@19.2.4)
devDependencies: devDependencies:
'@playwright/test':
specifier: ^1.61.1
version: 1.61.1
'@tailwindcss/vite': '@tailwindcss/vite':
specifier: ^4.2.2 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': '@tauri-apps/cli':
specifier: ^2 specifier: ^2
version: 2.10.1 version: 2.10.1
'@types/d3-force': '@types/d3-force':
specifier: ^3.0.10 specifier: ^3.0.10
version: 3.0.10 version: 3.0.10
'@types/node':
specifier: ^26.0.1
version: 26.0.1
'@types/react': '@types/react':
specifier: ^19.1.8 specifier: ^19.1.8
version: 19.2.14 version: 19.2.14
@@ -65,7 +71,7 @@ importers:
version: 19.2.3(@types/react@19.2.14) version: 19.2.3(@types/react@19.2.14)
'@vitejs/plugin-react': '@vitejs/plugin-react':
specifier: ^4.6.0 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: tailwindcss:
specifier: ^4.2.2 specifier: ^4.2.2
version: 4.2.2 version: 4.2.2
@@ -74,7 +80,7 @@ importers:
version: 5.8.3 version: 5.8.3
vite: vite:
specifier: ^7.0.4 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: website:
dependencies: dependencies:
@@ -96,7 +102,7 @@ importers:
devDependencies: devDependencies:
'@tailwindcss/vite': '@tailwindcss/vite':
specifier: ^4.2.2 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': '@types/react':
specifier: ^19.1.8 specifier: ^19.1.8
version: 19.2.14 version: 19.2.14
@@ -105,7 +111,7 @@ importers:
version: 19.2.3(@types/react@19.2.14) version: 19.2.3(@types/react@19.2.14)
'@vitejs/plugin-react': '@vitejs/plugin-react':
specifier: ^4.6.0 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: tailwindcss:
specifier: ^4.2.2 specifier: ^4.2.2
version: 4.2.2 version: 4.2.2
@@ -114,10 +120,10 @@ importers:
version: 5.8.3 version: 5.8.3
vite: vite:
specifier: ^7.0.4 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: vite-imagetools:
specifier: ^10.0.0 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: packages:
@@ -538,6 +544,11 @@ packages:
'@jridgewell/trace-mapping@0.3.31': '@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} 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': '@rolldown/pluginutils@1.0.0-beta.27':
resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==}
@@ -906,6 +917,9 @@ packages:
'@types/estree@1.0.8': '@types/estree@1.0.8':
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
'@types/node@26.0.1':
resolution: {integrity: sha512-fc3KiUoBt6kie0N9bIW3E47vZsuaMf0PM2AaUpLCLT0s/LvX1nxAim6Fc049cNxODPpGm6qRAuUOB86SkRuPQw==}
'@types/react-dom@19.2.3': '@types/react-dom@19.2.3':
resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==} resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}
peerDependencies: peerDependencies:
@@ -1010,6 +1024,11 @@ packages:
react-dom: react-dom:
optional: true 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: fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -1147,6 +1166,16 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'} 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: postcss@8.5.8:
resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==} resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==}
engines: {node: ^10 || ^12 || >=14} engines: {node: ^10 || ^12 || >=14}
@@ -1208,6 +1237,9 @@ packages:
engines: {node: '>=14.17'} engines: {node: '>=14.17'}
hasBin: true hasBin: true
undici-types@8.3.0:
resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==}
update-browserslist-db@1.2.3: update-browserslist-db@1.2.3:
resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
hasBin: true hasBin: true
@@ -1597,6 +1629,10 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2 '@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5 '@jridgewell/sourcemap-codec': 1.5.5
'@playwright/test@1.61.1':
dependencies:
playwright: 1.61.1
'@rolldown/pluginutils@1.0.0-beta.27': {} '@rolldown/pluginutils@1.0.0-beta.27': {}
'@rollup/pluginutils@5.4.0(rollup@4.60.1)': '@rollup/pluginutils@5.4.0(rollup@4.60.1)':
@@ -1743,12 +1779,12 @@ snapshots:
'@tailwindcss/oxide-win32-arm64-msvc': 4.2.2 '@tailwindcss/oxide-win32-arm64-msvc': 4.2.2
'@tailwindcss/oxide-win32-x64-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: dependencies:
'@tailwindcss/node': 4.2.2 '@tailwindcss/node': 4.2.2
'@tailwindcss/oxide': 4.2.2 '@tailwindcss/oxide': 4.2.2
tailwindcss: 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)': '@tanstack/react-virtual@3.13.23(react-dom@19.2.4(react@19.2.4))(react@19.2.4)':
dependencies: dependencies:
@@ -1856,6 +1892,10 @@ snapshots:
'@types/estree@1.0.8': {} '@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)': '@types/react-dom@19.2.3(@types/react@19.2.14)':
dependencies: dependencies:
'@types/react': 19.2.14 '@types/react': 19.2.14
@@ -1864,7 +1904,7 @@ snapshots:
dependencies: dependencies:
csstype: 3.2.3 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: dependencies:
'@babel/core': 7.29.0 '@babel/core': 7.29.0
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.0) '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.29.0)
@@ -1872,7 +1912,7 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-beta.27 '@rolldown/pluginutils': 1.0.0-beta.27
'@types/babel__core': 7.20.5 '@types/babel__core': 7.20.5
react-refresh: 0.17.0 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: transitivePeerDependencies:
- supports-color - supports-color
@@ -1963,6 +2003,9 @@ snapshots:
react: 19.2.4 react: 19.2.4
react-dom: 19.2.4(react@19.2.4) react-dom: 19.2.4(react@19.2.4)
fsevents@2.3.2:
optional: true
fsevents@2.3.3: fsevents@2.3.3:
optional: true optional: true
@@ -2053,6 +2096,14 @@ snapshots:
picomatch@4.0.4: {} 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: postcss@8.5.8:
dependencies: dependencies:
nanoid: 3.3.11 nanoid: 3.3.11
@@ -2151,22 +2202,24 @@ snapshots:
typescript@5.8.3: {} typescript@5.8.3: {}
undici-types@8.3.0: {}
update-browserslist-db@1.2.3(browserslist@4.28.2): update-browserslist-db@1.2.3(browserslist@4.28.2):
dependencies: dependencies:
browserslist: 4.28.2 browserslist: 4.28.2
escalade: 3.2.0 escalade: 3.2.0
picocolors: 1.1.1 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: dependencies:
'@rollup/pluginutils': 5.4.0(rollup@4.60.1) '@rollup/pluginutils': 5.4.0(rollup@4.60.1)
imagetools-core: 9.1.0 imagetools-core: 9.1.0
sharp: 0.34.5 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: transitivePeerDependencies:
- rollup - 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: dependencies:
esbuild: 0.27.7 esbuild: 0.27.7
fdir: 6.5.0(picomatch@4.0.4) fdir: 6.5.0(picomatch@4.0.4)
@@ -2175,6 +2228,7 @@ snapshots:
rollup: 4.60.1 rollup: 4.60.1
tinyglobby: 0.2.15 tinyglobby: 0.2.15
optionalDependencies: optionalDependencies:
'@types/node': 26.0.1
fsevents: 2.3.3 fsevents: 2.3.3
jiti: 2.6.1 jiti: 2.6.1
lightningcss: 1.32.0 lightningcss: 1.32.0
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

+45
View File
@@ -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");
}
}
}
+91
View File
@@ -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.01.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;
+766 -74
View File
File diff suppressed because it is too large Load Diff
+492 -11
View File
@@ -1,4 +1,4 @@
use crate::vector; use crate::{ai_tag_filter, vector};
use anyhow::Result; use anyhow::Result;
use r2d2::Pool; use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
@@ -34,6 +34,18 @@ pub struct Folder {
pub sort_order: i64, 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)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageRecord { pub struct ImageRecord {
pub id: i64, pub id: i64,
@@ -255,12 +267,16 @@ pub fn migrate(conn: &Connection) -> Result<()> {
UNIQUE(image_id, tag) 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, folder_scope TEXT PRIMARY KEY,
image_ids_hash INTEGER NOT NULL, image_ids_hash INTEGER NOT NULL,
entries_json TEXT NOT NULL, entries_json TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')) 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 ( CREATE TABLE IF NOT EXISTS duplicate_scan_cache (
folder_scope TEXT PRIMARY KEY, folder_scope TEXT PRIMARY KEY,
@@ -285,6 +301,41 @@ 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_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_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 ON image_tags(tag);
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 +382,42 @@ pub fn migrate(conn: &Connection) -> Result<()> {
)?; )?;
vector::migrate(conn)?; 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(()) Ok(())
} }
@@ -1586,6 +1673,309 @@ pub fn reorder_folders(conn: &Connection, folder_ids: &[i64]) -> Result<()> {
Ok(()) 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> { pub fn repair_deferred_embedding_jobs(conn: &Connection) -> Result<usize> {
let pattern = "No thumbnail available yet for%"; let pattern = "No thumbnail available yet for%";
let repaired = conn.execute( let repaired = conn.execute(
@@ -1713,6 +2103,7 @@ pub fn get_images(
rating_min: i64, rating_min: i64,
embedding_failed_only: bool, embedding_failed_only: bool,
tagging_failed_only: bool, tagging_failed_only: bool,
color: Option<(u8, u8, u8)>,
sort: &str, sort: &str,
offset: i64, offset: i64,
limit: i64, limit: i64,
@@ -1737,6 +2128,10 @@ pub fn get_images(
let favorites_flag = i64::from(favorites_only); let favorites_flag = i64::from(favorites_only);
let embedding_failed_flag = i64::from(embedding_failed_only); let embedding_failed_flag = i64::from(embedding_failed_only);
let tagging_failed_flag = i64::from(tagging_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!( let sql = format!(
"SELECT id, folder_id, path, filename, thumbnail_path, width, height, file_size, created_at, modified_at, taken_at, mime_type, "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, media_kind, duration_ms, video_codec, audio_codec, metadata_updated_at, metadata_error,
@@ -1751,6 +2146,12 @@ pub fn get_images(
AND rating >= ?5 AND rating >= ?5
AND (?6 = 0 OR embedding_status = 'failed') 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 (?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} ORDER BY {order}
LIMIT ?8 OFFSET ?9" LIMIT ?8 OFFSET ?9"
); );
@@ -1765,7 +2166,13 @@ pub fn get_images(
embedding_failed_flag, embedding_failed_flag,
tagging_failed_flag, tagging_failed_flag,
limit, limit,
offset offset,
color_flag,
qr,
qg,
qb,
crate::color::MATCH_DISTANCE_SQ,
crate::color::MATCH_MIN_WEIGHT
], ],
map_image_row, map_image_row,
)?; )?;
@@ -1782,12 +2189,17 @@ pub fn count_images(
rating_min: i64, rating_min: i64,
embedding_failed_only: bool, embedding_failed_only: bool,
tagging_failed_only: bool, tagging_failed_only: bool,
color: Option<(u8, u8, u8)>,
) -> Result<i64> { ) -> Result<i64> {
let search_pattern = search.map(|value| format!("%{value}%")); let search_pattern = search.map(|value| format!("%{value}%"));
let favorites_flag = i64::from(favorites_only); let favorites_flag = i64::from(favorites_only);
let embedding_failed_flag = i64::from(embedding_failed_only); let embedding_failed_flag = i64::from(embedding_failed_only);
let tagging_failed_flag = i64::from(tagging_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( let count = conn.query_row(
"SELECT COUNT(*) FROM images "SELECT COUNT(*) FROM images
WHERE (?1 IS NULL OR folder_id = ?1) WHERE (?1 IS NULL OR folder_id = ?1)
@@ -1796,7 +2208,13 @@ pub fn count_images(
AND (?4 = 0 OR favorite = 1) AND (?4 = 0 OR favorite = 1)
AND rating >= ?5 AND rating >= ?5
AND (?6 = 0 OR embedding_status = 'failed') 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![ params![
folder_id, folder_id,
search_pattern, search_pattern,
@@ -1804,7 +2222,13 @@ pub fn count_images(
favorites_flag, favorites_flag,
rating_min, rating_min,
embedding_failed_flag, 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), |row| row.get(0),
)?; )?;
@@ -2016,6 +2440,34 @@ pub fn get_explore_tags(
Ok(rows) 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>); type FailedEmbeddingRow = (i64, String, String, Option<String>);
pub fn get_failed_embedding_images( pub fn get_failed_embedding_images(
@@ -2338,6 +2790,35 @@ pub fn remove_tag(conn: &Connection, tag_id: i64) -> Result<()> {
Ok(()) 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 enqueue_missing_tagging_jobs_for_folder(conn: &Connection, folder_id: i64) -> Result<usize> { pub fn enqueue_missing_tagging_jobs_for_folder(conn: &Connection, folder_id: i64) -> Result<usize> {
let inserted = conn.execute( let inserted = conn.execute(
"INSERT INTO tagging_jobs (image_id, status, attempts, last_error, created_at, updated_at) "INSERT INTO tagging_jobs (image_id, status, attempts, last_error, created_at, updated_at)
@@ -2506,14 +2987,14 @@ fn map_image_row(row: &Row<'_>) -> rusqlite::Result<ImageRecord> {
}) })
} }
/// Returns cached tag-cloud entries if the stored hash matches `current_hash`. /// Returns cached visual-cluster entries if the stored hash matches `current_hash`.
pub fn get_tag_cloud_cache( pub fn get_visual_cluster_cache(
conn: &Connection, conn: &Connection,
folder_scope: &str, folder_scope: &str,
current_hash: u64, current_hash: u64,
) -> Result<Option<String>> { ) -> Result<Option<String>> {
let result: rusqlite::Result<(i64, String)> = conn.query_row( 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], params![folder_scope],
|row| Ok((row.get(0)?, row.get(1)?)), |row| Ok((row.get(0)?, row.get(1)?)),
); );
@@ -2525,15 +3006,15 @@ pub fn get_tag_cloud_cache(
} }
} }
/// Upserts the tag-cloud cache for the given scope. /// Upserts the visual-cluster cache for the given scope.
pub fn set_tag_cloud_cache( pub fn set_visual_cluster_cache(
conn: &Connection, conn: &Connection,
folder_scope: &str, folder_scope: &str,
image_ids_hash: u64, image_ids_hash: u64,
entries_json: &str, entries_json: &str,
) -> Result<()> { ) -> Result<()> {
conn.execute( 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')) VALUES (?1, ?2, ?3, datetime('now'))
ON CONFLICT(folder_scope) DO UPDATE SET ON CONFLICT(folder_scope) DO UPDATE SET
image_ids_hash = excluded.image_ids_hash, image_ids_hash = excluded.image_ids_hash,
+12 -4
View File
@@ -92,6 +92,7 @@ pub fn find_similar_image_matches(
conn: &Connection, conn: &Connection,
image_id: i64, image_id: i64,
folder_id: Option<i64>, folder_id: Option<i64>,
album_id: Option<i64>,
threshold: f32, threshold: f32,
offset: usize, offset: usize,
limit: usize, limit: usize,
@@ -103,10 +104,17 @@ pub fn find_similar_image_matches(
None => return Ok(Vec::new()), 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 // the lock across a potentially slow SQLite query, which would delay any
// concurrent ensure_index call waiting for a write lock. // concurrent ensure_index call waiting for a write lock. Album scope takes
let folder_image_ids: Option<Vec<i64>> = if let Some(folder_id) = folder_id { // 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))? let ids = vector::get_all_image_embeddings_with_ids(conn, Some(folder_id))?
.into_iter() .into_iter()
.map(|(id, _)| id) .map(|(id, _)| id)
@@ -122,7 +130,7 @@ pub fn find_similar_image_matches(
}; };
let knbn = (offset + limit).max(limit).saturating_add(32); 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 let mut allowed_ids = image_ids
.into_iter() .into_iter()
.filter_map(|allowed_image_id| { .filter_map(|allowed_image_id| {
+251 -19
View File
@@ -3,18 +3,18 @@ use crate::db::{self, DbPool, EmbeddingJob, FolderJobProgress, ImageRecord, Inde
use crate::embedder::{embedding_source_path, ClipImageEmbedder}; use crate::embedder::{embedding_source_path, ClipImageEmbedder};
use crate::media::{probe_video_metadata, MediaTools}; use crate::media::{probe_video_metadata, MediaTools};
use crate::storage::{detect_storage_profile, RuntimeAdaptiveProfile, StorageProfile}; use crate::storage::{detect_storage_profile, RuntimeAdaptiveProfile, StorageProfile};
use crate::tagger::{self, WdTagger}; use crate::tagger::{self, Tagger};
use crate::thumbnail; use crate::thumbnail;
use crate::vector; use crate::vector;
use anyhow::Result; use anyhow::Result;
use notify::{RecommendedWatcher, RecursiveMode, Watcher}; use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use rayon::prelude::*; use rayon::prelude::*;
use serde::Serialize; use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock}; use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter}; use tauri::{AppHandle, Emitter, Manager};
use walkdir::WalkDir; use walkdir::WalkDir;
const IMAGE_EXTENSIONS: &[&str] = &[ const IMAGE_EXTENSIONS: &[&str] = &[
@@ -41,6 +41,14 @@ struct PausedWorkerFolders {
tagging: HashSet<i64>, 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)] #[derive(Clone, Copy)]
pub struct FolderWorkerPausedState { pub struct FolderWorkerPausedState {
pub thumbnail: bool, pub thumbnail: bool,
@@ -50,6 +58,41 @@ pub struct FolderWorkerPausedState {
pub tagging: bool, 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) { pub fn set_worker_paused(worker: &str, folder_id: i64, paused: bool) {
if let Ok(mut paused_folders) = PAUSED_WORKER_FOLDERS if let Ok(mut paused_folders) = PAUSED_WORKER_FOLDERS
.get_or_init(|| Mutex::new(PausedWorkerFolders::default())) .get_or_init(|| Mutex::new(PausedWorkerFolders::default()))
@@ -190,6 +233,13 @@ pub struct MediaUpdateBatch {
pub images: Vec<ImageRecord>, pub images: Vec<ImageRecord>,
} }
#[derive(Clone, Serialize)]
pub struct ColorBackfillProgress {
pub processed: i64,
pub total: i64,
pub done: bool,
}
#[derive(Clone, Serialize)] #[derive(Clone, Serialize)]
pub struct MediaJobProgressEvent { pub struct MediaJobProgressEvent {
pub progress: Vec<FolderJobProgress>, 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) { pub fn start_tagging_worker(app: AppHandle, pool: DbPool, app_data_dir: PathBuf) {
std::thread::spawn(move || { 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."); log::info!("Tagging worker started.");
loop { loop {
// If the acceleration setting changed, drop the cached session so // 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<()> { 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 existing_entries = {
let conn = pool.get()?; let conn = pool.get()?;
db::get_folder_media_index(&conn, folder_id)? 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) let media_paths: Vec<PathBuf> = WalkDir::new(&folder_path)
.follow_links(true) .follow_links(true)
.into_iter() .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 { .filter_map(|entry| match entry {
Ok(e) if e.file_type().is_file() && is_supported_media(e.path()) => { Ok(e) if e.file_type().is_file() && is_supported_media(e.path()) => {
Some(e.path().to_path_buf()) Some(e.path().to_path_buf())
@@ -737,6 +834,13 @@ fn persist_thumbnail_results(
width, width,
height, 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()?; tx.commit()?;
@@ -767,6 +871,76 @@ fn is_avif_path(path: &Path) -> bool {
.is_some_and(|ext| ext.eq_ignore_ascii_case("avif")) .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 /// Returns `Ok(true)` if a batch was claimed and processed, `Ok(false)` if
/// the queue was empty. /// the queue was empty.
fn process_metadata_batch( fn process_metadata_batch(
@@ -1105,7 +1279,7 @@ fn process_tagging_batch(
app: &AppHandle, app: &AppHandle,
pool: &DbPool, pool: &DbPool,
app_data_dir: &Path, app_data_dir: &Path,
tagger_instance: &mut Option<WdTagger>, tagger_instance: &mut Option<Box<dyn Tagger>>,
) -> Result<bool> { ) -> Result<bool> {
if !tagger::tagger_model_status(app_data_dir).ready { if !tagger::tagger_model_status(app_data_dir).ready {
return Ok(false); return Ok(false);
@@ -1117,20 +1291,23 @@ fn process_tagging_batch(
// Exclude actively-indexing folders for the same reason as the other // Exclude actively-indexing folders for the same reason as the other
// workers: don't compete with a running scan. // workers: don't compete with a running scan.
let batch_started_at = Instant::now();
let mut excluded_folders = paused_folder_ids("tagging"); let mut excluded_folders = paused_folder_ids("tagging");
excluded_folders.extend(active_indexing_folders()); excluded_folders.extend(active_indexing_folders());
let batch_size = crate::tagger::tagger_batch_size(app_data_dir); let batch_size = crate::tagger::tagger_batch_size(app_data_dir);
let claim_started_at = Instant::now();
let jobs = with_db_write_lock(|| { let jobs = with_db_write_lock(|| {
let mut conn = pool.get()?; let mut conn = pool.get()?;
db::claim_tagging_jobs(&mut conn, &excluded_folders, batch_size) db::claim_tagging_jobs(&mut conn, &excluded_folders, batch_size)
})?; })?;
let claim_elapsed = claim_started_at.elapsed();
if jobs.is_empty() { if jobs.is_empty() {
return Ok(false); return Ok(false);
} }
if tagger_instance.is_none() { 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), Ok(model) => *tagger_instance = Some(model),
Err(error) => { Err(error) => {
with_db_write_lock(|| { with_db_write_lock(|| {
@@ -1157,21 +1334,45 @@ fn process_tagging_batch(
.as_mut() .as_mut()
.expect("tagger should be initialized before tagging batch processing"); .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() .iter()
.map(|job| { .map(|job| {
let source_path = if is_avif_path(Path::new(&job.path)) { if is_avif_path(Path::new(&job.path)) {
job.thumbnail_path.as_deref().unwrap_or(&job.path) PathBuf::from(job.thumbnail_path.as_deref().unwrap_or(&job.path))
} else { } else {
&job.path PathBuf::from(&job.path)
}; }
(
job.clone(),
tagger_ref.run(Path::new(source_path), tagger::DEFAULT_MAX_TAGS),
)
}) })
.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 updated_images = with_db_write_lock(|| {
let mut conn = pool.get()?; let mut conn = pool.get()?;
let tx = conn.transaction()?; let tx = conn.transaction()?;
@@ -1201,7 +1402,7 @@ fn process_tagging_batch(
job.image_id, job.image_id,
&tag_pairs, &tag_pairs,
&output.rating, &output.rating,
tagger::WD_TAGGER_MODEL_NAME, tagger_model_name,
)?; )?;
} }
Err(error) => { Err(error) => {
@@ -1223,6 +1424,7 @@ fn process_tagging_batch(
db::requeue_tagging_jobs(&conn, &image_ids) db::requeue_tagging_jobs(&conn, &image_ids)
}); });
})?; })?;
let write_elapsed = write_started_at.elapsed();
if !updated_images.is_empty() { if !updated_images.is_empty() {
let folder_ids = updated_images 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); 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) 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. // Spawn the debounce loop on its own thread.
let folder_map_thread = Arc::clone(&folder_map); 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 || { std::thread::spawn(move || {
// path → deadline: the earliest instant at which this path should be processed. // path → deadline: the earliest instant at which this path should be processed.
let mut pending: HashMap<PathBuf, Instant> = HashMap::new(); 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 old = event.paths[0].clone();
let new = event.paths[1].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 // Remove either side from regular pending so it isn't
// processed as an independent delete/create. // processed as an independent delete/create.
pending.remove(&old); pending.remove(&old);
@@ -1564,7 +1794,9 @@ pub fn start_watcher(app: AppHandle, pool: DbPool, thumb_dir: PathBuf) -> Watche
} }
} else { } else {
for path in event.paths { 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); pending.insert(path, now + WATCHER_DEBOUNCE);
} }
} }
+57 -1
View File
@@ -1,4 +1,6 @@
mod ai_tag_filter;
mod captioner; mod captioner;
mod color;
mod commands; mod commands;
mod db; mod db;
mod embedder; mod embedder;
@@ -45,6 +47,32 @@ pub fn run() {
.plugin(tauri_plugin_fs::init()) .plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_notification::init()) .plugin(tauri_plugin_notification::init())
.setup(|app| { .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 let app_dir = app
.path() .path()
.app_data_dir() .app_data_dir()
@@ -91,6 +119,7 @@ pub fn run() {
let thumb_dir = app_dir.join("thumbnails"); let thumb_dir = app_dir.join("thumbnails");
std::fs::create_dir_all(&thumb_dir).expect("Failed to create thumbnail dir"); 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 // The asset protocol scope is no longer a blanket "**": thumbnails
// are allowed statically in tauri.conf.json, and each indexed // 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. // 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_caption_worker(app.handle().clone(), pool.clone(), app_dir.clone());
indexer::start_tagging_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()); 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::suggest_image_tags,
commands::set_worker_paused, commands::set_worker_paused,
commands::get_worker_states, 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_explore_tags,
commands::get_related_tags,
commands::get_images_by_ids, commands::get_images_by_ids,
commands::get_failed_embedding_images, commands::get_failed_embedding_images,
commands::get_failed_tagging_images, commands::get_failed_tagging_images,
commands::get_tagger_model_status, commands::get_tagger_model_status,
commands::get_tagger_acceleration, commands::get_tagger_acceleration,
commands::set_tagger_acceleration, commands::set_tagger_acceleration,
commands::get_tagger_model,
commands::set_tagger_model,
commands::probe_tagger_runtime, commands::probe_tagger_runtime,
commands::get_tagger_threshold, commands::get_tagger_threshold,
commands::set_tagger_threshold, commands::set_tagger_threshold,
@@ -185,6 +221,22 @@ pub fn run() {
commands::get_image_tags, commands::get_image_tags,
commands::add_user_tag, commands::add_user_tag,
commands::remove_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::search_tags_autocomplete,
commands::find_duplicates, commands::find_duplicates,
commands::load_duplicate_scan_cache, commands::load_duplicate_scan_cache,
@@ -197,6 +249,8 @@ pub fn run() {
commands::get_tagging_queue_folder_ids, commands::get_tagging_queue_folder_ids,
commands::set_tagging_queue_folder_ids, commands::set_tagging_queue_folder_ids,
commands::open_app_data_folder, commands::open_app_data_folder,
commands::open_map_location,
commands::open_changelog_url,
commands::get_database_info, commands::get_database_info,
commands::vacuum_database, commands::vacuum_database,
commands::rebuild_semantic_index, commands::rebuild_semantic_index,
@@ -208,6 +262,8 @@ pub fn run() {
commands::retry_ffmpeg_download, commands::retry_ffmpeg_download,
commands::get_onboarding_completed, commands::get_onboarding_completed,
commands::set_onboarding_completed, commands::set_onboarding_completed,
commands::get_last_seen_version,
commands::set_last_seen_version,
commands::get_notifications_paused, commands::get_notifications_paused,
commands::set_notifications_paused, commands::set_notifications_paused,
]) ])
+609 -73
View File
@@ -1,9 +1,11 @@
use crate::ai_tag_filter;
use anyhow::Result; use anyhow::Result;
use hf_hub::{api::sync::Api, Repo, RepoType}; use hf_hub::{api::sync::Api, Repo, RepoType};
use image::{imageops::FilterType, DynamicImage, ImageReader}; use image::{imageops::FilterType, DynamicImage, ImageReader};
use ort::ep; use ort::ep;
use ort::session::{builder::GraphOptimizationLevel, Session}; use ort::session::{builder::GraphOptimizationLevel, Session};
use ort::value::Tensor; use ort::value::Tensor;
use rayon::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
@@ -15,15 +17,27 @@ pub const WD_TAGGER_MODEL_NAME: &str = "wd-swinv2-tagger-v3";
const TAGGER_ACCELERATION_FILE: &str = "settings/tagger_acceleration.txt"; const TAGGER_ACCELERATION_FILE: &str = "settings/tagger_acceleration.txt";
const TAGGER_THRESHOLD_FILE: &str = "settings/tagger_threshold.txt"; const TAGGER_THRESHOLD_FILE: &str = "settings/tagger_threshold.txt";
const TAGGER_BATCH_SIZE_FILE: &str = "settings/tagger_batch_size.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 pub const JOYTAG_MODEL_ID: &str = "fancyfeast/joytag";
// are shared with the captioner and live in the same `onnxruntime/` directory. pub const JOYTAG_MODEL_NAME: &str = "joytag";
const TAGGER_REQUIRED_FILES: &[&str] = &[
// 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 (used as the default; the user's
// tagger_threshold setting still overrides it).
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.dll",
"onnxruntime/onnxruntime_providers_shared.dll", "onnxruntime/onnxruntime_providers_shared.dll",
"onnxruntime/DirectML.dll", "onnxruntime/DirectML.dll",
"model.onnx",
"selected_tags.csv",
]; ];
// Tags in these Danbooru categories are kept in the output. // Tags in these Danbooru categories are kept in the output.
@@ -37,6 +51,19 @@ const RATING_CATEGORY: u8 = 9;
pub const DEFAULT_THRESHOLD: f32 = 0.35; pub const DEFAULT_THRESHOLD: f32 = 0.35;
pub const DEFAULT_MAX_TAGS: usize = 30; pub const DEFAULT_MAX_TAGS: usize = 30;
/// 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 `set_tagger_acceleration` so the tagging worker loop /// Set to `true` by `set_tagger_acceleration` so the tagging worker loop
/// knows to drop its cached `WdTagger` and reload with the new EP. /// knows to drop its cached `WdTagger` and reload with the new EP.
pub static TAGGER_SESSION_DIRTY: AtomicBool = AtomicBool::new(false); pub static TAGGER_SESSION_DIRTY: AtomicBool = AtomicBool::new(false);
@@ -64,6 +91,61 @@ 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",
}
}
/// 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 // Status / probe types exposed to the frontend
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -138,14 +220,41 @@ struct TagEntry {
// Path helpers // 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 { 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 // 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 { pub fn tagger_acceleration(app_data_dir: &Path) -> TaggerAcceleration {
let path = app_data_dir.join(TAGGER_ACCELERATION_FILE); let path = app_data_dir.join(TAGGER_ACCELERATION_FILE);
let Ok(value) = std::fs::read_to_string(path) else { let Ok(value) = std::fs::read_to_string(path) else {
@@ -217,25 +326,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 { 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); let local_dir = model_dir(app_data_dir);
// The ONNX runtime DLLs live in the caption model dir; reuse them. // 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 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() .iter()
.filter(|file| { .filter(|file| !caption_model_dir.join(file).exists())
let path = if file.starts_with("onnxruntime/") {
caption_model_dir.join(file)
} else {
local_dir.join(file)
};
!path.exists()
})
.map(|file| (*file).to_string()) .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 { TaggerModelStatus {
model_id: WD_TAGGER_MODEL_ID, model_id: model.repo_id(),
model_name: WD_TAGGER_MODEL_NAME, model_name: model.model_name(),
local_dir: local_dir.to_string_lossy().to_string(), local_dir: local_dir.to_string_lossy().to_string(),
ready: missing_files.is_empty(), ready: missing_files.is_empty(),
missing_files, missing_files,
@@ -246,19 +357,20 @@ pub fn prepare_tagger_model_with_progress(
app_data_dir: &Path, app_data_dir: &Path,
emit_progress: impl Fn(TaggerModelProgress), emit_progress: impl Fn(TaggerModelProgress),
) -> Result<TaggerModelStatus> { ) -> Result<TaggerModelStatus> {
let model = tagger_model(app_data_dir);
let local_dir = model_dir(app_data_dir); let local_dir = model_dir(app_data_dir);
std::fs::create_dir_all(&local_dir)?; std::fs::create_dir_all(&local_dir)?;
// The tagger shares the ONNX runtime DLLs with the captioner; download // 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 // them here so the tagger works even on a clean install where the caption
// model has never been fetched (ensure_onnx_runtime only initializes). // 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); let caption_model_dir = crate::captioner::model_dir(app_data_dir);
std::fs::create_dir_all(&caption_model_dir)?; std::fs::create_dir_all(&caption_model_dir)?;
// Unified step count across DLLs and tagger files so the bar is coherent. // 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 dll_count = crate::captioner::missing_onnx_runtime_count(&caption_model_dir);
let model_pending = DOWNLOAD_FILES let model_pending = download_files
.iter() .iter()
.filter(|file| !local_dir.join(file).exists()) .filter(|file| !local_dir.join(file).exists())
.count(); .count();
@@ -304,9 +416,9 @@ pub fn prepare_tagger_model_with_progress(
// (timeout + resume), rather than hf-hub's download_with_progress, whose // (timeout + resume), rather than hf-hub's download_with_progress, whose
// agent has no read timeout and would hang on a stalled connection. // agent has no read timeout and would hang on a stalled connection.
let api = Api::new()?; 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); let destination = local_dir.join(file);
if destination.exists() { if destination.exists() {
continue; continue;
@@ -410,11 +522,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 { pub struct WdTagger {
@@ -456,33 +653,34 @@ impl WdTagger {
let session = create_tagger_session(&model_path, acceleration)?; let session = create_tagger_session(&model_path, acceleration)?;
// Determine the input spatial size from the ONNX model graph. // Determine the input spatial size (and batch axis, for diagnostics) from
// WD v3 models use (1, H, W, 3) where H == W, typically 448. // the ONNX model graph. WD v3 models use (N, H, W, 3) with H == W,
let input_size = { // 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 inputs = session.inputs();
let dim = inputs inputs
.first() .first()
.and_then(|inp| { .and_then(|inp| {
if let ort::value::ValueType::Tensor { shape, .. } = inp.dtype() { if let ort::value::ValueType::Tensor { shape, .. } = inp.dtype() {
shape let size = shape.get(1).copied().filter(|&d| d > 0).map(|d| d as usize);
.get(1) Some((size.unwrap_or(448), shape.first().copied()))
.and_then(|&d| if d > 0 { Some(d as usize) } else { None })
} else { } else {
None None
} }
}) })
.unwrap_or(448); .unwrap_or((448, None))
dim
}; };
let labels = load_labels(&labels_path)?; let labels = load_labels(&labels_path)?;
log::info!( log::info!(
"WD tagger loaded in {:?} ({} labels, input {}x{}, {:?} acceleration)", "WD tagger loaded in {:?} ({} labels, input {}x{}, batch axis {:?}, {:?} acceleration)",
started_at.elapsed(), started_at.elapsed(),
labels.len(), labels.len(),
input_size, input_size,
input_size, input_size,
batch_axis,
acceleration, acceleration,
); );
@@ -494,14 +692,17 @@ impl WdTagger {
}) })
} }
pub fn run(&mut self, image_path: &Path, max_tags: usize) -> Result<TaggerOutput> { /// Run `count` already-preprocessed images (contiguous `[count, H, W, 3]`
let started_at = Instant::now(); /// pixels) through the model in one forward pass.
fn infer_batch(
let image_array = preprocess_image(image_path, self.input_size)?; &mut self,
let batch_size = 1usize; pixels: &[f32],
count: usize,
max_tags: usize,
) -> Result<Vec<TaggerOutput>> {
let input = Tensor::from_array(( let input = Tensor::from_array((
[batch_size, self.input_size, self.input_size, 3usize], [count, self.input_size, self.input_size, 3usize],
image_array.into_boxed_slice(), pixels.to_vec().into_boxed_slice(),
)) ))
.map_err(|error| anyhow::anyhow!("{error}"))?; .map_err(|error| anyhow::anyhow!("{error}"))?;
@@ -511,23 +712,40 @@ impl WdTagger {
.run(ort::inputs! { input_name.as_str() => input }) .run(ort::inputs! { input_name.as_str() => input })
.map_err(|error| anyhow::anyhow!("{error}"))?; .map_err(|error| anyhow::anyhow!("{error}"))?;
let (_, probabilities) = outputs[0] let (_, probs) = outputs[0]
.try_extract_tensor::<f32>() .try_extract_tensor::<f32>()
.map_err(|error| anyhow::anyhow!("{error}"))?; .map_err(|error| anyhow::anyhow!("{error}"))?;
let probs: &[f32] = probabilities; let n_labels = self.labels.len();
if probs.len() != count * n_labels {
if probs.len() != self.labels.len() {
anyhow::bail!( anyhow::bail!(
"Model output length {} does not match label count {}", "Model output length {} does not match {} images x {} labels",
probs.len(), probs.len(),
self.labels.len() count,
n_labels
); );
} }
// Collect rating scores (category 9) - pick the argmax as the rating. // Borrow disjoint fields (not all of `self`) so this doesn't conflict
let rating = self // with the mutable session borrow `outputs` still holds.
.labels 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() .iter()
.zip(probs.iter()) .zip(probs.iter())
.filter(|(entry, _)| entry.category == RATING_CATEGORY) .filter(|(entry, _)| entry.category == RATING_CATEGORY)
@@ -535,14 +753,14 @@ impl WdTagger {
.map(|(entry, _)| entry.name.clone()) .map(|(entry, _)| entry.name.clone())
.unwrap_or_else(|| "general".to_string()); .unwrap_or_else(|| "general".to_string());
// Collect general + character tags above threshold, sorted by confidence. // General + character tags above threshold, sorted by confidence.
let mut tags: Vec<TagResult> = self let mut tags: Vec<TagResult> = labels
.labels
.iter() .iter()
.zip(probs.iter()) .zip(probs.iter())
.filter(|(entry, prob)| { .filter(|(entry, prob)| {
(entry.category == GENERAL_CATEGORY || entry.category == CHARACTER_CATEGORY) (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 { .map(|(entry, prob)| TagResult {
tag: entry.name.clone(), tag: entry.name.clone(),
@@ -553,16 +771,178 @@ impl WdTagger {
tags.sort_by(|a, b| b.confidence.total_cmp(&a.confidence)); tags.sort_by(|a, b| b.confidence.total_cmp(&a.confidence));
tags.truncate(max_tags); 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!( log::info!(
"WD tagger: {} tags (threshold={}, rating={}) in {:?} for {}", "JoyTag loaded in {:?} ({} tags, input {}x{}, batch axis {:?}, {:?} acceleration)",
tags.len(),
self.threshold,
rating,
started_at.elapsed(), 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 +961,22 @@ fn create_tagger_session(path: &Path, acceleration: TaggerAcceleration) -> Resul
TaggerAcceleration::Auto | TaggerAcceleration::Directml 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 let builder = builder
.with_memory_pattern(!use_directml) .with_memory_pattern(!use_directml)
.map_err(|error| anyhow::anyhow!("{error}"))?; .map_err(|error| anyhow::anyhow!("{error}"))?;
@@ -588,18 +984,18 @@ fn create_tagger_session(path: &Path, acceleration: TaggerAcceleration) -> Resul
.with_parallel_execution(false) .with_parallel_execution(false)
.map_err(|error| anyhow::anyhow!("{error}"))?; .map_err(|error| anyhow::anyhow!("{error}"))?;
let builder = builder let builder = builder
.with_intra_threads(1) .with_intra_threads(intra_threads)
.map_err(|error| anyhow::anyhow!("{error}"))?; .map_err(|error| anyhow::anyhow!("{error}"))?;
let mut builder = match acceleration { let mut builder = match acceleration {
TaggerAcceleration::Cpu => { TaggerAcceleration::Cpu => {
log::info!("WD tagger: using CPU execution provider"); log::info!("Tagger: using CPU execution provider ({intra_threads} intra-op threads)");
builder builder
} }
TaggerAcceleration::Auto => builder TaggerAcceleration::Auto => builder
.with_execution_providers([ep::DirectML::default().build().fail_silently()]) .with_execution_providers([ep::DirectML::default().build().fail_silently()])
.unwrap_or_else(|error| { .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() error.recover()
}), }),
TaggerAcceleration::Directml => builder TaggerAcceleration::Directml => builder
@@ -641,12 +1037,134 @@ fn load_labels(path: &Path) -> Result<Vec<TagEntry>> {
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Image preprocessing // JoyTag: label loading, threshold, rating derivation
// WD tagger expects: (1, H, W, 3) float32, raw [0,255] values, BGR channel
// order, padded to square with white (255,255,255).
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
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. Honours the shared `tagger_threshold` setting if
/// the user has set it, otherwise uses JoyTag's recommended default (0.4).
fn joytag_threshold(app_data_dir: &Path) -> f32 {
match std::fs::read_to_string(app_data_dir.join(TAGGER_THRESHOLD_FILE)) {
Ok(value) => value
.trim()
.parse::<f32>()
.unwrap_or(JOYTAG_DEFAULT_THRESHOLD)
.clamp(0.01, 1.0),
Err(_) => JOYTAG_DEFAULT_THRESHOLD,
}
}
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()?; let image = ImageReader::open(image_path)?.decode()?;
// Composite any alpha channel onto a white background. // Composite any alpha channel onto a white background.
@@ -657,22 +1175,25 @@ fn preprocess_image(image_path: &Path, target_size: usize) -> Result<Vec<f32>> {
image::imageops::overlay(&mut canvas_rgba, &image_rgba, 0, 0); image::imageops::overlay(&mut canvas_rgba, &image_rgba, 0, 0);
let image_rgb = DynamicImage::ImageRgba8(canvas_rgba).to_rgb8(); let image_rgb = DynamicImage::ImageRgba8(canvas_rgba).to_rgb8();
// Pad to square. // Pad to a centered square.
let max_dim = width.max(height); let max_dim = width.max(height);
let pad_left = (max_dim - width) / 2; let pad_left = (max_dim - width) / 2;
let pad_top = (max_dim - height) / 2; let pad_top = (max_dim - height) / 2;
let mut square = image::RgbImage::from_pixel(max_dim, max_dim, image::Rgb([255, 255, 255])); 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); image::imageops::overlay(&mut square, &image_rgb, pad_left as i64, pad_top as i64);
// Resize to model input size. // Resize to model input size (CatmullRom ≈ PIL BICUBIC).
let resized = image::imageops::resize( Ok(image::imageops::resize(
&square, &square,
target_size as u32, target_size as u32,
target_size as u32, target_size as u32,
FilterType::CatmullRom, 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]; let mut pixel_values = vec![0.0f32; target_size * target_size * 3];
for (x, y, pixel) in resized.enumerate_pixels() { for (x, y, pixel) in resized.enumerate_pixels() {
let base = (y as usize * target_size + x as usize) * 3; let base = (y as usize * target_size + x as usize) * 3;
@@ -681,6 +1202,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 + 1] = f32::from(pixel[1]); // G
pixel_values[base + 2] = f32::from(pixel[0]); // R 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) Ok(pixel_values)
} }
+23
View File
@@ -12,6 +12,9 @@ pub struct GeneratedThumbnail {
pub path: PathBuf, pub path: PathBuf,
pub width: Option<i64>, pub width: Option<i64>,
pub height: 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> { 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, path: out_path,
width: original_dimensions.0, width: original_dimensions.0,
height: original_dimensions.1, 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()) let thumb = image::RgbImage::from_raw(dst_width, dst_height, dst.buffer().to_vec())
.ok_or_else(|| anyhow!("failed to construct resized thumbnail buffer"))?; .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() { if let Some(parent) = out_path.parent() {
std::fs::create_dir_all(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, path: out_path,
width: original_dimensions.0, width: original_dimensions.0,
height: original_dimensions.1, height: original_dimensions.1,
palette,
}) })
} }
@@ -166,6 +177,7 @@ pub fn generate_video_thumbnail(
path: out_path, path: out_path,
width: None, width: None,
height: None, height: None,
palette: Vec::new(),
}); });
} }
@@ -231,6 +243,7 @@ pub fn generate_video_thumbnail(
path: out_path, path: out_path,
width: None, width: None,
height: None, height: None,
palette: Vec::new(),
}); });
} }
last_error = String::from_utf8_lossy(&output.stderr).to_string(); last_error = String::from_utf8_lossy(&output.stderr).to_string();
@@ -255,6 +268,7 @@ pub fn generate_avif_thumbnail(
path: out_path, path: out_path,
width: original_dimensions.0, width: original_dimensions.0,
height: original_dimensions.1, height: original_dimensions.1,
palette: Vec::new(),
}); });
} }
@@ -282,10 +296,19 @@ pub fn generate_avif_thumbnail(
.output()?; .output()?;
if output.status.success() && out_path.exists() { 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 { return Ok(GeneratedThumbnail {
path: out_path, path: out_path,
width: original_dimensions.0, width: original_dimensions.0,
height: original_dimensions.1, height: original_dimensions.1,
palette,
}); });
} }
+73
View File
@@ -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. /// Returns all stored image embeddings with their image IDs, optionally filtered to one folder.
/// Each entry is `(image_id, normalized_f32_embedding)`. /// 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( pub fn get_all_image_embeddings_with_ids(
conn: &Connection, conn: &Connection,
folder_id: Option<i64>, folder_id: Option<i64>,
@@ -372,6 +410,41 @@ pub fn search_image_ids_by_embedding_in_folder(
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?) 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)] #[allow(dead_code)]
pub fn search_caption_ids_by_embedding( pub fn search_caption_ids_by_embedding(
conn: &Connection, conn: &Connection,
+20 -5
View File
@@ -5,13 +5,15 @@ import { BackgroundTasks } from "./components/BackgroundTasks";
import { Toolbar } from "./components/Toolbar"; import { Toolbar } from "./components/Toolbar";
import { Gallery } from "./components/Gallery"; import { Gallery } from "./components/Gallery";
import { Lightbox } from "./components/Lightbox"; import { Lightbox } from "./components/Lightbox";
import { TagCloud } from "./components/TagCloud"; import { ExploreView } from "./components/ExploreView";
import { DuplicateFinder } from "./components/DuplicateFinder"; import { DuplicateFinder } from "./components/DuplicateFinder";
import { Timeline } from "./components/Timeline"; import { Timeline } from "./components/Timeline";
import { TitleBar } from "./components/TitleBar"; import { TitleBar } from "./components/TitleBar";
import { SettingsModal } from "./components/SettingsModal"; import { SettingsModal } from "./components/SettingsModal";
import { FolderPickerModal } from "./components/FolderPickerModal"; import { FolderPickerModal } from "./components/FolderPickerModal";
import { UpdateToast } from "./components/UpdateToast"; import { UpdateToast } from "./components/UpdateToast";
import { WhatsNewToast } from "./components/WhatsNewToast";
import { WhatsNewModal } from "./components/WhatsNewModal";
import { OnboardingOverlay } from "./components/onboarding/OnboardingOverlay"; import { OnboardingOverlay } from "./components/onboarding/OnboardingOverlay";
import { DemoPanel } from "./components/DemoPanel"; import { DemoPanel } from "./components/DemoPanel";
import { initializeNotifications } from "./notifications"; import { initializeNotifications } from "./notifications";
@@ -22,31 +24,42 @@ export default function App() {
const loadImages = useGalleryStore((state) => state.loadImages); const loadImages = useGalleryStore((state) => state.loadImages);
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus); const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus);
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache); const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache);
const loadAlbums = useGalleryStore((state) => state.loadAlbums);
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds); const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds);
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused); const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused);
const loadWorkerPausesPersist = useGalleryStore((state) => state.loadWorkerPausesPersist);
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress); const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress);
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion); const loadAppVersion = useGalleryStore((state) => state.loadAppVersion);
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates); const checkForUpdates = useGalleryStore((state) => state.checkForUpdates);
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus); const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus);
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted); const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted);
const initWhatsNew = useGalleryStore((state) => state.initWhatsNew);
const activeView = useGalleryStore((state) => state.activeView); const activeView = useGalleryStore((state) => state.activeView);
useEffect(() => { useEffect(() => {
void initializeNotifications(); void initializeNotifications();
void loadMutedFolderIds(); void loadMutedFolderIds();
void loadNotificationsPaused(); void loadNotificationsPaused();
void loadAppVersion(); void loadWorkerPausesPersist();
void loadFfmpegStatus(); void loadFfmpegStatus();
void loadOnboardingCompleted(); 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. // Quiet launch check — dev builds have no signed artifacts to update to.
if (import.meta.env.PROD) { if (import.meta.env.PROD) {
void checkForUpdates({ quiet: true }); void checkForUpdates({ quiet: true });
} }
loadFolders().then(() => { loadFolders().then(async () => {
void loadBackgroundJobProgress(); void loadBackgroundJobProgress();
void loadCaptionModelStatus(); void loadCaptionModelStatus();
void loadDuplicateScanCache(); void loadDuplicateScanCache();
return loadImages(true); await loadAlbums();
await loadImages(true);
if (import.meta.env.MODE === "ui") {
const { applyMockScenario } = await import("./dev/applyMockScenario");
applyMockScenario();
}
}); });
let unlisten: (() => void) | undefined; let unlisten: (() => void) | undefined;
subscribeToProgress().then((fn) => { subscribeToProgress().then((fn) => {
@@ -75,7 +88,7 @@ export default function App() {
) : activeView === "explore" ? ( ) : activeView === "explore" ? (
<> <>
<BackgroundTasks /> <BackgroundTasks />
<TagCloud /> <ExploreView />
</> </>
) : activeView === "duplicates" ? ( ) : activeView === "duplicates" ? (
<> <>
@@ -96,6 +109,8 @@ export default function App() {
<SettingsModal /> <SettingsModal />
<FolderPickerModal /> <FolderPickerModal />
<UpdateToast /> <UpdateToast />
<WhatsNewToast />
<WhatsNewModal />
<OnboardingOverlay /> <OnboardingOverlay />
{import.meta.env.DEV && <DemoPanel />} {import.meta.env.DEV && <DemoPanel />}
</div> </div>
+114
View File
@@ -0,0 +1,114 @@
// 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);
export function getChangelogForVersion(version: string | null | undefined): ChangelogEntry | null {
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;
}
+21 -2
View File
@@ -21,6 +21,7 @@ interface Task {
id: number; id: number;
name: string; name: string;
stages: TaskStage[]; stages: TaskStage[];
isActive: boolean;
hasFailedEmbeddings: boolean; hasFailedEmbeddings: boolean;
hasFailedTagging: boolean; hasFailedTagging: boolean;
hasFailedCaptions: boolean; hasFailedCaptions: boolean;
@@ -156,6 +157,18 @@ export function BackgroundTasks() {
const captionReady = jobs?.caption_ready ?? 0; const captionReady = jobs?.caption_ready ?? 0;
const captionFailed = jobs?.caption_failed ?? 0; const captionFailed = jobs?.caption_failed ?? 0;
// A folder is "actively processing" when something is genuinely moving:
// an in-progress scan, or pending work on a worker that isn't paused.
// Captions have no per-folder pause toggle, so any caption work counts.
const paused = workerPaused[folder.id];
const isActive =
(!!index && !index.done) ||
(thumbnailPending > 0 && !(paused?.thumbnail ?? false)) ||
(metadataPending > 0 && !(paused?.metadata ?? false)) ||
(embeddingPending > 0 && !(paused?.embedding ?? false)) ||
(taggingPending > 0 && !(paused?.tagging ?? false)) ||
captionPending > 0;
const pendingMediaWork = thumbnailPending + metadataPending + embeddingPending + taggingPending + captionPending; const pendingMediaWork = thumbnailPending + metadataPending + embeddingPending + taggingPending + captionPending;
const embeddingProcessed = embeddingReady + embeddingFailed; const embeddingProcessed = embeddingReady + embeddingFailed;
const embeddingTotal = embeddingProcessed + embeddingPending; const embeddingTotal = embeddingProcessed + embeddingPending;
@@ -262,6 +275,7 @@ export function BackgroundTasks() {
id: folder.id, id: folder.id,
name: folder.name, name: folder.name,
stages, stages,
isActive,
hasFailedEmbeddings, hasFailedEmbeddings,
hasFailedTagging, hasFailedTagging,
hasFailedCaptions, hasFailedCaptions,
@@ -273,8 +287,12 @@ export function BackgroundTasks() {
}; };
}) })
.filter((t): t is Task => t !== null) .filter((t): t is Task => t !== null)
.filter((t) => dismissed[t.id] !== t.snapshot); .filter((t) => dismissed[t.id] !== t.snapshot)
}, [folders, indexingProgress, mediaJobProgress, dismissed]); // Surface actively-processing folders first so a paused folder never holds
// the primary (collapsed) slot while another is genuinely working. Array
// sort is stable, so folders within each group keep their existing order.
.sort((a, b) => Number(b.isActive) - Number(a.isActive));
}, [folders, indexingProgress, mediaJobProgress, workerPaused, dismissed]);
// Synthetic task for duplicate scanning — negative id so dismiss/retry are suppressed // Synthetic task for duplicate scanning — negative id so dismiss/retry are suppressed
const duplicateScanTask: Task | null = duplicateScanning ? { const duplicateScanTask: Task | null = duplicateScanning ? {
@@ -294,6 +312,7 @@ export function BackgroundTasks() {
: null, : null,
failed: false, failed: false,
}], }],
isActive: true,
hasFailedEmbeddings: false, hasFailedEmbeddings: false,
hasFailedTagging: false, hasFailedTagging: false,
hasFailedCaptions: false, hasFailedCaptions: false,
+276
View File
@@ -0,0 +1,276 @@
import { useEffect, useRef, useState } from "react";
import { useGalleryStore } from "../store";
import { BulkTagPopover } from "./bulk/BulkTagPopover";
type Panel = "tag" | "rating" | "album" | "delete" | null;
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 albums = useGalleryStore((state) => state.albums);
const addToAlbum = useGalleryStore((state) => state.addToAlbum);
const removeFromAlbum = useGalleryStore((state) => state.removeFromAlbum);
const createAlbum = useGalleryStore((state) => state.createAlbum);
const [panel, setPanel] = useState<Panel>(null);
const [deleting, setDeleting] = useState(false);
const [creatingAlbum, setCreatingAlbum] = useState(false);
const [newAlbumName, setNewAlbumName] = useState("");
const barRef = useRef<HTMLDivElement>(null);
// Close any open popover when clicking outside the bar.
useEffect(() => {
const onPointerDown = (event: PointerEvent) => {
if (barRef.current?.contains(event.target as Node)) return;
setPanel(null);
};
window.addEventListener("pointerdown", onPointerDown);
return () => window.removeEventListener("pointerdown", onPointerDown);
}, []);
// Reset transient UI whenever the selection empties.
useEffect(() => {
if (selectedCount === 0) {
setPanel(null);
setNewAlbumName("");
}
}, [selectedCount]);
if (selectedCount === 0) return null;
const ids = Array.from(selectedIds);
const inAlbumView = activeView === "album" && selectedAlbumId !== null;
const togglePanel = (next: Exclude<Panel, 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 handleCreateAlbum = async () => {
const name = newAlbumName.trim();
if (!name || creatingAlbum) return;
setCreatingAlbum(true);
try {
const album = await createAlbum(name);
await addToAlbum(album.id, ids);
setNewAlbumName("");
setPanel(null);
} finally {
setCreatingAlbum(false);
}
};
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()}
>
<div className="flex items-center gap-2 px-1.5">
<span className="text-xs font-medium text-white">{selectedCount} selected</span>
{loadedCount < totalImages || loadedCount > selectedCount ? (
<button
className="text-[11px] text-gray-500 transition-colors hover:text-gray-300"
onClick={selectAllGallery}
title={loadedCount < totalImages ? "Selects loaded items only" : "Select all loaded"}
>
Select all{loadedCount < totalImages ? " loaded" : ""}
</button>
) : null}
</div>
<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" ? (
<div
data-bulk-popover
className="absolute bottom-full left-1/2 mb-2 flex -translate-x-1/2 items-center gap-1 rounded-xl border border-white/10 bg-gray-950/98 p-2 shadow-2xl backdrop-blur"
>
{Array.from({ length: 5 }, (_, index) => {
const rating = index + 1;
return (
<button
key={rating}
className="rounded-md p-1 text-white/25 transition-colors hover:bg-white/5 hover:text-amber-300"
onClick={async () => {
await bulkSetRating(rating);
setPanel(null);
}}
title={`Set ${rating} star${rating === 1 ? "" : "s"}`}
>
<svg className="h-4 w-4" 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>
);
})}
<button
className="ml-1 rounded-md border border-white/10 px-2 py-1 text-[11px] text-gray-400 transition-colors hover:bg-white/5 hover:text-white"
onClick={async () => {
await bulkSetRating(0);
setPanel(null);
}}
>
Clear
</button>
</div>
) : null}
</div>
<button className={btnIdle} onClick={() => void bulkSetFavorite(true)} title="Mark as favorite">
Favorite
</button>
<div className="relative">
<button className={panel === "album" ? btnActive : btnIdle} onClick={() => togglePanel("album")}>
Add to album
</button>
{panel === "album" ? (
<div
data-bulk-popover
className="absolute bottom-full left-1/2 mb-2 w-60 -translate-x-1/2 rounded-xl border border-white/10 bg-gray-950/98 p-2 shadow-2xl backdrop-blur"
>
<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 handlePickAlbum(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 handleCreateAlbum();
}}
>
<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={creatingAlbum}
/>
<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={creatingAlbum || !newAlbumName.trim()}
>
Add
</button>
</form>
</div>
) : 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">
<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}
title="Delete files from disk"
>
{deleting ? "Deleting…" : "Delete"}
</button>
{panel === "delete" ? (
<div
data-bulk-popover
className="absolute bottom-full left-1/2 mb-2 w-64 -translate-x-1/2 rounded-xl border border-red-500/30 bg-gray-950/98 p-3 shadow-2xl backdrop-blur"
>
<div className="mb-1 flex items-center gap-1.5 text-red-300">
<svg className="h-3.5 w-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
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>
<p className="text-xs font-semibold">Delete from disk</p>
</div>
<p className="mb-2.5 text-[11px] leading-relaxed text-gray-400">
Permanently delete {selectedCount} file{selectedCount === 1 ? "" : "s"} from your computer.
This removes the actual file{selectedCount === 1 ? "" : "s"} from disk and cannot be undone.
</p>
<div className="flex justify-end gap-1.5">
<button
className="rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] text-gray-300 transition-colors hover:bg-white/10 hover:text-white"
onClick={() => setPanel(null)}
>
Cancel
</button>
<button
className="rounded-md bg-red-500/20 px-2.5 py-1 text-[11px] font-medium text-red-300 transition-colors hover:bg-red-500/30 hover:text-red-200 disabled:opacity-50"
onClick={() => void handleDelete()}
disabled={deleting}
>
{deleting ? "Deleting…" : `Delete ${selectedCount} from disk`}
</button>
</div>
</div>
) : null}
</div>
<button
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
onClick={clearGallerySelection}
title="Clear selection"
>
<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>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { useEffect, useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { useGalleryStore } from "../store";
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.
useEffect(() => {
if (!open) return;
const onPointerDown = (event: PointerEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) setOpen(false);
};
window.addEventListener("pointerdown", onPointerDown);
return () => window.removeEventListener("pointerdown", onPointerDown);
}, [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}>
<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="absolute right-0 top-full z-30 mt-2 w-max rounded-xl border border-white/10 bg-gray-950/98 p-2.5 shadow-2xl backdrop-blur light-theme:border-gray-700/50"
>
<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="mt-2 flex items-center justify-between gap-3 border-t border-white/6 pt-2 light-theme:border-gray-700/40">
{colorBackfill && colorBackfill.total > 0 ? (
<span
className="text-[10px] text-gray-600"
title="Sampling colors from existing thumbnails — color search fills in as this runs"
>
sampling {colorBackfill.processed.toLocaleString()}/{colorBackfill.total.toLocaleString()}
</span>
) : <span />}
{isActive ? (
<button
className="shrink-0 rounded px-1 text-[11px] text-gray-500 transition-colors hover:text-gray-200"
onClick={() => setColorFilter(null)}
title="Clear color filter"
>
Clear
</button>
) : null}
</div>
) : null}
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}
+31
View File
@@ -42,6 +42,7 @@ const DEMO_UPDATE_VERSION = "0.2.0";
export function DemoPanel() { export function DemoPanel() {
const folders = useGalleryStore((state) => state.folders); const folders = useGalleryStore((state) => state.folders);
const appVersion = useGalleryStore((state) => state.appVersion);
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const downloadTimer = useRef<number | null>(null); const downloadTimer = useRef<number | null>(null);
@@ -160,6 +161,18 @@ export function DemoPanel() {
}); });
}; };
// --- 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; if (!open) return null;
const injectBtn = const injectBtn =
@@ -215,6 +228,24 @@ export function DemoPanel() {
Reset updater state Reset updater state
</button> </button>
</div> </div>
<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">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> </div>
); );
} }
+46 -9
View File
@@ -1,8 +1,8 @@
import { useRef, useState } from "react"; import { useRef, useState } from "react";
import { useVirtualizer } from "@tanstack/react-virtual"; import { useVirtualizer } from "@tanstack/react-virtual";
import { convertFileSrc } from "@tauri-apps/api/core";
import { DuplicateGroup, useGalleryStore } from "../store"; import { DuplicateGroup, useGalleryStore } from "../store";
import { FolderScopeDropdown } from "./FolderScopeDropdown"; import { FolderScopeDropdown } from "./FolderScopeDropdown";
import { mediaSrc } from "../lib/mediaSrc";
function formatBytes(bytes: number): string { function formatBytes(bytes: number): string {
if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toFixed(1)} GB`; if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toFixed(1)} GB`;
@@ -68,7 +68,7 @@ function DuplicateGroupCard({ group }: { group: DuplicateGroup }) {
<div className="flex flex-wrap gap-3"> <div className="flex flex-wrap gap-3">
{group.images.map((image) => { {group.images.map((image) => {
const isSelected = selectedIds.has(image.id); const isSelected = selectedIds.has(image.id);
const src = image.thumbnail_path ? convertFileSrc(image.thumbnail_path) : null; const src = mediaSrc(image.thumbnail_path);
return ( return (
<button <button
key={image.id} key={image.id}
@@ -129,6 +129,7 @@ export function DuplicateFinder() {
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates); const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates);
const [deleting, setDeleting] = useState(false); const [deleting, setDeleting] = useState(false);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const [deleteResult, setDeleteResult] = useState<string | null>(null); const [deleteResult, setDeleteResult] = useState<string | null>(null);
// Virtualize the group list so a large result set (e.g. thousands of pairs) // Virtualize the group list so a large result set (e.g. thousands of pairs)
@@ -153,6 +154,7 @@ export function DuplicateFinder() {
const handleDelete = async () => { const handleDelete = async () => {
setDeleting(true); setDeleting(true);
setConfirmingDelete(false);
setDeleteResult(null); setDeleteResult(null);
try { try {
const deleted = await deleteSelectedDuplicates(); const deleted = await deleteSelectedDuplicates();
@@ -222,13 +224,48 @@ export function DuplicateFinder() {
> >
Deselect all Deselect all
</button> </button>
<button <div className="relative">
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" <button
onClick={handleDelete} 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"
disabled={deleting} onClick={() => setConfirmingDelete((v) => !v)}
> disabled={deleting}
{deleting ? "Deleting…" : `Delete ${selectedCount} file${selectedCount === 1 ? "" : "s"}`} >
</button> {deleting ? "Deleting…" : `Delete ${selectedCount} file${selectedCount === 1 ? "" : "s"}`}
</button>
{confirmingDelete && !deleting ? (
<>
{/* Click-away backdrop */}
<div className="fixed inset-0 z-40" onClick={() => setConfirmingDelete(false)} />
<div className="absolute right-0 top-full z-50 mt-2 w-72 rounded-xl border border-red-500/30 bg-gray-950/98 p-3 text-left shadow-2xl backdrop-blur">
<div className="mb-1 flex items-center gap-1.5 text-red-300">
<svg className="h-3.5 w-3.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
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>
<p className="text-xs font-semibold">Delete from disk</p>
</div>
<p className="mb-2.5 text-[11px] leading-relaxed text-gray-400">
Permanently delete {selectedCount} file{selectedCount === 1 ? "" : "s"} from your computer.
This removes the actual file{selectedCount === 1 ? "" : "s"} from disk and cannot be undone.
</p>
<div className="flex justify-end gap-1.5">
<button
className="rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] text-gray-300 transition-colors hover:bg-white/10 hover:text-white"
onClick={() => setConfirmingDelete(false)}
>
Cancel
</button>
<button
className="rounded-md bg-red-500/20 px-2.5 py-1 text-[11px] font-medium text-red-300 transition-colors hover:bg-red-500/30 hover:text-red-200"
onClick={handleDelete}
>
Delete {selectedCount} from disk
</button>
</div>
</div>
</>
) : null}
</div>
</> </>
) : null} ) : null}
<button <button
File diff suppressed because it is too large Load Diff
+82 -32
View File
@@ -1,7 +1,9 @@
import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from "react"; import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from "react";
import { useVirtualizer } from "@tanstack/react-virtual"; import { useVirtualizer } from "@tanstack/react-virtual";
import { convertFileSrc } from "@tauri-apps/api/core";
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from "../store"; import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from "../store";
import { BulkActionBar } from "./BulkActionBar";
import { Tooltip } from "./Tooltip";
import { mediaSrc } from "../lib/mediaSrc";
const GAP = 6; const GAP = 6;
@@ -30,8 +32,7 @@ export function ContextMenu({
}) { }) {
const openImage = useGalleryStore((state) => state.openImage); const openImage = useGalleryStore((state) => state.openImage);
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails); const updateImageDetails = useGalleryStore((state) => state.updateImageDetails);
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages); const findSimilar = useGalleryStore((state) => state.findSimilar);
const similarScope = useGalleryStore((state) => state.similarScope);
const canFindSimilar = image.embedding_status === "ready"; const canFindSimilar = image.embedding_status === "ready";
return ( return (
@@ -59,9 +60,9 @@ export function ContextMenu({
? "text-gray-200 hover:bg-white/5 hover:text-white" ? "text-gray-200 hover:bg-white/5 hover:text-white"
: "text-gray-600 cursor-not-allowed" : "text-gray-600 cursor-not-allowed"
}`} }`}
onClick={async () => { onClick={() => {
if (!canFindSimilar) return; if (!canFindSimilar) return;
await loadSimilarImages(image.id, similarScope === "current_folder" ? image.folder_id : null, true, image.folder_id); findSimilar(image.id, image.folder_id);
onClose(); onClose();
}} }}
disabled={!canFindSimilar} disabled={!canFindSimilar}
@@ -112,24 +113,70 @@ export function ImageTile({
}: { }: {
image: ImageRecord; image: ImageRecord;
onClick: () => void; onClick: () => void;
onContextMenu: (event: React.MouseEvent<HTMLButtonElement>) => void; onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void;
}) { }) {
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
const [errored, setErrored] = useState(false); const [errored, setErrored] = useState(false);
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages); const findSimilar = useGalleryStore((state) => state.findSimilar);
const similarScope = useGalleryStore((state) => state.similarScope); const selected = useGalleryStore((state) => state.gallerySelectedIds.has(image.id));
const selectionActive = useGalleryStore((state) => state.gallerySelectedIds.size > 0);
const toggleGallerySelected = useGalleryStore((state) => state.toggleGallerySelected);
const canFindSimilar = image.embedding_status === "ready"; const canFindSimilar = image.embedding_status === "ready";
const src = image.thumbnail_path ? convertFileSrc(image.thumbnail_path) : null; const src = mediaSrc(image.thumbnail_path);
return ( return (
<button <Tooltip label={image.filename} delay={500} block followCursor>
className="media-dark-surface group relative overflow-hidden rounded-xl bg-white/[0.04] text-left focus:outline-none" <div
className={`media-dark-surface group relative overflow-hidden rounded-xl bg-white/[0.04] text-left focus:outline-none transition-shadow ${
selected ? "ring-2 ring-inset ring-blue-400/80" : ""
}`}
style={{ width: "100%", aspectRatio: "1 / 1" }} style={{ width: "100%", aspectRatio: "1 / 1" }}
onClick={onClick}
onContextMenu={onContextMenu} onContextMenu={onContextMenu}
title={image.filename}
> >
{/* Full-tile click target — opens, or toggles selection while selecting.
A real button (over the non-interactive tile div) keeps it keyboard-
accessible without nesting buttons. */}
<button
type="button"
className="absolute inset-0 z-10 cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/80"
aria-label={`Open ${image.filename}`}
onClick={(event) => {
event.stopPropagation();
if (selectionActive) toggleGallerySelected(image.id);
else onClick();
}}
onDoubleClick={(event) => {
event.stopPropagation();
onClick();
}}
/>
{/* Selection corner — a top-left zone that reveals the checkbox only when
hovered (not the whole tile) and toggles selection on click. The
checkbox stays visible once the item is selected. */}
<button
type="button"
role="checkbox"
aria-checked={selected}
aria-label={selected ? "Deselect" : "Select"}
className="group/cb absolute top-0 left-0 z-20 h-11 w-11 cursor-pointer"
onClick={(event) => {
event.stopPropagation();
toggleGallerySelected(image.id);
}}
>
<div
className={`absolute top-2 left-2 flex h-5 w-5 items-center justify-center rounded-full border transition-all duration-150 ${
selected
? "border-blue-400 bg-blue-500 text-white opacity-100"
: "border-white/70 bg-black/40 text-transparent opacity-0 backdrop-blur-sm group-hover/cb:opacity-100"
}`}
>
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
</svg>
</div>
</button>
{/* Image / placeholder */} {/* Image / placeholder */}
{src && !errored ? ( {src && !errored ? (
<> <>
@@ -173,6 +220,17 @@ export function ImageTile({
{/* Persistent badges — only shown when meaningful */} {/* Persistent badges — only shown when meaningful */}
<div className="absolute top-2 right-2 flex flex-col items-end gap-1 pointer-events-none"> <div className="absolute top-2 right-2 flex flex-col items-end gap-1 pointer-events-none">
{image.embedding_status === "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"
title={image.embedding_error ?? "Embedding failed"}
>
<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>
)}
{image.favorite && ( {image.favorite && (
<div className="rounded-full bg-black/50 p-1 text-rose-400 backdrop-blur-sm"> <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"> <svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
@@ -196,21 +254,6 @@ export function ImageTile({
)} )}
</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 */} {/* 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" /> <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" />
@@ -230,7 +273,7 @@ export function ImageTile({
<span /> <span />
)} )}
<button <button
className={`rounded-md px-2 py-0.5 text-[10px] transition-colors pointer-events-auto backdrop-blur-sm ${ className={`relative z-20 rounded-md px-2 py-0.5 text-[10px] transition-colors pointer-events-auto backdrop-blur-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/80 ${
canFindSimilar canFindSimilar
? "bg-white/10 text-white/80 hover:bg-white/20 hover:text-white" ? "bg-white/10 text-white/80 hover:bg-white/20 hover:text-white"
: "bg-white/5 text-white/30 cursor-not-allowed" : "bg-white/5 text-white/30 cursor-not-allowed"
@@ -238,7 +281,7 @@ export function ImageTile({
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
if (!canFindSimilar) return; if (!canFindSimilar) return;
void loadSimilarImages(image.id, similarScope === "current_folder" ? image.folder_id : null, true, image.folder_id); findSimilar(image.id, image.folder_id);
}} }}
disabled={!canFindSimilar} disabled={!canFindSimilar}
> >
@@ -246,7 +289,8 @@ export function ImageTile({
</button> </button>
</div> </div>
</div> </div>
</button> </div>
</Tooltip>
); );
} }
@@ -338,7 +382,8 @@ export function Gallery() {
}, []); }, []);
return ( return (
<div ref={parentRef} className="relative flex-1 overflow-y-auto overflow-x-hidden min-h-0 bg-gray-950"> <div className="relative flex-1 min-h-0">
<div ref={parentRef} className="absolute inset-0 overflow-y-auto overflow-x-hidden bg-gray-950">
{images.length === 0 && loadingImages ? ( {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="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="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 min-w-72">
@@ -448,5 +493,10 @@ export function Gallery() {
/> />
) : null} ) : null}
</div> </div>
{/* Pinned to the bottom of the gallery viewport — outside the scroll
container so it stays put while the grid scrolls. */}
<BulkActionBar />
</div>
); );
} }
+174 -20
View File
@@ -1,9 +1,10 @@
import { useEffect, useCallback, useRef, useState } from "react"; import { useEffect, useCallback, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion"; import { motion, AnimatePresence } from "framer-motion";
import { convertFileSrc } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { revealItemInDir } from "@tauri-apps/plugin-opener"; import { revealItemInDir } from "@tauri-apps/plugin-opener";
import { useGalleryStore, ImageTag, AiRating } from "../store"; import { useGalleryStore, ImageTag, ImageExif, AiRating } from "../store";
import { VideoPlayer } from "./VideoPlayer"; import { VideoPlayer } from "./VideoPlayer";
import { mediaSrc } from "../lib/mediaSrc";
function formatBytes(bytes: number): string { function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`; if (bytes < 1024) return `${bytes} B`;
@@ -144,15 +145,18 @@ export function Lightbox() {
const closeImage = useGalleryStore((state) => state.closeImage); const closeImage = useGalleryStore((state) => state.closeImage);
const images = useGalleryStore((state) => state.images); const images = useGalleryStore((state) => state.images);
const openImage = useGalleryStore((state) => state.openImage); const openImage = useGalleryStore((state) => state.openImage);
const loadSimilarImages = useGalleryStore((state) => state.loadSimilarImages); const findSimilar = useGalleryStore((state) => state.findSimilar);
const loadSimilarByRegion = useGalleryStore((state) => state.loadSimilarByRegion); const findSimilarByRegion = useGalleryStore((state) => state.findSimilarByRegion);
const similarScope = useGalleryStore((state) => state.similarScope);
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails); const updateImageDetails = useGalleryStore((state) => state.updateImageDetails);
const getImageTags = useGalleryStore((state) => state.getImageTags); const getImageTags = useGalleryStore((state) => state.getImageTags);
const addUserTag = useGalleryStore((state) => state.addUserTag); const addUserTag = useGalleryStore((state) => state.addUserTag);
const removeTag = useGalleryStore((state) => state.removeTag); const removeTag = useGalleryStore((state) => state.removeTag);
const taggerModelStatus = useGalleryStore((state) => state.taggerModelStatus); const taggerModelStatus = useGalleryStore((state) => state.taggerModelStatus);
const queueTaggingForImage = useGalleryStore((state) => state.queueTaggingForImage); const queueTaggingForImage = useGalleryStore((state) => state.queueTaggingForImage);
const albums = useGalleryStore((state) => state.albums);
const addToAlbum = useGalleryStore((state) => state.addToAlbum);
const createAlbum = useGalleryStore((state) => state.createAlbum);
const getImageExif = useGalleryStore((state) => state.getImageExif);
// Tracks the image id that is currently displayed, used to discard async // Tracks the image id that is currently displayed, used to discard async
// tag mutations that resolve after the user has navigated to another image. // tag mutations that resolve after the user has navigated to another image.
@@ -164,12 +168,17 @@ export function Lightbox() {
const [isPanning, setIsPanning] = useState(false); const [isPanning, setIsPanning] = useState(false);
const lastPanPointRef = useRef({ x: 0, y: 0 }); const lastPanPointRef = useRef({ x: 0, y: 0 });
const [imageTags, setImageTags] = useState<ImageTag[]>([]); const [imageTags, setImageTags] = useState<ImageTag[]>([]);
const [imageExif, setImageExif] = useState<ImageExif | null>(null);
const [tagInput, setTagInput] = useState(""); const [tagInput, setTagInput] = useState("");
const [tagAdding, setTagAdding] = useState(false); const [tagAdding, setTagAdding] = useState(false);
const [tagsExpanded, setTagsExpanded] = useState(false); const [tagsExpanded, setTagsExpanded] = useState(false);
const [taggingQueued, setTaggingQueued] = useState(false); const [taggingQueued, setTaggingQueued] = useState(false);
// Region selection state // Region selection state
const [albumMenuOpen, setAlbumMenuOpen] = useState(false);
const [albumAddedTo, setAlbumAddedTo] = useState<number | null>(null);
const [newAlbumName, setNewAlbumName] = useState("");
const [albumAdding, setAlbumAdding] = useState(false);
const [regionSelectMode, setRegionSelectMode] = useState(false); const [regionSelectMode, setRegionSelectMode] = useState(false);
const [isDragging, setIsDragging] = useState(false); const [isDragging, setIsDragging] = useState(false);
const [dragRect, setDragRect] = useState<DragRect | null>(null); const [dragRect, setDragRect] = useState<DragRect | null>(null);
@@ -215,6 +224,7 @@ export function Lightbox() {
useEffect(() => { useEffect(() => {
setView(IDENTITY_VIEW); setView(IDENTITY_VIEW);
setImageTags([]); setImageTags([]);
setImageExif(null);
setTagInput(""); setTagInput("");
setTagsExpanded(false); setTagsExpanded(false);
setTaggingQueued(false); setTaggingQueued(false);
@@ -233,6 +243,20 @@ export function Lightbox() {
return () => { cancelled = true; }; return () => { cancelled = true; };
}, [selectedImage?.id, selectedImage?.ai_tagged_at, getImageTags]); }, [selectedImage?.id, selectedImage?.ai_tagged_at, getImageTags]);
// EXIF is read on demand from the file (not stored), so it works on every
// already-indexed image without a reindex. Only meaningful for images.
useEffect(() => {
if (!selectedImage || selectedImage.media_kind !== "image") {
setImageExif(null);
return;
}
let cancelled = false;
void getImageExif(selectedImage.id)
.then((exif) => { if (!cancelled) setImageExif(exif); })
.catch(() => { if (!cancelled) setImageExif(null); });
return () => { cancelled = true; };
}, [selectedImage?.id, selectedImage?.media_kind, getImageExif]);
// Reset the queued state once the worker finishes so the button is usable again // Reset the queued state once the worker finishes so the button is usable again
useEffect(() => { useEffect(() => {
if (selectedImage?.ai_tagged_at) setTaggingQueued(false); if (selectedImage?.ai_tagged_at) setTaggingQueued(false);
@@ -361,12 +385,10 @@ export function Lightbox() {
exitRegionMode(); exitRegionMode();
setRegionSearching(true); setRegionSearching(true);
const folderId = void findSimilarByRegion(selectedImage.id, crop, selectedImage.folder_id)
similarScope === "current_folder" ? selectedImage.folder_id : null;
void loadSimilarByRegion(selectedImage.id, crop, folderId, selectedImage.folder_id)
.finally(() => setRegionSearching(false)); .finally(() => setRegionSearching(false));
}, },
[isPanning, isDragging, dragRect, selectedImage, similarScope, loadSimilarByRegion, exitRegionMode], [isPanning, isDragging, dragRect, selectedImage, findSimilarByRegion, exitRegionMode],
); );
// Build the CSS rect for the selection overlay (viewport-relative) // Build the CSS rect for the selection overlay (viewport-relative)
@@ -454,12 +476,12 @@ export function Lightbox() {
transition={{ duration: 0.12 }} transition={{ duration: 0.12 }}
> >
{selectedImage.media_kind === "video" ? ( {selectedImage.media_kind === "video" ? (
<VideoPlayer src={convertFileSrc(selectedImage.path)} /> <VideoPlayer src={mediaSrc(selectedImage.path) ?? ""} />
) : ( ) : (
<> <>
<img <img
ref={imgRef} ref={imgRef}
src={convertFileSrc(selectedImage.path)} src={mediaSrc(selectedImage.path) ?? ""}
alt={selectedImage.filename} alt={selectedImage.filename}
className="max-w-full rounded-2xl shadow-2xl" className="max-w-full rounded-2xl shadow-2xl"
draggable={false} draggable={false}
@@ -496,7 +518,7 @@ export function Lightbox() {
</AnimatePresence> </AnimatePresence>
</div> </div>
<div className="lightbox-panel flex w-72 shrink-0 flex-col border-l border-white/5 bg-gray-900/95"> <div className="lightbox-panel flex w-64 shrink-0 flex-col border-l border-white/5 bg-gray-900/95 lg:w-72">
<div className="flex shrink-0 items-center justify-between px-5 pt-5 pb-4"> <div className="flex shrink-0 items-center justify-between px-5 pt-5 pb-4">
<div className="min-w-0"> <div className="min-w-0">
<p className="truncate text-sm font-medium text-white">{selectedImage.filename}</p> <p className="truncate text-sm font-medium text-white">{selectedImage.filename}</p>
@@ -513,18 +535,25 @@ export function Lightbox() {
</svg> </svg>
</button> </button>
<button <button
className={`rounded-full border px-3 py-1.5 text-xs ${ className={`flex items-center gap-1.5 rounded-full border px-2 py-1.5 text-xs lg:px-3 ${
canFindSimilar canFindSimilar
? "border-white/10 bg-white/5 text-gray-300 hover:text-white" ? "border-white/10 bg-white/5 text-gray-300 hover:text-white"
: "border-white/5 bg-white/[0.03] text-gray-600 cursor-not-allowed" : "border-white/5 bg-white/[0.03] text-gray-600 cursor-not-allowed"
}`} }`}
onClick={() => { onClick={() => {
if (!canFindSimilar) return; if (!canFindSimilar) return;
void loadSimilarImages(selectedImage.id, similarScope === "current_folder" ? selectedImage.folder_id : null, true, selectedImage.folder_id); void findSimilar(selectedImage.id, selectedImage.folder_id);
}} }}
disabled={!canFindSimilar} disabled={!canFindSimilar}
title={canFindSimilar ? "Find similar images" : "Embeddings not ready"}
> >
{canFindSimilar ? "Similar" : "Embeddings not ready"} <svg className="h-4 w-4 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.6}
d="M13 3l1.55 4.65L19 9.2l-4.45 1.55L13 15.4l-1.55-4.65L7 9.2l4.45-1.55L13 3z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.6}
d="M5.5 14.5l.8 2.2 2.2.8-2.2.8-.8 2.2-.8-2.2L2.5 17.5l2.2-.8.8-2.2z" />
</svg>
<span className="hidden lg:inline">{canFindSimilar ? "Similar" : "Embeddings not ready"}</span>
</button> </button>
</div> </div>
<button className="rounded p-1 text-gray-400 hover:text-white" onClick={closeImage}> <button className="rounded p-1 text-gray-400 hover:text-white" onClick={closeImage}>
@@ -582,7 +611,8 @@ export function Lightbox() {
)} )}
<div className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 space-y-4 text-sm"> <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-4 space-y-4 text-sm">
<div> <div className="grid grid-cols-2 gap-x-6 gap-y-4">
<div className="col-span-2">
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Rating</p> <p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Rating</p>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
{Array.from({ length: 5 }, (_, index) => { {Array.from({ length: 5 }, (_, index) => {
@@ -645,7 +675,7 @@ export function Lightbox() {
</div> </div>
{selectedImage.metadata_error ? ( {selectedImage.metadata_error ? (
<div> <div className="col-span-2">
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Metadata</p> <p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Metadata</p>
<p className="text-amber-300">{selectedImage.metadata_error}</p> <p className="text-amber-300">{selectedImage.metadata_error}</p>
</div> </div>
@@ -663,18 +693,19 @@ export function Lightbox() {
<p className="text-white">{formatBytes(selectedImage.file_size)}</p> <p className="text-white">{formatBytes(selectedImage.file_size)}</p>
</div> </div>
<div> <div className="col-span-2">
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Modified</p> <p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Modified</p>
<p className="text-white">{formatDate(selectedImage.modified_at)}</p> <p className="text-white">{formatDate(selectedImage.modified_at)}</p>
</div> </div>
<div> <div className="col-span-2">
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Embedding</p> <p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Embedding</p>
<p className="text-white">{embeddingLabel(selectedImage.embedding_status, selectedImage.embedding_model)}</p> <p className="text-white">{embeddingLabel(selectedImage.embedding_status, selectedImage.embedding_model)}</p>
{selectedImage.embedding_error ? ( {selectedImage.embedding_error ? (
<p className="mt-1 text-xs text-amber-300">{selectedImage.embedding_error}</p> <p className="mt-1 text-xs text-amber-300">{selectedImage.embedding_error}</p>
) : null} ) : null}
</div> </div>
</div>
<div> <div>
<div className="mb-2 flex items-center justify-between"> <div className="mb-2 flex items-center justify-between">
@@ -780,6 +811,129 @@ export function Lightbox() {
</form> </form>
</div> </div>
<div className="relative">
<div className="mb-2 flex items-center justify-between">
<p className="text-xs uppercase tracking-wider text-gray-500">Albums</p>
<button
className="rounded-md border border-white/10 bg-white/5 px-2 py-0.5 text-[10px] text-gray-400 transition-colors hover:bg-white/10 hover:text-white"
onClick={() => { setAlbumMenuOpen((v) => !v); setAlbumAddedTo(null); }}
>
Add to album
</button>
</div>
{albumMenuOpen ? (
<div className="rounded-lg border border-white/10 bg-white/[0.03] p-1.5">
<div className="max-h-40 overflow-y-auto">
{albums.length === 0 ? (
<p className="px-2 py-1.5 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 text-left text-xs text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
onClick={() => {
if (albumAdding) return;
setAlbumAdding(true);
void addToAlbum(album.id, [selectedImage.id])
.then(() => setAlbumAddedTo(album.id))
.catch(() => undefined)
.finally(() => setAlbumAdding(false));
}}
disabled={albumAdding}
>
<span className="truncate">{album.name}</span>
{albumAddedTo === album.id ? (
<span className="shrink-0 text-[10px] text-emerald-400">Added</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-1.5"
onSubmit={(e) => {
e.preventDefault();
const name = newAlbumName.trim();
if (!name || albumAdding) return;
setAlbumAdding(true);
void createAlbum(name)
.then(async (album) => {
await addToAlbum(album.id, [selectedImage.id]);
setAlbumAddedTo(album.id);
setNewAlbumName("");
})
.catch(() => undefined)
.finally(() => setAlbumAdding(false));
}}
>
<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={(e) => setNewAlbumName(e.target.value)}
disabled={albumAdding}
/>
<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={albumAdding || !newAlbumName.trim()}
>
Add
</button>
</form>
</div>
) : null}
</div>
{imageExif &&
(imageExif.make ||
imageExif.model ||
imageExif.lens ||
imageExif.f_number ||
imageExif.exposure_time ||
imageExif.iso ||
imageExif.focal_length ||
(imageExif.gps_lat != null && imageExif.gps_lon != null)) ? (
<div>
<p className="mb-2 text-xs uppercase tracking-wider text-gray-500">Camera</p>
<div className="space-y-1.5">
{imageExif.make || imageExif.model ? (
<p className="text-sm text-white">
{[imageExif.make, imageExif.model].filter(Boolean).join(" ")}
</p>
) : null}
{imageExif.lens ? <p className="text-xs text-gray-400">{imageExif.lens}</p> : null}
{imageExif.f_number || imageExif.exposure_time || imageExif.iso || imageExif.focal_length ? (
<div className="flex flex-wrap gap-x-3 gap-y-1 text-xs text-gray-400">
{imageExif.f_number ? <span>{imageExif.f_number}</span> : null}
{imageExif.exposure_time ? <span>{imageExif.exposure_time}</span> : null}
{imageExif.iso ? <span>ISO {imageExif.iso}</span> : null}
{imageExif.focal_length ? <span>{imageExif.focal_length}</span> : null}
</div>
) : null}
{imageExif.gps_lat != null && imageExif.gps_lon != null ? (
<button
className="inline-flex items-center gap-1 text-xs text-sky-400 transition-colors hover:text-sky-300"
title="Open location in your browser"
onClick={() =>
void invoke("open_map_location", {
params: { lat: imageExif.gps_lat, lon: imageExif.gps_lon },
})
}
>
{imageExif.gps_lat.toFixed(5)}, {imageExif.gps_lon.toFixed(5)}
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</button>
) : null}
</div>
</div>
) : null}
<div> <div>
<div className="mb-1 flex items-center justify-between"> <div className="mb-1 flex items-center justify-between">
<p className="text-xs uppercase tracking-wider text-gray-500">Path</p> <p className="text-xs uppercase tracking-wider text-gray-500">Path</p>
@@ -805,7 +959,7 @@ export function Lightbox() {
</div> </div>
<button <button
className="absolute right-80 top-1/2 z-10 -translate-y-1/2 rounded-full bg-white/10 p-3 text-white transition-colors hover:bg-white/20 disabled:opacity-20" className="absolute right-72 top-1/2 z-10 -translate-y-1/2 rounded-full bg-white/10 p-3 text-white transition-colors hover:bg-white/20 disabled:opacity-20 lg:right-80"
disabled={currentIndex >= images.length - 1 || regionSelectMode} disabled={currentIndex >= images.length - 1 || regionSelectMode}
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
+146 -7
View File
@@ -1,7 +1,8 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { AppTheme, CleanupOrphanedThumbnailsResult, DatabaseInfo, OrphanedThumbnailsInfo, TaggerAcceleration, TaggingQueueScope, VacuumResult, useGalleryStore } from "../store"; import { AppTheme, CleanupOrphanedThumbnailsResult, DatabaseInfo, OrphanedThumbnailsInfo, TaggerAcceleration, TaggerModel, TaggingQueueScope, VacuumResult, useGalleryStore } from "../store";
import { FfmpegStatusRow } from "./onboarding/StepWelcome"; import { FfmpegStatusRow } from "./onboarding/StepWelcome";
import { ThemedDropdown } from "./ThemedDropdown"; import { ThemedDropdown } from "./ThemedDropdown";
import { getChangelogForVersion } from "../changelog";
type SettingsSection = "workspace" | "general"; type SettingsSection = "workspace" | "general";
@@ -99,6 +100,44 @@ function ScopeButton({ scope, current, onSelect, children }: {
); );
} }
// Display metadata for each selectable tagging model.
const TAGGER_MODELS: Record<TaggerModel, { name: string; tab: string; description: string }> = {
wd: {
name: "WD SwinV2 Tagger v3",
tab: "WD (anime)",
description:
"Anime-focused vision model by SmilingWolf. Generates booru-style tags with configurable confidence thresholds.",
},
joytag: {
name: "JoyTag",
tab: "JoyTag (general)",
description:
"Booru-schema tagger that also handles photographic content and is strong on NSFW concepts. The explicitness rating is derived from its tags.",
},
};
function TaggerModelButton({ model, current, onSelect, children }: {
model: TaggerModel;
current: TaggerModel;
onSelect: (model: TaggerModel) => void;
children: React.ReactNode;
}) {
const active = model === 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(model)}
>
{children}
</button>
);
}
function TaggerAccelerationButton({ acceleration, current, onSelect, children }: { function TaggerAccelerationButton({ acceleration, current, onSelect, children }: {
acceleration: TaggerAcceleration; acceleration: TaggerAcceleration;
current: TaggerAcceleration; current: TaggerAcceleration;
@@ -128,6 +167,8 @@ export function SettingsModal() {
const [taggerClearing, setTaggerClearing] = useState(false); const [taggerClearing, setTaggerClearing] = useState(false);
const [taggerAccelerationSaving, setTaggerAccelerationSaving] = useState(false); const [taggerAccelerationSaving, setTaggerAccelerationSaving] = useState(false);
const [taggerAccelerationError, setTaggerAccelerationError] = useState<string | null>(null); const [taggerAccelerationError, setTaggerAccelerationError] = useState<string | null>(null);
const [taggerModelSwitching, setTaggerModelSwitching] = useState(false);
const [taggerModelSwitchError, setTaggerModelSwitchError] = useState<string | null>(null);
const [taggerThresholdDraft, setTaggerThresholdDraft] = useState<string | null>(null); const [taggerThresholdDraft, setTaggerThresholdDraft] = useState<string | null>(null);
const [taggerThresholdSaving, setTaggerThresholdSaving] = useState(false); const [taggerThresholdSaving, setTaggerThresholdSaving] = useState(false);
const [taggerThresholdError, setTaggerThresholdError] = useState<string | null>(null); const [taggerThresholdError, setTaggerThresholdError] = useState<string | null>(null);
@@ -172,6 +213,9 @@ export function SettingsModal() {
const deleteTaggerModel = useGalleryStore((state) => state.deleteTaggerModel); const deleteTaggerModel = useGalleryStore((state) => state.deleteTaggerModel);
const loadTaggerAcceleration = useGalleryStore((state) => state.loadTaggerAcceleration); const loadTaggerAcceleration = useGalleryStore((state) => state.loadTaggerAcceleration);
const setTaggerAcceleration = useGalleryStore((state) => state.setTaggerAcceleration); const setTaggerAcceleration = useGalleryStore((state) => state.setTaggerAcceleration);
const taggerModel = useGalleryStore((state) => state.taggerModel);
const loadTaggerModel = useGalleryStore((state) => state.loadTaggerModel);
const setTaggerModel = useGalleryStore((state) => state.setTaggerModel);
const loadTaggerThreshold = useGalleryStore((state) => state.loadTaggerThreshold); const loadTaggerThreshold = useGalleryStore((state) => state.loadTaggerThreshold);
const setTaggerThreshold = useGalleryStore((state) => state.setTaggerThreshold); const setTaggerThreshold = useGalleryStore((state) => state.setTaggerThreshold);
const loadTaggerBatchSize = useGalleryStore((state) => state.loadTaggerBatchSize); const loadTaggerBatchSize = useGalleryStore((state) => state.loadTaggerBatchSize);
@@ -184,20 +228,26 @@ export function SettingsModal() {
const openAppDataFolder = useGalleryStore((state) => state.openAppDataFolder); const openAppDataFolder = useGalleryStore((state) => state.openAppDataFolder);
const notificationsPaused = useGalleryStore((state) => state.notificationsPaused); const notificationsPaused = useGalleryStore((state) => state.notificationsPaused);
const setNotificationsPaused = useGalleryStore((state) => state.setNotificationsPaused); const setNotificationsPaused = useGalleryStore((state) => state.setNotificationsPaused);
const workerPausesPersist = useGalleryStore((state) => state.workerPausesPersist);
const setWorkerPausesPersist = useGalleryStore((state) => state.setWorkerPausesPersist);
const getDatabaseInfo = useGalleryStore((state) => state.getDatabaseInfo); const getDatabaseInfo = useGalleryStore((state) => state.getDatabaseInfo);
const vacuumDatabase = useGalleryStore((state) => state.vacuumDatabase); const vacuumDatabase = useGalleryStore((state) => state.vacuumDatabase);
const rebuildSemanticIndex = useGalleryStore((state) => state.rebuildSemanticIndex); const rebuildSemanticIndex = useGalleryStore((state) => state.rebuildSemanticIndex);
const getOrphanedThumbnailsInfo = useGalleryStore((state) => state.getOrphanedThumbnailsInfo); const getOrphanedThumbnailsInfo = useGalleryStore((state) => state.getOrphanedThumbnailsInfo);
const cleanupOrphanedThumbnails = useGalleryStore((state) => state.cleanupOrphanedThumbnails); const cleanupOrphanedThumbnails = useGalleryStore((state) => state.cleanupOrphanedThumbnails);
const appVersion = useGalleryStore((state) => state.appVersion); const appVersion = useGalleryStore((state) => state.appVersion);
const buildVariant = useGalleryStore((state) => state.buildVariant);
const updateStatus = useGalleryStore((state) => state.updateStatus); const updateStatus = useGalleryStore((state) => state.updateStatus);
const updateVersion = useGalleryStore((state) => state.updateVersion); const updateVersion = useGalleryStore((state) => state.updateVersion);
const updateProgress = useGalleryStore((state) => state.updateProgress);
const updateError = useGalleryStore((state) => state.updateError); const updateError = useGalleryStore((state) => state.updateError);
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates); const checkForUpdates = useGalleryStore((state) => state.checkForUpdates);
const installUpdate = useGalleryStore((state) => state.installUpdate); const installUpdate = useGalleryStore((state) => state.installUpdate);
const openWhatsNew = useGalleryStore((state) => state.openWhatsNew);
const openOnboarding = useGalleryStore((state) => state.openOnboarding); const openOnboarding = useGalleryStore((state) => state.openOnboarding);
const theme = useGalleryStore((state) => state.theme); const theme = useGalleryStore((state) => state.theme);
const setTheme = useGalleryStore((state) => state.setTheme); const setTheme = useGalleryStore((state) => state.setTheme);
const openTagManager = useGalleryStore((state) => state.openTagManager);
const lightboxAutoplay = useGalleryStore((state) => state.lightboxAutoplay); const lightboxAutoplay = useGalleryStore((state) => state.lightboxAutoplay);
const setLightboxAutoplay = useGalleryStore((state) => state.setLightboxAutoplay); const setLightboxAutoplay = useGalleryStore((state) => state.setLightboxAutoplay);
const lightboxAutoMute = useGalleryStore((state) => state.lightboxAutoMute); const lightboxAutoMute = useGalleryStore((state) => state.lightboxAutoMute);
@@ -206,6 +256,7 @@ export function SettingsModal() {
useEffect(() => { useEffect(() => {
if (!settingsOpen) return; if (!settingsOpen) return;
void loadTaggerModelStatus(); void loadTaggerModelStatus();
void loadTaggerModel();
void loadTaggerAcceleration(); void loadTaggerAcceleration();
void loadTaggerThreshold(); void loadTaggerThreshold();
void loadTaggerBatchSize(); void loadTaggerBatchSize();
@@ -217,7 +268,7 @@ export function SettingsModal() {
}; };
window.addEventListener("keydown", handleKeyDown); window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown);
}, [settingsOpen, loadTaggerModelStatus, loadTaggerAcceleration, loadTaggerThreshold, loadTaggerBatchSize, loadTaggingQueueScope, loadTaggingQueueFolderIds, setSettingsOpen]); }, [settingsOpen, loadTaggerModelStatus, loadTaggerModel, loadTaggerAcceleration, loadTaggerThreshold, loadTaggerBatchSize, loadTaggingQueueScope, loadTaggingQueueFolderIds, setSettingsOpen]);
useEffect(() => { useEffect(() => {
if (!settingsOpen || activeSection !== "general") return; if (!settingsOpen || activeSection !== "general") return;
@@ -361,10 +412,39 @@ export function SettingsModal() {
{activeSection === "workspace" ? ( {activeSection === "workspace" ? (
<div className="mt-8 space-y-9"> <div className="mt-8 space-y-9">
<SettingsGroup title="Model"> <SettingsGroup title="Model">
<SettingsItem label="Tagging model" description="Choose which model generates tags. JoyTag suits photos and NSFW; WD is anime-focused. Switching may require a one-time download.">
<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">
{(["wd", "joytag"] as const).map((model) => (
<TaggerModelButton
key={model}
model={model}
current={taggerModel}
onSelect={(nextModel) => {
if (nextModel === taggerModel) return;
setTaggerModelSwitching(true);
setTaggerModelSwitchError(null);
void setTaggerModel(nextModel)
.catch((error: unknown) => setTaggerModelSwitchError(String(error)))
.finally(() => setTaggerModelSwitching(false));
}}
>
{TAGGER_MODELS[model].tab}
</TaggerModelButton>
))}
</div>
{taggerModelSwitchError ? (
<p className="text-[11px] text-amber-300">{taggerModelSwitchError}</p>
) : (
<p className="text-[11px] text-gray-600">{taggerModelSwitching ? "Switching..." : `Current: ${TAGGER_MODELS[taggerModel].name}`}</p>
)}
</div>
</SettingsItem>
<SettingsItem <SettingsItem
label={ label={
<> <>
WD SwinV2 Tagger v3{" "} {TAGGER_MODELS[taggerModel].name}{" "}
<span className="ml-1.5 align-middle"> <span className="ml-1.5 align-middle">
<StatusPill tone={taggerReady ? "ready" : taggerModelPreparing ? "busy" : "muted"}> <StatusPill tone={taggerReady ? "ready" : taggerModelPreparing ? "busy" : "muted"}>
{taggerReady ? "Installed" : taggerModelPreparing ? "Preparing" : "Not installed"} {taggerReady ? "Installed" : taggerModelPreparing ? "Preparing" : "Not installed"}
@@ -372,7 +452,7 @@ export function SettingsModal() {
</span> </span>
</> </>
} }
description="Anime-focused vision model by SmilingWolf. Generates booru-style tags with configurable confidence thresholds." description={TAGGER_MODELS[taggerModel].description}
> >
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{taggerReady ? ( {taggerReady ? (
@@ -465,7 +545,7 @@ export function SettingsModal() {
{taggerThresholdError ? ( {taggerThresholdError ? (
<p className="text-[11px] text-amber-300">{taggerThresholdError}</p> <p className="text-[11px] text-amber-300">{taggerThresholdError}</p>
) : ( ) : (
<p className="text-[11px] text-gray-600">{taggerThresholdSaving ? "Saving..." : "Default: 0.35"}</p> <p className="text-[11px] text-gray-600">{taggerThresholdSaving ? "Saving..." : `Default: ${taggerModel === "joytag" ? "0.4" : "0.35"}`}</p>
)} )}
</div> </div>
</SettingsItem> </SettingsItem>
@@ -607,6 +687,17 @@ export function SettingsModal() {
{taggerQueueStatus ? <p className="pt-3 text-xs text-gray-500">{taggerQueueStatus}</p> : null} {taggerQueueStatus ? <p className="pt-3 text-xs text-gray-500">{taggerQueueStatus}</p> : null}
</SettingsGroup> </SettingsGroup>
<SettingsGroup title="Tag library" description="Review and clean up the tags across your library.">
<SettingsItem label="Manage tags" description="Open the tag manager in Explore to search, rename, and delete tags.">
<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={openTagManager}
>
Open tag manager
</button>
</SettingsItem>
</SettingsGroup>
</div> </div>
) : ( ) : (
<div className="mt-8 space-y-9"> <div className="mt-8 space-y-9">
@@ -659,6 +750,11 @@ export function SettingsModal() {
label={ label={
<span className="inline-flex items-center gap-2.5"> <span className="inline-flex items-center gap-2.5">
<span>Phokus {appVersion ? `v${appVersion}` : "—"}</span> <span>Phokus {appVersion ? `v${appVersion}` : "—"}</span>
{buildVariant ? (
<StatusPill tone={buildVariant === "cuda" ? "ready" : "muted"}>
{buildVariant === "cuda" ? "CUDA" : "CPU"}
</StatusPill>
) : null}
{updateStatus === "available" || updateStatus === "downloading" || updateStatus === "installing" ? ( {updateStatus === "available" || updateStatus === "downloading" || updateStatus === "installing" ? (
<StatusPill tone="busy">v{updateVersion} available</StatusPill> <StatusPill tone="busy">v{updateVersion} available</StatusPill>
) : updateStatus === "upToDate" ? ( ) : updateStatus === "upToDate" ? (
@@ -670,7 +766,24 @@ export function SettingsModal() {
updateStatus === "error" ? ( updateStatus === "error" ? (
<span className="text-amber-300/90">Update check failed: {updateError}</span> <span className="text-amber-300/90">Update check failed: {updateError}</span>
) : updateStatus === "downloading" || updateStatus === "installing" ? ( ) : updateStatus === "downloading" || updateStatus === "installing" ? (
"Downloading update — the app will restart when it finishes." <span className="block">
<span className="text-gray-400">
{updateStatus === "installing"
? "Installing update…"
: updateProgress !== null
? `Downloading update — ${Math.round(updateProgress * 100)}%`
: "Downloading update…"}
</span>
<span className="mt-2 block h-1 overflow-hidden rounded-full bg-white/10">
<span
className={`block h-full rounded-full bg-emerald-400/80 transition-[width] duration-200 ${
updateProgress === null ? "w-full animate-pulse" : ""
}`}
style={updateProgress !== null ? { width: `${Math.round(updateProgress * 100)}%` } : undefined}
/>
</span>
<span className="mt-1 block text-gray-600">The app will restart when it finishes.</span>
</span>
) : ( ) : (
"Updates are checked quietly at launch and installed only when you choose." "Updates are checked quietly at launch and installed only when you choose."
) )
@@ -678,7 +791,7 @@ export function SettingsModal() {
> >
{updateStatus === "available" ? ( {updateStatus === "available" ? (
<button <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()} onClick={() => void installUpdate()}
> >
Install &amp; restart Install &amp; restart
@@ -693,6 +806,19 @@ export function SettingsModal() {
</button> </button>
)} )}
</SettingsItem> </SettingsItem>
{getChangelogForVersion(appVersion) ? (
<SettingsItem
label="What's new"
description={`See what changed in Phokus v${appVersion}.`}
>
<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={openWhatsNew}
>
View changes
</button>
</SettingsItem>
) : null}
</SettingsGroup> </SettingsGroup>
<SettingsGroup title="Setup"> <SettingsGroup title="Setup">
@@ -742,6 +868,19 @@ export function SettingsModal() {
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${notificationsPaused ? "translate-x-4" : "translate-x-0"}`} /> <span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${notificationsPaused ? "translate-x-4" : "translate-x-0"}`} />
</button> </button>
</SettingsItem> </SettingsItem>
<SettingsItem
label="Keep background pauses after restart"
description="When enabled, folders you pause from the sidebar or background bar stay paused the next time Phokus opens."
>
<button
role="switch"
aria-checked={workerPausesPersist}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors focus:outline-none ${workerPausesPersist ? "bg-sky-500" : "bg-white/15"}`}
onClick={() => setWorkerPausesPersist(!workerPausesPersist)}
>
<span className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${workerPausesPersist ? "translate-x-4" : "translate-x-0"}`} />
</button>
</SettingsItem>
</SettingsGroup> </SettingsGroup>
<SettingsGroup title="Maintenance"> <SettingsGroup title="Maintenance">
+521 -2
View File
@@ -1,8 +1,9 @@
import { useEffect, useMemo, useRef, useState } from "react"; import { useEffect, useMemo, useRef, useState } from "react";
import { Reorder, useDragControls } from "framer-motion"; import { Reorder, useDragControls } from "framer-motion";
import { open } from "@tauri-apps/plugin-dialog"; import { open } from "@tauri-apps/plugin-dialog";
import { useGalleryStore, Folder, IndexProgress } from "../store"; import { useGalleryStore, Folder, Album, IndexProgress } from "../store";
import { ThemedDropdown } from "./ThemedDropdown"; import { ThemedDropdown } from "./ThemedDropdown";
import { mediaSrc } from "../lib/mediaSrc";
interface ContextMenuState { interface ContextMenuState {
folderId: number; folderId: number;
@@ -339,6 +340,270 @@ function FolderItem({
); );
} }
function AlbumContextMenu({
x,
y,
onClose,
onRename,
onDelete,
}: {
x: number;
y: number;
onClose: () => void;
onRename: () => void;
onDelete: () => 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={(event) => {
event.stopPropagation();
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: x, top: y }}
>
{item("Rename", onRename)}
<div className="my-1 border-t border-white/[0.06]" />
{item("Delete album", onDelete, true)}
</div>
);
}
function AlbumItem({
album,
manageMode = false,
selectedForManage = false,
onToggleManage,
reorderable = false,
onDragStart,
onDragEnd,
}: {
album: Album;
manageMode?: boolean;
selectedForManage?: boolean;
onToggleManage?: () => void;
reorderable?: boolean;
onDragStart?: () => void;
onDragEnd?: () => void;
}) {
const dragControls = useDragControls();
const viewAlbum = useGalleryStore((state) => state.viewAlbum);
const renameAlbum = useGalleryStore((state) => state.renameAlbum);
const deleteAlbum = useGalleryStore((state) => state.deleteAlbum);
const activeView = useGalleryStore((state) => state.activeView);
const selectedAlbumId = useGalleryStore((state) => state.selectedAlbumId);
const selected = !manageMode && activeView === "album" && selectedAlbumId === album.id;
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
const [renaming, setRenaming] = useState(false);
const [renameValue, setRenameValue] = useState(album.name);
const [confirmingRemoval, setConfirmingRemoval] = useState(false);
const renameInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (renaming) {
setRenameValue(album.name);
setTimeout(() => renameInputRef.current?.select(), 0);
}
}, [renaming, album.name]);
const commitRename = async () => {
const trimmed = renameValue.trim();
if (trimmed && trimmed !== album.name) {
await renameAlbum(album.id, trimmed);
}
setRenaming(false);
};
const cover = mediaSrc(album.cover_thumbnail_path);
const row = (
<div
role={manageMode ? "checkbox" : "button"}
tabIndex={renaming ? -1 : 0}
aria-checked={manageMode ? selectedForManage : undefined}
aria-current={!manageMode && selected ? "page" : undefined}
className={`group relative flex items-center gap-2.5 px-2 py-1.5 rounded-lg cursor-pointer transition-all duration-150 ${
selectedForManage
? "bg-blue-500/10 text-white ring-1 ring-inset ring-blue-400/50"
: selected
? "bg-white/8 text-white"
: "text-gray-500 hover:text-gray-200 hover:bg-white/5"
}`}
onClick={() => {
if (manageMode) {
onToggleManage?.();
} else if (!renaming) {
viewAlbum(album.id);
}
}}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
if (renaming || (e.key !== "Enter" && e.key !== " ")) return;
e.preventDefault();
if (manageMode) {
onToggleManage?.();
} else {
viewAlbum(album.id);
}
}}
onContextMenu={(e) => {
if (manageMode) return;
e.preventDefault();
e.stopPropagation();
setMenu({ x: Math.min(e.clientX, window.innerWidth - 180), y: Math.min(e.clientY, window.innerHeight - 120) });
}}
>
{/* Manage-mode selection checkbox */}
{manageMode ? (
<div
className={`flex h-4 w-4 shrink-0 items-center justify-center rounded border transition-colors ${
selectedForManage ? "border-blue-400 bg-blue-500 text-white" : "border-white/30 text-transparent"
}`}
>
<svg className="h-2.5 w-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
</svg>
</div>
) : null}
{/* Drag handle — hover-revealed, reorders albums */}
{reorderable ? (
<button
type="button"
aria-label={`Reorder ${album.name}`}
title="Drag to reorder"
className="-ml-1 flex h-6 w-3.5 shrink-0 cursor-grab touch-none items-center justify-center rounded text-gray-700 opacity-0 transition-opacity hover:text-gray-400 group-hover:opacity-100"
onPointerDown={(e) => {
e.stopPropagation();
onDragStart?.();
dragControls.start(e);
}}
onClick={(e) => e.stopPropagation()}
>
<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="6" r="1" /><circle cx="9" cy="6" r="1" />
<circle cx="3" cy="9" r="1" /><circle cx="9" cy="9" r="1" />
</svg>
</button>
) : null}
{/* Cover thumbnail — distinguishes albums from folder rows */}
<div className="h-7 w-7 shrink-0 overflow-hidden rounded-md bg-white/[0.05] ring-1 ring-white/10">
{cover ? (
<img src={cover} alt="" className="h-full w-full object-cover" />
) : (
<div className="flex h-full w-full items-center justify-center text-white/20">
<svg className="h-3.5 w-3.5" 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>
</div>
)}
</div>
<div className="min-w-0 flex-1">
{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={(e) => {
if (e.key === "Enter") { e.preventDefault(); void commitRename(); }
if (e.key === "Escape") setRenaming(false);
}}
onBlur={() => void commitRename()}
onClick={(e) => e.stopPropagation()}
/>
) : (
<div className={`truncate text-[13px] font-medium leading-tight ${selected ? "text-white" : ""}`}>
{album.name}
</div>
)}
<div className="text-[11px] text-gray-600 mt-0.5">{album.image_count.toLocaleString()}</div>
</div>
{!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 deleteAlbum(album.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>
) : null}
{menu ? (
<AlbumContextMenu
x={menu.x}
y={menu.y}
onClose={() => setMenu(null)}
onRename={() => setRenaming(true)}
onDelete={() => setConfirmingRemoval(true)}
/>
) : null}
</div>
);
if (reorderable) {
return (
<Reorder.Item
as="div"
value={album.id}
drag="y"
dragControls={dragControls}
dragListener={false}
dragElastic={0.08}
onDragEnd={onDragEnd}
layout
transition={{ layout: { type: "spring", stiffness: 520, damping: 38, mass: 0.55 } }}
>
{row}
</Reorder.Item>
);
}
return row;
}
export function Sidebar() { export function Sidebar() {
const folders = useGalleryStore((state) => state.folders); const folders = useGalleryStore((state) => state.folders);
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId); const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
@@ -348,6 +613,59 @@ export function Sidebar() {
const activeView = useGalleryStore((state) => state.activeView); const activeView = useGalleryStore((state) => state.activeView);
const setView = useGalleryStore((state) => state.setView); const setView = useGalleryStore((state) => state.setView);
const reorderFolders = useGalleryStore((state) => state.reorderFolders); const reorderFolders = useGalleryStore((state) => state.reorderFolders);
const albums = useGalleryStore((state) => state.albums);
const createAlbum = useGalleryStore((state) => state.createAlbum);
const deleteAlbums = useGalleryStore((state) => state.deleteAlbums);
const reorderAlbums = useGalleryStore((state) => state.reorderAlbums);
const [creatingAlbum, setCreatingAlbum] = useState(false);
const [createAlbumPending, setCreateAlbumPending] = useState(false);
const [newAlbumName, setNewAlbumName] = useState("");
const newAlbumInputRef = useRef<HTMLInputElement>(null);
const [manageAlbums, setManageAlbums] = useState(false);
const [manageSelectedIds, setManageSelectedIds] = useState<Set<number>>(new Set());
const [confirmingAlbumDelete, setConfirmingAlbumDelete] = useState(false);
const [orderedAlbums, setOrderedAlbums] = useState(albums);
const orderedAlbumsRef = useRef(albums);
const [draggingAlbum, setDraggingAlbum] = useState(false);
// Keep the local drag order in sync with the store except mid-drag, so a
// background album refresh doesn't yank the row out from under the pointer.
useEffect(() => {
if (draggingAlbum) return;
setOrderedAlbums(albums);
orderedAlbumsRef.current = albums;
}, [albums, draggingAlbum]);
const handleAlbumReorder = (ids: number[]) => {
const byId = new Map(orderedAlbumsRef.current.map((album) => [album.id, album]));
const next = ids
.map((id) => byId.get(id))
.filter((album): album is Album => album !== undefined);
orderedAlbumsRef.current = next;
setOrderedAlbums(next);
};
const finishAlbumReorder = () => {
setDraggingAlbum(false);
const nextIds = orderedAlbumsRef.current.map((album) => album.id);
// Read live store order (not the render-time closure) in case albums changed.
const currentIds = useGalleryStore.getState().albums.map((album) => album.id);
const snapshotIds = albums.map((album) => album.id);
if (
snapshotIds.length !== currentIds.length ||
snapshotIds.some((id, index) => id !== currentIds[index])
) {
orderedAlbumsRef.current = useGalleryStore.getState().albums;
setOrderedAlbums(orderedAlbumsRef.current);
return;
}
if (
nextIds.length !== currentIds.length ||
nextIds.some((id, index) => id !== currentIds[index])
) {
void reorderAlbums(nextIds);
}
};
const [librarySort, setLibrarySortState] = useState<LibrarySort>(() => { const [librarySort, setLibrarySortState] = useState<LibrarySort>(() => {
const saved = window.localStorage.getItem(LIBRARY_SORT_KEY); const saved = window.localStorage.getItem(LIBRARY_SORT_KEY);
return saved === "za" || saved === "custom" ? saved : "az"; return saved === "za" || saved === "custom" ? saved : "az";
@@ -463,8 +781,55 @@ export function Sidebar() {
setFolderPickerOpen(true); setFolderPickerOpen(true);
}; };
const startCreatingAlbum = () => {
setCreatingAlbum(true);
setNewAlbumName("");
setTimeout(() => newAlbumInputRef.current?.focus(), 0);
};
const handleCreateAlbum = async () => {
const name = newAlbumName.trim();
if (!name) {
setCreatingAlbum(false);
return;
}
if (createAlbumPending) return;
setCreateAlbumPending(true);
try {
const album = await createAlbum(name);
setNewAlbumName("");
setCreatingAlbum(false);
useGalleryStore.getState().viewAlbum(album.id);
} finally {
setCreateAlbumPending(false);
}
};
const exitManageAlbums = () => {
setManageAlbums(false);
setManageSelectedIds(new Set());
setConfirmingAlbumDelete(false);
};
const toggleManageSelected = (albumId: number) => {
setManageSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(albumId)) next.delete(albumId);
else next.add(albumId);
return next;
});
setConfirmingAlbumDelete(false);
};
const handleDeleteSelectedAlbums = async () => {
const ids = Array.from(manageSelectedIds);
if (ids.length === 0) return;
await deleteAlbums(ids);
exitManageAlbums();
};
return ( return (
<aside className="w-60 shrink-0 flex flex-col bg-gray-950 border-r border-white/[0.06]"> <aside className="w-52 shrink-0 flex flex-col bg-gray-950 border-r border-white/[0.06] lg:w-60">
{/* Header */} {/* Header */}
<div className="flex items-center justify-between px-4 h-12 border-b border-white/[0.06] shrink-0"> <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> <span className="text-[13px] font-semibold text-white/80 tracking-wide">Phokus</span>
@@ -601,6 +966,160 @@ export function Sidebar() {
)) ))
)} )}
</Reorder.Group> </Reorder.Group>
{/* Albums a visually distinct block, separated from Libraries by a
heavier divider and given cover-thumbnail rows so the two never
read as one list. */}
<div className="shrink-0 border-t-2 border-white/[0.08] bg-white/[0.015]">
<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">
{manageAlbums ? `${manageSelectedIds.size} selected` : "Albums"}
</span>
{manageAlbums ? (
<button
onClick={exitManageAlbums}
className="rounded px-1 text-[10px] font-semibold uppercase tracking-wider text-gray-500 transition-colors hover:text-gray-200"
>
Done
</button>
) : (
<div className="flex items-center gap-0.5">
{albums.length > 0 ? (
<button
onClick={() => setManageAlbums(true)}
className="rounded p-0.5 text-gray-600 transition-colors hover:bg-white/8 hover:text-gray-200"
title="Manage albums"
>
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.75}
d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</button>
) : null}
<button
onClick={startCreatingAlbum}
className="rounded p-0.5 text-gray-600 transition-colors hover:bg-white/8 hover:text-gray-200"
title="New album"
>
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.75} d="M12 4v16m8-8H4" />
</svg>
</button>
</div>
)}
</div>
{/* Manage action row */}
{manageAlbums ? (
<div className="px-3 pb-1.5">
{confirmingAlbumDelete ? (
<div className="rounded-lg border border-red-500/25 bg-red-500/[0.06] p-2">
<p className="mb-2 text-[11px] leading-relaxed text-gray-400">
Delete {manageSelectedIds.size} album{manageSelectedIds.size === 1 ? "" : "s"}? Your images stay in
the library only the album{manageSelectedIds.size === 1 ? "" : "s"} {manageSelectedIds.size === 1 ? "is" : "are"} removed.
</p>
<div className="flex justify-end gap-1.5">
<button
className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-[11px] text-gray-300 transition-colors hover:bg-white/10 hover:text-white"
onClick={() => setConfirmingAlbumDelete(false)}
>
Cancel
</button>
<button
className="rounded-md bg-red-500/20 px-2 py-1 text-[11px] font-medium text-red-300 transition-colors hover:bg-red-500/30 hover:text-red-200"
onClick={() => void handleDeleteSelectedAlbums()}
>
Delete {manageSelectedIds.size}
</button>
</div>
</div>
) : (
<div className="flex items-center justify-between gap-2">
<button
className="text-[11px] text-gray-500 transition-colors hover:text-gray-300"
onClick={() =>
setManageSelectedIds((prev) =>
prev.size === albums.length ? new Set() : new Set(albums.map((a) => a.id)),
)
}
>
{manageSelectedIds.size === albums.length ? "Deselect all" : "Select all"}
</button>
<button
className="rounded-md border border-red-400/25 bg-red-500/10 px-2 py-1 text-[11px] text-red-300 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-40"
onClick={() => setConfirmingAlbumDelete(true)}
disabled={manageSelectedIds.size === 0}
>
Delete {manageSelectedIds.size > 0 ? manageSelectedIds.size : ""}
</button>
</div>
)}
</div>
) : null}
<div className="max-h-52 overflow-y-auto px-2 pb-2 space-y-px">
{creatingAlbum ? (
<form
className="flex gap-1 px-1 py-1"
onSubmit={(e) => {
e.preventDefault();
void handleCreateAlbum();
}}
>
<input
ref={newAlbumInputRef}
className="min-w-0 flex-1 rounded border border-white/10 bg-white/10 px-1.5 py-1 text-[13px] text-white outline-none ring-1 ring-blue-500/40 placeholder-gray-600"
placeholder="Album name…"
value={newAlbumName}
onChange={(e) => setNewAlbumName(e.target.value)}
disabled={createAlbumPending}
onKeyDown={(e) => {
if (createAlbumPending) return;
if (e.key === "Escape") {
setCreatingAlbum(false);
setNewAlbumName("");
}
}}
onBlur={() => void handleCreateAlbum()}
/>
</form>
) : null}
{albums.length === 0 && !creatingAlbum ? (
<p className="px-3 py-3 text-center text-[11px] leading-relaxed text-gray-700">
Select images and Add to album to start curating
</p>
) : manageAlbums ? (
albums.map((album) => (
<AlbumItem
key={album.id}
album={album}
manageMode
selectedForManage={manageSelectedIds.has(album.id)}
onToggleManage={() => toggleManageSelected(album.id)}
/>
))
) : (
<Reorder.Group
as="div"
axis="y"
values={orderedAlbums.map((album) => album.id)}
onReorder={handleAlbumReorder}
className="space-y-px"
>
{orderedAlbums.map((album) => (
<AlbumItem
key={album.id}
album={album}
reorderable
onDragStart={() => setDraggingAlbum(true)}
onDragEnd={finishAlbumReorder}
/>
))}
</Reorder.Group>
)}
</div>
</div>
</aside> </aside>
); );
} }
-402
View File
@@ -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>
);
}
+19 -18
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import { useVirtualizer } from "@tanstack/react-virtual"; import { useVirtualizer } from "@tanstack/react-virtual";
import { ImageRecord, tileSizeForZoom, useGalleryStore } from "../store"; import { ImageRecord, tileSizeForZoom, useGalleryStore } from "../store";
import { ContextMenu, ImageTile } from "./Gallery"; import { ContextMenu, ImageTile } from "./Gallery";
import { Tooltip } from "./Tooltip";
const GAP = 6; const GAP = 6;
const HEADER_HEIGHT = 52; const HEADER_HEIGHT = 52;
@@ -374,16 +375,16 @@ function ScrubberYearBlock({ yearEntry, activeGroupIndex, onScrollTo }: Scrubber
return ( return (
<div className="w-full flex flex-col items-center"> <div className="w-full flex flex-col items-center">
<button <Tooltip label={yearEntry.year} anchorToCursor>
className={`w-full text-center py-0.5 text-[10px] font-semibold tracking-wide transition-colors ${ <button
isYearActive ? "text-white/80" : "text-white/30 hover:text-white/55" 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} onClick={() => onScrollTo(yearEntry.firstGroupIndex)}
> >
{yearEntry.year} {yearEntry.year}
</button> </button>
</Tooltip>
<div <div
className="grid gap-[3px] pb-1.5" className="grid gap-[3px] pb-1.5"
style={{ gridTemplateColumns: "repeat(3, 10px)" }} style={{ gridTemplateColumns: "repeat(3, 10px)" }}
@@ -396,14 +397,14 @@ function ScrubberYearBlock({ yearEntry, activeGroupIndex, onScrollTo }: Scrubber
return <span key={monthNum} className="h-[10px] w-[10px]" />; return <span key={monthNum} className="h-[10px] w-[10px]" />;
} }
return ( return (
<button <Tooltip key={monthNum} label={`${monthEntry.label} ${yearEntry.year}`} anchorToCursor>
key={monthNum} <button
title={`${monthEntry.label} ${yearEntry.year}`} onClick={() => onScrollTo(monthEntry.groupIndex)}
onClick={() => onScrollTo(monthEntry.groupIndex)} className={`h-[10px] w-[10px] rounded-full transition-colors ${
className={`h-[10px] w-[10px] rounded-full transition-colors ${ isActive ? "bg-white/70" : "bg-white/15 hover:bg-white/40"
isActive ? "bg-white/70" : "bg-white/15 hover:bg-white/40" }`}
}`} />
/> </Tooltip>
); );
})} })}
</div> </div>
+84 -20
View File
@@ -1,7 +1,14 @@
import { useState, useEffect } from "react"; import { useState, useEffect, useRef } from "react";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { useGalleryStore } from "../store"; import { useGalleryStore, AppTheme } from "../store";
import { PhokusMark } from "./PhokusMark"; 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 // SVG icons for window controls
function MinimizeIcon() { function MinimizeIcon() {
@@ -40,11 +47,40 @@ function CloseIcon() {
export function TitleBar() { export function TitleBar() {
const [isMaximized, setIsMaximized] = useState(false); const [isMaximized, setIsMaximized] = useState(false);
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen); 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 updateStatus = useGalleryStore((state) => state.updateStatus);
const updateVersion = useGalleryStore((state) => state.updateVersion); const updateVersion = useGalleryStore((state) => state.updateVersion);
const installUpdate = useGalleryStore((state) => state.installUpdate); const installUpdate = useGalleryStore((state) => state.installUpdate);
const appWindow = getCurrentWindow(); 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 themeMenuRef = useRef<HTMLDivElement>(null);
const [themeMenu, setThemeMenu] = useState<{ top: number; right: number } | null>(null);
useEffect(() => {
if (!themeMenu) return;
const handleDown = (e: MouseEvent) => {
if (themeMenuRef.current && !themeMenuRef.current.contains(e.target as Node)) setThemeMenu(null);
};
const handleKey = (e: KeyboardEvent) => { if (e.key === "Escape") setThemeMenu(null); };
document.addEventListener("mousedown", handleDown);
document.addEventListener("keydown", handleKey);
return () => {
document.removeEventListener("mousedown", handleDown);
document.removeEventListener("keydown", handleKey);
};
}, [themeMenu]);
const handleSettingsContextMenu = (e: React.MouseEvent) => {
e.preventDefault();
const rect = settingsBtnRef.current?.getBoundingClientRect();
if (!rect) return;
setThemeMenu({ top: rect.bottom + 4, right: window.innerWidth - rect.right });
};
useEffect(() => { useEffect(() => {
// Get initial maximized state // Get initial maximized state
appWindow.isMaximized().then(setIsMaximized); appWindow.isMaximized().then(setIsMaximized);
@@ -79,22 +115,18 @@ export function TitleBar() {
up its focal point and the chip becomes a button that re-opens the prompt. */} 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 pl-3 pr-4">
{updatePending ? ( {updatePending ? (
<div <div style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>
className="group relative" {/* Instant tooltip (delay 0) — this affordance should read immediately. */}
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties} <Tooltip label={`Click to update — v${updateVersion}`} delay={0} align="start">
> <button
<button onClick={() => void installUpdate()}
onClick={() => void installUpdate()} aria-label={`Update available — click to update to Phokus v${updateVersion}`}
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"
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" />
<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" />
<PhokusMark className="relative h-4 w-4" dotClassName="fill-amber-400" /> </button>
</button> </Tooltip>
{/* 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> </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 rounded-md bg-white/8 overflow-hidden text-gray-300">
@@ -112,9 +144,11 @@ export function TitleBar() {
className="flex items-stretch h-full" className="flex items-stretch h-full"
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties} style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
> >
<Tooltip label="Settings (right-click to switch theme)" anchorToCursor>
<button <button
ref={settingsBtnRef}
onClick={() => setSettingsOpen(true)} onClick={() => setSettingsOpen(true)}
title="Settings" 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" 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"> <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@@ -122,7 +156,7 @@ export function TitleBar() {
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg> </svg>
</button> </button>
</Tooltip>
{/* Minimize */} {/* Minimize */}
<button <button
onClick={handleMinimize} onClick={handleMinimize}
@@ -150,6 +184,36 @@ export function TitleBar() {
<CloseIcon /> <CloseIcon />
</button> </button>
</div> </div>
{/* Quick theme switcher — opened by right-clicking the settings cog. */}
{themeMenu && (
<div
ref={themeMenuRef}
className="fixed z-50 min-w-[170px] py-1 px-1 rounded-lg bg-gray-900 border border-white/10 shadow-xl shadow-black/50"
style={{ top: themeMenu.top, right: themeMenu.right, WebkitAppRegion: "no-drag" } as React.CSSProperties}
>
<div className="px-3 pt-1 pb-1 text-[10px] font-semibold uppercase tracking-wide text-gray-500">Theme</div>
{THEME_OPTIONS.map((opt) => {
const active = theme === opt.value;
return (
<button
key={opt.value}
className={`flex w-full items-center justify-between gap-3 rounded-md px-3 py-1.5 text-left text-[12px] transition-colors ${
active ? "bg-white/8 text-white" : "text-gray-300 hover:bg-white/8 hover:text-white"
}`}
onClick={() => { setTheme(opt.value); setThemeMenu(null); }}
>
{opt.label}
{active && (
<svg className="h-3.5 w-3.5 text-sky-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
</svg>
)}
</button>
);
})}
</div>
)}
</div> </div>
); );
} }
+47 -29
View File
@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core"; import { invoke } from "@tauri-apps/api/core";
import { tileSizeForZoom, useGalleryStore, SortOrder, MediaFilter, SearchCommand, parseSearchValue, searchModeLabel, ExploreTagEntry } from "../store"; import { tileSizeForZoom, useGalleryStore, SortOrder, MediaFilter, SearchCommand, parseSearchValue, searchModeLabel, ExploreTagEntry } from "../store";
import { FolderScopeDropdown } from "./FolderScopeDropdown"; import { FolderScopeDropdown } from "./FolderScopeDropdown";
import { ColorFilter } from "./ColorFilter";
import { Tooltip } from "./Tooltip";
const BASE_SORT_OPTIONS: { value: SortOrder; label: string }[] = [ const BASE_SORT_OPTIONS: { value: SortOrder; label: string }[] = [
{ value: "date_desc", label: "Newest first" }, { value: "date_desc", label: "Newest first" },
@@ -110,7 +112,7 @@ function FilterPill({
: "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white"; : "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white";
return ( return (
<button <button
className={`rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-150 ${ className={`shrink-0 whitespace-nowrap rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-150 ${
active active
? activeClass ? 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" : "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"
@@ -160,8 +162,11 @@ export function Toolbar() {
const setFailedEmbeddingsOnly = useGalleryStore((state) => state.setFailedEmbeddingsOnly); const setFailedEmbeddingsOnly = useGalleryStore((state) => state.setFailedEmbeddingsOnly);
const failedTaggingOnly = useGalleryStore((state) => state.failedTaggingOnly); const failedTaggingOnly = useGalleryStore((state) => state.failedTaggingOnly);
const setFailedTaggingOnly = useGalleryStore((state) => state.setFailedTaggingOnly); const setFailedTaggingOnly = useGalleryStore((state) => state.setFailedTaggingOnly);
const colorFilter = useGalleryStore((state) => state.colorFilter);
const setColorFilter = useGalleryStore((state) => state.setColorFilter);
const similarScope = useGalleryStore((state) => state.similarScope); const similarScope = useGalleryStore((state) => state.similarScope);
const setSimilarScope = useGalleryStore((state) => state.setSimilarScope); const setSimilarScope = useGalleryStore((state) => state.setSimilarScope);
const similarSourceAlbumId = useGalleryStore((state) => state.similarSourceAlbumId);
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress); const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
const zoomPreset = useGalleryStore((state) => state.zoomPreset); const zoomPreset = useGalleryStore((state) => state.zoomPreset);
const setZoomPreset = useGalleryStore((state) => state.setZoomPreset); const setZoomPreset = useGalleryStore((state) => state.setZoomPreset);
@@ -187,6 +192,12 @@ export function Toolbar() {
const hasActiveSearch = search.trim().length > 0; const hasActiveSearch = search.trim().length > 0;
const parsedSearch = parseSearchValue(composeSearchValue(searchCommand, searchQuery)); const parsedSearch = parseSearchValue(composeSearchValue(searchCommand, searchQuery));
const isSimilarResults = collectionTitle === "Similar Images"; const isSimilarResults = collectionTitle === "Similar Images";
// Album scope is offered while browsing an album (where it's the default) and
// while viewing similar/region results that were launched from an album.
const showAlbumScope =
activeView === "album" ||
(similarSourceAlbumId !== null &&
(collectionTitle === "Similar Images" || collectionTitle === "Region Search Results"));
// If current sort is video-only but we switched away from video filter, reset to date_desc // If current sort is video-only but we switched away from video filter, reset to date_desc
useEffect(() => { useEffect(() => {
@@ -220,7 +231,7 @@ export function Toolbar() {
const results = await invoke<ExploreTagEntry[]>("search_tags_autocomplete", { const results = await invoke<ExploreTagEntry[]>("search_tags_autocomplete", {
params: { query: searchQuery.trim(), folder_id: selectedFolderId ?? null, limit: 10 }, params: { query: searchQuery.trim(), folder_id: selectedFolderId ?? null, limit: 10 },
}); });
setTagSuggestions(results); setTagSuggestions(Array.isArray(results) ? results : []);
} catch { } catch {
setTagSuggestions([]); setTagSuggestions([]);
} }
@@ -256,12 +267,12 @@ export function Toolbar() {
const showCommandHints = !searchCommand && searchPanelOpen; const showCommandHints = !searchCommand && searchPanelOpen;
return ( return (
<div className="relative z-20 shrink-0 border-b border-white/[0.06] bg-gray-950/80 backdrop-blur-xl"> <div className="relative z-40 shrink-0 border-b border-white/[0.06] bg-gray-950/80 backdrop-blur-xl">
{/* Primary row */} {/* Primary row */}
<div className="flex items-center gap-3 px-5 h-12"> <div className="flex items-center gap-2 px-3 h-12 lg:gap-3 lg:px-5">
{/* Title + count */} {/* Title + count */}
<div className="flex items-baseline gap-2.5 min-w-0 shrink-0"> <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> <h2 className="text-[15px] font-semibold text-white truncate max-w-32 lg:max-w-48">{title}</h2>
<span className="text-xs text-gray-600 shrink-0"> <span className="text-xs text-gray-600 shrink-0">
{loadedCount < totalImages {loadedCount < totalImages
? `${loadedCount.toLocaleString()} / ${totalImages.toLocaleString()}` ? `${loadedCount.toLocaleString()} / ${totalImages.toLocaleString()}`
@@ -312,7 +323,7 @@ export function Toolbar() {
}} }}
onFocus={() => setSearchPanelOpen(true)} onFocus={() => setSearchPanelOpen(true)}
placeholder="Search files, or use /s /t" 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"}`} className={`w-40 bg-transparent py-1.5 pr-9 text-sm text-white placeholder:text-gray-600 focus:outline-none transition-colors lg:w-52 xl:w-64 ${searchCommand !== null ? "pl-16" : "pl-8"}`}
/> />
{searchCommand !== null ? ( {searchCommand !== null ? (
<div className="absolute left-8 top-1/2 -translate-y-1/2"> <div className="absolute left-8 top-1/2 -translate-y-1/2">
@@ -347,7 +358,7 @@ export function Toolbar() {
{/* Tag autocomplete suggestions */} {/* Tag autocomplete suggestions */}
{showTagSuggestions && tagSuggestions.length > 0 ? ( {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"> <div className="absolute left-0 top-full z-50 mt-1.5 w-72 rounded-xl border border-white/10 bg-gray-950/98 py-1 shadow-2xl backdrop-blur">
{tagSuggestions.map((entry) => ( {tagSuggestions.map((entry) => (
<button <button
key={entry.tag} key={entry.tag}
@@ -371,25 +382,25 @@ export function Toolbar() {
{/* Tag mode with no suggestions yet — show a brief hint */} {/* Tag mode with no suggestions yet — show a brief hint */}
{showTagSuggestions && tagSuggestions.length === 0 && searchQuery.trim().length > 0 ? ( {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"> <div className="absolute left-0 top-full z-50 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> <p className="text-xs text-white/25">No matching tags</p>
</div> </div>
) : null} ) : null}
{/* Semantic mode hint */} {/* Semantic mode hint */}
{searchCommand === "semantic" && searchPanelOpen ? ( {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"> <div className="absolute left-0 top-full z-50 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> <p className="text-xs text-white/40">Search by meaning and visual concepts</p>
</div> </div>
) : null} ) : null}
{/* Command hints — only shown when no command is active */} {/* Command hints — only shown when no command is active */}
{showCommandHints ? ( {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"> <div className="absolute left-0 top-full z-50 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: "tag" as SearchCommand, prefix: "/t", label: "Tags", description: "Search user and AI tags" },
{ command: "semantic" as SearchCommand, prefix: "/s", label: "Semantic", description: "Search by meaning" }, { command: "semantic" as SearchCommand, prefix: "/s", label: "Semantic", description: "Search by meaning, object, mood" },
] as const ] as const
).map((option) => ( ).map((option) => (
<button <button
@@ -424,32 +435,37 @@ export function Toolbar() {
{/* Zoom */} {/* Zoom */}
<div className="flex items-center rounded-lg border border-white/8 overflow-hidden light-theme:border-gray-700/40"> <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) => ( {(["compact", "comfortable", "detail"] as const).map((preset, i) => (
<button <Tooltip key={preset} label={`${tileSize}px tiles`} followCursor>
key={preset} <button
className={`px-2.5 py-1.5 text-xs font-medium transition-colors ${ className={`px-2.5 py-1.5 text-xs font-medium transition-colors ${
i > 0 ? "border-l border-white/8" : "" i > 0 ? "border-l border-white/8" : ""
} ${ } ${
zoomPreset === preset zoomPreset === preset
? "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white" ? "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" : "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)}
onClick={() => setZoomPreset(preset)} >
> {preset === "compact" ? "S" : preset === "comfortable" ? "M" : "L"}
{preset === "compact" ? "S" : preset === "comfortable" ? "M" : "L"} </button>
</button> </Tooltip>
))} ))}
</div> </div>
</div> </div>
{/* Filter row */} {/* Filter row pills scroll horizontally on narrow widths so they never
squash or stack; the color filter stays pinned to the right. */}
<div className="flex items-center gap-1 px-4 pb-1.5"> <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); }} /> <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<FilterPill label="All" active={mediaFilter === "all" && !favoritesOnly && !failedEmbeddingsOnly && !failedTaggingOnly && minimumRating === 0 && colorFilter === null} onClick={() => { setMediaFilter("all"); setFavoritesOnly(false); setMinimumRating(0); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); setColorFilter(null); }} />
<FilterPill label="Images" active={mediaFilter === "image" && !favoritesOnly && !failedEmbeddingsOnly && !failedTaggingOnly} onClick={() => { setMediaFilter("image"); setFavoritesOnly(false); 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="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="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="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="4★+" active={minimumRating === 4} onClick={() => { setMinimumRating(minimumRating === 4 ? 0 : 4); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
{showAlbumScope ? (
<FilterPill label="Similar: Album" active={similarScope === "current_album"} onClick={() => setSimilarScope("current_album")} />
) : null}
<FilterPill label="Similar: Folder" active={similarScope === "current_folder"} onClick={() => setSimilarScope("current_folder")} /> <FilterPill label="Similar: Folder" active={similarScope === "current_folder"} onClick={() => setSimilarScope("current_folder")} />
<FilterPill label="Similar: All" active={similarScope === "all_media"} onClick={() => setSimilarScope("all_media")} /> <FilterPill label="Similar: All" active={similarScope === "all_media"} onClick={() => setSimilarScope("all_media")} />
{hasAnyFailedEmbeddings ? ( {hasAnyFailedEmbeddings ? (
@@ -468,7 +484,9 @@ export function Toolbar() {
onClick={() => setFailedTaggingOnly(!failedTaggingOnly)} onClick={() => setFailedTaggingOnly(!failedTaggingOnly)}
/> />
) : null} ) : null}
{isSimilarResults ? <span className="ml-2 text-[11px] text-gray-500">Current similar scope: {similarScope === "current_folder" ? "current folder" : "all media"}</span> : null} {isSimilarResults ? <span className="ml-2 shrink-0 whitespace-nowrap text-[11px] text-gray-500">Current similar scope: {similarScope === "current_album" ? "this album" : similarScope === "current_folder" ? "current folder" : "all media"}</span> : null}
</div>
<ColorFilter />
</div> </div>
</div> </div>
); );
+156
View File
@@ -0,0 +1,156 @@
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,
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;
/** 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>) => {
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;
}, []);
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}
{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 -1
View File
@@ -31,7 +31,7 @@ export function UpdateToast() {
</p> </p>
<div className="mt-3 flex items-center gap-2"> <div className="mt-3 flex items-center gap-2">
<button <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()} onClick={() => void installUpdate()}
> >
Install &amp; restart Install &amp; restart
+202
View File
@@ -0,0 +1,202 @@
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 ChangelogSection } from "../changelog";
import { Tooltip } from "./Tooltip";
// 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" };
// 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 Section({ section }: { section: ChangelogSection }) {
const style = SECTION_STYLES[section.title] ?? NEUTRAL_STYLE;
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}
>
<svg
className={`h-3 w-3 shrink-0 text-gray-600 transition-transform ${open ? "rotate-90" : ""}`}
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
</svg>
<span className={`text-[11px] font-semibold uppercase tracking-[0.1em] ${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"
>
<ul className="mt-2.5 space-y-2.5 pl-5">
{section.items.map((item, index) => (
<li key={index} className="flex gap-3">
<span className={`mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full ${style.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>
))}
</ul>
</motion.div>
) : null}
</AnimatePresence>
</section>
);
}
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);
useEffect(() => {
if (!whatsNewOpen) return;
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "Escape") closeWhatsNew();
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [whatsNewOpen, closeWhatsNew]);
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)] w-[min(88vw,560px)] 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 uppercase tracking-[0.12em] text-emerald-300">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>
<button
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
onClick={closeWhatsNew}
title="Close"
>
<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>
<div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-6 py-5">
{entry && entry.sections.length > 0 ? (
entry.sections.map((section) => <Section 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>
);
}
+44
View File
@@ -0,0 +1,44 @@
import { AnimatePresence, motion } from "framer-motion";
import { useGalleryStore } from "../store";
// Shown once on the first launch after an update, inviting the user to read the
// changelog. Distinct from UpdateToast (which drives the download/install flow).
export function WhatsNewToast() {
const whatsNewToast = useGalleryStore((s) => s.whatsNewToast);
const whatsNewOpen = useGalleryStore((s) => s.whatsNewOpen);
const openWhatsNew = useGalleryStore((s) => s.openWhatsNew);
const dismissWhatsNewToast = useGalleryStore((s) => s.dismissWhatsNewToast);
const visible = whatsNewToast !== null && !whatsNewOpen;
return (
<AnimatePresence>
{visible ? (
<motion.div
initial={{ opacity: 0, y: 12 }}
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-emerald-400/20 bg-gray-900 p-4 shadow-xl"
>
<p className="text-sm font-medium text-white">What's new in Phokus v{whatsNewToast}</p>
<p className="mt-1 text-xs text-gray-500">See what's changed in this version.</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"
onClick={openWhatsNew}
>
What's new
</button>
<button
className="rounded-md border border-transparent px-3 py-1.5 text-xs text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-gray-200"
onClick={dismissWhatsNewToast}
>
Dismiss
</button>
</div>
</motion.div>
) : null}
</AnimatePresence>
);
}
+73
View File
@@ -0,0 +1,73 @@
import { useBulkTagEditor } from "./useBulkTagEditor";
// Presentational tag-editing fields shared by the popover and modal surfaces.
export function BulkTagFields({ autoFocus = false }: { autoFocus?: boolean }) {
const { selectedCount, input, setInput, suggestions, appliedTags, pending, addTag, removeTag } =
useBulkTagEditor();
return (
<div className="space-y-2">
<form
className="flex gap-1.5"
onSubmit={(event) => {
event.preventDefault();
void addTag(input);
}}
>
{/* eslint-disable-next-line jsx-a11y/no-autofocus */}
<input
autoFocus={autoFocus}
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={`Add tag to ${selectedCount} item${selectedCount === 1 ? "" : "s"}`}
value={input}
onChange={(event) => setInput(event.target.value)}
disabled={pending}
/>
<button
type="submit"
className="rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
disabled={pending || !input.trim()}
>
Add
</button>
</form>
{suggestions.length > 0 ? (
<div className="flex flex-wrap gap-1">
{suggestions.map((suggestion) => (
<button
key={suggestion.tag}
className="rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-[11px] text-gray-400 transition-colors hover:bg-white/10 hover:text-white"
onClick={() => void addTag(suggestion.tag)}
title={`${suggestion.count.toLocaleString()} tagged`}
>
{suggestion.tag}
</button>
))}
</div>
) : null}
{appliedTags.length > 0 ? (
<div className="flex flex-wrap gap-1 border-t border-white/[0.06] pt-2">
{appliedTags.map((tag) => (
<span
key={tag}
className="group/chip flex items-center gap-1 rounded-md border border-white/10 bg-white/5 px-2 py-0.5 text-xs text-gray-300"
>
{tag}
<button
className="text-gray-600 transition-colors hover:text-white"
title="Remove from selected"
onClick={() => void removeTag(tag)}
>
<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>
</span>
))}
</div>
) : null}
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
import { BulkTagFields } from "./BulkTagFields";
// Inline popover surface for bulk tagging — the default editing surface.
// Anchored above the bar by the parent; closes on outside click via the
// data-bulk-popover guard handled in BulkActionBar.
export function BulkTagPopover({ onClose }: { onClose: () => void }) {
return (
<div
data-bulk-popover
className="absolute bottom-full left-1/2 mb-2 w-72 -translate-x-1/2 rounded-xl border border-white/10 bg-gray-950/98 p-3 shadow-2xl backdrop-blur"
onClick={(event) => event.stopPropagation()}
>
<div className="mb-2 flex items-center justify-between">
<p className="text-[11px] uppercase tracking-wider text-gray-500">Add tags</p>
<button
className="text-gray-600 transition-colors hover:text-white"
onClick={onClose}
title="Close"
>
<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>
<BulkTagFields autoFocus />
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
import { ExploreTagEntry, useGalleryStore } from "../../store";
// Shared logic for the bulk tag editor, consumed by both the inline popover and
// the modal surface so they stay behaviorally identical.
export function useBulkTagEditor() {
const selectedCount = useGalleryStore((state) => state.gallerySelectedIds.size);
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
const bulkAddTags = useGalleryStore((state) => state.bulkAddTags);
const bulkRemoveTag = useGalleryStore((state) => state.bulkRemoveTag);
const [input, setInput] = useState("");
const [suggestions, setSuggestions] = useState<ExploreTagEntry[]>([]);
const [appliedTags, setAppliedTags] = useState<string[]>([]);
const [pending, setPending] = useState(false);
const debounceRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const requestRef = useRef(0);
useEffect(() => {
const query = input.trim();
if (!query) {
requestRef.current += 1;
setSuggestions([]);
return;
}
if (debounceRef.current) clearTimeout(debounceRef.current);
const requestId = ++requestRef.current;
debounceRef.current = setTimeout(async () => {
try {
const results = await invoke<ExploreTagEntry[]>("search_tags_autocomplete", {
params: { query, folder_id: selectedFolderId ?? null, limit: 8 },
});
if (requestId !== requestRef.current) return;
setSuggestions(results);
} catch {
if (requestId !== requestRef.current) return;
setSuggestions([]);
}
}, 120);
return () => {
requestRef.current += 1;
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, [input, selectedFolderId]);
const addTag = useCallback(
async (raw: string) => {
const tag = raw.trim();
if (!tag || pending) return;
setPending(true);
try {
await bulkAddTags([tag]);
setAppliedTags((prev) => (prev.includes(tag) ? prev : [...prev, tag]));
setInput("");
setSuggestions([]);
} finally {
setPending(false);
}
},
[bulkAddTags, pending],
);
const removeTag = useCallback(
async (tag: string) => {
await bulkRemoveTag(tag);
setAppliedTags((prev) => prev.filter((entry) => entry !== tag));
},
[bulkRemoveTag],
);
return { selectedCount, input, setInput, suggestions, appliedTags, pending, addTag, removeTag };
}
@@ -103,7 +103,7 @@ export function OnboardingOverlay() {
Back Back
</button> </button>
<button <button
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-4 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-4 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25"
onClick={() => (isLast ? completeOnboarding() : setOnboardingStep(onboardingStep + 1))} onClick={() => (isLast ? completeOnboarding() : setOnboardingStep(onboardingStep + 1))}
> >
{isLast ? "Finish" : "Next"} {isLast ? "Finish" : "Next"}
+1 -1
View File
@@ -37,7 +37,7 @@ export function StepAddLibrary() {
)} )}
</div> </div>
<button <button
className="shrink-0 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 disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-emerald-600/50 light-theme:bg-emerald-100 light-theme:text-emerald-700 light-theme:hover:bg-emerald-200" className="shrink-0 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 disabled:cursor-not-allowed disabled:opacity-45"
onClick={handlePick} onClick={handlePick}
> >
{folders.length > 0 ? "Add another folder" : "Choose a folder"} {folders.length > 0 ? "Add another folder" : "Choose a folder"}
+1 -1
View File
@@ -142,7 +142,7 @@ export function StepWelcome() {
type="button" type="button"
className={`rounded-md border p-2 text-left transition-colors ${ className={`rounded-md border p-2 text-left transition-colors ${
selected selected
? "border-emerald-400/35 bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-400/40 light-theme:border-emerald-600/50 light-theme:bg-emerald-100 light-theme:text-emerald-700 light-theme:hover:bg-emerald-200" ? "border-emerald-400/35 bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-400/40"
: "border-white/10 bg-white/[0.055] text-gray-300 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" : "border-white/10 bg-white/[0.055] text-gray-300 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={() => setTheme(option.value)} onClick={() => setTheme(option.value)}
+17
View File
@@ -0,0 +1,17 @@
import { useGalleryStore } from "../store";
import { getMockScenario } from "./mockScenarios";
export function applyMockScenario() {
const scenario = getMockScenario();
const store = useGalleryStore.getState();
if (scenario === "album") {
const albumId = store.albums[0]?.id;
if (albumId !== undefined) store.viewAlbum(albumId);
return;
}
if (scenario === "duplicates") {
store.setView("duplicates");
}
}
+434
View File
@@ -0,0 +1,434 @@
import { emit } from "@tauri-apps/api/event";
import type { Album, ExploreTagEntry, Folder, ImageRecord, ImageTag, SortOrder } from "../store";
import { compareImages, createMockDb, mockExif } from "./mockFixtures";
import { getMockScenario } from "./mockScenarios";
const db = createMockDb(getMockScenario());
let nextFolderId = 100;
let nextAlbumId = 100;
let nextTagId = 10_000;
type AnyPayload = Record<string, any> | undefined;
function params(payload: unknown): Record<string, any> {
if (!payload || typeof payload !== "object") return {};
const record = payload as Record<string, any>;
return record.params && typeof record.params === "object" ? record.params : record;
}
function page<T>(items: T[], offset = 0, limit = 200) {
return {
images: items.slice(offset, offset + limit),
total: items.length,
offset,
limit,
};
}
function filterImages(input: ImageRecord[], payload: unknown): ImageRecord[] {
const p = params(payload);
const query = String(p.search ?? p.query ?? "").trim().toLowerCase();
return input.filter((image) => {
if (p.folder_id !== undefined && p.folder_id !== null && image.folder_id !== p.folder_id) return false;
if (p.media_kind && image.media_kind !== p.media_kind) return false;
if (p.favorites_only && !image.favorite) return false;
if (p.rating_min !== undefined && p.rating_min !== null && image.rating < p.rating_min) return false;
if (p.embedding_failed_only && image.embedding_status !== "failed") return false;
if (p.tagging_failed_only && !image.ai_tagger_error) return false;
if (query && !image.filename.toLowerCase().includes(query)) return false;
return true;
});
}
function getImages(payload: unknown) {
const p = params(payload);
const sort = (p.sort ?? "date_desc") as SortOrder;
return page(
filterImages(db.images, payload).sort(compareImages(sort)),
Number(p.offset ?? 0),
Number(p.limit ?? 200),
);
}
function searchTags(payload: unknown) {
const p = params(payload);
const query = String(p.query ?? "").trim().toLowerCase();
const matchingIds = new Set(
Object.entries(db.tagsByImageId)
.filter(([, tags]) => tags.some((tag) => tag.tag.toLowerCase().includes(query)))
.map(([imageId]) => Number(imageId)),
);
const images = filterImages(db.images, { params: { ...p, query: "", search: "" } })
.filter((image) => matchingIds.has(image.id))
.sort(compareImages((p.sort ?? "date_desc") as SortOrder));
return page(images, Number(p.offset ?? 0), Number(p.limit ?? 200));
}
function searchTagsAutocomplete(payload: unknown): ExploreTagEntry[] {
const p = params(payload);
const query = String(p.query ?? "").trim().toLowerCase();
const limit = Number(p.limit ?? 10);
return db.exploreTags
.filter((entry) => !query || entry.tag.toLowerCase().includes(query))
.sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag))
.slice(0, limit);
}
function semanticSearch(payload: unknown): ImageRecord[] {
const p = params(payload);
const query = String(p.query ?? "").toLowerCase();
const scored = filterImages(db.images, payload)
.map((image, index) => ({
image,
score:
(image.generated_caption?.toLowerCase().includes(query) ? 0 : 20) +
(image.filename.toLowerCase().includes(query) ? 0 : 10) +
(index % 9),
}))
.sort((left, right) => left.score - right.score)
.slice(0, Number(p.limit ?? 200))
.map((entry) => entry.image);
return scored.length ? scored : filterImages(db.images, payload).slice(0, Number(p.limit ?? 200));
}
function albumImages(payload: unknown) {
const p = params(payload);
const albumId = Number(p.album_id);
const ids = new Set(db.albumImageIds[albumId] ?? []);
const sort = (p.sort ?? "date_desc") as SortOrder;
return page(
db.images.filter((image) => ids.has(image.id)).sort(compareImages(sort)),
Number(p.offset ?? 0),
Number(p.limit ?? 200),
);
}
function similarImages(payload: unknown) {
const p = params(payload);
const source = db.images.find((image) => image.id === p.image_id);
let images = db.images.filter((image) => image.id !== p.image_id && image.embedding_status === "ready");
if (p.album_id !== undefined && p.album_id !== null) {
const ids = new Set(db.albumImageIds[Number(p.album_id)] ?? []);
images = images.filter((image) => ids.has(image.id));
} else if (p.folder_id !== undefined && p.folder_id !== null) {
images = images.filter((image) => image.folder_id === p.folder_id);
}
const ordered = images.sort((left, right) => {
const leftScore = Math.abs(left.rating - (source?.rating ?? 0)) + (left.folder_id === source?.folder_id ? 0 : 2);
const rightScore = Math.abs(right.rating - (source?.rating ?? 0)) + (right.folder_id === source?.folder_id ? 0 : 2);
return leftScore - rightScore;
});
const offset = Number(p.offset ?? 0);
const limit = Number(p.limit ?? 200);
return {
images: ordered.slice(offset, offset + limit),
offset,
limit,
has_more: offset + limit < ordered.length,
};
}
function updateImages(ids: number[], updates: { favorite?: boolean | null; rating?: number | null }) {
const changed: ImageRecord[] = [];
for (const image of db.images) {
if (!ids.includes(image.id)) continue;
if (updates.favorite !== null && updates.favorite !== undefined) image.favorite = updates.favorite;
if (updates.rating !== null && updates.rating !== undefined) image.rating = updates.rating;
changed.push({ ...image });
}
return changed;
}
function refreshAlbumCounts() {
for (const album of db.albums) {
const ids = db.albumImageIds[album.id] ?? [];
album.image_count = ids.length;
album.cover_image_id = ids[0] ?? null;
album.cover_thumbnail_path = db.images.find((image) => image.id === ids[0])?.thumbnail_path ?? null;
album.updated_at = new Date().toISOString();
}
}
function createAlbum(name: string): Album {
const album: Album = {
id: nextAlbumId++,
name,
cover_image_id: null,
cover_thumbnail_path: null,
image_count: 0,
sort_order: db.albums.length + 1,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
};
db.albums.push(album);
db.albumImageIds[album.id] = [];
return album;
}
function addFolder(path: string): Folder {
const parts = path.split(/[\\/]/).filter(Boolean);
const name = parts[parts.length - 1] ?? "New Folder";
const folder: Folder = {
id: nextFolderId++,
path,
name,
image_count: 0,
indexed_at: new Date().toISOString(),
scan_error: null,
sort_order: db.folders.length + 1,
};
db.folders.push(folder);
return folder;
}
function safeFallback(cmd: string, payload: AnyPayload): unknown {
if (cmd.includes("app|version")) return "0.1.1-ui";
if (cmd.includes("path|resolve_directory")) return "C:\\Users\\phokus\\AppData\\Roaming\\Phokus";
if (cmd.includes("path|join")) {
const paths = payload?.paths ?? payload?.args ?? [];
return Array.isArray(paths) ? paths.join("\\") : "C:\\Users\\phokus\\AppData\\Roaming\\Phokus";
}
if (cmd.includes("notification|is_permission_granted")) return false;
if (cmd.includes("notification|request_permission")) return "denied";
if (cmd.includes("dialog|open")) return null;
if (cmd.includes("window|is_maximized")) return false;
if (cmd.includes("window|minimize")) return null;
if (cmd.includes("window|toggle_maximize")) return null;
if (cmd.includes("window|close")) return null;
if (cmd.includes("opener|reveal_item_in_dir")) return null;
if (cmd.includes("opener|open")) return null;
if (cmd.includes("process|relaunch")) return null;
console.warn("[Phokus UI Lab] Unmocked command:", cmd, payload);
return null;
}
export async function handleMockCommand(cmd: string, payload?: unknown): Promise<unknown> {
const p = params(payload);
switch (cmd) {
case "get_folders":
return db.folders;
case "add_folder":
addFolder(String(p.path ?? "C:\\Users\\phokus\\Pictures\\NewFolder"));
return null;
case "add_folders":
return (p.paths ?? []).map((path: string) => ({ status: "added", data: addFolder(path) }));
case "remove_folder":
db.folders = db.folders.filter((folder) => folder.id !== p.folderId);
return null;
case "rename_folder": {
const folder = db.folders.find((entry) => entry.id === p.folderId);
if (folder) folder.name = String(p.newName ?? folder.name);
return null;
}
case "update_folder_path": {
const folder = db.folders.find((entry) => entry.id === p.folderId);
if (folder) folder.path = String(p.newPath ?? folder.path);
return null;
}
case "reindex_folder":
case "reorder_folders":
return null;
case "list_directories":
return {
current: p.path ?? null,
parent: p.path ? "C:\\Users\\phokus" : null,
entries: db.folders.map((folder) => ({ name: folder.name, path: folder.path, has_children: false })),
};
case "get_background_job_progress":
return db.backgroundJobs;
case "get_images":
return getImages(payload);
case "semantic_search_images":
return semanticSearch(payload);
case "search_images_by_tag":
return searchTags(payload);
case "search_tags_autocomplete":
return searchTagsAutocomplete(payload);
case "get_images_by_ids":
return (p.image_ids ?? []).map((id: number) => db.images.find((image) => image.id === id)).filter(Boolean);
case "find_similar_images":
case "find_similar_by_region":
return similarImages(payload);
case "get_visual_clusters":
return db.scenario === "empty" ? [] : db.visualClusters;
case "get_explore_tags":
return db.scenario === "empty" ? [] : db.exploreTags.slice(0, Number(p.limit ?? 180));
case "get_related_tags": {
const relatedCounts = new Map<string, number>();
for (const imageTags of Object.values(db.tagsByImageId)) {
if (!imageTags.some((tag) => tag.tag === p.tag)) continue;
for (const tag of imageTags) {
if (tag.tag === p.tag) continue;
relatedCounts.set(tag.tag, (relatedCounts.get(tag.tag) ?? 0) + 1);
}
}
return Array.from(relatedCounts.entries())
.map(([tag, shared_count]) => ({ tag, shared_count }))
.sort((left, right) => right.shared_count - left.shared_count || left.tag.localeCompare(right.tag))
.slice(0, Number(p.limit ?? 18));
}
case "suggest_image_tags":
return ["select", "warm light"];
case "rename_tag":
case "delete_tag":
return cmd === "delete_tag" ? 6 : null;
case "get_image_tags":
return db.tagsByImageId[p.image_id] ?? [];
case "add_user_tag": {
const tag: ImageTag = { id: nextTagId++, image_id: p.image_id, tag: p.tag, source: "user", ai_model: null, confidence: null, created_at: new Date().toISOString() };
db.tagsByImageId[p.image_id] = [...(db.tagsByImageId[p.image_id] ?? []), tag];
return tag;
}
case "remove_tag":
for (const [imageId, imageTags] of Object.entries(db.tagsByImageId)) {
db.tagsByImageId[Number(imageId)] = imageTags.filter((tag) => tag.id !== p.tag_id);
}
return null;
case "get_image_exif":
return mockExif(Number(p.image_id));
case "update_image_details":
return updateImages([Number(p.image_id)], { favorite: p.favorite, rating: p.rating })[0];
case "bulk_update_details":
return updateImages(p.image_ids ?? [], { favorite: p.favorite, rating: p.rating });
case "bulk_add_tags":
case "bulk_remove_tag":
return null;
case "delete_images_from_disk":
return p.image_ids ?? [];
case "list_albums":
refreshAlbumCounts();
return db.albums;
case "create_album":
return createAlbum(String(p.name ?? "Untitled Album"));
case "rename_album": {
const album = db.albums.find((entry) => entry.id === p.album_id);
if (album) album.name = String(p.new_name ?? album.name);
return null;
}
case "delete_album":
db.albums = db.albums.filter((album) => album.id !== p.album_id);
delete db.albumImageIds[p.album_id];
return null;
case "delete_albums":
db.albums = db.albums.filter((album) => !(p.album_ids ?? []).includes(album.id));
for (const id of p.album_ids ?? []) delete db.albumImageIds[id];
return null;
case "reorder_albums":
return null;
case "add_images_to_album": {
const existing = new Set(db.albumImageIds[p.album_id] ?? []);
for (const id of p.image_ids ?? []) existing.add(id);
db.albumImageIds[p.album_id] = [...existing];
refreshAlbumCounts();
return p.image_ids?.length ?? 0;
}
case "remove_images_from_album":
db.albumImageIds[p.album_id] = (db.albumImageIds[p.album_id] ?? []).filter((id) => !(p.image_ids ?? []).includes(id));
refreshAlbumCounts();
return null;
case "get_album_images":
return albumImages(payload);
case "load_duplicate_scan_cache":
return db.duplicateScannedAt ? { groups: db.duplicateGroups, scanned_at: db.duplicateScannedAt } : null;
case "find_duplicates":
await emit("duplicate_scan_progress", { phase: "hashing", processed: Math.floor(db.images.length * 0.6), total: db.images.length, skipped: db.scenario === "errors" ? 3 : 0 });
db.duplicateScannedAt = Math.floor(Date.now() / 1000);
return {
groups: db.duplicateGroups,
scanned_files: db.images.length,
candidate_files: db.duplicateGroups.flatMap((group) => group.images).length,
skipped_files: db.scenario === "errors" ? 3 : 0,
};
case "invalidate_duplicate_scan_cache":
return null;
case "get_caption_model_status":
return { model_id: "Salesforce/blip-image-captioning-base", model_name: "BLIP Base", local_dir: "mock://models/caption", ready: true, missing_files: [] };
case "get_caption_acceleration":
case "set_caption_acceleration":
return p.acceleration ?? "auto";
case "get_caption_detail":
case "set_caption_detail":
return p.detail ?? "paragraph";
case "prepare_caption_model":
case "delete_caption_model":
return { model_id: "Salesforce/blip-image-captioning-base", model_name: "BLIP Base", local_dir: "mock://models/caption", ready: true, missing_files: [] };
case "probe_caption_runtime":
return { ready: true, acceleration: "auto", detail: "paragraph", tokenizer_vocab_size: 30522, sessions: [] };
case "probe_caption_image":
return { input_shape: [1, 3, 384, 384], output_shape: [1, 768], output_values: 768, acceleration: "auto" };
case "generate_caption_for_image": {
const image = db.images.find((entry) => entry.id === p.image_id);
if (image) image.generated_caption = `Generated in UI Lab for ${image.filename}.`;
return image;
}
case "queue_caption_jobs":
case "clear_caption_jobs":
case "reset_generated_captions":
case "queue_tagging_jobs":
case "clear_tagging_jobs":
return 12;
case "get_tagger_model_status":
return { model_id: "SmilingWolf/wd-vit-tagger-v3", model_name: "WD ViT Tagger", local_dir: "mock://models/tagger", ready: true, missing_files: [] };
case "get_tagger_model":
case "set_tagger_model":
return p.model ?? "wd";
case "get_tagger_acceleration":
case "set_tagger_acceleration":
return p.acceleration ?? "auto";
case "get_tagger_threshold":
case "set_tagger_threshold":
return p.threshold ?? 0.35;
case "get_tagger_batch_size":
case "set_tagger_batch_size":
return p.batch_size ?? 8;
case "probe_tagger_runtime":
return { ready: true, acceleration: "auto", session: { file: "model.onnx", inputs: ["input"], outputs: ["tags"] } };
case "get_tagging_queue_scope":
return "all";
case "get_tagging_queue_folder_ids":
case "get_muted_folder_ids":
return [];
case "set_tagging_queue_scope":
case "set_tagging_queue_folder_ids":
case "set_muted_folder_ids":
case "set_notifications_paused":
case "set_worker_pauses_persist":
case "set_worker_paused":
return null;
case "get_notifications_paused":
case "get_worker_pauses_persist":
case "get_onboarding_completed":
return db.scenario !== "empty";
case "set_onboarding_completed":
case "set_last_seen_version":
return null;
case "get_worker_states":
return (p.folderIds ?? []).map((folder_id: number) => ({ folder_id, thumbnail_paused: false, metadata_paused: false, embedding_paused: false, tagging_paused: false }));
case "get_build_variant":
return "cpu";
case "get_last_seen_version":
return "0.1.1-ui";
case "get_ffmpeg_status":
return { installed: true, downloading: false, failed: false };
case "retry_ffmpeg_download":
case "open_app_data_folder":
case "open_map_location":
case "open_changelog_url":
return null;
case "get_database_info":
return { size_mb: 14.2, reclaimable_mb: 1.8 };
case "vacuum_database":
return { before_mb: 14.2, after_mb: 12.4, freed_mb: 1.8 };
case "rebuild_semantic_index":
return db.images.length;
case "get_orphaned_thumbnails_info":
return { count: 9, size_mb: 3.4 };
case "cleanup_orphaned_thumbnails":
return { deleted_count: 9, freed_mb: 3.4 };
case "retry_failed_embeddings":
return null;
default:
return safeFallback(cmd, payload as AnyPayload);
}
}
+369
View File
@@ -0,0 +1,369 @@
import type {
Album,
AiRating,
DuplicateGroup,
ExploreTagEntry,
Folder,
FolderJobProgress,
ImageExif,
ImageRecord,
ImageTag,
SortOrder,
VisualClusterEntry,
} from "../store";
import type { MockScenario } from "./mockScenarios";
import { fixtureMediaPath } from "./mockMedia";
export interface MockDb {
scenario: MockScenario;
folders: Folder[];
images: ImageRecord[];
albums: Album[];
albumImageIds: Record<number, number[]>;
tagsByImageId: Record<number, ImageTag[]>;
visualClusters: VisualClusterEntry[];
exploreTags: ExploreTagEntry[];
backgroundJobs: FolderJobProgress[];
duplicateGroups: DuplicateGroup[];
duplicateScannedAt: number | null;
}
const folderNames = ["Camera Roll", "Client Selects", "Video Archive"];
const mediaNames = [
"alpine-lake",
"city-after-rain",
"coastal-walk",
"studio-portrait",
"market-neon",
"forest-floor",
"product-macro",
"golden-hour",
"night-drive",
"desk-flatlay",
"museum-hall",
"wildflower",
];
const tags = [
"landscape",
"portrait",
"street",
"travel",
"night",
"product",
"editorial",
"architecture",
"nature",
"warm light",
"blue hour",
"select",
];
const hugeTagThemes = [
"alpine",
"archive",
"botanical",
"cinematic",
"coastal",
"editorial",
"industrial",
"interior",
"macro",
"night",
"portrait",
"street",
"travel",
"urban",
"wildlife",
"workspace",
];
const hugeTagSubjects = [
"glass",
"steel",
"water",
"stone",
"mist",
"foliage",
"market",
"signage",
"neon",
"shadow",
"reflection",
"texture",
"silhouette",
"motion",
"symmetry",
"detail",
"warm light",
"blue hour",
"gold accent",
"soft focus",
"hard light",
"negative space",
"foreground",
"background",
"wide angle",
"close crop",
"environment",
"still life",
"natural light",
"available light",
];
const hugeTags = [
...tags,
...Array.from({ length: hugeTagThemes.length * hugeTagSubjects.length }, (_, index) => {
const theme = hugeTagThemes[index % hugeTagThemes.length];
const subject = hugeTagSubjects[Math.floor(index / hugeTagThemes.length) % hugeTagSubjects.length];
return `${theme} ${subject}`;
}),
...Array.from({ length: 320 }, (_, index) => `fixture concept ${String(index + 1).padStart(3, "0")}`),
];
const aiRatings: AiRating[] = ["general", "sensitive", "questionable"];
function daysAgo(days: number): string {
return new Date(Date.now() - days * 86_400_000).toISOString();
}
function mockPath(folder: number, name: string, index: number, ext: string): string {
return `mock://full/${folder}-${name}-${index}.${ext}`;
}
function mockThumb(index: number): string {
return fixtureMediaPath(index);
}
function makeImage(index: number, folderId: number, scenario: MockScenario): ImageRecord {
const name = mediaNames[index % mediaNames.length];
const isVideo = index % 11 === 6;
const failedEmbedding = scenario === "errors" && index % 9 === 0;
const failedTagging = scenario === "errors" && index % 7 === 0;
const ext = isVideo ? "mp4" : "jpg";
return {
id: index + 1,
folder_id: folderId,
path: isVideo ? mockPath(folderId, name, index + 1, ext) : mockThumb(index),
filename: `${name}-${String(index + 1).padStart(3, "0")}.${ext}`,
thumbnail_path: scenario === "errors" && index % 10 === 3 ? "mock://missing-thumb.svg" : mockThumb(index),
width: isVideo ? 3840 : 3000 + (index % 5) * 180,
height: isVideo ? 2160 : 2000 + (index % 4) * 160,
file_size: 480_000 + index * 73_000,
created_at: daysAgo(index + 3),
modified_at: daysAgo(index + 1),
taken_at: daysAgo(index + 10),
mime_type: isVideo ? "video/mp4" : "image/jpeg",
media_kind: isVideo ? "video" : "image",
duration_ms: isVideo ? 42_000 + index * 1300 : null,
video_codec: isVideo ? "h264" : null,
audio_codec: isVideo ? "aac" : null,
metadata_updated_at: daysAgo(index),
metadata_error: scenario === "errors" && index % 8 === 2 ? "EXIF parse failed in UI fixture" : null,
favorite: index % 5 === 0,
rating: index % 6,
embedding_status: failedEmbedding ? "failed" : index % 13 === 0 ? "processing" : "ready",
embedding_model: failedEmbedding ? null : "clip-vit-b-32",
embedding_updated_at: failedEmbedding ? null : daysAgo(index),
embedding_error: failedEmbedding ? "Fixture embedding failure" : null,
generated_caption: `Fixture caption for ${name.replace(/-/g, " ")}.`,
caption_model: "blip-base",
caption_updated_at: daysAgo(index),
caption_error: null,
ai_rating: aiRatings[index % aiRatings.length],
ai_tagger_model: failedTagging ? null : "wd-vit-tagger-v3",
ai_tagged_at: failedTagging ? null : daysAgo(index),
ai_tagger_error: failedTagging ? "Fixture tagger failure" : null,
};
}
function makeFolders(scenario: MockScenario): Folder[] {
if (scenario === "empty") return [];
return folderNames.map((name, index) => ({
id: index + 1,
path: `C:\\Users\\phokus\\Pictures\\${name.replace(/ /g, "")}`,
name,
image_count: 0,
indexed_at: daysAgo(index + 1),
scan_error: scenario === "errors" && index === 1 ? "Folder moved or permission denied" : null,
sort_order: index + 1,
}));
}
function makeImages(scenario: MockScenario, folders: Folder[]): ImageRecord[] {
if (scenario === "empty") return [];
const count = scenario === "huge" ? 720 : scenario === "errors" ? 54 : 72;
const images = Array.from({ length: count }, (_, index) => makeImage(index, folders[index % folders.length].id, scenario));
for (const folder of folders) {
folder.image_count = images.filter((image) => image.folder_id === folder.id).length;
}
return images;
}
function tagVocabularyForScenario(scenario: MockScenario): string[] {
return scenario === "huge" ? hugeTags : tags;
}
function makeTags(images: ImageRecord[], scenario: MockScenario): Record<number, ImageTag[]> {
const vocabulary = tagVocabularyForScenario(scenario);
const tagCount = scenario === "huge" ? 9 : 3;
return Object.fromEntries(
images.map((image, index) => [
image.id,
Array.from({ length: tagCount }, (_, offset) => ({
id: image.id * 10 + offset,
image_id: image.id,
tag: vocabulary[(index * (offset + 3) + offset * 29) % vocabulary.length],
source: offset === 0 ? "user" : "ai",
ai_model: offset === 0 ? null : "wd-vit-tagger-v3",
confidence: offset === 0 ? null : Math.min(0.99, 0.72 + offset * 0.03),
created_at: daysAgo(index + offset),
})),
]),
);
}
function makeAlbums(images: ImageRecord[], scenario: MockScenario): { albums: Album[]; albumImageIds: Record<number, number[]> } {
if (scenario === "empty") return { albums: [], albumImageIds: {} };
const selects = images.filter((image) => image.rating >= 4).slice(0, 36).map((image) => image.id);
const motion = images.filter((image) => image.media_kind === "video").map((image) => image.id);
const favorites = images.filter((image) => image.favorite).slice(0, 40).map((image) => image.id);
const albumImageIds = { 1: selects, 2: motion, 3: favorites };
const albums: Album[] = [
{ id: 1, name: "Portfolio Shortlist", cover_image_id: selects[0] ?? null, cover_thumbnail_path: images.find((image) => image.id === selects[0])?.thumbnail_path ?? null, image_count: selects.length, sort_order: 1, created_at: daysAgo(40), updated_at: daysAgo(2) },
{ id: 2, name: "Motion Tests", cover_image_id: motion[0] ?? null, cover_thumbnail_path: images.find((image) => image.id === motion[0])?.thumbnail_path ?? null, image_count: motion.length, sort_order: 2, created_at: daysAgo(38), updated_at: daysAgo(3) },
{ id: 3, name: "Favorites", cover_image_id: favorites[0] ?? null, cover_thumbnail_path: images.find((image) => image.id === favorites[0])?.thumbnail_path ?? null, image_count: favorites.length, sort_order: 3, created_at: daysAgo(20), updated_at: daysAgo(1) },
];
return { albums, albumImageIds };
}
function makeProgress(folders: Folder[], scenario: MockScenario): FolderJobProgress[] {
return folders.map((folder, index) => ({
folder_id: folder.id,
thumbnail_pending: scenario === "busy" ? 18 - index * 3 : 0,
metadata_pending: scenario === "busy" ? 12 - index * 2 : 0,
embedding_pending: scenario === "busy" ? 36 - index * 4 : scenario === "errors" ? 4 : 0,
embedding_ready: Math.max(0, folder.image_count - (scenario === "busy" ? 20 : 2)),
embedding_failed: scenario === "errors" ? 3 + index : 0,
caption_pending: scenario === "busy" ? 24 - index * 2 : 0,
caption_ready: Math.max(0, Math.floor(folder.image_count * 0.5)),
caption_failed: scenario === "errors" ? 2 : 0,
tagging_pending: scenario === "busy" ? 30 - index * 5 : 0,
tagging_ready: Math.max(0, Math.floor(folder.image_count * 0.65)),
tagging_failed: scenario === "errors" ? 4 : 0,
}));
}
function makeVisualClusters(images: ImageRecord[], scenario: MockScenario): VisualClusterEntry[] {
if (images.length < 5) return [];
// Mirror the backend's k = (n / 20).clamp(5, 30). Force the full spread for the
// "huge" scenario so Explore shows a realistic field of clusters rather than a
// fixed handful, and size the counts off a large virtual library so the badges
// read like a big collection.
const clusterCount = scenario === "huge" ? 30 : Math.min(30, Math.max(5, Math.round(images.length / 20)));
const virtualTotal = scenario === "huge" ? 12_000 : images.length;
// Long-tailed sizes (a few large clusters, many smaller), like real k-means output.
const weights = Array.from({ length: clusterCount }, (_, i) => 1 / (i + 1.5));
const weightSum = weights.reduce((sum, weight) => sum + weight, 0);
return weights.map((weight, index) => {
const group = images.filter((image) => image.id % (index + 2) === 0).slice(0, 28);
const representative = group[0] ?? images[index % images.length];
return {
count: Math.max(1, Math.round((virtualTotal * weight) / weightSum)),
representative_image_id: representative?.id ?? index + 1,
thumbnail_path: representative?.thumbnail_path ?? null,
image_ids: group.length ? group.map((image) => image.id) : [representative?.id ?? 1],
};
});
}
function makeExploreTags(images: ImageRecord[], scenario: MockScenario): ExploreTagEntry[] {
const vocabulary = tagVocabularyForScenario(scenario);
return vocabulary.map((tag, index) => {
const representative = images[index % Math.max(images.length, 1)];
const divisor = scenario === "huge" ? 2 + Math.pow(index + 1, 0.58) : index + 3;
return {
tag,
count: Math.max(1, Math.round(images.length / divisor)),
representative_image_id: representative?.id ?? index + 1,
thumbnail_path: representative?.thumbnail_path ?? null,
};
}).sort((left, right) => right.count - left.count || left.tag.localeCompare(right.tag));
}
function makeDuplicateGroups(images: ImageRecord[], scenario: MockScenario): DuplicateGroup[] {
if (scenario === "empty") return [];
const candidates = images.filter((image) => image.media_kind === "image");
const groups = [0, 1, 2, 3].map((groupIndex) => ({
file_hash: `fixture-hash-${groupIndex}`,
file_size: candidates[groupIndex]?.file_size ?? 1_200_000,
images: candidates.slice(groupIndex * 4, groupIndex * 4 + (groupIndex === 1 ? 3 : 2)),
})).filter((group) => group.images.length > 1);
return scenario === "duplicates" ? groups.concat(groups.map((group, index) => ({
...group,
file_hash: `${group.file_hash}-extra`,
images: candidates.slice(20 + index * 3, 23 + index * 3),
})).filter((group) => group.images.length > 1)) : groups;
}
export function createMockDb(scenario: MockScenario): MockDb {
const folders = makeFolders(scenario);
const images = makeImages(scenario, folders);
const { albums, albumImageIds } = makeAlbums(images, scenario);
return {
scenario,
folders,
images,
albums,
albumImageIds,
tagsByImageId: makeTags(images, scenario),
visualClusters: makeVisualClusters(images, scenario),
exploreTags: makeExploreTags(images, scenario),
backgroundJobs: makeProgress(folders, scenario),
duplicateGroups: makeDuplicateGroups(images, scenario),
duplicateScannedAt: scenario === "duplicates" ? Math.floor(Date.now() / 1000) - 420 : null,
};
}
export function compareImages(sort: SortOrder): (left: ImageRecord, right: ImageRecord) => number {
return (left, right) => {
switch (sort) {
case "name_asc":
return left.filename.localeCompare(right.filename);
case "name_desc":
return right.filename.localeCompare(left.filename);
case "size_asc":
return left.file_size - right.file_size;
case "size_desc":
return right.file_size - left.file_size;
case "rating_asc":
return left.rating - right.rating;
case "rating_desc":
return right.rating - left.rating;
case "duration_asc":
return (left.duration_ms ?? 0) - (right.duration_ms ?? 0);
case "duration_desc":
return (right.duration_ms ?? 0) - (left.duration_ms ?? 0);
case "date_asc":
case "taken_asc":
return Date.parse(left.taken_at ?? left.created_at ?? "") - Date.parse(right.taken_at ?? right.created_at ?? "");
case "date_desc":
case "taken_desc":
default:
return Date.parse(right.taken_at ?? right.created_at ?? "") - Date.parse(left.taken_at ?? left.created_at ?? "");
}
};
}
export function mockExif(imageId: number): ImageExif {
return {
make: "Phokus Fixture Co.",
model: `MockCam ${100 + imageId}`,
lens: "35mm f/1.8",
iso: String(100 + (imageId % 8) * 100),
f_number: "f/4",
exposure_time: "1/250",
focal_length: "35mm",
datetime_original: daysAgo(imageId),
gps_lat: imageId % 2 === 0 ? 51.5072 : null,
gps_lon: imageId % 2 === 0 ? -0.1276 : null,
};
}
+8
View File
@@ -0,0 +1,8 @@
const fixtureMedia = Array.from(
{ length: 48 },
(_, index) => `/dev-media/fixture-${String(index + 1).padStart(2, "0")}.webp`,
);
export function fixtureMediaPath(index: number): string {
return fixtureMedia[index % fixtureMedia.length];
}
+17
View File
@@ -0,0 +1,17 @@
export type MockScenario = "rich" | "empty" | "busy" | "duplicates" | "album" | "errors" | "huge";
const SCENARIOS = new Set<MockScenario>([
"rich",
"empty",
"busy",
"duplicates",
"album",
"errors",
"huge",
]);
export function getMockScenario(): MockScenario {
if (typeof window === "undefined") return "rich";
const value = new URLSearchParams(window.location.search).get("scenario");
return value && SCENARIOS.has(value as MockScenario) ? (value as MockScenario) : "rich";
}
+11
View File
@@ -0,0 +1,11 @@
import { mockConvertFileSrc, mockIPC, mockWindows } from "@tauri-apps/api/mocks";
import { handleMockCommand } from "./mockBackend";
mockWindows("main");
mockConvertFileSrc("windows");
mockIPC((cmd, payload) => handleMockCommand(cmd, payload), {
shouldMockEvents: true,
});
console.info("[Phokus UI Lab] Mock Tauri backend installed.");
+116 -12
View File
@@ -190,29 +190,32 @@ html[data-theme="subtle-light"] .explore-cluster-card:hover {
} }
html[data-theme="subtle-light"] .explore-cluster-overlay { html[data-theme="subtle-light"] .explore-cluster-overlay {
/* A cream wash over the photo read as a faded, foggy haze. Use a gentle dark
scrim instead the same natural "photo caption" vignette the dark theme
uses with light text on top (label/count rules below). */
background: linear-gradient( background: linear-gradient(
to top, to top,
rgb(251 250 246 / 0.9), rgb(17 18 22 / 0.82),
rgb(251 250 246 / 0.52) 34%, rgb(17 18 22 / 0.34) 38%,
rgb(251 250 246 / 0.06) 68%, transparent 66%
transparent
) !important; ) !important;
} }
html[data-theme="subtle-light"] .explore-cluster-label { html[data-theme="subtle-light"] .explore-cluster-label {
color: #6b6257 !important; color: rgb(255 255 255 / 0.62) !important;
} }
html[data-theme="subtle-light"] .explore-cluster-count { html[data-theme="subtle-light"] .explore-cluster-count {
color: #111827 !important; color: #ffffff !important;
} }
html[data-theme="subtle-light"] .explore-tag-word:hover { html[data-theme="subtle-light"] .explore-tag-word::before {
background: #e8e2d6 !important; background: radial-gradient(
} ellipse at center,
rgba(60, 50, 30, 0.13),
html[data-theme="subtle-light"] .explore-tag-word span:first-child { rgba(60, 50, 30, 0.05) 46%,
color: #374151 !important; rgba(60, 50, 30, 0) 72%
) !important;
} }
html[data-theme="subtle-light"] .explore-spinner { html[data-theme="subtle-light"] .explore-spinner {
@@ -220,6 +223,107 @@ html[data-theme="subtle-light"] .explore-spinner {
border-top-color: rgb(17 24 39 / 0.55) !important; border-top-color: rgb(17 24 39 / 0.55) !important;
} }
html[data-theme="subtle-light"] .tag-manager-header {
background: rgb(244 242 234 / 0.72) !important;
border-color: #d8d2c7 !important;
}
html[data-theme="subtle-light"] .tag-manager-stat {
background: rgb(31 41 55 / 0.06) !important;
color: #5f5a52 !important;
}
html[data-theme="subtle-light"] .tag-manager-match {
background: rgb(37 99 235 / 0.12) !important;
color: #1d4ed8 !important;
}
html[data-theme="subtle-light"] .tag-manager-help,
html[data-theme="subtle-light"] .tag-manager-empty {
color: #6f6a61 !important;
}
html[data-theme="subtle-light"] .tag-manager-filter {
background: #fbfaf6 !important;
border-color: #cfc7b8 !important;
color: #111827 !important;
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.64) !important;
}
html[data-theme="subtle-light"] .tag-manager-filter::placeholder {
color: #8a8378 !important;
}
html[data-theme="subtle-light"] .tag-manager-filter:focus {
background: #fffdfa !important;
border-color: #7aa2e3 !important;
}
html[data-theme="subtle-light"] .tag-manager-clear {
color: #6b645a !important;
}
html[data-theme="subtle-light"] .tag-manager-clear:hover {
background: rgb(31 41 55 / 0.08) !important;
color: #111827 !important;
}
html[data-theme="subtle-light"] .tag-manager-tile {
background: rgb(251 250 246 / 0.5) !important;
border-color: rgb(151 141 126 / 0.22) !important;
}
html[data-theme="subtle-light"] .tag-manager-tile:hover,
html[data-theme="subtle-light"] .tag-manager-tile:focus-within {
background: rgb(255 253 250 / 0.74) !important;
border-color: rgb(151 141 126 / 0.36) !important;
}
html[data-theme="subtle-light"] .tag-manager-name {
color: #1f2937 !important;
}
html[data-theme="subtle-light"] .tag-manager-name:hover {
color: #111827 !important;
}
html[data-theme="subtle-light"] .tag-manager-count {
background: rgb(31 41 55 / 0.07) !important;
color: #6b645a !important;
}
html[data-theme="subtle-light"] .tag-manager-edit-input {
background: #fffdfa !important;
color: #111827 !important;
}
html[data-theme="subtle-light"] .tag-manager-secondary,
html[data-theme="subtle-light"] .tag-manager-action {
background: rgb(255 253 250 / 0.92) !important;
border-color: rgb(31 41 55 / 0.12) !important;
color: #5f5a52 !important;
}
html[data-theme="subtle-light"] .tag-manager-secondary:hover,
html[data-theme="subtle-light"] .tag-manager-action:hover {
background: rgb(31 41 55 / 0.06) !important;
color: #111827 !important;
}
html[data-theme="subtle-light"] .tag-manager-save {
color: #1d4ed8 !important;
}
html[data-theme="subtle-light"] .tag-manager-danger,
html[data-theme="subtle-light"] .tag-manager-action-danger:hover {
color: #b91c1c !important;
}
html[data-theme="subtle-light"] .tag-manager-empty {
background: rgb(251 250 246 / 0.42) !important;
border-color: #d8d2c7 !important;
}
html[data-theme="subtle-light"] .feature-scope-trigger { html[data-theme="subtle-light"] .feature-scope-trigger {
background: #f8f6ef !important; background: #f8f6ef !important;
border-color: #d0c8ba !important; border-color: #d0c8ba !important;

Some files were not shown because too many files have changed in this diff Show More