Compare commits
81 Commits
23e9850c7a
...
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
| cad3b9c57d | |||
| e551b15aca | |||
| 0b4459365d | |||
| 4aa74d535b | |||
| 48df4f2965 | |||
| 2bc4a98164 | |||
| 6923777345 | |||
| 96e62cb7c1 | |||
| 42564a93e0 | |||
| b8d009c973 | |||
| dcc1612802 | |||
| 2c699a5aac | |||
| ca5c500e18 | |||
| 782cf0ea08 | |||
| 5004a2d01a | |||
| 9a282dda86 | |||
| b23212ea1c | |||
| a791f112f5 | |||
| 7020a6b6cf | |||
| bf38fac30d | |||
| 79e2e28979 | |||
| aa3fe2062d | |||
| af1a443a64 | |||
| 302a3151ef | |||
| d7c3cbd683 | |||
| 2d567c0810 | |||
| 5ff3ff53a6 | |||
| 827e1a8ecf | |||
| 32c6ae09d6 | |||
| 44179c83a7 | |||
| 4fcc42f356 | |||
| aa3d843a4b | |||
| 01faec9155 | |||
| 3242897a3b | |||
| 8f424773d2 | |||
| 2149b4cad5 | |||
| 2901425f42 | |||
| 1074c875a3 | |||
| 58ecb03070 | |||
| 2c0b928bf5 | |||
| fe312e7678 | |||
| 52ac2543ec | |||
| fbf8a7878c | |||
| 4d41f3744f | |||
| c27662dd74 | |||
| ee2a1b204e | |||
| 6806703363 | |||
| 90fd6f4fed | |||
| 053a2bd846 | |||
| 54016df830 | |||
| 5d46ee5b94 | |||
| 83081928f6 | |||
| e374ff6b02 | |||
| 3ab9357d6f | |||
| fe65bc6f38 | |||
| 68932b55c5 | |||
| f1116c6c26 | |||
| b92b850d02 | |||
| bf04df7484 | |||
| d29a779c13 | |||
| b7e82dbf91 | |||
| 749b23723a | |||
| 68d19d219e | |||
| 31b46327fd | |||
| 29d9106039 | |||
| a78111c8d4 | |||
| 4cdbc54d18 | |||
| d5b93b2e21 | |||
| 257b2b54e7 | |||
| d619b01f2e | |||
| 1a971899d1 | |||
| 8fe5daf25d | |||
| 619bd0c9d2 | |||
| 996bb71375 | |||
| 0d9229635b | |||
| cdb8aa20b9 | |||
| d2af84d9e8 | |||
| 68a9df5ab3 | |||
| 79ce458fd5 | |||
| a9a8f8422e | |||
| ab7022e118 |
@@ -0,0 +1,22 @@
|
||||
# Keep LF in the working copy for all text files (prettier enforces LF)
|
||||
* text=auto eol=lf
|
||||
|
||||
# Windows scripts that genuinely need CRLF
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
|
||||
# Binary assets — never touch line endings
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.webp binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.icns binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.ttf binary
|
||||
*.otf binary
|
||||
*.mp4 binary
|
||||
*.onnx binary
|
||||
@@ -4,16 +4,39 @@ on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.github/workflows/ci.yml'
|
||||
# CHANGELOG.md is a build input: src/changelog.ts imports it ?raw for
|
||||
# the What's New modal, and changelog.test.ts asserts on its content.
|
||||
- 'CHANGELOG.md'
|
||||
- 'index.html'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'src/**'
|
||||
- 'src-tauri/**'
|
||||
- 'tsconfig*.json'
|
||||
- 'vite.config.ts'
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/ci.yml'
|
||||
# CHANGELOG.md is a build input: src/changelog.ts imports it ?raw for
|
||||
# the What's New modal, and changelog.test.ts asserts on its content.
|
||||
- 'CHANGELOG.md'
|
||||
- 'index.html'
|
||||
- 'package.json'
|
||||
- 'pnpm-lock.yaml'
|
||||
- 'pnpm-workspace.yaml'
|
||||
- 'src/**'
|
||||
- 'src-tauri/**'
|
||||
- 'tsconfig*.json'
|
||||
- 'vite.config.ts'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
@@ -21,7 +44,9 @@ jobs:
|
||||
# windows-latest to match the release target — the ML crates (ort, candle)
|
||||
# and the NSIS bundle only ever ship from Windows.
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
GITEA_STATUS_TOKEN: ${{ secrets.GITEA_STATUS_TOKEN }}
|
||||
steps:
|
||||
- name: Report pending status to Gitea
|
||||
@@ -58,10 +83,14 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Unit tests
|
||||
run: pnpm test:unit
|
||||
|
||||
# tsc + vite build; also produces dist/ which tauri's build script expects
|
||||
- name: Type-check and build frontend
|
||||
run: pnpm build:vite
|
||||
@@ -85,6 +114,10 @@ jobs:
|
||||
working-directory: src-tauri
|
||||
run: cargo clippy --all-targets --locked --no-default-features -- -D warnings
|
||||
|
||||
- name: Rust tests
|
||||
working-directory: src-tauri
|
||||
run: cargo test --locked --no-default-features
|
||||
|
||||
- name: Report final status to Gitea
|
||||
if: always() && github.event_name != 'pull_request' && env.GITEA_STATUS_TOKEN != ''
|
||||
continue-on-error: true
|
||||
|
||||
@@ -8,15 +8,59 @@ on:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Existing release tag to build, for example v0.1.1'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
permissions:
|
||||
contents: write
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 120
|
||||
env:
|
||||
CARGO_INCREMENTAL: 0
|
||||
GITEA_STATUS_TOKEN: ${{ secrets.GITEA_STATUS_TOKEN }}
|
||||
RELEASE_TAG: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
steps:
|
||||
# refs/tags/ qualification: a branch with a tag-like name must never win
|
||||
# ref resolution. Works for tag pushes too — RELEASE_TAG is the tag name.
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: refs/tags/${{ env.RELEASE_TAG }}
|
||||
|
||||
# On workflow_dispatch GITHUB_SHA is the dispatched branch head, not the
|
||||
# tag's commit — resolve the real one for Gitea commit statuses.
|
||||
- name: Resolve release commit
|
||||
shell: pwsh
|
||||
run: |
|
||||
$sha = git rev-parse HEAD
|
||||
"RELEASE_SHA=$sha" | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
|
||||
- name: Verify release version
|
||||
shell: pwsh
|
||||
run: |
|
||||
if ($env:RELEASE_TAG -notmatch '^v\d+\.\d+\.\d+(-.+)?$') {
|
||||
throw "Release tag '$env:RELEASE_TAG' must look like v0.1.1"
|
||||
}
|
||||
|
||||
$packageVersion = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
||||
$cargoVersion = (Select-String -Path src-tauri/Cargo.toml -Pattern '^version\s*=\s*"(.+)"').Matches[0].Groups[1].Value
|
||||
|
||||
if ($packageVersion -ne $cargoVersion) {
|
||||
throw "package.json version ($packageVersion) does not match Cargo.toml version ($cargoVersion)"
|
||||
}
|
||||
|
||||
if ($env:RELEASE_TAG -ne "v$packageVersion") {
|
||||
throw "Release tag '$env:RELEASE_TAG' does not match project version v$packageVersion"
|
||||
}
|
||||
|
||||
- name: Report pending status to Gitea
|
||||
if: env.GITEA_STATUS_TOKEN != ''
|
||||
continue-on-error: true
|
||||
@@ -36,13 +80,11 @@ jobs:
|
||||
} | ConvertTo-Json
|
||||
Invoke-RestMethod `
|
||||
-Method Post `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$env:GITHUB_SHA" `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$env:RELEASE_SHA" `
|
||||
-Headers $headers `
|
||||
-ContentType "application/json" `
|
||||
-Body $body
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 11
|
||||
@@ -51,6 +93,7 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
cache-dependency-path: pnpm-lock.yaml
|
||||
|
||||
- name: Install Rust stable
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
@@ -71,7 +114,7 @@ jobs:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }}
|
||||
with:
|
||||
tagName: ${{ github.ref_name }}
|
||||
tagName: ${{ env.RELEASE_TAG }}
|
||||
releaseName: 'Phokus v__VERSION__'
|
||||
releaseBody: 'See the assets below to download and install this version.'
|
||||
releaseDraft: true
|
||||
@@ -105,9 +148,11 @@ jobs:
|
||||
description = "GitHub Actions release finished: $env:JOB_STATUS"
|
||||
target_url = $env:GITHUB_RUN_URL
|
||||
} | ConvertTo-Json
|
||||
# RELEASE_SHA is unset if the job died before checkout; fall back.
|
||||
$sha = if ($env:RELEASE_SHA) { $env:RELEASE_SHA } else { $env:GITHUB_SHA }
|
||||
Invoke-RestMethod `
|
||||
-Method Post `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$env:GITHUB_SHA" `
|
||||
-Uri "https://git.jezz.wtf/api/v1/repos/JezzWTF/phokus/statuses/$sha" `
|
||||
-Headers $headers `
|
||||
-ContentType "application/json" `
|
||||
-Body $body
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Build outputs
|
||||
dist/
|
||||
build/
|
||||
|
||||
# Tauri / Rust (handled by cargo fmt)
|
||||
src-tauri/
|
||||
|
||||
# Lock files & generated
|
||||
pnpm-lock.yaml
|
||||
*.lock
|
||||
|
||||
# Generated
|
||||
src/vite-env.d.ts
|
||||
|
||||
# Public assets
|
||||
public/
|
||||
|
||||
# Website subpackage (has its own config if needed)
|
||||
website/
|
||||
|
||||
# Markdown & docs (hand-written or tool-generated, keep diffs quiet)
|
||||
*.md
|
||||
docs/
|
||||
|
||||
# CI workflows
|
||||
.github/
|
||||
.gitea/
|
||||
|
||||
# Tool-managed config
|
||||
.claude/
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": false,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 100,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"bracketSpacing": true,
|
||||
"bracketSameLine": false,
|
||||
"arrowParens": "always",
|
||||
"endOfLine": "lf",
|
||||
"plugins": ["prettier-plugin-tailwindcss"]
|
||||
}
|
||||
+133
-121
@@ -5,137 +5,148 @@ All notable changes to Phokus are documented here. The format is based on
|
||||
aims to follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
|
||||
(0.x: anything may change between minor versions).
|
||||
|
||||
## [Unreleased]
|
||||
## [0.2.0] — 2026-07-11
|
||||
|
||||
### Added
|
||||
|
||||
- **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.
|
||||
- **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.
|
||||
toast that opens a tidy in-app tour of the new version. Added, Changed, and
|
||||
Fixed notes are grouped into collapsible sections, so you can skim the good
|
||||
bits without playing "spot the difference".
|
||||
- **Quick theme switch** — right-click the settings cog in the title bar to
|
||||
swap between Phokus, Subtle Light, and Conventional Dark instantly. No Settings
|
||||
detour required.
|
||||
- **Albums** — make your own cross-folder collections without moving a single
|
||||
file. Albums live in their own sidebar section with cover thumbnails, can be
|
||||
created, renamed, reordered, opened, and cleaned up in Manage mode, and deleting
|
||||
one only removes the grouping.
|
||||
- **Gallery multi-select** — hover a thumbnail's top-left corner to start
|
||||
selecting, then use the floating action bar to tag, rate, favorite, add to an
|
||||
album, or delete a whole batch at once. It also works in similar-image, region,
|
||||
and album views, because bulk work should not disappear the moment you need it.
|
||||
- **Colour search** — narrow the Gallery, Timeline, or tag results by dominant
|
||||
colour using toolbar swatches or a custom picker. Great for those "I know it
|
||||
was mostly blue" moments.
|
||||
- **Album-aware similar search** — similar-image and region searches started from
|
||||
an album can now stay inside that album, jump back to the source folder, or
|
||||
search everything.
|
||||
- **Tag manager** — Explore's Tag Cloud now has a Manage mode for renaming,
|
||||
merging, and deleting tags across the whole library.
|
||||
- **Camera info in the lightbox** — the info panel now shows EXIF details like
|
||||
camera, lens, aperture, shutter speed, ISO, and focal length. Geotagged photos
|
||||
also get a browser link for their GPS coordinates, and already-indexed images
|
||||
do not need a re-index.
|
||||
- **Build badge in Settings** — Settings -> Updates now shows whether you are
|
||||
running the CPU build or the CUDA build.
|
||||
- **Choose your tagging model** — Settings -> AI Workspace now lets you pick
|
||||
between the anime-focused WD tagger and JoyTag, which is better suited to photo
|
||||
libraries and stronger on NSFW concepts (if that's your thing, we don't judge).
|
||||
New users get the same choice during the welcome tour, and each model keeps its
|
||||
own confidence threshold instead of sharing one.
|
||||
- **Reset AI tags** — a new reset action in Settings -> AI Workspace and the Tag
|
||||
manager wipes AI-generated tags for a folder or the whole library, cancelling
|
||||
any tagging still in flight. Tag manager rows now show which tags came from the
|
||||
AI, so you know what you are about to lose before you lose it. Manually-added
|
||||
tags are never touched.
|
||||
- **Related tags in Explore** — Hover over a tag in the Tag Cloud to see the tags
|
||||
that most often appear with it, complete with connection lines and image counts.
|
||||
Handy for finding little clusters you did not know were there.
|
||||
- **Pause workers for longer** — Settings -> General can now remember per-folder
|
||||
worker pauses across app restarts, useful for folders you want to keep in the
|
||||
library but leave out of background processing for now.
|
||||
- **Editable folder path** — the folder picker now has an address bar, so you can
|
||||
paste a path directly while still using breadcrumbs for quick jumps.
|
||||
- **Slideshow mode** — turn the lightbox into a fullscreen, image-only slideshow
|
||||
from whatever collection you are already browsing.
|
||||
- **Add to album from the right-click menu** — right-click any image in the
|
||||
Gallery or Timeline and file it straight into an album from the new "Add to
|
||||
Album" submenu. One image, one click, zero ceremony.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Tag manager search and sort** — the Manage mode tag list now has a live
|
||||
filter input and a sort dropdown (most-used / least-used / A–Z / Z–A). 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.
|
||||
- **Settings got a spring clean** — preferences are now organised into General,
|
||||
Media, Updates & Setup, Storage, and AI Workspace pages, so update and
|
||||
maintenance controls no longer hide at the bottom of unrelated sections.
|
||||
- **Menus got their act together** — right-click menus (images, folders,
|
||||
albums, the theme switcher) and every dropdown (sort, folder scope, settings,
|
||||
sidebar) now share one style with one set of manners: they stay on screen
|
||||
instead of wandering off the edge, all close on Escape, and right-click menus
|
||||
can do proper submenus now. Subtle Light dresses them all the same way too,
|
||||
instead of saving the nice outfit for one dropdown.
|
||||
- **Neater lightbox details** — image and video metadata now sits in two columns,
|
||||
so the info panel shows more at a glance with less scrolling.
|
||||
- **Faster Explore revisits** — returning to a folder's visual clusters should
|
||||
feel much faster now, even in big libraries.
|
||||
- **Calmer Tag Cloud during AI tagging** — Explore no longer keeps hammering the
|
||||
tag list while a folder is actively being tagged, so tagging stays smoother and
|
||||
the cloud catches up once the work settles.
|
||||
- **Faster first-time clustering** — large libraries build their first visual
|
||||
clusters much more quickly, while still keeping the groups nicely balanced.
|
||||
- **Better tag browsing** — the Tag manager now has live search, sorting
|
||||
(most-used, least-used, A-Z, and Z-A), smooth scrolling for huge tag lists, and
|
||||
it keeps your filter/sort in place while you edit.
|
||||
- **Safer deletion** — deleting media now asks for confirmation and clearly says
|
||||
the file is being removed from disk. This covers gallery bulk delete and the
|
||||
Duplicate Finder.
|
||||
- **Clearer update progress** — Settings -> Updates now shows a real download
|
||||
progress bar with a percentage instead of the old lonely "Downloading" label.
|
||||
- **Better narrow-window layout** — the toolbar, filters, search box, colour
|
||||
picker, sidebar, and lightbox info panel now adapt more gracefully when the
|
||||
window is short on space.
|
||||
- **Tidier Explore clusters** — busier clusters get more room, dense groups
|
||||
overlap less, and everything should stay easier to read and click.
|
||||
- **Faster CPU tagging** — CPU-only AI tagging can now use multiple cores while
|
||||
leaving some breathing room for the rest of the app. GPU tagging is unchanged.
|
||||
- **Smoother tooltips** — Phokus now uses its custom tooltip style across more of
|
||||
the app instead of falling back to the native browser tooltip.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **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.
|
||||
- **Explore no longer flashes the last folder** — switching folders now clears
|
||||
the old clusters/tags and shows a loading state while the new folder catches
|
||||
up.
|
||||
- **Ratings keep your search order** — if you ever rated an image mid-search and
|
||||
watched your results reshuffle themselves, that's over. Similar-image, region,
|
||||
semantic, tag, and album results now stay put.
|
||||
- **Update progress comes back when you need it** — if you dismiss the update
|
||||
prompt and later start the update from the title bar or Settings, the progress
|
||||
toast now reappears instead of hiding away in Settings.
|
||||
- **Subtle Light cleanup** — fixed dark or hard-to-read surfaces, hover states,
|
||||
dialogs, updater buttons, onboarding controls, and green action buttons in the
|
||||
light theme.
|
||||
- **No more self-indexing loops** — adding a broad folder like your whole user
|
||||
profile used to send Phokus off indexing its own thumbnail cache, generating
|
||||
thumbnails of thumbnails until the end of time. It now skips its own app-data
|
||||
directory.
|
||||
- **Background tasks show the active work first** — when one folder is paused and
|
||||
another is processing, the active folder gets the main spot in the background
|
||||
tasks bar.
|
||||
- **First launch fits smaller screens** — on 1366x768-style displays, fresh
|
||||
installs used to open with part of the app tucked below the taskbar. The window
|
||||
now clamps itself to the usable monitor area.
|
||||
- **Explore is clearer in Subtle Light** — cluster captions, buttons, cloud
|
||||
words, hover glows, and the new connection lines now use stronger light-theme
|
||||
colours.
|
||||
- **Explore got a few sharp edges sanded down** — Cluster Cloud uses the in-app
|
||||
tooltip, singular counts now say "1 image", and the folder-scope dropdown no
|
||||
longer hides behind cluster cards.
|
||||
- **AI tagging stays responsive** — starting a big tagging job used to turn the
|
||||
rest of the app into a slideshow. GPU tagging now works in smaller bursts with
|
||||
brief pauses between them, so the UI keeps moving and the first results land
|
||||
sooner.
|
||||
- **Lightbox AI tags wake up on time** — the lightbox's AI tags action no longer
|
||||
stays disabled until you happen to open Settings, and it switches on as soon as
|
||||
a model download finishes.
|
||||
- **Noisy AI tags get cleaned up** — generic low-signal tags from WD and JoyTag
|
||||
are filtered before they are saved, and matching older generated tags are
|
||||
cleaned up on startup. Your manually-added tags are left alone.
|
||||
- **Selected Folders starts empty** — choosing "Selected Folders" for AI tagging
|
||||
no longer pre-selects the first folder. You decide exactly what gets queued.
|
||||
- **A handful of tiny UI papercuts are gone** — the zoom buttons now show the
|
||||
right tile size when you hover them, the folder picker no longer adds an odd
|
||||
trailing slash to Windows drive breadcrumbs, the search field's clear button
|
||||
no longer sits a few pixels too high, and menu labels no longer highlight like
|
||||
text when you drag across them.
|
||||
|
||||
## [0.1.1] — 2026-06-23
|
||||
|
||||
@@ -253,5 +264,6 @@ installer with a built-in updater.
|
||||
Settings, with live size/reclaimable stats.
|
||||
- **Window state** persistence and single-instance handling.
|
||||
|
||||
[0.2.0]: https://github.com/JezzWTF/phokus/releases/tag/v0.2.0
|
||||
[0.1.1]: https://github.com/JezzWTF/phokus/releases/tag/v0.1.1
|
||||
[0.1.0]: https://github.com/JezzWTF/phokus/releases/tag/v0.1.0
|
||||
|
||||
@@ -15,6 +15,9 @@ pnpm dev:app
|
||||
# Frontend only (no Tauri window)
|
||||
pnpm dev:vite
|
||||
|
||||
# UI Lab — browser-only frontend with mocked Tauri backend (http://127.0.0.1:1422)
|
||||
pnpm dev:ui
|
||||
|
||||
# Production build (CPU)
|
||||
pnpm build:app:cpu
|
||||
|
||||
@@ -23,27 +26,56 @@ pnpm build:app:cuda
|
||||
|
||||
# Type-check frontend
|
||||
pnpm build:vite
|
||||
|
||||
# Frontend unit tests (Vitest; only picks up src/**/*.test.ts)
|
||||
pnpm test:unit
|
||||
pnpm test:unit:watch
|
||||
|
||||
# Rust unit tests (in-memory SQLite; --no-default-features skips CUDA)
|
||||
pnpm test:rust
|
||||
|
||||
# E2E tests (Playwright against the UI Lab; auto-starts the server)
|
||||
pnpm test:e2e
|
||||
pnpm exec playwright test tests/ui-lab.spec.ts # single file
|
||||
pnpm exec playwright test -g "filename search" # single test by name
|
||||
|
||||
# Formatting (Prettier + prettier-plugin-tailwindcss; cargo fmt for Rust)
|
||||
pnpm format:all
|
||||
```
|
||||
|
||||
Use **pnpm** — never npm.
|
||||
|
||||
There are no test suites configured.
|
||||
Three test layers, none of which exercise the real Tauri window:
|
||||
- **Vitest unit tests** — co-located `*.test.ts` next to the pure logic they cover (`src/store/helpers.ts`, formatters, path utils); fixture factories in `src/test/factories.ts`.
|
||||
- **Rust unit tests** — inline `#[cfg(test)]` modules; DB tests run against in-memory SQLite via the shared `db::test_support` fixture (`test_conn()` + `test_image()`), which registers sqlite-vec and applies both migrations. Reuse it for any new DB-touching tests.
|
||||
- **Playwright e2e smoke tests** in `tests/` — run against the UI Lab (browser mocks).
|
||||
|
||||
## Architecture
|
||||
|
||||
### Frontend (`src/`)
|
||||
|
||||
- **`store.ts`** — single Zustand store (`useGalleryStore`) that owns all app state and all `invoke()` calls to the Tauri backend. Every feature (folders, images, search, similar images, tags, captions, tagger, duplicates) is implemented as store actions here. React components are thin consumers.
|
||||
- **`src/store/`** — single Zustand store (`useGalleryStore`) that owns all app state and all `invoke()` calls to the Tauri backend, split into per-feature slices combined in `index.ts` (which exports `useGalleryStore` and the `GalleryStore` type). `types.ts` holds all interfaces/type unions (including `ImageRecord`); `helpers.ts` holds pure functions and cross-slice module state (search parsing, image sort/merge, request-token guards). Slices: `librarySlice` (folders), `gallerySlice` (image paging/filters/bulk actions), `searchSlice` (search + similar-images), `exploreSlice` (visual clusters, tag cloud, tags), `albumSlice`, `duplicateSlice`, `taggerSlice`, `captionSlice`, `settingsSlice`, `appSlice` (updates, onboarding, ffmpeg, worker pauses); `events.ts` wires the Tauri event listeners (`subscribeToProgress`). Components still call `useGalleryStore(s => s.field)` against one flat state object — the slice split is internal. React components are thin consumers.
|
||||
- **`App.tsx`** — sets up Tauri event listeners (`subscribeToProgress`) and renders the top-level layout (sidebar + active view).
|
||||
- **`src/components/`** — UI components: `Gallery`, `Lightbox`, `Sidebar`, `Toolbar`, `TagCloud`, `DuplicateFinder`, `BackgroundTasks`, `SettingsModal`, `MenuBar`, `TitleBar`.
|
||||
- **`src/components/`** — UI components: `Gallery`, `Lightbox`, `Sidebar`, `Toolbar`, `Timeline`, `ExploreView`, `DuplicateFinder`, `BackgroundTasks`, `SettingsModal`, `TitleBar`.
|
||||
- **`src/components/menu/`** — shared floating-UI primitives: `useDismissable`, `MenuPanel`/`MenuItem`/`SubMenu`, the portal-based `ContextMenu`, and the app-wide `Dropdown`. Build menus, dropdowns, and popovers on these instead of hand-rolling.
|
||||
- State management: Zustand v5, no selectors library — components call `useGalleryStore(s => s.field)` directly.
|
||||
- Styling: Tailwind CSS v4 (Vite plugin, no config file).
|
||||
- Virtualized gallery grid: `@tanstack/react-virtual`.
|
||||
- Animation: `framer-motion`.
|
||||
|
||||
### UI Lab (`src/dev/`)
|
||||
|
||||
`pnpm dev:ui` runs the real frontend (same `App.tsx`, store, components, CSS) in a plain browser with Tauri fully mocked — no Rust backend or Tauri window. `src/main.tsx` imports `src/dev/setupMockTauri.ts` before `App` in `ui` mode; `mockBackend.ts` implements an in-memory command backend, with fixtures in `mockFixtures.ts`/`mockScenarios.ts`. Pick a seeded state via `?scenario=` (`rich` default; also `empty`, `new-user`, `just-updated`, `busy`, `duplicates`, `album`, `errors`, `huge`) and a What's New entry via `?changelog=`. `Ctrl+Shift+D` opens the demo panel. Full guide: `docs/ui-lab.md`.
|
||||
|
||||
Rules that keep UI Lab working:
|
||||
- Components that render thumbnails/covers/posters must use `mediaSrc(...)` from `src/lib/mediaSrc.ts`, never `convertFileSrc(...)` directly.
|
||||
- New Tauri commands invoked from the frontend need a mock in `src/dev/mockBackend.ts` (unmocked commands log console errors, which fail the e2e tests).
|
||||
|
||||
UI Lab is for visual/layout work and agent browser inspection. Native behavior (file pickers, real thumbnails, window controls, updater) must still be validated in `pnpm dev:app`.
|
||||
|
||||
### Search modes
|
||||
|
||||
The search bar supports prefix syntax parsed by `parseSearchValue` in `store.ts`:
|
||||
The search bar supports prefix syntax parsed by `parseSearchValue` in `src/store/helpers.ts`:
|
||||
- No prefix / `f:` — filename search (paginated, DB-backed)
|
||||
- `/s <query>` or `s: <query>` — semantic (embedding) search
|
||||
- `/t <tag>` or `t: <tag>` — tag search
|
||||
@@ -67,6 +99,8 @@ Key modules:
|
||||
| `hnsw_index.rs` | In-memory HNSW index wrapper (hnsw_rs) |
|
||||
| `tagger.rs` | WD tagger: ONNX model download, inference, CSV tag loading |
|
||||
| `captioner.rs` | AI captioning (ONNX, disabled in workers but code intact) |
|
||||
| `download.rs` | Resilient file downloads via the system `curl` (resume, stall detection) |
|
||||
| `onnx_runtime.rs` | Shared ONNX Runtime DLL provisioning + `ort` init (used by tagger and captioner; DLLs live in the caption model dir for legacy reasons) |
|
||||
| `thumbnail.rs` | Thumbnail generation (image crate + fast_image_resize, FFmpeg for video) |
|
||||
| `media.rs` | FFmpeg sidecar provisioning and probing |
|
||||
| `storage.rs` | `StorageProfile` for tuning worker counts |
|
||||
@@ -87,7 +121,7 @@ Database: SQLite with WAL mode, stored in the Tauri app data directory as `galle
|
||||
|
||||
### Key types
|
||||
|
||||
`ImageRecord` (mirrored in `store.ts` and `db.rs`) is the central data type. It carries embedding status, tagging status, caption data, and media metadata. The frontend type must stay in sync with the Rust struct serialization.
|
||||
`ImageRecord` (mirrored in `src/store/types.ts` and `db.rs`) is the central data type. It carries embedding status, tagging status, caption data, and media metadata. The frontend type must stay in sync with the Rust struct serialization.
|
||||
|
||||
## Development notes
|
||||
|
||||
@@ -95,3 +129,5 @@ Database: SQLite with WAL mode, stored in the Tauri app data directory as `galle
|
||||
- ML inference crates (`candle-*`, `ort`, `image`, `rayon`, `tokenizers`, `xxhash-rust`, `rusqlite`) use `opt-level = 3` in dev profile to keep inference performance acceptable.
|
||||
- The caption worker is intentionally disabled (`lib.rs:73`) — the backend code is intact for future re-enabling.
|
||||
- **Never use `any` type** in TypeScript — look up correct types.
|
||||
- `website/` is a separate Vite project for the marketing site (phokus.jezz.wtf): `pnpm dev:web` / `pnpm build:web`. It is not part of the app build.
|
||||
- `pnpm changelog:add -- --type fixed --message "..."` appends an entry to the `[Unreleased]` section of `CHANGELOG.md`, which also feeds the in-app What's New modal (types: added, changed, deprecated, removed, fixed, security).
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# Phokus v0.2.0
|
||||
|
||||
> Draft for the GitHub Release body. Fill in the checksums and trim as needed.
|
||||
|
||||
**Phokus is a local-first desktop media library for Windows** — point it at
|
||||
your image and video folders and it builds a fast, searchable gallery with
|
||||
thumbnails, semantic search, visual discovery, AI tagging, and duplicate
|
||||
cleanup. Everything is processed on your machine; nothing is uploaded.
|
||||
|
||||
0.2.0 is the biggest update since launch: albums, gallery multi-select with
|
||||
bulk actions, colour search, a second AI tagging model (JoyTag), a full tag
|
||||
manager, camera EXIF details in the lightbox, a slideshow mode, and a large
|
||||
batch of performance and theme fixes. Updating from 0.1.x? The built-in
|
||||
updater will fetch this for you — and afterwards, a new in-app "What's New"
|
||||
tour shows you around.
|
||||
|
||||
## Install / update
|
||||
|
||||
- **Updating from 0.1.x:** the in-app updater will offer 0.2.0 on launch — one
|
||||
click downloads, installs, and relaunches.
|
||||
- **Fresh install:** download `Phokus_0.2.0_x64-setup.exe` below and run it.
|
||||
**Windows SmartScreen will warn** that the publisher is unrecognized — this
|
||||
build is **not code-signed**. Click **More info → Run anyway**.
|
||||
- Requires **Windows 10/11**. WebView2 is fetched automatically if missing.
|
||||
|
||||
NVIDIA users wanting GPU embedding/tagging speed can use the
|
||||
`Phokus_0.2.0_x64-cuda-setup.exe` variant instead (larger download; bundles the
|
||||
CUDA runtime DLLs). Settings → Updates now shows which build you are running.
|
||||
|
||||
## Highlights
|
||||
|
||||
### Added
|
||||
- **Albums** — cross-folder collections without moving files: their own
|
||||
sidebar section with cover thumbnails, create/rename/reorder/manage, and
|
||||
album-aware similar-image search.
|
||||
- **Gallery multi-select** — hover a thumbnail's corner to start selecting,
|
||||
then bulk tag, rate, favorite, add to an album, or delete from a floating
|
||||
action bar. Works in similar-image, region, and album views too.
|
||||
- **Colour search** — filter the Gallery, Timeline, or tag results by dominant
|
||||
colour via toolbar swatches or a custom picker.
|
||||
- **Choose your tagging model** — pick between the anime-focused WD tagger and
|
||||
**JoyTag** (better for photo libraries), each with its own confidence
|
||||
threshold, plus a **Reset AI tags** action that never touches manual tags.
|
||||
- **Tag manager** — rename, merge, and delete tags across the library, with
|
||||
live search and sorting; Explore's Tag Cloud also shows **related tags** on
|
||||
hover.
|
||||
- **Camera info in the lightbox** — EXIF camera, lens, aperture, shutter
|
||||
speed, ISO, focal length, and a map link for geotagged photos.
|
||||
- **Slideshow mode**, **What's New tour after updates**, **quick theme switch**
|
||||
from the title bar, an editable path bar in the folder picker, persistent
|
||||
per-folder worker pauses, and add-to-album from the right-click menu.
|
||||
|
||||
### Changed
|
||||
- **Settings reorganised** into General, Media, Updates & Setup, Storage, and
|
||||
AI Workspace pages.
|
||||
- **Menus unified** — all context menus and dropdowns share one style, stay on
|
||||
screen, close on Escape, and support submenus.
|
||||
- **Faster Explore** — quicker cluster revisits, much faster first-time
|
||||
clustering on large libraries, and a calmer Tag Cloud during active tagging.
|
||||
- **Faster CPU tagging** (multi-core with headroom) and smoother GPU tagging.
|
||||
- **Safer deletion** — deleting media now asks for confirmation and says
|
||||
clearly that files are removed from disk.
|
||||
- Better narrow-window layouts, a real update download progress bar, and a
|
||||
two-column lightbox info panel.
|
||||
|
||||
### Fixed
|
||||
- **No more self-indexing loops** — Phokus now skips its own thumbnail cache
|
||||
when you add a broad folder like your user profile.
|
||||
- **Ratings keep your search order** — rating an image mid-search no longer
|
||||
reshuffles similar-image, region, semantic, tag, or album results.
|
||||
- **AI tagging stays responsive** — big GPU tagging jobs no longer freeze the
|
||||
UI, and noisy low-signal tags are filtered (older ones cleaned up on
|
||||
startup).
|
||||
- First launch now fits smaller screens, Explore no longer flashes the
|
||||
previous folder, and a long list of Subtle Light readability fixes.
|
||||
|
||||
See the [changelog](https://github.com/JezzWTF/phokus/blob/main/CHANGELOG.md)
|
||||
for the full list.
|
||||
|
||||
## Checksums
|
||||
|
||||
```
|
||||
SHA-256 (Phokus_0.2.0_x64-setup.exe) = TBD
|
||||
SHA-256 (Phokus_0.2.0_x64-cuda-setup.exe) = TBD
|
||||
```
|
||||
+21
-2
@@ -22,7 +22,7 @@ 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
|
||||
vite --mode ui --host 127.0.0.1 --port 1422 --strictPort
|
||||
```
|
||||
|
||||
The normal app development commands are unchanged:
|
||||
@@ -40,7 +40,9 @@ UI Lab reads `?scenario=` from the URL. If no scenario is provided, it uses
|
||||
| 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=empty` | Empty library with no folders or media (onboarding already completed) |
|
||||
| `/?scenario=new-user` | True first run: onboarding tour open, empty library, no tagger model downloaded |
|
||||
| `/?scenario=just-updated` | Rich library that has just been updated — the "What's new" toast fires on launch |
|
||||
| `/?scenario=busy` | Background workers with pending thumbnail, metadata, embedding, caption, and tagging jobs |
|
||||
| `/?scenario=duplicates` | Duplicate Finder opened with duplicate groups already available |
|
||||
| `/?scenario=album` | Gallery opened directly into an album |
|
||||
@@ -55,6 +57,23 @@ http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
```
|
||||
|
||||
## Changelog Previews
|
||||
|
||||
The What's New modal adapts its layout to release size (compact single column
|
||||
for small releases, a two-pane section rail for large ones). UI Lab reads
|
||||
`?changelog=` to override which entry the modal shows:
|
||||
|
||||
| URL | Purpose |
|
||||
| --- | --- |
|
||||
| `/?changelog=unreleased` | The in-progress `[Unreleased]` notes — large release, rail layout |
|
||||
| `/?changelog=small` | Synthetic hotfix-sized entry — compact single-column layout |
|
||||
| `/?changelog=0.1.1` | Any specific released version |
|
||||
|
||||
Open the modal via the demo panel: `Ctrl+Shift+D` → Open "What's new" modal.
|
||||
|
||||
Combine with the scenario above to walk the whole post-update greeting for the
|
||||
next release: `/?scenario=just-updated&changelog=unreleased`.
|
||||
|
||||
## How It Works
|
||||
|
||||
`src/main.tsx` bootstraps the app asynchronously. In `ui` mode it imports
|
||||
|
||||
+16
-6
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "phokus",
|
||||
"private": true,
|
||||
"version": "0.1.1",
|
||||
"version": "0.2.0",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -13,13 +13,20 @@
|
||||
"clean:app": "cd src-tauri && cargo clean",
|
||||
"dev:app": "tauri dev",
|
||||
"dev:app:cpu": "tauri dev -- --no-default-features",
|
||||
"dev:ui": "vite --mode ui --host 127.0.0.1 --port 1422 --strictPort --open",
|
||||
"dev:ui": "vite --mode ui --host 127.0.0.1 --port 1422 --strictPort",
|
||||
"dev:vite": "vite",
|
||||
"dev:web": "cd website && pnpm dev",
|
||||
"format:app": "cd src-tauri && cargo fmt",
|
||||
"format:check": "cd src-tauri && cargo fmt --check",
|
||||
"format": "prettier --write .",
|
||||
"format:all": "pnpm format && pnpm format:rust",
|
||||
"format:check": "prettier --check .",
|
||||
"format:rust": "cd src-tauri && cargo fmt",
|
||||
"format:rust:check": "cd src-tauri && cargo fmt --check",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
"tauri": "tauri",
|
||||
"test:e2e": "playwright test",
|
||||
"test:rust": "cd src-tauri && cargo test --no-default-features",
|
||||
"test:unit": "vitest run",
|
||||
"test:unit:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-virtual": "^3.13.23",
|
||||
@@ -45,8 +52,11 @@
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/react-dom": "^19.1.6",
|
||||
"@vitejs/plugin-react": "^4.6.0",
|
||||
"prettier": "^3.9.4",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^7.0.4"
|
||||
"vite": "^7.0.4",
|
||||
"vitest": "^4.1.9"
|
||||
}
|
||||
}
|
||||
|
||||
+11
-15
@@ -1,4 +1,4 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
import { defineConfig, devices } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* Read environment variables from file.
|
||||
@@ -20,13 +20,13 @@ export default defineConfig({
|
||||
/* Retry on CI only */
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
/* Opt out of parallel tests on CI. */
|
||||
workers: process.env.CI ? 1 : undefined,
|
||||
workers: process.env.CI ? 1 : 4,
|
||||
/* 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',
|
||||
baseURL: 'http://127.0.0.1:1422',
|
||||
|
||||
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
|
||||
trace: 'on-first-retry',
|
||||
@@ -39,11 +39,6 @@ export default defineConfig({
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
|
||||
{
|
||||
name: 'firefox',
|
||||
use: { ...devices['Desktop Firefox'] },
|
||||
},
|
||||
|
||||
{
|
||||
name: 'webkit',
|
||||
use: { ...devices['Desktop Safari'] },
|
||||
@@ -70,10 +65,11 @@ export default defineConfig({
|
||||
// },
|
||||
],
|
||||
|
||||
/* Run your local dev server before starting the tests */
|
||||
// webServer: {
|
||||
// command: 'npm run start',
|
||||
// url: 'http://localhost:3000',
|
||||
// reuseExistingServer: !process.env.CI,
|
||||
// },
|
||||
});
|
||||
/* Run the Phokus UI Lab (browser-only dev mode, see docs/ui-lab.md) before starting the tests */
|
||||
webServer: {
|
||||
command: 'pnpm exec vite --mode ui --host 127.0.0.1 --port 1422 --strictPort',
|
||||
url: 'http://127.0.0.1:1422',
|
||||
reuseExistingServer: !process.env.CI,
|
||||
timeout: 120_000,
|
||||
},
|
||||
})
|
||||
|
||||
Generated
+314
@@ -72,6 +72,12 @@ importers:
|
||||
'@vitejs/plugin-react':
|
||||
specifier: ^4.6.0
|
||||
version: 4.7.0(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
prettier:
|
||||
specifier: ^3.9.4
|
||||
version: 3.9.4
|
||||
prettier-plugin-tailwindcss:
|
||||
specifier: ^0.8.0
|
||||
version: 0.8.0(prettier@3.9.4)
|
||||
tailwindcss:
|
||||
specifier: ^4.2.2
|
||||
version: 4.2.2
|
||||
@@ -81,6 +87,9 @@ importers:
|
||||
vite:
|
||||
specifier: ^7.0.4
|
||||
version: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
vitest:
|
||||
specifier: ^4.1.9
|
||||
version: 4.1.9(@types/node@26.0.1)(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
|
||||
website:
|
||||
dependencies:
|
||||
@@ -699,6 +708,9 @@ packages:
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@standard-schema/spec@1.1.0':
|
||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||
|
||||
'@tailwindcss/node@4.2.2':
|
||||
resolution: {integrity: sha512-pXS+wJ2gZpVXqFaUEjojq7jzMpTGf8rU6ipJz5ovJV6PUGmlJ+jvIwGrzdHdQ80Sg+wmQxUFuoW1UAAwHNEdFA==}
|
||||
|
||||
@@ -911,9 +923,15 @@ packages:
|
||||
'@types/babel__traverse@7.28.0':
|
||||
resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||
|
||||
'@types/d3-force@3.0.10':
|
||||
resolution: {integrity: sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw==}
|
||||
|
||||
'@types/deep-eql@4.0.2':
|
||||
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
|
||||
|
||||
'@types/estree@1.0.8':
|
||||
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
|
||||
|
||||
@@ -934,6 +952,39 @@ packages:
|
||||
peerDependencies:
|
||||
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
|
||||
|
||||
'@vitest/expect@4.1.9':
|
||||
resolution: {integrity: sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==}
|
||||
|
||||
'@vitest/mocker@4.1.9':
|
||||
resolution: {integrity: sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==}
|
||||
peerDependencies:
|
||||
msw: ^2.4.9
|
||||
vite: ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
peerDependenciesMeta:
|
||||
msw:
|
||||
optional: true
|
||||
vite:
|
||||
optional: true
|
||||
|
||||
'@vitest/pretty-format@4.1.9':
|
||||
resolution: {integrity: sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==}
|
||||
|
||||
'@vitest/runner@4.1.9':
|
||||
resolution: {integrity: sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==}
|
||||
|
||||
'@vitest/snapshot@4.1.9':
|
||||
resolution: {integrity: sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==}
|
||||
|
||||
'@vitest/spy@4.1.9':
|
||||
resolution: {integrity: sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==}
|
||||
|
||||
'@vitest/utils@4.1.9':
|
||||
resolution: {integrity: sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==}
|
||||
|
||||
assertion-error@2.0.1:
|
||||
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
baseline-browser-mapping@2.10.14:
|
||||
resolution: {integrity: sha512-fOVLPAsFTsQfuCkvahZkzq6nf8KvGWanlYoTh0SVA0A/PIUxQGU2AOZAoD95n2gFLVDW/jP6sbGLny95nmEuHA==}
|
||||
engines: {node: '>=6.0.0'}
|
||||
@@ -947,6 +998,10 @@ packages:
|
||||
caniuse-lite@1.0.30001785:
|
||||
resolution: {integrity: sha512-blhOL/WNR+Km1RI/LCVAvA73xplXA7ZbjzI4YkMK9pa6T/P3F2GxjNpEkyw5repTw9IvkyrjyHpwjnhZ5FOvYQ==}
|
||||
|
||||
chai@6.2.2:
|
||||
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
convert-source-map@2.0.0:
|
||||
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
|
||||
|
||||
@@ -989,6 +1044,9 @@ packages:
|
||||
resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==}
|
||||
engines: {node: '>=10.13.0'}
|
||||
|
||||
es-module-lexer@2.3.0:
|
||||
resolution: {integrity: sha512-KLdwQm2NvGLDkQDCGvmiQrhkd0JbMzXthwQAUgWjQuQdBLFa3eiBP5arXZyA+f8x+x7OXgud6bq2rxjGtHV2tw==}
|
||||
|
||||
esbuild@0.27.7:
|
||||
resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==}
|
||||
engines: {node: '>=18'}
|
||||
@@ -1001,6 +1059,13 @@ packages:
|
||||
estree-walker@2.0.2:
|
||||
resolution: {integrity: sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==}
|
||||
|
||||
estree-walker@3.0.3:
|
||||
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
|
||||
|
||||
expect-type@1.4.0:
|
||||
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
fdir@6.5.0:
|
||||
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
@@ -1159,6 +1224,13 @@ packages:
|
||||
node-releases@2.0.37:
|
||||
resolution: {integrity: sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==}
|
||||
|
||||
obug@2.1.3:
|
||||
resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
pathe@2.0.3:
|
||||
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
|
||||
|
||||
picocolors@1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@@ -1180,6 +1252,66 @@ packages:
|
||||
resolution: {integrity: sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
prettier-plugin-tailwindcss@0.8.0:
|
||||
resolution: {integrity: sha512-V8ITGH87yuBDF6JpEZTOVlUz/saAwqb8f3HRgUj8Lh+tGCcrmorhsLpYqzygwFwK0PE2Ib6Mv3M7T/uE2tZV1g==}
|
||||
engines: {node: '>=20.19'}
|
||||
peerDependencies:
|
||||
'@ianvs/prettier-plugin-sort-imports': '*'
|
||||
'@prettier/plugin-hermes': '*'
|
||||
'@prettier/plugin-oxc': '*'
|
||||
'@prettier/plugin-pug': '*'
|
||||
'@shopify/prettier-plugin-liquid': '*'
|
||||
'@trivago/prettier-plugin-sort-imports': '*'
|
||||
'@zackad/prettier-plugin-twig': '*'
|
||||
prettier: ^3.0
|
||||
prettier-plugin-astro: '*'
|
||||
prettier-plugin-css-order: '*'
|
||||
prettier-plugin-jsdoc: '*'
|
||||
prettier-plugin-marko: '*'
|
||||
prettier-plugin-multiline-arrays: '*'
|
||||
prettier-plugin-organize-attributes: '*'
|
||||
prettier-plugin-organize-imports: '*'
|
||||
prettier-plugin-sort-imports: '*'
|
||||
prettier-plugin-svelte: '*'
|
||||
peerDependenciesMeta:
|
||||
'@ianvs/prettier-plugin-sort-imports':
|
||||
optional: true
|
||||
'@prettier/plugin-hermes':
|
||||
optional: true
|
||||
'@prettier/plugin-oxc':
|
||||
optional: true
|
||||
'@prettier/plugin-pug':
|
||||
optional: true
|
||||
'@shopify/prettier-plugin-liquid':
|
||||
optional: true
|
||||
'@trivago/prettier-plugin-sort-imports':
|
||||
optional: true
|
||||
'@zackad/prettier-plugin-twig':
|
||||
optional: true
|
||||
prettier-plugin-astro:
|
||||
optional: true
|
||||
prettier-plugin-css-order:
|
||||
optional: true
|
||||
prettier-plugin-jsdoc:
|
||||
optional: true
|
||||
prettier-plugin-marko:
|
||||
optional: true
|
||||
prettier-plugin-multiline-arrays:
|
||||
optional: true
|
||||
prettier-plugin-organize-attributes:
|
||||
optional: true
|
||||
prettier-plugin-organize-imports:
|
||||
optional: true
|
||||
prettier-plugin-sort-imports:
|
||||
optional: true
|
||||
prettier-plugin-svelte:
|
||||
optional: true
|
||||
|
||||
prettier@3.9.4:
|
||||
resolution: {integrity: sha512-yWG/o/4oJfo036EKAfK6ACAoDOfHeRHx4tuxkfBZiauURiaSmYwlpOr5LQqKtIkRD2z1PLteme2WoxEnj4tHTg==}
|
||||
engines: {node: '>=14'}
|
||||
hasBin: true
|
||||
|
||||
react-dom@19.2.4:
|
||||
resolution: {integrity: sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==}
|
||||
peerDependencies:
|
||||
@@ -1214,10 +1346,19 @@ packages:
|
||||
resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}
|
||||
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
|
||||
|
||||
siginfo@2.0.0:
|
||||
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
|
||||
|
||||
source-map-js@1.2.1:
|
||||
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
stackback@0.0.2:
|
||||
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
|
||||
|
||||
std-env@4.1.0:
|
||||
resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==}
|
||||
|
||||
tailwindcss@4.2.2:
|
||||
resolution: {integrity: sha512-KWBIxs1Xb6NoLdMVqhbhgwZf2PGBpPEiwOqgI4pFIYbNTfBXiKYyWoTsXgBQ9WFg/OlhnvHaY+AEpW7wSmFo2Q==}
|
||||
|
||||
@@ -1225,10 +1366,21 @@ packages:
|
||||
resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==}
|
||||
engines: {node: '>=6'}
|
||||
|
||||
tinybench@2.9.0:
|
||||
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
|
||||
|
||||
tinyexec@1.2.4:
|
||||
resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
tinyglobby@0.2.15:
|
||||
resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
tinyrainbow@3.1.0:
|
||||
resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}
|
||||
engines: {node: '>=14.0.0'}
|
||||
|
||||
tslib@2.8.1:
|
||||
resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}
|
||||
|
||||
@@ -1292,6 +1444,52 @@ packages:
|
||||
yaml:
|
||||
optional: true
|
||||
|
||||
vitest@4.1.9:
|
||||
resolution: {integrity: sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==}
|
||||
engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@edge-runtime/vm': '*'
|
||||
'@opentelemetry/api': ^1.9.0
|
||||
'@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0
|
||||
'@vitest/browser-playwright': 4.1.9
|
||||
'@vitest/browser-preview': 4.1.9
|
||||
'@vitest/browser-webdriverio': 4.1.9
|
||||
'@vitest/coverage-istanbul': 4.1.9
|
||||
'@vitest/coverage-v8': 4.1.9
|
||||
'@vitest/ui': 4.1.9
|
||||
happy-dom: '*'
|
||||
jsdom: '*'
|
||||
vite: ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
peerDependenciesMeta:
|
||||
'@edge-runtime/vm':
|
||||
optional: true
|
||||
'@opentelemetry/api':
|
||||
optional: true
|
||||
'@types/node':
|
||||
optional: true
|
||||
'@vitest/browser-playwright':
|
||||
optional: true
|
||||
'@vitest/browser-preview':
|
||||
optional: true
|
||||
'@vitest/browser-webdriverio':
|
||||
optional: true
|
||||
'@vitest/coverage-istanbul':
|
||||
optional: true
|
||||
'@vitest/coverage-v8':
|
||||
optional: true
|
||||
'@vitest/ui':
|
||||
optional: true
|
||||
happy-dom:
|
||||
optional: true
|
||||
jsdom:
|
||||
optional: true
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
|
||||
engines: {node: '>=8'}
|
||||
hasBin: true
|
||||
|
||||
yallist@3.1.1:
|
||||
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
|
||||
|
||||
@@ -1718,6 +1916,8 @@ snapshots:
|
||||
'@rollup/rollup-win32-x64-msvc@4.60.1':
|
||||
optional: true
|
||||
|
||||
'@standard-schema/spec@1.1.0': {}
|
||||
|
||||
'@tailwindcss/node@4.2.2':
|
||||
dependencies:
|
||||
'@jridgewell/remapping': 2.3.5
|
||||
@@ -1888,8 +2088,15 @@ snapshots:
|
||||
dependencies:
|
||||
'@babel/types': 7.29.0
|
||||
|
||||
'@types/chai@5.2.3':
|
||||
dependencies:
|
||||
'@types/deep-eql': 4.0.2
|
||||
assertion-error: 2.0.1
|
||||
|
||||
'@types/d3-force@3.0.10': {}
|
||||
|
||||
'@types/deep-eql@4.0.2': {}
|
||||
|
||||
'@types/estree@1.0.8': {}
|
||||
|
||||
'@types/node@26.0.1':
|
||||
@@ -1916,6 +2123,49 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@vitest/expect@4.1.9':
|
||||
dependencies:
|
||||
'@standard-schema/spec': 1.1.0
|
||||
'@types/chai': 5.2.3
|
||||
'@vitest/spy': 4.1.9
|
||||
'@vitest/utils': 4.1.9
|
||||
chai: 6.2.2
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@vitest/mocker@4.1.9(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))':
|
||||
dependencies:
|
||||
'@vitest/spy': 4.1.9
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.21
|
||||
optionalDependencies:
|
||||
vite: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
|
||||
'@vitest/pretty-format@4.1.9':
|
||||
dependencies:
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@vitest/runner@4.1.9':
|
||||
dependencies:
|
||||
'@vitest/utils': 4.1.9
|
||||
pathe: 2.0.3
|
||||
|
||||
'@vitest/snapshot@4.1.9':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 4.1.9
|
||||
'@vitest/utils': 4.1.9
|
||||
magic-string: 0.30.21
|
||||
pathe: 2.0.3
|
||||
|
||||
'@vitest/spy@4.1.9': {}
|
||||
|
||||
'@vitest/utils@4.1.9':
|
||||
dependencies:
|
||||
'@vitest/pretty-format': 4.1.9
|
||||
convert-source-map: 2.0.0
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
assertion-error@2.0.1: {}
|
||||
|
||||
baseline-browser-mapping@2.10.14: {}
|
||||
|
||||
browserslist@4.28.2:
|
||||
@@ -1928,6 +2178,8 @@ snapshots:
|
||||
|
||||
caniuse-lite@1.0.30001785: {}
|
||||
|
||||
chai@6.2.2: {}
|
||||
|
||||
convert-source-map@2.0.0: {}
|
||||
|
||||
csstype@3.2.3: {}
|
||||
@@ -1957,6 +2209,8 @@ snapshots:
|
||||
graceful-fs: 4.2.11
|
||||
tapable: 2.3.2
|
||||
|
||||
es-module-lexer@2.3.0: {}
|
||||
|
||||
esbuild@0.27.7:
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.27.7
|
||||
@@ -1990,6 +2244,12 @@ snapshots:
|
||||
|
||||
estree-walker@2.0.2: {}
|
||||
|
||||
estree-walker@3.0.3:
|
||||
dependencies:
|
||||
'@types/estree': 1.0.8
|
||||
|
||||
expect-type@1.4.0: {}
|
||||
|
||||
fdir@6.5.0(picomatch@4.0.4):
|
||||
optionalDependencies:
|
||||
picomatch: 4.0.4
|
||||
@@ -2092,6 +2352,10 @@ snapshots:
|
||||
|
||||
node-releases@2.0.37: {}
|
||||
|
||||
obug@2.1.3: {}
|
||||
|
||||
pathe@2.0.3: {}
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
|
||||
picomatch@4.0.4: {}
|
||||
@@ -2110,6 +2374,12 @@ snapshots:
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.1
|
||||
|
||||
prettier-plugin-tailwindcss@0.8.0(prettier@3.9.4):
|
||||
dependencies:
|
||||
prettier: 3.9.4
|
||||
|
||||
prettier@3.9.4: {}
|
||||
|
||||
react-dom@19.2.4(react@19.2.4):
|
||||
dependencies:
|
||||
react: 19.2.4
|
||||
@@ -2187,17 +2457,29 @@ snapshots:
|
||||
'@img/sharp-win32-ia32': 0.34.5
|
||||
'@img/sharp-win32-x64': 0.34.5
|
||||
|
||||
siginfo@2.0.0: {}
|
||||
|
||||
source-map-js@1.2.1: {}
|
||||
|
||||
stackback@0.0.2: {}
|
||||
|
||||
std-env@4.1.0: {}
|
||||
|
||||
tailwindcss@4.2.2: {}
|
||||
|
||||
tapable@2.3.2: {}
|
||||
|
||||
tinybench@2.9.0: {}
|
||||
|
||||
tinyexec@1.2.4: {}
|
||||
|
||||
tinyglobby@0.2.15:
|
||||
dependencies:
|
||||
fdir: 6.5.0(picomatch@4.0.4)
|
||||
picomatch: 4.0.4
|
||||
|
||||
tinyrainbow@3.1.0: {}
|
||||
|
||||
tslib@2.8.1: {}
|
||||
|
||||
typescript@5.8.3: {}
|
||||
@@ -2233,6 +2515,38 @@ snapshots:
|
||||
jiti: 2.6.1
|
||||
lightningcss: 1.32.0
|
||||
|
||||
vitest@4.1.9(@types/node@26.0.1)(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.9
|
||||
'@vitest/mocker': 4.1.9(vite@7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0))
|
||||
'@vitest/pretty-format': 4.1.9
|
||||
'@vitest/runner': 4.1.9
|
||||
'@vitest/snapshot': 4.1.9
|
||||
'@vitest/spy': 4.1.9
|
||||
'@vitest/utils': 4.1.9
|
||||
es-module-lexer: 2.3.0
|
||||
expect-type: 1.4.0
|
||||
magic-string: 0.30.21
|
||||
obug: 2.1.3
|
||||
pathe: 2.0.3
|
||||
picomatch: 4.0.4
|
||||
std-env: 4.1.0
|
||||
tinybench: 2.9.0
|
||||
tinyexec: 1.2.4
|
||||
tinyglobby: 0.2.15
|
||||
tinyrainbow: 3.1.0
|
||||
vite: 7.3.1(@types/node@26.0.1)(jiti@2.6.1)(lightningcss@1.32.0)
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 26.0.1
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
why-is-node-running@2.3.0:
|
||||
dependencies:
|
||||
siginfo: 2.0.0
|
||||
stackback: 0.0.2
|
||||
|
||||
yallist@3.1.1: {}
|
||||
|
||||
zustand@5.0.12(@types/react@19.2.14)(react@19.2.4):
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# Codex Cloud setup for Phokus.
|
||||
# Paste this script into the Codex Cloud environment setup field, or run it from
|
||||
# the repo root with: bash scripts/codex-cloud-setup.sh
|
||||
#
|
||||
# Goals:
|
||||
# - install Linux packages needed by Tauri/WebKit and native Rust crates
|
||||
# - install JS dependencies with pnpm using the lockfile
|
||||
# - pre-fetch Rust dependencies while setup still has internet access
|
||||
# - keep the environment CPU-safe by avoiding Phokus' default CUDA feature set
|
||||
# - leave Codex with clear verification commands for UI and Rust work
|
||||
|
||||
log() {
|
||||
printf '\n\033[1;36m[phokus-codex]\033[0m %s\n' "$*"
|
||||
}
|
||||
|
||||
warn() {
|
||||
printf '\n\033[1;33m[phokus-codex warning]\033[0m %s\n' "$*" >&2
|
||||
}
|
||||
|
||||
repo_root="$(pwd)"
|
||||
|
||||
if [[ ! -f "package.json" || ! -d "src-tauri" ]]; then
|
||||
warn "This script should be run from the Phokus repository root. Current directory: ${repo_root}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export CI=1
|
||||
export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"
|
||||
export PATH="$PNPM_HOME:$HOME/.cargo/bin:$PATH"
|
||||
|
||||
# Persist useful shell defaults for the later Codex agent phase. Codex setup runs
|
||||
# in a separate Bash session, so exports here alone would not survive.
|
||||
if ! grep -q "# Phokus Codex Cloud" "$HOME/.bashrc" 2>/dev/null; then
|
||||
cat >> "$HOME/.bashrc" <<'BASHRC'
|
||||
|
||||
# Phokus Codex Cloud
|
||||
export PNPM_HOME="${PNPM_HOME:-$HOME/.local/share/pnpm}"
|
||||
export PATH="$PNPM_HOME:$HOME/.cargo/bin:$PATH"
|
||||
export CI=1
|
||||
BASHRC
|
||||
fi
|
||||
|
||||
install_apt_packages() {
|
||||
if ! command -v apt-get >/dev/null 2>&1; then
|
||||
warn "apt-get not found; skipping system package installation."
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "Installing Linux system dependencies for Tauri, WebKit, SQLite/native crates, and browser tooling"
|
||||
|
||||
sudo apt-get update
|
||||
|
||||
# Tauri v2 Linux builds need the WebKitGTK/AppIndicator/Rsvg stack. Some base
|
||||
# images expose either the 4.1 or 4.0 WebKit development package, so try the
|
||||
# modern package first and gracefully fall back.
|
||||
local common_packages=(
|
||||
build-essential
|
||||
curl
|
||||
wget
|
||||
file
|
||||
pkg-config
|
||||
libssl-dev
|
||||
libgtk-3-dev
|
||||
libayatana-appindicator3-dev
|
||||
librsvg2-dev
|
||||
patchelf
|
||||
ca-certificates
|
||||
)
|
||||
|
||||
if apt-cache show libwebkit2gtk-4.1-dev >/dev/null 2>&1; then
|
||||
sudo apt-get install -y --no-install-recommends "${common_packages[@]}" libwebkit2gtk-4.1-dev
|
||||
else
|
||||
sudo apt-get install -y --no-install-recommends "${common_packages[@]}" libwebkit2gtk-4.0-dev
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_node_and_pnpm() {
|
||||
log "Preparing Node/pnpm"
|
||||
|
||||
if ! command -v node >/dev/null 2>&1; then
|
||||
warn "Node.js is not available in this image. Pin Node.js 20+ in the Codex environment settings or use a Codex universal image with Node installed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node_major="$(node -p "process.versions.node.split('.')[0]")"
|
||||
if [[ "$node_major" -lt 20 ]]; then
|
||||
warn "Phokus expects Node.js 20+. Current version: $(node --version). Pin Node.js 20+ in Codex environment settings."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$PNPM_HOME"
|
||||
|
||||
if command -v corepack >/dev/null 2>&1; then
|
||||
corepack enable
|
||||
corepack prepare pnpm@latest --activate
|
||||
fi
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
npm install -g pnpm
|
||||
fi
|
||||
|
||||
log "Node: $(node --version)"
|
||||
log "pnpm: $(pnpm --version)"
|
||||
}
|
||||
|
||||
ensure_rust() {
|
||||
log "Preparing Rust toolchain"
|
||||
|
||||
if ! command -v rustup >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
|
||||
# shellcheck source=/dev/null
|
||||
source "$HOME/.cargo/env"
|
||||
fi
|
||||
|
||||
rustup toolchain install stable --profile minimal
|
||||
rustup default stable
|
||||
rustup component add rustfmt clippy
|
||||
|
||||
log "rustc: $(rustc --version)"
|
||||
log "cargo: $(cargo --version)"
|
||||
}
|
||||
|
||||
install_js_dependencies() {
|
||||
log "Installing frontend dependencies"
|
||||
pnpm install --frozen-lockfile
|
||||
}
|
||||
|
||||
prefetch_rust_dependencies() {
|
||||
log "Pre-fetching Rust dependencies for CPU-safe Tauri checks"
|
||||
|
||||
# Phokus enables candle-cuda by default in Cargo.toml. Codex Cloud usually runs
|
||||
# in a CPU Linux container, so use --no-default-features for checks/builds
|
||||
# unless you intentionally configure a CUDA-capable environment.
|
||||
cargo fetch --manifest-path src-tauri/Cargo.toml --locked
|
||||
|
||||
# This is intentionally a check, not a full release build. It warms the Cargo
|
||||
# cache and catches missing native packages without making setup painfully slow.
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --locked --no-default-features
|
||||
}
|
||||
|
||||
install_playwright_browsers() {
|
||||
log "Installing Playwright Chromium dependencies for UI Lab/browser screenshots"
|
||||
|
||||
# Safe even if no Playwright tests are present yet. Useful for Codex browser
|
||||
# inspection against `pnpm dev:ui`.
|
||||
pnpm exec playwright install --with-deps chromium || warn "Playwright browser install failed; UI work may still run, but browser automation/screenshots may need manual setup."
|
||||
}
|
||||
|
||||
print_next_steps() {
|
||||
cat <<'EOF'
|
||||
|
||||
[phokus-codex] Setup complete.
|
||||
|
||||
Recommended Codex verification commands:
|
||||
pnpm exec tsc --noEmit
|
||||
pnpm build:vite
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --locked --no-default-features
|
||||
|
||||
For visual UI work in Codex/browser environments:
|
||||
pnpm dev:ui
|
||||
open http://127.0.0.1:1422/?scenario=rich
|
||||
|
||||
Other useful UI Lab scenarios:
|
||||
http://127.0.0.1:1422/?scenario=empty
|
||||
http://127.0.0.1:1422/?scenario=duplicates
|
||||
http://127.0.0.1:1422/?scenario=errors
|
||||
http://127.0.0.1:1422/?scenario=huge
|
||||
|
||||
Avoid the below in standard CPU-only Codex Cloud unless you have configured CUDA:
|
||||
pnpm dev:app
|
||||
pnpm build:app:cuda
|
||||
cargo check --manifest-path src-tauri/Cargo.toml
|
||||
EOF
|
||||
}
|
||||
|
||||
main() {
|
||||
install_apt_packages
|
||||
ensure_node_and_pnpm
|
||||
ensure_rust
|
||||
install_js_dependencies
|
||||
prefetch_rust_dependencies
|
||||
install_playwright_browsers
|
||||
print_next_steps
|
||||
}
|
||||
|
||||
main "$@"
|
||||
Generated
+1
-1
@@ -4595,7 +4595,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "phokus"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"candle-core",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "phokus"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
description = "Local-first desktop media library"
|
||||
authors = ["JezzWTF"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"opener:default",
|
||||
@@ -19,6 +21,8 @@
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-toggle-maximize",
|
||||
"core:window:allow-is-maximized"
|
||||
"core:window:allow-is-maximized",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-start-resize-dragging"
|
||||
]
|
||||
}
|
||||
@@ -42,4 +42,13 @@ mod tests {
|
||||
assert!(!is_removed_ai_tag(tag), "{tag} should be kept");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_ai_tags_tolerate_padding_and_mixed_separators() {
|
||||
assert!(is_removed_ai_tag(" 1girl "));
|
||||
assert!(is_removed_ai_tag("1_-_girl"));
|
||||
assert!(is_removed_ai_tag("No Humans"));
|
||||
assert!(!is_removed_ai_tag(""));
|
||||
assert!(!is_removed_ai_tag(" "));
|
||||
}
|
||||
}
|
||||
|
||||
+8
-326
@@ -1,3 +1,6 @@
|
||||
use crate::onnx_runtime::{
|
||||
self, DIRECTML_DLL_FILE, ONNX_RUNTIME_DLL_FILE, ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use hf_hub::{api::sync::Api, Repo, RepoType};
|
||||
use image::{imageops::FilterType, ImageReader};
|
||||
@@ -8,50 +11,16 @@ use ort::session::{builder::GraphOptimizationLevel, Session};
|
||||
use ort::value::{Shape, Tensor};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::Instant;
|
||||
use tokenizers::Tokenizer;
|
||||
|
||||
// Suppress the console window when spawning curl.exe from the GUI app.
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::CommandExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
pub const FLORENCE_MODEL_ID: &str = "onnx-community/Florence-2-base-ft";
|
||||
pub const FLORENCE_CAPTION_MODEL_NAME: &str = "florence-2-base-ft-onnx-q4";
|
||||
const ONNX_RUNTIME_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.ML.OnnxRuntime.DirectML/1.24.2";
|
||||
const DIRECTML_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.AI.DirectML/1.15.4";
|
||||
const ONNX_RUNTIME_DLL_FILE: &str = "onnxruntime/onnxruntime.dll";
|
||||
const ONNX_RUNTIME_PROVIDERS_DLL_FILE: &str = "onnxruntime/onnxruntime_providers_shared.dll";
|
||||
const DIRECTML_DLL_FILE: &str = "onnxruntime/DirectML.dll";
|
||||
const CAPTION_ACCELERATION_FILE: &str = "settings/caption_acceleration.txt";
|
||||
const CAPTION_DETAIL_FILE: &str = "settings/caption_detail.txt";
|
||||
|
||||
const ONNX_RUNTIME_FILES: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime.dll",
|
||||
),
|
||||
(
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime_providers_shared.dll",
|
||||
),
|
||||
(
|
||||
DIRECTML_DLL_FILE,
|
||||
DIRECTML_NUGET_URL,
|
||||
"bin/x64-win/DirectML.dll",
|
||||
),
|
||||
];
|
||||
|
||||
const REQUIRED_FILES: &[&str] = &[
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
@@ -69,11 +38,6 @@ const REQUIRED_FILES: &[&str] = &[
|
||||
"onnx/embed_tokens_fp16.onnx",
|
||||
];
|
||||
|
||||
// Mutex<bool> rather than OnceLock<Result>: a failed attempt (DLL not yet
|
||||
// downloaded) must NOT be cached, or a later successful download could never
|
||||
// recover within the same app session.
|
||||
static ORT_RUNTIME_INIT: Mutex<bool> = Mutex::new(false);
|
||||
|
||||
/// Set to `true` by `set_caption_acceleration` so the caption worker loop
|
||||
/// knows to drop its cached `FlorenceCaptioner` and reload with the new EP.
|
||||
pub static CAPTION_SESSION_DIRTY: AtomicBool = AtomicBool::new(false);
|
||||
@@ -294,11 +258,11 @@ pub fn prepare_caption_model_with_progress(
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
if ONNX_RUNTIME_FILES
|
||||
if onnx_runtime::ONNX_RUNTIME_FILES
|
||||
.iter()
|
||||
.any(|(runtime_file, _, _)| runtime_file == file)
|
||||
{
|
||||
download_onnx_runtime_files(&local_dir)?;
|
||||
onnx_runtime::download_onnx_runtime_files(&local_dir)?;
|
||||
completed_files = REQUIRED_FILES
|
||||
.iter()
|
||||
.filter(|file| local_dir.join(file).exists())
|
||||
@@ -344,7 +308,7 @@ pub fn probe_caption_runtime(app_data_dir: &Path) -> Result<CaptionRuntimeProbe>
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
ensure_onnx_runtime(&local_dir)?;
|
||||
onnx_runtime::ensure_onnx_runtime(&local_dir)?;
|
||||
let tokenizer =
|
||||
Tokenizer::from_file(local_dir.join("tokenizer.json")).map_err(anyhow::Error::msg)?;
|
||||
|
||||
@@ -393,7 +357,7 @@ pub fn probe_caption_vision(app_data_dir: &Path, image_path: &Path) -> Result<Ca
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
ensure_onnx_runtime(&local_dir)?;
|
||||
onnx_runtime::ensure_onnx_runtime(&local_dir)?;
|
||||
let pixels = preprocess_image(image_path)?;
|
||||
let input_shape = vec![1, 3, 768, 768];
|
||||
let input = Tensor::from_array(([1usize, 3, 768, 768], pixels.into_boxed_slice()))
|
||||
@@ -438,7 +402,7 @@ impl FlorenceCaptioner {
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
ensure_onnx_runtime(&local_dir)?;
|
||||
onnx_runtime::ensure_onnx_runtime(&local_dir)?;
|
||||
let tokenizer =
|
||||
Tokenizer::from_file(local_dir.join("tokenizer.json")).map_err(anyhow::Error::msg)?;
|
||||
let caption_detail = caption_detail(app_data_dir);
|
||||
@@ -647,288 +611,6 @@ fn probe_vision_session(
|
||||
})
|
||||
}
|
||||
|
||||
pub fn ensure_onnx_runtime(local_dir: &Path) -> Result<()> {
|
||||
let mut initialized = ORT_RUNTIME_INIT
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("ONNX runtime init lock poisoned"))?;
|
||||
if *initialized {
|
||||
return Ok(());
|
||||
}
|
||||
let dll_path = local_dir.join(ONNX_RUNTIME_DLL_FILE);
|
||||
if !dll_path.exists() {
|
||||
anyhow::bail!("ONNX Runtime DLL is missing: {}", dll_path.display());
|
||||
}
|
||||
ort::environment::init_from(&dll_path)
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?
|
||||
.with_name("phokus-florence")
|
||||
.commit();
|
||||
*initialized = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download any ONNX Runtime DLLs missing from `local_dir`, reporting per-file
|
||||
/// byte progress as `(short_label, downloaded_bytes, total_bytes)`.
|
||||
/// `total_bytes` is `None` when the server omits Content-Length. Unlike
|
||||
/// `ensure_onnx_runtime` (init only), this actually provisions the files —
|
||||
/// callers that can run on a clean install must call this first. The callback
|
||||
/// fires per chunk; callers should throttle.
|
||||
pub fn provision_onnx_runtime_with_progress(
|
||||
local_dir: &Path,
|
||||
mut on_progress: impl FnMut(&str, u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
if destination.exists() {
|
||||
continue;
|
||||
}
|
||||
// Strip the "onnxruntime/" prefix for a clean label.
|
||||
let label = destination_file
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or(destination_file);
|
||||
download_nuget_file(
|
||||
source_url,
|
||||
archive_path,
|
||||
&destination,
|
||||
|downloaded, total| on_progress(label, downloaded, total),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Number of ONNX Runtime DLLs still missing from `local_dir` (for progress
|
||||
/// step counts before downloading).
|
||||
pub fn missing_onnx_runtime_count(local_dir: &Path) -> usize {
|
||||
ONNX_RUNTIME_FILES
|
||||
.iter()
|
||||
.filter(|(destination_file, _, _)| !local_dir.join(destination_file).exists())
|
||||
.count()
|
||||
}
|
||||
|
||||
fn download_onnx_runtime_files(local_dir: &Path) -> Result<()> {
|
||||
if !cfg!(target_os = "windows") {
|
||||
anyhow::bail!(
|
||||
"Florence-2 ONNX Runtime download is currently configured for Windows builds"
|
||||
);
|
||||
}
|
||||
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
download_nuget_file(source_url, archive_path, &destination, |_, _| {})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Give up only after this many *consecutive* curl runs that download nothing;
|
||||
// a run that makes any progress resets the counter, so a large file completes
|
||||
// across however many resumes it takes. Kept low so a hard stall (e.g. a
|
||||
// broken VM NIC) fails in a couple of minutes — surfacing a retryable error —
|
||||
// rather than locking the UI on "preparing" for many minutes.
|
||||
const MAX_STALL_RETRIES: usize = 3;
|
||||
|
||||
/// Resiliently download `url` to `destination` using the system `curl.exe`.
|
||||
///
|
||||
/// ureq's read timeout does not fire on a stalled large transfer on Windows
|
||||
/// (schannel doesn't honor the socket read timeout), so a stall there hangs
|
||||
/// forever. curl detects an inactivity stall (`--speed-time`), resumes from
|
||||
/// the partial file (`-C -`), and retries internally — the same behavior a
|
||||
/// browser gets. We monitor the `.part` file's size for the progress bar and
|
||||
/// wrap curl in an outer progress-aware retry as a backstop. The partial file
|
||||
/// survives an app restart, so a later retry continues from disk.
|
||||
pub fn download_file_resilient(
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
mut on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let part = match destination.extension() {
|
||||
Some(ext) => destination.with_extension(format!("{}.part", ext.to_string_lossy())),
|
||||
None => destination.with_extension("part"),
|
||||
};
|
||||
let name = destination
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| url.to_string());
|
||||
|
||||
log::info!("{name}: resolving download size");
|
||||
let total = remote_content_length(url);
|
||||
|
||||
// Reconcile any existing `.part` against the real size: exactly complete →
|
||||
// finish; oversized (stale/corrupt) → discard so curl restarts cleanly
|
||||
// (otherwise `curl -C -` would 416 forever).
|
||||
if let Some(total) = total {
|
||||
let size = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if size == total {
|
||||
std::fs::rename(&part, destination)?;
|
||||
return Ok(());
|
||||
}
|
||||
if size > total {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
}
|
||||
log::info!(
|
||||
"{name}: downloading via curl ({} bytes)",
|
||||
total
|
||||
.map(|t| t.to_string())
|
||||
.unwrap_or_else(|| "unknown size".into())
|
||||
);
|
||||
|
||||
let mut stalls = 0usize;
|
||||
loop {
|
||||
let before = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
match run_curl_download(url, &part, total, &mut on_progress) {
|
||||
Ok(()) => break,
|
||||
Err(error) => {
|
||||
let after = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if after > before {
|
||||
log::warn!("{name}: curl interrupted at {after} bytes, resuming: {error}");
|
||||
stalls = 0;
|
||||
} else {
|
||||
stalls += 1;
|
||||
log::warn!(
|
||||
"{name}: curl made no progress ({stalls}/{MAX_STALL_RETRIES}): {error}"
|
||||
);
|
||||
if stalls >= MAX_STALL_RETRIES {
|
||||
// Discard the partial so a future attempt restarts clean
|
||||
// rather than getting stuck re-resuming a bad file.
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(total) = total {
|
||||
let got = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if got < total {
|
||||
anyhow::bail!("{name}: incomplete after curl ({got}/{total} bytes)");
|
||||
}
|
||||
}
|
||||
std::fs::rename(&part, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Size probe via `curl -r 0-0` (a 1-byte Range request), parsing the total
|
||||
/// from the `Content-Range: bytes 0-0/<total>` header. Uses curl rather than
|
||||
/// ureq so no part of the download path depends on ureq (which hangs on this
|
||||
/// VM's TLS stack). Returns None if the server doesn't report a size.
|
||||
fn remote_content_length(url: &str) -> Option<u64> {
|
||||
let mut command = Command::new("curl.exe");
|
||||
command.args([
|
||||
"-sL",
|
||||
"-r",
|
||||
"0-0",
|
||||
"-D",
|
||||
"-",
|
||||
"-o",
|
||||
"NUL",
|
||||
"--connect-timeout",
|
||||
"30",
|
||||
"--max-time",
|
||||
"30",
|
||||
url,
|
||||
]);
|
||||
#[cfg(target_os = "windows")]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
let output = command.output().ok()?;
|
||||
let headers = String::from_utf8_lossy(&output.stdout);
|
||||
for line in headers.lines() {
|
||||
if let Some(rest) = line.to_ascii_lowercase().strip_prefix("content-range:") {
|
||||
if let Some(total) = rest.rsplit('/').next().map(str::trim) {
|
||||
if let Ok(n) = total.parse::<u64>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Run one `curl.exe` download to `dest`, resuming from any partial file, while
|
||||
/// reporting progress from the growing file size. Returns an error (leaving the
|
||||
/// partial in place) if curl exits non-zero.
|
||||
fn run_curl_download(
|
||||
url: &str,
|
||||
dest: &Path,
|
||||
total: Option<u64>,
|
||||
on_progress: &mut impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
let mut command = Command::new("curl.exe");
|
||||
command
|
||||
.arg("-fSL") // fail on HTTP errors, follow redirects, show errors
|
||||
.args(["-C", "-"]) // resume from the existing output file
|
||||
.args(["--retry", "3", "--retry-delay", "1", "--retry-connrefused"])
|
||||
.args(["--connect-timeout", "30"])
|
||||
// Abort (then --retry resumes) if under 1 KB/s for 30s — a real
|
||||
// inactivity timeout, which is what ureq couldn't deliver here.
|
||||
.args(["--speed-limit", "1024", "--speed-time", "30"])
|
||||
.arg("-s") // no progress meter (we watch the file instead)
|
||||
.arg("-o")
|
||||
.arg(dest)
|
||||
.arg(url)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
#[cfg(target_os = "windows")]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| anyhow::anyhow!("failed to launch curl.exe (required for downloads): {e}"))?;
|
||||
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut stderr = String::new();
|
||||
if let Some(mut pipe) = child.stderr.take() {
|
||||
let _ = pipe.read_to_string(&mut stderr);
|
||||
}
|
||||
anyhow::bail!(
|
||||
"curl exited with {}: {}",
|
||||
status
|
||||
.code()
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| "signal".into()),
|
||||
stderr.trim()
|
||||
);
|
||||
}
|
||||
let downloaded = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0);
|
||||
on_progress(downloaded, total);
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
}
|
||||
|
||||
fn download_nuget_file(
|
||||
source_url: &str,
|
||||
archive_path: &str,
|
||||
destination: &Path,
|
||||
on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
// Download the .nupkg (a zip) resiliently, then extract the one DLL.
|
||||
let package = destination.with_extension("nupkg");
|
||||
download_file_resilient(source_url, &package, on_progress)?;
|
||||
|
||||
log::info!("extracting {archive_path} from package");
|
||||
let file = std::fs::File::open(&package)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
let mut dll = archive.by_name(archive_path)?;
|
||||
let temp_destination = destination.with_extension("tmp");
|
||||
{
|
||||
let mut out = std::fs::File::create(&temp_destination)?;
|
||||
std::io::copy(&mut dll, &mut out)?;
|
||||
}
|
||||
std::fs::rename(&temp_destination, destination)?;
|
||||
let _ = std::fs::remove_file(&package);
|
||||
log::info!("extracted {archive_path}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_vision_encoder(session: &mut Session, image_path: &Path) -> Result<TensorData> {
|
||||
let pixels = preprocess_image(image_path)?;
|
||||
let input = Tensor::from_array(([1usize, 3, 768, 768], pixels.into_boxed_slice()))
|
||||
|
||||
+249
-59
@@ -162,6 +162,8 @@ pub struct TagSearchParams {
|
||||
pub media_kind: Option<String>,
|
||||
pub favorites_only: Option<bool>,
|
||||
pub rating_min: Option<i64>,
|
||||
/// Optional `[r, g, b]` color filter applied within the tag result set.
|
||||
pub color: Option<[u8; 3]>,
|
||||
pub limit: Option<usize>,
|
||||
pub offset: Option<usize>,
|
||||
}
|
||||
@@ -957,6 +959,7 @@ pub async fn search_images_by_tag(
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
let limit = params.limit.unwrap_or(64);
|
||||
let offset = params.offset.unwrap_or(0);
|
||||
let color = params.color.map(|[r, g, b]| (r, g, b));
|
||||
let (images, total) = db::search_images_by_tag(
|
||||
&conn,
|
||||
¶ms.query,
|
||||
@@ -964,6 +967,7 @@ pub async fn search_images_by_tag(
|
||||
params.media_kind.as_deref(),
|
||||
params.favorites_only.unwrap_or(false),
|
||||
params.rating_min.unwrap_or(0),
|
||||
color,
|
||||
limit,
|
||||
offset,
|
||||
)
|
||||
@@ -1161,7 +1165,7 @@ pub async fn reset_generated_captions(
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct TagCloudEntry {
|
||||
pub struct VisualClusterEntry {
|
||||
pub count: usize,
|
||||
pub representative_image_id: i64,
|
||||
pub thumbnail_path: Option<String>,
|
||||
@@ -1174,48 +1178,50 @@ pub struct TagCloudEntry {
|
||||
/// Results are cached in SQLite keyed by a hash of the embedded image IDs, so repeated
|
||||
/// calls (including across app restarts) return instantly when the library hasn't changed.
|
||||
#[tauri::command]
|
||||
pub async fn get_tag_cloud(
|
||||
pub async fn get_visual_clusters(
|
||||
db: State<'_, DbState>,
|
||||
folder_id: Option<i64>,
|
||||
) -> Result<Vec<TagCloudEntry>, String> {
|
||||
let embeddings_with_ids = {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
vector::get_all_image_embeddings_with_ids(&conn, folder_id).map_err(|e| e.to_string())?
|
||||
};
|
||||
|
||||
let n = embeddings_with_ids.len();
|
||||
if n < 5 {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
// Sort by ID for stable ordering; hash both IDs and embedding bytes so that
|
||||
// replacing a file and regenerating its embedding invalidates the cache even
|
||||
// when the set of image IDs hasn't changed.
|
||||
let mut sorted_pairs: Vec<_> = embeddings_with_ids.iter().collect();
|
||||
sorted_pairs.sort_unstable_by_key(|(id, _)| *id);
|
||||
let current_hash = {
|
||||
use xxhash_rust::xxh3::Xxh3;
|
||||
let mut hasher = Xxh3::new();
|
||||
for (id, embedding) in &sorted_pairs {
|
||||
hasher.update(&id.to_le_bytes());
|
||||
for val in embedding.iter() {
|
||||
hasher.update(&val.to_le_bytes());
|
||||
}
|
||||
}
|
||||
hasher.digest()
|
||||
};
|
||||
) -> Result<Vec<VisualClusterEntry>, String> {
|
||||
let folder_scope = match folder_id {
|
||||
Some(id) => format!("folder_{id}"),
|
||||
None => "all".to_string(),
|
||||
};
|
||||
|
||||
// Try to return a valid SQLite cache
|
||||
// Build a cheap cache key from a hash of the embedded image-ID set plus the
|
||||
// global monotonic embedding revision. The ID-set hash catches membership
|
||||
// changes (add/remove, or moving an image between folders — even when the
|
||||
// count is unchanged); the revision catches an image being re-embedded in
|
||||
// place (same IDs, new vector). Together they validate the cache WITHOUT
|
||||
// reading and unpacking every embedding blob — which for a large library is
|
||||
// hundreds of MB and was the real cause of the multi-second Explore stall
|
||||
// even on a cache hit.
|
||||
let (count, current_hash) = {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
let (count, ids_hash) =
|
||||
vector::embedding_ids_signature(&conn, folder_id).map_err(|e| e.to_string())?;
|
||||
let revision = vector::get_embedding_revision(&conn).map_err(|e| e.to_string())?;
|
||||
let hash = {
|
||||
use xxhash_rust::xxh3::Xxh3;
|
||||
let mut hasher = Xxh3::new();
|
||||
hasher.update(&ids_hash.to_le_bytes());
|
||||
hasher.update(revision.as_bytes());
|
||||
hasher.update(CLUSTER_CACHE_VERSION.as_bytes());
|
||||
hasher.digest()
|
||||
};
|
||||
(count, hash)
|
||||
};
|
||||
|
||||
if count < 5 {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
// Try to return a valid SQLite cache before loading any embeddings.
|
||||
{
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
if let Some(json) = db::get_tag_cloud_cache(&conn, &folder_scope, current_hash)
|
||||
if let Some(json) = db::get_visual_cluster_cache(&conn, &folder_scope, current_hash)
|
||||
.map_err(|e| e.to_string())?
|
||||
{
|
||||
if let Ok(entries) = serde_json::from_str::<Vec<TagCloudEntry>>(&json) {
|
||||
if let Ok(entries) = serde_json::from_str::<Vec<VisualClusterEntry>>(&json) {
|
||||
// Reject cache entries written before image_ids were tracked — they all
|
||||
// have empty image_ids which causes "No media found" when a cluster is opened.
|
||||
if entries.iter().all(|e| !e.image_ids.is_empty()) {
|
||||
@@ -1225,17 +1231,32 @@ pub async fn get_tag_cloud(
|
||||
}
|
||||
}
|
||||
|
||||
// Cache miss — run k-means
|
||||
// Cache miss — now pay the cost of loading embeddings and running k-means.
|
||||
let embeddings_with_ids = {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
vector::get_all_image_embeddings_with_ids(&conn, folder_id).map_err(|e| e.to_string())?
|
||||
};
|
||||
if embeddings_with_ids.len() < 5 {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
|
||||
let ids: Vec<i64> = embeddings_with_ids.iter().map(|(id, _)| *id).collect();
|
||||
let n = embeddings_with_ids.len();
|
||||
let points: Vec<Vec<f32>> = embeddings_with_ids
|
||||
.into_iter()
|
||||
.map(|(_, emb)| emb)
|
||||
.collect();
|
||||
|
||||
let k = (n / 20).clamp(5, 30);
|
||||
let kmeans_start = std::time::Instant::now();
|
||||
let (centroids, cluster_counts, assignments) = kmeans_cosine(&points, k, 40);
|
||||
log::debug!(
|
||||
"visual-cluster clustering: {n} embeddings, k={k}, sampled={} → {:.2?}",
|
||||
n > MAX_KMEANS_SAMPLE,
|
||||
kmeans_start.elapsed(),
|
||||
);
|
||||
|
||||
let mut entries: Vec<TagCloudEntry> = Vec::new();
|
||||
let mut entries: Vec<VisualClusterEntry> = Vec::new();
|
||||
let mut order: Vec<usize> = (0..k).collect();
|
||||
order.sort_unstable_by(|&a, &b| cluster_counts[b].cmp(&cluster_counts[a]));
|
||||
|
||||
@@ -1268,7 +1289,7 @@ pub async fn get_tag_cloud(
|
||||
.ok()
|
||||
.and_then(|img| img.thumbnail_path);
|
||||
|
||||
entries.push(TagCloudEntry {
|
||||
entries.push(VisualClusterEntry {
|
||||
count,
|
||||
representative_image_id: best_id,
|
||||
thumbnail_path,
|
||||
@@ -1276,9 +1297,12 @@ pub async fn get_tag_cloud(
|
||||
});
|
||||
}
|
||||
|
||||
// Persist to SQLite — ignore write errors (cache is best-effort)
|
||||
// Persist to SQLite. The cache is best-effort, but a silent write failure here
|
||||
// would defeat the whole optimization (every visit would recompute), so log it.
|
||||
if let Ok(json) = serde_json::to_string(&entries) {
|
||||
let _ = db::set_tag_cloud_cache(&conn, &folder_scope, current_hash, &json);
|
||||
if let Err(e) = db::set_visual_cluster_cache(&conn, &folder_scope, current_hash, &json) {
|
||||
log::warn!("failed to persist visual-cluster cache for {folder_scope}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
@@ -1833,34 +1857,139 @@ fn normalize(v: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// When the library is larger than this, the iterative k-means centroid search
|
||||
/// runs on a deterministic, evenly-strided sample of this many embeddings rather
|
||||
/// than the full set; every image is then assigned to its nearest centroid in a
|
||||
/// single parallel pass. The centroid search is the expensive O(n·k·dim·iters)
|
||||
/// part, so sampling it keeps the (statistically equivalent) clustering fast on
|
||||
/// large libraries while the full assignment still places every image.
|
||||
const MAX_KMEANS_SAMPLE: usize = 3000;
|
||||
|
||||
/// Bumped whenever the clustering algorithm changes so persisted visual-cluster caches
|
||||
/// computed by an older algorithm are invalidated and recomputed on next view.
|
||||
const CLUSTER_CACHE_VERSION: &str = "sampled-v2";
|
||||
|
||||
/// Cosine k-means. For large inputs the iterative centroid search runs on a
|
||||
/// strided sample (see [`MAX_KMEANS_SAMPLE`]); the final assignment of every
|
||||
/// point to its nearest centroid always covers the full input, in parallel.
|
||||
fn kmeans_cosine(
|
||||
points: &[Vec<f32>],
|
||||
k: usize,
|
||||
max_iter: usize,
|
||||
) -> (Vec<Vec<f32>>, Vec<usize>, Vec<usize>) {
|
||||
let n = points.len();
|
||||
let dim = points[0].len();
|
||||
|
||||
// Deterministic k-means++ init: spread centroids as far apart as possible
|
||||
// Deterministic, evenly-distributed sample for the centroid search. For n at
|
||||
// or below the cap this is just the full set (a clone), so behaviour is
|
||||
// unchanged on small/medium libraries.
|
||||
let sample: Vec<Vec<f32>> = if n > MAX_KMEANS_SAMPLE {
|
||||
let step = n / MAX_KMEANS_SAMPLE;
|
||||
points
|
||||
.iter()
|
||||
.step_by(step)
|
||||
.take(MAX_KMEANS_SAMPLE)
|
||||
.cloned()
|
||||
.collect()
|
||||
} else {
|
||||
points.to_vec()
|
||||
};
|
||||
|
||||
let centroids = kmeans_centroids(&sample, k, max_iter);
|
||||
|
||||
// Assign every point — not just the sample — to its nearest centroid.
|
||||
let assignments = assign_to_centroids(points, ¢roids);
|
||||
|
||||
let mut counts = vec![0usize; k];
|
||||
for &a in &assignments {
|
||||
counts[a] += 1;
|
||||
}
|
||||
|
||||
(centroids, counts, assignments)
|
||||
}
|
||||
|
||||
/// Small deterministic PRNG (SplitMix64) so k-means++ seeding is reproducible
|
||||
/// across runs without pulling in the `rand` crate.
|
||||
struct DetRng(u64);
|
||||
|
||||
impl DetRng {
|
||||
fn new(seed: u64) -> Self {
|
||||
DetRng(seed)
|
||||
}
|
||||
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// Uniform f64 in [0, 1).
|
||||
fn next_f64(&mut self) -> f64 {
|
||||
(self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic k-means++ seeding: the first centroid is the middle point, then
|
||||
/// each subsequent centroid is drawn from the remaining points with probability
|
||||
/// proportional to its squared distance to the nearest chosen centroid (D²
|
||||
/// weighting). For unit-normalized embeddings the squared Euclidean distance is
|
||||
/// proportional to `1 - cos`, so that is used as the weight. Unlike greedy
|
||||
/// farthest-point seeding this places proportionally more centroids in dense
|
||||
/// regions, preventing a single centroid from absorbing the whole dominant mode.
|
||||
fn kmeans_pp_seed(points: &[Vec<f32>], k: usize) -> Vec<Vec<f32>> {
|
||||
let n = points.len();
|
||||
let mut rng = DetRng::new(0x5EED_1234_ABCD_0001);
|
||||
let mut centroids: Vec<Vec<f32>> = Vec::with_capacity(k);
|
||||
centroids.push(points[n / 2].clone());
|
||||
|
||||
// d2[i] = distance from point i to its nearest chosen centroid (∝ squared
|
||||
// Euclidean for unit vectors), kept up to date as centroids are added.
|
||||
let mut d2 = vec![f32::MAX; n];
|
||||
for _ in 1..k {
|
||||
let next = points
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let best_sim = centroids
|
||||
.iter()
|
||||
.map(|c| dot(p, c))
|
||||
.fold(f32::NEG_INFINITY, f32::max);
|
||||
1.0 - best_sim // distance = 1 - cosine_similarity
|
||||
})
|
||||
.enumerate()
|
||||
.max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
|
||||
.map(|(i, _)| i)
|
||||
.unwrap_or(0);
|
||||
centroids.push(points[next].clone());
|
||||
let last = centroids.last().unwrap();
|
||||
for (i, p) in points.iter().enumerate() {
|
||||
let dist = (1.0 - dot(p, last)).max(0.0);
|
||||
if dist < d2[i] {
|
||||
d2[i] = dist;
|
||||
}
|
||||
}
|
||||
|
||||
let total: f64 = d2.iter().map(|&w| w as f64).sum();
|
||||
if total <= 0.0 {
|
||||
// Remaining points coincide with chosen centroids; pad deterministically.
|
||||
centroids.push(points[n / 2].clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut target = rng.next_f64() * total;
|
||||
let mut idx = n - 1;
|
||||
for (i, &w) in d2.iter().enumerate() {
|
||||
target -= w as f64;
|
||||
if target <= 0.0 {
|
||||
idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
centroids.push(points[idx].clone());
|
||||
}
|
||||
|
||||
centroids
|
||||
}
|
||||
|
||||
/// Runs deterministic k-means++ seeding + Lloyd iterations on `points`, returning
|
||||
/// the final normalized centroids. Operates only on the slice it is given — the
|
||||
/// caller passes a sample for large libraries.
|
||||
fn kmeans_centroids(points: &[Vec<f32>], k: usize, max_iter: usize) -> Vec<Vec<f32>> {
|
||||
let n = points.len();
|
||||
let dim = points[0].len();
|
||||
|
||||
// Density-aware k-means++ seeding (see kmeans_pp_seed). Crucially NOT greedy
|
||||
// farthest-point seeding, which picks outliers and — on a sampled large
|
||||
// library — leaves the dense core under-seeded so one centroid swallows a huge
|
||||
// share of the (visually generic) images.
|
||||
let mut centroids = kmeans_pp_seed(points, k);
|
||||
|
||||
let mut assignments = vec![0usize; n];
|
||||
|
||||
for _ in 0..max_iter {
|
||||
@@ -1901,12 +2030,26 @@ fn kmeans_cosine(
|
||||
}
|
||||
}
|
||||
|
||||
let mut counts = vec![0usize; k];
|
||||
for &a in &assignments {
|
||||
counts[a] += 1;
|
||||
}
|
||||
centroids
|
||||
}
|
||||
|
||||
(centroids, counts, assignments)
|
||||
/// Assigns each point to its nearest centroid (max cosine similarity) in parallel.
|
||||
/// This is the only step that touches every embedding, so parallelising it is
|
||||
/// where the multi-core speed-up on large libraries comes from.
|
||||
fn assign_to_centroids(points: &[Vec<f32>], centroids: &[Vec<f32>]) -> Vec<usize> {
|
||||
use rayon::prelude::*;
|
||||
points
|
||||
.par_iter()
|
||||
.map(|p| {
|
||||
centroids
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(j, c)| (j, dot(p, c)))
|
||||
.max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
|
||||
.map(|(j, _)| j)
|
||||
.unwrap_or(0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -2016,6 +2159,7 @@ pub struct SetTaggerModelParams {
|
||||
#[derive(Deserialize)]
|
||||
pub struct SetTaggerThresholdParams {
|
||||
pub threshold: f32,
|
||||
pub model: Option<TaggerModel>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -2036,6 +2180,12 @@ pub struct ClearTaggingJobsParams {
|
||||
pub folder_ids: Option<Vec<i64>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ResetAiTagsParams {
|
||||
pub folder_id: Option<i64>,
|
||||
pub folder_ids: Option<Vec<i64>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct GetImageTagsParams {
|
||||
pub image_id: i64,
|
||||
@@ -2109,7 +2259,11 @@ pub async fn set_tagger_threshold(
|
||||
params: SetTaggerThresholdParams,
|
||||
) -> Result<f32, String> {
|
||||
let app_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
|
||||
tagger::set_tagger_threshold(&app_dir, params.threshold).map_err(|e| e.to_string())
|
||||
match params.model {
|
||||
Some(model) => tagger::set_tagger_threshold_for_model(&app_dir, model, params.threshold),
|
||||
None => tagger::set_tagger_threshold(&app_dir, params.threshold),
|
||||
}
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -2234,6 +2388,42 @@ pub async fn clear_tagging_jobs(
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn reset_ai_tags(
|
||||
app: AppHandle,
|
||||
db: State<'_, DbState>,
|
||||
params: ResetAiTagsParams,
|
||||
) -> Result<usize, String> {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
let requested_folder_ids = params.folder_ids.unwrap_or_default();
|
||||
let (n, folder_ids): (usize, Vec<i64>) =
|
||||
match (params.folder_id, requested_folder_ids.is_empty()) {
|
||||
(Some(id), _) => (
|
||||
db::reset_ai_tags(&conn, Some(id)).map_err(|e| e.to_string())?,
|
||||
vec![id],
|
||||
),
|
||||
(None, false) => {
|
||||
let mut total = 0usize;
|
||||
for &folder_id in &requested_folder_ids {
|
||||
total +=
|
||||
db::reset_ai_tags(&conn, Some(folder_id)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
(total, requested_folder_ids)
|
||||
}
|
||||
(None, true) => (
|
||||
db::reset_ai_tags(&conn, None).map_err(|e| e.to_string())?,
|
||||
db::get_folders(&conn)
|
||||
.map_err(|e| e.to_string())?
|
||||
.into_iter()
|
||||
.map(|f| f.id)
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
drop(conn);
|
||||
indexer::emit_folder_job_progress(&app, db.inner(), &folder_ids, true);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_image_tags(
|
||||
db: State<'_, DbState>,
|
||||
|
||||
+690
-33
@@ -146,6 +146,8 @@ pub struct ExploreTagEntry {
|
||||
pub count: i64,
|
||||
pub representative_image_id: i64,
|
||||
pub thumbnail_path: Option<String>,
|
||||
pub has_ai_source: bool,
|
||||
pub has_user_source: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -267,12 +269,16 @@ pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
UNIQUE(image_id, tag)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tag_cloud_cache (
|
||||
CREATE TABLE IF NOT EXISTS visual_cluster_cache (
|
||||
folder_scope TEXT PRIMARY KEY,
|
||||
image_ids_hash INTEGER NOT NULL,
|
||||
entries_json TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
-- Renamed from the misnamed tag_cloud_cache (it caches visual clusters,
|
||||
-- not tags). The cache is disposable and was already invalidated by a
|
||||
-- cluster-algorithm version bump, so the old table is simply dropped.
|
||||
DROP TABLE IF EXISTS tag_cloud_cache;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS duplicate_scan_cache (
|
||||
folder_scope TEXT PRIMARY KEY,
|
||||
@@ -297,6 +303,7 @@ pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_image_id ON image_tags(image_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_source ON image_tags(source);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_tag ON image_tags(tag);
|
||||
CREATE INDEX IF NOT EXISTS idx_image_tags_tag_image_id ON image_tags(tag, image_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS albums (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -407,7 +414,7 @@ fn remove_filtered_ai_tags(conn: &Connection) -> Result<()> {
|
||||
delete_stmt.execute([id])?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM tag_cloud_cache", [])?;
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
|
||||
log::info!(
|
||||
@@ -1297,6 +1304,16 @@ fn media_kind_clause(include_videos: bool) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Escapes `%`, `_`, and `\` so a user-supplied string can be safely embedded
|
||||
/// in a `LIKE` pattern (paired with `ESCAPE '\\'` in the query) without the
|
||||
/// wildcards being interpreted literally.
|
||||
fn escape_like_pattern(value: &str) -> String {
|
||||
value
|
||||
.replace('\\', "\\\\")
|
||||
.replace('%', "\\%")
|
||||
.replace('_', "\\_")
|
||||
}
|
||||
|
||||
/// True if any claimable (pending, non-excluded) jobs exist in `job_table`.
|
||||
/// Used by lower-priority workers to defer to higher-priority queues.
|
||||
/// `extra_predicate` narrows the image join (e.g. videos only for metadata).
|
||||
@@ -2120,7 +2137,7 @@ pub fn get_images(
|
||||
_ => "modified_at DESC NULLS LAST",
|
||||
};
|
||||
|
||||
let search_pattern = search.map(|value| format!("%{value}%"));
|
||||
let search_pattern = search.map(|value| format!("%{}%", escape_like_pattern(value)));
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let embedding_failed_flag = i64::from(embedding_failed_only);
|
||||
let tagging_failed_flag = i64::from(tagging_failed_only);
|
||||
@@ -2136,7 +2153,7 @@ pub fn get_images(
|
||||
ai_rating, ai_tagger_model, ai_tagged_at, ai_tagger_error
|
||||
FROM images
|
||||
WHERE (?1 IS NULL OR folder_id = ?1)
|
||||
AND (?2 IS NULL OR filename LIKE ?2)
|
||||
AND (?2 IS NULL OR filename LIKE ?2 ESCAPE '\\')
|
||||
AND (?3 IS NULL OR media_kind = ?3)
|
||||
AND (?4 = 0 OR favorite = 1)
|
||||
AND rating >= ?5
|
||||
@@ -2187,7 +2204,7 @@ pub fn count_images(
|
||||
tagging_failed_only: bool,
|
||||
color: Option<(u8, u8, u8)>,
|
||||
) -> Result<i64> {
|
||||
let search_pattern = search.map(|value| format!("%{value}%"));
|
||||
let search_pattern = search.map(|value| format!("%{}%", escape_like_pattern(value)));
|
||||
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let embedding_failed_flag = i64::from(embedding_failed_only);
|
||||
@@ -2199,7 +2216,7 @@ pub fn count_images(
|
||||
let count = conn.query_row(
|
||||
"SELECT COUNT(*) FROM images
|
||||
WHERE (?1 IS NULL OR folder_id = ?1)
|
||||
AND (?2 IS NULL OR filename LIKE ?2)
|
||||
AND (?2 IS NULL OR filename LIKE ?2 ESCAPE '\\')
|
||||
AND (?3 IS NULL OR media_kind = ?3)
|
||||
AND (?4 = 0 OR favorite = 1)
|
||||
AND rating >= ?5
|
||||
@@ -2240,6 +2257,7 @@ pub fn search_images_by_tag(
|
||||
media_kind: Option<&str>,
|
||||
favorites_only: bool,
|
||||
rating_min: i64,
|
||||
color: Option<(u8, u8, u8)>,
|
||||
limit: usize,
|
||||
offset: usize,
|
||||
) -> Result<(Vec<ImageRecord>, usize)> {
|
||||
@@ -2248,6 +2266,10 @@ pub fn search_images_by_tag(
|
||||
return Ok((Vec::new(), 0));
|
||||
}
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let (color_flag, qr, qg, qb) = match color {
|
||||
Some((r, g, b)) => (1i64, r as i64, g as i64, b as i64),
|
||||
None => (0, 0, 0, 0),
|
||||
};
|
||||
|
||||
// Total count (for pagination)
|
||||
let total: usize = conn.query_row(
|
||||
@@ -2258,13 +2280,25 @@ pub fn search_images_by_tag(
|
||||
AND (?2 IS NULL OR i.media_kind = ?2)
|
||||
AND (?3 = 0 OR i.favorite = 1)
|
||||
AND i.rating >= ?4
|
||||
AND LOWER(TRIM(t.tag)) = ?5",
|
||||
AND LOWER(TRIM(t.tag)) = ?5
|
||||
AND (?6 = 0 OR EXISTS (
|
||||
SELECT 1 FROM image_colors c
|
||||
WHERE c.image_id = i.id
|
||||
AND c.weight >= ?11
|
||||
AND ((c.r - ?7)*(c.r - ?7) + (c.g - ?8)*(c.g - ?8) + (c.b - ?9)*(c.b - ?9)) <= ?10
|
||||
))",
|
||||
params![
|
||||
folder_id,
|
||||
media_kind,
|
||||
favorites_flag,
|
||||
rating_min,
|
||||
normalized_query
|
||||
normalized_query,
|
||||
color_flag,
|
||||
qr,
|
||||
qg,
|
||||
qb,
|
||||
crate::color::MATCH_DISTANCE_SQ,
|
||||
crate::color::MATCH_MIN_WEIGHT
|
||||
],
|
||||
|row| row.get::<_, i64>(0),
|
||||
)? as usize;
|
||||
@@ -2278,8 +2312,14 @@ pub fn search_images_by_tag(
|
||||
AND (?3 = 0 OR i.favorite = 1)
|
||||
AND i.rating >= ?4
|
||||
AND LOWER(TRIM(t.tag)) = ?5
|
||||
AND (?6 = 0 OR EXISTS (
|
||||
SELECT 1 FROM image_colors c
|
||||
WHERE c.image_id = i.id
|
||||
AND c.weight >= ?11
|
||||
AND ((c.r - ?7)*(c.r - ?7) + (c.g - ?8)*(c.g - ?8) + (c.b - ?9)*(c.b - ?9)) <= ?10
|
||||
))
|
||||
ORDER BY i.rating DESC, i.modified_at DESC NULLS LAST, i.filename ASC
|
||||
LIMIT ?6 OFFSET ?7",
|
||||
LIMIT ?12 OFFSET ?13",
|
||||
)?;
|
||||
|
||||
let image_ids = stmt
|
||||
@@ -2290,6 +2330,12 @@ pub fn search_images_by_tag(
|
||||
favorites_flag,
|
||||
rating_min,
|
||||
normalized_query,
|
||||
color_flag,
|
||||
qr,
|
||||
qg,
|
||||
qb,
|
||||
crate::color::MATCH_DISTANCE_SQ,
|
||||
crate::color::MATCH_MIN_WEIGHT,
|
||||
limit as i64,
|
||||
offset as i64
|
||||
],
|
||||
@@ -2306,13 +2352,15 @@ pub fn search_tags_autocomplete(
|
||||
folder_id: Option<i64>,
|
||||
limit: usize,
|
||||
) -> Result<Vec<ExploreTagEntry>> {
|
||||
let pattern = format!("%{}%", query.to_lowercase());
|
||||
let pattern = format!("%{}%", escape_like_pattern(&query.to_lowercase()));
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT t.tag, COUNT(DISTINCT t.image_id) AS tag_count, MIN(t.image_id) AS representative_image_id
|
||||
"SELECT t.tag, COUNT(DISTINCT t.image_id) AS tag_count, MIN(t.image_id) AS representative_image_id,
|
||||
MAX(CASE WHEN t.source = 'ai' THEN 1 ELSE 0 END) AS has_ai_source,
|
||||
MAX(CASE WHEN t.source = 'user' THEN 1 ELSE 0 END) AS has_user_source
|
||||
FROM image_tags t
|
||||
JOIN images i ON i.id = t.image_id
|
||||
WHERE (?1 IS NULL OR i.folder_id = ?1)
|
||||
AND LOWER(t.tag) LIKE ?2
|
||||
AND LOWER(t.tag) LIKE ?2 ESCAPE '\\'
|
||||
GROUP BY t.tag
|
||||
ORDER BY tag_count DESC, t.tag ASC
|
||||
LIMIT ?3",
|
||||
@@ -2324,6 +2372,8 @@ pub fn search_tags_autocomplete(
|
||||
count: row.get(1)?,
|
||||
representative_image_id: row.get(2)?,
|
||||
thumbnail_path: None, // skip per-suggestion thumbnail for speed
|
||||
has_ai_source: row.get::<_, i64>(3)? != 0,
|
||||
has_user_source: row.get::<_, i64>(4)? != 0,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
@@ -2407,28 +2457,42 @@ pub fn get_explore_tags(
|
||||
limit: usize,
|
||||
) -> Result<Vec<ExploreTagEntry>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT t.tag, COUNT(DISTINCT t.image_id) AS tag_count, MIN(t.image_id) AS representative_image_id
|
||||
FROM image_tags t
|
||||
JOIN images i ON i.id = t.image_id
|
||||
WHERE (?1 IS NULL OR i.folder_id = ?1)
|
||||
GROUP BY t.tag
|
||||
HAVING COUNT(DISTINCT t.image_id) >= 1
|
||||
ORDER BY tag_count DESC, t.tag ASC
|
||||
LIMIT ?2",
|
||||
"WITH tag_counts AS (
|
||||
SELECT t.tag,
|
||||
COUNT(DISTINCT t.image_id) AS tag_count,
|
||||
MIN(t.image_id) AS representative_image_id,
|
||||
MAX(CASE WHEN t.source = 'ai' THEN 1 ELSE 0 END) AS has_ai_source,
|
||||
MAX(CASE WHEN t.source = 'user' THEN 1 ELSE 0 END) AS has_user_source
|
||||
FROM image_tags t
|
||||
JOIN images i ON i.id = t.image_id
|
||||
WHERE (?1 IS NULL OR i.folder_id = ?1)
|
||||
GROUP BY t.tag
|
||||
HAVING COUNT(DISTINCT t.image_id) >= 1
|
||||
ORDER BY tag_count DESC, t.tag ASC
|
||||
LIMIT ?2
|
||||
)
|
||||
SELECT c.tag,
|
||||
c.tag_count,
|
||||
c.representative_image_id,
|
||||
i.thumbnail_path,
|
||||
c.has_ai_source,
|
||||
c.has_user_source
|
||||
FROM tag_counts c
|
||||
JOIN images i ON i.id = c.representative_image_id
|
||||
ORDER BY c.tag_count DESC, c.tag ASC",
|
||||
)?;
|
||||
|
||||
let rows = stmt
|
||||
.query_map(params![folder_id, limit as i64], |row| {
|
||||
let representative_image_id = row.get::<_, i64>(2)?;
|
||||
let thumbnail_path = get_image_by_id(conn, representative_image_id)
|
||||
.ok()
|
||||
.and_then(|image| image.thumbnail_path);
|
||||
|
||||
Ok(ExploreTagEntry {
|
||||
tag: row.get(0)?,
|
||||
count: row.get(1)?,
|
||||
representative_image_id,
|
||||
thumbnail_path,
|
||||
thumbnail_path: row.get(3)?,
|
||||
has_ai_source: row.get::<_, i64>(4)? != 0,
|
||||
has_user_source: row.get::<_, i64>(5)? != 0,
|
||||
})
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
@@ -2799,9 +2863,9 @@ pub fn rename_tag(conn: &Connection, from: &str, to: &str) -> Result<()> {
|
||||
)?;
|
||||
// …then drop the now-duplicate leftovers still under the old name.
|
||||
tx.execute("DELETE FROM image_tags WHERE tag = ?1", params![from])?;
|
||||
// The tag-cloud cache keys on image-id hashes, not tag text, so a rename
|
||||
// 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 tag_cloud_cache", [])?;
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -2810,11 +2874,115 @@ pub fn rename_tag(conn: &Connection, from: &str, to: &str) -> Result<()> {
|
||||
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 tag_cloud_cache", [])?;
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn reset_ai_tags(conn: &Connection, folder_id: Option<i64>) -> Result<usize> {
|
||||
let image_ids = match folder_id {
|
||||
Some(folder_id) => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT DISTINCT i.id
|
||||
FROM images i
|
||||
LEFT JOIN image_tags t ON t.image_id = i.id AND t.source = 'ai'
|
||||
LEFT JOIN tagging_jobs j ON j.image_id = i.id
|
||||
WHERE i.folder_id = ?1
|
||||
AND i.media_kind = 'image'
|
||||
AND (
|
||||
t.id IS NOT NULL
|
||||
OR i.ai_rating IS NOT NULL
|
||||
OR i.ai_tagger_model IS NOT NULL
|
||||
OR i.ai_tagged_at IS NOT NULL
|
||||
OR i.ai_tagger_error IS NOT NULL
|
||||
OR j.image_id IS NOT NULL
|
||||
)",
|
||||
)?;
|
||||
let rows = stmt.query_map([folder_id], |row| row.get::<_, i64>(0))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
}
|
||||
None => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT DISTINCT i.id
|
||||
FROM images i
|
||||
LEFT JOIN image_tags t ON t.image_id = i.id AND t.source = 'ai'
|
||||
LEFT JOIN tagging_jobs j ON j.image_id = i.id
|
||||
WHERE i.media_kind = 'image'
|
||||
AND (
|
||||
t.id IS NOT NULL
|
||||
OR i.ai_rating IS NOT NULL
|
||||
OR i.ai_tagger_model IS NOT NULL
|
||||
OR i.ai_tagged_at IS NOT NULL
|
||||
OR i.ai_tagger_error IS NOT NULL
|
||||
OR j.image_id IS NOT NULL
|
||||
)",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| row.get::<_, i64>(0))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
}
|
||||
};
|
||||
|
||||
let tx = conn.unchecked_transaction()?;
|
||||
match folder_id {
|
||||
Some(folder_id) => {
|
||||
tx.execute(
|
||||
"DELETE FROM image_tags
|
||||
WHERE source = 'ai'
|
||||
AND image_id IN (SELECT id FROM images WHERE folder_id = ?1)",
|
||||
[folder_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE images
|
||||
SET ai_rating = NULL,
|
||||
ai_tagger_model = NULL,
|
||||
ai_tagged_at = NULL,
|
||||
ai_tagger_error = NULL
|
||||
WHERE folder_id = ?1
|
||||
AND media_kind = 'image'",
|
||||
[folder_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE tagging_jobs
|
||||
SET status = 'cancelled', last_error = NULL, updated_at = datetime('now')
|
||||
WHERE status = 'processing'
|
||||
AND image_id IN (SELECT id FROM images WHERE folder_id = ?1)",
|
||||
[folder_id],
|
||||
)?;
|
||||
tx.execute(
|
||||
"DELETE FROM tagging_jobs
|
||||
WHERE status NOT IN ('processing', 'cancelled')
|
||||
AND image_id IN (SELECT id FROM images WHERE folder_id = ?1)",
|
||||
[folder_id],
|
||||
)?;
|
||||
}
|
||||
None => {
|
||||
tx.execute("DELETE FROM image_tags WHERE source = 'ai'", [])?;
|
||||
tx.execute(
|
||||
"UPDATE images
|
||||
SET ai_rating = NULL,
|
||||
ai_tagger_model = NULL,
|
||||
ai_tagged_at = NULL,
|
||||
ai_tagger_error = NULL
|
||||
WHERE media_kind = 'image'",
|
||||
[],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE tagging_jobs
|
||||
SET status = 'cancelled', last_error = NULL, updated_at = datetime('now')
|
||||
WHERE status = 'processing'",
|
||||
[],
|
||||
)?;
|
||||
tx.execute(
|
||||
"DELETE FROM tagging_jobs WHERE status NOT IN ('processing', 'cancelled')",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM visual_cluster_cache", [])?;
|
||||
tx.commit()?;
|
||||
Ok(image_ids.len())
|
||||
}
|
||||
|
||||
pub fn enqueue_missing_tagging_jobs_for_folder(conn: &Connection, folder_id: i64) -> Result<usize> {
|
||||
let inserted = conn.execute(
|
||||
"INSERT INTO tagging_jobs (image_id, status, attempts, last_error, created_at, updated_at)
|
||||
@@ -2983,14 +3151,14 @@ fn map_image_row(row: &Row<'_>) -> rusqlite::Result<ImageRecord> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns cached tag-cloud entries if the stored hash matches `current_hash`.
|
||||
pub fn get_tag_cloud_cache(
|
||||
/// Returns cached visual-cluster entries if the stored hash matches `current_hash`.
|
||||
pub fn get_visual_cluster_cache(
|
||||
conn: &Connection,
|
||||
folder_scope: &str,
|
||||
current_hash: u64,
|
||||
) -> Result<Option<String>> {
|
||||
let result: rusqlite::Result<(i64, String)> = conn.query_row(
|
||||
"SELECT image_ids_hash, entries_json FROM tag_cloud_cache WHERE folder_scope = ?1",
|
||||
"SELECT image_ids_hash, entries_json FROM visual_cluster_cache WHERE folder_scope = ?1",
|
||||
params![folder_scope],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
);
|
||||
@@ -3002,15 +3170,15 @@ pub fn get_tag_cloud_cache(
|
||||
}
|
||||
}
|
||||
|
||||
/// Upserts the tag-cloud cache for the given scope.
|
||||
pub fn set_tag_cloud_cache(
|
||||
/// Upserts the visual-cluster cache for the given scope.
|
||||
pub fn set_visual_cluster_cache(
|
||||
conn: &Connection,
|
||||
folder_scope: &str,
|
||||
image_ids_hash: u64,
|
||||
entries_json: &str,
|
||||
) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT INTO tag_cloud_cache (folder_scope, image_ids_hash, entries_json, created_at)
|
||||
"INSERT INTO visual_cluster_cache (folder_scope, image_ids_hash, entries_json, created_at)
|
||||
VALUES (?1, ?2, ?3, datetime('now'))
|
||||
ON CONFLICT(folder_scope) DO UPDATE SET
|
||||
image_ids_hash = excluded.image_ids_hash,
|
||||
@@ -3107,3 +3275,492 @@ fn folder_exclusion_clause(
|
||||
.join(",");
|
||||
format!("AND {image_alias}.folder_id NOT IN ({id_list})")
|
||||
}
|
||||
|
||||
/// Shared fixtures for unit tests across modules (db, vector, …).
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
|
||||
pub(crate) fn test_conn() -> Connection {
|
||||
vector::register_sqlite_vec();
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
// The r2d2 pool customizer normally sets this; mirror it so FK cascades
|
||||
// (album deletion, folder deletion) behave like production.
|
||||
conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
|
||||
migrate(&conn).unwrap();
|
||||
vector::migrate(&conn).unwrap();
|
||||
conn
|
||||
}
|
||||
|
||||
pub(crate) fn test_image(folder_id: i64, path: &str) -> ImageRecord {
|
||||
ImageRecord {
|
||||
id: 0,
|
||||
folder_id,
|
||||
path: path.to_string(),
|
||||
filename: path.rsplit('/').next().unwrap_or(path).to_string(),
|
||||
thumbnail_path: None,
|
||||
width: Some(100),
|
||||
height: Some(100),
|
||||
file_size: 1024,
|
||||
created_at: None,
|
||||
modified_at: Some("2026-01-01T00:00:00Z".into()),
|
||||
taken_at: None,
|
||||
mime_type: "image/jpeg".into(),
|
||||
media_kind: "image".into(),
|
||||
duration_ms: None,
|
||||
video_codec: None,
|
||||
audio_codec: None,
|
||||
metadata_updated_at: None,
|
||||
metadata_error: None,
|
||||
favorite: false,
|
||||
rating: 0,
|
||||
embedding_status: "pending".into(),
|
||||
embedding_model: None,
|
||||
embedding_updated_at: None,
|
||||
embedding_error: None,
|
||||
generated_caption: None,
|
||||
caption_model: None,
|
||||
caption_updated_at: None,
|
||||
caption_error: None,
|
||||
ai_rating: None,
|
||||
ai_tagger_model: None,
|
||||
ai_tagged_at: None,
|
||||
ai_tagger_error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::test_support::{test_conn, test_image};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn escape_like_pattern_escapes_wildcards_and_backslash() {
|
||||
assert_eq!(escape_like_pattern("50%off"), "50\\%off");
|
||||
assert_eq!(escape_like_pattern("a_b"), "a\\_b");
|
||||
assert_eq!(escape_like_pattern(r"C:\images"), r"C:\\images");
|
||||
assert_eq!(escape_like_pattern("50%_x\\"), "50\\%\\_x\\\\");
|
||||
assert_eq!(escape_like_pattern("plain text"), "plain text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_folder_is_idempotent_per_path() {
|
||||
let conn = test_conn();
|
||||
let first = insert_folder(&conn, "C:/media", "media").unwrap();
|
||||
let second = insert_folder(&conn, "C:/media", "media again").unwrap();
|
||||
assert_eq!(first, second);
|
||||
|
||||
insert_folder(&conn, "C:/other", "other").unwrap();
|
||||
let folders = get_folders(&conn).unwrap();
|
||||
assert_eq!(folders.len(), 2);
|
||||
assert_eq!(folders[0].name, "media");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_image_updates_in_place_and_preserves_user_state() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/media", "media").unwrap();
|
||||
let mut img = test_image(folder_id, "C:/media/a.jpg");
|
||||
let id = upsert_image(&conn, &img).unwrap();
|
||||
|
||||
// Simulate user state + AI state on the stored row.
|
||||
conn.execute(
|
||||
"UPDATE images SET favorite = 1, rating = 4, ai_tagger_model = 'wd' WHERE id = ?1",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
add_user_tag(&conn, id, "keeper").unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO image_tags (image_id, tag, source, ai_model, confidence, created_at)
|
||||
VALUES (?1, 'cat', 'ai', 'wd', 0.9, datetime('now'))",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
img.file_size = 2048;
|
||||
let same_id = upsert_image(&conn, &img).unwrap();
|
||||
assert_eq!(same_id, id);
|
||||
|
||||
let stored = get_image_by_id(&conn, id).unwrap();
|
||||
assert_eq!(stored.file_size, 2048);
|
||||
// favorite/rating survive re-index; AI tag state is invalidated.
|
||||
assert!(stored.favorite);
|
||||
assert_eq!(stored.rating, 4);
|
||||
assert_eq!(stored.ai_tagger_model, None);
|
||||
|
||||
let tags = get_image_tags(&conn, id).unwrap();
|
||||
assert_eq!(tags.len(), 1);
|
||||
assert_eq!(tags[0].tag, "keeper");
|
||||
assert_eq!(tags[0].source, "user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_images_applies_filters_and_agrees_with_count() {
|
||||
let conn = test_conn();
|
||||
let folder_a = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let folder_b = insert_folder(&conn, "C:/b", "b").unwrap();
|
||||
|
||||
upsert_image(&conn, &test_image(folder_a, "C:/a/cat.jpg")).unwrap();
|
||||
let dog_id = upsert_image(&conn, &test_image(folder_a, "C:/a/dog.jpg")).unwrap();
|
||||
let mut video = test_image(folder_b, "C:/b/clip.mp4");
|
||||
video.media_kind = "video".into();
|
||||
video.embedding_status = "failed".into();
|
||||
upsert_image(&conn, &video).unwrap();
|
||||
conn.execute(
|
||||
"UPDATE images SET favorite = 1, rating = 5 WHERE id = ?1",
|
||||
[dog_id],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let no_filter = get_images(
|
||||
&conn, None, None, None, false, 0, false, false, None, "name_asc", 0, 100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(no_filter.len(), 3);
|
||||
assert_eq!(
|
||||
count_images(&conn, None, None, None, false, 0, false, false, None).unwrap(),
|
||||
3
|
||||
);
|
||||
|
||||
let by_folder = get_images(
|
||||
&conn,
|
||||
Some(folder_a),
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
0,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
"name_asc",
|
||||
0,
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(by_folder.len(), 2);
|
||||
|
||||
let by_search = get_images(
|
||||
&conn,
|
||||
None,
|
||||
Some("cat"),
|
||||
None,
|
||||
false,
|
||||
0,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
"name_asc",
|
||||
0,
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(by_search.len(), 1);
|
||||
assert_eq!(by_search[0].filename, "cat.jpg");
|
||||
|
||||
let videos = get_images(
|
||||
&conn,
|
||||
None,
|
||||
None,
|
||||
Some("video"),
|
||||
false,
|
||||
0,
|
||||
false,
|
||||
false,
|
||||
None,
|
||||
"name_asc",
|
||||
0,
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(videos.len(), 1);
|
||||
|
||||
let favorites = get_images(
|
||||
&conn, None, None, None, true, 0, false, false, None, "name_asc", 0, 100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(favorites.len(), 1);
|
||||
assert_eq!(favorites[0].filename, "dog.jpg");
|
||||
|
||||
let rated = get_images(
|
||||
&conn, None, None, None, false, 3, false, false, None, "name_asc", 0, 100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rated.len(), 1);
|
||||
|
||||
let failed = get_images(
|
||||
&conn, None, None, None, false, 0, true, false, None, "name_asc", 0, 100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(failed.len(), 1);
|
||||
assert_eq!(failed[0].filename, "clip.mp4");
|
||||
|
||||
// Pagination: page size 2 then the remaining 1.
|
||||
let page_one = get_images(
|
||||
&conn, None, None, None, false, 0, false, false, None, "name_asc", 0, 2,
|
||||
)
|
||||
.unwrap();
|
||||
let page_two = get_images(
|
||||
&conn, None, None, None, false, 0, false, false, None, "name_asc", 2, 2,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(page_one.len(), 2);
|
||||
assert_eq!(page_two.len(), 1);
|
||||
assert_eq!(page_one[0].filename, "cat.jpg");
|
||||
assert_eq!(page_two[0].filename, "dog.jpg");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_tags_upgrade_ai_tags_and_survive_tag_maintenance() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let id = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO image_tags (image_id, tag, source, ai_model, confidence, created_at)
|
||||
VALUES (?1, 'cat', 'ai', 'wd', 0.9, datetime('now'))",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
let upgraded = add_user_tag(&conn, id, "cat").unwrap();
|
||||
assert_eq!(upgraded.source, "user");
|
||||
assert_eq!(upgraded.ai_model, None);
|
||||
assert_eq!(get_image_tags(&conn, id).unwrap().len(), 1);
|
||||
|
||||
let tag = add_user_tag(&conn, id, "kitty").unwrap();
|
||||
remove_tag(&conn, tag.id).unwrap();
|
||||
assert_eq!(get_image_tags(&conn, id).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_tag_merges_into_existing_tag() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let with_both = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
let with_old = upsert_image(&conn, &test_image(folder_id, "C:/a/b.jpg")).unwrap();
|
||||
|
||||
add_user_tag(&conn, with_both, "cat").unwrap();
|
||||
add_user_tag(&conn, with_both, "kitty").unwrap();
|
||||
add_user_tag(&conn, with_old, "kitty").unwrap();
|
||||
|
||||
rename_tag(&conn, "kitty", "cat").unwrap();
|
||||
|
||||
let both_tags = get_image_tags(&conn, with_both).unwrap();
|
||||
assert_eq!(both_tags.len(), 1);
|
||||
assert_eq!(both_tags[0].tag, "cat");
|
||||
let old_tags = get_image_tags(&conn, with_old).unwrap();
|
||||
assert_eq!(old_tags.len(), 1);
|
||||
assert_eq!(old_tags[0].tag, "cat");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_tag_removes_it_everywhere_and_reports_count() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let first = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
let second = upsert_image(&conn, &test_image(folder_id, "C:/a/b.jpg")).unwrap();
|
||||
add_user_tag(&conn, first, "cat").unwrap();
|
||||
add_user_tag(&conn, second, "cat").unwrap();
|
||||
add_user_tag(&conn, second, "dog").unwrap();
|
||||
|
||||
assert_eq!(delete_tag(&conn, "cat").unwrap(), 2);
|
||||
assert_eq!(get_image_tags(&conn, first).unwrap().len(), 0);
|
||||
assert_eq!(get_image_tags(&conn, second).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn album_crud_and_membership() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let first = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
let second = upsert_image(&conn, &test_image(folder_id, "C:/a/b.jpg")).unwrap();
|
||||
|
||||
let album = create_album(&conn, "Holiday").unwrap();
|
||||
assert_eq!(album.name, "Holiday");
|
||||
assert_eq!(album.image_count, 0);
|
||||
|
||||
// Adding is idempotent.
|
||||
assert_eq!(
|
||||
add_images_to_album(&conn, album.id, &[first, second]).unwrap(),
|
||||
2
|
||||
);
|
||||
assert_eq!(add_images_to_album(&conn, album.id, &[first]).unwrap(), 0);
|
||||
assert_eq!(count_album_images(&conn, album.id).unwrap(), 2);
|
||||
|
||||
remove_images_from_album(&conn, album.id, &[first]).unwrap();
|
||||
assert_eq!(count_album_images(&conn, album.id).unwrap(), 1);
|
||||
|
||||
rename_album(&conn, album.id, "Trip").unwrap();
|
||||
assert_eq!(get_album(&conn, album.id).unwrap().name, "Trip");
|
||||
|
||||
delete_album(&conn, album.id).unwrap();
|
||||
assert!(list_albums(&conn).unwrap().is_empty());
|
||||
// Membership rows cascade away with the album.
|
||||
let orphans: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM album_images", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(orphans, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backfill_enqueues_only_unqueued_unready_images() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let pending = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
let mut ready = test_image(folder_id, "C:/a/b.jpg");
|
||||
ready.embedding_status = "ready".into();
|
||||
upsert_image(&conn, &ready).unwrap();
|
||||
let queued = upsert_image(&conn, &test_image(folder_id, "C:/a/c.jpg")).unwrap();
|
||||
enqueue_embedding_job(&conn, queued).unwrap();
|
||||
|
||||
assert_eq!(backfill_embedding_jobs(&conn).unwrap(), 1);
|
||||
let has_job: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM embedding_jobs WHERE image_id = ?1",
|
||||
[pending],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(has_job, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_failed_embeddings_skips_thumbnailless_videos() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let mut failed_image = test_image(folder_id, "C:/a/a.jpg");
|
||||
failed_image.embedding_status = "failed".into();
|
||||
let failed_image_id = upsert_image(&conn, &failed_image).unwrap();
|
||||
|
||||
let mut failed_video = test_image(folder_id, "C:/a/clip.mp4");
|
||||
failed_video.media_kind = "video".into();
|
||||
failed_video.embedding_status = "failed".into();
|
||||
failed_video.thumbnail_path = None;
|
||||
upsert_image(&conn, &failed_video).unwrap();
|
||||
|
||||
assert_eq!(retry_failed_embedding_jobs(&conn, folder_id).unwrap(), 1);
|
||||
let requeued = get_image_by_id(&conn, failed_image_id).unwrap();
|
||||
assert_eq!(requeued.embedding_status, "pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repair_embedding_consistency_requeues_ready_images_without_vectors() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let mut ready = test_image(folder_id, "C:/a/a.jpg");
|
||||
ready.embedding_status = "ready".into();
|
||||
let ready_id = upsert_image(&conn, &ready).unwrap();
|
||||
|
||||
let (orphaned, requeued) = repair_embedding_consistency(&conn).unwrap();
|
||||
assert_eq!(orphaned, 0);
|
||||
assert_eq!(requeued, 1);
|
||||
let repaired = get_image_by_id(&conn, ready_id).unwrap();
|
||||
assert_eq!(repaired.embedding_status, "pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn search_images_by_tag_is_case_insensitive_and_paginates() {
|
||||
let conn = test_conn();
|
||||
let folder_a = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let folder_b = insert_folder(&conn, "C:/b", "b").unwrap();
|
||||
let first = upsert_image(&conn, &test_image(folder_a, "C:/a/a.jpg")).unwrap();
|
||||
let second = upsert_image(&conn, &test_image(folder_a, "C:/a/b.jpg")).unwrap();
|
||||
let third = upsert_image(&conn, &test_image(folder_b, "C:/b/c.jpg")).unwrap();
|
||||
add_user_tag(&conn, first, "Cat").unwrap();
|
||||
add_user_tag(&conn, second, "cat").unwrap();
|
||||
add_user_tag(&conn, third, "cat").unwrap();
|
||||
add_user_tag(&conn, third, "dog").unwrap();
|
||||
|
||||
// Query is trimmed and matched case-insensitively against stored tags.
|
||||
let (all, total) =
|
||||
search_images_by_tag(&conn, " CAT ", None, None, false, 0, None, 10, 0).unwrap();
|
||||
assert_eq!(total, 3);
|
||||
assert_eq!(all.len(), 3);
|
||||
|
||||
let (scoped, scoped_total) =
|
||||
search_images_by_tag(&conn, "cat", Some(folder_a), None, false, 0, None, 10, 0)
|
||||
.unwrap();
|
||||
assert_eq!(scoped_total, 2);
|
||||
assert_eq!(scoped.len(), 2);
|
||||
|
||||
// Pagination: total stays the full count while the page shrinks.
|
||||
let (page, page_total) =
|
||||
search_images_by_tag(&conn, "cat", None, None, false, 0, None, 2, 2).unwrap();
|
||||
assert_eq!(page_total, 3);
|
||||
assert_eq!(page.len(), 1);
|
||||
|
||||
// Blank queries return nothing instead of matching everything.
|
||||
let (empty, empty_total) =
|
||||
search_images_by_tag(&conn, " ", None, None, false, 0, None, 10, 0).unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert_eq!(empty_total, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_ai_tags_replaces_ai_state_without_downgrading_user_tags() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let id = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
add_user_tag(&conn, id, "cat").unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO image_tags (image_id, tag, source, ai_model, confidence, created_at)
|
||||
VALUES (?1, 'stale', 'ai', 'wd', 0.5, datetime('now'))",
|
||||
[id],
|
||||
)
|
||||
.unwrap();
|
||||
enqueue_tagging_job(&conn, id).unwrap();
|
||||
|
||||
update_ai_tags(
|
||||
&conn,
|
||||
id,
|
||||
&[("cat".into(), 0.9), ("outdoors".into(), 0.7)],
|
||||
"general",
|
||||
"wd",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let tags = get_image_tags(&conn, id).unwrap();
|
||||
assert_eq!(tags.len(), 2, "stale AI tag should be gone");
|
||||
let cat = tags.iter().find(|tag| tag.tag == "cat").unwrap();
|
||||
assert_eq!(cat.source, "user", "user tag must not be downgraded to ai");
|
||||
let outdoors = tags.iter().find(|tag| tag.tag == "outdoors").unwrap();
|
||||
assert_eq!(outdoors.source, "ai");
|
||||
assert_eq!(outdoors.confidence, Some(0.7));
|
||||
|
||||
let record = get_image_by_id(&conn, id).unwrap();
|
||||
assert_eq!(record.ai_rating.as_deref(), Some("general"));
|
||||
assert_eq!(record.ai_tagger_model.as_deref(), Some("wd"));
|
||||
assert_eq!(record.ai_tagger_error, None);
|
||||
|
||||
let pending_jobs: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM tagging_jobs WHERE image_id = ?1",
|
||||
[id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(pending_jobs, 0, "completed job should be dequeued");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_folder_cascades_images_tags_and_vectors() {
|
||||
let conn = test_conn();
|
||||
let folder_id = insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let id = upsert_image(&conn, &test_image(folder_id, "C:/a/a.jpg")).unwrap();
|
||||
add_user_tag(&conn, id, "cat").unwrap();
|
||||
vector::upsert_embedding(&conn, id, &vec![0.5f32; vector::CLIP_VECTOR_DIM]).unwrap();
|
||||
|
||||
delete_folder(&conn, folder_id).unwrap();
|
||||
|
||||
assert!(get_folders(&conn).unwrap().is_empty());
|
||||
let remaining_images: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM images", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(remaining_images, 0);
|
||||
let remaining_tags: i64 = conn
|
||||
.query_row("SELECT COUNT(*) FROM image_tags", [], |row| row.get(0))
|
||||
.unwrap();
|
||||
assert_eq!(remaining_tags, 0);
|
||||
assert!(!vector::has_image_vector(&conn, id).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Resilient file downloads via the system `curl` binary.
|
||||
//!
|
||||
//! Used for all large model/runtime downloads (tagger models, ONNX Runtime
|
||||
//! DLLs, caption model). ureq's read timeout does not fire on a stalled large
|
||||
//! transfer on Windows (schannel doesn't honor the socket read timeout), so a
|
||||
//! stall there hangs forever. curl detects an inactivity stall
|
||||
//! (`--speed-time`), resumes from the partial file (`-C -`), and retries
|
||||
//! internally — the same behavior a browser gets.
|
||||
|
||||
use anyhow::Result;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
// Suppress the console window when spawning curl from the GUI app.
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::CommandExt;
|
||||
#[cfg(target_os = "windows")]
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
|
||||
/// Discard target for curl output we only need the headers of.
|
||||
#[cfg(target_os = "windows")]
|
||||
const NULL_DEVICE: &str = "NUL";
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
const NULL_DEVICE: &str = "/dev/null";
|
||||
|
||||
/// Build a `curl` command with platform quirks applied. Windows resolves the
|
||||
/// bare name to `curl.exe` (bundled since Windows 10 1803) and needs the
|
||||
/// no-window flag; macOS ships curl; Linux is expected to have it installed.
|
||||
fn curl_command() -> Command {
|
||||
#[allow(unused_mut)]
|
||||
let mut command = Command::new("curl");
|
||||
#[cfg(target_os = "windows")]
|
||||
command.creation_flags(CREATE_NO_WINDOW);
|
||||
command
|
||||
}
|
||||
|
||||
// Give up only after this many *consecutive* curl runs that download nothing;
|
||||
// a run that makes any progress resets the counter, so a large file completes
|
||||
// across however many resumes it takes. Kept low so a hard stall (e.g. a
|
||||
// broken VM NIC) fails in a couple of minutes — surfacing a retryable error —
|
||||
// rather than locking the UI on "preparing" for many minutes.
|
||||
const MAX_STALL_RETRIES: usize = 3;
|
||||
|
||||
/// Resiliently download `url` to `destination` using the system `curl`.
|
||||
///
|
||||
/// We monitor the `.part` file's size for the progress bar and wrap curl in an
|
||||
/// outer progress-aware retry as a backstop. The partial file survives an app
|
||||
/// restart, so a later retry continues from disk.
|
||||
pub fn download_file_resilient(
|
||||
url: &str,
|
||||
destination: &Path,
|
||||
mut on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
if let Some(parent) = destination.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let part = match destination.extension() {
|
||||
Some(ext) => destination.with_extension(format!("{}.part", ext.to_string_lossy())),
|
||||
None => destination.with_extension("part"),
|
||||
};
|
||||
let name = destination
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| url.to_string());
|
||||
|
||||
log::info!("{name}: resolving download size");
|
||||
let total = remote_content_length(url);
|
||||
|
||||
// Reconcile any existing `.part` against the real size: exactly complete →
|
||||
// finish; oversized (stale/corrupt) → discard so curl restarts cleanly
|
||||
// (otherwise `curl -C -` would 416 forever).
|
||||
if let Some(total) = total {
|
||||
let size = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if size == total {
|
||||
std::fs::rename(&part, destination)?;
|
||||
return Ok(());
|
||||
}
|
||||
if size > total {
|
||||
let _ = std::fs::remove_file(&part);
|
||||
}
|
||||
}
|
||||
log::info!(
|
||||
"{name}: downloading via curl ({} bytes)",
|
||||
total
|
||||
.map(|t| t.to_string())
|
||||
.unwrap_or_else(|| "unknown size".into())
|
||||
);
|
||||
|
||||
let mut stalls = 0usize;
|
||||
loop {
|
||||
let before = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
match run_curl_download(url, &part, total, &mut on_progress) {
|
||||
Ok(()) => break,
|
||||
Err(error) => {
|
||||
let after = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if after > before {
|
||||
log::warn!("{name}: curl interrupted at {after} bytes, resuming: {error}");
|
||||
stalls = 0;
|
||||
} else {
|
||||
stalls += 1;
|
||||
log::warn!(
|
||||
"{name}: curl made no progress ({stalls}/{MAX_STALL_RETRIES}): {error}"
|
||||
);
|
||||
if stalls >= MAX_STALL_RETRIES {
|
||||
// Discard the partial so a future attempt restarts clean
|
||||
// rather than getting stuck re-resuming a bad file.
|
||||
let _ = std::fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(total) = total {
|
||||
let got = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
|
||||
if got < total {
|
||||
anyhow::bail!("{name}: incomplete after curl ({got}/{total} bytes)");
|
||||
}
|
||||
}
|
||||
std::fs::rename(&part, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Size probe via `curl -r 0-0` (a 1-byte Range request), parsing the total
|
||||
/// from the `Content-Range: bytes 0-0/<total>` header. Uses curl rather than
|
||||
/// ureq so no part of the download path depends on ureq (which hangs on this
|
||||
/// VM's TLS stack). Returns None if the server doesn't report a size.
|
||||
fn remote_content_length(url: &str) -> Option<u64> {
|
||||
let mut command = curl_command();
|
||||
command.args([
|
||||
"-sL",
|
||||
"-r",
|
||||
"0-0",
|
||||
"-D",
|
||||
"-",
|
||||
"-o",
|
||||
NULL_DEVICE,
|
||||
"--connect-timeout",
|
||||
"30",
|
||||
"--max-time",
|
||||
"30",
|
||||
"--",
|
||||
url,
|
||||
]);
|
||||
let output = command.output().ok()?;
|
||||
let headers = String::from_utf8_lossy(&output.stdout);
|
||||
for line in headers.lines() {
|
||||
if let Some(rest) = line.to_ascii_lowercase().strip_prefix("content-range:") {
|
||||
if let Some(total) = rest.rsplit('/').next().map(str::trim) {
|
||||
if let Ok(n) = total.parse::<u64>() {
|
||||
return Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Run one `curl` download to `dest`, resuming from any partial file, while
|
||||
/// reporting progress from the growing file size. Returns an error (leaving the
|
||||
/// partial in place) if curl exits non-zero.
|
||||
fn run_curl_download(
|
||||
url: &str,
|
||||
dest: &Path,
|
||||
total: Option<u64>,
|
||||
on_progress: &mut impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
let mut command = curl_command();
|
||||
command
|
||||
.arg("-fSL") // fail on HTTP errors, follow redirects, show errors
|
||||
.args(["-C", "-"]) // resume from the existing output file
|
||||
.args(["--retry", "3", "--retry-delay", "1", "--retry-connrefused"])
|
||||
.args(["--connect-timeout", "30"])
|
||||
// Abort (then --retry resumes) if under 1 KB/s for 30s — a real
|
||||
// inactivity timeout, which is what ureq couldn't deliver here.
|
||||
.args(["--speed-limit", "1024", "--speed-time", "30"])
|
||||
.arg("-s") // no progress meter (we watch the file instead)
|
||||
.arg("-o")
|
||||
.arg(dest)
|
||||
.arg("--")
|
||||
.arg(url)
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| anyhow::anyhow!("failed to launch curl (required for downloads): {e}"))?;
|
||||
|
||||
loop {
|
||||
if let Some(status) = child.try_wait()? {
|
||||
if status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut stderr = String::new();
|
||||
if let Some(mut pipe) = child.stderr.take() {
|
||||
let _ = pipe.read_to_string(&mut stderr);
|
||||
}
|
||||
anyhow::bail!(
|
||||
"curl exited with {}: {}",
|
||||
status
|
||||
.code()
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| "signal".into()),
|
||||
stderr.trim()
|
||||
);
|
||||
}
|
||||
let downloaded = std::fs::metadata(dest).map(|m| m.len()).unwrap_or(0);
|
||||
on_progress(downloaded, total);
|
||||
std::thread::sleep(std::time::Duration::from_millis(300));
|
||||
}
|
||||
}
|
||||
|
||||
/// Download a NuGet package (a zip) resiliently, then extract the single file
|
||||
/// at `archive_path` into `destination`.
|
||||
pub fn download_nuget_file(
|
||||
source_url: &str,
|
||||
archive_path: &str,
|
||||
destination: &Path,
|
||||
on_progress: impl FnMut(u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
let package = destination.with_extension("nupkg");
|
||||
download_file_resilient(source_url, &package, on_progress)?;
|
||||
|
||||
log::info!("extracting {archive_path} from package");
|
||||
let file = std::fs::File::open(&package)?;
|
||||
let mut archive = zip::ZipArchive::new(file)?;
|
||||
let mut dll = archive.by_name(archive_path)?;
|
||||
let temp_destination = destination.with_extension("tmp");
|
||||
{
|
||||
let mut out = std::fs::File::create(&temp_destination)?;
|
||||
std::io::copy(&mut dll, &mut out)?;
|
||||
}
|
||||
std::fs::rename(&temp_destination, destination)?;
|
||||
let _ = std::fs::remove_file(&package);
|
||||
log::info!("extracted {archive_path}");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1995,3 +1995,42 @@ fn process_watcher_rename(
|
||||
Err(e) => log::error!("Watcher rename: post-update fetch error: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn supported_media_matches_known_extensions_case_insensitively() {
|
||||
for path in ["a.jpg", "b.JPEG", "c.PNG", "d.avif", "e.mp4", "f.WEBM"] {
|
||||
assert!(
|
||||
is_supported_media(Path::new(path)),
|
||||
"{path} should be supported"
|
||||
);
|
||||
}
|
||||
for path in ["notes.txt", "archive.zip", "no_extension", "clip.mkv"] {
|
||||
assert!(
|
||||
!is_supported_media(Path::new(path)),
|
||||
"{path} should be skipped"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_kind_splits_video_from_image_extensions() {
|
||||
for ext in ["mp4", "MOV", "m4v", "webm"] {
|
||||
assert_eq!(media_kind_for_ext(ext), "video");
|
||||
}
|
||||
for ext in ["jpg", "PNG", "webp", "avif"] {
|
||||
assert_eq!(media_kind_for_ext(ext), "image");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mime_types_map_per_extension() {
|
||||
assert_eq!(mime_for_ext("JPG"), "image/jpeg");
|
||||
assert_eq!(mime_for_ext("png"), "image/png");
|
||||
assert_eq!(mime_for_ext("mov"), "video/quicktime");
|
||||
assert_eq!(mime_for_ext("m4v"), "video/mp4");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,12 @@ mod captioner;
|
||||
mod color;
|
||||
mod commands;
|
||||
mod db;
|
||||
mod download;
|
||||
mod embedder;
|
||||
mod hnsw_index;
|
||||
mod indexer;
|
||||
mod media;
|
||||
mod onnx_runtime;
|
||||
mod storage;
|
||||
mod tagger;
|
||||
mod thumbnail;
|
||||
@@ -198,7 +200,7 @@ pub fn run() {
|
||||
commands::get_worker_states,
|
||||
commands::get_worker_pauses_persist,
|
||||
commands::set_worker_pauses_persist,
|
||||
commands::get_tag_cloud,
|
||||
commands::get_visual_clusters,
|
||||
commands::get_explore_tags,
|
||||
commands::get_related_tags,
|
||||
commands::get_images_by_ids,
|
||||
@@ -218,6 +220,7 @@ pub fn run() {
|
||||
commands::delete_tagger_model,
|
||||
commands::queue_tagging_jobs,
|
||||
commands::clear_tagging_jobs,
|
||||
commands::reset_ai_tags,
|
||||
commands::get_image_tags,
|
||||
commands::add_user_tag,
|
||||
commands::remove_tag,
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
//! Shared ONNX Runtime provisioning: downloading the runtime + DirectML DLLs
|
||||
//! and initializing `ort` from them.
|
||||
//!
|
||||
//! Both ONNX consumers go through here — the tagger (live) and the Florence-2
|
||||
//! captioner (backend intact, UI disabled). The DLLs are Windows/DirectML
|
||||
//! specific; a future cross-platform build needs a per-OS runtime strategy.
|
||||
|
||||
use crate::download;
|
||||
use anyhow::Result;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
const ONNX_RUNTIME_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.ML.OnnxRuntime.DirectML/1.24.2";
|
||||
const DIRECTML_NUGET_URL: &str =
|
||||
"https://www.nuget.org/api/v2/package/Microsoft.AI.DirectML/1.15.4";
|
||||
|
||||
pub const ONNX_RUNTIME_DLL_FILE: &str = "onnxruntime/onnxruntime.dll";
|
||||
pub const ONNX_RUNTIME_PROVIDERS_DLL_FILE: &str = "onnxruntime/onnxruntime_providers_shared.dll";
|
||||
pub const DIRECTML_DLL_FILE: &str = "onnxruntime/DirectML.dll";
|
||||
|
||||
/// The shared runtime DLLs, as paths relative to [`runtime_dir`].
|
||||
pub const RUNTIME_DLLS: &[&str] = &[
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
DIRECTML_DLL_FILE,
|
||||
];
|
||||
|
||||
/// `(destination_file, nuget_package_url, path_inside_package)` for each DLL.
|
||||
pub const ONNX_RUNTIME_FILES: &[(&str, &str, &str)] = &[
|
||||
(
|
||||
ONNX_RUNTIME_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime.dll",
|
||||
),
|
||||
(
|
||||
ONNX_RUNTIME_PROVIDERS_DLL_FILE,
|
||||
ONNX_RUNTIME_NUGET_URL,
|
||||
"runtimes/win-x64/native/onnxruntime_providers_shared.dll",
|
||||
),
|
||||
(
|
||||
DIRECTML_DLL_FILE,
|
||||
DIRECTML_NUGET_URL,
|
||||
"bin/x64-win/DirectML.dll",
|
||||
),
|
||||
];
|
||||
|
||||
// Mutex<bool> rather than OnceLock<Result>: a failed attempt (DLL not yet
|
||||
// downloaded) must NOT be cached, or a later successful download could never
|
||||
// recover within the same app session.
|
||||
static ORT_RUNTIME_INIT: Mutex<bool> = Mutex::new(false);
|
||||
|
||||
/// Directory the shared runtime DLLs are provisioned into.
|
||||
///
|
||||
/// Historically the DLLs were downloaded as part of the Florence-2 caption
|
||||
/// model, so they live inside that model's directory
|
||||
/// (`models/florence-2-base-ft/onnxruntime/`). The location is kept even
|
||||
/// though the tagger is now the main consumer, so existing installs don't
|
||||
/// have to re-download the runtime.
|
||||
pub fn runtime_dir(app_data_dir: &Path) -> PathBuf {
|
||||
crate::captioner::model_dir(app_data_dir)
|
||||
}
|
||||
|
||||
/// Initialize `ort` from the already-downloaded runtime DLL in `local_dir`.
|
||||
/// Fails if the DLL is missing — use [`provision_onnx_runtime_with_progress`]
|
||||
/// to download it first on a clean install.
|
||||
pub fn ensure_onnx_runtime(local_dir: &Path) -> Result<()> {
|
||||
let mut initialized = ORT_RUNTIME_INIT
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("ONNX runtime init lock poisoned"))?;
|
||||
if *initialized {
|
||||
return Ok(());
|
||||
}
|
||||
let dll_path = local_dir.join(ONNX_RUNTIME_DLL_FILE);
|
||||
if !dll_path.exists() {
|
||||
anyhow::bail!("ONNX Runtime DLL is missing: {}", dll_path.display());
|
||||
}
|
||||
ort::environment::init_from(&dll_path)
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?
|
||||
.with_name("phokus-florence")
|
||||
.commit();
|
||||
*initialized = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download any ONNX Runtime DLLs missing from `local_dir`, reporting per-file
|
||||
/// byte progress as `(short_label, downloaded_bytes, total_bytes)`.
|
||||
/// `total_bytes` is `None` when the server omits Content-Length. Unlike
|
||||
/// `ensure_onnx_runtime` (init only), this actually provisions the files —
|
||||
/// callers that can run on a clean install must call this first. The callback
|
||||
/// fires per chunk; callers should throttle.
|
||||
pub fn provision_onnx_runtime_with_progress(
|
||||
local_dir: &Path,
|
||||
mut on_progress: impl FnMut(&str, u64, Option<u64>),
|
||||
) -> Result<()> {
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
if destination.exists() {
|
||||
continue;
|
||||
}
|
||||
// Strip the "onnxruntime/" prefix for a clean label.
|
||||
let label = destination_file
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or(destination_file);
|
||||
download::download_nuget_file(
|
||||
source_url,
|
||||
archive_path,
|
||||
&destination,
|
||||
|downloaded, total| on_progress(label, downloaded, total),
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Number of ONNX Runtime DLLs still missing from `local_dir` (for progress
|
||||
/// step counts before downloading).
|
||||
pub fn missing_onnx_runtime_count(local_dir: &Path) -> usize {
|
||||
ONNX_RUNTIME_FILES
|
||||
.iter()
|
||||
.filter(|(destination_file, _, _)| !local_dir.join(destination_file).exists())
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Download all missing runtime DLLs without progress reporting.
|
||||
pub fn download_onnx_runtime_files(local_dir: &Path) -> Result<()> {
|
||||
if !cfg!(target_os = "windows") {
|
||||
anyhow::bail!("ONNX Runtime DLL download is currently configured for Windows builds");
|
||||
}
|
||||
|
||||
for (destination_file, source_url, archive_path) in ONNX_RUNTIME_FILES {
|
||||
let destination = local_dir.join(destination_file);
|
||||
download::download_nuget_file(source_url, archive_path, &destination, |_, _| {})?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -122,3 +122,53 @@ fn fallback_profile_for_path(path: &Path) -> StorageProfile {
|
||||
|
||||
StorageProfile::Balanced
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
#[test]
|
||||
fn thumbnail_workers_scale_with_parallelism_within_clamps() {
|
||||
assert_eq!(StorageProfile::Fast.thumbnail_workers(3), 2);
|
||||
assert_eq!(StorageProfile::Fast.thumbnail_workers(12), 4);
|
||||
assert_eq!(StorageProfile::Fast.thumbnail_workers(64), 4);
|
||||
assert_eq!(StorageProfile::Balanced.thumbnail_workers(4), 2);
|
||||
assert_eq!(StorageProfile::Balanced.thumbnail_workers(12), 3);
|
||||
assert_eq!(StorageProfile::Balanced.thumbnail_workers(64), 3);
|
||||
assert_eq!(StorageProfile::Conservative.thumbnail_workers(64), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_profile_tracks_scan_speed() {
|
||||
let mut adaptive = RuntimeAdaptiveProfile::new(StorageProfile::Balanced);
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Balanced);
|
||||
|
||||
// 1 ms/item → fast storage.
|
||||
adaptive.observe_scan_batch(10, Duration::from_millis(10));
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Fast);
|
||||
|
||||
// A very slow batch drags the EMA over the conservative threshold.
|
||||
adaptive.observe_scan_batch(1, Duration::from_millis(100));
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Conservative);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adaptive_profile_ignores_empty_batches() {
|
||||
let mut adaptive = RuntimeAdaptiveProfile::new(StorageProfile::Fast);
|
||||
adaptive.observe_scan_batch(0, Duration::from_secs(10));
|
||||
assert_eq!(adaptive.profile(), StorageProfile::Fast);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallback_profile_treats_unc_paths_as_conservative() {
|
||||
assert_eq!(
|
||||
fallback_profile_for_path(Path::new("\\\\server\\share\\photos")),
|
||||
StorageProfile::Conservative
|
||||
);
|
||||
assert_eq!(
|
||||
fallback_profile_for_path(Path::new("C:\\photos")),
|
||||
StorageProfile::Balanced
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+62
-56
@@ -16,6 +16,7 @@ pub const WD_TAGGER_MODEL_NAME: &str = "wd-swinv2-tagger-v3";
|
||||
|
||||
const TAGGER_ACCELERATION_FILE: &str = "settings/tagger_acceleration.txt";
|
||||
const TAGGER_THRESHOLD_FILE: &str = "settings/tagger_threshold.txt";
|
||||
const JOYTAG_THRESHOLD_FILE: &str = "settings/joytag_threshold.txt";
|
||||
const TAGGER_BATCH_SIZE_FILE: &str = "settings/tagger_batch_size.txt";
|
||||
const TAGGER_MODEL_FILE: &str = "settings/tagger_model.txt";
|
||||
|
||||
@@ -26,20 +27,10 @@ pub const JOYTAG_MODEL_NAME: &str = "joytag";
|
||||
// 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_58, 0.275_777_11];
|
||||
// JoyTag's recommended detection threshold (used as the default; the user's
|
||||
// tagger_threshold setting still overrides it).
|
||||
const JOYTAG_STD: [f32; 3] = [0.268_629_54, 0.261_302_6, 0.275_777_1];
|
||||
// JoyTag's recommended detection threshold.
|
||||
const JOYTAG_DEFAULT_THRESHOLD: f32 = 0.4;
|
||||
|
||||
// Shared ONNX Runtime DLLs (live in the caption model's `onnxruntime/` dir and
|
||||
// are reused by the tagger). The per-model weight + label files are listed by
|
||||
// `TaggerModel::download_files`.
|
||||
const TAGGER_RUNTIME_DLLS: &[&str] = &[
|
||||
"onnxruntime/onnxruntime.dll",
|
||||
"onnxruntime/onnxruntime_providers_shared.dll",
|
||||
"onnxruntime/DirectML.dll",
|
||||
];
|
||||
|
||||
// Tags in these Danbooru categories are kept in the output.
|
||||
// Category 0 = general, category 4 = character.
|
||||
// Category 9 = rating (explicit/questionable/sensitive/general) – used for
|
||||
@@ -64,8 +55,8 @@ pub const TAGGER_INFER_CHUNK: usize = 4;
|
||||
/// 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
|
||||
/// knows to drop its cached `WdTagger` and reload with the new EP.
|
||||
/// Set to `true` by tagger setting changes so the tagging worker loop knows to
|
||||
/// drop its cached model session and reload with the current settings.
|
||||
pub static TAGGER_SESSION_DIRTY: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -112,6 +103,20 @@ impl TaggerModel {
|
||||
}
|
||||
}
|
||||
|
||||
fn threshold_file(self) -> &'static str {
|
||||
match self {
|
||||
Self::Wd => TAGGER_THRESHOLD_FILE,
|
||||
Self::JoyTag => JOYTAG_THRESHOLD_FILE,
|
||||
}
|
||||
}
|
||||
|
||||
fn default_threshold(self) -> f32 {
|
||||
match self {
|
||||
Self::Wd => DEFAULT_THRESHOLD,
|
||||
Self::JoyTag => JOYTAG_DEFAULT_THRESHOLD,
|
||||
}
|
||||
}
|
||||
|
||||
/// Hugging Face repo the model files are fetched from.
|
||||
fn repo_id(self) -> &'static str {
|
||||
match self {
|
||||
@@ -280,21 +285,33 @@ pub fn set_tagger_acceleration(
|
||||
Ok(acceleration)
|
||||
}
|
||||
|
||||
pub fn tagger_threshold(app_data_dir: &Path) -> f32 {
|
||||
let path = app_data_dir.join(TAGGER_THRESHOLD_FILE);
|
||||
fn tagger_threshold_for_model(app_data_dir: &Path, model: TaggerModel) -> f32 {
|
||||
let path = app_data_dir.join(model.threshold_file());
|
||||
let Ok(value) = std::fs::read_to_string(path) else {
|
||||
return DEFAULT_THRESHOLD;
|
||||
return model.default_threshold();
|
||||
};
|
||||
value
|
||||
.trim()
|
||||
.parse::<f32>()
|
||||
.unwrap_or(DEFAULT_THRESHOLD)
|
||||
.unwrap_or_else(|_| model.default_threshold())
|
||||
.clamp(0.01, 1.0)
|
||||
}
|
||||
|
||||
pub fn tagger_threshold(app_data_dir: &Path) -> f32 {
|
||||
tagger_threshold_for_model(app_data_dir, tagger_model(app_data_dir))
|
||||
}
|
||||
|
||||
pub fn set_tagger_threshold(app_data_dir: &Path, threshold: f32) -> Result<f32> {
|
||||
set_tagger_threshold_for_model(app_data_dir, tagger_model(app_data_dir), threshold)
|
||||
}
|
||||
|
||||
pub fn set_tagger_threshold_for_model(
|
||||
app_data_dir: &Path,
|
||||
model: TaggerModel,
|
||||
threshold: f32,
|
||||
) -> Result<f32> {
|
||||
let clamped = threshold.clamp(0.01, 1.0);
|
||||
let path = app_data_dir.join(TAGGER_THRESHOLD_FILE);
|
||||
let path = app_data_dir.join(model.threshold_file());
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
@@ -328,12 +345,11 @@ pub fn set_tagger_batch_size(app_data_dir: &Path, batch_size: usize) -> Result<u
|
||||
pub fn tagger_model_status(app_data_dir: &Path) -> TaggerModelStatus {
|
||||
let model = tagger_model(app_data_dir);
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
// The ONNX runtime DLLs live in the caption model dir; reuse them.
|
||||
let caption_model_dir = app_data_dir.join("models").join("florence-2-base-ft");
|
||||
let runtime_dir = crate::onnx_runtime::runtime_dir(app_data_dir);
|
||||
|
||||
let mut missing_files: Vec<String> = TAGGER_RUNTIME_DLLS
|
||||
let mut missing_files: Vec<String> = crate::onnx_runtime::RUNTIME_DLLS
|
||||
.iter()
|
||||
.filter(|file| !caption_model_dir.join(file).exists())
|
||||
.filter(|file| !runtime_dir.join(file).exists())
|
||||
.map(|file| (*file).to_string())
|
||||
.collect();
|
||||
missing_files.extend(
|
||||
@@ -361,15 +377,14 @@ pub fn prepare_tagger_model_with_progress(
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
std::fs::create_dir_all(&local_dir)?;
|
||||
|
||||
// The tagger shares the ONNX runtime DLLs with the captioner; download
|
||||
// them here so the tagger works even on a clean install where the caption
|
||||
// model has never been fetched (ensure_onnx_runtime only initializes).
|
||||
// Download the shared ONNX Runtime DLLs here so the tagger works even on
|
||||
// a clean install (ensure_onnx_runtime only initializes).
|
||||
let download_files = model.download_files();
|
||||
let caption_model_dir = crate::captioner::model_dir(app_data_dir);
|
||||
std::fs::create_dir_all(&caption_model_dir)?;
|
||||
let runtime_dir = crate::onnx_runtime::runtime_dir(app_data_dir);
|
||||
std::fs::create_dir_all(&runtime_dir)?;
|
||||
|
||||
// Unified step count across DLLs and tagger files so the bar is coherent.
|
||||
let dll_count = crate::captioner::missing_onnx_runtime_count(&caption_model_dir);
|
||||
let dll_count = crate::onnx_runtime::missing_onnx_runtime_count(&runtime_dir);
|
||||
let model_pending = download_files
|
||||
.iter()
|
||||
.filter(|file| !local_dir.join(file).exists())
|
||||
@@ -389,8 +404,8 @@ pub fn prepare_tagger_model_with_progress(
|
||||
// ── ONNX runtime DLLs (small, but non-trivial on a slow link) ──
|
||||
{
|
||||
let mut last_emit = Instant::now() - std::time::Duration::from_secs(1);
|
||||
crate::captioner::provision_onnx_runtime_with_progress(
|
||||
&caption_model_dir,
|
||||
crate::onnx_runtime::provision_onnx_runtime_with_progress(
|
||||
&runtime_dir,
|
||||
|label, downloaded, total| {
|
||||
if last_emit.elapsed() >= std::time::Duration::from_millis(200) {
|
||||
last_emit = Instant::now();
|
||||
@@ -408,7 +423,7 @@ pub fn prepare_tagger_model_with_progress(
|
||||
completed_files += dll_count;
|
||||
}
|
||||
log::info!("Tagger: ONNX runtime DLLs ready; initializing runtime");
|
||||
crate::captioner::ensure_onnx_runtime(&caption_model_dir)?;
|
||||
crate::onnx_runtime::ensure_onnx_runtime(&runtime_dir)?;
|
||||
log::info!("Tagger: runtime initialized; downloading model files");
|
||||
|
||||
// ── Tagger model files (model.onnx is ~446 MB) ──
|
||||
@@ -426,7 +441,7 @@ pub fn prepare_tagger_model_with_progress(
|
||||
let url = repo.url(file);
|
||||
let label = (*file).to_string();
|
||||
let mut last_emit = Instant::now() - std::time::Duration::from_secs(1);
|
||||
crate::captioner::download_file_resilient(&url, &destination, |downloaded, total| {
|
||||
crate::download::download_file_resilient(&url, &destination, |downloaded, total| {
|
||||
if last_emit.elapsed() >= std::time::Duration::from_millis(200) {
|
||||
last_emit = Instant::now();
|
||||
emit_progress(TaggerModelProgress {
|
||||
@@ -466,15 +481,15 @@ pub fn probe_tagger_runtime(app_data_dir: &Path) -> Result<TaggerRuntimeProbe> {
|
||||
let status = tagger_model_status(app_data_dir);
|
||||
if !status.ready {
|
||||
anyhow::bail!(
|
||||
"WD Tagger model is missing {} required file(s): {}",
|
||||
"{} is missing {} required file(s): {}",
|
||||
status.model_name,
|
||||
status.missing_files.len(),
|
||||
status.missing_files.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
let caption_model_dir = app_data_dir.join("models").join("florence-2-base-ft");
|
||||
crate::captioner::ensure_onnx_runtime(&caption_model_dir)?;
|
||||
crate::onnx_runtime::ensure_onnx_runtime(&crate::onnx_runtime::runtime_dir(app_data_dir))?;
|
||||
|
||||
let acceleration = tagger_acceleration(app_data_dir);
|
||||
let model_path = local_dir.join("model.onnx");
|
||||
@@ -636,13 +651,11 @@ impl WdTagger {
|
||||
|
||||
let local_dir = model_dir(app_data_dir);
|
||||
|
||||
// The ONNX runtime DLLs are shared with the captioner; use the
|
||||
// captioner's shared ORT init lock to avoid double-initialisation.
|
||||
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| {
|
||||
let runtime_dir = crate::onnx_runtime::runtime_dir(app_data_dir);
|
||||
crate::onnx_runtime::ensure_onnx_runtime(&runtime_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}"
|
||||
"ONNX Runtime not initialised — the shared runtime DLLs are missing; \
|
||||
re-run the tagger model download. Original error: {e}"
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -829,11 +842,11 @@ impl JoyTagger {
|
||||
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| {
|
||||
let runtime_dir = crate::onnx_runtime::runtime_dir(app_data_dir);
|
||||
crate::onnx_runtime::ensure_onnx_runtime(&runtime_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}"
|
||||
"ONNX Runtime not initialised — the shared runtime DLLs are missing; \
|
||||
re-run the tagger model download. Original error: {e}"
|
||||
)
|
||||
})?;
|
||||
|
||||
@@ -1056,17 +1069,10 @@ fn load_joytag_labels(path: &Path) -> Result<Vec<String>> {
|
||||
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).
|
||||
/// JoyTag detection threshold. Uses JoyTag's own setting so WD tuning does not
|
||||
/// leak into the general/photo-friendly model.
|
||||
fn joytag_threshold(app_data_dir: &Path) -> f32 {
|
||||
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,
|
||||
}
|
||||
tagger_threshold_for_model(app_data_dir, TaggerModel::JoyTag)
|
||||
}
|
||||
|
||||
fn sigmoid(x: f32) -> f32 {
|
||||
|
||||
@@ -383,6 +383,26 @@ fn fit_dimensions(width: u32, height: u32, max_size: u32) -> (u32, u32) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fit_dimensions_preserves_aspect_ratio_within_max() {
|
||||
// Already small enough: unchanged.
|
||||
assert_eq!(fit_dimensions(100, 50, THUMB_SIZE), (100, 50));
|
||||
// Landscape and portrait scale to the max on their long edge.
|
||||
assert_eq!(fit_dimensions(6400, 3200, THUMB_SIZE), (320, 160));
|
||||
assert_eq!(fit_dimensions(3200, 6400, THUMB_SIZE), (160, 320));
|
||||
// Extreme ratios never collapse to zero.
|
||||
assert_eq!(fit_dimensions(1, 100_000, 320), (1, 320));
|
||||
assert_eq!(fit_dimensions(100_000, 1, 320), (320, 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_jpeg_checks_extension_only() {
|
||||
assert!(is_jpeg(Path::new("photo.jpg")));
|
||||
assert!(is_jpeg(Path::new("photo.JPEG")));
|
||||
assert!(!is_jpeg(Path::new("photo.png")));
|
||||
assert!(!is_jpeg(Path::new("photo")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scale_numerator_picks_smallest_sufficient() {
|
||||
assert_eq!(scale_numerator(6000, THUMB_SIZE), 1);
|
||||
|
||||
@@ -263,6 +263,44 @@ pub fn get_embedding_revision(conn: &Connection) -> Result<String> {
|
||||
|
||||
/// Returns all stored image embeddings with their image IDs, optionally filtered to one folder.
|
||||
/// Each entry is `(image_id, normalized_f32_embedding)`.
|
||||
/// Returns `(count, hash)` over the stored embedding image IDs for the scope in a
|
||||
/// single ordered pass, without loading any embedding blobs. The hash covers the
|
||||
/// exact set of IDs, so it is membership-sensitive: adding, removing, or moving an
|
||||
/// image between folders changes it even when the count happens to stay the same.
|
||||
/// Used (together with the embedding revision, which catches an image being
|
||||
/// re-embedded in place) as the cheap visual-cluster cache key so a cache hit doesn't
|
||||
/// have to read and unpack hundreds of MB of embeddings just to validate freshness.
|
||||
pub fn embedding_ids_signature(conn: &Connection, folder_id: Option<i64>) -> Result<(i64, u64)> {
|
||||
use xxhash_rust::xxh3::Xxh3;
|
||||
let mut hasher = Xxh3::new();
|
||||
let mut count: i64 = 0;
|
||||
let mut hash_row = |id: i64| {
|
||||
hasher.update(&id.to_le_bytes());
|
||||
count += 1;
|
||||
};
|
||||
match folder_id {
|
||||
Some(fid) => {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT image_id FROM image_vec
|
||||
WHERE image_id IN (SELECT id FROM images WHERE folder_id = ?1)
|
||||
ORDER BY image_id",
|
||||
)?;
|
||||
let mut rows = stmt.query([fid])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
hash_row(row.get(0)?);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let mut stmt = conn.prepare("SELECT image_id FROM image_vec ORDER BY image_id")?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
hash_row(row.get(0)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((count, hasher.digest()))
|
||||
}
|
||||
|
||||
pub fn get_all_image_embeddings_with_ids(
|
||||
conn: &Connection,
|
||||
folder_id: Option<i64>,
|
||||
@@ -524,3 +562,81 @@ fn pack_f32(values: &[f32]) -> Vec<u8> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::db::test_support::{test_conn, test_image};
|
||||
|
||||
#[test]
|
||||
fn pack_unpack_roundtrip() {
|
||||
let values = vec![0.0f32, 1.5, -2.25, f32::MIN_POSITIVE, 1e10];
|
||||
assert_eq!(unpack_f32(&pack_f32(&values)), values);
|
||||
assert!(unpack_f32(&pack_f32(&[])).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_embedding_rejects_wrong_dimension() {
|
||||
let conn = test_conn();
|
||||
let error = upsert_embedding(&conn, 1, &[0.5f32; 3]).unwrap_err();
|
||||
assert!(error.to_string().contains("dimension"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_and_delete_embedding_roundtrip() {
|
||||
let conn = test_conn();
|
||||
let embedding = vec![0.25f32; CLIP_VECTOR_DIM];
|
||||
upsert_embedding(&conn, 42, &embedding).unwrap();
|
||||
assert!(has_image_vector(&conn, 42).unwrap());
|
||||
|
||||
// Upsert replaces rather than duplicates.
|
||||
upsert_embedding(&conn, 42, &embedding).unwrap();
|
||||
let rows: i64 = conn
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM image_vec WHERE image_id = 42",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
|
||||
delete_embedding(&conn, 42).unwrap();
|
||||
assert!(!has_image_vector(&conn, 42).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_similar_image_ids_ranks_by_cosine_distance() {
|
||||
let conn = test_conn();
|
||||
let folder_id = crate::db::insert_folder(&conn, "C:/a", "a").unwrap();
|
||||
let base_id =
|
||||
crate::db::upsert_image(&conn, &test_image(folder_id, "C:/a/base.jpg")).unwrap();
|
||||
let close_id =
|
||||
crate::db::upsert_image(&conn, &test_image(folder_id, "C:/a/close.jpg")).unwrap();
|
||||
let far_id =
|
||||
crate::db::upsert_image(&conn, &test_image(folder_id, "C:/a/far.jpg")).unwrap();
|
||||
|
||||
let mut base = vec![0.0f32; CLIP_VECTOR_DIM];
|
||||
base[0] = 1.0;
|
||||
let mut close = vec![0.0f32; CLIP_VECTOR_DIM];
|
||||
close[0] = 1.0;
|
||||
close[1] = 0.2;
|
||||
let mut far = vec![0.0f32; CLIP_VECTOR_DIM];
|
||||
far[1] = 1.0;
|
||||
upsert_embedding(&conn, base_id, &base).unwrap();
|
||||
upsert_embedding(&conn, close_id, &close).unwrap();
|
||||
upsert_embedding(&conn, far_id, &far).unwrap();
|
||||
|
||||
// Global KNN path: nearest first, query image excluded.
|
||||
let global = find_similar_image_ids(&conn, base_id, 2, None).unwrap();
|
||||
assert_eq!(global, vec![close_id, far_id]);
|
||||
|
||||
// Folder-scoped brute-force path returns the same ranking.
|
||||
let scoped = find_similar_image_ids(&conn, base_id, 2, Some(folder_id)).unwrap();
|
||||
assert_eq!(scoped, vec![close_id, far_id]);
|
||||
|
||||
// Images without an embedding yield no matches instead of an error.
|
||||
assert!(find_similar_image_ids(&conn, 9999, 5, None)
|
||||
.unwrap()
|
||||
.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
+70
-66
@@ -1,96 +1,100 @@
|
||||
import { useEffect } from "react";
|
||||
import { useGalleryStore } from "./store";
|
||||
import { Sidebar } from "./components/Sidebar";
|
||||
import { BackgroundTasks } from "./components/BackgroundTasks";
|
||||
import { Toolbar } from "./components/Toolbar";
|
||||
import { Gallery } from "./components/Gallery";
|
||||
import { Lightbox } from "./components/Lightbox";
|
||||
import { TagCloud } from "./components/TagCloud";
|
||||
import { DuplicateFinder } from "./components/DuplicateFinder";
|
||||
import { Timeline } from "./components/Timeline";
|
||||
import { TitleBar } from "./components/TitleBar";
|
||||
import { SettingsModal } from "./components/SettingsModal";
|
||||
import { FolderPickerModal } from "./components/FolderPickerModal";
|
||||
import { UpdateToast } from "./components/UpdateToast";
|
||||
import { WhatsNewToast } from "./components/WhatsNewToast";
|
||||
import { WhatsNewModal } from "./components/WhatsNewModal";
|
||||
import { OnboardingOverlay } from "./components/onboarding/OnboardingOverlay";
|
||||
import { DemoPanel } from "./components/DemoPanel";
|
||||
import { initializeNotifications } from "./notifications";
|
||||
import { useEffect } from 'react'
|
||||
import { useGalleryStore } from './store'
|
||||
import { Sidebar } from './components/Sidebar'
|
||||
import { BackgroundTasks } from './components/BackgroundTasks'
|
||||
import { Toolbar } from './components/Toolbar'
|
||||
import { Gallery } from './components/Gallery'
|
||||
import { Lightbox } from './components/Lightbox'
|
||||
import { ExploreView } from './components/ExploreView'
|
||||
import { DuplicateFinder } from './components/DuplicateFinder'
|
||||
import { Timeline } from './components/Timeline'
|
||||
import { TitleBar } from './components/TitleBar'
|
||||
import { SettingsModal } from './components/SettingsModal'
|
||||
import { FolderPickerModal } from './components/FolderPickerModal'
|
||||
import { UpdateToast } from './components/UpdateToast'
|
||||
import { WhatsNewToast } from './components/WhatsNewToast'
|
||||
import { WhatsNewModal } from './components/WhatsNewModal'
|
||||
import { OnboardingOverlay } from './components/onboarding/OnboardingOverlay'
|
||||
import { DemoPanel } from './dev/DemoPanel'
|
||||
import { initializeNotifications } from './notifications'
|
||||
|
||||
export default function App() {
|
||||
const loadFolders = useGalleryStore((state) => state.loadFolders);
|
||||
const loadBackgroundJobProgress = useGalleryStore((state) => state.loadBackgroundJobProgress);
|
||||
const loadImages = useGalleryStore((state) => state.loadImages);
|
||||
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus);
|
||||
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache);
|
||||
const loadAlbums = useGalleryStore((state) => state.loadAlbums);
|
||||
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds);
|
||||
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused);
|
||||
const loadWorkerPausesPersist = useGalleryStore((state) => state.loadWorkerPausesPersist);
|
||||
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress);
|
||||
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion);
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates);
|
||||
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus);
|
||||
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted);
|
||||
const initWhatsNew = useGalleryStore((state) => state.initWhatsNew);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
const loadFolders = useGalleryStore((state) => state.loadFolders)
|
||||
const loadBackgroundJobProgress = useGalleryStore((state) => state.loadBackgroundJobProgress)
|
||||
const loadImages = useGalleryStore((state) => state.loadImages)
|
||||
const loadCaptionModelStatus = useGalleryStore((state) => state.loadCaptionModelStatus)
|
||||
const loadTaggerModelStatus = useGalleryStore((state) => state.loadTaggerModelStatus)
|
||||
const loadTaggerModel = useGalleryStore((state) => state.loadTaggerModel)
|
||||
const loadDuplicateScanCache = useGalleryStore((state) => state.loadDuplicateScanCache)
|
||||
const loadAlbums = useGalleryStore((state) => state.loadAlbums)
|
||||
const loadMutedFolderIds = useGalleryStore((state) => state.loadMutedFolderIds)
|
||||
const loadNotificationsPaused = useGalleryStore((state) => state.loadNotificationsPaused)
|
||||
const loadWorkerPausesPersist = useGalleryStore((state) => state.loadWorkerPausesPersist)
|
||||
const subscribeToProgress = useGalleryStore((state) => state.subscribeToProgress)
|
||||
const loadAppVersion = useGalleryStore((state) => state.loadAppVersion)
|
||||
const checkForUpdates = useGalleryStore((state) => state.checkForUpdates)
|
||||
const loadFfmpegStatus = useGalleryStore((state) => state.loadFfmpegStatus)
|
||||
const loadOnboardingCompleted = useGalleryStore((state) => state.loadOnboardingCompleted)
|
||||
const initWhatsNew = useGalleryStore((state) => state.initWhatsNew)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
|
||||
useEffect(() => {
|
||||
void initializeNotifications();
|
||||
void loadMutedFolderIds();
|
||||
void loadNotificationsPaused();
|
||||
void loadWorkerPausesPersist();
|
||||
void loadFfmpegStatus();
|
||||
void loadOnboardingCompleted();
|
||||
void initializeNotifications()
|
||||
void loadMutedFolderIds()
|
||||
void loadNotificationsPaused()
|
||||
void loadWorkerPausesPersist()
|
||||
void loadFfmpegStatus()
|
||||
void loadOnboardingCompleted()
|
||||
// Load the app version first so the What's New toast/modal (which read
|
||||
// appVersion from the store) have it before the greeting can appear.
|
||||
void loadAppVersion().then(() => initWhatsNew());
|
||||
void loadAppVersion().then(() => initWhatsNew())
|
||||
// Quiet launch check — dev builds have no signed artifacts to update to.
|
||||
if (import.meta.env.PROD) {
|
||||
void checkForUpdates({ quiet: true });
|
||||
void checkForUpdates({ quiet: true })
|
||||
}
|
||||
loadFolders().then(async () => {
|
||||
void loadBackgroundJobProgress();
|
||||
void loadCaptionModelStatus();
|
||||
void loadDuplicateScanCache();
|
||||
await loadAlbums();
|
||||
await loadImages(true);
|
||||
if (import.meta.env.MODE === "ui") {
|
||||
const { applyMockScenario } = await import("./dev/applyMockScenario");
|
||||
applyMockScenario();
|
||||
void loadBackgroundJobProgress()
|
||||
void loadCaptionModelStatus()
|
||||
void loadTaggerModel()
|
||||
void loadTaggerModelStatus()
|
||||
void loadDuplicateScanCache()
|
||||
await loadAlbums()
|
||||
await loadImages(true)
|
||||
if (import.meta.env.MODE === 'ui') {
|
||||
const { applyMockScenario } = await import('./dev/applyMockScenario')
|
||||
applyMockScenario()
|
||||
}
|
||||
});
|
||||
let unlisten: (() => void) | undefined;
|
||||
})
|
||||
let unlisten: (() => void) | undefined
|
||||
subscribeToProgress().then((fn) => {
|
||||
unlisten = fn;
|
||||
});
|
||||
unlisten = fn
|
||||
})
|
||||
return () => {
|
||||
unlisten?.();
|
||||
};
|
||||
}, []);
|
||||
unlisten?.()
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-gray-950 text-white overflow-hidden select-none">
|
||||
<div className="flex h-screen flex-col overflow-hidden bg-gray-950 text-white select-none">
|
||||
{/* Custom title bar — sits at the very top */}
|
||||
<TitleBar />
|
||||
|
||||
{/* Main app content below the title bar */}
|
||||
<div className="flex flex-1 min-h-0">
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<Sidebar />
|
||||
<main className="flex-1 flex flex-col min-w-0">
|
||||
{activeView === "timeline" ? (
|
||||
<main className="flex min-w-0 flex-1 flex-col">
|
||||
{activeView === 'timeline' ? (
|
||||
<>
|
||||
<Toolbar />
|
||||
<BackgroundTasks />
|
||||
<Timeline />
|
||||
</>
|
||||
) : activeView === "explore" ? (
|
||||
) : activeView === 'explore' ? (
|
||||
<>
|
||||
<BackgroundTasks />
|
||||
<TagCloud />
|
||||
<ExploreView />
|
||||
</>
|
||||
) : activeView === "duplicates" ? (
|
||||
) : activeView === 'duplicates' ? (
|
||||
<>
|
||||
<BackgroundTasks />
|
||||
<DuplicateFinder />
|
||||
@@ -114,5 +118,5 @@ export default function App() {
|
||||
<OnboardingOverlay />
|
||||
{import.meta.env.DEV && <DemoPanel />}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getChangelogForVersion } from './changelog'
|
||||
|
||||
describe('getChangelogForVersion', () => {
|
||||
it('returns null for a null/undefined version', () => {
|
||||
expect(getChangelogForVersion(null)).toBeNull()
|
||||
expect(getChangelogForVersion(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('never surfaces the in-progress Unreleased section', () => {
|
||||
expect(getChangelogForVersion('Unreleased')).toBeNull()
|
||||
expect(getChangelogForVersion('unreleased')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for a version with no matching entry', () => {
|
||||
expect(getChangelogForVersion('99.9.9')).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves a plain released version', () => {
|
||||
const entry = getChangelogForVersion('0.1.1')
|
||||
expect(entry?.version).toBe('0.1.1')
|
||||
expect(entry?.date).toBe('2026-06-23')
|
||||
})
|
||||
|
||||
it('strips a leading "v" from the version string', () => {
|
||||
expect(getChangelogForVersion('v0.1.1')?.version).toBe('0.1.1')
|
||||
})
|
||||
|
||||
it('strips dev/UI-lab build suffixes so they resolve to the base version', () => {
|
||||
expect(getChangelogForVersion('0.1.1-dev')?.version).toBe('0.1.1')
|
||||
expect(getChangelogForVersion('0.1.1-ui')?.version).toBe('0.1.1')
|
||||
expect(getChangelogForVersion('0.1.1-beta.1')?.version).toBe('0.1.1')
|
||||
})
|
||||
})
|
||||
+113
-51
@@ -2,113 +2,175 @@
|
||||
// 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";
|
||||
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;
|
||||
lead: string | null
|
||||
/** The remaining descriptive text. May still contain inline `code` / **bold** markers. */
|
||||
body: string;
|
||||
body: string
|
||||
}
|
||||
|
||||
export interface ChangelogSection {
|
||||
/** "Added" | "Changed" | "Fixed" | "Removed" | "Deprecated" | "Security" */
|
||||
title: string;
|
||||
items: ChangelogItem[];
|
||||
title: string
|
||||
items: ChangelogItem[]
|
||||
}
|
||||
|
||||
export interface ChangelogEntry {
|
||||
version: string;
|
||||
date: string | null;
|
||||
sections: ChangelogSection[];
|
||||
version: string
|
||||
date: string | null
|
||||
sections: ChangelogSection[]
|
||||
}
|
||||
|
||||
// "## [0.1.1] — 2026-06-23" / "## [Unreleased]"
|
||||
const VERSION_HEADING = /^##\s+\[([^\]]+)\]\s*(?:[—–-]\s*(.+?)\s*)?$/;
|
||||
const VERSION_HEADING = /^##\s+\[([^\]]+)\]\s*(?:[—–-]\s*(.+?)\s*)?$/
|
||||
// "### Added"
|
||||
const SECTION_HEADING = /^###\s+(.+?)\s*$/;
|
||||
const SECTION_HEADING = /^###\s+(.+?)\s*$/
|
||||
// "- bullet text"
|
||||
const BULLET = /^[-*]\s+(.*)$/;
|
||||
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*)?(.*)$/;
|
||||
const LEAD = /^\*\*(.+?)\*\*\s*(?:[—–-]\s*)?(.*)$/
|
||||
|
||||
function toItem(text: string): ChangelogItem {
|
||||
const collapsed = text.replace(/\s+/g, " ").trim();
|
||||
const match = collapsed.match(LEAD);
|
||||
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: match[1].trim(), body: match[2].trim() }
|
||||
}
|
||||
return { lead: null, body: collapsed };
|
||||
return { lead: null, body: collapsed }
|
||||
}
|
||||
|
||||
function parseChangelog(raw: string): ChangelogEntry[] {
|
||||
const lines = raw.split(/\r?\n/);
|
||||
const entries: ChangelogEntry[] = [];
|
||||
const lines = raw.split(/\r?\n/)
|
||||
const entries: ChangelogEntry[] = []
|
||||
|
||||
let entry: ChangelogEntry | null = null;
|
||||
let section: ChangelogSection | null = null;
|
||||
let buffer: string[] = [];
|
||||
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(" ")));
|
||||
section.items.push(toItem(buffer.join(' ')))
|
||||
}
|
||||
buffer = [];
|
||||
};
|
||||
buffer = []
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const versionMatch = line.match(VERSION_HEADING);
|
||||
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;
|
||||
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;
|
||||
if (!entry) continue
|
||||
|
||||
const sectionMatch = line.match(SECTION_HEADING);
|
||||
const sectionMatch = line.match(SECTION_HEADING)
|
||||
if (sectionMatch) {
|
||||
flushItem();
|
||||
section = { title: sectionMatch[1].trim(), items: [] };
|
||||
entry.sections.push(section);
|
||||
continue;
|
||||
flushItem()
|
||||
section = { title: sectionMatch[1].trim(), items: [] }
|
||||
entry.sections.push(section)
|
||||
continue
|
||||
}
|
||||
|
||||
const bulletMatch = line.match(BULLET);
|
||||
const bulletMatch = line.match(BULLET)
|
||||
if (bulletMatch) {
|
||||
flushItem();
|
||||
buffer.push(bulletMatch[1]);
|
||||
continue;
|
||||
flushItem()
|
||||
buffer.push(bulletMatch[1])
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.trim() === "") {
|
||||
if (line.trim() === '') {
|
||||
// A blank line ends a (possibly wrapped) multi-line bullet.
|
||||
flushItem();
|
||||
continue;
|
||||
flushItem()
|
||||
continue
|
||||
}
|
||||
|
||||
// Indented continuation of the current wrapped bullet.
|
||||
if (buffer.length > 0) {
|
||||
buffer.push(line.trim());
|
||||
buffer.push(line.trim())
|
||||
}
|
||||
}
|
||||
|
||||
flushItem();
|
||||
return entries.map((e) => ({ ...e, sections: e.sections.filter((s) => s.items.length > 0) }));
|
||||
flushItem()
|
||||
return entries.map((e) => ({ ...e, sections: e.sections.filter((s) => s.items.length > 0) }))
|
||||
}
|
||||
|
||||
const ENTRIES = parseChangelog(changelogRaw);
|
||||
const ENTRIES = parseChangelog(changelogRaw)
|
||||
|
||||
// Synthetic small release for UI Lab (`?changelog=small`). The What's New modal
|
||||
// switches layout by release size, and every real entry in CHANGELOG.md is
|
||||
// large — so the compact single-column layout can't be exercised from real
|
||||
// data. This stays below the modal's rail threshold on purpose.
|
||||
const SMALL_PREVIEW_ENTRY: ChangelogEntry = {
|
||||
version: '0.0.0-preview',
|
||||
date: '2026-01-01',
|
||||
sections: [
|
||||
{
|
||||
title: 'Added',
|
||||
items: [
|
||||
{
|
||||
lead: 'Sample setting',
|
||||
body: 'a small toggle that exists purely so this preview has an Added section.',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Changed',
|
||||
items: [
|
||||
{
|
||||
lead: 'Snappier previews',
|
||||
body: 'the preview fixture now loads instantly, because it is made up.',
|
||||
},
|
||||
{ lead: null, body: 'A plain full-sentence bullet without a bold lead, for coverage.' },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Fixed',
|
||||
items: [
|
||||
{
|
||||
lead: 'Hotfix-sized fix',
|
||||
body: 'a believable one-liner about a bug that never shipped.',
|
||||
},
|
||||
{
|
||||
lead: 'Another small fix',
|
||||
body: 'keeps the total item count comfortably under the rail threshold.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
// UI Lab affordance (browser-only `ui` mode): `?changelog=` previews an entry
|
||||
// other than the running version's, mirroring the `?scenario=` pattern.
|
||||
// ?changelog=unreleased — the in-progress [Unreleased] notes (large release)
|
||||
// ?changelog=small — synthetic hotfix-sized entry (compact layout)
|
||||
// ?changelog=0.1.1 — any specific released version
|
||||
function previewOverride(): ChangelogEntry | null {
|
||||
if (import.meta.env.MODE !== 'ui') return null
|
||||
const preview = new URLSearchParams(window.location.search).get('changelog')
|
||||
if (!preview) return null
|
||||
if (preview === 'small') return SMALL_PREVIEW_ENTRY
|
||||
return ENTRIES.find((e) => e.version.toLowerCase() === preview.toLowerCase()) ?? null
|
||||
}
|
||||
|
||||
export function getChangelogForVersion(version: string | null | undefined): ChangelogEntry | null {
|
||||
if (!version) return null;
|
||||
const override = previewOverride()
|
||||
if (override) return override
|
||||
if (!version) return null
|
||||
// Strip leading "v" and any build suffix (e.g. "-ui", "-dev", "-beta.1") so
|
||||
// dev/UI-lab builds still resolve to the correct changelog entry.
|
||||
const normalized = version.replace(/^v/, "").replace(/-[a-z].*/i, "");
|
||||
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;
|
||||
if (normalized.toLowerCase() === 'unreleased') return null
|
||||
return ENTRIES.find((e) => e.version.replace(/^v/, '') === normalized) ?? null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
|
||||
/**
|
||||
* Album list plus a create-new-album form. The host decides what picking
|
||||
* means — the bulk bar adds the current selection; a newly created album is
|
||||
* picked immediately.
|
||||
*/
|
||||
export function AlbumPicker({ onPick }: { onPick: (albumId: number) => Promise<void> | void }) {
|
||||
const albums = useGalleryStore((state) => state.albums)
|
||||
const createAlbum = useGalleryStore((state) => state.createAlbum)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [newAlbumName, setNewAlbumName] = useState('')
|
||||
|
||||
const handleCreate = async () => {
|
||||
const name = newAlbumName.trim()
|
||||
if (!name || creating) return
|
||||
setCreating(true)
|
||||
try {
|
||||
const album = await createAlbum(name)
|
||||
setNewAlbumName('')
|
||||
await onPick(album.id)
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="max-h-48 overflow-y-auto">
|
||||
{albums.length === 0 ? (
|
||||
<p className="px-2 py-2 text-[11px] text-gray-600">No albums yet — create one below.</p>
|
||||
) : (
|
||||
albums.map((album) => (
|
||||
<button
|
||||
key={album.id}
|
||||
className="flex w-full items-center justify-between gap-2 rounded-md px-2 py-1.5 text-left text-xs text-gray-300 transition-colors hover:bg-white/5 hover:text-white"
|
||||
onClick={() => void onPick(album.id)}
|
||||
>
|
||||
<span className="truncate">{album.name}</span>
|
||||
<span className="shrink-0 text-[10px] text-gray-600">{album.image_count}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
<form
|
||||
className="mt-1 flex gap-1 border-t border-white/[0.06] pt-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void handleCreate()
|
||||
}}
|
||||
>
|
||||
<input
|
||||
className="min-w-0 flex-1 rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-white placeholder-gray-600 focus:border-white/20 focus:outline-none"
|
||||
placeholder="New album…"
|
||||
value={newAlbumName}
|
||||
onChange={(event) => setNewAlbumName(event.target.value)}
|
||||
disabled={creating}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="rounded-md border border-white/10 bg-white/5 px-2 py-1 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-50"
|
||||
disabled={creating || !newAlbumName.trim()}
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)
|
||||
}
|
||||
+114
-567
@@ -1,608 +1,155 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { revealItemInDir } from "@tauri-apps/plugin-opener";
|
||||
import { useGalleryStore, WorkerKey } from "../store";
|
||||
|
||||
const WORKER_FOR_STAGE: Record<string, WorkerKey> = {
|
||||
Thumbnails: "thumbnail",
|
||||
Metadata: "metadata",
|
||||
Embeddings: "embedding",
|
||||
Tags: "tagging",
|
||||
};
|
||||
|
||||
interface TaskStage {
|
||||
label: string;
|
||||
detail: string;
|
||||
progress: number | null; // 0–100, or null for indeterminate
|
||||
failed: boolean;
|
||||
}
|
||||
|
||||
interface Task {
|
||||
id: number;
|
||||
name: string;
|
||||
stages: TaskStage[];
|
||||
isActive: boolean;
|
||||
hasFailedEmbeddings: boolean;
|
||||
hasFailedTagging: boolean;
|
||||
hasFailedCaptions: boolean;
|
||||
pendingMediaWork: number;
|
||||
embeddingProcessed: number;
|
||||
embeddingTotal: number;
|
||||
currentFile: string | null;
|
||||
snapshot: string;
|
||||
}
|
||||
|
||||
interface FailedWorkerItem {
|
||||
image_id: number;
|
||||
filename: string;
|
||||
path: string;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
function FailedWorkerItemRow({ item }: { item: FailedWorkerItem }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-start gap-1.5">
|
||||
<svg className="mt-px h-2.5 w-2.5 shrink-0 text-amber-500 light-theme:text-amber-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5}
|
||||
d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||
</svg>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-[10px] font-medium text-amber-400/80 light-theme:text-amber-700">{item.filename}</p>
|
||||
{item.error && (
|
||||
<p className="truncate text-[9px] text-gray-600">{item.error}</p>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
className="shrink-0 text-gray-700 transition-colors hover:text-gray-300 light-theme:text-gray-600 light-theme:hover:text-gray-100"
|
||||
title="Reveal in Explorer"
|
||||
onClick={() => void revealItemInDir(item.path)}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { useGalleryStore, type WorkerKey } from '../store'
|
||||
import { BackgroundTaskSummary } from './backgroundTasks/BackgroundTaskSummary'
|
||||
import { ExpandedTaskPanel } from './backgroundTasks/ExpandedTaskPanel'
|
||||
import {
|
||||
buildDuplicateScanTask,
|
||||
buildFolderTasks,
|
||||
taskHasTerminalFailure,
|
||||
taskProgress,
|
||||
} from './backgroundTasks/taskModel'
|
||||
import type { BackgroundTask, FailedWorkerItem } from './backgroundTasks/types'
|
||||
|
||||
export function BackgroundTasks() {
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress);
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
|
||||
const retryFailedEmbeddings = useGalleryStore((state) => state.retryFailedEmbeddings);
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs);
|
||||
const showFailedTagging = useGalleryStore((state) => state.showFailedTagging);
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning);
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [dismissed, setDismissed] = useState<Record<number, string>>({});
|
||||
const [failedEmbeddingItems, setFailedEmbeddingItems] = useState<Record<number, FailedWorkerItem[]>>({});
|
||||
const [failedTaggingItems, setFailedTaggingItems] = useState<Record<number, FailedWorkerItem[]>>({});
|
||||
|
||||
const workerPaused = useGalleryStore((state) => state.workerPaused);
|
||||
const loadWorkerStates = useGalleryStore((state) => state.loadWorkerStates);
|
||||
const setWorkerPaused = useGalleryStore((state) => state.setWorkerPaused);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const indexingProgress = useGalleryStore((state) => state.indexingProgress)
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress)
|
||||
const retryFailedEmbeddings = useGalleryStore((state) => state.retryFailedEmbeddings)
|
||||
const queueTaggingJobs = useGalleryStore((state) => state.queueTaggingJobs)
|
||||
const showFailedTagging = useGalleryStore((state) => state.showFailedTagging)
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning)
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress)
|
||||
const workerPaused = useGalleryStore((state) => state.workerPaused)
|
||||
const loadWorkerStates = useGalleryStore((state) => state.loadWorkerStates)
|
||||
const setWorkerPaused = useGalleryStore((state) => state.setWorkerPaused)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [dismissed, setDismissed] = useState<Record<number, string>>({})
|
||||
const [failedEmbeddingItems, setFailedEmbeddingItems] = useState<
|
||||
Record<number, FailedWorkerItem[]>
|
||||
>({})
|
||||
const [failedTaggingItems, setFailedTaggingItems] = useState<Record<number, FailedWorkerItem[]>>(
|
||||
{}
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void loadWorkerStates();
|
||||
}, [folders, loadWorkerStates]);
|
||||
void loadWorkerStates()
|
||||
}, [folders, loadWorkerStates])
|
||||
|
||||
// Fetch failed filenames whenever the expanded panel opens or failure counts change.
|
||||
const failedEmbeddingCounts = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(mediaJobProgress).map(([id, p]) => [id, p?.embedding_failed ?? 0]),
|
||||
Object.entries(mediaJobProgress).map(([id, progress]) => [
|
||||
id,
|
||||
progress?.embedding_failed ?? 0,
|
||||
])
|
||||
),
|
||||
[mediaJobProgress],
|
||||
);
|
||||
[mediaJobProgress]
|
||||
)
|
||||
const failedTaggingCounts = useMemo(
|
||||
() =>
|
||||
Object.fromEntries(
|
||||
Object.entries(mediaJobProgress).map(([id, p]) => [id, p?.tagging_failed ?? 0]),
|
||||
Object.entries(mediaJobProgress).map(([id, progress]) => [
|
||||
id,
|
||||
progress?.tagging_failed ?? 0,
|
||||
])
|
||||
),
|
||||
[mediaJobProgress],
|
||||
);
|
||||
[mediaJobProgress]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!expanded) return;
|
||||
if (!expanded) return
|
||||
for (const [folderId, count] of Object.entries(failedEmbeddingCounts)) {
|
||||
if (count > 0) {
|
||||
invoke<FailedWorkerItem[]>("get_failed_embedding_images", {
|
||||
invoke<FailedWorkerItem[]>('get_failed_embedding_images', {
|
||||
folderId: Number(folderId),
|
||||
})
|
||||
.then((items) => setFailedEmbeddingItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined);
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
for (const [folderId, count] of Object.entries(failedTaggingCounts)) {
|
||||
if (count > 0) {
|
||||
invoke<FailedWorkerItem[]>("get_failed_tagging_images", {
|
||||
invoke<FailedWorkerItem[]>('get_failed_tagging_images', {
|
||||
folderId: Number(folderId),
|
||||
})
|
||||
.then((items) => setFailedTaggingItems((prev) => ({ ...prev, [folderId]: items })))
|
||||
.catch(() => undefined);
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
}, [expanded, failedEmbeddingCounts, failedTaggingCounts]);
|
||||
}, [expanded, failedEmbeddingCounts, failedTaggingCounts])
|
||||
|
||||
const isWorkerPaused = (folderId: number, worker: WorkerKey) => {
|
||||
return workerPaused[folderId]?.[worker] ?? false;
|
||||
};
|
||||
const folderTasks = useMemo(
|
||||
() =>
|
||||
buildFolderTasks({
|
||||
dismissed,
|
||||
folders,
|
||||
indexingProgress,
|
||||
mediaJobProgress,
|
||||
workerPaused,
|
||||
}),
|
||||
[dismissed, folders, indexingProgress, mediaJobProgress, workerPaused]
|
||||
)
|
||||
|
||||
const duplicateScanTask = useMemo(
|
||||
() => buildDuplicateScanTask(duplicateScanning, duplicateScanProgress),
|
||||
[duplicateScanning, duplicateScanProgress]
|
||||
)
|
||||
const allTasks = duplicateScanTask ? [duplicateScanTask, ...folderTasks] : folderTasks
|
||||
|
||||
if (allTasks.length === 0) return null
|
||||
|
||||
const isWorkerPaused = (folderId: number, worker: WorkerKey) =>
|
||||
workerPaused[folderId]?.[worker] ?? false
|
||||
|
||||
const toggleWorker = (folderId: number, worker: WorkerKey) => {
|
||||
setWorkerPaused(folderId, worker, !isWorkerPaused(folderId, worker));
|
||||
};
|
||||
setWorkerPaused(folderId, worker, !isWorkerPaused(folderId, worker))
|
||||
}
|
||||
|
||||
const dismissTask = (id: number, snapshot: string) => {
|
||||
if (id < 0) return; // system tasks (duplicate scan) cannot be dismissed
|
||||
setDismissed((prev) => ({ ...prev, [id]: snapshot }));
|
||||
setExpanded(false);
|
||||
};
|
||||
const dismissTask = (task: BackgroundTask) => {
|
||||
if (task.id < 0) return
|
||||
setDismissed((prev) => ({ ...prev, [task.id]: task.snapshot }))
|
||||
setExpanded(false)
|
||||
}
|
||||
|
||||
const tasks = useMemo<Task[]>(() => {
|
||||
return folders
|
||||
.map((folder): Task | null => {
|
||||
const index = indexingProgress[folder.id];
|
||||
const jobs = mediaJobProgress[folder.id];
|
||||
const retryTask = (task: BackgroundTask) => {
|
||||
if (task.hasFailedEmbeddings) void retryFailedEmbeddings(task.id)
|
||||
if (task.hasFailedTagging) void queueTaggingJobs(task.id)
|
||||
}
|
||||
|
||||
const thumbnailPending = jobs?.thumbnail_pending ?? 0;
|
||||
const metadataPending = jobs?.metadata_pending ?? 0;
|
||||
const embeddingPending = jobs?.embedding_pending ?? 0;
|
||||
const embeddingReady = jobs?.embedding_ready ?? 0;
|
||||
const embeddingFailed = jobs?.embedding_failed ?? 0;
|
||||
const taggingPending = jobs?.tagging_pending ?? 0;
|
||||
const taggingReady = jobs?.tagging_ready ?? 0;
|
||||
const taggingFailed = jobs?.tagging_failed ?? 0;
|
||||
const captionPending = jobs?.caption_pending ?? 0;
|
||||
const captionReady = jobs?.caption_ready ?? 0;
|
||||
const captionFailed = jobs?.caption_failed ?? 0;
|
||||
|
||||
// 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 embeddingProcessed = embeddingReady + embeddingFailed;
|
||||
const embeddingTotal = embeddingProcessed + embeddingPending;
|
||||
const taggingProcessed = taggingReady + taggingFailed;
|
||||
const taggingTotal = taggingProcessed + taggingPending;
|
||||
const captionProcessed = captionReady + captionFailed;
|
||||
const captionTotal = captionProcessed + captionPending;
|
||||
const hasFailedEmbeddings = embeddingFailed > 0;
|
||||
const hasFailedTagging = taggingFailed > 0;
|
||||
const hasFailedCaptions = captionFailed > 0;
|
||||
|
||||
if (!index && pendingMediaWork === 0 && !hasFailedEmbeddings && !hasFailedTagging && !hasFailedCaptions) return null;
|
||||
|
||||
const stages: TaskStage[] = [];
|
||||
|
||||
if (index && !index.done) {
|
||||
const pct = index.total > 0 ? (index.indexed / index.total) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Scanning",
|
||||
detail: `${index.indexed.toLocaleString()} / ${index.total.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (thumbnailPending > 0) {
|
||||
stages.push({
|
||||
label: "Thumbnails",
|
||||
detail: thumbnailPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (metadataPending > 0) {
|
||||
stages.push({
|
||||
label: "Metadata",
|
||||
detail: metadataPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (embeddingPending > 0) {
|
||||
const pct = embeddingTotal > 0 ? (embeddingProcessed / embeddingTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Embeddings",
|
||||
detail: `${embeddingProcessed.toLocaleString()} / ${embeddingTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (taggingPending > 0) {
|
||||
const pct = taggingTotal > 0 ? (taggingProcessed / taggingTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Tags",
|
||||
detail: `${taggingProcessed.toLocaleString()} / ${taggingTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (captionPending > 0) {
|
||||
const pct = captionTotal > 0 ? (captionProcessed / captionTotal) * 100 : 0;
|
||||
stages.push({
|
||||
label: "Captions",
|
||||
detail: `${captionProcessed.toLocaleString()} / ${captionTotal.toLocaleString()}`,
|
||||
progress: pct,
|
||||
failed: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedEmbeddings && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${embeddingFailed.toLocaleString()} embeddings`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedTagging && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${taggingFailed.toLocaleString()} tags`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (hasFailedCaptions && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: "Failed",
|
||||
detail: `${captionFailed.toLocaleString()} captions`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
});
|
||||
}
|
||||
|
||||
const snapshot = `${pendingMediaWork}:${embeddingFailed}:${taggingFailed}:${captionFailed}`;
|
||||
|
||||
return {
|
||||
id: folder.id,
|
||||
name: folder.name,
|
||||
stages,
|
||||
isActive,
|
||||
hasFailedEmbeddings,
|
||||
hasFailedTagging,
|
||||
hasFailedCaptions,
|
||||
pendingMediaWork,
|
||||
embeddingProcessed,
|
||||
embeddingTotal,
|
||||
currentFile: index && !index.done ? (index.current_file || null) : null,
|
||||
snapshot,
|
||||
};
|
||||
})
|
||||
.filter((t): t is Task => t !== null)
|
||||
.filter((t) => dismissed[t.id] !== t.snapshot)
|
||||
// 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
|
||||
const duplicateScanTask: Task | null = duplicateScanning ? {
|
||||
id: -1,
|
||||
name: "Duplicate Scan",
|
||||
stages: [{
|
||||
label: duplicateScanProgress?.phase === "checking"
|
||||
? "Checking"
|
||||
: duplicateScanProgress?.phase === "confirming"
|
||||
? "Confirming"
|
||||
: "Hashing",
|
||||
detail: duplicateScanProgress
|
||||
? `${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ""}`
|
||||
: "Starting…",
|
||||
progress: duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? (duplicateScanProgress.processed / duplicateScanProgress.total) * 100
|
||||
: null,
|
||||
failed: false,
|
||||
}],
|
||||
isActive: true,
|
||||
hasFailedEmbeddings: false,
|
||||
hasFailedTagging: false,
|
||||
hasFailedCaptions: false,
|
||||
pendingMediaWork: 1,
|
||||
embeddingProcessed: 0,
|
||||
embeddingTotal: 0,
|
||||
currentFile: null,
|
||||
snapshot: "",
|
||||
} : null;
|
||||
|
||||
const allTasks = duplicateScanTask ? [duplicateScanTask, ...tasks] : tasks;
|
||||
|
||||
if (allTasks.length === 0) return null;
|
||||
|
||||
const primary = allTasks[0];
|
||||
const extraCount = allTasks.length - 1;
|
||||
const hasFailed = tasks.some((t) => (t.hasFailedEmbeddings || t.hasFailedTagging || t.hasFailedCaptions) && t.pendingMediaWork === 0);
|
||||
|
||||
// Best progress bar value: use embedding progress if available (most informative),
|
||||
// otherwise tagging progress, otherwise fall back to scanning progress, otherwise indeterminate.
|
||||
const embeddingStage = primary.stages.find((s) => s.label === "Embeddings");
|
||||
const taggingStage = primary.stages.find((s) => s.label === "Tags");
|
||||
const scanningStage = primary.stages.find((s) => s.label === "Scanning");
|
||||
const duplicateStage = primary.id === -1 ? primary.stages[0] : null;
|
||||
const barProgress = embeddingStage?.progress ?? taggingStage?.progress ?? scanningStage?.progress ?? duplicateStage?.progress ?? null;
|
||||
const primary = allTasks[0]
|
||||
const hasFailed = folderTasks.some(taskHasTerminalFailure)
|
||||
const barProgress = taskProgress(primary)
|
||||
|
||||
return (
|
||||
<div className="shrink-0 border-b border-white/[0.06]">
|
||||
{/* Slim bar */}
|
||||
<div
|
||||
className={`group flex items-center gap-3 px-5 h-11 cursor-pointer select-none transition-colors ${
|
||||
expanded ? "bg-white/[0.03]" : "hover:bg-white/[0.02]"
|
||||
}`}
|
||||
onClick={() => setExpanded((v) => !v)}
|
||||
>
|
||||
{/* Pulse dot */}
|
||||
<div className="relative shrink-0">
|
||||
<div className={`h-1.5 w-1.5 rounded-full ${hasFailed ? "bg-amber-400" : "bg-blue-400"}`} />
|
||||
<div className={`absolute inset-0 h-1.5 w-1.5 rounded-full animate-ping opacity-60 ${hasFailed ? "bg-amber-400" : "bg-blue-400"}`} />
|
||||
</div>
|
||||
<BackgroundTaskSummary
|
||||
expanded={expanded}
|
||||
extraCount={allTasks.length - 1}
|
||||
hasFailed={hasFailed}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onDismiss={dismissTask}
|
||||
onLocate={showFailedTagging}
|
||||
onRetry={retryTask}
|
||||
onToggleExpanded={() => setExpanded((value) => !value)}
|
||||
onToggleWorker={toggleWorker}
|
||||
primary={primary}
|
||||
progress={barProgress}
|
||||
taskCount={allTasks.length}
|
||||
/>
|
||||
|
||||
{/* Folder name */}
|
||||
<span className="text-[13px] font-medium text-white/60 shrink-0">{primary.name}</span>
|
||||
|
||||
{/* Stage tags — all active stages visible simultaneously */}
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0 overflow-hidden">
|
||||
{primary.stages.map((stage) => {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label];
|
||||
const isPaused = workerKey ? isWorkerPaused(primary.id, workerKey) : false;
|
||||
return (
|
||||
<span
|
||||
key={stage.label}
|
||||
className={`flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] shrink-0 ${
|
||||
stage.failed
|
||||
? "bg-amber-500/10 text-amber-400 light-theme:border light-theme:border-amber-500/40 light-theme:bg-amber-100 light-theme:text-amber-700"
|
||||
: isPaused
|
||||
? "bg-white/4 text-gray-600"
|
||||
: "bg-white/5 text-gray-400"
|
||||
}`}
|
||||
>
|
||||
<span>{stage.label}</span>
|
||||
<span className={`tabular-nums ${stage.failed ? "text-amber-500 light-theme:text-amber-700" : isPaused ? "text-gray-700" : "text-gray-600"}`}>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey && (
|
||||
<button
|
||||
className="ml-0.5 opacity-0 group-hover:opacity-100 hover:text-white transition-opacity"
|
||||
title={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); toggleWorker(primary.id, workerKey); }}
|
||||
>
|
||||
{isPaused ? (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Progress bar — embedding or scanning progress, pulsing if indeterminate */}
|
||||
<div className="w-24 h-px bg-white/8 rounded-full overflow-hidden shrink-0">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
hasFailed
|
||||
? "bg-amber-400/60"
|
||||
: barProgress === null
|
||||
? "bg-blue-500/40 animate-pulse w-full"
|
||||
: "bg-blue-500"
|
||||
}`}
|
||||
style={barProgress !== null ? { width: `${barProgress}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Extra folders badge */}
|
||||
{extraCount > 0 && (
|
||||
<span className="rounded-full bg-white/8 px-2 py-0.5 text-[10px] text-gray-500 shrink-0">
|
||||
+{extraCount}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{primary.pendingMediaWork === 0 && (primary.hasFailedEmbeddings || primary.hasFailedTagging) && (
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{primary.hasFailedTagging ? (
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={(e) => { e.stopPropagation(); showFailedTagging(primary.id); }}
|
||||
>
|
||||
Locate
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (primary.hasFailedEmbeddings) void retryFailedEmbeddings(primary.id);
|
||||
if (primary.hasFailedTagging) void queueTaggingJobs(primary.id);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Expand chevron (only when multiple tasks) */}
|
||||
{allTasks.length > 1 && (
|
||||
<svg
|
||||
className={`h-3.5 w-3.5 text-gray-600 transition-transform duration-200 shrink-0 ${expanded ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
)}
|
||||
|
||||
{/* Dismiss — hidden for system tasks like duplicate scan */}
|
||||
{primary.id >= 0 && (
|
||||
<button
|
||||
className="p-1 rounded-md text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors shrink-0"
|
||||
title="Dismiss"
|
||||
onClick={(e) => { e.stopPropagation(); dismissTask(primary.id, primary.snapshot); }}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expanded panel — one row per folder */}
|
||||
{expanded && (
|
||||
<div className="border-t border-white/[0.06] bg-white/[0.02] px-5 py-3 space-y-3">
|
||||
{allTasks.map((task) => {
|
||||
const taskEmbeddingStage = task.stages.find((s) => s.label === "Embeddings");
|
||||
const taskTaggingStage = task.stages.find((s) => s.label === "Tags");
|
||||
const taskScanningStage = task.stages.find((s) => s.label === "Scanning");
|
||||
const taskDuplicateStage = task.id === -1 ? task.stages[0] : null;
|
||||
const taskBarProgress = taskEmbeddingStage?.progress ?? taskTaggingStage?.progress ?? taskScanningStage?.progress ?? taskDuplicateStage?.progress ?? null;
|
||||
const taskHasFailed = (task.hasFailedEmbeddings || task.hasFailedTagging || task.hasFailedCaptions) && task.pendingMediaWork === 0;
|
||||
|
||||
return (
|
||||
<div key={task.id}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-[12px] text-white/50 w-28 truncate shrink-0">{task.name}</span>
|
||||
|
||||
<div className="flex items-center gap-1.5 flex-1 min-w-0 overflow-hidden">
|
||||
{task.stages.map((stage) => {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label];
|
||||
const isPaused = workerKey ? isWorkerPaused(task.id, workerKey) : false;
|
||||
return (
|
||||
<span
|
||||
key={stage.label}
|
||||
className={`flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] shrink-0 ${
|
||||
stage.failed
|
||||
? "bg-amber-500/10 text-amber-400 light-theme:border light-theme:border-amber-500/40 light-theme:bg-amber-100 light-theme:text-amber-700"
|
||||
: isPaused
|
||||
? "bg-white/4 text-gray-600"
|
||||
: "bg-white/5 text-gray-500"
|
||||
}`}
|
||||
>
|
||||
{isPaused && (
|
||||
<svg className="h-2 w-2 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
<span>{stage.label}</span>
|
||||
<span className={`tabular-nums ${stage.failed ? "text-amber-500 light-theme:text-amber-700" : "text-gray-600"}`}>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey && (
|
||||
<button
|
||||
className="ml-0.5 text-gray-600 hover:text-white transition-colors"
|
||||
title={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`}
|
||||
onClick={() => toggleWorker(task.id, workerKey)}
|
||||
>
|
||||
{isPaused ? (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="w-20 h-px bg-white/8 rounded-full overflow-hidden shrink-0">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
taskHasFailed
|
||||
? "bg-amber-400/60"
|
||||
: taskBarProgress === null
|
||||
? "bg-blue-500/40 animate-pulse w-full"
|
||||
: "bg-blue-500"
|
||||
}`}
|
||||
style={taskBarProgress !== null ? { width: `${taskBarProgress}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{taskHasFailed && (
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{task.hasFailedTagging ? (
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={() => showFailedTagging(task.id)}
|
||||
>
|
||||
Locate
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20 light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200"
|
||||
onClick={() => {
|
||||
if (task.hasFailedEmbeddings) void retryFailedEmbeddings(task.id);
|
||||
if (task.hasFailedTagging) void queueTaggingJobs(task.id);
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{task.id >= 0 && (
|
||||
<button
|
||||
className="p-1 rounded-md text-gray-600 hover:text-gray-300 hover:bg-white/8 transition-colors shrink-0"
|
||||
title="Dismiss"
|
||||
onClick={() => dismissTask(task.id, task.snapshot)}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{task.currentFile && (
|
||||
<p className="text-[10px] text-gray-600 truncate mt-1 pl-[calc(7rem+0.75rem)]">
|
||||
{task.currentFile}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Failed worker file lists */}
|
||||
{taskHasFailed && failedEmbeddingItems[task.id] && failedEmbeddingItems[task.id].length > 0 && (
|
||||
<div className="mt-2 pl-[calc(7rem+0.75rem)] space-y-0.5">
|
||||
{failedEmbeddingItems[task.id].map((item) => (
|
||||
<FailedWorkerItemRow key={item.image_id} item={item} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{taskHasFailed && failedTaggingItems[task.id] && failedTaggingItems[task.id].length > 0 && (
|
||||
<div className="mt-2 pl-[calc(7rem+0.75rem)] space-y-0.5">
|
||||
{failedTaggingItems[task.id].map((item) => (
|
||||
<FailedWorkerItemRow key={item.image_id} item={item} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{expanded ? (
|
||||
<ExpandedTaskPanel
|
||||
failedEmbeddingItems={failedEmbeddingItems}
|
||||
failedTaggingItems={failedTaggingItems}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onDismiss={dismissTask}
|
||||
onLocate={showFailedTagging}
|
||||
onRetry={retryTask}
|
||||
onToggleWorker={toggleWorker}
|
||||
tasks={allTasks}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
+102
-217
@@ -1,88 +1,67 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { BulkTagPopover } from "./bulk/BulkTagPopover";
|
||||
|
||||
type Panel = "tag" | "rating" | "album" | "delete" | null;
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { BulkAlbumPopover } from './bulk/BulkAlbumPopover'
|
||||
import { BulkDeleteConfirm } from './bulk/BulkDeleteConfirm'
|
||||
import { BulkRatingPopover } from './bulk/BulkRatingPopover'
|
||||
import { BulkSelectionSummary } from './bulk/BulkSelectionSummary'
|
||||
import { BulkTagPopover } from './bulk/BulkTagPopover'
|
||||
import { type BulkPanel } from './bulk/types'
|
||||
import { useDismissable } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
|
||||
export function BulkActionBar() {
|
||||
const selectedCount = useGalleryStore((state) => state.gallerySelectedIds.size);
|
||||
const selectedIds = useGalleryStore((state) => state.gallerySelectedIds);
|
||||
const clearGallerySelection = useGalleryStore((state) => state.clearGallerySelection);
|
||||
const selectAllGallery = useGalleryStore((state) => state.selectAllGallery);
|
||||
const loadedCount = useGalleryStore((state) => state.loadedCount);
|
||||
const totalImages = useGalleryStore((state) => state.totalImages);
|
||||
const bulkSetFavorite = useGalleryStore((state) => state.bulkSetFavorite);
|
||||
const bulkSetRating = useGalleryStore((state) => state.bulkSetRating);
|
||||
const bulkDeleteSelected = useGalleryStore((state) => state.bulkDeleteSelected);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
const selectedAlbumId = useGalleryStore((state) => state.selectedAlbumId);
|
||||
const albums = useGalleryStore((state) => state.albums);
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum);
|
||||
const removeFromAlbum = useGalleryStore((state) => state.removeFromAlbum);
|
||||
const createAlbum = useGalleryStore((state) => state.createAlbum);
|
||||
const selectedCount = useGalleryStore((state) => state.gallerySelectedIds.size)
|
||||
const selectedIds = useGalleryStore((state) => state.gallerySelectedIds)
|
||||
const clearGallerySelection = useGalleryStore((state) => state.clearGallerySelection)
|
||||
const selectAllGallery = useGalleryStore((state) => state.selectAllGallery)
|
||||
const loadedCount = useGalleryStore((state) => state.loadedCount)
|
||||
const totalImages = useGalleryStore((state) => state.totalImages)
|
||||
const bulkSetFavorite = useGalleryStore((state) => state.bulkSetFavorite)
|
||||
const bulkSetRating = useGalleryStore((state) => state.bulkSetRating)
|
||||
const bulkDeleteSelected = useGalleryStore((state) => state.bulkDeleteSelected)
|
||||
const activeView = useGalleryStore((state) => state.activeView)
|
||||
const selectedAlbumId = useGalleryStore((state) => state.selectedAlbumId)
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum)
|
||||
const removeFromAlbum = useGalleryStore((state) => state.removeFromAlbum)
|
||||
|
||||
const [panel, setPanel] = useState<Panel>(null);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [creatingAlbum, setCreatingAlbum] = useState(false);
|
||||
const [newAlbumName, setNewAlbumName] = useState("");
|
||||
const barRef = useRef<HTMLDivElement>(null);
|
||||
const [panel, setPanel] = useState<BulkPanel>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const barRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Close any open popover when clicking outside the bar.
|
||||
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);
|
||||
}, []);
|
||||
// Close any open popover when clicking outside the bar or pressing Escape.
|
||||
useDismissable(barRef, () => setPanel(null), panel !== null)
|
||||
|
||||
// Reset transient UI whenever the selection empties.
|
||||
useEffect(() => {
|
||||
if (selectedCount === 0) {
|
||||
setPanel(null);
|
||||
setNewAlbumName("");
|
||||
}
|
||||
}, [selectedCount]);
|
||||
if (selectedCount === 0) setPanel(null)
|
||||
}, [selectedCount])
|
||||
|
||||
if (selectedCount === 0) return null;
|
||||
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 ids = Array.from(selectedIds)
|
||||
const inAlbumView = activeView === 'album' && selectedAlbumId !== null
|
||||
const togglePanel = (next: Exclude<BulkPanel, null>) =>
|
||||
setPanel((current) => (current === next ? null : next))
|
||||
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
setDeleting(true)
|
||||
try {
|
||||
await bulkDeleteSelected();
|
||||
await bulkDeleteSelected()
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setPanel(null);
|
||||
setDeleting(false)
|
||||
setPanel(null)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const handlePickAlbum = async (albumId: number) => {
|
||||
await addToAlbum(albumId, ids);
|
||||
setPanel(null);
|
||||
};
|
||||
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`;
|
||||
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
|
||||
@@ -90,121 +69,49 @@ export function BulkActionBar() {
|
||||
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>
|
||||
<BulkSelectionSummary
|
||||
loadedCount={loadedCount}
|
||||
selectedCount={selectedCount}
|
||||
totalImages={totalImages}
|
||||
onSelectAll={selectAllGallery}
|
||||
/>
|
||||
|
||||
<div className="h-5 w-px bg-white/10" />
|
||||
|
||||
<div className="relative">
|
||||
<button className={panel === "tag" ? btnActive : btnIdle} onClick={() => togglePanel("tag")}>
|
||||
<button
|
||||
className={panel === 'tag' ? btnActive : btnIdle}
|
||||
onClick={() => togglePanel('tag')}
|
||||
>
|
||||
Tag
|
||||
</button>
|
||||
{panel === "tag" ? <BulkTagPopover onClose={() => setPanel(null)} /> : null}
|
||||
{panel === 'tag' ? <BulkTagPopover onClose={() => setPanel(null)} /> : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<button className={panel === "rating" ? btnActive : btnIdle} onClick={() => togglePanel("rating")}>
|
||||
<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>
|
||||
{panel === 'rating' ? (
|
||||
<BulkRatingPopover onSetRating={bulkSetRating} onClose={() => setPanel(null)} />
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<button className={btnIdle} onClick={() => void bulkSetFavorite(true)} title="Mark as favorite">
|
||||
Favorite
|
||||
</button>
|
||||
|
||||
<Tooltip label="Mark as favorite" followCursor>
|
||||
<button className={btnIdle} onClick={() => void bulkSetFavorite(true)}>
|
||||
Favorite
|
||||
</button>
|
||||
</Tooltip>
|
||||
<div className="relative">
|
||||
<button className={panel === "album" ? btnActive : btnIdle} onClick={() => togglePanel("album")}>
|
||||
<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}
|
||||
{panel === 'album' ? <BulkAlbumPopover onPick={handlePickAlbum} /> : null}
|
||||
</div>
|
||||
|
||||
{inAlbumView ? (
|
||||
@@ -219,58 +126,36 @@ export function BulkActionBar() {
|
||||
<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"
|
||||
<Tooltip label="Delete files from disk" followCursor>
|
||||
<button
|
||||
className={
|
||||
panel === 'delete'
|
||||
? `${btn} bg-red-500/15 text-red-300`
|
||||
: `${btn} text-gray-300 hover:bg-red-500/10 hover:text-red-300`
|
||||
}
|
||||
onClick={() => togglePanel('delete')}
|
||||
disabled={deleting}
|
||||
>
|
||||
<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>
|
||||
{deleting ? 'Deleting…' : 'Delete'}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{panel === 'delete' ? (
|
||||
<BulkDeleteConfirm
|
||||
deleting={deleting}
|
||||
selectedCount={selectedCount}
|
||||
onCancel={() => setPanel(null)}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
) : 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>
|
||||
<Tooltip label="Clear selection" followCursor>
|
||||
<button
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={clearGallerySelection}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
+113
-92
@@ -1,75 +1,82 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
import { useRef, useState } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { useDismissable } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
type Rgb = [number, number, number];
|
||||
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] },
|
||||
];
|
||||
{ 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];
|
||||
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("")}`;
|
||||
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];
|
||||
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 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));
|
||||
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]);
|
||||
// Collapse the panel when clicking elsewhere or pressing Escape.
|
||||
useDismissable(ref, () => setOpen(false), open)
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative ml-1 flex shrink-0 items-center border-l border-white/6 pl-2">
|
||||
<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}>
|
||||
<Tooltip
|
||||
label={isActive ? 'Color filter active' : 'Filter by color'}
|
||||
delay={400}
|
||||
anchorToCursor
|
||||
>
|
||||
<button
|
||||
className={`relative flex items-center gap-1.5 rounded-lg px-2 py-1.5 transition-colors ${
|
||||
open || isActive ? "bg-white/10 text-white" : "text-gray-500 hover:bg-white/5 hover:text-gray-200"
|
||||
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" />
|
||||
<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" />
|
||||
@@ -92,65 +99,79 @@ export function ColorFilter() {
|
||||
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"
|
||||
transition={{ duration: 0.14, ease: 'easeOut' }}
|
||||
className="light-theme:border-gray-700/50 absolute top-full right-0 z-30 mt-2 w-max rounded-xl border border-white/10 bg-gray-950/98 p-2.5 shadow-2xl backdrop-blur"
|
||||
>
|
||||
<div className="grid grid-cols-7 gap-1.5">
|
||||
{SWATCHES.map((swatch) => {
|
||||
const active = rgbEquals(colorFilter, swatch.rgb);
|
||||
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={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>
|
||||
<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">
|
||||
<div className="light-theme:border-gray-700/40 mt-2 flex items-center justify-between gap-3 border-t border-white/6 pt-2">
|
||||
{colorBackfill && colorBackfill.total > 0 ? (
|
||||
<span
|
||||
className="text-[10px] text-gray-600"
|
||||
title="Sampling colors from existing thumbnails — color search fills in as this runs"
|
||||
<Tooltip
|
||||
label="Sampling colours from existing thumbnails — colour search fills in as this runs"
|
||||
anchorToCursor
|
||||
>
|
||||
sampling {colorBackfill.processed.toLocaleString()}/{colorBackfill.total.toLocaleString()}
|
||||
</span>
|
||||
) : <span />}
|
||||
<span className="text-[10px] text-gray-600">
|
||||
sampling {colorBackfill.processed.toLocaleString()}/
|
||||
{colorBackfill.total.toLocaleString()}
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<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>
|
||||
<Tooltip label="Clear colour filter" anchorToCursor>
|
||||
<button
|
||||
className="shrink-0 rounded px-1 text-[11px] text-gray-500 transition-colors hover:text-gray-200"
|
||||
onClick={() => setColorFilter(null)}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
@@ -158,5 +179,5 @@ export function ColorFilter() {
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,358 +1,125 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { DuplicateGroup, useGalleryStore } from "../store";
|
||||
import { FolderScopeDropdown } from "./FolderScopeDropdown";
|
||||
import { mediaSrc } from "../lib/mediaSrc";
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toFixed(1)} GB`;
|
||||
if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`;
|
||||
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
|
||||
return `${bytes} B`;
|
||||
}
|
||||
|
||||
function DuplicateGroupCard({ group }: { group: DuplicateGroup }) {
|
||||
const selectedIds = useGalleryStore((state) => state.duplicateSelectedIds);
|
||||
const toggleDuplicateSelected = useGalleryStore((state) => state.toggleDuplicateSelected);
|
||||
const selectAllDuplicates = useGalleryStore((state) => state.selectAllDuplicates);
|
||||
const groupSelectedCount = group.images.filter((img) => selectedIds.has(img.id)).length;
|
||||
const noneSelected = groupSelectedCount === 0;
|
||||
|
||||
// "Keep all but the first" — a common quick action
|
||||
const handleKeepFirst = () => {
|
||||
const toDelete = group.images.slice(1).map((img) => img.id);
|
||||
// Clear any selection for this group first, then add the ones to delete
|
||||
for (const img of group.images) {
|
||||
if (selectedIds.has(img.id)) toggleDuplicateSelected(img.id);
|
||||
}
|
||||
selectAllDuplicates(toDelete);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/[0.07] bg-white/[0.02] p-4">
|
||||
{/* Group header */}
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-400">
|
||||
{group.images.length} copies
|
||||
</span>
|
||||
<span className="text-[11px] text-white/30">{formatBytes(group.file_size)} each</span>
|
||||
<span className="text-[11px] text-white/20">
|
||||
{formatBytes(group.file_size * (group.images.length - 1))} wasted
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{noneSelected ? (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={handleKeepFirst}
|
||||
>
|
||||
Keep first
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={() => {
|
||||
for (const img of group.images) {
|
||||
if (selectedIds.has(img.id)) toggleDuplicateSelected(img.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image grid */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{group.images.map((image) => {
|
||||
const isSelected = selectedIds.has(image.id);
|
||||
const src = mediaSrc(image.thumbnail_path);
|
||||
return (
|
||||
<button
|
||||
key={image.id}
|
||||
className={`media-dark-surface group relative overflow-hidden rounded-xl border transition-all ${
|
||||
isSelected
|
||||
? "border-red-400/50 ring-1 ring-red-400/30"
|
||||
: "border-white/8 hover:border-white/20"
|
||||
}`}
|
||||
style={{ width: 140, height: 105 }}
|
||||
onClick={() => toggleDuplicateSelected(image.id)}
|
||||
title={image.path}
|
||||
>
|
||||
{src ? (
|
||||
<img src={src} alt="" className="h-full w-full object-cover" draggable={false} />
|
||||
) : (
|
||||
<div className="h-full w-full bg-white/[0.03]" />
|
||||
)}
|
||||
{/* Delete overlay */}
|
||||
{isSelected ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-red-950/60">
|
||||
<svg className="h-6 w-6 text-red-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</div>
|
||||
) : null}
|
||||
{/* Path tooltip on hover */}
|
||||
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/90 to-transparent px-2 pb-1.5 pt-4 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<p className="truncate text-[9px] text-white/60">{image.path.split(/[\\/]/).slice(-2).join("/")}</p>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatRelativeTime(unixSecs: number): string {
|
||||
const diff = Math.floor(Date.now() / 1000) - unixSecs;
|
||||
if (diff < 60) return "just now";
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;
|
||||
return `${Math.floor(diff / 86400)}d ago`;
|
||||
}
|
||||
import { useRef, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { useGalleryStore } from '../store'
|
||||
import {
|
||||
DuplicateScanEmptyState,
|
||||
DuplicateScanIntroState,
|
||||
DuplicateScanLoadingState,
|
||||
} from './duplicateFinder/DuplicateFinderEmptyStates'
|
||||
import { DuplicateFinderHeader } from './duplicateFinder/DuplicateFinderHeader'
|
||||
import { DuplicateGroupCard } from './duplicateFinder/DuplicateGroupCard'
|
||||
import { duplicateProgressLabel } from './duplicateFinder/format'
|
||||
|
||||
export function DuplicateFinder() {
|
||||
const duplicateGroups = useGalleryStore((state) => state.duplicateGroups);
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning);
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress);
|
||||
const duplicateScanError = useGalleryStore((state) => state.duplicateScanError);
|
||||
const duplicateScanWarning = useGalleryStore((state) => state.duplicateScanWarning);
|
||||
const duplicateSelectedIds = useGalleryStore((state) => state.duplicateSelectedIds);
|
||||
const duplicateLastScanned = useGalleryStore((state) => state.duplicateLastScanned);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const scanDuplicates = useGalleryStore((state) => state.scanDuplicates);
|
||||
const clearDuplicateSelection = useGalleryStore((state) => state.clearDuplicateSelection);
|
||||
const selectKeepFirstAllGroups = useGalleryStore((state) => state.selectKeepFirstAllGroups);
|
||||
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates);
|
||||
const duplicateGroups = useGalleryStore((state) => state.duplicateGroups)
|
||||
const duplicateScanning = useGalleryStore((state) => state.duplicateScanning)
|
||||
const duplicateScanProgress = useGalleryStore((state) => state.duplicateScanProgress)
|
||||
const duplicateScanError = useGalleryStore((state) => state.duplicateScanError)
|
||||
const duplicateScanWarning = useGalleryStore((state) => state.duplicateScanWarning)
|
||||
const duplicateSelectedIds = useGalleryStore((state) => state.duplicateSelectedIds)
|
||||
const duplicateLastScanned = useGalleryStore((state) => state.duplicateLastScanned)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const scanDuplicates = useGalleryStore((state) => state.scanDuplicates)
|
||||
const clearDuplicateSelection = useGalleryStore((state) => state.clearDuplicateSelection)
|
||||
const selectKeepFirstAllGroups = useGalleryStore((state) => state.selectKeepFirstAllGroups)
|
||||
const deleteSelectedDuplicates = useGalleryStore((state) => state.deleteSelectedDuplicates)
|
||||
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||
const [deleteResult, setDeleteResult] = useState<string | null>(null);
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false)
|
||||
const [deleteResult, setDeleteResult] = useState<string | null>(null)
|
||||
|
||||
// Virtualize the group list so a large result set (e.g. thousands of pairs)
|
||||
// only mounts the on-screen cards. Group cards vary in height (number of
|
||||
// copies wraps across rows), so heights are measured dynamically.
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const virtualizer = useVirtualizer({
|
||||
count: duplicateGroups.length,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 220,
|
||||
overscan: 4,
|
||||
});
|
||||
|
||||
const selectedCount = duplicateSelectedIds.size;
|
||||
const hasResults = duplicateGroups.length > 0;
|
||||
const hasScanned = hasResults || duplicateLastScanned !== null || (!duplicateScanning && duplicateScanProgress !== null);
|
||||
const totalWasted = duplicateGroups.reduce(
|
||||
(sum, g) => sum + g.file_size * (g.images.length - 1),
|
||||
0,
|
||||
);
|
||||
const totalDuplicateImages = duplicateGroups.reduce((sum, g) => sum + g.images.length - 1, 0);
|
||||
})
|
||||
|
||||
const selectedCount = duplicateSelectedIds.size
|
||||
const hasResults = duplicateGroups.length > 0
|
||||
const hasScanned =
|
||||
hasResults ||
|
||||
duplicateLastScanned !== null ||
|
||||
(!duplicateScanning && duplicateScanProgress !== null)
|
||||
const handleDelete = async () => {
|
||||
setDeleting(true);
|
||||
setConfirmingDelete(false);
|
||||
setDeleteResult(null);
|
||||
setDeleting(true)
|
||||
setConfirmingDelete(false)
|
||||
setDeleteResult(null)
|
||||
try {
|
||||
const deleted = await deleteSelectedDuplicates();
|
||||
setDeleteResult(`Deleted ${deleted} file${deleted === 1 ? "" : "s"}.`);
|
||||
const deleted = await deleteSelectedDuplicates()
|
||||
setDeleteResult(`Deleted ${deleted} file${deleted === 1 ? '' : 's'}.`)
|
||||
} catch (e) {
|
||||
setDeleteResult(String(e));
|
||||
setDeleteResult(String(e))
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
setDeleting(false)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const progressPercent =
|
||||
duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? Math.round((duplicateScanProgress.processed / duplicateScanProgress.total) * 100)
|
||||
: 0;
|
||||
const progressLabel = duplicateScanProgress
|
||||
? duplicateScanProgress.phase === "checking"
|
||||
? "Checking file sizes"
|
||||
: duplicateScanProgress.phase === "hashing"
|
||||
? "Hashing duplicate candidates"
|
||||
: "Confirming exact matches"
|
||||
: null;
|
||||
const progressLabel = duplicateProgressLabel(duplicateScanProgress)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-gray-950">
|
||||
{/* Header */}
|
||||
<div className="shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-[15px] font-semibold text-white">Duplicate Finder</h2>
|
||||
<p className="mt-0.5 text-[11px] text-white/30">
|
||||
{duplicateScanning
|
||||
? duplicateScanProgress
|
||||
? `${progressLabel}… ${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ""}`
|
||||
: "Starting scan…"
|
||||
: hasResults
|
||||
? `${duplicateGroups.length} group${duplicateGroups.length === 1 ? "" : "s"} · ${formatBytes(totalWasted)} reclaimable`
|
||||
: duplicateLastScanned !== null
|
||||
? "No duplicates found"
|
||||
: "Scan your library for identical files"}
|
||||
</p>
|
||||
{!duplicateScanning && duplicateLastScanned !== null && (
|
||||
<p className="mt-0.5 text-[10px] text-white/20">
|
||||
Last scanned {formatRelativeTime(duplicateLastScanned)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderScopeDropdown />
|
||||
{/* Batch select — only shown when there are groups and nothing is selected yet */}
|
||||
{hasResults && selectedCount === 0 && !deleting && (
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={selectKeepFirstAllGroups}
|
||||
title={`Mark ${totalDuplicateImages} duplicate${totalDuplicateImages === 1 ? "" : "s"} for deletion across all groups (keeps first in each)`}
|
||||
>
|
||||
Select all duplicates
|
||||
</button>
|
||||
)}
|
||||
{selectedCount > 0 ? (
|
||||
<>
|
||||
<span className="text-[11px] text-white/40">{selectedCount} marked for deletion</span>
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white disabled:opacity-40 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={clearDuplicateSelection}
|
||||
disabled={deleting}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
<div className="relative">
|
||||
<button
|
||||
className="rounded-lg border border-red-400/25 bg-red-500/10 px-3 py-1.5 text-xs text-red-300 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={() => setConfirmingDelete((v) => !v)}
|
||||
disabled={deleting}
|
||||
>
|
||||
{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}
|
||||
<button
|
||||
className="rounded-lg border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-40 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => { setDeleteResult(null); void scanDuplicates(selectedFolderId); }}
|
||||
disabled={duplicateScanning}
|
||||
>
|
||||
{duplicateScanning ? "Scanning…" : hasScanned ? "Rescan" : "Scan for duplicates"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<DuplicateFinderHeader
|
||||
confirmingDelete={confirmingDelete}
|
||||
deleteResult={deleteResult}
|
||||
deleting={deleting}
|
||||
duplicateGroups={duplicateGroups}
|
||||
duplicateLastScanned={duplicateLastScanned}
|
||||
duplicateScanError={duplicateScanError}
|
||||
duplicateScanning={duplicateScanning}
|
||||
duplicateScanProgress={duplicateScanProgress}
|
||||
duplicateScanWarning={duplicateScanWarning}
|
||||
hasResults={hasResults}
|
||||
hasScanned={hasScanned}
|
||||
onClearSelection={clearDuplicateSelection}
|
||||
onConfirmDelete={() => setConfirmingDelete(false)}
|
||||
onDelete={handleDelete}
|
||||
onScan={() => {
|
||||
setDeleteResult(null)
|
||||
void scanDuplicates(selectedFolderId)
|
||||
}}
|
||||
onSelectKeepFirstAll={selectKeepFirstAllGroups}
|
||||
selectedCount={selectedCount}
|
||||
setConfirmingDelete={setConfirmingDelete}
|
||||
/>
|
||||
|
||||
{/* Progress bar */}
|
||||
{duplicateScanning && duplicateScanProgress ? (
|
||||
<div className="mt-3 h-px overflow-hidden rounded-full bg-white/[0.07]">
|
||||
<div
|
||||
className="h-full rounded-full bg-blue-500/60 transition-[width] duration-200"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{duplicateScanError ? (
|
||||
<p className="mt-2 text-[11px] text-red-400/80">{duplicateScanError}</p>
|
||||
) : null}
|
||||
{duplicateScanWarning ? (
|
||||
<p className="mt-2 text-[11px] text-amber-300/70">{duplicateScanWarning}</p>
|
||||
) : null}
|
||||
{deleteResult ? (
|
||||
<p className="mt-2 text-[11px] text-white/40">{deleteResult}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
{duplicateScanning && !hasResults ? (
|
||||
<div className="flex flex-1 items-center justify-center gap-3 text-white/25">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/15 border-t-white/50" />
|
||||
<span className="text-sm">{progressLabel ? `${progressLabel}…` : "Preparing scan…"}</span>
|
||||
</div>
|
||||
<DuplicateScanLoadingState progressLabel={progressLabel} />
|
||||
) : !hasScanned ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<div className="max-w-sm text-center">
|
||||
<svg className="mx-auto mb-4 h-10 w-10 text-white/10" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1}
|
||||
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p className="text-sm text-white/30">
|
||||
Finds files with identical content regardless of filename or location.
|
||||
Click <strong className="text-white/50">Scan for duplicates</strong> to begin.
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-white/20">
|
||||
Large libraries may take a minute — files are hashed from disk.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DuplicateScanIntroState />
|
||||
) : duplicateGroups.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-white/25">No duplicate files found.</p>
|
||||
</div>
|
||||
<DuplicateScanEmptyState />
|
||||
) : (
|
||||
<div ref={scrollRef} className="overflow-y-auto px-6 py-5">
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const group = duplicateGroups[virtualItem.index];
|
||||
if (!group) return null;
|
||||
const group = duplicateGroups[virtualItem.index]
|
||||
if (!group) return null
|
||||
return (
|
||||
<div
|
||||
key={group.file_hash}
|
||||
data-index={virtualItem.index}
|
||||
ref={virtualizer.measureElement}
|
||||
style={{
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
width: '100%',
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
paddingBottom: 16,
|
||||
}}
|
||||
>
|
||||
<DuplicateGroupCard group={group} />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { FolderScopeDropdown } from './FolderScopeDropdown'
|
||||
import { ClusterCloud } from './explore/ClusterCloud'
|
||||
import { ExploreLoadingPanel } from './explore/ExploreLoadingPanel'
|
||||
import { TagAtlas, TAG_ATLAS_MAX_VISIBLE } from './explore/TagAtlas'
|
||||
import { TagManageList } from './explore/TagManageList'
|
||||
|
||||
export function ExploreView() {
|
||||
const exploreMode = useGalleryStore((state) => state.exploreMode)
|
||||
const setExploreMode = useGalleryStore((state) => state.setExploreMode)
|
||||
const visualClusterEntries = useGalleryStore((state) => state.visualClusterEntries)
|
||||
const visualClusterLoading = useGalleryStore((state) => state.visualClusterLoading)
|
||||
const loadVisualClusters = useGalleryStore((state) => state.loadVisualClusters)
|
||||
const exploreTagEntries = useGalleryStore((state) => state.exploreTagEntries)
|
||||
const exploreTagLoading = useGalleryStore((state) => state.exploreTagLoading)
|
||||
const loadExploreTags = useGalleryStore((state) => state.loadExploreTags)
|
||||
const loadRelatedTags = useGalleryStore((state) => state.loadRelatedTags)
|
||||
const showVisualCluster = useGalleryStore((state) => state.showVisualCluster)
|
||||
const searchForTag = useGalleryStore((state) => state.searchForTag)
|
||||
const renameTag = useGalleryStore((state) => state.renameTag)
|
||||
const deleteTag = useGalleryStore((state) => state.deleteTag)
|
||||
const resetAiTags = useGalleryStore((state) => state.resetAiTags)
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
// Manage mode lives in the store so it can be opened from elsewhere (Settings).
|
||||
const manageTags = useGalleryStore((state) => state.tagManagerOpen)
|
||||
const setManageTags = useGalleryStore((state) => state.setTagManagerOpen)
|
||||
const handleDeleteTag = async (tag: string) => {
|
||||
await deleteTag(tag)
|
||||
}
|
||||
const tagManagerScopeLabel =
|
||||
selectedFolderId === null
|
||||
? 'all media'
|
||||
: (folders.find((folder) => folder.id === selectedFolderId)?.name ?? 'the current folder')
|
||||
const handleResetAiTags = async () => {
|
||||
const count = await resetAiTags(selectedFolderId)
|
||||
await loadExploreTags({ force: true })
|
||||
return count
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (exploreMode === 'visual') void loadVisualClusters()
|
||||
else void loadExploreTags()
|
||||
}, [exploreMode, selectedFolderId, loadVisualClusters, loadExploreTags])
|
||||
|
||||
const loading = exploreMode === 'visual' ? visualClusterLoading : exploreTagLoading
|
||||
const hasEntries =
|
||||
exploreMode === 'visual' ? visualClusterEntries.length > 0 : exploreTagEntries.length > 0
|
||||
const entryCount =
|
||||
exploreMode === 'visual' ? visualClusterEntries.length : exploreTagEntries.length
|
||||
const visibleTagCount = Math.min(exploreTagEntries.length, TAG_ATLAS_MAX_VISIBLE)
|
||||
|
||||
return (
|
||||
<div className="explore-view flex min-h-0 flex-1 flex-col overflow-hidden bg-[radial-gradient(ellipse_at_top,rgba(59,130,246,0.08),transparent_50%),radial-gradient(ellipse_at_80%_75%,rgba(168,85,247,0.07),transparent_40%),#07080f]">
|
||||
{/* Header — `relative z-10` keeps the folder-scope dropdown above the
|
||||
cluster canvas, whose cards use a high z-index of their own. */}
|
||||
<div className="explore-header relative z-10 shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="min-w-0">
|
||||
<h2 className="explore-title text-[15px] font-semibold text-white">Explore</h2>
|
||||
<p className="explore-subtitle mt-0.5 truncate text-[11px] text-white/30">
|
||||
{loading
|
||||
? exploreMode === 'visual'
|
||||
? 'Computing visual clusters…'
|
||||
: 'Loading tags…'
|
||||
: hasEntries
|
||||
? exploreMode === 'visual'
|
||||
? `${entryCount} cluster${entryCount !== 1 ? 's' : ''} — click any to open`
|
||||
: manageTags
|
||||
? `${entryCount} tag${entryCount !== 1 ? 's' : ''} available to manage`
|
||||
: visibleTagCount < entryCount
|
||||
? `${visibleTagCount} of ${entryCount} tags shown — click any to search`
|
||||
: `${entryCount} tag${entryCount !== 1 ? 's' : ''} — click any to search`
|
||||
: exploreMode === 'visual'
|
||||
? 'No clusters — images need embeddings first'
|
||||
: 'No tags — run the AI tagger or add tags manually'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{exploreMode === 'tags' && hasEntries ? (
|
||||
<button
|
||||
className={`rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
manageTags
|
||||
? 'border-white/15 bg-white/10 text-white'
|
||||
: 'border-white/8 bg-white/[0.03] text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setManageTags(!manageTags)}
|
||||
>
|
||||
{manageTags ? 'Done' : 'Manage'}
|
||||
</button>
|
||||
) : null}
|
||||
<FolderScopeDropdown />
|
||||
<div className="explore-mode-toggle flex rounded-lg border border-white/8 bg-white/[0.03] p-0.5">
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === 'visual'
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setExploreMode('visual')}
|
||||
>
|
||||
Clusters
|
||||
</button>
|
||||
<button
|
||||
className={`explore-mode-button rounded-md px-3 py-1.5 text-xs transition-colors ${
|
||||
exploreMode === 'tags'
|
||||
? 'bg-white/10 text-white'
|
||||
: 'text-gray-500 hover:text-gray-300'
|
||||
}`}
|
||||
onClick={() => setExploreMode('tags')}
|
||||
>
|
||||
Tag Cloud
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading && !hasEntries ? (
|
||||
<ExploreLoadingPanel mode={exploreMode} />
|
||||
) : !hasEntries ? (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<p className="explore-empty max-w-xs text-center text-sm leading-relaxed text-white/25">
|
||||
{exploreMode === 'visual'
|
||||
? 'No visual clusters yet. Images need embeddings before they can be grouped. Check indexing progress in the sidebar.'
|
||||
: 'No tags yet. Run the AI tagger from Settings, or add tags manually in the image preview.'}
|
||||
</p>
|
||||
</div>
|
||||
) : exploreMode === 'visual' ? (
|
||||
<div className="relative flex min-h-0 flex-1 flex-col">
|
||||
<ClusterCloud entries={visualClusterEntries} onOpen={showVisualCluster} />
|
||||
</div>
|
||||
) : manageTags ? (
|
||||
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<TagManageList
|
||||
entries={exploreTagEntries}
|
||||
onSearch={searchForTag}
|
||||
onRename={renameTag}
|
||||
onDelete={handleDeleteTag}
|
||||
onResetAiTags={handleResetAiTags}
|
||||
scopeLabel={tagManagerScopeLabel}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<TagAtlas
|
||||
entries={exploreTagEntries}
|
||||
onSearch={searchForTag}
|
||||
loadRelatedTags={loadRelatedTags}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,342 +1,50 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { DirEntry, DirListing, FolderAddResult, useGalleryStore } from "../store";
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
return path.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
||||
}
|
||||
|
||||
function folderName(path: string): string {
|
||||
const trimmed = path.replace(/[\\/]+$/, "");
|
||||
const parts = trimmed.split(/[\\/]+/).filter(Boolean);
|
||||
return parts.length > 0 ? parts[parts.length - 1] : path;
|
||||
}
|
||||
|
||||
function buildBreadcrumbs(path: string | null): { label: string; path: string | null }[] {
|
||||
if (!path) return [{ label: "This PC / Home", path: null }];
|
||||
|
||||
const separator = path.includes("\\") ? "\\" : "/";
|
||||
const normalized = path.replace(/[\\/]+$/, "");
|
||||
const windowsDrive = normalized.match(/^[A-Za-z]:/);
|
||||
|
||||
if (windowsDrive) {
|
||||
const drive = windowsDrive[0] + "\\";
|
||||
const rest = normalized.slice(2).split(/[\\/]+/).filter(Boolean);
|
||||
let current = drive;
|
||||
return [
|
||||
{ label: "This PC", path: null },
|
||||
{ label: drive, path: drive },
|
||||
...rest.map((part) => {
|
||||
current = current.endsWith("\\") ? `${current}${part}` : `${current}\\${part}`;
|
||||
return { label: part, path: current };
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
const parts = normalized.split(/[\\/]+/).filter(Boolean);
|
||||
let current = separator === "/" ? "" : "";
|
||||
return [
|
||||
{ label: "/", path: null },
|
||||
...parts.map((part) => {
|
||||
current = `${current}/${part}`;
|
||||
return { label: part, path: current };
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
function StatusLine({ results }: { results: FolderAddResult[] | null }) {
|
||||
if (!results) return null;
|
||||
const added = results.filter((result) => result.status === "added").length;
|
||||
const skipped = results.filter((result) => result.status === "skipped").length;
|
||||
const failed = results.filter((result) => result.status === "error").length;
|
||||
return (
|
||||
<p className="text-xs text-gray-500 light-theme:text-gray-600">
|
||||
Added {added}, skipped {skipped}, failed {failed}.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
function FolderRow({
|
||||
entry,
|
||||
selected,
|
||||
alreadyAdded,
|
||||
onToggle,
|
||||
onNavigate,
|
||||
}: {
|
||||
entry: DirEntry;
|
||||
selected: boolean;
|
||||
alreadyAdded: boolean;
|
||||
onToggle: () => void;
|
||||
onNavigate: () => void;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`group flex h-11 items-center gap-3 rounded-md border px-3 transition-colors ${
|
||||
alreadyAdded
|
||||
? "border-transparent bg-white/[0.025] text-gray-600 light-theme:bg-gray-900 light-theme:text-gray-500"
|
||||
: selected
|
||||
? "border-white/15 bg-white/[0.085] text-white shadow-[inset_0_0_0_1px_rgb(255_255_255_/_0.035)] light-theme:border-gray-700/45 light-theme:bg-gray-800/55 light-theme:text-white"
|
||||
: "border-transparent text-gray-300 hover:bg-white/[0.055] hover:text-white light-theme:text-gray-500 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={`grid h-5 w-5 shrink-0 place-items-center rounded border transition-colors ${
|
||||
selected
|
||||
? "border-white/30 bg-gray-200 text-gray-950 light-theme:border-gray-700/55 light-theme:bg-gray-700 light-theme:text-white"
|
||||
: "border-white/15 bg-white/[0.035] text-transparent hover:border-white/30 light-theme:border-gray-700/50 light-theme:bg-gray-950"
|
||||
} ${alreadyAdded ? "cursor-not-allowed opacity-40" : ""}`}
|
||||
onClick={onToggle}
|
||||
disabled={alreadyAdded}
|
||||
aria-label={selected ? `Remove ${entry.name} from folders to add` : `Choose ${entry.name}`}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="flex min-w-0 flex-1 items-center gap-2 text-left"
|
||||
onClick={onNavigate}
|
||||
title={entry.path}
|
||||
>
|
||||
<svg className="h-4 w-4 shrink-0 text-amber-300/90" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M3 6.5A2.5 2.5 0 015.5 4h4.1l2 2H18.5A2.5 2.5 0 0121 8.5v9A2.5 2.5 0 0118.5 20h-13A2.5 2.5 0 013 17.5v-11z" />
|
||||
</svg>
|
||||
<span className="truncate text-sm">{entry.name}</span>
|
||||
</button>
|
||||
|
||||
{alreadyAdded ? (
|
||||
<span className="rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-500 light-theme:border-gray-700/40 light-theme:bg-gray-950">
|
||||
Added
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
onClick={onNavigate}
|
||||
title={entry.has_children ? "Open folder" : "No subfolders"}
|
||||
>
|
||||
<svg className={`h-4 w-4 ${entry.has_children ? "" : "opacity-45"}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StagedFoldersPanel({
|
||||
stagedPaths,
|
||||
onRemove,
|
||||
onClear,
|
||||
}: {
|
||||
stagedPaths: string[];
|
||||
onRemove: (path: string) => void;
|
||||
onClear: () => void;
|
||||
}) {
|
||||
return (
|
||||
<aside className="flex min-h-0 w-full flex-col border-t border-white/[0.07] bg-white/[0.018] light-theme:border-gray-300/70 light-theme:bg-gray-900/35 lg:w-80 lg:border-l lg:border-t-0">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-white/[0.07] px-5 py-4 light-theme:border-gray-300/70">
|
||||
<p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-gray-500">
|
||||
Folders to add ({stagedPaths.length})
|
||||
</p>
|
||||
{stagedPaths.length > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-3">
|
||||
{stagedPaths.length === 0 ? (
|
||||
<div className="flex h-full min-h-40 flex-col items-center justify-center rounded-md border border-dashed border-white/[0.08] px-5 text-center light-theme:border-gray-700/35">
|
||||
<p className="text-sm text-gray-500">No folders selected.</p>
|
||||
<p className="mt-1 max-w-52 text-xs leading-relaxed text-gray-600 light-theme:text-gray-500">
|
||||
Choose folders on the left and they will collect here.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{stagedPaths.map((path) => (
|
||||
<div
|
||||
key={path}
|
||||
className="group flex min-h-12 items-center gap-2 rounded-md border border-white/[0.07] bg-white/[0.045] px-3 py-2 text-gray-200 transition-colors hover:border-white/15 hover:bg-white/[0.07] light-theme:border-gray-700/40 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
title={path}
|
||||
>
|
||||
<svg className="h-4 w-4 shrink-0 text-amber-300/90" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M3 6.5A2.5 2.5 0 015.5 4h4.1l2 2H18.5A2.5 2.5 0 0121 8.5v9A2.5 2.5 0 0118.5 20h-13A2.5 2.5 0 013 17.5v-11z" />
|
||||
</svg>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{folderName(path)}</p>
|
||||
<p className="mt-0.5 truncate text-[11px] text-gray-600 light-theme:text-gray-500">{path}</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1 text-gray-500 opacity-80 transition-colors hover:bg-white/[0.08] hover:text-white group-hover:opacity-100 light-theme:hover:bg-gray-700"
|
||||
onClick={() => onRemove(path)}
|
||||
aria-label={`Remove ${path} from folders to add`}
|
||||
title="Remove from folders to add"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon } from './icons'
|
||||
import { FolderRow } from './folderPicker/FolderRow'
|
||||
import { StagedFoldersPanel } from './folderPicker/StagedFoldersPanel'
|
||||
import { StatusLine } from './folderPicker/StatusLine'
|
||||
import { normalizePath } from './folderPicker/pathUtils'
|
||||
import { useFolderPicker } from './folderPicker/useFolderPicker'
|
||||
|
||||
export function FolderPickerModal() {
|
||||
const folderPickerOpen = useGalleryStore((state) => state.folderPickerOpen);
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen);
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const listDirectories = useGalleryStore((state) => state.listDirectories);
|
||||
const addFolders = useGalleryStore((state) => state.addFolders);
|
||||
|
||||
const [listing, setListing] = useState<DirListing | null>(null);
|
||||
const [currentPath, setCurrentPath] = useState<string | null>(null);
|
||||
const [stagedPaths, setStagedPaths] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [results, setResults] = useState<FolderAddResult[] | null>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const libraryPaths = useMemo(() => new Set(folders.map((folder) => normalizePath(folder.path))), [folders]);
|
||||
const stagedSet = useMemo(() => new Set(stagedPaths.map(normalizePath)), [stagedPaths]);
|
||||
const breadcrumbs = useMemo(() => buildBreadcrumbs(listing?.current ?? null), [listing?.current]);
|
||||
const folderPicker = useFolderPicker()
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: listing?.entries.length ?? 0,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
count: folderPicker.entries.length,
|
||||
getScrollElement: () => folderPicker.scrollRef.current,
|
||||
estimateSize: () => 48,
|
||||
overscan: 8,
|
||||
});
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderPickerOpen) return;
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void listDirectories(currentPath)
|
||||
.then((nextListing) => {
|
||||
if (cancelled) return;
|
||||
setListing(nextListing);
|
||||
scrollRef.current?.scrollTo({ top: 0, left: 0 });
|
||||
})
|
||||
.catch((loadError) => {
|
||||
if (cancelled) return;
|
||||
setListing({ current: currentPath, parent: null, entries: [] });
|
||||
setError(loadError instanceof Error ? loadError.message : String(loadError));
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [currentPath, folderPickerOpen, listDirectories]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderPickerOpen) return;
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setFolderPickerOpen(false);
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [folderPickerOpen, setFolderPickerOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (folderPickerOpen) return;
|
||||
setCurrentPath(null);
|
||||
setListing(null);
|
||||
setStagedPaths([]);
|
||||
setError(null);
|
||||
setResults(null);
|
||||
setAdding(false);
|
||||
}, [folderPickerOpen]);
|
||||
|
||||
if (!folderPickerOpen) return null;
|
||||
|
||||
const entries = listing?.entries ?? [];
|
||||
|
||||
const togglePath = (path: string) => {
|
||||
const normalized = normalizePath(path);
|
||||
if (libraryPaths.has(normalized)) return;
|
||||
setResults(null);
|
||||
setStagedPaths((current) => {
|
||||
const exists = current.some((staged) => normalizePath(staged) === normalized);
|
||||
return exists ? current.filter((staged) => normalizePath(staged) !== normalized) : [...current, path];
|
||||
});
|
||||
};
|
||||
|
||||
const removeStagedPath = (path: string) => {
|
||||
const normalized = normalizePath(path);
|
||||
setResults(null);
|
||||
setStagedPaths((current) => current.filter((staged) => normalizePath(staged) !== normalized));
|
||||
};
|
||||
|
||||
const clearStagedPaths = () => {
|
||||
setResults(null);
|
||||
setStagedPaths([]);
|
||||
};
|
||||
|
||||
const confirmAdd = async () => {
|
||||
if (stagedPaths.length === 0 || adding) return;
|
||||
setAdding(true);
|
||||
setError(null);
|
||||
try {
|
||||
const addResults = await addFolders(stagedPaths);
|
||||
const failed = addResults.filter((result) => result.status === "error");
|
||||
setResults(addResults);
|
||||
if (failed.length > 0) {
|
||||
setStagedPaths(stagedPaths.filter((_, i) => addResults[i]?.status === "error"));
|
||||
setError(failed.map((failure) => failure.data).join("; "));
|
||||
return;
|
||||
}
|
||||
setFolderPickerOpen(false);
|
||||
} catch (addError) {
|
||||
setError(addError instanceof Error ? addError.message : String(addError));
|
||||
} finally {
|
||||
setAdding(false);
|
||||
}
|
||||
};
|
||||
if (!folderPicker.folderPickerOpen) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/65 px-6 backdrop-blur-sm"
|
||||
onClick={() => setFolderPickerOpen(false)}
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
<div
|
||||
className="relative flex h-[min(82vh,760px)] w-[min(90vw,1180px)] flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60 light-theme:border-gray-300/70"
|
||||
className="light-theme:border-gray-300/70 relative flex h-[min(82vh,760px)] w-[min(90vw,1180px)] flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<header className="border-b border-white/[0.07] px-5 py-4 light-theme:border-gray-200">
|
||||
<header className="light-theme:border-gray-200 border-b border-white/[0.07] px-5 py-4">
|
||||
<div className="flex items-start justify-between gap-6">
|
||||
<div className="min-w-0">
|
||||
<p className="text-base font-semibold text-white">Add media folders</p>
|
||||
<p className="mt-1 text-xs text-gray-500 light-theme:text-gray-600">Choose folders from any location, then add them together.</p>
|
||||
<p className="light-theme:text-gray-600 mt-1 text-xs text-gray-500">
|
||||
Choose folders from any location, then add them together.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
onClick={() => setFolderPickerOpen(false)}
|
||||
title="Close folder picker"
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<Tooltip label="Close folder picker" anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:hover:bg-gray-900 light-theme:hover:text-white rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -345,52 +53,118 @@ export function FolderPickerModal() {
|
||||
<div className="mb-4 flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
onClick={() => setCurrentPath(listing?.parent ?? null)}
|
||||
disabled={!listing?.current}
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={() => folderPicker.setCurrentPath(folderPicker.listing?.parent ?? null)}
|
||||
disabled={!folderPicker.listing?.current}
|
||||
>
|
||||
Up
|
||||
</button>
|
||||
<nav className="flex min-w-0 flex-1 items-center gap-1 overflow-hidden rounded-md border border-white/10 bg-white/[0.025] px-2 py-1.5 light-theme:border-gray-300/70 light-theme:bg-gray-900">
|
||||
{breadcrumbs.map((crumb, index) => (
|
||||
<span key={`${crumb.path ?? "root"}-${index}`} className="flex min-w-0 items-center gap-1">
|
||||
{index > 0 ? <span className="text-gray-700 light-theme:text-gray-400">/</span> : null}
|
||||
<button
|
||||
type="button"
|
||||
className="max-w-40 truncate rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white"
|
||||
onClick={() => setCurrentPath(crumb.path)}
|
||||
title={crumb.path ?? "Roots"}
|
||||
>
|
||||
{crumb.label}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
{folderPicker.addressEditing ? (
|
||||
<form
|
||||
className="flex min-w-0 flex-1 items-center gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
folderPicker.navigateToAddress()
|
||||
}}
|
||||
>
|
||||
<label className="sr-only" htmlFor="folder-picker-address">
|
||||
Folder path
|
||||
</label>
|
||||
<input
|
||||
ref={folderPicker.addressInputRef}
|
||||
id="folder-picker-address"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:placeholder-gray-500 light-theme:focus:bg-gray-800 min-w-0 flex-1 rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 font-mono text-xs text-gray-200 placeholder-gray-600 transition-colors outline-none focus:border-white/25 focus:bg-white/[0.055]"
|
||||
value={folderPicker.addressDraft}
|
||||
onChange={(event) => folderPicker.updateAddressDraft(event.target.value)}
|
||||
placeholder="Paste or type a folder path"
|
||||
spellCheck={false}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-2.5 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={folderPicker.loading}
|
||||
>
|
||||
Go
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="light-theme:border-gray-300/70 light-theme:bg-gray-900 flex min-w-0 flex-1 items-center gap-1 overflow-hidden rounded-md border border-white/10 bg-white/[0.025] px-2 py-1.5">
|
||||
<nav className="flex min-w-0 items-center gap-1 overflow-hidden">
|
||||
{folderPicker.breadcrumbs.map((crumb, index) => (
|
||||
<span
|
||||
key={`${crumb.path ?? 'root'}-${index}`}
|
||||
className="flex min-w-0 items-center gap-1"
|
||||
>
|
||||
{index > 0 ? (
|
||||
<span className="light-theme:text-gray-400 text-gray-700">/</span>
|
||||
) : null}
|
||||
<Tooltip label={crumb.path ?? 'Roots'} anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white max-w-40 truncate rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
folderPicker.setCurrentPath(crumb.path)
|
||||
}}
|
||||
>
|
||||
{crumb.label}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
))}
|
||||
</nav>
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-10 flex-1 cursor-text self-stretch rounded px-1"
|
||||
onClick={folderPicker.beginAddressEdit}
|
||||
aria-label="Edit folder path"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-emerald-400/35 bg-emerald-500/15 px-2.5 py-1.5 text-xs text-emerald-200 transition-colors hover:bg-emerald-500/25 disabled:cursor-not-allowed disabled:opacity-45"
|
||||
onClick={() => folderPicker.stagePath(folderPicker.addressPath)}
|
||||
disabled={
|
||||
!folderPicker.addressPath ||
|
||||
folderPicker.addressAlreadyAdded ||
|
||||
folderPicker.addressAlreadyStaged
|
||||
}
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<div className="mb-3 rounded-md border border-amber-400/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-200 light-theme:border-amber-600/40 light-theme:bg-amber-100 light-theme:text-amber-800">
|
||||
{error}
|
||||
{folderPicker.error ? (
|
||||
<div className="light-theme:border-amber-600/40 light-theme:bg-amber-100 light-theme:text-amber-800 mb-3 rounded-md border border-amber-400/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-200">
|
||||
{folderPicker.error}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div ref={scrollRef} className="min-h-0 flex-1 overflow-auto rounded-md border border-white/[0.07] bg-white/[0.018] p-2 light-theme:border-gray-300/70 light-theme:bg-gray-900/50">
|
||||
{loading ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">Loading folders...</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">No folders found here.</div>
|
||||
<div
|
||||
ref={folderPicker.scrollRef}
|
||||
className="light-theme:border-gray-300/70 light-theme:bg-gray-900/50 min-h-0 flex-1 overflow-auto rounded-md border border-white/[0.07] bg-white/[0.018] p-2"
|
||||
>
|
||||
{folderPicker.loading ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">
|
||||
Loading folders...
|
||||
</div>
|
||||
) : folderPicker.entries.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-gray-500">
|
||||
No folders found here.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ height: `${virtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const entry = entries[virtualItem.index];
|
||||
const normalized = normalizePath(entry.path);
|
||||
const entry = folderPicker.entries[virtualItem.index]
|
||||
const normalized = normalizePath(entry.path)
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
className="absolute left-0 top-0 w-full px-0.5"
|
||||
className="absolute top-0 left-0 w-full px-0.5"
|
||||
style={{
|
||||
height: `${virtualItem.size}px`,
|
||||
transform: `translateY(${virtualItem.start}px)`,
|
||||
@@ -398,13 +172,13 @@ export function FolderPickerModal() {
|
||||
>
|
||||
<FolderRow
|
||||
entry={entry}
|
||||
selected={stagedSet.has(normalized)}
|
||||
alreadyAdded={libraryPaths.has(normalized)}
|
||||
onToggle={() => togglePath(entry.path)}
|
||||
onNavigate={() => setCurrentPath(entry.path)}
|
||||
selected={folderPicker.stagedSet.has(normalized)}
|
||||
alreadyAdded={folderPicker.libraryPaths.has(normalized)}
|
||||
onToggle={() => folderPicker.togglePath(entry.path)}
|
||||
onNavigate={() => folderPicker.setCurrentPath(entry.path)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
@@ -412,38 +186,38 @@ export function FolderPickerModal() {
|
||||
</main>
|
||||
|
||||
<StagedFoldersPanel
|
||||
stagedPaths={stagedPaths}
|
||||
onRemove={removeStagedPath}
|
||||
onClear={clearStagedPaths}
|
||||
stagedPaths={folderPicker.stagedPaths}
|
||||
onRemove={folderPicker.removeStagedPath}
|
||||
onClear={folderPicker.clearStagedPaths}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<footer className="border-t border-white/[0.07] px-5 py-4 light-theme:border-gray-200">
|
||||
<footer className="light-theme:border-gray-200 border-t border-white/[0.07] px-5 py-4">
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<StatusLine results={results} />
|
||||
<StatusLine results={folderPicker.results} />
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
onClick={() => setFolderPickerOpen(false)}
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/10 bg-white/[0.035] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/[0.07] hover:text-white"
|
||||
onClick={() => folderPicker.setFolderPickerOpen(false)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/15 bg-white/[0.08] px-3 py-1.5 text-xs text-white transition-colors hover:bg-white/[0.12] disabled:cursor-not-allowed disabled:opacity-45 light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800"
|
||||
onClick={() => void confirmAdd()}
|
||||
disabled={stagedPaths.length === 0 || adding}
|
||||
className="light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 rounded-md border border-white/15 bg-white/[0.08] px-3 py-1.5 text-xs text-white transition-colors hover:bg-white/[0.12] disabled:cursor-not-allowed disabled:opacity-45"
|
||||
onClick={() => void folderPicker.confirmAdd()}
|
||||
disabled={folderPicker.stagedPaths.length === 0 || folderPicker.adding}
|
||||
>
|
||||
{adding ? "Adding..." : `Add ${stagedPaths.length}`}
|
||||
{folderPicker.adding ? 'Adding...' : `Add ${folderPicker.stagedPaths.length}`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { useMemo } from 'react'
|
||||
import { useGalleryStore } from '../store'
|
||||
import { Dropdown, DropdownOption } from './menu'
|
||||
|
||||
/**
|
||||
* In-view folder scope picker for feature views (Timeline / Explore /
|
||||
@@ -7,92 +8,48 @@ import { useGalleryStore } from "../store";
|
||||
* current view active — unlike sidebar folder clicks, which jump to Gallery.
|
||||
*/
|
||||
export function FolderScopeDropdown() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId)
|
||||
const setViewFolderScope = useGalleryStore((state) => state.setViewFolderScope)
|
||||
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const setViewFolderScope = useGalleryStore((state) => state.setViewFolderScope);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: MouseEvent) => {
|
||||
if (!ref.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
const currentLabel =
|
||||
selectedFolderId === null
|
||||
? "All Media"
|
||||
: folders.find((folder) => folder.id === selectedFolderId)?.name ?? "All Media";
|
||||
|
||||
const select = (folderId: number | null) => {
|
||||
setViewFolderScope(folderId);
|
||||
setOpen(false);
|
||||
};
|
||||
const options = useMemo<DropdownOption<number | null>[]>(
|
||||
() => [
|
||||
{ value: null, label: 'All Media' },
|
||||
...folders.map((folder) => ({
|
||||
value: folder.id,
|
||||
label: folder.name,
|
||||
hint: <span className="tabular-nums">{folder.image_count.toLocaleString()}</span>,
|
||||
})),
|
||||
],
|
||||
[folders]
|
||||
)
|
||||
|
||||
return (
|
||||
<div ref={ref} className="feature-scope-dropdown relative">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className={`feature-scope-trigger flex max-w-56 items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
open
|
||||
? "border-white/15 bg-white/8 text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "border-white/8 bg-transparent text-gray-400 hover:border-white/15 hover:text-gray-200 light-theme:border-gray-700/40 light-theme:text-gray-600 light-theme:hover:border-gray-700 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
title="Change folder scope"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5 shrink-0 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
<span className="truncate">{currentLabel}</span>
|
||||
<Dropdown
|
||||
value={selectedFolderId}
|
||||
options={options}
|
||||
onChange={setViewFolderScope}
|
||||
ariaLabel="Folder scope"
|
||||
trigger="ghost"
|
||||
size="md"
|
||||
triggerTooltip="Change folder scope"
|
||||
triggerClassName="max-w-56"
|
||||
panelClassName="min-w-52 max-h-80 overflow-y-auto"
|
||||
triggerIcon={
|
||||
<svg
|
||||
className={`h-3 w-3 shrink-0 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
className="h-3.5 w-3.5 shrink-0 text-gray-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="feature-scope-menu absolute right-0 top-full z-30 mt-1.5 max-h-80 min-w-52 overflow-y-auto rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur light-theme:border-gray-700/50">
|
||||
<button
|
||||
className={`feature-scope-option flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
selectedFolderId === null ? "bg-white/6 text-white light-theme:bg-gray-900 light-theme:text-white" : "text-gray-400 hover:bg-white/5 hover:text-white light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => select(null)}
|
||||
>
|
||||
All Media
|
||||
{selectedFolderId === null ? (
|
||||
<svg className="h-3.5 w-3.5 shrink-0 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
{folders.map((folder) => {
|
||||
const active = selectedFolderId === folder.id;
|
||||
return (
|
||||
<button
|
||||
key={folder.id}
|
||||
className={`feature-scope-option flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
active ? "bg-white/6 text-white light-theme:bg-gray-900 light-theme:text-white" : "text-gray-400 hover:bg-white/5 hover:text-white light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => select(folder.id)}
|
||||
>
|
||||
<span className="min-w-0 truncate">{folder.name}</span>
|
||||
<span className="flex shrink-0 items-center gap-2">
|
||||
<span className="text-[11px] tabular-nums text-gray-600">{folder.image_count.toLocaleString()}</span>
|
||||
{active ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
+124
-466
@@ -1,336 +1,54 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from "../store";
|
||||
import { BulkActionBar } from "./BulkActionBar";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
import { mediaSrc } from "../lib/mediaSrc";
|
||||
import { useEffect, useLayoutEffect, useRef, useCallback, useMemo, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { ImageRecord, parseSearchValue, tileSizeForZoom, useGalleryStore } from '../store'
|
||||
import { BulkActionBar } from './BulkActionBar'
|
||||
import { ImageContextMenu } from './ImageContextMenu'
|
||||
import { GalleryEmptyState, GalleryLoadingState } from './gallery/GalleryEmptyState'
|
||||
import { ImageTile } from './gallery/ImageTile'
|
||||
|
||||
const GAP = 6;
|
||||
|
||||
function formatDuration(durationMs: number | null): string | null {
|
||||
if (!durationMs || durationMs <= 0) return null;
|
||||
const totalSeconds = Math.floor(durationMs / 1000);
|
||||
const seconds = totalSeconds % 60;
|
||||
const minutes = Math.floor(totalSeconds / 60) % 60;
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
if (hours > 0) {
|
||||
return `${hours}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
return `${minutes}:${seconds.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function ContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number;
|
||||
y: number;
|
||||
image: ImageRecord;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const openImage = useGalleryStore((state) => state.openImage);
|
||||
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails);
|
||||
const findSimilar = useGalleryStore((state) => state.findSimilar);
|
||||
const canFindSimilar = image.embedding_status === "ready";
|
||||
|
||||
return (
|
||||
<div
|
||||
data-gallery-context-menu
|
||||
className="fixed z-40 min-w-52 rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur"
|
||||
style={{ left: x, top: y }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="w-full rounded-lg px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5 hover:text-white transition-colors"
|
||||
onClick={() => { openImage(image); onClose(); }}
|
||||
>
|
||||
Open Preview
|
||||
</button>
|
||||
<button
|
||||
className="w-full rounded-lg px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5 hover:text-white transition-colors"
|
||||
onClick={async () => { await updateImageDetails(image.id, { favorite: !image.favorite }); onClose(); }}
|
||||
>
|
||||
{image.favorite ? "Remove Favorite" : "Add to Favorites"}
|
||||
</button>
|
||||
<button
|
||||
className={`w-full rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
canFindSimilar
|
||||
? "text-gray-200 hover:bg-white/5 hover:text-white"
|
||||
: "text-gray-600 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (!canFindSimilar) return;
|
||||
findSimilar(image.id, image.folder_id);
|
||||
onClose();
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
{canFindSimilar ? "Find Similar" : "Embeddings not ready"}
|
||||
</button>
|
||||
<div className="my-1 h-px bg-white/[0.06]" />
|
||||
<div className="px-3 py-1 text-[10px] uppercase tracking-[0.18em] text-gray-600">Rating</div>
|
||||
<div className="flex items-center gap-0.5 px-2 pb-1.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1;
|
||||
return (
|
||||
<button
|
||||
key={rating}
|
||||
className="rounded-md p-1 transition-colors hover:bg-white/5"
|
||||
onClick={async () => { await updateImageDetails(image.id, { rating }); onClose(); }}
|
||||
title={`Set ${rating} star rating`}
|
||||
>
|
||||
<svg
|
||||
className={`h-4 w-4 ${rating <= image.rating ? "text-amber-300" : "text-white/20 hover:text-white/40"}`}
|
||||
fill="currentColor" viewBox="0 0 20 20"
|
||||
>
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{image.rating > 0 ? (
|
||||
<button
|
||||
className="ml-1 rounded-md p-1 text-gray-600 hover:bg-white/5 hover:text-gray-300 transition-colors"
|
||||
onClick={async () => { await updateImageDetails(image.id, { rating: 0 }); onClose(); }}
|
||||
title="Remove rating"
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ImageTile({
|
||||
image,
|
||||
onClick,
|
||||
onContextMenu,
|
||||
}: {
|
||||
image: ImageRecord;
|
||||
onClick: () => void;
|
||||
onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void;
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [errored, setErrored] = useState(false);
|
||||
const findSimilar = useGalleryStore((state) => state.findSimilar);
|
||||
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 src = mediaSrc(image.thumbnail_path);
|
||||
|
||||
return (
|
||||
<Tooltip label={image.filename} delay={500} block followCursor>
|
||||
<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" }}
|
||||
onContextMenu={onContextMenu}
|
||||
>
|
||||
{/* 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 */}
|
||||
{src && !errored ? (
|
||||
<>
|
||||
{!loaded && <div className="absolute inset-0 animate-pulse bg-white/[0.04]" />}
|
||||
<img
|
||||
src={src}
|
||||
alt={image.filename}
|
||||
className={`h-full w-full object-cover transition-all duration-300 ${
|
||||
loaded ? "opacity-100 scale-100" : "opacity-0 scale-[1.02]"
|
||||
} group-hover:scale-[1.03]`}
|
||||
loading="lazy"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setErrored(true)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/[0.03] text-white/20">
|
||||
{image.media_kind === "video" ? (
|
||||
<svg className="h-7 w-7" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Video play icon — subtle at rest, visible on hover */}
|
||||
{image.media_kind === "video" && (
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<div className="rounded-full bg-black/40 p-3 text-white backdrop-blur-sm opacity-50 group-hover:opacity-90 transition-opacity duration-200">
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persistent badges — only shown when meaningful */}
|
||||
<div className="absolute top-2 right-2 flex flex-col items-end gap-1 pointer-events-none">
|
||||
{image.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 && (
|
||||
<div className="rounded-full bg-black/50 p-1 text-rose-400 backdrop-blur-sm">
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
{image.rating > 0 && (
|
||||
<div className="flex items-center gap-0.5 rounded-md bg-black/60 px-1.5 py-1 text-amber-300 backdrop-blur-sm">
|
||||
{Array.from({ length: image.rating }, (_, index) => (
|
||||
<svg key={index} className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{image.media_kind === "video" && image.duration_ms && (
|
||||
<div className="rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-white/80 backdrop-blur-sm">
|
||||
{formatDuration(image.duration_ms)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Hover overlay — slides up from bottom */}
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none" />
|
||||
|
||||
{/* Hover info — appears with overlay */}
|
||||
<div className="absolute bottom-0 left-0 right-0 p-2.5 translate-y-1 group-hover:translate-y-0 opacity-0 group-hover:opacity-100 transition-all duration-200">
|
||||
<p className="truncate text-[12px] font-medium text-white leading-tight">{image.filename}</p>
|
||||
<div className="mt-1.5 flex items-center justify-between gap-2">
|
||||
{image.rating > 0 ? (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{Array.from({ length: image.rating }, (_, i) => (
|
||||
<svg key={i} className="h-2.5 w-2.5 text-amber-300" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.176 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81H7.03a1 1 0 00.951-.69l1.07-3.292z" />
|
||||
</svg>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<button
|
||||
className={`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
|
||||
? "bg-white/10 text-white/80 hover:bg-white/20 hover:text-white"
|
||||
: "bg-white/5 text-white/30 cursor-not-allowed"
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (!canFindSimilar) return;
|
||||
findSimilar(image.id, image.folder_id);
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
Similar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
const GAP = 6
|
||||
|
||||
export function Gallery() {
|
||||
const images = useGalleryStore((state) => state.images);
|
||||
const loadMoreImages = useGalleryStore((state) => state.loadMoreImages);
|
||||
const openImage = useGalleryStore((state) => state.openImage);
|
||||
const totalImages = useGalleryStore((state) => state.totalImages);
|
||||
const loadingImages = useGalleryStore((state) => state.loadingImages);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const search = useGalleryStore((state) => state.search);
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle);
|
||||
const imageLoadError = useGalleryStore((state) => state.imageLoadError);
|
||||
const galleryScrollResetKey = useGalleryStore((state) => state.galleryScrollResetKey);
|
||||
const isSimilarResults = collectionTitle === "Similar Images";
|
||||
const parsedSearch = parseSearchValue(search);
|
||||
const images = useGalleryStore((state) => state.images)
|
||||
const loadMoreImages = useGalleryStore((state) => state.loadMoreImages)
|
||||
const openImage = useGalleryStore((state) => state.openImage)
|
||||
const totalImages = useGalleryStore((state) => state.totalImages)
|
||||
const loadingImages = useGalleryStore((state) => state.loadingImages)
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset)
|
||||
const search = useGalleryStore((state) => state.search)
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle)
|
||||
const imageLoadError = useGalleryStore((state) => state.imageLoadError)
|
||||
const galleryScrollResetKey = useGalleryStore((state) => state.galleryScrollResetKey)
|
||||
const isSimilarResults = collectionTitle === 'Similar Images'
|
||||
const parsedSearch = parseSearchValue(search)
|
||||
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; image: ImageRecord } | null>(null);
|
||||
const parentRef = useRef<HTMLDivElement>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
} | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
setContainerWidth(el.clientWidth);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
setContainerWidth(el.clientWidth)
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
setContainerWidth(entries[0].contentRect.width);
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
setContainerWidth(entries[0].contentRect.width)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
const tileSize = tileSizeForZoom(zoomPreset)
|
||||
const cols = useMemo(
|
||||
() => Math.max(1, Math.floor((containerWidth - GAP) / (tileSize + GAP))),
|
||||
[containerWidth, tileSize],
|
||||
);
|
||||
const rowCount = Math.ceil(images.length / cols);
|
||||
[containerWidth, tileSize]
|
||||
)
|
||||
const rowCount = Math.ceil(images.length / cols)
|
||||
|
||||
const estimateSize = useCallback(() => tileSize + GAP, [tileSize]);
|
||||
const estimateSize = useCallback(() => tileSize + GAP, [tileSize])
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rowCount,
|
||||
@@ -338,165 +56,105 @@ export function Gallery() {
|
||||
estimateSize,
|
||||
overscan: 3,
|
||||
paddingStart: GAP,
|
||||
});
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
virtualizer.measure();
|
||||
}, [cols, virtualizer]);
|
||||
virtualizer.measure()
|
||||
}, [cols, virtualizer])
|
||||
|
||||
useEffect(() => {
|
||||
parentRef.current?.scrollTo({ top: 0, left: 0 });
|
||||
}, [galleryScrollResetKey]);
|
||||
parentRef.current?.scrollTo({ top: 0, left: 0 })
|
||||
}, [galleryScrollResetKey])
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
if (el.scrollTop < 24) return;
|
||||
const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 600;
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
if (el.scrollTop < 24) return
|
||||
const nearBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 600
|
||||
if (nearBottom && !loadingImages && images.length < totalImages) {
|
||||
void loadMoreImages();
|
||||
void loadMoreImages()
|
||||
}
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages]);
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages])
|
||||
|
||||
useEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (event: PointerEvent) => {
|
||||
if ((event.target as HTMLElement | null)?.closest("[data-gallery-context-menu]")) return;
|
||||
setContextMenu(null);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setContextMenu(null);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", close);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
el.addEventListener('scroll', handleScroll, { passive: true })
|
||||
return () => el.removeEventListener('scroll', handleScroll)
|
||||
}, [handleScroll])
|
||||
|
||||
return (
|
||||
<div 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 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 min-w-72">
|
||||
<div className="h-5 w-5 mx-auto rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<p className="mt-4 text-sm text-white/40 font-medium">
|
||||
{isSimilarResults
|
||||
? "Finding similar images"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? `Searching for matches to "${parsedSearch.query}"`
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? `Searching tags for "${parsedSearch.query}"`
|
||||
: "Loading media"}
|
||||
</p>
|
||||
<p className="text-xs text-white/20 mt-1">
|
||||
{isSimilarResults
|
||||
? "Comparing visual embeddings"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "Semantic search can take a little longer than filename search"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "Matching against AI and user tags"
|
||||
: "Fetching results"}
|
||||
</p>
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<div
|
||||
ref={parentRef}
|
||||
className="absolute inset-0 overflow-x-hidden overflow-y-auto bg-gray-950"
|
||||
>
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<GalleryLoadingState isSimilarResults={isSimilarResults} parsedSearch={parsedSearch} />
|
||||
) : images.length === 0 && !loadingImages ? (
|
||||
<GalleryEmptyState
|
||||
imageLoadError={imageLoadError}
|
||||
isSimilarResults={isSimilarResults}
|
||||
parsedSearch={parsedSearch}
|
||||
/>
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const startIndex = virtualRow.index * cols
|
||||
const rowImages = images.slice(startIndex, startIndex + cols)
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: virtualRow.start,
|
||||
width: '100%',
|
||||
height: virtualRow.size,
|
||||
display: 'grid',
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
{rowImages.map((image) => (
|
||||
<ImageTile
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault()
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : images.length === 0 && !loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<svg className="h-12 w-12 mx-auto text-white/10 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={0.75}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<p className="text-sm text-white/30 font-medium">
|
||||
{imageLoadError
|
||||
? "Could not load results"
|
||||
: isSimilarResults
|
||||
? "No similar images found"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "No semantic matches found"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "No tag matches found"
|
||||
: "No media found"}
|
||||
</p>
|
||||
<p className="text-xs text-white/15 mt-1">
|
||||
{imageLoadError
|
||||
? imageLoadError
|
||||
: isSimilarResults
|
||||
? "This item may be visually isolated, or more embeddings may need to finish processing"
|
||||
: parsedSearch.mode === "semantic" && parsedSearch.query.length > 0
|
||||
? "Try a broader phrase, or wait for more embeddings to finish processing"
|
||||
: parsedSearch.mode === "tag" && parsedSearch.query.length > 0
|
||||
? "Try a shorter tag, or wait for more tagging jobs to finish"
|
||||
: "Try adjusting your filters or add a new folder"}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
|
||||
{virtualizer.getVirtualItems().map((virtualRow) => {
|
||||
const startIndex = virtualRow.index * cols;
|
||||
const rowImages = images.slice(startIndex, startIndex + cols);
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: virtualRow.start,
|
||||
width: "100%",
|
||||
height: virtualRow.size,
|
||||
display: "grid",
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: "border-box",
|
||||
}}
|
||||
>
|
||||
{rowImages.map((image) => (
|
||||
<ImageTile
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
) : null}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
</div>
|
||||
) : null}
|
||||
{contextMenu ? (
|
||||
<ImageContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
onClose={() => setContextMenu(null)}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{contextMenu ? (
|
||||
<ContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
onClose={() => setContextMenu(null)}
|
||||
/>
|
||||
) : null}
|
||||
{/* Pinned to the bottom of the gallery viewport — outside the scroll
|
||||
container so it stays put while the grid scrolls. */}
|
||||
<BulkActionBar />
|
||||
</div>
|
||||
|
||||
{/* Pinned to the bottom of the gallery viewport — outside the scroll
|
||||
container so it stays put while the grid scrolls. */}
|
||||
<BulkActionBar />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { ImageRecord, useGalleryStore } from '../store'
|
||||
import { ContextMenu, MenuItem, MenuLabel, MenuSeparator, SubMenu } from './menu'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { CloseIcon, StarIcon } from './icons'
|
||||
|
||||
/** Right-click menu for an image tile. Shared by the Gallery grid and the Timeline. */
|
||||
export function ImageContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
onClose: () => void
|
||||
}) {
|
||||
const openImage = useGalleryStore((state) => state.openImage)
|
||||
const updateImageDetails = useGalleryStore((state) => state.updateImageDetails)
|
||||
const findSimilar = useGalleryStore((state) => state.findSimilar)
|
||||
const albums = useGalleryStore((state) => state.albums)
|
||||
const addToAlbum = useGalleryStore((state) => state.addToAlbum)
|
||||
const canFindSimilar = image.embedding_status === 'ready'
|
||||
|
||||
return (
|
||||
<ContextMenu x={x} y={y} onClose={onClose}>
|
||||
<MenuItem label="Open Preview" onSelect={() => openImage(image)} />
|
||||
<MenuItem
|
||||
label={image.favorite ? 'Remove Favorite' : 'Add to Favorites'}
|
||||
onSelect={() => void updateImageDetails(image.id, { favorite: !image.favorite })}
|
||||
/>
|
||||
<MenuItem
|
||||
label={canFindSimilar ? 'Find Similar' : 'Embeddings not ready'}
|
||||
disabled={!canFindSimilar}
|
||||
onSelect={() => findSimilar(image.id, image.folder_id)}
|
||||
/>
|
||||
<SubMenu label="Add to Album" panelClassName="max-h-64 overflow-y-auto">
|
||||
{albums.length === 0 ? (
|
||||
<MenuItem label="No albums yet" disabled />
|
||||
) : (
|
||||
albums.map((album) => (
|
||||
<MenuItem
|
||||
key={album.id}
|
||||
label={album.name}
|
||||
hint={album.image_count.toLocaleString()}
|
||||
onSelect={() => void addToAlbum(album.id, [image.id])}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</SubMenu>
|
||||
<MenuSeparator />
|
||||
<MenuLabel>Rating</MenuLabel>
|
||||
<div className="flex items-center gap-0.5 px-2 pb-1.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1
|
||||
return (
|
||||
<Tooltip key={rating} label={`Set ${rating} star rating`} followCursor>
|
||||
<button
|
||||
className="rounded-md p-1 transition-colors hover:bg-white/5"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating })
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<StarIcon
|
||||
className={`h-4 w-4 ${rating <= image.rating ? 'text-amber-300' : 'text-white/20 hover:text-white/40'}`}
|
||||
/>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
{image.rating > 0 ? (
|
||||
<Tooltip label="Remove rating" followCursor>
|
||||
<button
|
||||
className="ml-1 rounded-md p-1 text-gray-600 transition-colors hover:bg-white/5 hover:text-gray-300"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating: 0 })
|
||||
onClose()
|
||||
}}
|
||||
>
|
||||
<CloseIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Compact Confirm/Cancel pair for destructive row actions (remove folder,
|
||||
* delete album). Swap it in where the hover actions normally sit.
|
||||
*/
|
||||
export function InlineConfirm({
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}: {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
}) {
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-1" onClick={(event) => event.stopPropagation()}>
|
||||
<button
|
||||
className="rounded bg-red-500/20 px-1.5 py-0.5 text-[10px] text-red-400 transition-colors hover:bg-red-500/30 hover:text-red-300"
|
||||
onClick={onConfirm}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
<button
|
||||
className="rounded bg-white/5 px-1.5 py-0.5 text-[10px] text-gray-500 transition-colors hover:bg-white/10 hover:text-gray-300"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
|
||||
/**
|
||||
* In-place rename input for sidebar rows (folders, albums). Mount it in
|
||||
* place of the row label while renaming: commits on Enter or blur (only when
|
||||
* the trimmed name is non-empty and actually changed), cancels on Escape.
|
||||
*/
|
||||
export function InlineRename({
|
||||
name,
|
||||
onRename,
|
||||
onClose,
|
||||
}: {
|
||||
name: string
|
||||
onRename: (next: string) => Promise<void> | void
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [value, setValue] = useState(name)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.focus()
|
||||
inputRef.current?.select()
|
||||
}, [])
|
||||
|
||||
const commit = async () => {
|
||||
const trimmed = value.trim()
|
||||
if (trimmed && trimmed !== name) {
|
||||
await onRename(trimmed)
|
||||
}
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="w-full rounded bg-white/10 px-1 py-0 text-[13px] leading-tight font-medium text-white ring-1 ring-blue-500/60 outline-none"
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
event.preventDefault()
|
||||
void commit()
|
||||
}
|
||||
if (event.key === 'Escape') onClose()
|
||||
}}
|
||||
onBlur={() => void commit()}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
+203
-943
File diff suppressed because it is too large
Load Diff
@@ -1,184 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { MediaFilter, ZoomPreset, useGalleryStore } from "../store";
|
||||
|
||||
type MenuKey = "library" | "view" | "filter";
|
||||
|
||||
function MenuButton({
|
||||
label,
|
||||
active,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`rounded-md px-2.5 py-1 text-xs transition-colors ${
|
||||
active ? "bg-white/10 text-white" : "text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function MenuPanel({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="absolute left-0 top-full z-30 mt-2 min-w-56 rounded-xl border border-white/10 bg-gray-950/95 p-2 shadow-2xl backdrop-blur">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MenuItem({
|
||||
label,
|
||||
hint,
|
||||
active = false,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
active?: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
active ? "bg-blue-500/15 text-white" : "text-gray-300 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
<span>{label}</span>
|
||||
{hint ? <span className="text-xs text-gray-500">{hint}</span> : null}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const ZOOM_OPTIONS: { value: ZoomPreset; label: string }[] = [
|
||||
{ value: "compact", label: "Compact Grid" },
|
||||
{ value: "comfortable", label: "Comfortable Grid" },
|
||||
{ value: "detail", label: "Detail Grid" },
|
||||
];
|
||||
|
||||
const FILTER_OPTIONS: { value: MediaFilter; label: string }[] = [
|
||||
{ value: "all", label: "All Media" },
|
||||
{ value: "image", label: "Images" },
|
||||
{ value: "video", label: "Videos" },
|
||||
];
|
||||
|
||||
export function MenuBar() {
|
||||
const [openMenu, setOpenMenu] = useState<MenuKey | null>(null);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen);
|
||||
const reindexFolder = useGalleryStore((state) => state.reindexFolder);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const setZoomPreset = useGalleryStore((state) => state.setZoomPreset);
|
||||
const mediaFilter = useGalleryStore((state) => state.mediaFilter);
|
||||
const setMediaFilter = useGalleryStore((state) => state.setMediaFilter);
|
||||
const favoritesOnly = useGalleryStore((state) => state.favoritesOnly);
|
||||
const setFavoritesOnly = useGalleryStore((state) => state.setFavoritesOnly);
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerDown = (event: MouseEvent) => {
|
||||
if (!rootRef.current?.contains(event.target as Node)) {
|
||||
setOpenMenu(null);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("pointerdown", handlePointerDown);
|
||||
return () => window.removeEventListener("pointerdown", handlePointerDown);
|
||||
}, []);
|
||||
|
||||
const handleAddFolder = () => {
|
||||
setFolderPickerOpen(true);
|
||||
setOpenMenu(null);
|
||||
};
|
||||
|
||||
const handleReindex = async () => {
|
||||
if (selectedFolderId !== null) {
|
||||
await reindexFolder(selectedFolderId);
|
||||
}
|
||||
setOpenMenu(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={rootRef} className="relative z-20 flex items-center gap-1 border-b border-white/5 bg-gray-950/90 px-4 py-2 backdrop-blur">
|
||||
<div className="relative">
|
||||
<MenuButton
|
||||
label="Library"
|
||||
active={openMenu === "library"}
|
||||
onClick={() => setOpenMenu((current) => (current === "library" ? null : "library"))}
|
||||
/>
|
||||
{openMenu === "library" ? (
|
||||
<MenuPanel>
|
||||
<MenuItem label="Add Folder" hint="Ctrl+O soon" onClick={handleAddFolder} />
|
||||
<MenuItem
|
||||
label="Re-index Current Folder"
|
||||
hint={selectedFolderId === null ? "Select folder" : undefined}
|
||||
onClick={handleReindex}
|
||||
active={selectedFolderId !== null}
|
||||
/>
|
||||
</MenuPanel>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<MenuButton
|
||||
label="View"
|
||||
active={openMenu === "view"}
|
||||
onClick={() => setOpenMenu((current) => (current === "view" ? null : "view"))}
|
||||
/>
|
||||
{openMenu === "view" ? (
|
||||
<MenuPanel>
|
||||
{ZOOM_OPTIONS.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
label={option.label}
|
||||
active={zoomPreset === option.value}
|
||||
onClick={() => {
|
||||
setZoomPreset(option.value);
|
||||
setOpenMenu(null);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</MenuPanel>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<MenuButton
|
||||
label="Filter"
|
||||
active={openMenu === "filter"}
|
||||
onClick={() => setOpenMenu((current) => (current === "filter" ? null : "filter"))}
|
||||
/>
|
||||
{openMenu === "filter" ? (
|
||||
<MenuPanel>
|
||||
{FILTER_OPTIONS.map((option) => (
|
||||
<MenuItem
|
||||
key={option.value}
|
||||
label={option.label}
|
||||
active={mediaFilter === option.value}
|
||||
onClick={() => {
|
||||
setMediaFilter(option.value);
|
||||
setOpenMenu(null);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<div className="my-2 h-px bg-white/5" />
|
||||
<MenuItem
|
||||
label={favoritesOnly ? "Hide Favorites Only" : "Show Favorites Only"}
|
||||
active={favoritesOnly}
|
||||
onClick={() => {
|
||||
setFavoritesOnly(!favoritesOnly);
|
||||
setOpenMenu(null);
|
||||
}}
|
||||
/>
|
||||
</MenuPanel>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,14 +6,14 @@
|
||||
//
|
||||
// Pass dotClassName (e.g. "fill-amber-400") to light up the central focal point —
|
||||
// used in the titlebar as the "update available" indicator.
|
||||
const BLADE = "M0,-4.18 A10,10 0 0 1 6.43,-7.66";
|
||||
const BLADE = 'M0,-4.18 A10,10 0 0 1 6.43,-7.66'
|
||||
|
||||
export function PhokusMark({
|
||||
className,
|
||||
dotClassName,
|
||||
}: {
|
||||
className?: string;
|
||||
dotClassName?: string;
|
||||
className?: string
|
||||
dotClassName?: string
|
||||
}) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" fill="none" className={className}>
|
||||
@@ -33,7 +33,9 @@ export function PhokusMark({
|
||||
<path d={BLADE} transform="rotate(240)" />
|
||||
<path d={BLADE} transform="rotate(300)" />
|
||||
</g>
|
||||
{dotClassName ? <circle cx="12" cy="12" r="2.6" stroke="none" className={dotClassName} /> : null}
|
||||
{dotClassName ? (
|
||||
<circle cx="12" cy="12" r="2.6" stroke="none" className={dotClassName} />
|
||||
) : null}
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+49
-1114
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,106 +0,0 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
export interface DropdownOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function ThemedDropdown({
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
ariaLabel,
|
||||
compact = false,
|
||||
align = "right",
|
||||
}: {
|
||||
value: string;
|
||||
options: DropdownOption[];
|
||||
onChange: (value: string) => void;
|
||||
ariaLabel: string;
|
||||
compact?: boolean;
|
||||
align?: "left" | "right";
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const current = options.find((option) => option.value === value) ?? options[0];
|
||||
|
||||
useEffect(() => {
|
||||
const handlePointerDown = (event: PointerEvent) => {
|
||||
if (!ref.current?.contains(event.target as Node)) setOpen(false);
|
||||
};
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", handlePointerDown);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", handlePointerDown);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={ariaLabel}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((currentOpen) => !currentOpen)}
|
||||
className={`flex items-center justify-between gap-2 rounded-md border transition-colors ${
|
||||
compact
|
||||
? "border-white/10 bg-white/[0.04] px-1.5 py-0.5 text-[10px] font-medium light-theme:border-gray-700/50 light-theme:bg-gray-900"
|
||||
: "min-w-40 border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs light-theme:border-gray-700/50 light-theme:bg-gray-900"
|
||||
} ${open ? "border-white/20 text-white light-theme:border-gray-700 light-theme:text-white" : "text-gray-400 hover:border-white/15 hover:text-gray-200 light-theme:text-white light-theme:hover:border-gray-700 light-theme:hover:bg-gray-800 light-theme:hover:text-white"}`}
|
||||
>
|
||||
<span>{current?.label}</span>
|
||||
<svg
|
||||
className={`h-3 w-3 shrink-0 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{open ? (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label={ariaLabel}
|
||||
className={`absolute top-full z-50 mt-1.5 min-w-full rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl shadow-black/30 backdrop-blur-xl light-theme:border-gray-700/50 ${
|
||||
align === "right" ? "right-0" : "left-0"
|
||||
}`}
|
||||
>
|
||||
{options.map((option) => {
|
||||
const selected = option.value === value;
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
className={`flex w-full items-center justify-between gap-4 whitespace-nowrap rounded-lg px-3 py-2 text-left text-xs transition-colors ${
|
||||
selected
|
||||
? "bg-white/[0.08] text-white light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "text-gray-400 hover:bg-white/[0.055] hover:text-gray-200 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => {
|
||||
onChange(option.value);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<span>{option.label}</span>
|
||||
{selected ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+97
-286
@@ -1,160 +1,69 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { ImageRecord, tileSizeForZoom, useGalleryStore } from "../store";
|
||||
import { ContextMenu, ImageTile } from "./Gallery";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import { ImageRecord, tileSizeForZoom, useGalleryStore } from '../store'
|
||||
import { ImageTile } from './gallery/ImageTile'
|
||||
import { ImageContextMenu } from './ImageContextMenu'
|
||||
import { ScrubberYearBlock } from './timeline/ScrubberYearBlock'
|
||||
import { TimelineEmptyState, TimelineLoadingState } from './timeline/TimelineEmptyState'
|
||||
import { buildScrubberYears, buildTimelineRows, groupImages } from './timeline/timelineModel'
|
||||
|
||||
const GAP = 6;
|
||||
const HEADER_HEIGHT = 52;
|
||||
const SCRUBBER_WIDTH = 48;
|
||||
const MONTH_SHORT = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] as const;
|
||||
|
||||
interface TimelineGroup {
|
||||
key: string;
|
||||
label: string;
|
||||
images: ImageRecord[];
|
||||
}
|
||||
|
||||
// One virtualized row: either a month header or a row of up to `cols` tiles.
|
||||
type TimelineRow =
|
||||
| { type: "header"; group: TimelineGroup }
|
||||
| { type: "tiles"; images: ImageRecord[] };
|
||||
|
||||
interface ScrubberMonth {
|
||||
monthNum: number;
|
||||
label: string;
|
||||
groupIndex: number;
|
||||
}
|
||||
|
||||
interface ScrubberYear {
|
||||
year: string;
|
||||
firstGroupIndex: number;
|
||||
months: ScrubberMonth[];
|
||||
}
|
||||
|
||||
function buildLabel(key: string): string {
|
||||
if (key === "unknown") return "Unknown Date";
|
||||
const [yearStr, monthStr] = key.split("-");
|
||||
const year = Number(yearStr);
|
||||
const month = Number(monthStr);
|
||||
if (!isFinite(year) || !isFinite(month) || month < 1 || month > 12) return "Unknown Date";
|
||||
const date = new Date(year, month - 1);
|
||||
if (isNaN(date.getTime())) return "Unknown Date";
|
||||
return date.toLocaleDateString(undefined, { month: "long", year: "numeric" });
|
||||
}
|
||||
|
||||
function groupImages(images: ImageRecord[]): TimelineGroup[] {
|
||||
const map = new Map<string, ImageRecord[]>();
|
||||
for (const img of images) {
|
||||
const ds = img.taken_at ?? img.modified_at;
|
||||
const key = ds ? ds.substring(0, 7) : "unknown";
|
||||
let bucket = map.get(key);
|
||||
if (bucket === undefined) {
|
||||
bucket = [];
|
||||
map.set(key, bucket);
|
||||
}
|
||||
bucket.push(img);
|
||||
}
|
||||
return Array.from(map.entries())
|
||||
.sort(([a], [b]) => {
|
||||
if (a === "unknown") return 1;
|
||||
if (b === "unknown") return -1;
|
||||
return a < b ? -1 : a > b ? 1 : 0;
|
||||
})
|
||||
.map(([key, imgs]) => ({ key, label: buildLabel(key), images: imgs }));
|
||||
}
|
||||
|
||||
function buildScrubberYears(groups: TimelineGroup[]): ScrubberYear[] {
|
||||
const byYear = new Map<string, ScrubberYear>();
|
||||
for (let i = 0; i < groups.length; i++) {
|
||||
const group = groups[i];
|
||||
if (group.key === "unknown") continue;
|
||||
const year = group.key.substring(0, 4);
|
||||
const monthNum = Number(group.key.substring(5, 7));
|
||||
if (!byYear.has(year)) {
|
||||
byYear.set(year, { year, firstGroupIndex: i, months: [] });
|
||||
}
|
||||
byYear.get(year)!.months.push({
|
||||
monthNum,
|
||||
label: MONTH_SHORT[monthNum - 1] ?? "",
|
||||
groupIndex: i,
|
||||
});
|
||||
}
|
||||
// Keep insertion order so the scrubber runs the same direction as the scrolled
|
||||
// content (oldest at top with taken_asc), keeping the active highlight aligned.
|
||||
return Array.from(byYear.values());
|
||||
}
|
||||
const GAP = 6
|
||||
const HEADER_HEIGHT = 52
|
||||
const SCRUBBER_WIDTH = 48
|
||||
|
||||
export function Timeline() {
|
||||
const images = useGalleryStore((s) => s.images);
|
||||
const loadMoreImages = useGalleryStore((s) => s.loadMoreImages);
|
||||
const openImage = useGalleryStore((s) => s.openImage);
|
||||
const totalImages = useGalleryStore((s) => s.totalImages);
|
||||
const loadingImages = useGalleryStore((s) => s.loadingImages);
|
||||
const imageLoadError = useGalleryStore((s) => s.imageLoadError);
|
||||
const zoomPreset = useGalleryStore((s) => s.zoomPreset);
|
||||
const images = useGalleryStore((s) => s.images)
|
||||
const loadMoreImages = useGalleryStore((s) => s.loadMoreImages)
|
||||
const openImage = useGalleryStore((s) => s.openImage)
|
||||
const totalImages = useGalleryStore((s) => s.totalImages)
|
||||
const loadingImages = useGalleryStore((s) => s.loadingImages)
|
||||
const imageLoadError = useGalleryStore((s) => s.imageLoadError)
|
||||
const zoomPreset = useGalleryStore((s) => s.zoomPreset)
|
||||
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const [containerWidth, setContainerWidth] = useState(0);
|
||||
const [activeGroupIndex, setActiveGroupIndex] = useState(0);
|
||||
const parentRef = useRef<HTMLDivElement>(null)
|
||||
const [containerWidth, setContainerWidth] = useState(0)
|
||||
const [activeGroupIndex, setActiveGroupIndex] = useState(0)
|
||||
const [contextMenu, setContextMenu] = useState<{
|
||||
x: number;
|
||||
y: number;
|
||||
image: ImageRecord;
|
||||
} | null>(null);
|
||||
x: number
|
||||
y: number
|
||||
image: ImageRecord
|
||||
} | null>(null)
|
||||
|
||||
// parentRef is the scroll container. Its clientWidth already excludes the
|
||||
// scrubber because they are flex siblings, so no further adjustment is needed.
|
||||
useLayoutEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
setContainerWidth(el.clientWidth);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
setContainerWidth(el.clientWidth)
|
||||
const ro = new ResizeObserver((entries) => {
|
||||
setContainerWidth(entries[0].contentRect.width);
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
setContainerWidth(entries[0].contentRect.width)
|
||||
})
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
const groups = useMemo(() => groupImages(images), [images]);
|
||||
const scrubberYears = useMemo(() => buildScrubberYears(groups), [groups]);
|
||||
const tileSize = tileSizeForZoom(zoomPreset)
|
||||
const groups = useMemo(() => groupImages(images), [images])
|
||||
const scrubberYears = useMemo(() => buildScrubberYears(groups), [groups])
|
||||
// Show as soon as there's more than one month to jump between — not gated on
|
||||
// a full year. With taken_asc sort the loaded set is oldest-first, so this
|
||||
// reflects whatever range is currently loaded.
|
||||
const showScrubber = groups.length > 1;
|
||||
const showScrubber = groups.length > 1
|
||||
|
||||
const cols = useMemo(
|
||||
() => Math.max(1, Math.floor((containerWidth - GAP) / (tileSize + GAP))),
|
||||
[containerWidth, tileSize],
|
||||
);
|
||||
[containerWidth, tileSize]
|
||||
)
|
||||
|
||||
// Flatten the month groups into a single list of fixed-height rows — one
|
||||
// header row per group, then one tile-row per `cols` images. This lets the
|
||||
// virtualizer render only the on-screen rows, exactly like the Gallery.
|
||||
// Previously each *group* was one virtual item that rendered ALL of its
|
||||
// images, so scrolling into a busy month mounted thousands of tiles at once.
|
||||
const { rows, rowToGroupIndex, groupFirstRow } = useMemo(() => {
|
||||
const rows: TimelineRow[] = [];
|
||||
const rowToGroupIndex: number[] = [];
|
||||
const groupFirstRow: number[] = [];
|
||||
groups.forEach((group, groupIndex) => {
|
||||
groupFirstRow[groupIndex] = rows.length;
|
||||
rows.push({ type: "header", group });
|
||||
rowToGroupIndex.push(groupIndex);
|
||||
for (let i = 0; i < group.images.length; i += cols) {
|
||||
rows.push({ type: "tiles", images: group.images.slice(i, i + cols) });
|
||||
rowToGroupIndex.push(groupIndex);
|
||||
}
|
||||
});
|
||||
return { rows, rowToGroupIndex, groupFirstRow };
|
||||
}, [groups, cols]);
|
||||
const { rows, rowToGroupIndex, groupFirstRow } = useMemo(
|
||||
() => buildTimelineRows(groups, cols),
|
||||
[groups, cols]
|
||||
)
|
||||
|
||||
const estimateSize = useCallback(
|
||||
(index: number): number =>
|
||||
rows[index]?.type === "header" ? HEADER_HEIGHT : tileSize + GAP,
|
||||
[rows, tileSize],
|
||||
);
|
||||
(index: number): number => (rows[index]?.type === 'header' ? HEADER_HEIGHT : tileSize + GAP),
|
||||
[rows, tileSize]
|
||||
)
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
count: rows.length,
|
||||
@@ -162,151 +71,101 @@ export function Timeline() {
|
||||
estimateSize,
|
||||
overscan: 6,
|
||||
paddingStart: GAP,
|
||||
});
|
||||
})
|
||||
|
||||
// Refs so the scroll handler can read the latest mappings without re-binding.
|
||||
const rowToGroupIndexRef = useRef(rowToGroupIndex);
|
||||
rowToGroupIndexRef.current = rowToGroupIndex;
|
||||
const groupFirstRowRef = useRef(groupFirstRow);
|
||||
groupFirstRowRef.current = groupFirstRow;
|
||||
const rowToGroupIndexRef = useRef(rowToGroupIndex)
|
||||
rowToGroupIndexRef.current = rowToGroupIndex
|
||||
const groupFirstRowRef = useRef(groupFirstRow)
|
||||
groupFirstRowRef.current = groupFirstRow
|
||||
|
||||
useEffect(() => {
|
||||
virtualizer.measure();
|
||||
}, [cols, virtualizer]);
|
||||
virtualizer.measure()
|
||||
}, [cols, virtualizer])
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
|
||||
// Active month = the group owning the first row still visible at the top.
|
||||
const scrollTop = el.scrollTop;
|
||||
const items = virtualizer.getVirtualItems();
|
||||
let activeRow = items.length > 0 ? items[0].index : 0;
|
||||
const scrollTop = el.scrollTop
|
||||
const items = virtualizer.getVirtualItems()
|
||||
let activeRow = items.length > 0 ? items[0].index : 0
|
||||
for (const item of items) {
|
||||
if (item.start + item.size > scrollTop + HEADER_HEIGHT / 2) {
|
||||
activeRow = item.index;
|
||||
break;
|
||||
activeRow = item.index
|
||||
break
|
||||
}
|
||||
}
|
||||
setActiveGroupIndex(rowToGroupIndexRef.current[activeRow] ?? 0);
|
||||
setActiveGroupIndex(rowToGroupIndexRef.current[activeRow] ?? 0)
|
||||
|
||||
if (scrollTop < 24) return;
|
||||
const nearBottom = scrollTop + el.clientHeight >= el.scrollHeight - 600;
|
||||
if (scrollTop < 24) return
|
||||
const nearBottom = scrollTop + el.clientHeight >= el.scrollHeight - 600
|
||||
if (nearBottom && !loadingImages && images.length < totalImages) {
|
||||
void loadMoreImages();
|
||||
void loadMoreImages()
|
||||
}
|
||||
}, [virtualizer, images.length, loadMoreImages, loadingImages, totalImages]);
|
||||
}, [virtualizer, images.length, loadMoreImages, loadingImages, totalImages])
|
||||
|
||||
useEffect(() => {
|
||||
const el = parentRef.current;
|
||||
if (!el) return;
|
||||
el.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => el.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: PointerEvent) => {
|
||||
if ((e.target as HTMLElement | null)?.closest("[data-gallery-context-menu]")) return;
|
||||
setContextMenu(null);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") setContextMenu(null);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => {
|
||||
window.removeEventListener("pointerdown", close);
|
||||
window.removeEventListener("keydown", onKey);
|
||||
};
|
||||
}, []);
|
||||
const el = parentRef.current
|
||||
if (!el) return
|
||||
el.addEventListener('scroll', handleScroll, { passive: true })
|
||||
return () => el.removeEventListener('scroll', handleScroll)
|
||||
}, [handleScroll])
|
||||
|
||||
const scrollToGroup = useCallback(
|
||||
(groupIndex: number) => {
|
||||
const row = groupFirstRowRef.current[groupIndex] ?? 0;
|
||||
virtualizer.scrollToIndex(row, { align: "start" });
|
||||
const row = groupFirstRowRef.current[groupIndex] ?? 0
|
||||
virtualizer.scrollToIndex(row, { align: 'start' })
|
||||
},
|
||||
[virtualizer],
|
||||
);
|
||||
[virtualizer]
|
||||
)
|
||||
|
||||
return (
|
||||
// Outer flex-row: fills remaining height in <main>'s flex-col, then
|
||||
// splits horizontally between the scroll area and the scrubber.
|
||||
<div className="flex flex-1 min-h-0 bg-gray-950">
|
||||
<div className="flex min-h-0 flex-1 bg-gray-950">
|
||||
{/* Scroll container — flex-1 takes all width except the scrubber */}
|
||||
<div
|
||||
ref={parentRef}
|
||||
className="relative flex-1 overflow-y-auto overflow-x-hidden min-h-0"
|
||||
>
|
||||
<div ref={parentRef} className="relative min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
|
||||
{images.length === 0 && loadingImages ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8 min-w-72">
|
||||
<div className="h-5 w-5 mx-auto rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<p className="mt-4 text-sm text-white/40 font-medium">Loading timeline</p>
|
||||
<p className="text-xs text-white/20 mt-1">Fetching results</p>
|
||||
</div>
|
||||
</div>
|
||||
<TimelineLoadingState />
|
||||
) : images.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-4 text-center px-8 absolute inset-0">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<svg
|
||||
className="h-12 w-12 mx-auto text-white/10 mb-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={0.75}
|
||||
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-white/30 font-medium">
|
||||
{imageLoadError ? "Could not load timeline" : "No media found"}
|
||||
</p>
|
||||
<p className="text-xs text-white/15 mt-1">
|
||||
{imageLoadError ?? "Add a folder to see your timeline"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<TimelineEmptyState imageLoadError={imageLoadError} />
|
||||
) : (
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
|
||||
<div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
|
||||
{virtualizer.getVirtualItems().map((virtualItem) => {
|
||||
const row = rows[virtualItem.index];
|
||||
if (!row) return null;
|
||||
const row = rows[virtualItem.index]
|
||||
if (!row) return null
|
||||
return (
|
||||
<div
|
||||
key={virtualItem.key}
|
||||
style={{
|
||||
position: "absolute",
|
||||
position: 'absolute',
|
||||
top: virtualItem.start,
|
||||
width: "100%",
|
||||
width: '100%',
|
||||
height: virtualItem.size,
|
||||
}}
|
||||
>
|
||||
{row.type === "header" ? (
|
||||
<div
|
||||
className="flex items-center gap-3 px-4"
|
||||
style={{ height: HEADER_HEIGHT }}
|
||||
>
|
||||
<span className="text-sm font-semibold text-white/80 shrink-0">
|
||||
{row.type === 'header' ? (
|
||||
<div className="flex items-center gap-3 px-4" style={{ height: HEADER_HEIGHT }}>
|
||||
<span className="shrink-0 text-sm font-semibold text-white/80">
|
||||
{row.group.label}
|
||||
</span>
|
||||
<span className="text-xs text-white/25 shrink-0 tabular-nums">
|
||||
<span className="shrink-0 text-xs text-white/25 tabular-nums">
|
||||
{row.group.images.length}
|
||||
</span>
|
||||
<div className="flex-1 h-px bg-white/[0.06]" />
|
||||
<div className="h-px flex-1 bg-white/[0.06]" />
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
display: 'grid',
|
||||
gridTemplateColumns: `repeat(${cols}, ${tileSize}px)`,
|
||||
gap: GAP,
|
||||
paddingLeft: GAP,
|
||||
paddingRight: GAP,
|
||||
paddingBottom: GAP,
|
||||
boxSizing: "border-box",
|
||||
boxSizing: 'border-box',
|
||||
}}
|
||||
>
|
||||
{row.images.map((image) => (
|
||||
@@ -315,22 +174,22 @@ export function Timeline() {
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image });
|
||||
event.preventDefault()
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{images.length > 0 && loadingImages ? (
|
||||
<div className="flex justify-center py-8">
|
||||
<div className="h-4 w-4 rounded-full border-2 border-white/20 border-t-white/60 animate-spin" />
|
||||
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -338,7 +197,7 @@ export function Timeline() {
|
||||
{/* Scrubber — flex sibling so it stays visible while the left panel scrolls */}
|
||||
{showScrubber ? (
|
||||
<div
|
||||
className="overflow-y-auto border-l border-white/[0.04] py-2 flex flex-col items-center gap-0.5"
|
||||
className="flex flex-col items-center gap-0.5 overflow-y-auto border-l border-white/[0.04] py-2"
|
||||
style={{ width: SCRUBBER_WIDTH }}
|
||||
>
|
||||
{scrubberYears.map((yearEntry) => (
|
||||
@@ -353,7 +212,7 @@ export function Timeline() {
|
||||
) : null}
|
||||
|
||||
{contextMenu ? (
|
||||
<ContextMenu
|
||||
<ImageContextMenu
|
||||
x={contextMenu.x}
|
||||
y={contextMenu.y}
|
||||
image={contextMenu.image}
|
||||
@@ -361,53 +220,5 @@ export function Timeline() {
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ScrubberYearBlockProps {
|
||||
yearEntry: ScrubberYear;
|
||||
activeGroupIndex: number;
|
||||
onScrollTo: (index: number) => void;
|
||||
}
|
||||
|
||||
function ScrubberYearBlock({ yearEntry, activeGroupIndex, onScrollTo }: ScrubberYearBlockProps) {
|
||||
const isYearActive = yearEntry.months.some((m) => m.groupIndex === activeGroupIndex);
|
||||
|
||||
return (
|
||||
<div className="w-full flex flex-col items-center">
|
||||
<Tooltip label={yearEntry.year} anchorToCursor>
|
||||
<button
|
||||
className={`w-full text-center py-0.5 text-[10px] font-semibold tracking-wide transition-colors ${
|
||||
isYearActive ? "text-white/80" : "text-white/30 hover:text-white/55"
|
||||
}`}
|
||||
onClick={() => onScrollTo(yearEntry.firstGroupIndex)}
|
||||
>
|
||||
{yearEntry.year}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<div
|
||||
className="grid gap-[3px] pb-1.5"
|
||||
style={{ gridTemplateColumns: "repeat(3, 10px)" }}
|
||||
>
|
||||
{Array.from({ length: 12 }, (_, i) => {
|
||||
const monthNum = i + 1;
|
||||
const monthEntry = yearEntry.months.find((m) => m.monthNum === monthNum);
|
||||
const isActive = monthEntry !== undefined && monthEntry.groupIndex === activeGroupIndex;
|
||||
if (!monthEntry) {
|
||||
return <span key={monthNum} className="h-[10px] w-[10px]" />;
|
||||
}
|
||||
return (
|
||||
<Tooltip key={monthNum} label={`${monthEntry.label} ${yearEntry.year}`} anchorToCursor>
|
||||
<button
|
||||
onClick={() => onScrollTo(monthEntry.groupIndex)}
|
||||
className={`h-[10px] w-[10px] rounded-full transition-colors ${
|
||||
isActive ? "bg-white/70" : "bg-white/15 hover:bg-white/40"
|
||||
}`}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
+119
-48
@@ -1,8 +1,19 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { PhokusMark } from "./PhokusMark";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { useGalleryStore, AppTheme } from '../store'
|
||||
import { ContextMenu, MenuItem, MenuLabel } from './menu'
|
||||
import { PhokusMark } from './PhokusMark'
|
||||
import { Tooltip } from './Tooltip'
|
||||
|
||||
const THEME_LABELS: Record<AppTheme, string> = {
|
||||
phokus: 'Phokus',
|
||||
'subtle-light': 'Subtle Light',
|
||||
'conventional-dark': 'Conventional Dark',
|
||||
}
|
||||
const THEME_OPTIONS = (Object.keys(THEME_LABELS) as AppTheme[]).map((value) => ({
|
||||
value,
|
||||
label: THEME_LABELS[value],
|
||||
}))
|
||||
|
||||
// SVG icons for window controls
|
||||
function MinimizeIcon() {
|
||||
@@ -10,7 +21,7 @@ function MinimizeIcon() {
|
||||
<svg width="10" height="2" viewBox="0 0 10 2" fill="none">
|
||||
<rect y="0.5" width="10" height="1" rx="0.5" fill="currentColor" />
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function MaximizeIcon() {
|
||||
@@ -18,16 +29,25 @@ function MaximizeIcon() {
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<rect x="0.5" y="0.5" width="9" height="9" rx="1.5" stroke="currentColor" strokeWidth="1" />
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function RestoreIcon() {
|
||||
return (
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<rect x="2.5" y="0.5" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1" />
|
||||
<rect x="0.5" y="2.5" width="7" height="7" rx="1.5" stroke="currentColor" strokeWidth="1" fill="var(--color-gray-950)" />
|
||||
<rect
|
||||
x="0.5"
|
||||
y="2.5"
|
||||
width="7"
|
||||
height="7"
|
||||
rx="1.5"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
fill="var(--color-gray-950)"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
function CloseIcon() {
|
||||
@@ -35,38 +55,52 @@ function CloseIcon() {
|
||||
<svg width="10" height="10" viewBox="0 0 10 10" fill="none">
|
||||
<path d="M1 1L9 9M9 1L1 9" stroke="currentColor" strokeWidth="1.25" strokeLinecap="round" />
|
||||
</svg>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export function TitleBar() {
|
||||
const [isMaximized, setIsMaximized] = useState(false);
|
||||
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen);
|
||||
const updateStatus = useGalleryStore((state) => state.updateStatus);
|
||||
const updateVersion = useGalleryStore((state) => state.updateVersion);
|
||||
const installUpdate = useGalleryStore((state) => state.installUpdate);
|
||||
const appWindow = getCurrentWindow();
|
||||
const [isMaximized, setIsMaximized] = useState(false)
|
||||
const setSettingsOpen = useGalleryStore((state) => state.setSettingsOpen)
|
||||
const theme = useGalleryStore((state) => state.theme)
|
||||
const setTheme = useGalleryStore((state) => state.setTheme)
|
||||
const updateStatus = useGalleryStore((state) => state.updateStatus)
|
||||
const updateVersion = useGalleryStore((state) => state.updateVersion)
|
||||
const installUpdate = useGalleryStore((state) => state.installUpdate)
|
||||
const appWindow = getCurrentWindow()
|
||||
|
||||
// Right-clicking the settings cog opens a quick theme switcher, anchored under
|
||||
// the cog so it never overflows the right edge of the window.
|
||||
const settingsBtnRef = useRef<HTMLButtonElement>(null)
|
||||
const [themeMenu, setThemeMenu] = useState<{ x: number; y: number } | null>(null)
|
||||
|
||||
const handleSettingsContextMenu = (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
const rect = settingsBtnRef.current?.getBoundingClientRect()
|
||||
if (!rect) return
|
||||
setThemeMenu({ x: rect.right, y: rect.bottom + 4 })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Get initial maximized state
|
||||
appWindow.isMaximized().then(setIsMaximized);
|
||||
appWindow.isMaximized().then(setIsMaximized)
|
||||
|
||||
// Listen for resize events to update maximized state
|
||||
const unlisten = appWindow.onResized(() => {
|
||||
appWindow.isMaximized().then(setIsMaximized);
|
||||
});
|
||||
appWindow.isMaximized().then(setIsMaximized)
|
||||
})
|
||||
|
||||
return () => {
|
||||
unlisten.then((fn) => fn());
|
||||
};
|
||||
}, []);
|
||||
unlisten.then((fn) => fn())
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleMinimize = () => appWindow.minimize();
|
||||
const handleMaximize = () => appWindow.toggleMaximize();
|
||||
const handleClose = () => appWindow.close();
|
||||
const handleMinimize = () => appWindow.minimize()
|
||||
const handleMaximize = () => appWindow.toggleMaximize()
|
||||
const handleClose = () => appWindow.close()
|
||||
|
||||
// An update is waiting for the user to act. Covers the "clicked Later" case too,
|
||||
// since dismissing the toast doesn't change updateStatus.
|
||||
const updatePending = updateStatus === "available";
|
||||
const updatePending = updateStatus === 'available'
|
||||
|
||||
return (
|
||||
// data-tauri-drag-region is the recommended Tauri approach for drag regions.
|
||||
@@ -74,31 +108,34 @@ export function TitleBar() {
|
||||
<div
|
||||
data-tauri-drag-region
|
||||
className="titlebar relative z-50 flex h-9 shrink-0 items-center bg-gray-950 select-none"
|
||||
style={{ WebkitAppRegion: "drag" } as React.CSSProperties}
|
||||
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
|
||||
>
|
||||
{/* App icon + name — left side. When an update is waiting, the iris lights
|
||||
up its focal point and the chip becomes a button that re-opens the prompt. */}
|
||||
<div className="flex items-center gap-2 pl-3 pr-4">
|
||||
<div className="flex items-center gap-2 pr-4 pl-3">
|
||||
{updatePending ? (
|
||||
<div style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>
|
||||
<div
|
||||
className="flex h-5 w-5 items-center justify-center"
|
||||
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
|
||||
>
|
||||
{/* Instant tooltip (delay 0) — this affordance should read immediately. */}
|
||||
<Tooltip label={`Click to update — v${updateVersion}`} delay={0} align="start">
|
||||
<button
|
||||
onClick={() => void installUpdate()}
|
||||
aria-label={`Update available — click to update to Phokus v${updateVersion}`}
|
||||
className="relative flex h-5 w-5 items-center justify-center 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 overflow-hidden rounded-md bg-white/8 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 top-1/2 left-1/2 h-3 w-3 -translate-x-1/2 -translate-y-1/2 animate-ping rounded-full bg-amber-400/60" />
|
||||
<PhokusMark className="relative h-4 w-4" dotClassName="fill-amber-400" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex h-5 w-5 items-center justify-center rounded-md bg-white/8 overflow-hidden text-gray-300">
|
||||
<div className="flex h-5 w-5 items-center justify-center overflow-hidden rounded-md bg-white/8 text-gray-300">
|
||||
<PhokusMark className="h-4 w-4" />
|
||||
</div>
|
||||
)}
|
||||
<span className="text-[11px] font-semibold text-gray-400 tracking-wide">Phokus</span>
|
||||
<span className="text-[11px] font-semibold tracking-wide text-gray-400">Phokus</span>
|
||||
</div>
|
||||
|
||||
{/* Spacer — draggable region fills here */}
|
||||
@@ -106,20 +143,33 @@ export function TitleBar() {
|
||||
|
||||
{/* Window control buttons — right side, non-draggable */}
|
||||
<div
|
||||
className="flex items-stretch h-full"
|
||||
style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
|
||||
className="flex h-full items-stretch"
|
||||
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
|
||||
>
|
||||
<button
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
title="Settings"
|
||||
className="group flex h-full w-10 items-center justify-center text-gray-600 transition-colors duration-100 hover:bg-white/6 hover:text-gray-300"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.607 2.296.07 2.572-1.065z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.8} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<Tooltip label="Settings (right-click to switch theme)" anchorToCursor>
|
||||
<button
|
||||
ref={settingsBtnRef}
|
||||
aria-label="Settings"
|
||||
onClick={() => setSettingsOpen(true)}
|
||||
onContextMenu={handleSettingsContextMenu}
|
||||
className="group flex h-full w-10 items-center justify-center text-gray-600 transition-colors duration-100 hover:bg-white/6 hover:text-gray-300"
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.8}
|
||||
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.607 2.296.07 2.572-1.065z"
|
||||
/>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.8}
|
||||
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/* Minimize */}
|
||||
<button
|
||||
onClick={handleMinimize}
|
||||
@@ -132,7 +182,7 @@ export function TitleBar() {
|
||||
{/* Maximize / Restore */}
|
||||
<button
|
||||
onClick={handleMaximize}
|
||||
title={isMaximized ? "Restore" : "Maximize"}
|
||||
title={isMaximized ? 'Restore' : 'Maximize'}
|
||||
className="group flex h-full w-10 items-center justify-center text-gray-600 transition-colors duration-100 hover:bg-white/6 hover:text-gray-300"
|
||||
>
|
||||
{isMaximized ? <RestoreIcon /> : <MaximizeIcon />}
|
||||
@@ -147,6 +197,27 @@ export function TitleBar() {
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Quick theme switcher — opened by right-clicking the settings cog. */}
|
||||
{themeMenu && (
|
||||
<ContextMenu
|
||||
x={themeMenu.x}
|
||||
y={themeMenu.y}
|
||||
size="sm"
|
||||
align="end"
|
||||
onClose={() => setThemeMenu(null)}
|
||||
>
|
||||
<MenuLabel>Theme</MenuLabel>
|
||||
{THEME_OPTIONS.map((opt) => (
|
||||
<MenuItem
|
||||
key={opt.value}
|
||||
label={opt.label}
|
||||
checked={theme === opt.value}
|
||||
onSelect={() => setTheme(opt.value)}
|
||||
/>
|
||||
))}
|
||||
</ContextMenu>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
+15
-484
@@ -1,493 +1,24 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { tileSizeForZoom, useGalleryStore, SortOrder, MediaFilter, SearchCommand, parseSearchValue, searchModeLabel, ExploreTagEntry } from "../store";
|
||||
import { FolderScopeDropdown } from "./FolderScopeDropdown";
|
||||
import { ColorFilter } from "./ColorFilter";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
|
||||
const BASE_SORT_OPTIONS: { value: SortOrder; label: string }[] = [
|
||||
{ value: "date_desc", label: "Newest first" },
|
||||
{ value: "date_asc", label: "Oldest first" },
|
||||
{ value: "taken_desc", label: "Taken: newest" },
|
||||
{ value: "taken_asc", label: "Taken: oldest" },
|
||||
{ value: "name_asc", label: "Name A–Z" },
|
||||
{ value: "name_desc", label: "Name Z–A" },
|
||||
{ value: "rating_desc", label: "Highest rated" },
|
||||
{ value: "rating_asc", label: "Lowest rated" },
|
||||
{ value: "size_desc", label: "Largest first" },
|
||||
{ value: "size_asc", label: "Smallest first" },
|
||||
];
|
||||
|
||||
const VIDEO_SORT_OPTIONS: { value: SortOrder; label: string }[] = [
|
||||
{ value: "duration_desc", label: "Longest first" },
|
||||
{ value: "duration_asc", label: "Shortest first" },
|
||||
];
|
||||
|
||||
function getSortOptions(mediaFilter: MediaFilter) {
|
||||
if (mediaFilter === "video") {
|
||||
return [...BASE_SORT_OPTIONS, ...VIDEO_SORT_OPTIONS];
|
||||
}
|
||||
return BASE_SORT_OPTIONS;
|
||||
}
|
||||
|
||||
function SortDropdown({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
}: {
|
||||
value: SortOrder;
|
||||
onChange: (v: SortOrder) => void;
|
||||
options: { value: SortOrder; label: string }[];
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const current = options.find((o) => o.value === value) ?? BASE_SORT_OPTIONS[0];
|
||||
|
||||
useEffect(() => {
|
||||
const close = (e: MouseEvent) => {
|
||||
if (!ref.current?.contains(e.target as Node)) setOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative">
|
||||
<button
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className={`flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs transition-colors ${
|
||||
open
|
||||
? "border-white/15 bg-white/8 text-white light-theme:border-gray-700/50 light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "border-white/8 bg-transparent text-gray-400 hover:border-white/15 hover:text-gray-200 light-theme:border-gray-700/40 light-theme:text-gray-600 light-theme:hover:border-gray-700 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<span>{current?.label ?? "Sort"}</span>
|
||||
<svg
|
||||
className={`h-3 w-3 text-gray-500 transition-transform duration-150 ${open ? "rotate-180" : ""}`}
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="absolute right-0 top-full z-30 mt-1.5 min-w-44 rounded-xl border border-white/10 bg-gray-950/98 p-1 shadow-2xl backdrop-blur light-theme:border-gray-700/50">
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={option.value}
|
||||
className={`flex w-full items-center justify-between rounded-lg px-3 py-2 text-left text-sm transition-colors ${
|
||||
option.value === value
|
||||
? "bg-white/6 text-white light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "text-gray-400 hover:bg-white/5 hover:text-white light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => { onChange(option.value); setOpen(false); }}
|
||||
>
|
||||
{option.label}
|
||||
{option.value === value ? (
|
||||
<svg className="h-3.5 w-3.5 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
) : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FilterPill({
|
||||
label,
|
||||
active,
|
||||
onClick,
|
||||
variant = "default",
|
||||
}: {
|
||||
label: string;
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
variant?: "default" | "amber";
|
||||
}) {
|
||||
const activeClass =
|
||||
variant === "amber"
|
||||
? "bg-amber-500/15 text-amber-300 border border-amber-500/30 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:border-amber-500/50"
|
||||
: "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white";
|
||||
return (
|
||||
<button
|
||||
className={`shrink-0 whitespace-nowrap rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-150 ${
|
||||
active
|
||||
? activeClass
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function commandPrefix(command: SearchCommand | null): string | null {
|
||||
switch (command) {
|
||||
case "semantic":
|
||||
return "/s";
|
||||
case "tag":
|
||||
return "/t";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function composeSearchValue(command: SearchCommand | null, query: string): string {
|
||||
const prefix = commandPrefix(command);
|
||||
if (!prefix) return query;
|
||||
return query.length > 0 ? `${prefix} ${query}` : prefix;
|
||||
}
|
||||
import { SortControl } from './toolbar/SortControl'
|
||||
import { ToolbarFilters } from './toolbar/ToolbarFilters'
|
||||
import { ToolbarSearch } from './toolbar/ToolbarSearch'
|
||||
import { ToolbarTitle } from './toolbar/ToolbarTitle'
|
||||
import { useToolbarSearch } from './toolbar/useToolbarSearch'
|
||||
import { ZoomControl } from './toolbar/ZoomControl'
|
||||
|
||||
export function Toolbar() {
|
||||
const search = useGalleryStore((state) => state.search);
|
||||
const setSearch = useGalleryStore((state) => state.setSearch);
|
||||
const clearSearch = useGalleryStore((state) => state.clearSearch);
|
||||
const sort = useGalleryStore((state) => state.sort);
|
||||
const setSort = useGalleryStore((state) => state.setSort);
|
||||
const totalImages = useGalleryStore((state) => state.totalImages);
|
||||
const loadedCount = useGalleryStore((state) => state.loadedCount);
|
||||
const selectedFolderId = useGalleryStore((state) => state.selectedFolderId);
|
||||
const collectionTitle = useGalleryStore((state) => state.collectionTitle);
|
||||
const folders = useGalleryStore((state) => state.folders);
|
||||
const mediaFilter = useGalleryStore((state) => state.mediaFilter);
|
||||
const setMediaFilter = useGalleryStore((state) => state.setMediaFilter);
|
||||
const favoritesOnly = useGalleryStore((state) => state.favoritesOnly);
|
||||
const setFavoritesOnly = useGalleryStore((state) => state.setFavoritesOnly);
|
||||
const minimumRating = useGalleryStore((state) => state.minimumRating);
|
||||
const setMinimumRating = useGalleryStore((state) => state.setMinimumRating);
|
||||
const failedEmbeddingsOnly = useGalleryStore((state) => state.failedEmbeddingsOnly);
|
||||
const setFailedEmbeddingsOnly = useGalleryStore((state) => state.setFailedEmbeddingsOnly);
|
||||
const failedTaggingOnly = useGalleryStore((state) => state.failedTaggingOnly);
|
||||
const setFailedTaggingOnly = useGalleryStore((state) => state.setFailedTaggingOnly);
|
||||
const colorFilter = useGalleryStore((state) => state.colorFilter);
|
||||
const setColorFilter = useGalleryStore((state) => state.setColorFilter);
|
||||
const similarScope = useGalleryStore((state) => state.similarScope);
|
||||
const setSimilarScope = useGalleryStore((state) => state.setSimilarScope);
|
||||
const similarSourceAlbumId = useGalleryStore((state) => state.similarSourceAlbumId);
|
||||
const mediaJobProgress = useGalleryStore((state) => state.mediaJobProgress);
|
||||
const zoomPreset = useGalleryStore((state) => state.zoomPreset);
|
||||
const setZoomPreset = useGalleryStore((state) => state.setZoomPreset);
|
||||
const activeView = useGalleryStore((state) => state.activeView);
|
||||
|
||||
const hasAnyFailedEmbeddings = Object.values(mediaJobProgress).some((p) => p.embedding_failed > 0);
|
||||
const hasAnyFailedTagging = Object.values(mediaJobProgress).some((p) => p.tagging_failed > 0);
|
||||
|
||||
const [searchCommand, setSearchCommand] = useState<SearchCommand | null>(null);
|
||||
const [searchQuery, setSearchQuery] = useState(search);
|
||||
const [searchPanelOpen, setSearchPanelOpen] = useState(false);
|
||||
const [tagSuggestions, setTagSuggestions] = useState<ExploreTagEntry[]>([]);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const suggestDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const searchInputRef = useRef<HTMLInputElement>(null);
|
||||
const searchShellRef = useRef<HTMLDivElement>(null);
|
||||
const userHasTyped = useRef(false);
|
||||
|
||||
const selectedFolder = folders.find((folder) => folder.id === selectedFolderId);
|
||||
const title = collectionTitle ?? (selectedFolder ? selectedFolder.name : "All Media");
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
const sortOptions = getSortOptions(mediaFilter);
|
||||
const hasActiveSearch = search.trim().length > 0;
|
||||
const parsedSearch = parseSearchValue(composeSearchValue(searchCommand, searchQuery));
|
||||
const isSimilarResults = collectionTitle === "Similar Images";
|
||||
// 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
|
||||
useEffect(() => {
|
||||
if (mediaFilter !== "video" && (sort === "duration_asc" || sort === "duration_desc")) {
|
||||
setSort("date_desc");
|
||||
}
|
||||
}, [mediaFilter, sort, setSort]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!userHasTyped.current) return;
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => { setSearch(composeSearchValue(searchCommand, searchQuery)); }, 200);
|
||||
return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
|
||||
}, [searchCommand, searchQuery, setSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
const parsed = parseSearchValue(search);
|
||||
setSearchCommand(parsed.prefix && parsed.mode !== "filename" ? parsed.mode : null);
|
||||
setSearchQuery(parsed.prefix ? parsed.query : search);
|
||||
}, [search]);
|
||||
|
||||
// Fetch tag suggestions when in tag mode
|
||||
useEffect(() => {
|
||||
if (searchCommand !== "tag") {
|
||||
setTagSuggestions([]);
|
||||
return;
|
||||
}
|
||||
if (suggestDebounceRef.current) clearTimeout(suggestDebounceRef.current);
|
||||
suggestDebounceRef.current = setTimeout(async () => {
|
||||
try {
|
||||
const results = await invoke<ExploreTagEntry[]>("search_tags_autocomplete", {
|
||||
params: { query: searchQuery.trim(), folder_id: selectedFolderId ?? null, limit: 10 },
|
||||
});
|
||||
setTagSuggestions(Array.isArray(results) ? results : []);
|
||||
} catch {
|
||||
setTagSuggestions([]);
|
||||
}
|
||||
}, 120);
|
||||
return () => { if (suggestDebounceRef.current) clearTimeout(suggestDebounceRef.current); };
|
||||
}, [searchCommand, searchQuery, selectedFolderId]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
const activeElement = document.activeElement;
|
||||
const searchFocused = activeElement === searchInputRef.current;
|
||||
if (event.key === "Escape" && (searchFocused || hasActiveSearch)) {
|
||||
event.preventDefault();
|
||||
setSearchCommand(null);
|
||||
setSearchQuery("");
|
||||
clearSearch();
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [clearSearch, hasActiveSearch]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = (event: PointerEvent) => {
|
||||
if (searchShellRef.current?.contains(event.target as Node)) return;
|
||||
setSearchPanelOpen(false);
|
||||
};
|
||||
window.addEventListener("pointerdown", close);
|
||||
return () => window.removeEventListener("pointerdown", close);
|
||||
}, []);
|
||||
|
||||
const showTagSuggestions = searchCommand === "tag" && searchPanelOpen;
|
||||
const showCommandHints = !searchCommand && searchPanelOpen;
|
||||
const searchState = useToolbarSearch()
|
||||
|
||||
return (
|
||||
<div className="relative z-40 shrink-0 border-b border-white/[0.06] bg-gray-950/80 backdrop-blur-xl">
|
||||
{/* Primary row */}
|
||||
<div className="flex items-center gap-2 px-3 h-12 lg:gap-3 lg:px-5">
|
||||
{/* Title + count */}
|
||||
<div className="flex items-baseline gap-2.5 min-w-0 shrink-0">
|
||||
<h2 className="text-[15px] font-semibold text-white truncate max-w-32 lg:max-w-48">{title}</h2>
|
||||
<span className="text-xs text-gray-600 shrink-0">
|
||||
{loadedCount < totalImages
|
||||
? `${loadedCount.toLocaleString()} / ${totalImages.toLocaleString()}`
|
||||
: totalImages.toLocaleString()}
|
||||
</span>
|
||||
{hasActiveSearch && (
|
||||
<span className="rounded-md border border-blue-500/20 bg-blue-500/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] text-blue-300 shrink-0">
|
||||
{searchModeLabel(parsedSearch.mode)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{activeView === "timeline" ? <FolderScopeDropdown /> : null}
|
||||
|
||||
<div className="flex h-12 items-center gap-2 px-3 lg:gap-3 lg:px-5">
|
||||
<ToolbarTitle parsedSearch={searchState.parsedSearch} />
|
||||
<div className="flex-1" />
|
||||
|
||||
{/* Search */}
|
||||
<div ref={searchShellRef} className="relative">
|
||||
<div className="flex items-center rounded-lg border border-white/8 bg-white/5 overflow-hidden">
|
||||
<div className="relative">
|
||||
<svg className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-gray-600"
|
||||
fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
|
||||
d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z" />
|
||||
</svg>
|
||||
<input
|
||||
ref={searchInputRef}
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(event) => {
|
||||
userHasTyped.current = true;
|
||||
const nextValue = event.target.value;
|
||||
if (!searchCommand) {
|
||||
const parsed = parseSearchValue(nextValue);
|
||||
if (parsed.prefix) {
|
||||
setSearchCommand(parsed.mode === "filename" ? null : parsed.mode);
|
||||
setSearchQuery(parsed.query);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setSearchQuery(nextValue);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Backspace" && searchQuery.length === 0 && searchCommand !== null) {
|
||||
event.preventDefault();
|
||||
setSearchCommand(null);
|
||||
}
|
||||
}}
|
||||
onFocus={() => setSearchPanelOpen(true)}
|
||||
placeholder="Search files, or use /s /t"
|
||||
className={`w-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 ? (
|
||||
<div className="absolute left-8 top-1/2 -translate-y-1/2">
|
||||
<button
|
||||
type="button"
|
||||
className="rounded-md border border-white/10 bg-white/[0.05] px-1.5 py-0.5 font-mono text-[11px] text-gray-300 transition-colors hover:bg-white/[0.08] hover:text-white"
|
||||
onClick={() => { setSearchCommand(null); setTagSuggestions([]); }}
|
||||
title="Remove search command"
|
||||
>
|
||||
{commandPrefix(searchCommand)}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{searchQuery.trim().length > 0 || searchCommand !== null ? (
|
||||
<button
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 rounded-md p-1 text-gray-500 hover:bg-white/5 hover:text-gray-200 transition-colors"
|
||||
title="Clear search"
|
||||
onClick={() => {
|
||||
setSearchCommand(null);
|
||||
setSearchQuery("");
|
||||
setTagSuggestions([]);
|
||||
clearSearch();
|
||||
}}
|
||||
>
|
||||
<svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tag autocomplete suggestions */}
|
||||
{showTagSuggestions && tagSuggestions.length > 0 ? (
|
||||
<div className="absolute left-0 top-full z-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) => (
|
||||
<button
|
||||
key={entry.tag}
|
||||
className="flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors hover:bg-white/[0.05]"
|
||||
onMouseDown={(e) => {
|
||||
// mousedown fires before input blur, so we prevent losing focus
|
||||
e.preventDefault();
|
||||
userHasTyped.current = true;
|
||||
setSearchQuery(entry.tag);
|
||||
setSearch(`/t ${entry.tag}`);
|
||||
setSearchPanelOpen(false);
|
||||
searchInputRef.current?.blur();
|
||||
}}
|
||||
>
|
||||
<span className="text-sm text-white/88">{entry.tag}</span>
|
||||
<span className="shrink-0 text-[11px] tabular-nums text-white/30">{entry.count.toLocaleString()}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Tag mode with no suggestions yet — show a brief hint */}
|
||||
{showTagSuggestions && tagSuggestions.length === 0 && searchQuery.trim().length > 0 ? (
|
||||
<div className="absolute left-0 top-full z-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>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Semantic mode hint */}
|
||||
{searchCommand === "semantic" && searchPanelOpen ? (
|
||||
<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>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Command hints — only shown when no command is active */}
|
||||
{showCommandHints ? (
|
||||
<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 user and AI tags" },
|
||||
{ command: "semantic" as SearchCommand, prefix: "/s", label: "Semantic", description: "Search by meaning, object, mood" },
|
||||
] as const
|
||||
).map((option) => (
|
||||
<button
|
||||
key={option.prefix}
|
||||
className="flex w-full items-center gap-3 px-3 py-2 text-left transition-colors hover:bg-white/[0.05]"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
userHasTyped.current = true;
|
||||
setSearchCommand(option.command);
|
||||
searchInputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
<span className="rounded border border-white/10 bg-white/[0.04] px-1.5 py-0.5 font-mono text-[11px] text-gray-400">
|
||||
{option.prefix}
|
||||
</span>
|
||||
<div>
|
||||
<p className="text-sm text-gray-200">{option.label}</p>
|
||||
<p className="text-xs text-gray-500">{option.description}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Sort */}
|
||||
<SortDropdown value={sort} onChange={setSort} options={sortOptions} />
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-4 w-px bg-white/10 shrink-0" />
|
||||
|
||||
{/* Zoom */}
|
||||
<div className="flex items-center rounded-lg border border-white/8 overflow-hidden light-theme:border-gray-700/40">
|
||||
{(["compact", "comfortable", "detail"] as const).map((preset, i) => (
|
||||
<Tooltip key={preset} label={`${tileSize}px tiles`} followCursor>
|
||||
<button
|
||||
className={`px-2.5 py-1.5 text-xs font-medium transition-colors ${
|
||||
i > 0 ? "border-l border-white/8" : ""
|
||||
} ${
|
||||
zoomPreset === preset
|
||||
? "bg-white/10 text-white light-theme:bg-gray-900 light-theme:text-white"
|
||||
: "text-gray-500 hover:text-gray-200 hover:bg-white/5 light-theme:text-gray-600 light-theme:hover:bg-gray-900 light-theme:hover:text-white"
|
||||
}`}
|
||||
onClick={() => setZoomPreset(preset)}
|
||||
>
|
||||
{preset === "compact" ? "S" : preset === "comfortable" ? "M" : "L"}
|
||||
</button>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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 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="Videos" active={mediaFilter === "video" && !favoritesOnly && !failedEmbeddingsOnly && !failedTaggingOnly} onClick={() => { setMediaFilter("video"); setFavoritesOnly(false); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Favorites" active={favoritesOnly} onClick={() => { setFavoritesOnly(!favoritesOnly); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="Rated" active={minimumRating === 1} onClick={() => { setMinimumRating(minimumRating === 1 ? 0 : 1); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
<FilterPill label="4★+" active={minimumRating === 4} onClick={() => { setMinimumRating(minimumRating === 4 ? 0 : 4); setFailedEmbeddingsOnly(false); setFailedTaggingOnly(false); }} />
|
||||
{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: All" active={similarScope === "all_media"} onClick={() => setSimilarScope("all_media")} />
|
||||
{hasAnyFailedEmbeddings ? (
|
||||
<FilterPill
|
||||
label="Failed Embeddings"
|
||||
active={failedEmbeddingsOnly}
|
||||
variant="amber"
|
||||
onClick={() => setFailedEmbeddingsOnly(!failedEmbeddingsOnly)}
|
||||
/>
|
||||
) : null}
|
||||
{hasAnyFailedTagging ? (
|
||||
<FilterPill
|
||||
label="Failed Tags"
|
||||
active={failedTaggingOnly}
|
||||
variant="amber"
|
||||
onClick={() => setFailedTaggingOnly(!failedTaggingOnly)}
|
||||
/>
|
||||
) : null}
|
||||
{isSimilarResults ? <span className="ml-2 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 />
|
||||
<ToolbarSearch searchState={searchState} />
|
||||
<SortControl />
|
||||
<div className="h-4 w-px shrink-0 bg-white/10" />
|
||||
<ZoomControl />
|
||||
</div>
|
||||
<ToolbarFilters />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
+89
-74
@@ -1,22 +1,23 @@
|
||||
import { MouseEvent, ReactNode, useEffect, useRef, useState } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { motion } from "framer-motion";
|
||||
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";
|
||||
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}`;
|
||||
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`;
|
||||
'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
|
||||
@@ -27,90 +28,98 @@ const STATIC_CLASSES = `${BASE_CLASSES} transition-opacity duration-100`;
|
||||
export function Tooltip({
|
||||
label,
|
||||
delay = 400,
|
||||
side = "bottom",
|
||||
align = "center",
|
||||
side = 'bottom',
|
||||
align = 'center',
|
||||
block = false,
|
||||
anchorToCursor = false,
|
||||
followCursor = false,
|
||||
className = "",
|
||||
disabled = false,
|
||||
className = '',
|
||||
children,
|
||||
}: {
|
||||
label: ReactNode;
|
||||
label: ReactNode
|
||||
/** Milliseconds the pointer must hover before the tooltip appears (0 = instant). */
|
||||
delay?: number;
|
||||
side?: TooltipSide;
|
||||
delay?: number
|
||||
side?: TooltipSide
|
||||
/** Horizontal alignment for top/bottom tooltips. */
|
||||
align?: TooltipAlign;
|
||||
align?: TooltipAlign
|
||||
/** Full-width block wrapper (e.g. wrapping a grid cell) instead of inline. */
|
||||
block?: boolean;
|
||||
block?: boolean
|
||||
/** Position at the cursor when shown, without following subsequent movement. */
|
||||
anchorToCursor?: boolean;
|
||||
anchorToCursor?: boolean
|
||||
/** Track the cursor (fixed position) instead of anchoring to a side. */
|
||||
followCursor?: boolean;
|
||||
followCursor?: boolean
|
||||
/** Render the wrapper but suppress tooltip display. */
|
||||
disabled?: boolean
|
||||
/** Extra classes for the wrapper (e.g. layout). */
|
||||
className?: string;
|
||||
children: ReactNode;
|
||||
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);
|
||||
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;
|
||||
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;
|
||||
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 });
|
||||
};
|
||||
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;
|
||||
};
|
||||
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 (disabled) return
|
||||
clear()
|
||||
if (anchorToCursor || followCursor) place(event.clientX, event.clientY)
|
||||
if (delay <= 0) {
|
||||
setVisible(true);
|
||||
return;
|
||||
setVisible(true)
|
||||
return
|
||||
}
|
||||
timer.current = setTimeout(() => setVisible(true), delay);
|
||||
};
|
||||
timer.current = setTimeout(() => setVisible(true), delay)
|
||||
}
|
||||
const hide = () => {
|
||||
clear();
|
||||
setVisible(false);
|
||||
};
|
||||
clear()
|
||||
setVisible(false)
|
||||
}
|
||||
const move = (event: MouseEvent<HTMLElement>) => {
|
||||
if (!followCursor) return;
|
||||
const { clientX, clientY } = event;
|
||||
if (frame.current !== undefined) cancelAnimationFrame(frame.current);
|
||||
if (!followCursor) return
|
||||
const { clientX, clientY } = event
|
||||
if (frame.current !== undefined) cancelAnimationFrame(frame.current)
|
||||
frame.current = requestAnimationFrame(() => {
|
||||
frame.current = undefined;
|
||||
place(clientX, clientY);
|
||||
});
|
||||
};
|
||||
frame.current = undefined
|
||||
place(clientX, clientY)
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
return clear;
|
||||
}, []);
|
||||
setMounted(true)
|
||||
return clear
|
||||
}, [])
|
||||
|
||||
const Wrapper = block ? "div" : "span";
|
||||
useEffect(() => {
|
||||
if (disabled) hide()
|
||||
}, [disabled])
|
||||
|
||||
const Wrapper = block ? 'div' : 'span'
|
||||
const cursorTooltip = (
|
||||
<motion.span
|
||||
ref={tooltipRef}
|
||||
@@ -122,35 +131,41 @@ export function Tooltip({
|
||||
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 },
|
||||
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}`}
|
||||
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
|
||||
{disabled ? null : anchorToCursor || followCursor ? (
|
||||
mounted ? (
|
||||
createPortal(cursorTooltip, document.body)
|
||||
) : null
|
||||
) : (
|
||||
<span
|
||||
role="tooltip"
|
||||
aria-hidden={!visible}
|
||||
className={`absolute ${STATIC_CLASSES} ${positionClasses(side, align)} ${visible ? "opacity-100" : "opacity-0"}`}
|
||||
className={`absolute ${STATIC_CLASSES} ${positionClasses(side, align)} ${visible ? 'opacity-100' : 'opacity-0'}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
)}
|
||||
</Wrapper>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useGalleryStore } from "../store";
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { useGalleryStore } from '../store'
|
||||
|
||||
export function UpdateToast() {
|
||||
const updateStatus = useGalleryStore((s) => s.updateStatus);
|
||||
const updateVersion = useGalleryStore((s) => s.updateVersion);
|
||||
const updateProgress = useGalleryStore((s) => s.updateProgress);
|
||||
const updateDismissed = useGalleryStore((s) => s.updateDismissed);
|
||||
const installUpdate = useGalleryStore((s) => s.installUpdate);
|
||||
const dismissUpdate = useGalleryStore((s) => s.dismissUpdate);
|
||||
const updateStatus = useGalleryStore((s) => s.updateStatus)
|
||||
const updateVersion = useGalleryStore((s) => s.updateVersion)
|
||||
const updateProgress = useGalleryStore((s) => s.updateProgress)
|
||||
const updateDismissed = useGalleryStore((s) => s.updateDismissed)
|
||||
const installUpdate = useGalleryStore((s) => s.installUpdate)
|
||||
const dismissUpdate = useGalleryStore((s) => s.dismissUpdate)
|
||||
|
||||
const visible =
|
||||
!updateDismissed &&
|
||||
(updateStatus === "available" || updateStatus === "downloading" || updateStatus === "installing");
|
||||
(updateStatus === 'available' ||
|
||||
updateStatus === 'downloading' ||
|
||||
updateStatus === 'installing')
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
@@ -21,9 +23,9 @@ export function UpdateToast() {
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: 12 }}
|
||||
transition={{ duration: 0.18 }}
|
||||
className="fixed bottom-4 right-4 z-50 w-80 rounded-lg border border-white/10 bg-gray-900 p-4 shadow-xl"
|
||||
className="fixed right-4 bottom-4 z-50 w-80 rounded-lg border border-white/10 bg-gray-900 p-4 shadow-xl"
|
||||
>
|
||||
{updateStatus === "available" ? (
|
||||
{updateStatus === 'available' ? (
|
||||
<>
|
||||
<p className="text-sm font-medium text-white">Update available</p>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
@@ -47,14 +49,18 @@ export function UpdateToast() {
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm font-medium text-white">
|
||||
{updateStatus === "installing" ? "Installing update..." : "Downloading update..."}
|
||||
{updateStatus === 'installing' ? 'Installing update...' : 'Downloading update...'}
|
||||
</p>
|
||||
<div className="mt-3 h-1 overflow-hidden rounded-full bg-white/10">
|
||||
<div
|
||||
className={`h-full rounded-full bg-emerald-400/80 transition-[width] duration-200 ${
|
||||
updateProgress === null ? "w-full animate-pulse" : ""
|
||||
updateProgress === null ? 'w-full animate-pulse' : ''
|
||||
}`}
|
||||
style={updateProgress !== null ? { width: `${Math.round(updateProgress * 100)}%` } : undefined}
|
||||
style={
|
||||
updateProgress !== null
|
||||
? { width: `${Math.round(updateProgress * 100)}%` }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-gray-600">The app will restart when it finishes.</p>
|
||||
@@ -63,5 +69,5 @@ export function UpdateToast() {
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
+44
-436
@@ -1,456 +1,64 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useGalleryStore } from "../store";
|
||||
|
||||
const SPEED_OPTIONS = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 2];
|
||||
const CONTROLS_HIDE_DELAY_MS = 2500;
|
||||
const SEEK_STEP_SECONDS = 5;
|
||||
const VOLUME_STEP = 0.1;
|
||||
|
||||
// Session-wide playback preferences shared across player instances.
|
||||
let persistedVolume = 1;
|
||||
let persistedMuted = false;
|
||||
|
||||
function formatTime(seconds: number): string {
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
|
||||
const total = Math.floor(seconds);
|
||||
const s = total % 60;
|
||||
const m = Math.floor(total / 60) % 60;
|
||||
const h = Math.floor(total / 3600);
|
||||
if (h > 0) return `${h}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
|
||||
return `${m}:${s.toString().padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
interface BufferedRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
function ControlButton({ onClick, title, active = false, children }: {
|
||||
onClick: () => void;
|
||||
title: string;
|
||||
active?: boolean;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`rounded-md p-1.5 transition-colors ${active ? "text-white" : "text-gray-300 hover:text-white"} hover:bg-white/10`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onClick();
|
||||
}}
|
||||
title={title}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
import { VideoControls } from './videoPlayer/VideoControls'
|
||||
import { useVideoPlayer } from './videoPlayer/useVideoPlayer'
|
||||
|
||||
export function VideoPlayer({ src }: { src: string }) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const trackRef = useRef<HTMLDivElement>(null);
|
||||
const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrubbingRef = useRef(false);
|
||||
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [currentTime, setCurrentTime] = useState(0);
|
||||
const [duration, setDuration] = useState(0);
|
||||
const [buffered, setBuffered] = useState<BufferedRange[]>([]);
|
||||
const [volume, setVolume] = useState(persistedVolume);
|
||||
const [muted, setMuted] = useState(
|
||||
() => useGalleryStore.getState().lightboxAutoMute || persistedMuted,
|
||||
);
|
||||
const [playbackRate, setPlaybackRate] = useState(1);
|
||||
const [loop, setLoop] = useState(false);
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
const [controlsVisible, setControlsVisible] = useState(true);
|
||||
const [speedMenuOpen, setSpeedMenuOpen] = useState(false);
|
||||
|
||||
const speedMenuOpenRef = useRef(speedMenuOpen);
|
||||
speedMenuOpenRef.current = speedMenuOpen;
|
||||
|
||||
// ── Controls visibility ────────────────────────────────────────────────────
|
||||
const showControls = useCallback(() => {
|
||||
setControlsVisible(true);
|
||||
if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
|
||||
hideTimerRef.current = setTimeout(() => {
|
||||
const video = videoRef.current;
|
||||
if (video && !video.paused && !scrubbingRef.current && !speedMenuOpenRef.current) {
|
||||
setControlsVisible(false);
|
||||
}
|
||||
}, CONTROLS_HIDE_DELAY_MS);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ── Video element wiring ───────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
// Read playback prefs fresh for each opened video — not reactive, so a
|
||||
// settings change applies to the next video rather than the current one.
|
||||
const { lightboxAutoplay, lightboxAutoMute } = useGalleryStore.getState();
|
||||
const startMuted = lightboxAutoMute || persistedMuted;
|
||||
video.volume = persistedVolume;
|
||||
video.muted = startMuted;
|
||||
setMuted(startMuted);
|
||||
// Autoplay when enabled; if the webview blocks it the catch leaves us paused
|
||||
// with controls visible, which is a fine fallback.
|
||||
if (lightboxAutoplay) video.play().catch(() => {});
|
||||
}, [src]);
|
||||
|
||||
const readBuffered = useCallback(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !Number.isFinite(video.duration) || video.duration <= 0) return;
|
||||
const ranges: BufferedRange[] = [];
|
||||
for (let i = 0; i < video.buffered.length; i++) {
|
||||
ranges.push({
|
||||
start: video.buffered.start(i) / video.duration,
|
||||
end: video.buffered.end(i) / video.duration,
|
||||
});
|
||||
}
|
||||
setBuffered(ranges);
|
||||
}, []);
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
if (video.paused) {
|
||||
void video.play().catch(() => {});
|
||||
} else {
|
||||
video.pause();
|
||||
}
|
||||
showControls();
|
||||
}, [showControls]);
|
||||
|
||||
const seekBy = useCallback(
|
||||
(deltaSeconds: number) => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !Number.isFinite(video.duration)) return;
|
||||
video.currentTime = Math.min(video.duration, Math.max(0, video.currentTime + deltaSeconds));
|
||||
showControls();
|
||||
},
|
||||
[showControls],
|
||||
);
|
||||
|
||||
const applyVolume = useCallback(
|
||||
(nextVolume: number, nextMuted?: boolean) => {
|
||||
const video = videoRef.current;
|
||||
const clamped = Math.min(1, Math.max(0, nextVolume));
|
||||
setVolume(clamped);
|
||||
persistedVolume = clamped;
|
||||
if (nextMuted !== undefined) {
|
||||
setMuted(nextMuted);
|
||||
persistedMuted = nextMuted;
|
||||
if (video) video.muted = nextMuted;
|
||||
}
|
||||
if (video) video.volume = clamped;
|
||||
showControls();
|
||||
},
|
||||
[showControls],
|
||||
);
|
||||
|
||||
const toggleMute = useCallback(() => {
|
||||
const next = !muted;
|
||||
setMuted(next);
|
||||
persistedMuted = next;
|
||||
const video = videoRef.current;
|
||||
if (video) video.muted = next;
|
||||
showControls();
|
||||
}, [muted, showControls]);
|
||||
|
||||
const toggleLoop = useCallback(() => {
|
||||
setLoop((value) => {
|
||||
const video = videoRef.current;
|
||||
if (video) video.loop = !value;
|
||||
return !value;
|
||||
});
|
||||
showControls();
|
||||
}, [showControls]);
|
||||
|
||||
const toggleFullscreen = useCallback(() => {
|
||||
if (document.fullscreenElement) {
|
||||
void document.exitFullscreen().catch(() => {});
|
||||
} else {
|
||||
void containerRef.current?.requestFullscreen().catch(() => {});
|
||||
}
|
||||
showControls();
|
||||
}, [showControls]);
|
||||
|
||||
useEffect(() => {
|
||||
const onChange = () => setFullscreen(document.fullscreenElement !== null);
|
||||
document.addEventListener("fullscreenchange", onChange);
|
||||
return () => document.removeEventListener("fullscreenchange", onChange);
|
||||
}, []);
|
||||
|
||||
const setSpeed = useCallback(
|
||||
(rate: number) => {
|
||||
setPlaybackRate(rate);
|
||||
const video = videoRef.current;
|
||||
if (video) video.playbackRate = rate;
|
||||
setSpeedMenuOpen(false);
|
||||
showControls();
|
||||
},
|
||||
[showControls],
|
||||
);
|
||||
|
||||
// ── Scrubber ───────────────────────────────────────────────────────────────
|
||||
const seekToPointer = useCallback((clientX: number) => {
|
||||
const video = videoRef.current;
|
||||
const track = trackRef.current;
|
||||
if (!video || !track || !Number.isFinite(video.duration) || video.duration <= 0) return;
|
||||
const bounds = track.getBoundingClientRect();
|
||||
const fraction = Math.min(1, Math.max(0, (clientX - bounds.left) / bounds.width));
|
||||
video.currentTime = fraction * video.duration;
|
||||
setCurrentTime(video.currentTime);
|
||||
}, []);
|
||||
|
||||
const handleTrackPointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.stopPropagation();
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
scrubbingRef.current = true;
|
||||
seekToPointer(event.clientX);
|
||||
},
|
||||
[seekToPointer],
|
||||
);
|
||||
|
||||
const handleTrackPointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!scrubbingRef.current) return;
|
||||
seekToPointer(event.clientX);
|
||||
},
|
||||
[seekToPointer],
|
||||
);
|
||||
|
||||
const handleTrackPointerUp = useCallback((event: React.PointerEvent<HTMLDivElement>) => {
|
||||
event.currentTarget.releasePointerCapture(event.pointerId);
|
||||
scrubbingRef.current = false;
|
||||
}, []);
|
||||
|
||||
// ── Keyboard ───────────────────────────────────────────────────────────────
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (target && (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable)) {
|
||||
return;
|
||||
}
|
||||
switch (event.key) {
|
||||
case " ":
|
||||
event.preventDefault();
|
||||
togglePlay();
|
||||
break;
|
||||
case "m":
|
||||
case "M":
|
||||
toggleMute();
|
||||
break;
|
||||
case "f":
|
||||
case "F":
|
||||
toggleFullscreen();
|
||||
break;
|
||||
case "l":
|
||||
case "L":
|
||||
toggleLoop();
|
||||
break;
|
||||
case "ArrowLeft":
|
||||
if (event.shiftKey) {
|
||||
event.preventDefault();
|
||||
seekBy(-SEEK_STEP_SECONDS);
|
||||
}
|
||||
break;
|
||||
case "ArrowRight":
|
||||
if (event.shiftKey) {
|
||||
event.preventDefault();
|
||||
seekBy(SEEK_STEP_SECONDS);
|
||||
}
|
||||
break;
|
||||
case "ArrowUp":
|
||||
event.preventDefault();
|
||||
// Adjusting volume always unmutes, matching the slider behavior.
|
||||
applyVolume(persistedVolume + VOLUME_STEP, false);
|
||||
break;
|
||||
case "ArrowDown":
|
||||
event.preventDefault();
|
||||
applyVolume(persistedVolume - VOLUME_STEP, false);
|
||||
break;
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [togglePlay, toggleMute, toggleFullscreen, toggleLoop, seekBy, applyVolume]);
|
||||
|
||||
const playedFraction = duration > 0 ? currentTime / duration : 0;
|
||||
const effectiveVolume = muted ? 0 : volume;
|
||||
const player = useVideoPlayer(src)
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`media-dark-surface relative flex h-full w-full items-center justify-center bg-black ${controlsVisible ? "" : "cursor-none"}`}
|
||||
onPointerMove={showControls}
|
||||
ref={player.containerRef}
|
||||
className={`media-dark-surface relative flex h-full w-full items-center justify-center bg-black ${player.controlsVisible ? '' : 'cursor-none'}`}
|
||||
onPointerMove={player.showControls}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<video
|
||||
ref={videoRef}
|
||||
ref={player.videoRef}
|
||||
src={src}
|
||||
className="h-full w-full object-contain"
|
||||
onClick={togglePlay}
|
||||
onDoubleClick={toggleFullscreen}
|
||||
onClick={player.togglePlay}
|
||||
onDoubleClick={player.toggleFullscreen}
|
||||
onPlay={() => {
|
||||
setPlaying(true);
|
||||
showControls();
|
||||
player.setPlaying(true)
|
||||
player.showControls()
|
||||
}}
|
||||
onPause={() => {
|
||||
setPlaying(false);
|
||||
setControlsVisible(true);
|
||||
player.setPlaying(false)
|
||||
player.setControlsVisible(true)
|
||||
}}
|
||||
onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)}
|
||||
onTimeUpdate={(event) => player.setCurrentTime(event.currentTarget.currentTime)}
|
||||
onLoadedMetadata={(event) => {
|
||||
setDuration(event.currentTarget.duration);
|
||||
readBuffered();
|
||||
player.setDuration(event.currentTarget.duration)
|
||||
player.readBuffered()
|
||||
}}
|
||||
onDurationChange={(event) => setDuration(event.currentTarget.duration)}
|
||||
onProgress={readBuffered}
|
||||
onDurationChange={(event) => player.setDuration(event.currentTarget.duration)}
|
||||
onProgress={player.readBuffered}
|
||||
/>
|
||||
|
||||
<AnimatePresence>
|
||||
{controlsVisible ? (
|
||||
<motion.div
|
||||
className="absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/80 via-black/40 to-transparent px-4 pb-2.5 pt-12"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
>
|
||||
{/* Scrubber */}
|
||||
<div
|
||||
ref={trackRef}
|
||||
className="group/track relative flex h-4 cursor-pointer items-center"
|
||||
onPointerDown={handleTrackPointerDown}
|
||||
onPointerMove={handleTrackPointerMove}
|
||||
onPointerUp={handleTrackPointerUp}
|
||||
>
|
||||
<div className="relative h-1 w-full overflow-hidden rounded-full bg-white/15 transition-[height] group-hover/track:h-1.5">
|
||||
{buffered.map((range, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="absolute inset-y-0 bg-white/20"
|
||||
style={{ left: `${range.start * 100}%`, width: `${(range.end - range.start) * 100}%` }}
|
||||
/>
|
||||
))}
|
||||
<div className="absolute inset-y-0 left-0 bg-white/90" style={{ width: `${playedFraction * 100}%` }} />
|
||||
</div>
|
||||
<div
|
||||
className="pointer-events-none absolute h-3 w-3 -translate-x-1/2 rounded-full bg-white opacity-0 shadow transition-opacity group-hover/track:opacity-100"
|
||||
style={{ left: `${playedFraction * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Control row */}
|
||||
<div className="mt-1 flex items-center gap-1.5">
|
||||
<ControlButton onClick={togglePlay} title={playing ? "Pause (Space)" : "Play (Space)"}>
|
||||
{playing ? (
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M7 5h4v14H7zM13 5h4v14h-4z" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-5 w-5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5.14v13.72L19 12 8 5.14z" />
|
||||
</svg>
|
||||
)}
|
||||
</ControlButton>
|
||||
|
||||
<span className="ml-1 text-xs tabular-nums text-gray-300">
|
||||
{formatTime(currentTime)} <span className="text-gray-500">/ {formatTime(duration)}</span>
|
||||
</span>
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
{/* Volume */}
|
||||
<ControlButton onClick={toggleMute} title={muted ? "Unmute (M)" : "Mute (M)"}>
|
||||
{effectiveVolume === 0 ? (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M17 9l4 6m0-6l-4 6" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15.536 8.464a5 5 0 010 7.072M18.364 5.636a9 9 0 010 12.728" />
|
||||
</svg>
|
||||
)}
|
||||
</ControlButton>
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={1}
|
||||
step={0.02}
|
||||
value={effectiveVolume}
|
||||
className="h-1 w-20 cursor-pointer accent-white"
|
||||
onChange={(event) => applyVolume(parseFloat(event.target.value), false)}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
title="Volume (↑/↓)"
|
||||
/>
|
||||
|
||||
{/* Playback speed */}
|
||||
<div className="relative">
|
||||
<button
|
||||
className={`min-w-12 rounded-md px-2 py-1.5 text-xs tabular-nums transition-colors hover:bg-white/10 ${playbackRate !== 1 ? "text-white" : "text-gray-300 hover:text-white"}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setSpeedMenuOpen((value) => !value);
|
||||
}}
|
||||
title="Playback speed"
|
||||
>
|
||||
{playbackRate}×
|
||||
</button>
|
||||
{speedMenuOpen ? (
|
||||
<div className="absolute bottom-full right-0 z-20 mb-2 min-w-20 rounded-lg border border-white/10 bg-gray-950/95 p-1 shadow-2xl backdrop-blur">
|
||||
{SPEED_OPTIONS.map((rate) => (
|
||||
<button
|
||||
key={rate}
|
||||
className={`flex w-full items-center justify-between gap-2 rounded-md px-2.5 py-1.5 text-left text-xs tabular-nums transition-colors ${
|
||||
rate === playbackRate ? "bg-white/10 text-white" : "text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setSpeed(rate);
|
||||
}}
|
||||
>
|
||||
{rate}×
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Loop */}
|
||||
<ControlButton onClick={toggleLoop} title={loop ? "Loop on (L)" : "Loop off (L)"} active={loop}>
|
||||
<svg className={`h-4.5 w-4.5 ${loop ? "text-emerald-300" : ""}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 4v5h5M20 20v-5h-5M4 9a8 8 0 0114-3M20 15a8 8 0 01-14 3" />
|
||||
</svg>
|
||||
</ControlButton>
|
||||
|
||||
{/* Fullscreen */}
|
||||
<ControlButton onClick={toggleFullscreen} title={fullscreen ? "Exit fullscreen (F)" : "Fullscreen (F)"}>
|
||||
{fullscreen ? (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M9 9H4m5 0V4m6 5h5m-5 0V4M9 15H4m5 0v5m6-5h5m-5 0v5" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-4.5 w-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M4 8V4h4M20 8V4h-4M4 16v4h4M20 16v4h-4" />
|
||||
</svg>
|
||||
)}
|
||||
</ControlButton>
|
||||
</div>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
<VideoControls
|
||||
applyVolume={player.applyVolume}
|
||||
buffered={player.buffered}
|
||||
controlsVisible={player.controlsVisible}
|
||||
currentTime={player.currentTime}
|
||||
duration={player.duration}
|
||||
effectiveVolume={player.effectiveVolume}
|
||||
fullscreen={player.fullscreen}
|
||||
handleTrackPointerDown={player.handleTrackPointerDown}
|
||||
handleTrackPointerMove={player.handleTrackPointerMove}
|
||||
handleTrackPointerUp={player.handleTrackPointerUp}
|
||||
loop={player.loop}
|
||||
muted={player.muted}
|
||||
playbackRate={player.playbackRate}
|
||||
playedFraction={player.playedFraction}
|
||||
playing={player.playing}
|
||||
setSpeed={player.setSpeed}
|
||||
setSpeedMenuOpen={player.setSpeedMenuOpen}
|
||||
speedMenuOpen={player.speedMenuOpen}
|
||||
toggleFullscreen={player.toggleFullscreen}
|
||||
toggleLoop={player.toggleLoop}
|
||||
toggleMute={player.toggleMute}
|
||||
togglePlay={player.togglePlay}
|
||||
trackRef={player.trackRef}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,34 @@
|
||||
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";
|
||||
import { useEffect, useState, type ReactNode } from 'react'
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { useGalleryStore } from '../store'
|
||||
import {
|
||||
getChangelogForVersion,
|
||||
type ChangelogEntry,
|
||||
type ChangelogItem,
|
||||
type ChangelogSection,
|
||||
} from '../changelog'
|
||||
import { Tooltip } from './Tooltip'
|
||||
import { ChevronRightIcon, CloseIcon } from './icons'
|
||||
|
||||
// The modal adapts its layout to the size of the release: small releases keep
|
||||
// the compact single-column list, while big ones switch to a two-pane layout
|
||||
// with a section nav rail so no one pane is a marathon scroll. Preview both in
|
||||
// UI Lab via `?changelog=unreleased` + the demo panel's "Open What's new modal".
|
||||
type WhatsNewLayout = 'single' | 'rail'
|
||||
|
||||
// Above this many total bullets, the single column gets unpleasantly long.
|
||||
const RAIL_THRESHOLD = 20
|
||||
|
||||
function chooseLayout(entry: ChangelogEntry | null): WhatsNewLayout {
|
||||
if (!entry || entry.sections.length < 2) return 'single'
|
||||
const total = entry.sections.reduce((sum, section) => sum + section.items.length, 0)
|
||||
return total > RAIL_THRESHOLD ? 'rail' : 'single'
|
||||
}
|
||||
|
||||
// Shown in the tooltip so the user can see the link's destination before
|
||||
// clicking. The actual navigation is handled by the open_changelog_url command.
|
||||
const CHANGELOG_URL = "https://github.com/JezzWTF/phokus/blob/main/CHANGELOG.md";
|
||||
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
|
||||
@@ -15,51 +36,91 @@ const CHANGELOG_URL = "https://github.com/JezzWTF/phokus/blob/main/CHANGELOG.md"
|
||||
// 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" },
|
||||
};
|
||||
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" };
|
||||
const NEUTRAL_STYLE = { label: 'text-gray-300', dot: 'bg-gray-400/70' }
|
||||
|
||||
function sectionStyle(title: string) {
|
||||
return SECTION_STYLES[title] ?? NEUTRAL_STYLE
|
||||
}
|
||||
|
||||
// Render the small amount of inline markdown the changelog uses: **bold** and
|
||||
// `code`. Anything else passes through as plain text.
|
||||
function renderInline(text: string): ReactNode[] {
|
||||
const nodes: ReactNode[] = [];
|
||||
const regex = /\*\*(.+?)\*\*|`([^`]+)`/g;
|
||||
let lastIndex = 0;
|
||||
let key = 0;
|
||||
let match: RegExpExecArray | null;
|
||||
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));
|
||||
nodes.push(text.slice(lastIndex, match.index))
|
||||
}
|
||||
if (match[1] !== undefined) {
|
||||
nodes.push(
|
||||
<strong key={key++} className="font-semibold text-white">
|
||||
{match[1]}
|
||||
</strong>,
|
||||
);
|
||||
</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>,
|
||||
);
|
||||
</code>
|
||||
)
|
||||
}
|
||||
lastIndex = regex.lastIndex;
|
||||
lastIndex = regex.lastIndex
|
||||
}
|
||||
if (lastIndex < text.length) {
|
||||
nodes.push(text.slice(lastIndex));
|
||||
nodes.push(text.slice(lastIndex))
|
||||
}
|
||||
return nodes;
|
||||
return nodes
|
||||
}
|
||||
|
||||
function Section({ section }: { section: ChangelogSection }) {
|
||||
const style = SECTION_STYLES[section.title] ?? NEUTRAL_STYLE;
|
||||
const [open, setOpen] = useState(true);
|
||||
function Item({ item, dot }: { item: ChangelogItem; dot: string }) {
|
||||
return (
|
||||
<li className="flex gap-3">
|
||||
<span className={`mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full ${dot}`} />
|
||||
<p className="text-[13px] leading-relaxed text-gray-400">
|
||||
{item.lead ? (
|
||||
<>
|
||||
<span className="font-semibold text-gray-100">{item.lead}</span>
|
||||
{item.body ? <span> — {renderInline(item.body)}</span> : null}
|
||||
</>
|
||||
) : (
|
||||
renderInline(item.body)
|
||||
)}
|
||||
</p>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function ItemList({
|
||||
items,
|
||||
dot,
|
||||
className = '',
|
||||
}: {
|
||||
items: ChangelogItem[]
|
||||
dot: string
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<ul className={`space-y-2.5 ${className}`}>
|
||||
{items.map((item, index) => (
|
||||
<Item key={index} item={item} dot={dot} />
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleSection({ section }: { section: ChangelogSection }) {
|
||||
const style = sectionStyle(section.title)
|
||||
const [open, setOpen] = useState(true)
|
||||
|
||||
return (
|
||||
<section>
|
||||
@@ -69,65 +130,96 @@ function Section({ section }: { section: ChangelogSection }) {
|
||||
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>
|
||||
<ChevronRightIcon
|
||||
className={`h-3 w-3 shrink-0 text-gray-600 transition-transform ${open ? 'rotate-90' : ''}`}
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
<span className={`text-[11px] font-semibold tracking-[0.1em] uppercase ${style.label}`}>
|
||||
{section.title}
|
||||
</span>
|
||||
<span className="text-[11px] font-medium text-gray-600">{section.items.length}</span>
|
||||
</button>
|
||||
<AnimatePresence initial={false}>
|
||||
{open ? (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: "auto", opacity: 1 }}
|
||||
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>
|
||||
<ItemList items={section.items} dot={style.dot} className="mt-2.5 pl-5" />
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
</section>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
// 'rail' layout — a section nav rail on the left, the selected section's items
|
||||
// on the right.
|
||||
function RailSections({ sections }: { sections: ChangelogSection[] }) {
|
||||
const [active, setActive] = useState(0)
|
||||
const section = sections[Math.min(active, sections.length - 1)]
|
||||
const style = sectionStyle(section.title)
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<nav className="flex w-44 shrink-0 flex-col gap-1 border-r border-white/[0.07] px-3 py-4">
|
||||
{sections.map((s, index) => {
|
||||
const navStyle = sectionStyle(s.title)
|
||||
const isActive = index === active
|
||||
return (
|
||||
<button
|
||||
key={s.title}
|
||||
type="button"
|
||||
onClick={() => setActive(index)}
|
||||
className={`flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-[12px] font-medium transition-colors ${
|
||||
isActive
|
||||
? 'bg-white/[0.07] text-white'
|
||||
: 'text-gray-500 hover:bg-white/[0.04] hover:text-gray-300'
|
||||
}`}
|
||||
>
|
||||
<span className={`h-1.5 w-1.5 shrink-0 rounded-full ${navStyle.dot}`} />
|
||||
<span className="flex-1">{s.title}</span>
|
||||
<span className="text-[11px] font-medium text-gray-600">{s.items.length}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</nav>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
|
||||
<p className={`mb-3 text-[11px] font-semibold tracking-[0.1em] uppercase ${style.label}`}>
|
||||
{section.title}
|
||||
</p>
|
||||
<ItemList items={section.items} dot={style.dot} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const MODAL_WIDTHS: Record<WhatsNewLayout, string> = {
|
||||
single: 'w-[min(88vw,560px)]',
|
||||
rail: 'w-[min(90vw,780px)]',
|
||||
}
|
||||
|
||||
export function WhatsNewModal() {
|
||||
const whatsNewOpen = useGalleryStore((s) => s.whatsNewOpen);
|
||||
const closeWhatsNew = useGalleryStore((s) => s.closeWhatsNew);
|
||||
const appVersion = useGalleryStore((s) => s.appVersion);
|
||||
const whatsNewOpen = useGalleryStore((s) => s.whatsNewOpen)
|
||||
const closeWhatsNew = useGalleryStore((s) => s.closeWhatsNew)
|
||||
const appVersion = useGalleryStore((s) => s.appVersion)
|
||||
|
||||
const entry = getChangelogForVersion(appVersion);
|
||||
const entry = getChangelogForVersion(appVersion)
|
||||
const layout = chooseLayout(entry)
|
||||
|
||||
useEffect(() => {
|
||||
if (!whatsNewOpen) return;
|
||||
if (!whatsNewOpen) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") closeWhatsNew();
|
||||
};
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [whatsNewOpen, closeWhatsNew]);
|
||||
if (event.key === 'Escape') closeWhatsNew()
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [whatsNewOpen, closeWhatsNew])
|
||||
|
||||
const hasSections = entry !== null && entry.sections.length > 0
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
@@ -141,7 +233,7 @@ export function WhatsNewModal() {
|
||||
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"
|
||||
className={`relative flex max-h-[min(82vh,760px)] ${MODAL_WIDTHS[layout]} flex-col overflow-hidden rounded-lg border border-white/10 bg-gray-950 shadow-2xl shadow-black/60`}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
initial={{ opacity: 0, scale: 0.97, y: 8 }}
|
||||
animate={{ opacity: 1, scale: 1, y: 0 }}
|
||||
@@ -150,38 +242,48 @@ export function WhatsNewModal() {
|
||||
>
|
||||
<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>
|
||||
<p className="text-[11px] font-semibold tracking-[0.12em] text-emerald-300 uppercase">
|
||||
What's new
|
||||
</p>
|
||||
<h3 className="mt-1 text-lg font-semibold text-white">
|
||||
Phokus v{entry?.version ?? appVersion ?? "—"}
|
||||
Phokus v{entry?.version ?? appVersion ?? '—'}
|
||||
</h3>
|
||||
{entry?.date ? <p className="mt-0.5 text-xs text-gray-600">Released {entry.date}</p> : null}
|
||||
{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>
|
||||
<Tooltip label="Close" anchorToCursor>
|
||||
<button
|
||||
className="rounded-md p-1.5 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={closeWhatsNew}
|
||||
>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<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>
|
||||
{hasSections && layout === 'rail' ? (
|
||||
<RailSections sections={entry.sections} />
|
||||
) : (
|
||||
<div className="min-h-0 flex-1 space-y-6 overflow-y-auto px-6 py-5">
|
||||
{hasSections ? (
|
||||
entry.sections.map((section) => (
|
||||
<CollapsibleSection key={section.title} section={section} />
|
||||
))
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
Release notes for this version aren't available in-app. See the full changelog
|
||||
on GitHub.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between gap-4 border-t border-white/[0.07] px-6 py-4">
|
||||
<Tooltip label={CHANGELOG_URL} side="top" align="start">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void invoke("open_changelog_url")}
|
||||
onClick={() => void invoke('open_changelog_url')}
|
||||
className="text-xs text-gray-500 transition-colors hover:text-gray-300"
|
||||
>
|
||||
Full changelog ↗
|
||||
@@ -198,5 +300,5 @@ export function WhatsNewModal() {
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { AnimatePresence, motion } from "framer-motion";
|
||||
import { useGalleryStore } from "../store";
|
||||
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 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;
|
||||
const visible = whatsNewToast !== null && !whatsNewOpen
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
@@ -19,7 +19,7 @@ export function WhatsNewToast() {
|
||||
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"
|
||||
className="fixed right-4 bottom-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>
|
||||
@@ -40,5 +40,5 @@ export function WhatsNewToast() {
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CloseIcon } from '../icons'
|
||||
import type { BackgroundTask } from './types'
|
||||
|
||||
export function FailureActions({
|
||||
onLocate,
|
||||
onRetry,
|
||||
task,
|
||||
}: {
|
||||
onLocate: (folderId: number) => void
|
||||
onRetry: (task: BackgroundTask) => void
|
||||
task: BackgroundTask
|
||||
}) {
|
||||
if (task.pendingMediaWork !== 0 || (!task.hasFailedEmbeddings && !task.hasFailedTagging))
|
||||
return null
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 items-center gap-1.5">
|
||||
{task.hasFailedTagging ? (
|
||||
<button
|
||||
className="light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200 rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onLocate(task.id)
|
||||
}}
|
||||
>
|
||||
Locate
|
||||
</button>
|
||||
) : null}
|
||||
<button
|
||||
className="light-theme:border-amber-500/50 light-theme:bg-amber-100 light-theme:text-amber-700 light-theme:hover:bg-amber-200 rounded-lg border border-amber-500/20 bg-amber-500/10 px-2.5 py-1 text-[11px] text-amber-300 transition-colors hover:bg-amber-500/20"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onRetry(task)
|
||||
}}
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DismissTaskButton({
|
||||
onDismiss,
|
||||
size = 'normal',
|
||||
task,
|
||||
}: {
|
||||
onDismiss: (task: BackgroundTask) => void
|
||||
size?: 'normal' | 'small'
|
||||
task: BackgroundTask
|
||||
}) {
|
||||
if (task.id < 0) return null
|
||||
|
||||
return (
|
||||
<Tooltip label="Dismiss" anchorToCursor>
|
||||
<button
|
||||
className="shrink-0 rounded-md p-1 text-gray-600 transition-colors hover:bg-white/8 hover:text-gray-300"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onDismiss(task)
|
||||
}}
|
||||
>
|
||||
<CloseIcon className={size === 'small' ? 'h-3 w-3' : 'h-3.5 w-3.5'} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { WorkerKey } from '../../store'
|
||||
import { ChevronDownIcon } from '../icons'
|
||||
import { DismissTaskButton, FailureActions } from './BackgroundTaskActions'
|
||||
import { TaskProgressBar } from './TaskProgressBar'
|
||||
import { TaskStagePill } from './TaskStagePill'
|
||||
import type { BackgroundTask } from './types'
|
||||
|
||||
export function BackgroundTaskSummary({
|
||||
expanded,
|
||||
extraCount,
|
||||
hasFailed,
|
||||
isWorkerPaused,
|
||||
onDismiss,
|
||||
onLocate,
|
||||
onRetry,
|
||||
onToggleExpanded,
|
||||
onToggleWorker,
|
||||
primary,
|
||||
progress,
|
||||
taskCount,
|
||||
}: {
|
||||
expanded: boolean
|
||||
extraCount: number
|
||||
hasFailed: boolean
|
||||
isWorkerPaused: (folderId: number, worker: WorkerKey) => boolean
|
||||
onDismiss: (task: BackgroundTask) => void
|
||||
onLocate: (folderId: number) => void
|
||||
onRetry: (task: BackgroundTask) => void
|
||||
onToggleExpanded: () => void
|
||||
onToggleWorker: (folderId: number, worker: WorkerKey) => void
|
||||
primary: BackgroundTask
|
||||
progress: number | null
|
||||
taskCount: number
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`group flex h-11 cursor-pointer items-center gap-3 px-5 transition-colors select-none ${
|
||||
expanded ? 'bg-white/[0.03]' : 'hover:bg-white/[0.02]'
|
||||
}`}
|
||||
onClick={onToggleExpanded}
|
||||
>
|
||||
<div className="relative shrink-0">
|
||||
<div className={`h-1.5 w-1.5 rounded-full ${hasFailed ? 'bg-amber-400' : 'bg-blue-400'}`} />
|
||||
<div
|
||||
className={`absolute inset-0 h-1.5 w-1.5 animate-ping rounded-full opacity-60 ${hasFailed ? 'bg-amber-400' : 'bg-blue-400'}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span className="shrink-0 text-[13px] font-medium text-white/60">{primary.name}</span>
|
||||
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">
|
||||
{primary.stages.map((stage) => (
|
||||
<TaskStagePill
|
||||
key={stage.label}
|
||||
folderId={primary.id}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
onToggleWorker={onToggleWorker}
|
||||
stage={stage}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<TaskProgressBar failed={hasFailed} progress={progress} widthClass="w-24" />
|
||||
|
||||
{extraCount > 0 ? (
|
||||
<span className="shrink-0 rounded-full bg-white/8 px-2 py-0.5 text-[10px] text-gray-500">
|
||||
+{extraCount}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<FailureActions onLocate={onLocate} onRetry={onRetry} task={primary} />
|
||||
|
||||
{taskCount > 1 ? (
|
||||
<ChevronDownIcon
|
||||
className={`h-3.5 w-3.5 shrink-0 text-gray-600 transition-transform duration-200 ${expanded ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<DismissTaskButton onDismiss={onDismiss} task={primary} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { WorkerKey } from '../../store'
|
||||
import { DismissTaskButton, FailureActions } from './BackgroundTaskActions'
|
||||
import { FailedWorkerItemRow } from './FailedWorkerItemRow'
|
||||
import { taskHasTerminalFailure, taskProgress } from './taskModel'
|
||||
import { TaskProgressBar } from './TaskProgressBar'
|
||||
import { TaskStagePill } from './TaskStagePill'
|
||||
import type { BackgroundTask, FailedWorkerItem } from './types'
|
||||
|
||||
export function ExpandedTaskPanel({
|
||||
failedEmbeddingItems,
|
||||
failedTaggingItems,
|
||||
isWorkerPaused,
|
||||
onDismiss,
|
||||
onLocate,
|
||||
onRetry,
|
||||
onToggleWorker,
|
||||
tasks,
|
||||
}: {
|
||||
failedEmbeddingItems: Record<number, FailedWorkerItem[]>
|
||||
failedTaggingItems: Record<number, FailedWorkerItem[]>
|
||||
isWorkerPaused: (folderId: number, worker: WorkerKey) => boolean
|
||||
onDismiss: (task: BackgroundTask) => void
|
||||
onLocate: (folderId: number) => void
|
||||
onRetry: (task: BackgroundTask) => void
|
||||
onToggleWorker: (folderId: number, worker: WorkerKey) => void
|
||||
tasks: BackgroundTask[]
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-3 border-t border-white/[0.06] bg-white/[0.02] px-5 py-3">
|
||||
{tasks.map((task) => {
|
||||
const progress = taskProgress(task)
|
||||
const failed = taskHasTerminalFailure(task)
|
||||
|
||||
return (
|
||||
<div key={task.id}>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="w-28 shrink-0 truncate text-[12px] text-white/50">{task.name}</span>
|
||||
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden">
|
||||
{task.stages.map((stage) => (
|
||||
<TaskStagePill
|
||||
key={stage.label}
|
||||
folderId={task.id}
|
||||
isWorkerPaused={isWorkerPaused}
|
||||
mutedWhenPaused
|
||||
onToggleWorker={onToggleWorker}
|
||||
stage={stage}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<TaskProgressBar failed={failed} progress={progress} />
|
||||
|
||||
{failed ? <FailureActions onLocate={onLocate} onRetry={onRetry} task={task} /> : null}
|
||||
|
||||
<DismissTaskButton onDismiss={onDismiss} size="small" task={task} />
|
||||
</div>
|
||||
|
||||
{task.currentFile ? (
|
||||
<p className="mt-1 truncate pl-[calc(7rem+0.75rem)] text-[10px] text-gray-600">
|
||||
{task.currentFile}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{failed && failedEmbeddingItems[task.id] && failedEmbeddingItems[task.id].length > 0 ? (
|
||||
<div className="mt-2 space-y-0.5 pl-[calc(7rem+0.75rem)]">
|
||||
{failedEmbeddingItems[task.id].map((item) => (
|
||||
<FailedWorkerItemRow key={item.image_id} item={item} />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{failed && failedTaggingItems[task.id] && failedTaggingItems[task.id].length > 0 ? (
|
||||
<div className="mt-2 space-y-0.5 pl-[calc(7rem+0.75rem)]">
|
||||
{failedTaggingItems[task.id].map((item) => (
|
||||
<FailedWorkerItemRow key={item.image_id} item={item} />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { revealItemInDir } from '@tauri-apps/plugin-opener'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { WarningIcon } from '../icons'
|
||||
import type { FailedWorkerItem } from './types'
|
||||
|
||||
export function FailedWorkerItemRow({ item }: { item: FailedWorkerItem }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-start gap-1.5">
|
||||
<WarningIcon
|
||||
className="light-theme:text-amber-700 mt-px h-2.5 w-2.5 shrink-0 text-amber-500"
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="light-theme:text-amber-700 truncate text-[10px] font-medium text-amber-400/80">
|
||||
{item.filename}
|
||||
</p>
|
||||
{item.error ? <p className="truncate text-[9px] text-gray-600">{item.error}</p> : null}
|
||||
</div>
|
||||
<Tooltip label="Reveal in Explorer" anchorToCursor>
|
||||
<button
|
||||
className="light-theme:text-gray-600 light-theme:hover:text-gray-100 shrink-0 text-gray-700 transition-colors hover:text-gray-300"
|
||||
onClick={() => void revealItemInDir(item.path)}
|
||||
>
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
export function TaskProgressBar({
|
||||
failed,
|
||||
progress,
|
||||
widthClass = 'w-20',
|
||||
}: {
|
||||
failed: boolean
|
||||
progress: number | null
|
||||
widthClass?: string
|
||||
}) {
|
||||
return (
|
||||
<div className={`${widthClass} h-px shrink-0 overflow-hidden rounded-full bg-white/8`}>
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-500 ${
|
||||
failed
|
||||
? 'bg-amber-400/60'
|
||||
: progress === null
|
||||
? 'w-full animate-pulse bg-blue-500/40'
|
||||
: 'bg-blue-500'
|
||||
}`}
|
||||
style={progress !== null ? { width: `${progress}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { WorkerKey } from '../../store'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { PlayIcon } from '../icons'
|
||||
import type { TaskStage } from './types'
|
||||
import { WORKER_FOR_STAGE } from './types'
|
||||
|
||||
export function TaskStagePill({
|
||||
folderId,
|
||||
isWorkerPaused,
|
||||
mutedWhenPaused = false,
|
||||
onToggleWorker,
|
||||
stage,
|
||||
}: {
|
||||
folderId: number
|
||||
isWorkerPaused: (folderId: number, worker: WorkerKey) => boolean
|
||||
mutedWhenPaused?: boolean
|
||||
onToggleWorker: (folderId: number, worker: WorkerKey) => void
|
||||
stage: TaskStage
|
||||
}) {
|
||||
const workerKey = WORKER_FOR_STAGE[stage.label]
|
||||
const isPaused = workerKey ? isWorkerPaused(folderId, workerKey) : false
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`flex shrink-0 items-center gap-1 rounded-md px-2 py-0.5 text-[11px] ${
|
||||
stage.failed
|
||||
? 'light-theme:border light-theme:border-amber-500/40 light-theme:bg-amber-100 light-theme:text-amber-700 bg-amber-500/10 text-amber-400'
|
||||
: isPaused
|
||||
? 'bg-white/4 text-gray-600'
|
||||
: mutedWhenPaused
|
||||
? 'bg-white/5 text-gray-500'
|
||||
: 'bg-white/5 text-gray-400'
|
||||
}`}
|
||||
>
|
||||
{isPaused && mutedWhenPaused ? (
|
||||
<svg className="h-2 w-2 text-gray-600" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
) : null}
|
||||
<span>{stage.label}</span>
|
||||
<span
|
||||
className={`tabular-nums ${stage.failed ? 'light-theme:text-amber-700 text-amber-500' : isPaused && !mutedWhenPaused ? 'text-gray-700' : 'text-gray-600'}`}
|
||||
>
|
||||
{stage.detail}
|
||||
</span>
|
||||
{workerKey ? (
|
||||
<Tooltip label={isPaused ? `Resume ${stage.label}` : `Pause ${stage.label}`} anchorToCursor>
|
||||
<button
|
||||
className={
|
||||
mutedWhenPaused
|
||||
? 'ml-0.5 text-gray-600 transition-colors hover:text-white'
|
||||
: 'ml-0.5 opacity-0 transition-opacity group-hover:opacity-100 hover:text-white'
|
||||
}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onToggleWorker(folderId, workerKey)
|
||||
}}
|
||||
>
|
||||
{isPaused ? (
|
||||
<PlayIcon className="h-2.5 w-2.5" />
|
||||
) : (
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import type {
|
||||
DuplicateScanProgress,
|
||||
Folder,
|
||||
FolderJobProgress,
|
||||
IndexProgress,
|
||||
WorkerKey,
|
||||
} from '../../store'
|
||||
import type { BackgroundTask, TaskStage } from './types'
|
||||
|
||||
export function buildFolderTasks({
|
||||
dismissed,
|
||||
folders,
|
||||
indexingProgress,
|
||||
mediaJobProgress,
|
||||
workerPaused,
|
||||
}: {
|
||||
dismissed: Record<number, string>
|
||||
folders: Folder[]
|
||||
indexingProgress: Record<number, IndexProgress>
|
||||
mediaJobProgress: Record<number, FolderJobProgress>
|
||||
workerPaused: Record<number, Record<WorkerKey, boolean>>
|
||||
}): BackgroundTask[] {
|
||||
return folders
|
||||
.map((folder): BackgroundTask | null => {
|
||||
const index = indexingProgress[folder.id]
|
||||
const jobs = mediaJobProgress[folder.id]
|
||||
|
||||
const thumbnailPending = jobs?.thumbnail_pending ?? 0
|
||||
const metadataPending = jobs?.metadata_pending ?? 0
|
||||
const embeddingPending = jobs?.embedding_pending ?? 0
|
||||
const embeddingReady = jobs?.embedding_ready ?? 0
|
||||
const embeddingFailed = jobs?.embedding_failed ?? 0
|
||||
const taggingPending = jobs?.tagging_pending ?? 0
|
||||
const taggingReady = jobs?.tagging_ready ?? 0
|
||||
const taggingFailed = jobs?.tagging_failed ?? 0
|
||||
const captionPending = jobs?.caption_pending ?? 0
|
||||
const captionReady = jobs?.caption_ready ?? 0
|
||||
const captionFailed = jobs?.caption_failed ?? 0
|
||||
|
||||
const 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 embeddingProcessed = embeddingReady + embeddingFailed
|
||||
const embeddingTotal = embeddingProcessed + embeddingPending
|
||||
const taggingProcessed = taggingReady + taggingFailed
|
||||
const taggingTotal = taggingProcessed + taggingPending
|
||||
const captionProcessed = captionReady + captionFailed
|
||||
const captionTotal = captionProcessed + captionPending
|
||||
const hasFailedEmbeddings = embeddingFailed > 0
|
||||
const hasFailedTagging = taggingFailed > 0
|
||||
const hasFailedCaptions = captionFailed > 0
|
||||
|
||||
if (
|
||||
!index &&
|
||||
pendingMediaWork === 0 &&
|
||||
!hasFailedEmbeddings &&
|
||||
!hasFailedTagging &&
|
||||
!hasFailedCaptions
|
||||
)
|
||||
return null
|
||||
|
||||
const stages: TaskStage[] = []
|
||||
|
||||
if (index && !index.done) {
|
||||
stages.push({
|
||||
label: 'Scanning',
|
||||
detail: `${index.indexed.toLocaleString()} / ${index.total.toLocaleString()}`,
|
||||
progress: index.total > 0 ? (index.indexed / index.total) * 100 : 0,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (thumbnailPending > 0) {
|
||||
stages.push({
|
||||
label: 'Thumbnails',
|
||||
detail: thumbnailPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (metadataPending > 0) {
|
||||
stages.push({
|
||||
label: 'Metadata',
|
||||
detail: metadataPending.toLocaleString(),
|
||||
progress: null,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (embeddingPending > 0) {
|
||||
stages.push({
|
||||
label: 'Embeddings',
|
||||
detail: `${embeddingProcessed.toLocaleString()} / ${embeddingTotal.toLocaleString()}`,
|
||||
progress: embeddingTotal > 0 ? (embeddingProcessed / embeddingTotal) * 100 : 0,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (taggingPending > 0) {
|
||||
stages.push({
|
||||
label: 'Tags',
|
||||
detail: `${taggingProcessed.toLocaleString()} / ${taggingTotal.toLocaleString()}`,
|
||||
progress: taggingTotal > 0 ? (taggingProcessed / taggingTotal) * 100 : 0,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (captionPending > 0) {
|
||||
stages.push({
|
||||
label: 'Captions',
|
||||
detail: `${captionProcessed.toLocaleString()} / ${captionTotal.toLocaleString()}`,
|
||||
progress: captionTotal > 0 ? (captionProcessed / captionTotal) * 100 : 0,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
if (hasFailedEmbeddings && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: 'Failed',
|
||||
detail: `${embeddingFailed.toLocaleString()} embeddings`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (hasFailedTagging && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: 'Failed',
|
||||
detail: `${taggingFailed.toLocaleString()} tags`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (hasFailedCaptions && pendingMediaWork === 0) {
|
||||
stages.push({
|
||||
label: 'Failed',
|
||||
detail: `${captionFailed.toLocaleString()} captions`,
|
||||
progress: null,
|
||||
failed: true,
|
||||
})
|
||||
}
|
||||
|
||||
const snapshot = `${pendingMediaWork}:${embeddingFailed}:${taggingFailed}:${captionFailed}`
|
||||
|
||||
return {
|
||||
id: folder.id,
|
||||
name: folder.name,
|
||||
stages,
|
||||
isActive,
|
||||
hasFailedEmbeddings,
|
||||
hasFailedTagging,
|
||||
hasFailedCaptions,
|
||||
pendingMediaWork,
|
||||
embeddingProcessed,
|
||||
embeddingTotal,
|
||||
currentFile: index && !index.done ? index.current_file || null : null,
|
||||
snapshot,
|
||||
}
|
||||
})
|
||||
.filter((task): task is BackgroundTask => task !== null)
|
||||
.filter((task) => dismissed[task.id] !== task.snapshot)
|
||||
.sort((a, b) => Number(b.isActive) - Number(a.isActive))
|
||||
}
|
||||
|
||||
export function buildDuplicateScanTask(
|
||||
duplicateScanning: boolean,
|
||||
duplicateScanProgress: DuplicateScanProgress | null
|
||||
): BackgroundTask | null {
|
||||
if (!duplicateScanning) return null
|
||||
|
||||
return {
|
||||
id: -1,
|
||||
name: 'Duplicate Scan',
|
||||
stages: [
|
||||
{
|
||||
label:
|
||||
duplicateScanProgress?.phase === 'checking'
|
||||
? 'Checking'
|
||||
: duplicateScanProgress?.phase === 'confirming'
|
||||
? 'Confirming'
|
||||
: 'Hashing',
|
||||
detail: duplicateScanProgress
|
||||
? `${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ''}`
|
||||
: 'Starting…',
|
||||
progress:
|
||||
duplicateScanProgress && duplicateScanProgress.total > 0
|
||||
? (duplicateScanProgress.processed / duplicateScanProgress.total) * 100
|
||||
: null,
|
||||
failed: false,
|
||||
},
|
||||
],
|
||||
isActive: true,
|
||||
hasFailedEmbeddings: false,
|
||||
hasFailedTagging: false,
|
||||
hasFailedCaptions: false,
|
||||
pendingMediaWork: 1,
|
||||
embeddingProcessed: 0,
|
||||
embeddingTotal: 0,
|
||||
currentFile: null,
|
||||
snapshot: '',
|
||||
}
|
||||
}
|
||||
|
||||
export function taskProgress(task: BackgroundTask): number | null {
|
||||
const embeddingStage = task.stages.find((stage) => stage.label === 'Embeddings')
|
||||
const taggingStage = task.stages.find((stage) => stage.label === 'Tags')
|
||||
const scanningStage = task.stages.find((stage) => stage.label === 'Scanning')
|
||||
const duplicateStage = task.id === -1 ? task.stages[0] : null
|
||||
return (
|
||||
embeddingStage?.progress ??
|
||||
taggingStage?.progress ??
|
||||
scanningStage?.progress ??
|
||||
duplicateStage?.progress ??
|
||||
null
|
||||
)
|
||||
}
|
||||
|
||||
export function taskHasTerminalFailure(task: BackgroundTask): boolean {
|
||||
return (
|
||||
(task.hasFailedEmbeddings || task.hasFailedTagging || task.hasFailedCaptions) &&
|
||||
task.pendingMediaWork === 0
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { WorkerKey } from '../../store'
|
||||
|
||||
export const WORKER_FOR_STAGE: Record<string, WorkerKey> = {
|
||||
Thumbnails: 'thumbnail',
|
||||
Metadata: 'metadata',
|
||||
Embeddings: 'embedding',
|
||||
Tags: 'tagging',
|
||||
}
|
||||
|
||||
export interface TaskStage {
|
||||
label: string
|
||||
detail: string
|
||||
progress: number | null
|
||||
failed: boolean
|
||||
}
|
||||
|
||||
export interface BackgroundTask {
|
||||
id: number
|
||||
name: string
|
||||
stages: TaskStage[]
|
||||
isActive: boolean
|
||||
hasFailedEmbeddings: boolean
|
||||
hasFailedTagging: boolean
|
||||
hasFailedCaptions: boolean
|
||||
pendingMediaWork: number
|
||||
embeddingProcessed: number
|
||||
embeddingTotal: number
|
||||
currentFile: string | null
|
||||
snapshot: string
|
||||
}
|
||||
|
||||
export interface FailedWorkerItem {
|
||||
image_id: number
|
||||
filename: string
|
||||
path: string
|
||||
error: string | null
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { AlbumPicker } from '../AlbumPicker'
|
||||
|
||||
interface BulkAlbumPopoverProps {
|
||||
onPick: (albumId: number) => Promise<void>
|
||||
}
|
||||
|
||||
export function BulkAlbumPopover({ onPick }: BulkAlbumPopoverProps) {
|
||||
return (
|
||||
<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"
|
||||
>
|
||||
<AlbumPicker onPick={(albumId) => void onPick(albumId)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { WarningIcon } from '../icons'
|
||||
|
||||
interface BulkDeleteConfirmProps {
|
||||
deleting: boolean
|
||||
selectedCount: number
|
||||
onCancel: () => void
|
||||
onDelete: () => Promise<void>
|
||||
}
|
||||
|
||||
export function BulkDeleteConfirm({
|
||||
deleting,
|
||||
selectedCount,
|
||||
onCancel,
|
||||
onDelete,
|
||||
}: BulkDeleteConfirmProps) {
|
||||
return (
|
||||
<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">
|
||||
<WarningIcon className="h-3.5 w-3.5 shrink-0" />
|
||||
<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={onCancel}
|
||||
>
|
||||
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 onDelete()}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting ? 'Deleting…' : `Delete ${selectedCount} from disk`}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { StarIcon } from '../icons'
|
||||
|
||||
interface BulkRatingPopoverProps {
|
||||
onClose: () => void
|
||||
onSetRating: (rating: number) => Promise<void>
|
||||
}
|
||||
|
||||
export function BulkRatingPopover({ onClose, onSetRating }: BulkRatingPopoverProps) {
|
||||
const setRating = async (rating: number) => {
|
||||
await onSetRating(rating)
|
||||
onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<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 (
|
||||
<Tooltip key={rating} label={`Set ${rating} star${rating === 1 ? '' : 's'}`}>
|
||||
<button
|
||||
className="rounded-md p-1 text-white/25 transition-colors hover:bg-white/5 hover:text-amber-300"
|
||||
onClick={() => void setRating(rating)}
|
||||
>
|
||||
<StarIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
<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={() => void setRating(0)}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Tooltip } from '../Tooltip'
|
||||
|
||||
interface BulkSelectionSummaryProps {
|
||||
loadedCount: number
|
||||
selectedCount: number
|
||||
totalImages: number
|
||||
onSelectAll: () => void
|
||||
}
|
||||
|
||||
export function BulkSelectionSummary({
|
||||
loadedCount,
|
||||
selectedCount,
|
||||
totalImages,
|
||||
onSelectAll,
|
||||
}: BulkSelectionSummaryProps) {
|
||||
const showSelectAll = loadedCount < totalImages || loadedCount > selectedCount
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2 px-1.5">
|
||||
<span className="text-xs font-medium text-white">{selectedCount} selected</span>
|
||||
{showSelectAll ? (
|
||||
<Tooltip
|
||||
label={loadedCount < totalImages ? 'Selects loaded items only' : 'Select all loaded'}
|
||||
>
|
||||
<button
|
||||
className="text-[11px] text-gray-500 transition-colors hover:text-gray-300"
|
||||
onClick={onSelectAll}
|
||||
>
|
||||
Select all{loadedCount < totalImages ? ' loaded' : ''}
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,24 +1,26 @@
|
||||
import { useBulkTagEditor } from "./useBulkTagEditor";
|
||||
import { useBulkTagEditor } from './useBulkTagEditor'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CloseIcon } from '../icons'
|
||||
|
||||
// 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();
|
||||
useBulkTagEditor()
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<form
|
||||
className="flex gap-1.5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
void addTag(input);
|
||||
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"}…`}
|
||||
placeholder={`Add tag to ${selectedCount} item${selectedCount === 1 ? '' : 's'}…`}
|
||||
value={input}
|
||||
onChange={(event) => setInput(event.target.value)}
|
||||
disabled={pending}
|
||||
@@ -35,14 +37,18 @@ export function BulkTagFields({ autoFocus = false }: { autoFocus?: boolean }) {
|
||||
{suggestions.length > 0 ? (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{suggestions.map((suggestion) => (
|
||||
<button
|
||||
<Tooltip
|
||||
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`}
|
||||
label={`${suggestion.count.toLocaleString()} tagged`}
|
||||
anchorToCursor
|
||||
>
|
||||
{suggestion.tag}
|
||||
</button>
|
||||
<button
|
||||
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)}
|
||||
>
|
||||
{suggestion.tag}
|
||||
</button>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
@@ -55,19 +61,18 @@ export function BulkTagFields({ autoFocus = false }: { autoFocus?: boolean }) {
|
||||
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>
|
||||
<Tooltip label="Remove from selected" followCursor>
|
||||
<button
|
||||
className="text-gray-600 transition-colors hover:text-white"
|
||||
onClick={() => void removeTag(tag)}
|
||||
>
|
||||
<CloseIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { BulkTagFields } from "./BulkTagFields";
|
||||
import { BulkTagFields } from './BulkTagFields'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CloseIcon } from '../icons'
|
||||
|
||||
// Inline popover surface for bulk tagging — the default editing surface.
|
||||
// Anchored above the bar by the parent; closes on outside click via the
|
||||
@@ -11,18 +13,14 @@ export function BulkTagPopover({ onClose }: { onClose: () => void }) {
|
||||
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>
|
||||
<p className="text-[11px] tracking-wider text-gray-500 uppercase">Add tags</p>
|
||||
<Tooltip label="Close" anchorToCursor>
|
||||
<button className="text-gray-600 transition-colors hover:text-white" onClick={onClose}>
|
||||
<CloseIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<BulkTagFields autoFocus />
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
export type BulkPanel = 'tag' | 'rating' | 'album' | 'delete' | null
|
||||
@@ -1,73 +1,73 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { ExploreTagEntry, useGalleryStore } from "../../store";
|
||||
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 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);
|
||||
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();
|
||||
const query = input.trim()
|
||||
if (!query) {
|
||||
requestRef.current += 1;
|
||||
setSuggestions([]);
|
||||
return;
|
||||
requestRef.current += 1
|
||||
setSuggestions([])
|
||||
return
|
||||
}
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
const requestId = ++requestRef.current;
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
const requestId = ++requestRef.current
|
||||
debounceRef.current = setTimeout(async () => {
|
||||
try {
|
||||
const results = await invoke<ExploreTagEntry[]>("search_tags_autocomplete", {
|
||||
const results = await invoke<ExploreTagEntry[]>('search_tags_autocomplete', {
|
||||
params: { query, folder_id: selectedFolderId ?? null, limit: 8 },
|
||||
});
|
||||
if (requestId !== requestRef.current) return;
|
||||
setSuggestions(results);
|
||||
})
|
||||
if (requestId !== requestRef.current) return
|
||||
setSuggestions(results)
|
||||
} catch {
|
||||
if (requestId !== requestRef.current) return;
|
||||
setSuggestions([]);
|
||||
if (requestId !== requestRef.current) return
|
||||
setSuggestions([])
|
||||
}
|
||||
}, 120);
|
||||
}, 120)
|
||||
return () => {
|
||||
requestRef.current += 1;
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, [input, selectedFolderId]);
|
||||
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);
|
||||
const tag = raw.trim()
|
||||
if (!tag || pending) return
|
||||
setPending(true)
|
||||
try {
|
||||
await bulkAddTags([tag]);
|
||||
setAppliedTags((prev) => (prev.includes(tag) ? prev : [...prev, tag]));
|
||||
setInput("");
|
||||
setSuggestions([]);
|
||||
await bulkAddTags([tag])
|
||||
setAppliedTags((prev) => (prev.includes(tag) ? prev : [...prev, tag]))
|
||||
setInput('')
|
||||
setSuggestions([])
|
||||
} finally {
|
||||
setPending(false);
|
||||
setPending(false)
|
||||
}
|
||||
},
|
||||
[bulkAddTags, pending],
|
||||
);
|
||||
[bulkAddTags, pending]
|
||||
)
|
||||
|
||||
const removeTag = useCallback(
|
||||
async (tag: string) => {
|
||||
await bulkRemoveTag(tag);
|
||||
setAppliedTags((prev) => prev.filter((entry) => entry !== tag));
|
||||
await bulkRemoveTag(tag)
|
||||
setAppliedTags((prev) => prev.filter((entry) => entry !== tag))
|
||||
},
|
||||
[bulkRemoveTag],
|
||||
);
|
||||
[bulkRemoveTag]
|
||||
)
|
||||
|
||||
return { selectedCount, input, setInput, suggestions, appliedTags, pending, addTag, removeTag };
|
||||
return { selectedCount, input, setInput, suggestions, appliedTags, pending, addTag, removeTag }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export function DuplicateScanLoadingState({ progressLabel }: { progressLabel: string | null }) {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center gap-3 text-white/25">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/15 border-t-white/50" />
|
||||
<span className="text-sm">{progressLabel ? `${progressLabel}…` : 'Preparing scan…'}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DuplicateScanIntroState() {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<div className="max-w-sm text-center">
|
||||
<svg
|
||||
className="mx-auto mb-4 h-10 w-10 text-white/10"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1}
|
||||
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
|
||||
/>
|
||||
</svg>
|
||||
<p className="text-sm text-white/30">
|
||||
Finds files with identical content regardless of filename or location. Click{' '}
|
||||
<strong className="text-white/50">Scan for duplicates</strong> to begin.
|
||||
</p>
|
||||
<p className="mt-2 text-xs text-white/20">
|
||||
Large libraries may take a minute — files are hashed from disk.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function DuplicateScanEmptyState() {
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-white/25">No duplicate files found.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { DuplicateGroup, DuplicateScanProgress } from '../../store'
|
||||
import { FolderScopeDropdown } from '../FolderScopeDropdown'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { WarningIcon } from '../icons'
|
||||
import {
|
||||
duplicateProgressLabel,
|
||||
duplicateProgressPercent,
|
||||
formatBytes,
|
||||
formatRelativeTime,
|
||||
} from './format'
|
||||
|
||||
export function DuplicateFinderHeader({
|
||||
confirmingDelete,
|
||||
deleteResult,
|
||||
deleting,
|
||||
duplicateGroups,
|
||||
duplicateLastScanned,
|
||||
duplicateScanError,
|
||||
duplicateScanning,
|
||||
duplicateScanProgress,
|
||||
duplicateScanWarning,
|
||||
hasResults,
|
||||
hasScanned,
|
||||
onClearSelection,
|
||||
onConfirmDelete,
|
||||
onDelete,
|
||||
onScan,
|
||||
onSelectKeepFirstAll,
|
||||
selectedCount,
|
||||
setConfirmingDelete,
|
||||
}: {
|
||||
confirmingDelete: boolean
|
||||
deleteResult: string | null
|
||||
deleting: boolean
|
||||
duplicateGroups: DuplicateGroup[]
|
||||
duplicateLastScanned: number | null
|
||||
duplicateScanError: string | null
|
||||
duplicateScanning: boolean
|
||||
duplicateScanProgress: DuplicateScanProgress | null
|
||||
duplicateScanWarning: string | null
|
||||
hasResults: boolean
|
||||
hasScanned: boolean
|
||||
onClearSelection: () => void
|
||||
onConfirmDelete: () => void
|
||||
onDelete: () => void
|
||||
onScan: () => void
|
||||
onSelectKeepFirstAll: () => void
|
||||
selectedCount: number
|
||||
setConfirmingDelete: (value: boolean | ((current: boolean) => boolean)) => void
|
||||
}) {
|
||||
const totalWasted = duplicateGroups.reduce(
|
||||
(sum, group) => sum + group.file_size * (group.images.length - 1),
|
||||
0
|
||||
)
|
||||
const totalDuplicateImages = duplicateGroups.reduce(
|
||||
(sum, group) => sum + group.images.length - 1,
|
||||
0
|
||||
)
|
||||
const progressLabel = duplicateProgressLabel(duplicateScanProgress)
|
||||
const progressPercent = duplicateProgressPercent(duplicateScanProgress)
|
||||
|
||||
return (
|
||||
<div className="shrink-0 border-b border-white/[0.05] px-6 py-4">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h2 className="text-[15px] font-semibold text-white">Duplicate Finder</h2>
|
||||
<p className="mt-0.5 text-[11px] text-white/30">
|
||||
{duplicateScanning
|
||||
? duplicateScanProgress
|
||||
? `${progressLabel}… ${duplicateScanProgress.processed.toLocaleString()} / ${duplicateScanProgress.total.toLocaleString()}${duplicateScanProgress.skipped > 0 ? ` · ${duplicateScanProgress.skipped.toLocaleString()} skipped` : ''}`
|
||||
: 'Starting scan…'
|
||||
: hasResults
|
||||
? `${duplicateGroups.length} group${duplicateGroups.length === 1 ? '' : 's'} · ${formatBytes(totalWasted)} reclaimable`
|
||||
: duplicateLastScanned !== null
|
||||
? 'No duplicates found'
|
||||
: 'Scan your library for identical files'}
|
||||
</p>
|
||||
{!duplicateScanning && duplicateLastScanned !== null ? (
|
||||
<p className="mt-0.5 text-[10px] text-white/20">
|
||||
Last scanned {formatRelativeTime(duplicateLastScanned)}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderScopeDropdown />
|
||||
{hasResults && selectedCount === 0 && !deleting ? (
|
||||
<Tooltip
|
||||
label={`Mark ${totalDuplicateImages} duplicate${totalDuplicateImages === 1 ? '' : 's'} for deletion across all groups (keeps first in each)`}
|
||||
anchorToCursor
|
||||
>
|
||||
<button
|
||||
className="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 rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white"
|
||||
onClick={onSelectKeepFirstAll}
|
||||
>
|
||||
Select all duplicates
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{selectedCount > 0 ? (
|
||||
<>
|
||||
<span className="text-[11px] text-white/40">{selectedCount} marked for deletion</span>
|
||||
<button
|
||||
className="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 rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.07] hover:text-white disabled:opacity-40"
|
||||
onClick={onClearSelection}
|
||||
disabled={deleting}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
<div className="relative">
|
||||
<button
|
||||
className="rounded-lg border border-red-400/25 bg-red-500/10 px-3 py-1.5 text-xs text-red-300 transition-colors hover:bg-red-500/15 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={() => setConfirmingDelete((value) => !value)}
|
||||
disabled={deleting}
|
||||
>
|
||||
{deleting
|
||||
? 'Deleting…'
|
||||
: `Delete ${selectedCount} file${selectedCount === 1 ? '' : 's'}`}
|
||||
</button>
|
||||
{confirmingDelete && !deleting ? (
|
||||
<>
|
||||
<div className="fixed inset-0 z-40" onClick={onConfirmDelete} />
|
||||
<div className="absolute top-full right-0 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">
|
||||
<WarningIcon className="h-3.5 w-3.5 shrink-0" />
|
||||
<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={onConfirmDelete}
|
||||
>
|
||||
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={onDelete}
|
||||
>
|
||||
Delete {selectedCount} from disk
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
<button
|
||||
className="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 rounded-lg border border-white/10 bg-white/[0.055] px-3 py-1.5 text-xs text-gray-300 transition-colors hover:bg-white/10 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
|
||||
onClick={onScan}
|
||||
disabled={duplicateScanning}
|
||||
>
|
||||
{duplicateScanning ? 'Scanning…' : hasScanned ? 'Rescan' : 'Scan for duplicates'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{duplicateScanning && duplicateScanProgress ? (
|
||||
<div className="mt-3 h-px overflow-hidden rounded-full bg-white/[0.07]">
|
||||
<div
|
||||
className="h-full rounded-full bg-blue-500/60 transition-[width] duration-200"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{duplicateScanError ? (
|
||||
<p className="mt-2 text-[11px] text-red-400/80">{duplicateScanError}</p>
|
||||
) : null}
|
||||
{duplicateScanWarning ? (
|
||||
<p className="mt-2 text-[11px] text-amber-300/70">{duplicateScanWarning}</p>
|
||||
) : null}
|
||||
{deleteResult ? <p className="mt-2 text-[11px] text-white/40">{deleteResult}</p> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { DuplicateGroup, useGalleryStore } from '../../store'
|
||||
import { mediaSrc } from '../../lib/mediaSrc'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { formatBytes } from './format'
|
||||
|
||||
export function DuplicateGroupCard({ group }: { group: DuplicateGroup }) {
|
||||
const selectedIds = useGalleryStore((state) => state.duplicateSelectedIds)
|
||||
const toggleDuplicateSelected = useGalleryStore((state) => state.toggleDuplicateSelected)
|
||||
const selectAllDuplicates = useGalleryStore((state) => state.selectAllDuplicates)
|
||||
const groupSelectedCount = group.images.filter((image) => selectedIds.has(image.id)).length
|
||||
const noneSelected = groupSelectedCount === 0
|
||||
|
||||
const handleKeepFirst = () => {
|
||||
const toDelete = group.images.slice(1).map((image) => image.id)
|
||||
for (const image of group.images) {
|
||||
if (selectedIds.has(image.id)) toggleDuplicateSelected(image.id)
|
||||
}
|
||||
selectAllDuplicates(toDelete)
|
||||
}
|
||||
|
||||
const handleDeselectGroup = () => {
|
||||
for (const image of group.images) {
|
||||
if (selectedIds.has(image.id)) toggleDuplicateSelected(image.id)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-white/[0.07] bg-white/[0.02] p-4">
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-400">
|
||||
{group.images.length} copies
|
||||
</span>
|
||||
<span className="text-[11px] text-white/30">{formatBytes(group.file_size)} each</span>
|
||||
<span className="text-[11px] text-white/20">
|
||||
{formatBytes(group.file_size * (group.images.length - 1))} wasted
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{noneSelected ? (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={handleKeepFirst}
|
||||
>
|
||||
Keep first
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
className="text-[11px] text-white/35 transition-colors hover:text-white/70"
|
||||
onClick={handleDeselectGroup}
|
||||
>
|
||||
Deselect all
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{group.images.map((image) => {
|
||||
const isSelected = selectedIds.has(image.id)
|
||||
const src = mediaSrc(image.thumbnail_path)
|
||||
return (
|
||||
<Tooltip key={image.id} label={image.path} anchorToCursor>
|
||||
<button
|
||||
className={`media-dark-surface group relative overflow-hidden rounded-xl border transition-all ${
|
||||
isSelected
|
||||
? 'border-red-400/50 ring-1 ring-red-400/30'
|
||||
: 'border-white/8 hover:border-white/20'
|
||||
}`}
|
||||
style={{ width: 140, height: 105 }}
|
||||
onClick={() => toggleDuplicateSelected(image.id)}
|
||||
>
|
||||
{src ? (
|
||||
<img src={src} alt="" className="h-full w-full object-cover" draggable={false} />
|
||||
) : (
|
||||
<div className="h-full w-full bg-white/[0.03]" />
|
||||
)}
|
||||
{isSelected ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-red-950/60">
|
||||
<svg
|
||||
className="h-6 w-6 text-red-300"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/90 to-transparent px-2 pt-4 pb-1.5 opacity-0 transition-opacity group-hover:opacity-100">
|
||||
<p className="truncate text-[9px] text-white/60">
|
||||
{image.path.split(/[\\/]/).slice(-2).join('/')}
|
||||
</p>
|
||||
</div>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { DuplicateScanProgress } from '../../store'
|
||||
import {
|
||||
duplicateProgressLabel,
|
||||
duplicateProgressPercent,
|
||||
formatBytes,
|
||||
formatRelativeTime,
|
||||
} from './format'
|
||||
|
||||
function progress(overrides: Partial<DuplicateScanProgress> = {}): DuplicateScanProgress {
|
||||
return { phase: 'checking', processed: 0, total: 0, skipped: 0, ...overrides }
|
||||
}
|
||||
|
||||
describe('formatBytes', () => {
|
||||
it('formats each size tier', () => {
|
||||
expect(formatBytes(0)).toBe('0 B')
|
||||
expect(formatBytes(512)).toBe('512 B')
|
||||
expect(formatBytes(2048)).toBe('2 KB')
|
||||
expect(formatBytes(1_048_576)).toBe('1.0 MB')
|
||||
expect(formatBytes(1_610_612_736)).toBe('1.5 GB')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatRelativeTime', () => {
|
||||
const now = () => Math.floor(Date.now() / 1000)
|
||||
|
||||
it('formats each time bucket', () => {
|
||||
expect(formatRelativeTime(now())).toBe('just now')
|
||||
expect(formatRelativeTime(now() - 120)).toBe('2m ago')
|
||||
expect(formatRelativeTime(now() - 7200)).toBe('2h ago')
|
||||
expect(formatRelativeTime(now() - 172_800)).toBe('2d ago')
|
||||
})
|
||||
})
|
||||
|
||||
describe('duplicateProgressLabel', () => {
|
||||
it('returns null without progress', () => {
|
||||
expect(duplicateProgressLabel(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('labels each phase', () => {
|
||||
expect(duplicateProgressLabel(progress({ phase: 'checking' }))).toBe('Checking file sizes')
|
||||
expect(duplicateProgressLabel(progress({ phase: 'hashing' }))).toBe(
|
||||
'Hashing duplicate candidates'
|
||||
)
|
||||
expect(duplicateProgressLabel(progress({ phase: 'confirming' }))).toBe(
|
||||
'Confirming exact matches'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('duplicateProgressPercent', () => {
|
||||
it('returns 0 for missing progress or zero totals', () => {
|
||||
expect(duplicateProgressPercent(null)).toBe(0)
|
||||
expect(duplicateProgressPercent(progress({ processed: 5, total: 0 }))).toBe(0)
|
||||
})
|
||||
|
||||
it('rounds to whole percent', () => {
|
||||
expect(duplicateProgressPercent(progress({ processed: 50, total: 200 }))).toBe(25)
|
||||
expect(duplicateProgressPercent(progress({ processed: 1, total: 3 }))).toBe(33)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { DuplicateScanProgress } from '../../store'
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes >= 1_073_741_824) return `${(bytes / 1_073_741_824).toFixed(1)} GB`
|
||||
if (bytes >= 1_048_576) return `${(bytes / 1_048_576).toFixed(1)} MB`
|
||||
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`
|
||||
return `${bytes} B`
|
||||
}
|
||||
|
||||
export function formatRelativeTime(unixSecs: number): string {
|
||||
const diff = Math.floor(Date.now() / 1000) - unixSecs
|
||||
if (diff < 60) return 'just now'
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)}m ago`
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`
|
||||
return `${Math.floor(diff / 86400)}d ago`
|
||||
}
|
||||
|
||||
export function duplicateProgressLabel(progress: DuplicateScanProgress | null): string | null {
|
||||
if (!progress) return null
|
||||
if (progress.phase === 'checking') return 'Checking file sizes'
|
||||
if (progress.phase === 'hashing') return 'Hashing duplicate candidates'
|
||||
return 'Confirming exact matches'
|
||||
}
|
||||
|
||||
export function duplicateProgressPercent(progress: DuplicateScanProgress | null): number {
|
||||
return progress && progress.total > 0
|
||||
? Math.round((progress.processed / progress.total) * 100)
|
||||
: 0
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { motion, useReducedMotion } from 'framer-motion'
|
||||
import type { VisualClusterEntry } from '../../store'
|
||||
import { mediaSrc } from '../../lib/mediaSrc'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { ACCENTS, GOLDEN_ANGLE, seeded } from './layout'
|
||||
|
||||
interface PlacedNode {
|
||||
entry: VisualClusterEntry
|
||||
index: number
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
zIndex: number
|
||||
accent: string
|
||||
driftX: number
|
||||
driftY: number
|
||||
driftDuration: number
|
||||
rotateSeed: number
|
||||
}
|
||||
|
||||
function buildCloud(
|
||||
entries: VisualClusterEntry[],
|
||||
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
|
||||
const n = entries.length
|
||||
const ASPECT = 0.72
|
||||
const PAD = 18
|
||||
|
||||
// Card width scales with image count; the sub-linear exponent (< 1) widens the
|
||||
// gap so the busiest clusters read as clearly larger and more prominent.
|
||||
const rawWidth = (count: number) => {
|
||||
const ratio = Math.max(count / maxCount, 0.05)
|
||||
return 92 + Math.pow(ratio, 0.65) * 158 // ~92–250px before fit scaling
|
||||
}
|
||||
|
||||
// Shrink every card uniformly when their padded footprint can't fit the
|
||||
// canvas, so overlap resolution can actually pull them apart instead of
|
||||
// settling into a pile. (0.6 leaves headroom for imperfect packing.)
|
||||
const totalArea = entries.reduce((sum, e) => {
|
||||
const w = rawWidth(e.count)
|
||||
return sum + (w + PAD) * (w * ASPECT + PAD)
|
||||
}, 0)
|
||||
const usableArea = containerW * containerH * 0.6
|
||||
const fit = totalArea > usableArea ? Math.sqrt(usableArea / totalArea) : 1
|
||||
|
||||
const spreadX = containerW * 0.44
|
||||
const spreadY = containerH * 0.4
|
||||
|
||||
// 1. Seed positions on a phyllotaxis spiral, sized by count.
|
||||
const nodes: PlacedNode[] = entries.map((entry, i) => {
|
||||
const w = rawWidth(entry.count) * fit
|
||||
const h = w * ASPECT
|
||||
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,
|
||||
// Bigger (busier) clusters stack above smaller ones, so they stay
|
||||
// clickable even if a sliver of overlap survives.
|
||||
zIndex: Math.round(w),
|
||||
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. Resolve overlaps by pushing pairs apart, clamping inside the canvas every
|
||||
// pass so edge cards settle in-bounds instead of being shoved out and
|
||||
// re-overlapping there.
|
||||
const marginX = 14
|
||||
const marginY = 14
|
||||
for (let iter = 0; iter < 160; 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 (ternary yields ±1 so coincident
|
||||
// cards still separate rather than stalling at a zero push).
|
||||
if (overlapX < overlapY) {
|
||||
const push = (overlapX / 2) * (dx >= 0 ? 1 : -1)
|
||||
nb.x += push
|
||||
na.x -= push
|
||||
} else {
|
||||
const push = (overlapY / 2) * (dy >= 0 ? 1 : -1)
|
||||
nb.y += push
|
||||
na.y -= push
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const node of nodes) {
|
||||
node.x = Math.min(Math.max(node.x, node.w / 2 + marginX), containerW - node.w / 2 - marginX)
|
||||
node.y = Math.min(Math.max(node.y, node.h / 2 + marginY), containerH - node.h / 2 - marginY)
|
||||
}
|
||||
}
|
||||
|
||||
return nodes
|
||||
}
|
||||
|
||||
function CloudCard({
|
||||
node,
|
||||
onOpen,
|
||||
animated,
|
||||
}: {
|
||||
node: PlacedNode
|
||||
onOpen: (imageIds: number[]) => void
|
||||
animated: boolean
|
||||
}) {
|
||||
const src = mediaSrc(node.entry.thumbnail_path)
|
||||
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 (
|
||||
<Tooltip
|
||||
label={`Open cluster — ${node.entry.count.toLocaleString()} ${node.entry.count === 1 ? 'image' : 'images'}`}
|
||||
followCursor
|
||||
>
|
||||
<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,
|
||||
zIndex: node.zIndex,
|
||||
}}
|
||||
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, zIndex: 500, transition: { duration: 0.18 } }}
|
||||
onClick={() => onOpen(node.entry.image_ids)}
|
||||
>
|
||||
{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)` }}
|
||||
/>
|
||||
<p className="explore-cluster-label text-[9px] tracking-[0.18em] text-white/35 uppercase">
|
||||
Cluster
|
||||
</p>
|
||||
<p className="explore-cluster-count text-base leading-none font-semibold text-white">
|
||||
{node.entry.count.toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
{/* Anchored to the card corner (not in the count's flex row) so a wide
|
||||
count can't push it past the edge on small cards. */}
|
||||
<span
|
||||
className="explore-cluster-open absolute right-3 bottom-3 rounded-full border px-2 py-0.5 text-[9px] tracking-[0.1em] uppercase opacity-0 transition-opacity duration-200 group-hover:opacity-100"
|
||||
style={{ borderColor: `${accent}50`, color: accent, backgroundColor: `${accent}12` }}
|
||||
>
|
||||
Open
|
||||
</span>
|
||||
</motion.button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
// Separate component so its useLayoutEffect fires when the canvas is actually
|
||||
// mounted, not at ExploreView mount time when the container may still be hidden
|
||||
// behind a loading state.
|
||||
export function ClusterCloud({
|
||||
entries,
|
||||
onOpen,
|
||||
}: {
|
||||
entries: VisualClusterEntry[]
|
||||
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 isolate min-h-0 flex-1 overflow-hidden">
|
||||
<div className="explore-cluster-grid pointer-events-none absolute inset-0 [background-image:radial-gradient(circle,rgba(255,255,255,0.6)_1px,transparent_1px)] [background-size:28px_28px] opacity-[0.07]" />
|
||||
{nodes.map((node) => (
|
||||
<CloudCard
|
||||
key={`${node.entry.representative_image_id}:${node.index}`}
|
||||
node={node}
|
||||
onOpen={onOpen}
|
||||
animated={!reducedMotion && node.index < 12}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { motion } from 'framer-motion'
|
||||
import type { ExploreMode } from '../../store'
|
||||
|
||||
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' }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export function ExploreLoadingPanel({ mode }: { mode: ExploreMode }) {
|
||||
const title = mode === 'visual' ? 'Building visual clusters' : 'Reading tag frequencies'
|
||||
const subtitle =
|
||||
mode === 'visual'
|
||||
? 'Grouping similar images into browsable clusters.'
|
||||
: 'Collecting tags from the current library scope.'
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 items-center justify-center px-8">
|
||||
<div className="flex max-w-sm flex-col items-center text-center">
|
||||
<div className="mb-4 flex items-center justify-center gap-3 text-white/65">
|
||||
<Spinner />
|
||||
<span className="text-sm font-medium">{title}</span>
|
||||
</div>
|
||||
<p className="text-sm leading-relaxed text-white/25">{subtitle}</p>
|
||||
<div className="mt-6 h-px w-40 overflow-hidden rounded-full bg-white/[0.06]">
|
||||
<motion.div
|
||||
className="h-full w-16 rounded-full bg-white/25"
|
||||
animate={{ x: [-72, 184] }}
|
||||
transition={{ duration: 1.4, repeat: Infinity, ease: 'easeInOut' }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { motion, useReducedMotion } from 'framer-motion'
|
||||
import type { ExploreTagEntry, RelatedTagEntry } from '../../store'
|
||||
import { useGalleryStore } from '../../store'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { ACCENTS, GOLDEN_ANGLE, LIGHT_ACCENTS, seeded } from './layout'
|
||||
|
||||
interface AtlasNode {
|
||||
entry: ExploreTagEntry
|
||||
index: number
|
||||
x: number
|
||||
y: number
|
||||
w: number
|
||||
h: number
|
||||
fontSize: number
|
||||
ratio: number
|
||||
accent: string
|
||||
driftX: number
|
||||
driftY: number
|
||||
}
|
||||
|
||||
interface TagAnchor {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export const TAG_ATLAS_MAX_VISIBLE = 132
|
||||
const TAG_ATLAS_DENSE_THRESHOLD = 120
|
||||
|
||||
function buildTagAtlas(
|
||||
entries: ExploreTagEntry[],
|
||||
containerW: number,
|
||||
containerH: number,
|
||||
isLight: boolean
|
||||
): AtlasNode[] {
|
||||
if (!entries.length || containerW <= 0 || containerH <= 0) return []
|
||||
|
||||
const logs = entries.map((entry) => Math.log(Math.max(entry.count, 1)))
|
||||
const logMin = Math.min(...logs)
|
||||
const logRange = Math.max(...logs) - logMin || 1
|
||||
const cx = containerW / 2
|
||||
const cy = containerH * 0.48
|
||||
const spreadX = containerW * 0.47
|
||||
const spreadY = containerH * 0.46
|
||||
const accents = isLight ? LIGHT_ACCENTS : ACCENTS
|
||||
|
||||
const nodes = entries.map((entry, index) => {
|
||||
const ratio = (Math.log(Math.max(entry.count, 1)) - logMin) / logRange
|
||||
const densityScale = entries.length > TAG_ATLAS_DENSE_THRESHOLD ? 0.94 : 1
|
||||
const fontSize = (9.75 + Math.pow(ratio, 0.92) * 19.5) * densityScale
|
||||
const maxWidthRatio = index < 48 ? 0.32 : index < 100 ? 0.26 : 0.2
|
||||
const textWidth = entry.tag.length * fontSize * 0.5 + (ratio > 0.55 ? 36 : 26)
|
||||
const w = Math.min(containerW * maxWidthRatio, textWidth)
|
||||
const h = fontSize * 1.18 + 14
|
||||
const radialRatio = Math.sqrt((index + 0.5) / entries.length)
|
||||
const angle = index * GOLDEN_ANGLE
|
||||
return {
|
||||
entry,
|
||||
index,
|
||||
x: cx + Math.cos(angle) * radialRatio * spreadX,
|
||||
y: cy + Math.sin(angle) * radialRatio * spreadY,
|
||||
w,
|
||||
h,
|
||||
fontSize,
|
||||
ratio,
|
||||
accent: accents[index % accents.length],
|
||||
driftX: (seeded(index + 101) - 0.5) * 7,
|
||||
driftY: (seeded(index + 113) - 0.5) * 6,
|
||||
}
|
||||
})
|
||||
|
||||
const padX = entries.length > TAG_ATLAS_DENSE_THRESHOLD ? 4 : 10
|
||||
const padY = entries.length > TAG_ATLAS_DENSE_THRESHOLD ? 3 : 7
|
||||
const margin = 28
|
||||
for (let iter = 0; iter < 140; 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 + padX - Math.abs(dx)
|
||||
const overlapY = (na.h + nb.h) / 2 + padY - Math.abs(dy)
|
||||
if (overlapX <= 0 || overlapY <= 0) continue
|
||||
if (overlapX < overlapY) {
|
||||
const push = (overlapX / 2) * (dx >= 0 ? 1 : -1)
|
||||
nb.x += push
|
||||
na.x -= push
|
||||
} else {
|
||||
const push = (overlapY / 2) * (dy >= 0 ? 1 : -1)
|
||||
nb.y += push
|
||||
na.y -= push
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const node of nodes) {
|
||||
node.x = Math.min(Math.max(node.x, node.w / 2 + margin), containerW - node.w / 2 - margin)
|
||||
node.y = Math.min(Math.max(node.y, node.h / 2 + margin), containerH - node.h / 2 - margin)
|
||||
if (node.x <= node.w / 2 + margin || node.x >= containerW - node.w / 2 - margin) {
|
||||
node.y += (seeded(node.index + iter + 211) - 0.5) * 2
|
||||
}
|
||||
if (node.y <= node.h / 2 + margin || node.y >= containerH - node.h / 2 - margin) {
|
||||
node.x += (seeded(node.index + iter + 223) - 0.5) * 2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let iter = 0; iter < 5; iter++) {
|
||||
const weighted = nodes.reduce(
|
||||
(acc, node) => {
|
||||
const weight = 1 + Math.pow(node.ratio, 1.35) * 9
|
||||
return {
|
||||
x: acc.x + node.x * weight,
|
||||
y: acc.y + node.y * weight,
|
||||
weight: acc.weight + weight,
|
||||
}
|
||||
},
|
||||
{ x: 0, y: 0, weight: 0 }
|
||||
)
|
||||
const offsetX = containerW * 0.48 - weighted.x / weighted.weight
|
||||
const offsetY = containerH * 0.44 - weighted.y / weighted.weight
|
||||
if (Math.abs(offsetX) < 0.5 && Math.abs(offsetY) < 0.5) break
|
||||
for (const node of nodes) {
|
||||
node.x = Math.min(
|
||||
Math.max(node.x + offsetX, node.w / 2 + margin),
|
||||
containerW - node.w / 2 - margin
|
||||
)
|
||||
node.y = Math.min(
|
||||
Math.max(node.y + offsetY, node.h / 2 + margin),
|
||||
containerH - node.h / 2 - margin
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return nodes
|
||||
}
|
||||
|
||||
export function TagAtlas({
|
||||
entries,
|
||||
onSearch,
|
||||
loadRelatedTags,
|
||||
}: {
|
||||
entries: ExploreTagEntry[]
|
||||
onSearch: (tag: string) => void
|
||||
loadRelatedTags: (tag: string) => Promise<RelatedTagEntry[]>
|
||||
}) {
|
||||
const theme = useGalleryStore((state) => state.theme)
|
||||
const isLight = theme === 'subtle-light'
|
||||
const reducedMotion = useReducedMotion()
|
||||
const canvasRef = useRef<HTMLDivElement>(null)
|
||||
const buttonRefs = useRef(new Map<string, HTMLButtonElement>())
|
||||
const [canvasSize, setCanvasSize] = useState({ w: 0, h: 0 })
|
||||
const [activeTag, setActiveTag] = useState<string | null>(null)
|
||||
const [relatedTags, setRelatedTags] = useState<RelatedTagEntry[]>([])
|
||||
const [anchors, setAnchors] = useState<Record<string, TagAnchor>>({})
|
||||
const visibleEntries = useMemo(
|
||||
() =>
|
||||
entries.length > TAG_ATLAS_MAX_VISIBLE ? entries.slice(0, TAG_ATLAS_MAX_VISIBLE) : entries,
|
||||
[entries]
|
||||
)
|
||||
|
||||
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()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeTag) {
|
||||
setRelatedTags([])
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
void loadRelatedTags(activeTag).then((entries) => {
|
||||
if (!cancelled) setRelatedTags(entries)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [activeTag, loadRelatedTags])
|
||||
|
||||
const nodes = useMemo(
|
||||
() => buildTagAtlas(visibleEntries, canvasSize.w, canvasSize.h, isLight),
|
||||
[visibleEntries, canvasSize.w, canvasSize.h, isLight]
|
||||
)
|
||||
const nodeByTag = useMemo(() => new Map(nodes.map((node) => [node.entry.tag, node])), [nodes])
|
||||
const activeNode = activeTag ? nodeByTag.get(activeTag) : undefined
|
||||
const minOpacity = isLight ? 0.62 : 0.42
|
||||
const visibleConnections = useMemo(
|
||||
() =>
|
||||
activeNode
|
||||
? relatedTags
|
||||
.map((related) => {
|
||||
const node = nodeByTag.get(related.tag)
|
||||
return node ? { node, related } : null
|
||||
})
|
||||
.filter((item): item is { node: AtlasNode; related: RelatedTagEntry } => item !== null)
|
||||
.slice(0, visibleEntries.length > TAG_ATLAS_DENSE_THRESHOLD ? 6 : 10)
|
||||
: [],
|
||||
[activeNode, nodeByTag, relatedTags, visibleEntries.length]
|
||||
)
|
||||
const activeAnchor = activeTag ? anchors[activeTag] : undefined
|
||||
const maxShared = Math.max(1, ...visibleConnections.map(({ related }) => related.shared_count))
|
||||
const connectedByTag = useMemo(
|
||||
() => new Map(visibleConnections.map(({ node, related }) => [node.entry.tag, related])),
|
||||
[visibleConnections]
|
||||
)
|
||||
|
||||
const setButtonRef = useCallback((tag: string, element: HTMLButtonElement | null) => {
|
||||
if (element) {
|
||||
buttonRefs.current.set(tag, element)
|
||||
} else {
|
||||
buttonRefs.current.delete(tag)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const measureAnchors = useCallback(() => {
|
||||
const canvas = canvasRef.current
|
||||
if (!canvas || !activeTag) {
|
||||
setAnchors({})
|
||||
return
|
||||
}
|
||||
|
||||
const canvasRect = canvas.getBoundingClientRect()
|
||||
const tagsToMeasure = [activeTag, ...visibleConnections.map(({ node }) => node.entry.tag)]
|
||||
const nextAnchors: Record<string, TagAnchor> = {}
|
||||
for (const tag of tagsToMeasure) {
|
||||
const element = buttonRefs.current.get(tag)
|
||||
if (!element) continue
|
||||
const rect = element.getBoundingClientRect()
|
||||
nextAnchors[tag] = {
|
||||
x: rect.left - canvasRect.left + rect.width / 2,
|
||||
y: rect.top - canvasRect.top + rect.height / 2,
|
||||
}
|
||||
}
|
||||
setAnchors(nextAnchors)
|
||||
}, [activeTag, visibleConnections])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!activeTag) {
|
||||
setAnchors({})
|
||||
return
|
||||
}
|
||||
|
||||
let firstFrame = 0
|
||||
let secondFrame = 0
|
||||
const settleTimer = window.setTimeout(measureAnchors, 180)
|
||||
firstFrame = window.requestAnimationFrame(() => {
|
||||
measureAnchors()
|
||||
secondFrame = window.requestAnimationFrame(measureAnchors)
|
||||
})
|
||||
return () => {
|
||||
window.cancelAnimationFrame(firstFrame)
|
||||
window.cancelAnimationFrame(secondFrame)
|
||||
window.clearTimeout(settleTimer)
|
||||
}
|
||||
}, [activeTag, canvasSize.w, canvasSize.h, measureAnchors])
|
||||
|
||||
return (
|
||||
<div ref={canvasRef} className="relative min-h-0 flex-1 overflow-hidden px-8 py-8">
|
||||
<svg className="pointer-events-none absolute inset-0 h-full w-full" aria-hidden="true">
|
||||
<defs>
|
||||
<radialGradient id="tag-atlas-glow" cx="50%" cy="50%" r="50%">
|
||||
<stop
|
||||
offset="0%"
|
||||
stopColor={isLight ? 'rgba(60,50,30,0.18)' : 'rgba(255,255,255,0.2)'}
|
||||
/>
|
||||
<stop offset="100%" stopColor="rgba(0,0,0,0)" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
{activeNode && activeAnchor ? (
|
||||
<circle
|
||||
cx={activeAnchor.x}
|
||||
cy={activeAnchor.y}
|
||||
r={Math.max(activeNode.w, activeNode.h) * 0.62}
|
||||
fill="url(#tag-atlas-glow)"
|
||||
opacity="0.24"
|
||||
/>
|
||||
) : null}
|
||||
{visibleConnections.map(({ node, related }) => {
|
||||
const from = activeAnchor
|
||||
const to = anchors[node.entry.tag]
|
||||
if (!from || !to) return null
|
||||
const strength = related.shared_count / maxShared
|
||||
return (
|
||||
<g key={`${activeTag}:${node.entry.tag}`}>
|
||||
<motion.line
|
||||
x1={from.x}
|
||||
y1={from.y}
|
||||
x2={to.x}
|
||||
y2={to.y}
|
||||
stroke={node.accent}
|
||||
strokeWidth={0.35 + strength * 0.55}
|
||||
strokeOpacity={0.05 + strength * 0.12}
|
||||
strokeLinecap="round"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
initial={reducedMotion ? undefined : { pathLength: 0, opacity: 0 }}
|
||||
animate={reducedMotion ? undefined : { pathLength: 1, opacity: 1 }}
|
||||
transition={{ duration: 0.32, ease: 'easeOut' }}
|
||||
/>
|
||||
{!reducedMotion ? (
|
||||
<motion.line
|
||||
x1={from.x}
|
||||
y1={from.y}
|
||||
x2={to.x}
|
||||
y2={to.y}
|
||||
stroke={node.accent}
|
||||
strokeWidth={0.65 + strength * 0.5}
|
||||
strokeOpacity={0.16 + strength * 0.1}
|
||||
strokeLinecap="round"
|
||||
pathLength={1}
|
||||
strokeDasharray="0.08 1"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
initial={{ strokeDashoffset: 1.08, opacity: 0 }}
|
||||
animate={{ strokeDashoffset: [1.08, 0], opacity: [0, 0.65, 0] }}
|
||||
transition={{
|
||||
duration: 4.1 + seeded(node.index + 307) * 1.2,
|
||||
repeat: Infinity,
|
||||
ease: 'easeInOut',
|
||||
delay: seeded(node.index + 317) * 0.75,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
{nodes.map((node) => {
|
||||
const isActive = activeTag === node.entry.tag
|
||||
const connectedRelated = connectedByTag.get(node.entry.tag)
|
||||
const isRelated = connectedRelated !== undefined
|
||||
const dimmed = activeTag !== null && !isActive && !isRelated
|
||||
const opacity = dimmed ? 0.2 : minOpacity + node.ratio * (1 - minOpacity)
|
||||
return (
|
||||
<Tooltip
|
||||
key={node.entry.tag}
|
||||
label={`${node.entry.tag} — ${node.entry.count.toLocaleString()} ${node.entry.count === 1 ? 'image' : 'images'}`}
|
||||
followCursor
|
||||
delay={250}
|
||||
>
|
||||
<button
|
||||
ref={(element) => setButtonRef(node.entry.tag, element)}
|
||||
className={`explore-tag-word group absolute inline-flex items-center justify-center rounded-full px-2 py-1 text-center transition-[opacity,transform] duration-300 ease-out before:absolute before:inset-x-[-14px] before:inset-y-[-8px] before:rounded-full before:bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.16),rgba(255,255,255,0.06)_46%,rgba(255,255,255,0)_72%)] before:opacity-0 before:blur-md before:transition-opacity before:duration-300 before:content-[''] hover:before:opacity-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/25 ${
|
||||
isActive ? 'before:opacity-100' : ''
|
||||
}`}
|
||||
style={{
|
||||
left: node.x - node.w / 2,
|
||||
top: node.y - node.h / 2,
|
||||
width: node.w,
|
||||
minHeight: node.h,
|
||||
fontSize: node.fontSize,
|
||||
color:
|
||||
node.ratio > 0.55 ? node.accent : isLight ? '#4b5563' : 'rgba(255,255,255,0.82)',
|
||||
opacity,
|
||||
transform: `translate3d(0, 0, 0) scale(${isActive ? 1.045 : isRelated ? 1.015 : 1})`,
|
||||
zIndex: isActive ? 30 : isRelated ? 20 : Math.round(node.ratio * 10),
|
||||
}}
|
||||
onMouseEnter={() => setActiveTag(node.entry.tag)}
|
||||
onFocus={() => setActiveTag(node.entry.tag)}
|
||||
onMouseLeave={() => setActiveTag(null)}
|
||||
onBlur={() => setActiveTag(null)}
|
||||
onClick={() => onSearch(node.entry.tag)}
|
||||
>
|
||||
<span className="relative z-10 block w-full truncate text-center leading-none font-medium">
|
||||
{node.entry.tag}
|
||||
</span>
|
||||
<span
|
||||
className={`absolute top-full left-1/2 z-10 mt-1 shrink-0 -translate-x-1/2 rounded-full px-1.5 py-0.5 text-[9px] tabular-nums shadow-sm backdrop-blur-sm transition-opacity ${
|
||||
isActive || isRelated ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
|
||||
}`}
|
||||
style={{ backgroundColor: `${node.accent}1A`, color: node.accent }}
|
||||
>
|
||||
{connectedRelated
|
||||
? connectedRelated.shared_count.toLocaleString()
|
||||
: node.entry.count.toLocaleString()}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useVirtualizer } from '@tanstack/react-virtual'
|
||||
import type { ExploreTagEntry } from '../../store'
|
||||
import { Dropdown } from '../menu'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
|
||||
type TagManageSort = 'count_desc' | 'count_asc' | 'az' | 'za'
|
||||
|
||||
const TAG_MANAGE_SORTS: { value: TagManageSort; label: string }[] = [
|
||||
{ value: 'count_desc', label: 'Most used' },
|
||||
{ value: 'count_asc', label: 'Least used' },
|
||||
{ value: 'az', label: 'A-Z' },
|
||||
{ value: 'za', label: 'Z-A' },
|
||||
]
|
||||
|
||||
function AiSourceGlyph({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path
|
||||
d="M8 2.75l.82 2.42a2.1 2.1 0 0 0 1.32 1.32l2.41.81-2.41.82a2.1 2.1 0 0 0-1.32 1.32L8 11.85l-.82-2.41a2.1 2.1 0 0 0-1.32-1.32L3.45 7.3l2.41-.81a2.1 2.1 0 0 0 1.32-1.32L8 2.75Z"
|
||||
stroke="currentColor"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.35"
|
||||
/>
|
||||
<path
|
||||
d="M12.25 11.15l.25.74.75.26-.75.25-.25.75-.26-.75-.74-.25.74-.26.26-.74Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function RenameGlyph({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path
|
||||
d="M3.25 11.85l.45-2.14 5.95-5.95a1.33 1.33 0 0 1 1.88 0l.71.71a1.33 1.33 0 0 1 0 1.88L6.29 12.3l-2.14.45a.76.76 0 0 1-.9-.9Z"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.35"
|
||||
/>
|
||||
<path d="M8.75 4.65l2.6 2.6" stroke="currentColor" strokeLinecap="round" strokeWidth="1.35" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function DeleteGlyph({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} viewBox="0 0 16 16" fill="none" aria-hidden="true">
|
||||
<path d="M3.25 4.65h9.5" stroke="currentColor" strokeLinecap="round" strokeWidth="1.35" />
|
||||
<path
|
||||
d="M6.35 4.55V3.7c0-.55.45-1 1-1h1.3c.55 0 1 .45 1 1v.85"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeWidth="1.35"
|
||||
/>
|
||||
<path
|
||||
d="M5.1 6.2l.35 5.65c.04.63.56 1.12 1.19 1.12h2.72c.63 0 1.15-.49 1.19-1.12l.35-5.65"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="1.35"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
// Compact management tile for a single tag. Rename doubles as merge when the new
|
||||
// name already exists, and delete applies across the scoped tag set.
|
||||
function TagManageTile({
|
||||
entry,
|
||||
onSearch,
|
||||
onRename,
|
||||
onDelete,
|
||||
}: {
|
||||
entry: ExploreTagEntry
|
||||
onSearch: (tag: string) => void
|
||||
onRename: (from: string, to: string) => Promise<void>
|
||||
onDelete: (tag: string) => Promise<void>
|
||||
}) {
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [value, setValue] = useState(entry.tag)
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (editing) {
|
||||
setValue(entry.tag)
|
||||
setTimeout(() => inputRef.current?.select(), 0)
|
||||
}
|
||||
}, [editing, entry.tag])
|
||||
|
||||
const commitRename = async () => {
|
||||
const next = value.trim()
|
||||
if (!next || next === entry.tag) {
|
||||
setEditing(false)
|
||||
return
|
||||
}
|
||||
setBusy(true)
|
||||
try {
|
||||
await onRename(entry.tag, next)
|
||||
setEditing(false)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const sourceLabel = entry.has_ai_source
|
||||
? entry.has_user_source
|
||||
? 'Used by AI tags and user tags'
|
||||
: 'AI-generated tag'
|
||||
: 'User tag'
|
||||
|
||||
return (
|
||||
<div
|
||||
data-tag-manager-tile
|
||||
className={`tag-manager-tile ${entry.has_ai_source ? 'tag-manager-tile-ai' : ''} group relative min-w-0 rounded-lg border bg-white/[0.018] px-3 py-2 transition-[background-color,border-color,transform] duration-150 focus-within:bg-white/[0.045] hover:bg-white/[0.04] ${
|
||||
entry.has_ai_source
|
||||
? 'border-white/[0.08] shadow-[inset_0_1px_0_rgba(125,211,252,0.055)] focus-within:border-white/[0.15] hover:border-white/[0.13]'
|
||||
: 'border-white/[0.06] focus-within:border-white/[0.14] hover:border-white/[0.12]'
|
||||
} ${editing || confirming ? 'min-h-[82px]' : 'min-h-[46px]'}`}
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
{editing ? (
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="tag-manager-edit-input min-w-0 flex-1 rounded-md border border-blue-400/35 bg-black/25 px-2 py-1 text-sm text-white ring-1 ring-blue-500/30 outline-none"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
void commitRename()
|
||||
}
|
||||
if (e.key === 'Escape') setEditing(false)
|
||||
}}
|
||||
disabled={busy}
|
||||
/>
|
||||
) : (
|
||||
<Tooltip label="Search this tag" delay={500} anchorToCursor className="min-w-0 flex-1">
|
||||
<button
|
||||
className="tag-manager-name block w-full truncate pr-36 text-left text-sm font-medium text-white/85 transition-colors hover:text-white"
|
||||
onClick={() => onSearch(entry.tag)}
|
||||
>
|
||||
{entry.tag}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<div className="absolute top-2 right-2.5 shrink-0">
|
||||
{entry.has_ai_source ? (
|
||||
<Tooltip label={sourceLabel} delay={400} anchorToCursor>
|
||||
<span className="tag-manager-count tag-manager-count-ai inline-flex h-5 items-center gap-1 rounded-full border border-sky-300/10 bg-sky-300/[0.075] px-1.5 text-[10px] text-sky-200/75 tabular-nums">
|
||||
<AiSourceGlyph className="tag-manager-ai-glyph h-3 w-3" />
|
||||
{entry.count.toLocaleString()}
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<span className="tag-manager-count rounded-full bg-white/[0.055] px-2 py-0.5 text-[10px] text-white/38 tabular-nums">
|
||||
{entry.count.toLocaleString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editing ? (
|
||||
<div className="mt-2 flex items-center gap-1">
|
||||
<button
|
||||
className="tag-manager-save rounded-md bg-blue-500/20 px-2 py-1 text-[11px] text-blue-200 transition-colors hover:bg-blue-500/30 disabled:opacity-50"
|
||||
onClick={() => void commitRename()}
|
||||
disabled={busy || !value.trim()}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
className="tag-manager-secondary rounded-md border border-white/10 px-2 py-1 text-[11px] text-white/50 transition-colors hover:bg-white/5 hover:text-white/80"
|
||||
onClick={() => setEditing(false)}
|
||||
disabled={busy}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : confirming ? (
|
||||
<div className="mt-2 flex items-center gap-1">
|
||||
<button
|
||||
className="tag-manager-danger rounded-md bg-red-500/20 px-2 py-1 text-[11px] text-red-300 transition-colors hover:bg-red-500/30 disabled:opacity-50"
|
||||
onClick={async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await onDelete(entry.tag)
|
||||
setConfirming(false)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}}
|
||||
disabled={busy}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
<button
|
||||
className="tag-manager-secondary rounded-md border border-white/10 px-2 py-1 text-[11px] text-white/50 transition-colors hover:bg-white/5 hover:text-white/80"
|
||||
onClick={() => setConfirming(false)}
|
||||
disabled={busy}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="pointer-events-none absolute top-1/2 right-[5rem] flex -translate-y-1/2 items-center gap-1 opacity-0 transition-opacity group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100">
|
||||
<Tooltip label="Rename or merge into another tag" delay={400} anchorToCursor>
|
||||
<button
|
||||
className="tag-manager-action inline-flex h-6 w-6 items-center justify-center rounded-md border border-white/10 bg-gray-950/80 text-white/55 transition-colors hover:bg-white/8 hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/80"
|
||||
onClick={() => setEditing(true)}
|
||||
aria-label={`Rename ${entry.tag}`}
|
||||
>
|
||||
<RenameGlyph className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label="Delete this tag in the current scope" delay={400} anchorToCursor>
|
||||
<button
|
||||
className="tag-manager-action tag-manager-action-danger inline-flex h-6 w-6 items-center justify-center rounded-md border border-white/10 bg-gray-950/80 text-white/55 transition-colors hover:bg-red-500/10 hover:text-red-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-400/80"
|
||||
onClick={() => setConfirming(true)}
|
||||
aria-label={`Delete ${entry.tag}`}
|
||||
>
|
||||
<DeleteGlyph className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function TagManageList({
|
||||
entries,
|
||||
onSearch,
|
||||
onRename,
|
||||
onDelete,
|
||||
onResetAiTags,
|
||||
scopeLabel,
|
||||
}: {
|
||||
entries: ExploreTagEntry[]
|
||||
onSearch: (tag: string) => void
|
||||
onRename: (from: string, to: string) => Promise<void>
|
||||
onDelete: (tag: string) => Promise<void>
|
||||
onResetAiTags: () => Promise<number>
|
||||
scopeLabel: string
|
||||
}) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const measureRef = useRef<HTMLDivElement>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [sort, setSort] = useState<TagManageSort>('count_desc')
|
||||
const [columns, setColumns] = useState(3)
|
||||
const [resetConfirming, setResetConfirming] = useState(false)
|
||||
const [resetting, setResetting] = useState(false)
|
||||
const [resetStatus, setResetStatus] = useState<string | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = measureRef.current
|
||||
if (!el) return
|
||||
const update = () => {
|
||||
const width = el.getBoundingClientRect().width
|
||||
setColumns(width >= 1160 ? 4 : width >= 780 ? 3 : width >= 520 ? 2 : 1)
|
||||
}
|
||||
update()
|
||||
const ro = new ResizeObserver(update)
|
||||
ro.observe(el)
|
||||
return () => ro.disconnect()
|
||||
}, [])
|
||||
|
||||
const filteredEntries = useMemo(() => {
|
||||
const needle = query.trim().toLowerCase()
|
||||
const filtered = needle
|
||||
? entries.filter((entry) => entry.tag.toLowerCase().includes(needle))
|
||||
: entries
|
||||
return [...filtered].sort((left, right) => {
|
||||
switch (sort) {
|
||||
case 'count_asc':
|
||||
return left.count - right.count || left.tag.localeCompare(right.tag)
|
||||
case 'az':
|
||||
return left.tag.localeCompare(right.tag)
|
||||
case 'za':
|
||||
return right.tag.localeCompare(left.tag)
|
||||
case 'count_desc':
|
||||
default:
|
||||
return right.count - left.count || left.tag.localeCompare(right.tag)
|
||||
}
|
||||
})
|
||||
}, [entries, query, sort])
|
||||
|
||||
const rowCount = Math.ceil(filteredEntries.length / columns)
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: rowCount,
|
||||
getScrollElement: () => scrollRef.current,
|
||||
estimateSize: () => 54,
|
||||
overscan: 7,
|
||||
})
|
||||
const visibleItems = rowVirtualizer.getVirtualItems()
|
||||
const totalUses = useMemo(() => entries.reduce((sum, entry) => sum + entry.count, 0), [entries])
|
||||
|
||||
const runResetAiTags = async () => {
|
||||
if (!resetConfirming) {
|
||||
setResetConfirming(true)
|
||||
setResetStatus(
|
||||
`Reset AI tags for ${scopeLabel}? User tags are preserved, and retagging is not queued automatically.`
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
setResetting(true)
|
||||
setResetStatus(null)
|
||||
try {
|
||||
const count = await onResetAiTags()
|
||||
setResetStatus(
|
||||
count === 0
|
||||
? 'No AI tag data found for this scope.'
|
||||
: `Reset AI tags for ${count.toLocaleString()} image${count === 1 ? '' : 's'}. Queue tagging when you're ready to retag.`
|
||||
)
|
||||
} catch (error) {
|
||||
setResetStatus(String(error))
|
||||
} finally {
|
||||
setResetting(false)
|
||||
setResetConfirming(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<div className="tag-manager-header shrink-0 border-b border-white/[0.05] bg-black/[0.08] px-6 py-4">
|
||||
<div className="flex flex-wrap items-end justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2 text-[11px] text-white/32">
|
||||
<span className="tag-manager-stat rounded-full bg-white/[0.045] px-2 py-1 tabular-nums">
|
||||
{entries.length.toLocaleString()} tags
|
||||
</span>
|
||||
<span className="tag-manager-stat rounded-full bg-white/[0.045] px-2 py-1 tabular-nums">
|
||||
{totalUses.toLocaleString()} uses
|
||||
</span>
|
||||
{query.trim() ? (
|
||||
<span className="tag-manager-match rounded-full bg-blue-500/10 px-2 py-1 text-blue-200/70 tabular-nums">
|
||||
{filteredEntries.length.toLocaleString()} matches
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<p className="tag-manager-help mt-2 max-w-2xl text-[11px] leading-relaxed text-white/28">
|
||||
Rename tags to clean them up, rename into an existing tag to merge, or delete a tag
|
||||
everywhere in the current scope.
|
||||
</p>
|
||||
{resetStatus ? (
|
||||
<p className="mt-2 text-[11px] leading-relaxed text-amber-200/80">{resetStatus}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex min-w-[320px] flex-1 flex-wrap justify-end gap-2">
|
||||
<button
|
||||
className={`tag-manager-reset-button h-9 rounded-lg border px-3 text-xs transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
|
||||
resetConfirming
|
||||
? 'tag-manager-reset-button-confirm border-red-400/30 bg-red-500/15 text-red-200 hover:bg-red-500/25'
|
||||
: 'border-white/8 bg-black/20 text-white/50 hover:bg-white/[0.06] hover:text-white/80'
|
||||
}`}
|
||||
onClick={() => void runResetAiTags()}
|
||||
disabled={resetting}
|
||||
>
|
||||
{resetting ? 'Resetting...' : resetConfirming ? 'Confirm reset' : 'Reset AI tags'}
|
||||
</button>
|
||||
{resetConfirming ? (
|
||||
<button
|
||||
className="tag-manager-reset-cancel h-9 rounded-lg border border-white/8 bg-black/20 px-3 text-xs text-white/45 transition-colors hover:bg-white/[0.06] hover:text-white/75 disabled:opacity-50"
|
||||
onClick={() => {
|
||||
setResetConfirming(false)
|
||||
setResetStatus(null)
|
||||
}}
|
||||
disabled={resetting}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
) : null}
|
||||
<div className="relative min-w-[220px] flex-1 sm:max-w-sm">
|
||||
<input
|
||||
className="tag-manager-filter h-9 w-full rounded-lg border border-white/8 bg-black/20 px-3 pr-8 text-sm text-white/85 transition-colors outline-none placeholder:text-white/22 focus:border-blue-400/35 focus:bg-black/28"
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder="Filter tags"
|
||||
/>
|
||||
{query ? (
|
||||
<span className="absolute top-2 right-2 z-10">
|
||||
<Tooltip label="Clear filter" delay={400} anchorToCursor>
|
||||
<button
|
||||
className="tag-manager-clear inline-flex h-5 w-5 items-center justify-center rounded-md text-white/35 transition-colors hover:bg-white/8 hover:text-white/75 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/70"
|
||||
onClick={() => setQuery('')}
|
||||
aria-label="Clear tag filter"
|
||||
>
|
||||
<svg
|
||||
className="h-3.5 w-3.5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2.2}
|
||||
d="M6 6l12 12M18 6L6 18"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<Dropdown
|
||||
value={sort}
|
||||
onChange={setSort}
|
||||
options={TAG_MANAGE_SORTS}
|
||||
ariaLabel="Sort managed tags"
|
||||
align="right"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={scrollRef}
|
||||
data-tag-manager-scroll
|
||||
className="min-h-0 flex-1 overflow-y-auto px-6 py-5"
|
||||
>
|
||||
<div ref={measureRef} className="mx-auto w-full max-w-7xl">
|
||||
{filteredEntries.length === 0 ? (
|
||||
<div className="tag-manager-empty flex h-48 items-center justify-center rounded-lg border border-white/[0.06] bg-white/[0.02] text-sm text-white/30">
|
||||
No tags match that filter.
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="relative w-full"
|
||||
style={{ height: `${rowVirtualizer.getTotalSize()}px` }}
|
||||
>
|
||||
{visibleItems.map((virtualRow) => {
|
||||
const start = virtualRow.index * columns
|
||||
const rowEntries = filteredEntries.slice(start, start + columns)
|
||||
return (
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
data-index={virtualRow.index}
|
||||
ref={rowVirtualizer.measureElement}
|
||||
className="absolute top-0 left-0 grid w-full gap-x-2 pb-2"
|
||||
style={{
|
||||
gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
|
||||
transform: `translateY(${virtualRow.start}px)`,
|
||||
}}
|
||||
>
|
||||
{rowEntries.map((entry) => (
|
||||
<TagManageTile
|
||||
key={entry.tag}
|
||||
entry={entry}
|
||||
onSearch={onSearch}
|
||||
onRename={onRename}
|
||||
onDelete={onDelete}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
export const ACCENTS = [
|
||||
'#60a5fa',
|
||||
'#c084fc',
|
||||
'#4ade80',
|
||||
'#fbbf24',
|
||||
'#f472b4',
|
||||
'#2dd4bf',
|
||||
'#fb923c',
|
||||
'#a78bfa',
|
||||
'#34d399',
|
||||
'#f87171',
|
||||
]
|
||||
|
||||
// Darker variants of each accent for the light theme -- the bright originals are
|
||||
// tuned for dark cards and wash out on the cream background.
|
||||
export const LIGHT_ACCENTS = [
|
||||
'#2563eb',
|
||||
'#9333ea',
|
||||
'#16a34a',
|
||||
'#d97706',
|
||||
'#db2777',
|
||||
'#0d9488',
|
||||
'#ea580c',
|
||||
'#7c3aed',
|
||||
'#059669',
|
||||
'#dc2626',
|
||||
]
|
||||
|
||||
export const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5))
|
||||
|
||||
export function seeded(n: number): number {
|
||||
const x = Math.sin(n * 9301 + 49297) * 233280
|
||||
return x - Math.floor(x)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { DirEntry } from '../../store'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CheckIcon, ChevronRightIcon } from '../icons'
|
||||
|
||||
export function FolderRow({
|
||||
entry,
|
||||
selected,
|
||||
alreadyAdded,
|
||||
onToggle,
|
||||
onNavigate,
|
||||
}: {
|
||||
entry: DirEntry
|
||||
selected: boolean
|
||||
alreadyAdded: boolean
|
||||
onToggle: () => void
|
||||
onNavigate: () => void
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`group flex h-11 items-center gap-3 rounded-md border px-3 transition-colors ${
|
||||
alreadyAdded
|
||||
? 'light-theme:bg-gray-900 light-theme:text-gray-500 border-transparent bg-white/[0.025] text-gray-600'
|
||||
: selected
|
||||
? 'light-theme:border-gray-700/45 light-theme:bg-gray-800/55 light-theme:text-white border-white/15 bg-white/[0.085] text-white shadow-[inset_0_0_0_1px_rgb(255_255_255_/_0.035)]'
|
||||
: 'light-theme:text-gray-500 light-theme:hover:bg-gray-900 light-theme:hover:text-white border-transparent text-gray-300 hover:bg-white/[0.055] hover:text-white'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={`grid h-5 w-5 shrink-0 place-items-center rounded border transition-colors ${
|
||||
selected
|
||||
? 'light-theme:border-gray-700/55 light-theme:bg-gray-700 light-theme:text-white border-white/30 bg-gray-200 text-gray-950'
|
||||
: 'light-theme:border-gray-700/50 light-theme:bg-gray-950 border-white/15 bg-white/[0.035] text-transparent hover:border-white/30'
|
||||
} ${alreadyAdded ? 'cursor-not-allowed opacity-40' : ''}`}
|
||||
onClick={onToggle}
|
||||
disabled={alreadyAdded}
|
||||
aria-label={selected ? `Remove ${entry.name} from folders to add` : `Choose ${entry.name}`}
|
||||
>
|
||||
<CheckIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
|
||||
<Tooltip label={entry.path} anchorToCursor className="min-w-0 flex-1">
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full min-w-0 items-center gap-2 text-left"
|
||||
onClick={onNavigate}
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4 shrink-0 text-amber-300/90"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M3 6.5A2.5 2.5 0 015.5 4h4.1l2 2H18.5A2.5 2.5 0 0121 8.5v9A2.5 2.5 0 0118.5 20h-13A2.5 2.5 0 013 17.5v-11z" />
|
||||
</svg>
|
||||
<span className="truncate text-sm">{entry.name}</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
|
||||
{alreadyAdded ? (
|
||||
<span className="light-theme:border-gray-700/40 light-theme:bg-gray-950 rounded-md border border-white/10 bg-white/[0.04] px-2 py-0.5 text-[11px] text-gray-500">
|
||||
Added
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<Tooltip label={entry.has_children ? 'Open folder' : 'No subfolders'} anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:hover:bg-gray-900 light-theme:hover:text-white rounded-md p-1 text-gray-500 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={onNavigate}
|
||||
>
|
||||
<ChevronRightIcon className={`h-4 w-4 ${entry.has_children ? '' : 'opacity-45'}`} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CloseIcon } from '../icons'
|
||||
import { folderName } from './pathUtils'
|
||||
|
||||
export function StagedFoldersPanel({
|
||||
stagedPaths,
|
||||
onRemove,
|
||||
onClear,
|
||||
}: {
|
||||
stagedPaths: string[]
|
||||
onRemove: (path: string) => void
|
||||
onClear: () => void
|
||||
}) {
|
||||
return (
|
||||
<aside className="light-theme:border-gray-300/70 light-theme:bg-gray-900/35 flex min-h-0 w-full flex-col border-t border-white/[0.07] bg-white/[0.018] lg:w-80 lg:border-t-0 lg:border-l">
|
||||
<div className="light-theme:border-gray-300/70 flex items-center justify-between gap-3 border-b border-white/[0.07] px-5 py-4">
|
||||
<p className="text-[11px] font-semibold tracking-[0.16em] text-gray-500 uppercase">
|
||||
Folders to add ({stagedPaths.length})
|
||||
</p>
|
||||
{stagedPaths.length > 0 ? (
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:text-gray-500 light-theme:hover:bg-gray-800 light-theme:hover:text-white rounded px-1.5 py-0.5 text-xs text-gray-400 transition-colors hover:bg-white/[0.06] hover:text-white"
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear all
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-3">
|
||||
{stagedPaths.length === 0 ? (
|
||||
<div className="light-theme:border-gray-700/35 flex h-full min-h-40 flex-col items-center justify-center rounded-md border border-dashed border-white/[0.08] px-5 text-center">
|
||||
<p className="text-sm text-gray-500">No folders selected.</p>
|
||||
<p className="light-theme:text-gray-500 mt-1 max-w-52 text-xs leading-relaxed text-gray-600">
|
||||
Choose folders on the left and they will collect here.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{stagedPaths.map((path) => (
|
||||
<Tooltip key={path} label={path} anchorToCursor block>
|
||||
<div className="group light-theme:border-gray-700/40 light-theme:bg-gray-900 light-theme:text-white light-theme:hover:bg-gray-800 flex min-h-12 items-center gap-2 rounded-md border border-white/[0.07] bg-white/[0.045] px-3 py-2 text-gray-200 transition-colors hover:border-white/15 hover:bg-white/[0.07]">
|
||||
<svg
|
||||
className="h-4 w-4 shrink-0 text-amber-300/90"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path d="M3 6.5A2.5 2.5 0 015.5 4h4.1l2 2H18.5A2.5 2.5 0 0121 8.5v9A2.5 2.5 0 0118.5 20h-13A2.5 2.5 0 013 17.5v-11z" />
|
||||
</svg>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-medium">{folderName(path)}</p>
|
||||
<p className="light-theme:text-gray-500 mt-0.5 truncate text-[11px] text-gray-600">
|
||||
{path}
|
||||
</p>
|
||||
</div>
|
||||
<Tooltip label="Remove from folders to add" anchorToCursor>
|
||||
<button
|
||||
type="button"
|
||||
className="light-theme:hover:bg-gray-700 rounded-md p-1 text-gray-500 opacity-80 transition-colors group-hover:opacity-100 hover:bg-white/[0.08] hover:text-white"
|
||||
onClick={() => onRemove(path)}
|
||||
aria-label={`Remove ${path} from folders to add`}
|
||||
>
|
||||
<CloseIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { FolderAddResult } from '../../store'
|
||||
|
||||
export function StatusLine({ results }: { results: FolderAddResult[] | null }) {
|
||||
if (!results) return null
|
||||
const added = results.filter((result) => result.status === 'added').length
|
||||
const skipped = results.filter((result) => result.status === 'skipped').length
|
||||
const failed = results.filter((result) => result.status === 'error').length
|
||||
return (
|
||||
<p className="light-theme:text-gray-600 text-xs text-gray-500">
|
||||
Added {added}, skipped {skipped}, failed {failed}.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildBreadcrumbs,
|
||||
cleanAddressInput,
|
||||
folderName,
|
||||
friendlyDirectoryError,
|
||||
normalizePath,
|
||||
} from './pathUtils'
|
||||
|
||||
describe('normalizePath', () => {
|
||||
it('converts backslashes, strips trailing slashes, and lowercases', () => {
|
||||
expect(normalizePath('C:\\Users\\Me\\Pictures\\')).toBe('c:/users/me/pictures')
|
||||
expect(normalizePath('/home/User/photos///')).toBe('/home/user/photos')
|
||||
expect(normalizePath('relative/path')).toBe('relative/path')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cleanAddressInput', () => {
|
||||
it('strips matching surrounding quotes', () => {
|
||||
expect(cleanAddressInput('"C:\\Photos"')).toBe('C:\\Photos')
|
||||
expect(cleanAddressInput("'C:\\Photos'")).toBe('C:\\Photos')
|
||||
})
|
||||
|
||||
it('leaves mismatched quotes alone', () => {
|
||||
expect(cleanAddressInput('"C:\\Photos\'')).toBe('"C:\\Photos\'')
|
||||
})
|
||||
|
||||
it('trims whitespace inside and outside quotes', () => {
|
||||
expect(cleanAddressInput(' " C:\\Photos " ')).toBe('C:\\Photos')
|
||||
expect(cleanAddressInput(' C:\\Photos ')).toBe('C:\\Photos')
|
||||
})
|
||||
})
|
||||
|
||||
describe('friendlyDirectoryError', () => {
|
||||
it('maps not-found style errors to a friendly message', () => {
|
||||
expect(friendlyDirectoryError(new Error('The system cannot find the path specified.'))).toBe(
|
||||
'Folder not found. Check the path and try again.'
|
||||
)
|
||||
expect(friendlyDirectoryError(new Error('os error 3'))).toBe(
|
||||
'Folder not found. Check the path and try again.'
|
||||
)
|
||||
expect(friendlyDirectoryError('No such file or directory')).toBe(
|
||||
'Folder not found. Check the path and try again.'
|
||||
)
|
||||
})
|
||||
|
||||
it('passes other messages through', () => {
|
||||
expect(friendlyDirectoryError(new Error('Access denied'))).toBe('Access denied')
|
||||
expect(friendlyDirectoryError(42)).toBe('42')
|
||||
})
|
||||
})
|
||||
|
||||
describe('folderName', () => {
|
||||
it('returns the final path component', () => {
|
||||
expect(folderName('C:\\Users\\me\\Pictures')).toBe('Pictures')
|
||||
expect(folderName('/home/user/photos/')).toBe('photos')
|
||||
})
|
||||
|
||||
it('handles roots', () => {
|
||||
expect(folderName('C:\\')).toBe('C:')
|
||||
expect(folderName('/')).toBe('/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildBreadcrumbs', () => {
|
||||
it('returns the home crumb for null paths', () => {
|
||||
expect(buildBreadcrumbs(null)).toEqual([{ label: 'This PC / Home', path: null }])
|
||||
})
|
||||
|
||||
it('builds Windows drive breadcrumbs', () => {
|
||||
expect(buildBreadcrumbs('C:\\Users\\me')).toEqual([
|
||||
{ label: 'This PC', path: null },
|
||||
{ label: 'C:', path: 'C:' },
|
||||
{ label: 'Users', path: 'C:\\Users' },
|
||||
{ label: 'me', path: 'C:\\Users\\me' },
|
||||
])
|
||||
})
|
||||
|
||||
it('builds Unix breadcrumbs', () => {
|
||||
expect(buildBreadcrumbs('/home/user')).toEqual([
|
||||
{ label: '/', path: null },
|
||||
{ label: 'home', path: '/home' },
|
||||
{ label: 'user', path: '/home/user' },
|
||||
])
|
||||
})
|
||||
|
||||
it('ignores trailing separators', () => {
|
||||
const crumbs = buildBreadcrumbs('C:\\Users\\')
|
||||
expect(crumbs.map((c) => c.label)).toEqual(['This PC', 'C:', 'Users'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
export interface Breadcrumb {
|
||||
label: string
|
||||
path: string | null
|
||||
}
|
||||
|
||||
export function normalizePath(path: string): string {
|
||||
return path.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
|
||||
}
|
||||
|
||||
export function cleanAddressInput(path: string): string {
|
||||
const trimmed = path.trim()
|
||||
if (trimmed.length >= 2) {
|
||||
const first = trimmed[0]
|
||||
const last = trimmed[trimmed.length - 1]
|
||||
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
|
||||
return trimmed.slice(1, -1).trim()
|
||||
}
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
export function friendlyDirectoryError(error: unknown): string {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
if (/cannot find the path|os error 3|not found|no such file/i.test(message)) {
|
||||
return 'Folder not found. Check the path and try again.'
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
export function folderName(path: string): string {
|
||||
const trimmed = path.replace(/[\\/]+$/, '')
|
||||
const parts = trimmed.split(/[\\/]+/).filter(Boolean)
|
||||
return parts.length > 0 ? parts[parts.length - 1] : path
|
||||
}
|
||||
|
||||
export function buildBreadcrumbs(path: string | null): Breadcrumb[] {
|
||||
if (!path) return [{ label: 'This PC / Home', path: null }]
|
||||
|
||||
const separator = path.includes('\\') ? '\\' : '/'
|
||||
const normalized = path.replace(/[\\/]+$/, '')
|
||||
const windowsDrive = normalized.match(/^[A-Za-z]:/)
|
||||
|
||||
if (windowsDrive) {
|
||||
const drive = windowsDrive[0]
|
||||
const rest = normalized
|
||||
.slice(2)
|
||||
.split(/[\\/]+/)
|
||||
.filter(Boolean)
|
||||
let current = drive
|
||||
return [
|
||||
{ label: 'This PC', path: null },
|
||||
{ label: drive, path: drive },
|
||||
...rest.map((part) => {
|
||||
current = current.endsWith('\\') ? `${current}${part}` : `${current}\\${part}`
|
||||
return { label: part, path: current }
|
||||
}),
|
||||
]
|
||||
}
|
||||
|
||||
const parts = normalized.split(/[\\/]+/).filter(Boolean)
|
||||
let current = separator === '/' ? '' : ''
|
||||
return [
|
||||
{ label: '/', path: null },
|
||||
...parts.map((part) => {
|
||||
current = `${current}/${part}`
|
||||
return { label: part, path: current }
|
||||
}),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { DirListing, FolderAddResult, useGalleryStore } from '../../store'
|
||||
import {
|
||||
buildBreadcrumbs,
|
||||
cleanAddressInput,
|
||||
friendlyDirectoryError,
|
||||
normalizePath,
|
||||
} from './pathUtils'
|
||||
|
||||
export function useFolderPicker() {
|
||||
const folderPickerOpen = useGalleryStore((state) => state.folderPickerOpen)
|
||||
const setFolderPickerOpen = useGalleryStore((state) => state.setFolderPickerOpen)
|
||||
const folders = useGalleryStore((state) => state.folders)
|
||||
const listDirectories = useGalleryStore((state) => state.listDirectories)
|
||||
const addFolders = useGalleryStore((state) => state.addFolders)
|
||||
|
||||
const [listing, setListing] = useState<DirListing | null>(null)
|
||||
const [currentPath, setCurrentPath] = useState<string | null>(null)
|
||||
const [addressDraft, setAddressDraft] = useState('')
|
||||
const [addressEditing, setAddressEditing] = useState(false)
|
||||
const [stagedPaths, setStagedPaths] = useState<string[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [results, setResults] = useState<FolderAddResult[] | null>(null)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const addressInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const libraryPaths = useMemo(
|
||||
() => new Set(folders.map((folder) => normalizePath(folder.path))),
|
||||
[folders]
|
||||
)
|
||||
const stagedSet = useMemo(() => new Set(stagedPaths.map(normalizePath)), [stagedPaths])
|
||||
const breadcrumbs = useMemo(() => buildBreadcrumbs(listing?.current ?? null), [listing?.current])
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderPickerOpen) return
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
void listDirectories(currentPath)
|
||||
.then((nextListing) => {
|
||||
if (cancelled) return
|
||||
setListing(nextListing)
|
||||
setAddressDraft(nextListing.current ?? '')
|
||||
setAddressEditing(false)
|
||||
scrollRef.current?.scrollTo({ top: 0, left: 0 })
|
||||
})
|
||||
.catch((loadError) => {
|
||||
if (cancelled) return
|
||||
setListing({ current: currentPath, parent: null, entries: [] })
|
||||
setError(friendlyDirectoryError(loadError))
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [currentPath, folderPickerOpen, listDirectories])
|
||||
|
||||
useEffect(() => {
|
||||
if (!folderPickerOpen) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
if (addressEditing) {
|
||||
setAddressDraft(listing?.current ?? '')
|
||||
setAddressEditing(false)
|
||||
return
|
||||
}
|
||||
setFolderPickerOpen(false)
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
return () => window.removeEventListener('keydown', handleKeyDown)
|
||||
}, [addressEditing, folderPickerOpen, listing?.current, setFolderPickerOpen])
|
||||
|
||||
useEffect(() => {
|
||||
if (!addressEditing) return
|
||||
requestAnimationFrame(() => {
|
||||
addressInputRef.current?.focus()
|
||||
addressInputRef.current?.select()
|
||||
})
|
||||
}, [addressEditing])
|
||||
|
||||
useEffect(() => {
|
||||
if (folderPickerOpen) return
|
||||
setCurrentPath(null)
|
||||
setAddressDraft('')
|
||||
setAddressEditing(false)
|
||||
setListing(null)
|
||||
setStagedPaths([])
|
||||
setError(null)
|
||||
setResults(null)
|
||||
setAdding(false)
|
||||
}, [folderPickerOpen])
|
||||
|
||||
const entries = listing?.entries ?? []
|
||||
const addressPath = cleanAddressInput(addressEditing ? addressDraft : (listing?.current ?? ''))
|
||||
const normalizedAddressPath = addressPath ? normalizePath(addressPath) : ''
|
||||
const addressAlreadyAdded = normalizedAddressPath
|
||||
? libraryPaths.has(normalizedAddressPath)
|
||||
: false
|
||||
const addressAlreadyStaged = normalizedAddressPath ? stagedSet.has(normalizedAddressPath) : false
|
||||
|
||||
const togglePath = (path: string) => {
|
||||
const normalized = normalizePath(path)
|
||||
if (libraryPaths.has(normalized)) return
|
||||
setResults(null)
|
||||
setStagedPaths((current) => {
|
||||
const exists = current.some((staged) => normalizePath(staged) === normalized)
|
||||
return exists
|
||||
? current.filter((staged) => normalizePath(staged) !== normalized)
|
||||
: [...current, path]
|
||||
})
|
||||
}
|
||||
|
||||
const stagePath = (path: string) => {
|
||||
const cleaned = cleanAddressInput(path)
|
||||
if (!cleaned) {
|
||||
setError('Enter a folder path first.')
|
||||
return
|
||||
}
|
||||
|
||||
const normalized = normalizePath(cleaned)
|
||||
if (libraryPaths.has(normalized)) {
|
||||
setError('That folder is already in your library.')
|
||||
return
|
||||
}
|
||||
if (stagedSet.has(normalized)) {
|
||||
setError('That folder is already selected.')
|
||||
return
|
||||
}
|
||||
|
||||
setError(null)
|
||||
setResults(null)
|
||||
setStagedPaths((current) => [...current, cleaned])
|
||||
}
|
||||
|
||||
const navigateToAddress = () => {
|
||||
const cleaned = cleanAddressInput(addressDraft)
|
||||
setResults(null)
|
||||
setError(null)
|
||||
setCurrentPath(cleaned || null)
|
||||
}
|
||||
|
||||
const updateAddressDraft = (nextDraft: string) => {
|
||||
setAddressDraft(nextDraft)
|
||||
setResults(null)
|
||||
}
|
||||
|
||||
const beginAddressEdit = () => {
|
||||
setAddressDraft(listing?.current ?? '')
|
||||
setAddressEditing(true)
|
||||
}
|
||||
|
||||
const removeStagedPath = (path: string) => {
|
||||
const normalized = normalizePath(path)
|
||||
setResults(null)
|
||||
setStagedPaths((current) => current.filter((staged) => normalizePath(staged) !== normalized))
|
||||
}
|
||||
|
||||
const clearStagedPaths = () => {
|
||||
setResults(null)
|
||||
setStagedPaths([])
|
||||
}
|
||||
|
||||
const confirmAdd = async () => {
|
||||
if (stagedPaths.length === 0 || adding) return
|
||||
setAdding(true)
|
||||
setError(null)
|
||||
try {
|
||||
const addResults = await addFolders(stagedPaths)
|
||||
const failed = addResults.filter((result) => result.status === 'error')
|
||||
setResults(addResults)
|
||||
if (failed.length > 0) {
|
||||
setStagedPaths(stagedPaths.filter((_, i) => addResults[i]?.status === 'error'))
|
||||
setError(failed.map((failure) => failure.data).join('; '))
|
||||
return
|
||||
}
|
||||
setFolderPickerOpen(false)
|
||||
} catch (addError) {
|
||||
setError(addError instanceof Error ? addError.message : String(addError))
|
||||
} finally {
|
||||
setAdding(false)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
adding,
|
||||
addressAlreadyAdded,
|
||||
addressAlreadyStaged,
|
||||
addressDraft,
|
||||
addressEditing,
|
||||
addressInputRef,
|
||||
addressPath,
|
||||
beginAddressEdit,
|
||||
breadcrumbs,
|
||||
clearStagedPaths,
|
||||
confirmAdd,
|
||||
entries,
|
||||
error,
|
||||
folderPickerOpen,
|
||||
libraryPaths,
|
||||
listing,
|
||||
loading,
|
||||
navigateToAddress,
|
||||
removeStagedPath,
|
||||
results,
|
||||
scrollRef,
|
||||
setCurrentPath,
|
||||
setFolderPickerOpen,
|
||||
stagePath,
|
||||
stagedPaths,
|
||||
stagedSet,
|
||||
togglePath,
|
||||
updateAddressDraft,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { ParsedSearch } from '../../store'
|
||||
import { PhotoIcon } from '../icons'
|
||||
|
||||
export function GalleryLoadingState({
|
||||
isSimilarResults,
|
||||
parsedSearch,
|
||||
}: {
|
||||
isSimilarResults: boolean
|
||||
parsedSearch: ParsedSearch
|
||||
}) {
|
||||
return (
|
||||
<div className="absolute inset-0 flex flex-1 flex-col items-center justify-center gap-4 px-8 text-center">
|
||||
<div className="min-w-72 rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<div className="mx-auto h-5 w-5 animate-spin rounded-full border-2 border-white/20 border-t-white/60" />
|
||||
<p className="mt-4 text-sm font-medium text-white/40">
|
||||
{isSimilarResults
|
||||
? 'Finding similar images'
|
||||
: parsedSearch.mode === 'semantic' && parsedSearch.query.length > 0
|
||||
? `Searching for matches to "${parsedSearch.query}"`
|
||||
: parsedSearch.mode === 'tag' && parsedSearch.query.length > 0
|
||||
? `Searching tags for "${parsedSearch.query}"`
|
||||
: 'Loading media'}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-white/20">
|
||||
{isSimilarResults
|
||||
? 'Comparing visual embeddings'
|
||||
: parsedSearch.mode === 'semantic' && parsedSearch.query.length > 0
|
||||
? 'Semantic search can take a little longer than filename search'
|
||||
: parsedSearch.mode === 'tag' && parsedSearch.query.length > 0
|
||||
? 'Matching against AI and user tags'
|
||||
: 'Fetching results'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function GalleryEmptyState({
|
||||
imageLoadError,
|
||||
isSimilarResults,
|
||||
parsedSearch,
|
||||
}: {
|
||||
imageLoadError: string | null
|
||||
isSimilarResults: boolean
|
||||
parsedSearch: ParsedSearch
|
||||
}) {
|
||||
return (
|
||||
<div className="absolute inset-0 flex flex-1 flex-col items-center justify-center gap-4 px-8 text-center">
|
||||
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-8">
|
||||
<PhotoIcon className="mx-auto mb-4 h-12 w-12 text-white/10" strokeWidth={0.75} />
|
||||
<p className="text-sm font-medium text-white/30">
|
||||
{imageLoadError
|
||||
? 'Could not load results'
|
||||
: isSimilarResults
|
||||
? 'No similar images found'
|
||||
: parsedSearch.mode === 'semantic' && parsedSearch.query.length > 0
|
||||
? 'No semantic matches found'
|
||||
: parsedSearch.mode === 'tag' && parsedSearch.query.length > 0
|
||||
? 'No tag matches found'
|
||||
: 'No media found'}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-white/15">
|
||||
{imageLoadError
|
||||
? imageLoadError
|
||||
: isSimilarResults
|
||||
? 'This item may be visually isolated, or more embeddings may need to finish processing'
|
||||
: parsedSearch.mode === 'semantic' && parsedSearch.query.length > 0
|
||||
? 'Try a broader phrase, or wait for more embeddings to finish processing'
|
||||
: parsedSearch.mode === 'tag' && parsedSearch.query.length > 0
|
||||
? 'Try a shorter tag, or wait for more tagging jobs to finish'
|
||||
: 'Try adjusting your filters or add a new folder'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { useState } from 'react'
|
||||
import { ImageRecord, useGalleryStore } from '../../store'
|
||||
import { mediaSrc } from '../../lib/mediaSrc'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CheckIcon, PhotoIcon, PlayIcon, StarIcon, WarningIcon } from '../icons'
|
||||
import { formatDuration } from './format'
|
||||
import { TruncatedFilename } from './TruncatedFilename'
|
||||
|
||||
export function ImageTile({
|
||||
image,
|
||||
onClick,
|
||||
onContextMenu,
|
||||
}: {
|
||||
image: ImageRecord
|
||||
onClick: () => void
|
||||
onContextMenu: (event: React.MouseEvent<HTMLDivElement>) => void
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [errored, setErrored] = useState(false)
|
||||
const findSimilar = useGalleryStore((state) => state.findSimilar)
|
||||
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 src = mediaSrc(image.thumbnail_path)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`media-dark-surface group relative overflow-hidden rounded-xl bg-white/[0.04] text-left transition-shadow focus:outline-none ${
|
||||
selected ? 'ring-2 ring-blue-400/80 ring-inset' : ''
|
||||
}`}
|
||||
style={{ width: '100%', aspectRatio: '1 / 1' }}
|
||||
onContextMenu={onContextMenu}
|
||||
>
|
||||
<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()
|
||||
}}
|
||||
/>
|
||||
<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'
|
||||
}`}
|
||||
>
|
||||
<CheckIcon className="h-3 w-3" strokeWidth={3} />
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{src && !errored ? (
|
||||
<>
|
||||
{!loaded ? <div className="absolute inset-0 animate-pulse bg-white/[0.04]" /> : null}
|
||||
<img
|
||||
src={src}
|
||||
alt={image.filename}
|
||||
className={`h-full w-full object-cover transition-all duration-300 ${
|
||||
loaded ? 'scale-100 opacity-100' : 'scale-[1.02] opacity-0'
|
||||
} group-hover:scale-[1.03]`}
|
||||
loading="lazy"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setErrored(true)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/[0.03] text-white/20">
|
||||
{image.media_kind === 'video' ? (
|
||||
<PlayIcon className="h-7 w-7" />
|
||||
) : (
|
||||
<PhotoIcon className="h-7 w-7" strokeWidth={1} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{image.media_kind === 'video' ? (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
|
||||
<div className="rounded-full bg-black/40 p-3 text-white opacity-50 backdrop-blur-sm transition-opacity duration-200 group-hover:opacity-90">
|
||||
<PlayIcon className="h-5 w-5" />
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="pointer-events-none absolute top-2 right-2 flex flex-col items-end gap-1">
|
||||
{image.embedding_status === 'failed' ? (
|
||||
<Tooltip
|
||||
label={image.embedding_error ?? 'Embedding failed'}
|
||||
followCursor
|
||||
className="pointer-events-auto"
|
||||
>
|
||||
<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">
|
||||
<WarningIcon className="h-2.5 w-2.5 shrink-0" strokeWidth={2.5} />
|
||||
</div>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
{image.favorite ? (
|
||||
<div className="rounded-full bg-black/50 p-1 text-rose-400 backdrop-blur-sm">
|
||||
<svg className="h-2.5 w-2.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
|
||||
</svg>
|
||||
</div>
|
||||
) : null}
|
||||
{image.rating > 0 ? (
|
||||
<div className="flex items-center gap-0.5 rounded-md bg-black/60 px-1.5 py-1 text-amber-300 backdrop-blur-sm">
|
||||
{Array.from({ length: image.rating }, (_, index) => (
|
||||
<StarIcon key={index} className="h-2.5 w-2.5" />
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{image.media_kind === 'video' && image.duration_ms ? (
|
||||
<div className="rounded-md bg-black/60 px-1.5 py-0.5 text-[10px] font-medium text-white/80 backdrop-blur-sm">
|
||||
{formatDuration(image.duration_ms)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/85 via-black/30 to-transparent opacity-0 transition-opacity duration-200 group-hover:opacity-100" />
|
||||
|
||||
<div className="absolute right-0 bottom-0 left-0 z-20 translate-y-1 p-2.5 opacity-0 transition-all duration-200 group-hover:translate-y-0 group-hover:opacity-100">
|
||||
<TruncatedFilename filename={image.filename} />
|
||||
<div className="mt-1.5 flex items-center justify-between gap-2">
|
||||
{image.rating > 0 ? (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{Array.from({ length: image.rating }, (_, index) => (
|
||||
<StarIcon key={index} className="h-2.5 w-2.5 text-amber-300" />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<button
|
||||
className={`pointer-events-auto relative z-20 rounded-md px-2 py-0.5 text-[10px] backdrop-blur-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400/80 ${
|
||||
canFindSimilar
|
||||
? 'bg-white/10 text-white/80 hover:bg-white/20 hover:text-white'
|
||||
: 'cursor-not-allowed bg-white/5 text-white/30'
|
||||
}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
if (!canFindSimilar) return
|
||||
findSimilar(image.id, image.folder_id)
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
Similar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
|
||||
export function TruncatedFilename({ filename }: { filename: string }) {
|
||||
const textRef = useRef<HTMLParagraphElement>(null)
|
||||
const [isTruncated, setIsTruncated] = useState(false)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const text = textRef.current
|
||||
if (!text) return
|
||||
|
||||
const update = () => {
|
||||
setIsTruncated(text.scrollWidth > text.clientWidth)
|
||||
}
|
||||
|
||||
update()
|
||||
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(text)
|
||||
return () => observer.disconnect()
|
||||
}, [filename])
|
||||
|
||||
const label = (
|
||||
<p ref={textRef} className="truncate text-[12px] leading-tight font-medium text-white">
|
||||
{filename}
|
||||
</p>
|
||||
)
|
||||
|
||||
return (
|
||||
<Tooltip label={filename} delay={500} block followCursor disabled={!isTruncated}>
|
||||
{label}
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { formatDuration } from './format'
|
||||
|
||||
describe('formatDuration', () => {
|
||||
it('returns null for missing or non-positive durations', () => {
|
||||
expect(formatDuration(null)).toBeNull()
|
||||
expect(formatDuration(0)).toBeNull()
|
||||
expect(formatDuration(-100)).toBeNull()
|
||||
})
|
||||
|
||||
it('formats sub-hour durations as M:SS', () => {
|
||||
expect(formatDuration(1000)).toBe('0:01')
|
||||
expect(formatDuration(59_999)).toBe('0:59')
|
||||
expect(formatDuration(65_000)).toBe('1:05')
|
||||
})
|
||||
|
||||
it('formats hour-plus durations as H:MM:SS', () => {
|
||||
expect(formatDuration(3_600_000)).toBe('1:00:00')
|
||||
expect(formatDuration(3_661_000)).toBe('1:01:01')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
export function formatDuration(durationMs: number | null): string | null {
|
||||
if (!durationMs || durationMs <= 0) return null
|
||||
const totalSeconds = Math.floor(durationMs / 1000)
|
||||
const seconds = totalSeconds % 60
|
||||
const minutes = Math.floor(totalSeconds / 60) % 60
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
if (hours > 0) {
|
||||
return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
|
||||
}
|
||||
return `${minutes}:${seconds.toString().padStart(2, '0')}`
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Shared icons for paths that repeat across the app. One-off icons stay
|
||||
* inline at their call site — only extract here once a shape shows up in
|
||||
* three or more places. Stroke icons take a per-site strokeWidth because
|
||||
* weights legitimately differ by context (menus vs badges vs empty states).
|
||||
*/
|
||||
|
||||
export interface IconProps {
|
||||
className?: string
|
||||
strokeWidth?: number
|
||||
}
|
||||
|
||||
function strokeIcon(d: string, defaultStrokeWidth: number, displayName: string) {
|
||||
function Icon({ className = '', strokeWidth = defaultStrokeWidth }: IconProps) {
|
||||
return (
|
||||
<svg
|
||||
className={className}
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d={d} />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
Icon.displayName = displayName
|
||||
return Icon
|
||||
}
|
||||
|
||||
export const CheckIcon = strokeIcon('M5 13l4 4L19 7', 2.5, 'CheckIcon')
|
||||
export const CloseIcon = strokeIcon('M6 18L18 6M6 6l12 12', 2, 'CloseIcon')
|
||||
export const ChevronDownIcon = strokeIcon('M19 9l-7 7-7-7', 2, 'ChevronDownIcon')
|
||||
export const ChevronRightIcon = strokeIcon('M9 5l7 7-7 7', 2, 'ChevronRightIcon')
|
||||
export const PlusIcon = strokeIcon('M12 4v16m8-8H4', 1.75, 'PlusIcon')
|
||||
export const PhotoIcon = strokeIcon(
|
||||
'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',
|
||||
1.5,
|
||||
'PhotoIcon'
|
||||
)
|
||||
export const FolderIcon = strokeIcon(
|
||||
'M3 7a2 2 0 012-2h3.586a1 1 0 01.707.293l1.414 1.414A1 1 0 0011.414 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z',
|
||||
1.5,
|
||||
'FolderIcon'
|
||||
)
|
||||
export const WarningIcon = strokeIcon(
|
||||
'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',
|
||||
2,
|
||||
'WarningIcon'
|
||||
)
|
||||
|
||||
export function StarIcon({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} fill="currentColor" viewBox="0 0 20 20" aria-hidden="true">
|
||||
<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>
|
||||
)
|
||||
}
|
||||
|
||||
export function PlayIcon({ className = '' }: { className?: string }) {
|
||||
return (
|
||||
<svg className={className} fill="currentColor" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useState } from 'react'
|
||||
import { Album } from '../../store'
|
||||
|
||||
interface LightboxAlbumMenuProps {
|
||||
imageId: number
|
||||
albums: Album[]
|
||||
addToAlbum: (albumId: number, imageIds: number[]) => Promise<number>
|
||||
createAlbum: (name: string) => Promise<Album>
|
||||
}
|
||||
|
||||
export function LightboxAlbumMenu({
|
||||
imageId,
|
||||
albums,
|
||||
addToAlbum,
|
||||
createAlbum,
|
||||
}: LightboxAlbumMenuProps) {
|
||||
const [albumMenuOpen, setAlbumMenuOpen] = useState(false)
|
||||
const [albumAddedTo, setAlbumAddedTo] = useState<number | null>(null)
|
||||
const [newAlbumName, setNewAlbumName] = useState('')
|
||||
const [albumAdding, setAlbumAdding] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<p className="text-xs tracking-wider text-gray-500 uppercase">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((open) => !open)
|
||||
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, [imageId])
|
||||
.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={(event) => {
|
||||
event.preventDefault()
|
||||
const name = newAlbumName.trim()
|
||||
if (!name || albumAdding) return
|
||||
setAlbumAdding(true)
|
||||
void createAlbum(name)
|
||||
.then(async (album) => {
|
||||
await addToAlbum(album.id, [imageId])
|
||||
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={(event) => setNewAlbumName(event.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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
import { MutableRefObject } from 'react'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { revealItemInDir } from '@tauri-apps/plugin-opener'
|
||||
import { Album, ImageExif, ImageRecord, ImageTag } from '../../store'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { CloseIcon, StarIcon } from '../icons'
|
||||
import { embeddingLabel, formatBytes, formatDate, formatDuration, ratingPill } from './format'
|
||||
import { LightboxAlbumMenu } from './LightboxAlbumMenu'
|
||||
|
||||
interface LightboxDetailsPanelProps {
|
||||
selectedImage: ImageRecord
|
||||
currentIndex: number
|
||||
imageCount: number
|
||||
imageTags: ImageTag[]
|
||||
setImageTags: React.Dispatch<React.SetStateAction<ImageTag[]>>
|
||||
imageExif: ImageExif | null
|
||||
tagInput: string
|
||||
setTagInput: React.Dispatch<React.SetStateAction<string>>
|
||||
tagAdding: boolean
|
||||
setTagAdding: React.Dispatch<React.SetStateAction<boolean>>
|
||||
tagsExpanded: boolean
|
||||
setTagsExpanded: React.Dispatch<React.SetStateAction<boolean>>
|
||||
taggingQueued: boolean
|
||||
setTaggingQueued: React.Dispatch<React.SetStateAction<boolean>>
|
||||
currentImageIdRef: MutableRefObject<number | null>
|
||||
albums: Album[]
|
||||
canFindSimilar: boolean
|
||||
canSearchRegion: boolean
|
||||
regionSelectMode: boolean
|
||||
regionSearching: boolean
|
||||
taggerReady: boolean
|
||||
taggerButtonTooltip: string
|
||||
closeImage: () => void
|
||||
findSimilar: (imageId: number, sourceFolderId: number | null) => Promise<void>
|
||||
updateImageDetails: (
|
||||
imageId: number,
|
||||
updates: { favorite?: boolean; rating?: number }
|
||||
) => Promise<void>
|
||||
addUserTag: (imageId: number, tag: string) => Promise<ImageTag>
|
||||
removeTag: (tagId: number) => Promise<void>
|
||||
queueTaggingForImage: (imageId: number) => Promise<number>
|
||||
addToAlbum: (albumId: number, imageIds: number[]) => Promise<number>
|
||||
createAlbum: (name: string) => Promise<Album>
|
||||
onToggleRegionMode: () => void
|
||||
}
|
||||
|
||||
export function LightboxDetailsPanel({
|
||||
selectedImage,
|
||||
currentIndex,
|
||||
imageCount,
|
||||
imageTags,
|
||||
setImageTags,
|
||||
imageExif,
|
||||
tagInput,
|
||||
setTagInput,
|
||||
tagAdding,
|
||||
setTagAdding,
|
||||
tagsExpanded,
|
||||
setTagsExpanded,
|
||||
taggingQueued,
|
||||
setTaggingQueued,
|
||||
currentImageIdRef,
|
||||
albums,
|
||||
canFindSimilar,
|
||||
canSearchRegion,
|
||||
regionSelectMode,
|
||||
regionSearching,
|
||||
taggerReady,
|
||||
taggerButtonTooltip,
|
||||
closeImage,
|
||||
findSimilar,
|
||||
updateImageDetails,
|
||||
addUserTag,
|
||||
removeTag,
|
||||
queueTaggingForImage,
|
||||
addToAlbum,
|
||||
createAlbum,
|
||||
onToggleRegionMode,
|
||||
}: LightboxDetailsPanelProps) {
|
||||
const aiRating = selectedImage.ai_rating ? ratingPill(selectedImage.ai_rating) : null
|
||||
const hasCameraInfo =
|
||||
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))
|
||||
|
||||
return (
|
||||
<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="min-w-0">
|
||||
<p className="truncate text-sm font-medium text-white">{selectedImage.filename}</p>
|
||||
<p className="text-xs text-gray-500">Details</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Tooltip label={selectedImage.favorite ? 'Remove favorite' : 'Add favorite'} followCursor>
|
||||
<button
|
||||
className={`rounded-full border p-2 ${selectedImage.favorite ? 'border-rose-400/40 bg-rose-500/10 text-rose-300' : 'border-white/10 bg-white/5 text-gray-400 hover:text-white'}`}
|
||||
onClick={() =>
|
||||
void updateImageDetails(selectedImage.id, { favorite: !selectedImage.favorite })
|
||||
}
|
||||
>
|
||||
<svg className="h-4 w-4" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z" />
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip
|
||||
label={canFindSimilar ? 'Find similar images' : 'Embeddings not ready'}
|
||||
followCursor
|
||||
>
|
||||
<button
|
||||
className={`flex items-center gap-1.5 rounded-full border px-2 py-1.5 text-xs lg:px-3 ${
|
||||
canFindSimilar
|
||||
? 'border-white/10 bg-white/5 text-gray-300 hover:text-white'
|
||||
: 'cursor-not-allowed border-white/5 bg-white/[0.03] text-gray-600'
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (!canFindSimilar) return
|
||||
void findSimilar(selectedImage.id, selectedImage.folder_id)
|
||||
}}
|
||||
disabled={!canFindSimilar}
|
||||
>
|
||||
<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>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<button className="rounded p-1 text-gray-400 hover:text-white" onClick={closeImage}>
|
||||
<CloseIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{canSearchRegion && (
|
||||
<div className="shrink-0 px-5 pb-3">
|
||||
<Tooltip
|
||||
label={
|
||||
regionSelectMode
|
||||
? 'Cancel region selection'
|
||||
: 'Draw a region on the image to search for similar content'
|
||||
}
|
||||
followCursor
|
||||
>
|
||||
<button
|
||||
className={`w-full rounded-lg border px-3 py-2 text-xs transition-colors ${
|
||||
regionSelectMode
|
||||
? 'border-violet-400/40 bg-violet-500/15 text-violet-300 hover:bg-violet-500/20'
|
||||
: regionSearching
|
||||
? 'cursor-not-allowed border-white/5 bg-white/[0.03] text-gray-500'
|
||||
: 'border-white/10 bg-white/5 text-gray-300 hover:bg-white/10 hover:text-white'
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (regionSearching) return
|
||||
onToggleRegionMode()
|
||||
}}
|
||||
disabled={regionSearching}
|
||||
>
|
||||
{regionSearching ? (
|
||||
<span className="flex items-center justify-center gap-1.5">
|
||||
<svg className="h-3 w-3 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
/>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z" />
|
||||
</svg>
|
||||
Searching region…
|
||||
</span>
|
||||
) : regionSelectMode ? (
|
||||
<span className="flex items-center justify-center gap-1.5">
|
||||
<CloseIcon className="h-3 w-3" />
|
||||
Cancel selection
|
||||
</span>
|
||||
) : (
|
||||
<span className="flex items-center justify-center gap-1.5">
|
||||
<svg className="h-3 w-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"
|
||||
/>
|
||||
</svg>
|
||||
Search within image
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 pb-4 text-sm">
|
||||
<div className="grid grid-cols-2 gap-x-6 gap-y-4">
|
||||
<div className="col-span-2">
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Rating</p>
|
||||
<div className="flex items-center gap-1">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1
|
||||
return (
|
||||
<Tooltip
|
||||
key={rating}
|
||||
label={`Set ${rating} star rating`}
|
||||
followCursor
|
||||
delay={750}
|
||||
>
|
||||
<button
|
||||
className="rounded-md p-1"
|
||||
onClick={() => void updateImageDetails(selectedImage.id, { rating })}
|
||||
>
|
||||
<StarIcon
|
||||
className={`h-5 w-5 ${rating <= selectedImage.rating ? 'text-amber-300' : 'text-white/20 hover:text-white/50'}`}
|
||||
/>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
{selectedImage.rating > 0 ? (
|
||||
<Tooltip label="Remove rating" followCursor>
|
||||
<button
|
||||
className="ml-2 rounded-md border border-white/10 p-1.5 text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
onClick={() => void updateImageDetails(selectedImage.id, { rating: 0 })}
|
||||
>
|
||||
<CloseIcon className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Dimensions</p>
|
||||
<p className="text-white">
|
||||
{selectedImage.width && selectedImage.height
|
||||
? `${selectedImage.width} x ${selectedImage.height}px`
|
||||
: 'Pending / unavailable'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{selectedImage.media_kind === 'video' ? (
|
||||
<>
|
||||
<div>
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Duration</p>
|
||||
<p className="text-white">{formatDuration(selectedImage.duration_ms)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Video codec</p>
|
||||
<p className="text-white">{selectedImage.video_codec ?? 'Pending / unavailable'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Audio codec</p>
|
||||
<p className="text-white">{selectedImage.audio_codec ?? 'None / unavailable'}</p>
|
||||
</div>
|
||||
{selectedImage.metadata_error ? (
|
||||
<div className="col-span-2">
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Metadata</p>
|
||||
<p className="text-amber-300">{selectedImage.metadata_error}</p>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Type</p>
|
||||
<p className="text-white">{selectedImage.mime_type}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">File size</p>
|
||||
<p className="text-white">{formatBytes(selectedImage.file_size)}</p>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Modified</p>
|
||||
<p className="text-white">{formatDate(selectedImage.modified_at)}</p>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<p className="mb-1 text-xs tracking-wider text-gray-500 uppercase">Embedding</p>
|
||||
<p className="text-white">
|
||||
{embeddingLabel(selectedImage.embedding_status, selectedImage.embedding_model)}
|
||||
</p>
|
||||
{selectedImage.embedding_error ? (
|
||||
<p className="mt-1 text-xs text-amber-300">{selectedImage.embedding_error}</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<p className="text-xs tracking-wider text-gray-500 uppercase">Tags</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{aiRating ? (
|
||||
<span
|
||||
className={`rounded-md border px-1.5 py-0.5 text-[10px] font-medium ${aiRating.className}`}
|
||||
>
|
||||
{aiRating.label}
|
||||
</span>
|
||||
) : null}
|
||||
{selectedImage.media_kind === 'image' ? (
|
||||
<Tooltip label={taggerButtonTooltip} followCursor>
|
||||
<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 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
disabled={!taggerReady || taggingQueued}
|
||||
onClick={() => {
|
||||
setTaggingQueued(true)
|
||||
void queueTaggingForImage(selectedImage.id).catch(() => undefined)
|
||||
}}
|
||||
>
|
||||
{taggingQueued ? 'Queued' : 'AI tags'}
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{imageTags.length > 0 ? (
|
||||
<>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{(tagsExpanded ? imageTags : imageTags.slice(0, 8)).map((tag) => (
|
||||
<Tooltip
|
||||
key={tag.id}
|
||||
label={
|
||||
tag.source === 'ai' && tag.confidence !== null
|
||||
? `AI confidence: ${(tag.confidence * 100).toFixed(0)}%`
|
||||
: ''
|
||||
}
|
||||
followCursor
|
||||
disabled={tag.source !== 'ai' || tag.confidence === null}
|
||||
>
|
||||
<span
|
||||
className={`group flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs ${
|
||||
tag.source === 'ai'
|
||||
? 'border-sky-400/20 bg-sky-500/8 text-sky-300'
|
||||
: 'border-white/10 bg-white/5 text-gray-300'
|
||||
}`}
|
||||
>
|
||||
{tag.tag}
|
||||
<Tooltip label="Remove tag" followCursor>
|
||||
<button
|
||||
className="text-gray-600 opacity-0 transition-opacity group-hover:opacity-100 hover:text-white"
|
||||
onClick={() => {
|
||||
void removeTag(tag.id).then(() =>
|
||||
setImageTags((prev) => prev.filter((item) => item.id !== tag.id))
|
||||
)
|
||||
}}
|
||||
>
|
||||
<CloseIcon className="h-3 w-3" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
</Tooltip>
|
||||
))}
|
||||
</div>
|
||||
{imageTags.length > 8 && (
|
||||
<button
|
||||
className="mt-1.5 text-xs text-gray-500 transition-colors hover:text-gray-300"
|
||||
onClick={() => setTagsExpanded((expanded) => !expanded)}
|
||||
>
|
||||
{tagsExpanded ? 'Show less' : `+${imageTags.length - 8} more`}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<p className="text-xs text-gray-600">No tags yet</p>
|
||||
)}
|
||||
|
||||
<form
|
||||
className="mt-2 flex gap-1.5"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
const raw = tagInput.trim()
|
||||
if (!raw || tagAdding) return
|
||||
setTagAdding(true)
|
||||
const taggedImageId = selectedImage.id
|
||||
void addUserTag(taggedImageId, raw)
|
||||
.then((newTag) => {
|
||||
if (currentImageIdRef.current !== taggedImageId) return
|
||||
setImageTags((prev) => [...prev, newTag])
|
||||
setTagInput('')
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => setTagAdding(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="Add tag…"
|
||||
value={tagInput}
|
||||
onChange={(event) => setTagInput(event.target.value)}
|
||||
disabled={tagAdding}
|
||||
/>
|
||||
<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={tagAdding || !tagInput.trim()}
|
||||
>
|
||||
Add
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<LightboxAlbumMenu
|
||||
imageId={selectedImage.id}
|
||||
albums={albums}
|
||||
addToAlbum={addToAlbum}
|
||||
createAlbum={createAlbum}
|
||||
/>
|
||||
|
||||
{hasCameraInfo ? (
|
||||
<div>
|
||||
<p className="mb-2 text-xs tracking-wider text-gray-500 uppercase">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 ? (
|
||||
<Tooltip label="Open location in your browser" anchorToCursor>
|
||||
<button
|
||||
className="inline-flex items-center gap-1 text-xs text-sky-400 transition-colors hover:text-sky-300"
|
||||
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>
|
||||
</Tooltip>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div>
|
||||
<div className="mb-1 flex items-center justify-between">
|
||||
<p className="text-xs tracking-wider text-gray-500 uppercase">Path</p>
|
||||
<Tooltip label="Reveal in Explorer" anchorToCursor>
|
||||
<button
|
||||
className="rounded p-0.5 text-gray-600 transition-colors hover:text-gray-300"
|
||||
onClick={() => void revealItemInDir(selectedImage.path)}
|
||||
>
|
||||
<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="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<p className="text-xs break-all text-gray-400">{selectedImage.path}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-auto shrink-0 px-5 pt-2 pb-4 text-center text-xs text-gray-600">
|
||||
{currentIndex + 1} / {imageCount}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { ChevronRightIcon } from '../icons'
|
||||
|
||||
interface LightboxNavButtonProps {
|
||||
direction: 'previous' | 'next'
|
||||
disabled: boolean
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
export function LightboxNavButton({ direction, disabled, onClick }: LightboxNavButtonProps) {
|
||||
const isNext = direction === 'next'
|
||||
|
||||
return (
|
||||
<button
|
||||
className={`absolute 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 ${
|
||||
isNext ? 'right-72 lg:right-80' : 'left-4'
|
||||
}`}
|
||||
disabled={disabled}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onClick()
|
||||
}}
|
||||
aria-label={isNext ? 'Next image' : 'Previous image'}
|
||||
>
|
||||
{isNext ? (
|
||||
<ChevronRightIcon className="h-5 w-5" />
|
||||
) : (
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { AnimatePresence, motion } from 'framer-motion'
|
||||
import { RefObject } from 'react'
|
||||
import { ImageRecord } from '../../store'
|
||||
import { mediaSrc } from '../../lib/mediaSrc'
|
||||
import { VideoPlayer } from '../VideoPlayer'
|
||||
import { Tooltip } from '../Tooltip'
|
||||
import { SelectionOverlay, ViewTransform } from './types'
|
||||
import { MAX_ZOOM, MIN_ZOOM, zoomViewAt } from './viewTransform'
|
||||
|
||||
interface LightboxViewportProps {
|
||||
selectedImage: ImageRecord
|
||||
imageViewportRef: RefObject<HTMLDivElement | null>
|
||||
imgRef: RefObject<HTMLImageElement | null>
|
||||
view: ViewTransform
|
||||
zoom: number
|
||||
regionSelectMode: boolean
|
||||
isPanning: boolean
|
||||
selectionOverlay: SelectionOverlay | null
|
||||
canStartSlideshow: boolean
|
||||
onStartSlideshow: () => void
|
||||
onPointerDown: (event: React.PointerEvent<HTMLDivElement>) => void
|
||||
onPointerMove: (event: React.PointerEvent<HTMLDivElement>) => void
|
||||
onPointerUp: (event: React.PointerEvent<HTMLDivElement>) => void
|
||||
setView: React.Dispatch<React.SetStateAction<ViewTransform>>
|
||||
clampPan: (view: ViewTransform) => ViewTransform
|
||||
}
|
||||
|
||||
export function LightboxViewport({
|
||||
selectedImage,
|
||||
imageViewportRef,
|
||||
imgRef,
|
||||
view,
|
||||
zoom,
|
||||
regionSelectMode,
|
||||
isPanning,
|
||||
selectionOverlay,
|
||||
canStartSlideshow,
|
||||
onStartSlideshow,
|
||||
onPointerDown,
|
||||
onPointerMove,
|
||||
onPointerUp,
|
||||
setView,
|
||||
clampPan,
|
||||
}: LightboxViewportProps) {
|
||||
return (
|
||||
<div
|
||||
ref={imageViewportRef}
|
||||
className={`group relative flex flex-1 items-center justify-center overflow-hidden p-10 ${
|
||||
regionSelectMode
|
||||
? 'cursor-crosshair select-none'
|
||||
: isPanning
|
||||
? 'cursor-grabbing select-none'
|
||||
: zoom > 1 && selectedImage.media_kind === 'image'
|
||||
? 'cursor-grab'
|
||||
: ''
|
||||
}`}
|
||||
onPointerDown={onPointerDown}
|
||||
onPointerMove={onPointerMove}
|
||||
onPointerUp={onPointerUp}
|
||||
>
|
||||
{regionSelectMode && (
|
||||
<div className="pointer-events-none absolute inset-x-0 top-4 z-20 flex justify-center">
|
||||
<div className="flex items-center gap-2 rounded-full border border-white/15 bg-black/70 px-4 py-2 text-xs text-gray-300 backdrop-blur">
|
||||
<svg
|
||||
className="h-3.5 w-3.5 text-violet-400"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"
|
||||
/>
|
||||
</svg>
|
||||
Draw a region to search —{' '}
|
||||
<kbd className="ml-1 rounded border border-white/20 bg-white/10 px-1.5 py-0.5 font-mono text-[10px]">
|
||||
Esc
|
||||
</kbd>{' '}
|
||||
to cancel
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectionOverlay && selectionOverlay.width > 4 && selectionOverlay.height > 4 && (
|
||||
<div
|
||||
className="pointer-events-none fixed z-30 rounded border-2 border-violet-400 bg-violet-400/15 shadow-[0_0_0_9999px_rgba(0,0,0,0.35)]"
|
||||
style={{
|
||||
left: selectionOverlay.left,
|
||||
top: selectionOverlay.top,
|
||||
width: selectionOverlay.width,
|
||||
height: selectionOverlay.height,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<AnimatePresence mode="wait">
|
||||
<motion.div
|
||||
key={selectedImage.id}
|
||||
className={
|
||||
selectedImage.media_kind === 'video'
|
||||
? 'absolute inset-0'
|
||||
: 'flex items-center justify-center'
|
||||
}
|
||||
initial={{ opacity: 0.3, scale: 0.985 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0.3, scale: 0.985 }}
|
||||
transition={{ duration: 0.12 }}
|
||||
>
|
||||
{selectedImage.media_kind === 'video' ? (
|
||||
<VideoPlayer src={mediaSrc(selectedImage.path) ?? ''} />
|
||||
) : (
|
||||
<img
|
||||
ref={imgRef}
|
||||
src={mediaSrc(selectedImage.path) ?? ''}
|
||||
alt={selectedImage.filename}
|
||||
className="max-w-full rounded-2xl shadow-2xl"
|
||||
draggable={false}
|
||||
style={{
|
||||
maxHeight: 'calc(100vh - 10rem)',
|
||||
transform: `translate(${view.panX}px, ${view.panY}px) scale(${zoom})`,
|
||||
transformOrigin: 'center center',
|
||||
...(regionSelectMode ? { opacity: 0.85 } : {}),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</motion.div>
|
||||
</AnimatePresence>
|
||||
|
||||
{!regionSelectMode && (
|
||||
<div className="pointer-events-none absolute top-6 right-6 opacity-75 transition-opacity group-hover:opacity-100">
|
||||
<div className="pointer-events-auto flex items-center gap-1 rounded-full border border-white/10 bg-black/55 p-1 shadow-2xl shadow-black/25 backdrop-blur">
|
||||
<Tooltip
|
||||
label={canStartSlideshow ? 'Start slideshow' : 'No images available for slideshow'}
|
||||
followCursor
|
||||
>
|
||||
<button
|
||||
aria-label="Start slideshow"
|
||||
className={`rounded-full p-2 transition-colors ${
|
||||
canStartSlideshow
|
||||
? 'text-gray-300 hover:bg-white/10 hover:text-white'
|
||||
: 'cursor-not-allowed text-gray-600'
|
||||
}`}
|
||||
disabled={!canStartSlideshow}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
onStartSlideshow()
|
||||
}}
|
||||
>
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.8}
|
||||
d="M8 5.5v13l10-6.5-10-6.5z"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{selectedImage.media_kind === 'image' ? (
|
||||
<>
|
||||
<div className="mx-0.5 h-5 w-px bg-white/10" />
|
||||
<button
|
||||
aria-label="Zoom out"
|
||||
className="rounded-full px-2 py-1 text-sm text-gray-300 transition-colors hover:bg-white/10 hover:text-white"
|
||||
onClick={() =>
|
||||
setView((currentView) =>
|
||||
clampPan(
|
||||
zoomViewAt(currentView, Math.max(MIN_ZOOM, currentView.zoom - 0.25), 0, 0)
|
||||
)
|
||||
)
|
||||
}
|
||||
>
|
||||
-
|
||||
</button>
|
||||
<span className="min-w-14 text-center text-xs text-gray-300">
|
||||
{Math.round(zoom * 100)}%
|
||||
</span>
|
||||
<button
|
||||
aria-label="Zoom in"
|
||||
className="rounded-full px-2 py-1 text-sm text-gray-300 transition-colors hover:bg-white/10 hover:text-white"
|
||||
onClick={() =>
|
||||
setView((currentView) =>
|
||||
clampPan(
|
||||
zoomViewAt(currentView, Math.min(MAX_ZOOM, currentView.zoom + 0.25), 0, 0)
|
||||
)
|
||||
)
|
||||
}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user