Initial commit — Tauri image gallery with sqlite-vec
Sets up Tauri v2 + React frontend with SQLite metadata store, sqlite-vec for CLIP embedding infrastructure, and r2d2 connection pool replacing the single Arc<Mutex<Connection>>. Indexer now uses rayon for parallel file metadata collection.
@@ -0,0 +1,25 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
src-tauri/target
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,118 @@
|
||||
# Phokus
|
||||
|
||||
`Phokus` is the chosen name for this project. It keeps the visual/photo association obvious while feeling sharper and more distinctive than `image-gallery`.
|
||||
|
||||
## Overview
|
||||
|
||||
Phokus is a Tauri desktop app for building a fast, local media library from folders on disk. It indexes images and videos, stores metadata in SQLite, and gives you a dense browsing workflow with filtering, favorites, ratings, and a lightbox preview.
|
||||
|
||||
The current app is optimized for:
|
||||
|
||||
- local folders instead of cloud import flows
|
||||
- large visual libraries
|
||||
- quick review and curation
|
||||
- mixed image and video browsing
|
||||
|
||||
## Current features
|
||||
|
||||
- Add and remove media folders
|
||||
- Background indexing with progress updates
|
||||
- Browse all media or filter by folder
|
||||
- Search by filename
|
||||
- Filter by images, videos, or favorites
|
||||
- Sort by modified date, name, or file size
|
||||
- Grid density controls
|
||||
- Lightbox preview with keyboard navigation
|
||||
- Favorite and star-rating metadata saved in SQLite
|
||||
- Virtualized/local-first architecture built on Tauri + React
|
||||
|
||||
## Supported formats
|
||||
|
||||
Images:
|
||||
|
||||
- `jpg`
|
||||
- `jpeg`
|
||||
- `png`
|
||||
- `gif`
|
||||
- `bmp`
|
||||
- `tiff`
|
||||
- `tif`
|
||||
- `webp`
|
||||
- `avif`
|
||||
- `heic`
|
||||
- `heif`
|
||||
|
||||
Videos:
|
||||
|
||||
- `mp4`
|
||||
- `mov`
|
||||
- `m4v`
|
||||
- `webm`
|
||||
|
||||
## Stack
|
||||
|
||||
- Tauri 2
|
||||
- React 19
|
||||
- TypeScript
|
||||
- Zustand
|
||||
- Rust
|
||||
- SQLite + `sqlite-vec`
|
||||
- Vite
|
||||
|
||||
## Project structure
|
||||
|
||||
- `src/`: React UI, state, and components
|
||||
- `src-tauri/src/commands.rs`: Tauri command surface
|
||||
- `src-tauri/src/db.rs`: SQLite schema and queries
|
||||
- `src-tauri/src/indexer.rs`: folder crawling and batch indexing
|
||||
- `src-tauri/src/vector.rs`: vector table setup for future semantic workflows
|
||||
|
||||
## Development
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 20+
|
||||
- `pnpm`
|
||||
- Rust toolchain
|
||||
- Tauri system prerequisites for Windows
|
||||
|
||||
### Install
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### Run in development
|
||||
|
||||
```bash
|
||||
pnpm tauri dev
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
pnpm tauri build
|
||||
```
|
||||
|
||||
## How it works
|
||||
|
||||
1. Add a folder from the sidebar or Library menu.
|
||||
2. The Rust indexer walks the directory recursively.
|
||||
3. Supported files are written into SQLite with metadata such as path, size, dimensions, media type, rating, and favorite state.
|
||||
4. Progress events stream back to the UI while the gallery updates incrementally.
|
||||
5. The gallery view loads media in pages and opens items in a lightbox for review.
|
||||
|
||||
## Notes
|
||||
|
||||
- This is currently a local desktop library, not a sync product.
|
||||
- Search is filename-based right now.
|
||||
- The vector table and embedding fields exist, but semantic search is not wired into the UI yet.
|
||||
- Some visible UI copy may still use the old working name until the frontend text is updated.
|
||||
|
||||
## Positioning
|
||||
|
||||
The clearest product description today is:
|
||||
|
||||
> A local-first desktop media library for browsing, filtering, and curating image and video folders.
|
||||
|
||||
That description is more accurate than "gallery" alone and gives you a better base for future branding, onboarding copy, and a landing page.
|
||||
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Tauri + React + Typescript</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "phokus",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview",
|
||||
"tauri": "tauri"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/react-virtual": "^3.13.23",
|
||||
"@tauri-apps/api": "^2",
|
||||
"@tauri-apps/plugin-dialog": "^2.7.0",
|
||||
"@tauri-apps/plugin-fs": "^2.5.0",
|
||||
"@tauri-apps/plugin-opener": "^2",
|
||||
"framer-motion": "^12.38.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"zustand": "^5.0.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@tauri-apps/cli": "^2",
|
||||
"@types/react": "^19.1.8",
|
||||
"@types/react-dom": "^19.1.6",
|
||||
"@vitejs/plugin-react": "^4.6.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"typescript": "~5.8.3",
|
||||
"vite": "^7.0.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.5 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,7 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
/gen/schemas
|
||||
@@ -0,0 +1,33 @@
|
||||
[package]
|
||||
name = "image-gallery"
|
||||
version = "0.1.0"
|
||||
description = "A performant image gallery application"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
name = "image_gallery_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = ["protocol-asset"] }
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-fs = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
rusqlite = { version = "0.32", features = ["bundled"] }
|
||||
r2d2 = "0.8"
|
||||
r2d2_sqlite = "0.25"
|
||||
sqlite-vec = "=0.1.9"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp", "tiff"] }
|
||||
walkdir = "2"
|
||||
rayon = "1"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
anyhow = "1"
|
||||
log = "0.4"
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"opener:default",
|
||||
"dialog:default",
|
||||
"dialog:allow-open",
|
||||
"fs:default",
|
||||
"fs:allow-read-file",
|
||||
"fs:allow-read-dir",
|
||||
"fs:read-files",
|
||||
"fs:read-dirs"
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 974 B |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 903 B |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,153 @@
|
||||
use crate::db::{self, DbPool, Folder, ImageRecord};
|
||||
use crate::indexer;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use tauri::{AppHandle, State};
|
||||
|
||||
pub type DbState = DbPool;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ImagesPage {
|
||||
pub images: Vec<ImageRecord>,
|
||||
pub total: i64,
|
||||
pub offset: i64,
|
||||
pub limit: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct GetImagesParams {
|
||||
pub folder_id: Option<i64>,
|
||||
pub search: Option<String>,
|
||||
pub media_kind: Option<String>,
|
||||
pub favorites_only: Option<bool>,
|
||||
pub sort: Option<String>,
|
||||
pub offset: Option<i64>,
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateImageDetailsParams {
|
||||
pub image_id: i64,
|
||||
pub favorite: Option<bool>,
|
||||
pub rating: Option<i64>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn add_folder(
|
||||
app: AppHandle,
|
||||
db: State<'_, DbState>,
|
||||
path: String,
|
||||
cache_dir: String,
|
||||
) -> Result<Folder, String> {
|
||||
let folder_path = PathBuf::from(&path);
|
||||
|
||||
if !folder_path.exists() || !folder_path.is_dir() {
|
||||
return Err("Path is not a valid directory".into());
|
||||
}
|
||||
|
||||
let name = folder_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| path.clone());
|
||||
|
||||
let folder_id = {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
db::insert_folder(&conn, &path, &name).map_err(|e| e.to_string())?
|
||||
};
|
||||
|
||||
let folders = {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
db::get_folders(&conn).map_err(|e| e.to_string())?
|
||||
};
|
||||
|
||||
let folder = folders
|
||||
.into_iter()
|
||||
.find(|f| f.id == folder_id)
|
||||
.ok_or("Folder not found after insert")?;
|
||||
|
||||
let cache_path = PathBuf::from(cache_dir);
|
||||
indexer::index_folder(app, db.inner().clone(), folder_id, folder_path, cache_path);
|
||||
|
||||
Ok(folder)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_folders(db: State<'_, DbState>) -> Result<Vec<Folder>, String> {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
db::get_folders(&conn).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn remove_folder(db: State<'_, DbState>, folder_id: i64) -> Result<(), String> {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
db::delete_folder(&conn, folder_id).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_images(
|
||||
db: State<'_, DbState>,
|
||||
params: GetImagesParams,
|
||||
) -> Result<ImagesPage, String> {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
|
||||
let sort = params.sort.as_deref().unwrap_or("date_desc");
|
||||
let offset = params.offset.unwrap_or(0);
|
||||
let limit = params.limit.unwrap_or(100);
|
||||
let search = params.search.as_deref();
|
||||
let media_kind = params.media_kind.as_deref();
|
||||
let favorites_only = params.favorites_only.unwrap_or(false);
|
||||
|
||||
let total = db::count_images(&conn, params.folder_id, search, media_kind, favorites_only)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let images = db::get_images(
|
||||
&conn,
|
||||
params.folder_id,
|
||||
search,
|
||||
media_kind,
|
||||
favorites_only,
|
||||
sort,
|
||||
offset,
|
||||
limit,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(ImagesPage {
|
||||
images,
|
||||
total,
|
||||
offset,
|
||||
limit,
|
||||
})
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn update_image_details(
|
||||
db: State<'_, DbState>,
|
||||
params: UpdateImageDetailsParams,
|
||||
) -> Result<ImageRecord, String> {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
db::update_image_details(&conn, params.image_id, params.favorite, params.rating)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn reindex_folder(
|
||||
app: AppHandle,
|
||||
db: State<'_, DbState>,
|
||||
folder_id: i64,
|
||||
cache_dir: String,
|
||||
) -> Result<(), String> {
|
||||
let folder_path = {
|
||||
let conn = db.get().map_err(|e| e.to_string())?;
|
||||
let folders = db::get_folders(&conn).map_err(|e| e.to_string())?;
|
||||
folders
|
||||
.into_iter()
|
||||
.find(|f| f.id == folder_id)
|
||||
.map(|f| PathBuf::from(f.path))
|
||||
.ok_or("Folder not found")?
|
||||
};
|
||||
|
||||
let cache_path = PathBuf::from(cache_dir);
|
||||
indexer::index_folder(app, db.inner().clone(), folder_id, folder_path, cache_path);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
use crate::vector;
|
||||
use anyhow::Result;
|
||||
use r2d2::Pool;
|
||||
use r2d2_sqlite::SqliteConnectionManager;
|
||||
use rusqlite::{params, Connection, Row};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
pub type DbPool = Pool<SqliteConnectionManager>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ConnectionOptions;
|
||||
|
||||
impl r2d2::CustomizeConnection<Connection, rusqlite::Error> for ConnectionOptions {
|
||||
fn on_acquire(&self, conn: &mut Connection) -> Result<(), rusqlite::Error> {
|
||||
conn.execute_batch(
|
||||
"PRAGMA journal_mode=WAL;
|
||||
PRAGMA synchronous=NORMAL;
|
||||
PRAGMA foreign_keys=ON;
|
||||
PRAGMA busy_timeout=5000;",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Folder {
|
||||
pub id: i64,
|
||||
pub path: String,
|
||||
pub name: String,
|
||||
pub image_count: i64,
|
||||
pub indexed_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ImageRecord {
|
||||
pub id: i64,
|
||||
pub folder_id: i64,
|
||||
pub path: String,
|
||||
pub filename: String,
|
||||
pub thumbnail_path: Option<String>,
|
||||
pub width: Option<i64>,
|
||||
pub height: Option<i64>,
|
||||
pub file_size: i64,
|
||||
pub created_at: Option<String>,
|
||||
pub modified_at: Option<String>,
|
||||
pub mime_type: String,
|
||||
pub media_kind: String,
|
||||
pub favorite: bool,
|
||||
pub rating: i64,
|
||||
pub embedding_status: String,
|
||||
pub embedding_model: Option<String>,
|
||||
pub embedding_updated_at: Option<String>,
|
||||
pub embedding_error: Option<String>,
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EmbeddingJob {
|
||||
pub image_id: i64,
|
||||
pub status: String,
|
||||
pub attempts: i64,
|
||||
pub last_error: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
pub fn create_pool(db_path: &Path) -> Result<DbPool> {
|
||||
vector::register_sqlite_vec();
|
||||
let manager = SqliteConnectionManager::file(db_path);
|
||||
let pool = Pool::builder()
|
||||
.connection_customizer(Box::new(ConnectionOptions))
|
||||
.build(manager)?;
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"
|
||||
CREATE TABLE IF NOT EXISTS folders (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
path TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
image_count INTEGER NOT NULL DEFAULT 0,
|
||||
indexed_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS images (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
folder_id INTEGER NOT NULL REFERENCES folders(id) ON DELETE CASCADE,
|
||||
path TEXT NOT NULL UNIQUE,
|
||||
filename TEXT NOT NULL,
|
||||
thumbnail_path TEXT,
|
||||
width INTEGER,
|
||||
height INTEGER,
|
||||
file_size INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT,
|
||||
modified_at TEXT,
|
||||
mime_type TEXT NOT NULL DEFAULT 'image/jpeg',
|
||||
media_kind TEXT NOT NULL DEFAULT 'image',
|
||||
favorite INTEGER NOT NULL DEFAULT 0,
|
||||
rating INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS embedding_jobs (
|
||||
image_id INTEGER PRIMARY KEY REFERENCES images(id) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_images_folder_id ON images(folder_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_images_modified_at ON images(modified_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_embedding_jobs_status ON embedding_jobs(status);
|
||||
",
|
||||
)?;
|
||||
|
||||
ensure_column(
|
||||
conn,
|
||||
"images",
|
||||
"embedding_status",
|
||||
"TEXT NOT NULL DEFAULT 'pending'",
|
||||
)?;
|
||||
ensure_column(conn, "images", "embedding_model", "TEXT")?;
|
||||
ensure_column(conn, "images", "embedding_updated_at", "TEXT")?;
|
||||
ensure_column(conn, "images", "embedding_error", "TEXT")?;
|
||||
ensure_column(
|
||||
conn,
|
||||
"images",
|
||||
"media_kind",
|
||||
"TEXT NOT NULL DEFAULT 'image'",
|
||||
)?;
|
||||
ensure_column(conn, "images", "favorite", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
ensure_column(conn, "images", "rating", "INTEGER NOT NULL DEFAULT 0")?;
|
||||
|
||||
vector::migrate(conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn insert_folder(conn: &Connection, path: &str, name: &str) -> Result<i64> {
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO folders (path, name) VALUES (?1, ?2)",
|
||||
params![path, name],
|
||||
)?;
|
||||
let id: i64 = conn.query_row(
|
||||
"SELECT id FROM folders WHERE path = ?1",
|
||||
params![path],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub fn upsert_image(conn: &Connection, img: &ImageRecord) -> Result<i64> {
|
||||
let id = conn.query_row(
|
||||
"INSERT INTO images (folder_id, path, filename, thumbnail_path, width, height, file_size, created_at, modified_at, mime_type, media_kind, favorite, rating, embedding_status, embedding_model, embedding_updated_at, embedding_error)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
|
||||
ON CONFLICT(path) DO UPDATE SET
|
||||
folder_id = excluded.folder_id,
|
||||
filename = excluded.filename,
|
||||
thumbnail_path = excluded.thumbnail_path,
|
||||
width = excluded.width,
|
||||
height = excluded.height,
|
||||
file_size = excluded.file_size,
|
||||
created_at = excluded.created_at,
|
||||
modified_at = excluded.modified_at,
|
||||
mime_type = excluded.mime_type,
|
||||
media_kind = excluded.media_kind,
|
||||
embedding_status = excluded.embedding_status,
|
||||
embedding_model = excluded.embedding_model,
|
||||
embedding_updated_at = excluded.embedding_updated_at,
|
||||
embedding_error = excluded.embedding_error
|
||||
RETURNING id",
|
||||
params![
|
||||
img.folder_id,
|
||||
img.path,
|
||||
img.filename,
|
||||
img.thumbnail_path,
|
||||
img.width,
|
||||
img.height,
|
||||
img.file_size,
|
||||
img.created_at,
|
||||
img.modified_at,
|
||||
img.mime_type,
|
||||
img.media_kind,
|
||||
img.favorite,
|
||||
img.rating,
|
||||
img.embedding_status,
|
||||
img.embedding_model,
|
||||
img.embedding_updated_at,
|
||||
img.embedding_error,
|
||||
],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub fn enqueue_embedding_job(conn: &Connection, image_id: i64) -> Result<()> {
|
||||
conn.execute(
|
||||
"INSERT INTO embedding_jobs (image_id, status, attempts, last_error, created_at, updated_at)
|
||||
VALUES (?1, 'pending', 0, NULL, datetime('now'), datetime('now'))
|
||||
ON CONFLICT(image_id) DO UPDATE SET
|
||||
status = 'pending',
|
||||
last_error = NULL,
|
||||
updated_at = datetime('now')",
|
||||
[image_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn get_next_embedding_job(conn: &Connection) -> Result<Option<EmbeddingJob>> {
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT image_id, status, attempts, last_error, created_at, updated_at
|
||||
FROM embedding_jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY updated_at, image_id
|
||||
LIMIT 1",
|
||||
)?;
|
||||
|
||||
let mut rows = stmt.query([])?;
|
||||
let Some(row) = rows.next()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
Ok(Some(EmbeddingJob {
|
||||
image_id: row.get(0)?,
|
||||
status: row.get(1)?,
|
||||
attempts: row.get(2)?,
|
||||
last_error: row.get(3)?,
|
||||
created_at: row.get(4)?,
|
||||
updated_at: row.get(5)?,
|
||||
}))
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn mark_embedding_job_processing(conn: &Connection, image_id: i64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE embedding_jobs
|
||||
SET status = 'processing', attempts = attempts + 1, updated_at = datetime('now')
|
||||
WHERE image_id = ?1",
|
||||
[image_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn mark_embedding_ready(conn: &Connection, image_id: i64, model: &str) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE images
|
||||
SET embedding_status = 'ready', embedding_model = ?2, embedding_updated_at = datetime('now'), embedding_error = NULL
|
||||
WHERE id = ?1",
|
||||
params![image_id, model],
|
||||
)?;
|
||||
conn.execute("DELETE FROM embedding_jobs WHERE image_id = ?1", [image_id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn mark_embedding_failed(conn: &Connection, image_id: i64, error: &str) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE images
|
||||
SET embedding_status = 'failed', embedding_error = ?2
|
||||
WHERE id = ?1",
|
||||
params![image_id, error],
|
||||
)?;
|
||||
conn.execute(
|
||||
"UPDATE embedding_jobs
|
||||
SET status = 'failed', last_error = ?2, updated_at = datetime('now')
|
||||
WHERE image_id = ?1",
|
||||
params![image_id, error],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_folder_count(conn: &Connection, folder_id: i64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE folders SET image_count = (SELECT COUNT(*) FROM images WHERE folder_id = ?1), indexed_at = datetime('now') WHERE id = ?1",
|
||||
params![folder_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_image_details(
|
||||
conn: &Connection,
|
||||
image_id: i64,
|
||||
favorite: Option<bool>,
|
||||
rating: Option<i64>,
|
||||
) -> Result<ImageRecord> {
|
||||
conn.execute(
|
||||
"UPDATE images
|
||||
SET favorite = COALESCE(?2, favorite),
|
||||
rating = COALESCE(?3, rating)
|
||||
WHERE id = ?1",
|
||||
params![image_id, favorite, rating],
|
||||
)?;
|
||||
|
||||
conn.query_row(
|
||||
"SELECT id, folder_id, path, filename, thumbnail_path, width, height, file_size, created_at, modified_at, mime_type,
|
||||
media_kind, favorite, rating, embedding_status, embedding_model, embedding_updated_at, embedding_error
|
||||
FROM images
|
||||
WHERE id = ?1",
|
||||
[image_id],
|
||||
map_image_row,
|
||||
)
|
||||
.map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn get_folders(conn: &Connection) -> Result<Vec<Folder>> {
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT id, path, name, image_count, indexed_at FROM folders ORDER BY name")?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok(Folder {
|
||||
id: row.get(0)?,
|
||||
path: row.get(1)?,
|
||||
name: row.get(2)?,
|
||||
image_count: row.get(3)?,
|
||||
indexed_at: row.get(4)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn get_images(
|
||||
conn: &Connection,
|
||||
folder_id: Option<i64>,
|
||||
search: Option<&str>,
|
||||
media_kind: Option<&str>,
|
||||
favorites_only: bool,
|
||||
sort: &str,
|
||||
offset: i64,
|
||||
limit: i64,
|
||||
) -> Result<Vec<ImageRecord>> {
|
||||
let order = match sort {
|
||||
"name_asc" => "filename ASC",
|
||||
"name_desc" => "filename DESC",
|
||||
"date_asc" => "modified_at ASC NULLS LAST",
|
||||
"date_desc" => "modified_at DESC NULLS LAST",
|
||||
"size_asc" => "file_size ASC",
|
||||
"size_desc" => "file_size DESC",
|
||||
_ => "modified_at DESC NULLS LAST",
|
||||
};
|
||||
|
||||
let search_pattern = search.map(|value| format!("%{}%", value));
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
let sql = format!(
|
||||
"SELECT id, folder_id, path, filename, thumbnail_path, width, height, file_size, created_at, modified_at, mime_type,
|
||||
media_kind, favorite, rating, embedding_status, embedding_model, embedding_updated_at, embedding_error
|
||||
FROM images
|
||||
WHERE (?1 IS NULL OR folder_id = ?1)
|
||||
AND (?2 IS NULL OR filename LIKE ?2)
|
||||
AND (?3 IS NULL OR media_kind = ?3)
|
||||
AND (?4 = 0 OR favorite = 1)
|
||||
ORDER BY {}
|
||||
LIMIT ?5 OFFSET ?6",
|
||||
order
|
||||
);
|
||||
let mut stmt = conn.prepare(&sql)?;
|
||||
let rows = stmt.query_map(
|
||||
params![
|
||||
folder_id,
|
||||
search_pattern,
|
||||
media_kind,
|
||||
favorites_flag,
|
||||
limit,
|
||||
offset
|
||||
],
|
||||
map_image_row,
|
||||
)?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn count_images(
|
||||
conn: &Connection,
|
||||
folder_id: Option<i64>,
|
||||
search: Option<&str>,
|
||||
media_kind: Option<&str>,
|
||||
favorites_only: bool,
|
||||
) -> Result<i64> {
|
||||
let search_pattern = search.map(|value| format!("%{}%", value));
|
||||
|
||||
let favorites_flag = i64::from(favorites_only);
|
||||
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 (?3 IS NULL OR media_kind = ?3)
|
||||
AND (?4 = 0 OR favorite = 1)",
|
||||
params![folder_id, search_pattern, media_kind, favorites_flag],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
pub fn delete_folder(conn: &Connection, folder_id: i64) -> Result<()> {
|
||||
conn.execute("DELETE FROM folders WHERE id = ?1", params![folder_id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn map_image_row(row: &Row<'_>) -> rusqlite::Result<ImageRecord> {
|
||||
Ok(ImageRecord {
|
||||
id: row.get(0)?,
|
||||
folder_id: row.get(1)?,
|
||||
path: row.get(2)?,
|
||||
filename: row.get(3)?,
|
||||
thumbnail_path: row.get(4)?,
|
||||
width: row.get(5)?,
|
||||
height: row.get(6)?,
|
||||
file_size: row.get(7)?,
|
||||
created_at: row.get(8)?,
|
||||
modified_at: row.get(9)?,
|
||||
mime_type: row.get(10)?,
|
||||
media_kind: row.get(11)?,
|
||||
favorite: row.get::<_, i64>(12)? != 0,
|
||||
rating: row.get(13)?,
|
||||
embedding_status: row.get(14)?,
|
||||
embedding_model: row.get(15)?,
|
||||
embedding_updated_at: row.get(16)?,
|
||||
embedding_error: row.get(17)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_column(conn: &Connection, table: &str, column: &str, definition: &str) -> Result<()> {
|
||||
let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", table))?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let existing_name: String = row.get(1)?;
|
||||
if existing_name == column {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
conn.execute(
|
||||
&format!("ALTER TABLE {} ADD COLUMN {} {}", table, column, definition),
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
use crate::db::{self, DbPool, ImageRecord};
|
||||
use crate::thumbnail;
|
||||
use crate::vector;
|
||||
use anyhow::Result;
|
||||
use rayon::prelude::*;
|
||||
use serde::Serialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
use walkdir::WalkDir;
|
||||
|
||||
const IMAGE_EXTENSIONS: &[&str] = &[
|
||||
"jpg", "jpeg", "png", "gif", "bmp", "tiff", "tif", "webp", "avif", "heic", "heif",
|
||||
];
|
||||
|
||||
const VIDEO_EXTENSIONS: &[&str] = &["mp4", "mov", "m4v", "webm"];
|
||||
|
||||
fn is_supported_media(path: &Path) -> bool {
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(|e| {
|
||||
let ext = e.to_lowercase();
|
||||
IMAGE_EXTENSIONS.contains(&ext.as_str()) || VIDEO_EXTENSIONS.contains(&ext.as_str())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn media_kind_for_ext(ext: &str) -> &'static str {
|
||||
match ext.to_lowercase().as_str() {
|
||||
"mp4" | "mov" | "m4v" | "webm" => "video",
|
||||
_ => "image",
|
||||
}
|
||||
}
|
||||
|
||||
fn mime_for_ext(ext: &str) -> &'static str {
|
||||
match ext.to_lowercase().as_str() {
|
||||
"jpg" | "jpeg" => "image/jpeg",
|
||||
"png" => "image/png",
|
||||
"gif" => "image/gif",
|
||||
"bmp" => "image/bmp",
|
||||
"webp" => "image/webp",
|
||||
"tiff" | "tif" => "image/tiff",
|
||||
"avif" => "image/avif",
|
||||
"heic" | "heif" => "image/heif",
|
||||
"mp4" | "m4v" => "video/mp4",
|
||||
"mov" => "video/quicktime",
|
||||
"webm" => "video/webm",
|
||||
_ => "image/jpeg",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct IndexProgress {
|
||||
pub folder_id: i64,
|
||||
pub total: usize,
|
||||
pub indexed: usize,
|
||||
pub current_file: String,
|
||||
pub done: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct IndexedImagesBatch {
|
||||
pub folder_id: i64,
|
||||
pub images: Vec<ImageRecord>,
|
||||
}
|
||||
|
||||
const INDEX_BATCH_SIZE: usize = 25;
|
||||
|
||||
pub fn index_folder(
|
||||
app: AppHandle,
|
||||
pool: DbPool,
|
||||
folder_id: i64,
|
||||
folder_path: PathBuf,
|
||||
_cache_dir: PathBuf,
|
||||
) {
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = do_index(app, pool, folder_id, folder_path) {
|
||||
eprintln!("Indexing error: {}", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn do_index(app: AppHandle, pool: DbPool, folder_id: i64, folder_path: PathBuf) -> Result<()> {
|
||||
let image_paths: Vec<PathBuf> = WalkDir::new(&folder_path)
|
||||
.follow_links(true)
|
||||
.into_iter()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| e.file_type().is_file() && is_supported_media(e.path()))
|
||||
.map(|e| e.path().to_path_buf())
|
||||
.collect();
|
||||
|
||||
let total = image_paths.len();
|
||||
|
||||
emit_progress(
|
||||
&app,
|
||||
&IndexProgress {
|
||||
folder_id,
|
||||
total,
|
||||
indexed: 0,
|
||||
current_file: String::new(),
|
||||
done: false,
|
||||
},
|
||||
);
|
||||
|
||||
// Parallel: read file metadata and dimensions across all CPU cores
|
||||
let records: Vec<ImageRecord> = image_paths
|
||||
.par_iter()
|
||||
.filter_map(|path| build_record(path, folder_id))
|
||||
.collect();
|
||||
|
||||
// Sequential: commit in batches and stream results to the frontend
|
||||
let mut indexed = 0usize;
|
||||
for chunk in records.chunks(INDEX_BATCH_SIZE) {
|
||||
let committed = commit_batch(&pool, chunk)?;
|
||||
indexed += committed.len();
|
||||
emit_images(&app, &IndexedImagesBatch { folder_id, images: committed });
|
||||
emit_progress(
|
||||
&app,
|
||||
&IndexProgress {
|
||||
folder_id,
|
||||
total,
|
||||
indexed,
|
||||
current_file: String::new(),
|
||||
done: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
{
|
||||
let conn = pool.get()?;
|
||||
db::update_folder_count(&conn, folder_id)?;
|
||||
}
|
||||
|
||||
emit_progress(
|
||||
&app,
|
||||
&IndexProgress {
|
||||
folder_id,
|
||||
total,
|
||||
indexed,
|
||||
current_file: String::new(),
|
||||
done: true,
|
||||
},
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_record(path: &Path, folder_id: i64) -> Option<ImageRecord> {
|
||||
let path_str = path.to_string_lossy().to_string();
|
||||
let filename = path.file_name()?.to_string_lossy().to_string();
|
||||
|
||||
let meta = std::fs::metadata(path).ok();
|
||||
let file_size = meta.as_ref().map(|m| m.len() as i64).unwrap_or(0);
|
||||
let modified_at = meta.as_ref().and_then(|m| m.modified().ok()).map(|t| {
|
||||
let dt: chrono::DateTime<chrono::Utc> = t.into();
|
||||
dt.to_rfc3339()
|
||||
});
|
||||
|
||||
let (width, height) = thumbnail::get_dimensions(path)
|
||||
.map(|(w, h)| (Some(w as i64), Some(h as i64)))
|
||||
.unwrap_or((None, None));
|
||||
|
||||
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("jpg");
|
||||
|
||||
Some(ImageRecord {
|
||||
id: 0,
|
||||
folder_id,
|
||||
path: path_str,
|
||||
filename,
|
||||
thumbnail_path: None,
|
||||
width,
|
||||
height,
|
||||
file_size,
|
||||
created_at: None,
|
||||
modified_at,
|
||||
mime_type: mime_for_ext(ext).to_string(),
|
||||
media_kind: media_kind_for_ext(ext).to_string(),
|
||||
favorite: false,
|
||||
rating: 0,
|
||||
embedding_status: "pending".to_string(),
|
||||
embedding_model: Some(vector::CLIP_MODEL_NAME.to_string()),
|
||||
embedding_updated_at: None,
|
||||
embedding_error: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn emit_progress(app: &AppHandle, progress: &IndexProgress) {
|
||||
let _ = app.emit("index-progress", progress);
|
||||
}
|
||||
|
||||
fn emit_images(app: &AppHandle, batch: &IndexedImagesBatch) {
|
||||
let _ = app.emit("indexed-images", batch);
|
||||
}
|
||||
|
||||
fn commit_batch(pool: &DbPool, records: &[ImageRecord]) -> Result<Vec<ImageRecord>> {
|
||||
let mut conn = pool.get()?;
|
||||
let tx = conn.transaction()?;
|
||||
let mut committed = Vec::with_capacity(records.len());
|
||||
|
||||
for record in records {
|
||||
let mut committed_record = record.clone();
|
||||
committed_record.id = db::upsert_image(&tx, record)?;
|
||||
db::enqueue_embedding_job(&tx, committed_record.id)?;
|
||||
committed.push(committed_record);
|
||||
}
|
||||
|
||||
tx.commit()?;
|
||||
Ok(committed)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
mod commands;
|
||||
mod db;
|
||||
mod indexer;
|
||||
mod thumbnail;
|
||||
mod vector;
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.setup(|app| {
|
||||
let app_dir = app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.expect("Failed to get app data dir");
|
||||
|
||||
std::fs::create_dir_all(&app_dir).expect("Failed to create app data dir");
|
||||
|
||||
let db_path = app_dir.join("gallery.db");
|
||||
let pool = db::create_pool(&db_path).expect("Failed to create database pool");
|
||||
|
||||
{
|
||||
let conn = pool.get().expect("Failed to get connection for migration");
|
||||
db::migrate(&conn).expect("Failed to run migrations");
|
||||
}
|
||||
|
||||
app.manage(pool);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
commands::add_folder,
|
||||
commands::get_folders,
|
||||
commands::remove_folder,
|
||||
commands::get_images,
|
||||
commands::reindex_folder,
|
||||
commands::update_image_details,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
image_gallery_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
use std::path::Path;
|
||||
|
||||
/// Gets image dimensions without fully decoding.
|
||||
pub fn get_dimensions(image_path: &Path) -> Option<(u32, u32)> {
|
||||
image::image_dimensions(image_path).ok()
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use rusqlite::{ffi::sqlite3_auto_extension, Connection};
|
||||
use sqlite_vec::sqlite3_vec_init;
|
||||
use std::sync::Once;
|
||||
|
||||
pub const CLIP_MODEL_NAME: &str = "openclip-vit-b-32";
|
||||
pub const CLIP_VECTOR_DIM: usize = 512;
|
||||
|
||||
static SQLITE_VEC_INIT: Once = Once::new();
|
||||
|
||||
pub fn register_sqlite_vec() {
|
||||
SQLITE_VEC_INIT.call_once(|| unsafe {
|
||||
sqlite3_auto_extension(Some(std::mem::transmute(sqlite3_vec_init as *const ())));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(&format!(
|
||||
"CREATE VIRTUAL TABLE IF NOT EXISTS image_vec USING vec0(
|
||||
image_id INTEGER PRIMARY KEY,
|
||||
embedding FLOAT[{}] distance_metric=cosine
|
||||
);",
|
||||
CLIP_VECTOR_DIM
|
||||
))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn delete_embedding(conn: &Connection, image_id: i64) -> Result<()> {
|
||||
conn.execute("DELETE FROM image_vec WHERE image_id = ?1", [image_id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn upsert_embedding(conn: &Connection, image_id: i64, embedding: &[f32]) -> Result<()> {
|
||||
if embedding.len() != CLIP_VECTOR_DIM {
|
||||
return Err(anyhow!(
|
||||
"expected {}-dimensional embedding, got {}",
|
||||
CLIP_VECTOR_DIM,
|
||||
embedding.len()
|
||||
));
|
||||
}
|
||||
|
||||
let packed = pack_f32(embedding);
|
||||
conn.execute("DELETE FROM image_vec WHERE image_id = ?1", [image_id])?;
|
||||
conn.execute(
|
||||
"INSERT INTO image_vec (image_id, embedding) VALUES (?1, ?2)",
|
||||
(&image_id, &packed),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
fn pack_f32(values: &[f32]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(values.len() * std::mem::size_of::<f32>());
|
||||
for value in values {
|
||||
out.extend_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Phokus",
|
||||
"version": "0.1.0",
|
||||
"identifier": "wtf.jezz.phokus",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
"devUrl": "http://localhost:1420",
|
||||
"beforeBuildCommand": "pnpm build",
|
||||
"frontendDist": "../dist"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "Phokus",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"minWidth": 800,
|
||||
"minHeight": 600
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": null,
|
||||
"assetProtocol": {
|
||||
"enable": true,
|
||||
"scope": ["**"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
.logo.vite:hover {
|
||||
filter: drop-shadow(0 0 2em #747bff);
|
||||
}
|
||||
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafb);
|
||||
}
|
||||
:root {
|
||||
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
font-weight: 400;
|
||||
|
||||
color: #0f0f0f;
|
||||
background-color: #f6f6f6;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
|
||||
.container {
|
||||
margin: 0;
|
||||
padding-top: 10vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: 0.75s;
|
||||
}
|
||||
|
||||
.logo.tauri:hover {
|
||||
filter: drop-shadow(0 0 2em #24c8db);
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
h1 {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
color: #0f0f0f;
|
||||
background-color: #ffffff;
|
||||
transition: border-color 0.25s;
|
||||
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
border-color: #396cd8;
|
||||
}
|
||||
button:active {
|
||||
border-color: #396cd8;
|
||||
background-color: #e8e8e8;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#greet-input {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
color: #f6f6f6;
|
||||
background-color: #2f2f2f;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
color: #24c8db;
|
||||
}
|
||||
|
||||
input,
|
||||
button {
|
||||
color: #ffffff;
|
||||
background-color: #0f0f0f98;
|
||||
}
|
||||
button:active {
|
||||
background-color: #0f0f0f69;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useEffect } from "react";
|
||||
import { useGalleryStore } from "./store";
|
||||
import { Sidebar } from "./components/Sidebar";
|
||||
import { MenuBar } from "./components/MenuBar";
|
||||
import { Toolbar } from "./components/Toolbar";
|
||||
import { Gallery } from "./components/Gallery";
|
||||
import { Lightbox } from "./components/Lightbox";
|
||||
|
||||
export default function App() {
|
||||
const { loadFolders, loadImages, subscribeToProgress } = useGalleryStore();
|
||||
|
||||
useEffect(() => {
|
||||
loadFolders().then(() => loadImages(true));
|
||||
let unlisten: (() => void) | undefined;
|
||||
subscribeToProgress().then((fn) => {
|
||||
unlisten = fn;
|
||||
});
|
||||
return () => {
|
||||
unlisten?.();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-gray-950 text-white overflow-hidden select-none">
|
||||
<Sidebar />
|
||||
<main className="flex-1 flex flex-col min-w-0">
|
||||
<MenuBar />
|
||||
<Toolbar />
|
||||
<Gallery />
|
||||
</main>
|
||||
<Lightbox />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,273 @@
|
||||
import { useEffect, useRef, useCallback, useState } from "react";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { ImageRecord, tileSizeForZoom, useGalleryStore } from "../store";
|
||||
|
||||
const GAP = 8;
|
||||
|
||||
function RatingStars({ rating }: { rating: number }) {
|
||||
return (
|
||||
<div className="flex items-center gap-0.5">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const filled = index < rating;
|
||||
return (
|
||||
<svg
|
||||
key={index}
|
||||
className={`h-3 w-3 ${filled ? "text-amber-300" : "text-white/25"}`}
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
function ContextMenu({
|
||||
x,
|
||||
y,
|
||||
image,
|
||||
onClose,
|
||||
}: {
|
||||
x: number;
|
||||
y: number;
|
||||
image: ImageRecord;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { openImage, updateImageDetails } = useGalleryStore();
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed z-40 min-w-56 rounded-2xl border border-white/10 bg-gray-950/95 p-2 shadow-2xl backdrop-blur"
|
||||
style={{ left: x, top: y }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="w-full rounded-xl px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5"
|
||||
onClick={() => {
|
||||
openImage(image);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Open Preview
|
||||
</button>
|
||||
<button
|
||||
className="w-full rounded-xl px-3 py-2 text-left text-sm text-gray-200 hover:bg-white/5"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { favorite: !image.favorite });
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
{image.favorite ? "Remove Favorite" : "Add to Favorites"}
|
||||
</button>
|
||||
<div className="my-2 h-px bg-white/5" />
|
||||
<div className="px-3 pb-1 pt-1 text-[11px] uppercase tracking-[0.2em] text-gray-500">Rating</div>
|
||||
<div className="flex gap-1 px-2 pb-1">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1;
|
||||
return (
|
||||
<button
|
||||
key={rating}
|
||||
className={`rounded-lg px-2 py-1 text-sm ${rating <= image.rating ? "bg-amber-400/15 text-amber-300" : "bg-white/5 text-gray-400 hover:text-white"}`}
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating });
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
{rating}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<button
|
||||
className="ml-auto rounded-lg px-2 py-1 text-sm text-gray-400 hover:bg-white/5 hover:text-white"
|
||||
onClick={async () => {
|
||||
await updateImageDetails(image.id, { rating: 0 });
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageTile({
|
||||
image,
|
||||
onClick,
|
||||
onContextMenu,
|
||||
}: {
|
||||
image: ImageRecord;
|
||||
onClick: () => void;
|
||||
onContextMenu: (event: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
}) {
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [errored, setErrored] = useState(false);
|
||||
|
||||
const src = image.thumbnail_path
|
||||
? convertFileSrc(image.thumbnail_path)
|
||||
: image.media_kind === "image" && image.path
|
||||
? convertFileSrc(image.path)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<button
|
||||
className="group relative overflow-hidden rounded-2xl border border-white/5 bg-white/[0.03] text-left"
|
||||
style={{ width: "100%", aspectRatio: "1 / 1" }}
|
||||
onClick={onClick}
|
||||
onContextMenu={onContextMenu}
|
||||
title={image.filename}
|
||||
>
|
||||
{image.media_kind === "video" ? (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-fuchsia-500/10 via-white/5 to-cyan-500/10">
|
||||
<div className="rounded-full border border-white/10 bg-black/30 p-4 text-white shadow-lg">
|
||||
<svg className="h-8 w-8" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M8 5v14l11-7z" />
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
) : src && !errored ? (
|
||||
<>
|
||||
{!loaded ? <div className="absolute inset-0 animate-pulse bg-white/5" /> : null}
|
||||
<img
|
||||
src={src}
|
||||
alt={image.filename}
|
||||
className={`h-full w-full object-cover transition-opacity duration-200 ${loaded ? "opacity-100" : "opacity-0"}`}
|
||||
loading="lazy"
|
||||
onLoad={() => setLoaded(true)}
|
||||
onError={() => setErrored(true)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-white/5 text-gray-600">
|
||||
<svg className="h-9 w-9" 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>
|
||||
)}
|
||||
|
||||
<div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/20 to-transparent opacity-80 transition-opacity group-hover:opacity-100" />
|
||||
|
||||
<div className="absolute left-3 right-3 top-3 flex items-start justify-between gap-2">
|
||||
<div className="rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] uppercase tracking-[0.18em] text-white/80">
|
||||
{image.media_kind}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{image.favorite ? (
|
||||
<div className="rounded-full border border-white/10 bg-black/35 p-1 text-rose-300">
|
||||
<svg className="h-3.5 w-3.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}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="absolute bottom-0 left-0 right-0 p-3">
|
||||
<p className="truncate text-sm font-medium text-white">{image.filename}</p>
|
||||
<div className="mt-1 flex items-center justify-between gap-2 text-xs text-white/70">
|
||||
<RatingStars rating={image.rating} />
|
||||
<span>{image.embedding_status === "ready" ? "indexed" : image.embedding_status}</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Gallery() {
|
||||
const { images, loadMoreImages, openImage, totalImages, loadingImages, zoomPreset } = useGalleryStore();
|
||||
|
||||
const parentRef = useRef<HTMLDivElement>(null);
|
||||
const [contextMenu, setContextMenu] = useState<{ x: number; y: number; image: ImageRecord } | null>(null);
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
const element = parentRef.current;
|
||||
if (!element) return;
|
||||
const nearBottom = element.scrollTop + element.clientHeight >= element.scrollHeight - 600;
|
||||
if (nearBottom && !loadingImages && images.length < totalImages) {
|
||||
void loadMoreImages();
|
||||
}
|
||||
}, [images.length, loadMoreImages, loadingImages, totalImages]);
|
||||
|
||||
useEffect(() => {
|
||||
const element = parentRef.current;
|
||||
if (!element) return;
|
||||
element.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => element.removeEventListener("scroll", handleScroll);
|
||||
}, [handleScroll]);
|
||||
|
||||
useEffect(() => {
|
||||
const close = () => setContextMenu(null);
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") {
|
||||
setContextMenu(null);
|
||||
}
|
||||
};
|
||||
window.addEventListener("click", close);
|
||||
window.addEventListener("contextmenu", close);
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
window.removeEventListener("click", close);
|
||||
window.removeEventListener("contextmenu", close);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, []);
|
||||
|
||||
if (images.length === 0 && !loadingImages) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 text-gray-600">
|
||||
<svg className="h-16 w-16 opacity-30" 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">No media found</p>
|
||||
<p className="text-xs opacity-60">Try another filter, or add a folder from the library menu.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={parentRef} className="relative flex-1 overflow-y-auto overflow-x-hidden min-h-0 bg-[#060816]">
|
||||
<div
|
||||
className="grid content-start"
|
||||
style={{
|
||||
padding: GAP,
|
||||
gap: GAP,
|
||||
gridTemplateColumns: `repeat(auto-fill, minmax(${tileSizeForZoom(zoomPreset)}px, 1fr))`,
|
||||
}}
|
||||
>
|
||||
{images.map((image) => (
|
||||
<ImageTile
|
||||
key={image.id}
|
||||
image={image}
|
||||
onClick={() => openImage(image)}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setContextMenu({ x: event.clientX, y: event.clientY, image });
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{loadingImages ? (
|
||||
<div className="flex justify-center py-6">
|
||||
<div className="h-5 w-5 rounded-full border-2 border-blue-500 border-t-transparent animate-spin" />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{contextMenu ? (
|
||||
<ContextMenu x={contextMenu.x} y={contextMenu.y} image={contextMenu.image} onClose={() => setContextMenu(null)} />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { useEffect, useCallback, useRef, useState } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { convertFileSrc } from "@tauri-apps/api/core";
|
||||
import { useGalleryStore } from "../store";
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
function formatDate(iso: string | null): string {
|
||||
if (!iso) return "Unknown";
|
||||
return new Date(iso).toLocaleDateString(undefined, {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
}
|
||||
|
||||
export function Lightbox() {
|
||||
const { selectedImage, closeImage, images, openImage, updateImageDetails } = useGalleryStore();
|
||||
const [zoom, setZoom] = useState(1);
|
||||
const imageViewportRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const currentIndex = selectedImage ? images.findIndex((image) => image.id === selectedImage.id) : -1;
|
||||
|
||||
const goPrev = useCallback(() => {
|
||||
if (currentIndex > 0) openImage(images[currentIndex - 1]);
|
||||
}, [currentIndex, images, openImage]);
|
||||
|
||||
const goNext = useCallback(() => {
|
||||
if (currentIndex >= 0 && currentIndex < images.length - 1) openImage(images[currentIndex + 1]);
|
||||
}, [currentIndex, images, openImage]);
|
||||
|
||||
useEffect(() => {
|
||||
setZoom(1);
|
||||
}, [selectedImage?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
const viewport = imageViewportRef.current;
|
||||
if (!viewport || !selectedImage || selectedImage.media_kind !== "image") return;
|
||||
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
if (!event.ctrlKey && Math.abs(event.deltaY) < Math.abs(event.deltaX)) return;
|
||||
event.preventDefault();
|
||||
setZoom((value) => {
|
||||
const delta = event.deltaY < 0 ? 0.15 : -0.15;
|
||||
return Math.min(4, Math.max(0.5, value + delta));
|
||||
});
|
||||
};
|
||||
|
||||
viewport.addEventListener("wheel", handleWheel, { passive: false });
|
||||
return () => viewport.removeEventListener("wheel", handleWheel);
|
||||
}, [selectedImage]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: KeyboardEvent) => {
|
||||
if (!selectedImage) return;
|
||||
if (event.key === "Escape") closeImage();
|
||||
if (event.key === "ArrowLeft") goPrev();
|
||||
if (event.key === "ArrowRight") goNext();
|
||||
if (event.key === "+" || event.key === "=") setZoom((value) => Math.min(3, value + 0.25));
|
||||
if (event.key === "-") setZoom((value) => Math.max(0.75, value - 0.25));
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [selectedImage, closeImage, goPrev, goNext]);
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{selectedImage ? (
|
||||
<motion.div
|
||||
key="lightbox"
|
||||
className="fixed inset-0 z-50 flex bg-black/90 backdrop-blur-sm"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={closeImage}
|
||||
>
|
||||
<button
|
||||
className="absolute left-4 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"
|
||||
disabled={currentIndex <= 0}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
goPrev();
|
||||
}}
|
||||
>
|
||||
<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>
|
||||
|
||||
<motion.div
|
||||
key={selectedImage.id}
|
||||
className="flex flex-1 flex-col"
|
||||
initial={{ scale: 0.95, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.95, opacity: 0 }}
|
||||
transition={{ duration: 0.15 }}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
>
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
<div
|
||||
ref={imageViewportRef}
|
||||
className="group relative flex flex-1 items-center justify-center overflow-auto p-10"
|
||||
>
|
||||
{selectedImage.media_kind === "video" ? (
|
||||
<video
|
||||
src={convertFileSrc(selectedImage.path)}
|
||||
controls
|
||||
className="max-h-full max-w-full rounded-2xl shadow-2xl"
|
||||
style={{ maxHeight: "calc(100vh - 10rem)" }}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<img
|
||||
src={convertFileSrc(selectedImage.path)}
|
||||
alt={selectedImage.filename}
|
||||
className="max-w-full rounded-2xl shadow-2xl"
|
||||
style={{
|
||||
maxHeight: "calc(100vh - 10rem)",
|
||||
transform: `scale(${zoom})`,
|
||||
transformOrigin: "center center",
|
||||
}}
|
||||
/>
|
||||
<div className="pointer-events-none absolute right-6 top-6 opacity-0 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 px-2 py-1 backdrop-blur">
|
||||
<button
|
||||
className="px-2 text-sm text-gray-300 hover:text-white"
|
||||
onClick={() => setZoom((value) => Math.max(0.5, value - 0.25))}
|
||||
>
|
||||
-
|
||||
</button>
|
||||
<span className="min-w-14 text-center text-xs text-gray-300">{Math.round(zoom * 100)}%</span>
|
||||
<button
|
||||
className="px-2 text-sm text-gray-300 hover:text-white"
|
||||
onClick={() => setZoom((value) => Math.min(4, value + 0.25))}
|
||||
>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex w-72 shrink-0 flex-col border-l border-white/5 bg-gray-900/95 p-5">
|
||||
<div className="mb-5 flex items-center justify-between">
|
||||
<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">
|
||||
<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 })}
|
||||
title={selectedImage.favorite ? "Remove favorite" : "Add 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>
|
||||
</div>
|
||||
<button className="rounded p-1 text-gray-400 hover:text-white" onClick={closeImage}>
|
||||
<svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 text-sm">
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Rating</p>
|
||||
<div className="flex items-center gap-1">
|
||||
{Array.from({ length: 5 }, (_, index) => {
|
||||
const rating = index + 1;
|
||||
return (
|
||||
<button
|
||||
key={rating}
|
||||
className="rounded-md p-1"
|
||||
onClick={() => void updateImageDetails(selectedImage.id, { rating })}
|
||||
title={`Set ${rating} star rating`}
|
||||
>
|
||||
<svg
|
||||
className={`h-5 w-5 ${rating <= selectedImage.rating ? "text-amber-300" : "text-white/20 hover:text-white/50"}`}
|
||||
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>
|
||||
);
|
||||
})}
|
||||
{selectedImage.rating > 0 ? (
|
||||
<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 })}
|
||||
title="Remove rating"
|
||||
>
|
||||
<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>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Dimensions</p>
|
||||
<p className="text-white">
|
||||
{selectedImage.width && selectedImage.height
|
||||
? `${selectedImage.width} x ${selectedImage.height}px`
|
||||
: "Pending / unavailable"}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Type</p>
|
||||
<p className="text-white">{selectedImage.mime_type}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">File size</p>
|
||||
<p className="text-white">{formatBytes(selectedImage.file_size)}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Modified</p>
|
||||
<p className="text-white">{formatDate(selectedImage.modified_at)}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Embedding</p>
|
||||
<p className="text-white">{selectedImage.embedding_status}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="mb-1 text-xs uppercase tracking-wider text-gray-500">Path</p>
|
||||
<p className="break-all text-xs text-gray-400">{selectedImage.path}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-auto pt-4 text-center text-xs text-gray-600">
|
||||
{currentIndex + 1} / {images.length}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
<button
|
||||
className="absolute right-80 top-1/2 z-10 -translate-y-1/2 rounded-full bg-white/10 p-3 text-white transition-colors hover:bg-white/20 disabled:opacity-20"
|
||||
disabled={currentIndex >= images.length - 1}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
goNext();
|
||||
}}
|
||||
>
|
||||
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
</motion.div>
|
||||
) : null}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
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 {
|
||||
addFolder,
|
||||
reindexFolder,
|
||||
selectedFolderId,
|
||||
zoomPreset,
|
||||
setZoomPreset,
|
||||
mediaFilter,
|
||||
setMediaFilter,
|
||||
favoritesOnly,
|
||||
setFavoritesOnly,
|
||||
} = useGalleryStore();
|
||||
|
||||
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 = async () => {
|
||||
const selected = await open({ directory: true, multiple: false, title: "Select Media Folder" });
|
||||
if (selected && typeof selected === "string") {
|
||||
await addFolder(selected);
|
||||
}
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { open } from "@tauri-apps/plugin-dialog";
|
||||
import { useGalleryStore, Folder, IndexProgress } from "../store";
|
||||
|
||||
function FolderItem({
|
||||
folder,
|
||||
selected,
|
||||
progress,
|
||||
}: {
|
||||
folder: Folder;
|
||||
selected: boolean;
|
||||
progress: IndexProgress | undefined;
|
||||
}) {
|
||||
const { selectFolder, removeFolder, reindexFolder } = useGalleryStore();
|
||||
const isIndexing = progress && !progress.done;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`group flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer transition-colors ${
|
||||
selected
|
||||
? "bg-blue-600 text-white"
|
||||
: "hover:bg-white/5 text-gray-300 hover:text-white"
|
||||
}`}
|
||||
onClick={() => selectFolder(folder.id)}
|
||||
>
|
||||
<svg
|
||||
className="w-4 h-4 shrink-0 opacity-70"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M3 7a2 2 0 012-2h3.586a1 1 0 01.707.293l1.414 1.414A1 1 0 0011.414 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z"
|
||||
/>
|
||||
</svg>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="truncate text-sm font-medium">{folder.name}</div>
|
||||
{isIndexing ? (
|
||||
<div className="text-xs opacity-60">
|
||||
{progress.indexed}/{progress.total} indexed
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-xs opacity-50">
|
||||
{folder.image_count.toLocaleString()} items
|
||||
</div>
|
||||
)}
|
||||
{isIndexing && (
|
||||
<div className="h-0.5 bg-white/20 rounded mt-1 overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-blue-400 transition-all duration-300"
|
||||
style={{
|
||||
width: `${progress.total > 0 ? (progress.indexed / progress.total) * 100 : 0}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
|
||||
<button
|
||||
className="p-1 rounded hover:bg-white/10"
|
||||
title="Re-index"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
reindexFolder(folder.id);
|
||||
}}
|
||||
>
|
||||
<svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
className="p-1 rounded hover:bg-red-500/20 hover:text-red-400"
|
||||
title="Remove folder"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeFolder(folder.id);
|
||||
}}
|
||||
>
|
||||
<svg className="w-3 h-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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const { folders, selectedFolderId, addFolder, indexingProgress, totalImages, selectFolder } =
|
||||
useGalleryStore();
|
||||
|
||||
const handleAddFolder = async () => {
|
||||
const selected = await open({
|
||||
directory: true,
|
||||
multiple: false,
|
||||
title: "Select Media Folder",
|
||||
});
|
||||
if (selected && typeof selected === "string") {
|
||||
await addFolder(selected);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="w-72 shrink-0 flex flex-col bg-gray-900 border-r border-white/5">
|
||||
{/* Header */}
|
||||
<div className="px-4 py-4 border-b border-white/5">
|
||||
<h1 className="text-white font-semibold text-base">Image Gallery</h1>
|
||||
<p className="text-gray-500 text-xs mt-0.5">
|
||||
{folders.reduce((s, f) => s + f.image_count, 0).toLocaleString()} total items
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* All photos link */}
|
||||
<div className="px-3 pt-3">
|
||||
<div
|
||||
className={`flex items-center gap-2 px-3 py-2 rounded-lg cursor-pointer transition-colors ${
|
||||
selectedFolderId === null
|
||||
? "bg-blue-600 text-white"
|
||||
: "hover:bg-white/5 text-gray-300 hover:text-white"
|
||||
}`}
|
||||
onClick={() => selectFolder(null)}
|
||||
>
|
||||
<svg className="w-4 h-4 shrink-0 opacity-70" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5}
|
||||
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium">All Media</span>
|
||||
{selectedFolderId === null && (
|
||||
<span className="ml-auto text-xs opacity-60">{totalImages.toLocaleString()}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Folder list */}
|
||||
<div className="flex-1 overflow-y-auto px-3 py-2 space-y-0.5 min-h-0">
|
||||
{folders.length === 0 ? (
|
||||
<p className="text-gray-600 text-xs px-3 py-4 text-center">
|
||||
No folders added yet
|
||||
</p>
|
||||
) : (
|
||||
folders.map((folder) => (
|
||||
<FolderItem
|
||||
key={folder.id}
|
||||
folder={folder}
|
||||
selected={selectedFolderId === folder.id}
|
||||
progress={indexingProgress[folder.id]}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Add folder button */}
|
||||
<div className="px-3 pb-4 pt-2 border-t border-white/5">
|
||||
<button
|
||||
onClick={handleAddFolder}
|
||||
className="w-full flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl bg-blue-600 hover:bg-blue-500 text-white text-sm font-medium transition-colors"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
|
||||
</svg>
|
||||
Add Media Folder
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { tileSizeForZoom, useGalleryStore, SortOrder } from "../store";
|
||||
|
||||
const SORT_OPTIONS: { value: SortOrder; label: string }[] = [
|
||||
{ value: "date_desc", label: "Newest first" },
|
||||
{ value: "date_asc", label: "Oldest first" },
|
||||
{ value: "name_asc", label: "Name A-Z" },
|
||||
{ value: "name_desc", label: "Name Z-A" },
|
||||
{ value: "size_desc", label: "Largest first" },
|
||||
{ value: "size_asc", label: "Smallest first" },
|
||||
];
|
||||
|
||||
function FilterChip({
|
||||
label,
|
||||
active,
|
||||
onClick,
|
||||
}: {
|
||||
label: string;
|
||||
active: boolean;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
className={`rounded-full border px-3 py-1 text-xs transition-colors ${
|
||||
active
|
||||
? "border-blue-400/50 bg-blue-500/15 text-white"
|
||||
: "border-white/10 bg-white/5 text-gray-400 hover:border-white/20 hover:text-white"
|
||||
}`}
|
||||
onClick={onClick}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Toolbar() {
|
||||
const {
|
||||
search,
|
||||
setSearch,
|
||||
sort,
|
||||
setSort,
|
||||
totalImages,
|
||||
loadedCount,
|
||||
selectedFolderId,
|
||||
folders,
|
||||
mediaFilter,
|
||||
setMediaFilter,
|
||||
favoritesOnly,
|
||||
setFavoritesOnly,
|
||||
zoomPreset,
|
||||
setZoomPreset,
|
||||
} = useGalleryStore();
|
||||
|
||||
const [searchValue, setSearchValue] = useState(search);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const selectedFolder = folders.find((folder) => folder.id === selectedFolderId);
|
||||
const title = selectedFolder ? selectedFolder.name : "All Media";
|
||||
const tileSize = tileSizeForZoom(zoomPreset);
|
||||
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => {
|
||||
setSearch(searchValue);
|
||||
}, 200);
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, [searchValue, setSearch]);
|
||||
|
||||
return (
|
||||
<div className="border-b border-white/5 bg-gray-950/60 px-5 py-4 backdrop-blur-xl shrink-0">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="truncate text-base font-semibold text-white">{title}</h2>
|
||||
<div className="rounded-full border border-white/10 bg-white/5 px-2.5 py-1 text-[11px] uppercase tracking-[0.16em] text-gray-400">
|
||||
{favoritesOnly ? "Favorites" : mediaFilter === "all" ? "Mixed Library" : mediaFilter}
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
{loadedCount < totalImages
|
||||
? `Showing ${loadedCount.toLocaleString()} of ${totalImages.toLocaleString()} items`
|
||||
: `${totalImages.toLocaleString()} items ready`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="relative">
|
||||
<svg
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500"
|
||||
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
|
||||
type="text"
|
||||
value={searchValue}
|
||||
onChange={(event) => setSearchValue(event.target.value)}
|
||||
placeholder="Search filenames, scenes, references..."
|
||||
className="w-72 rounded-xl border border-white/10 bg-white/5 py-2 pl-9 pr-4 text-sm text-white placeholder:text-gray-500 focus:border-blue-500 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<select
|
||||
value={sort}
|
||||
onChange={(event) => setSort(event.target.value as SortOrder)}
|
||||
className="rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
|
||||
>
|
||||
{SORT_OPTIONS.map((option) => (
|
||||
<option key={option.value} value={option.value} className="bg-gray-900">
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<FilterChip label="All" active={mediaFilter === "all"} onClick={() => setMediaFilter("all")} />
|
||||
<FilterChip label="Images" active={mediaFilter === "image"} onClick={() => setMediaFilter("image")} />
|
||||
<FilterChip label="Videos" active={mediaFilter === "video"} onClick={() => setMediaFilter("video")} />
|
||||
<FilterChip label="Favorites" active={favoritesOnly} onClick={() => setFavoritesOnly(!favoritesOnly)} />
|
||||
|
||||
<div className="ml-auto flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-2 py-1 text-xs text-gray-400">
|
||||
<span className="px-2">Tile {tileSize}px</span>
|
||||
<button
|
||||
className={`rounded-full px-2 py-1 ${zoomPreset === "compact" ? "bg-white/10 text-white" : "hover:text-white"}`}
|
||||
onClick={() => setZoomPreset("compact")}
|
||||
>
|
||||
S
|
||||
</button>
|
||||
<button
|
||||
className={`rounded-full px-2 py-1 ${zoomPreset === "comfortable" ? "bg-white/10 text-white" : "hover:text-white"}`}
|
||||
onClick={() => setZoomPreset("comfortable")}
|
||||
>
|
||||
M
|
||||
</button>
|
||||
<button
|
||||
className={`rounded-full px-2 py-1 ${zoomPreset === "detail" ? "bg-white/10 text-white" : "hover:text-white"}`}
|
||||
onClick={() => setZoomPreset("detail")}
|
||||
>
|
||||
L
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: #030712;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* Custom scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border-radius: 3px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./index.css";
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,361 @@
|
||||
import { create } from "zustand";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { appDataDir, join } from "@tauri-apps/api/path";
|
||||
|
||||
export interface Folder {
|
||||
id: number;
|
||||
path: string;
|
||||
name: string;
|
||||
image_count: number;
|
||||
indexed_at: string | null;
|
||||
}
|
||||
|
||||
export type MediaKind = "image" | "video";
|
||||
export type MediaFilter = "all" | MediaKind;
|
||||
export type ZoomPreset = "compact" | "comfortable" | "detail";
|
||||
|
||||
export interface ImageRecord {
|
||||
id: number;
|
||||
folder_id: number;
|
||||
path: string;
|
||||
filename: string;
|
||||
thumbnail_path: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
file_size: number;
|
||||
created_at: string | null;
|
||||
modified_at: string | null;
|
||||
mime_type: string;
|
||||
media_kind: MediaKind;
|
||||
favorite: boolean;
|
||||
rating: number;
|
||||
embedding_status: string;
|
||||
embedding_model: string | null;
|
||||
embedding_updated_at: string | null;
|
||||
embedding_error: string | null;
|
||||
}
|
||||
|
||||
export interface IndexProgress {
|
||||
folder_id: number;
|
||||
total: number;
|
||||
indexed: number;
|
||||
current_file: string;
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
export interface IndexedImagesBatch {
|
||||
folder_id: number;
|
||||
images: ImageRecord[];
|
||||
}
|
||||
|
||||
export type SortOrder =
|
||||
| "date_desc"
|
||||
| "date_asc"
|
||||
| "name_asc"
|
||||
| "name_desc"
|
||||
| "size_desc"
|
||||
| "size_asc";
|
||||
|
||||
interface GalleryState {
|
||||
folders: Folder[];
|
||||
selectedFolderId: number | null;
|
||||
images: ImageRecord[];
|
||||
totalImages: number;
|
||||
loadedCount: number;
|
||||
loadingImages: boolean;
|
||||
search: string;
|
||||
sort: SortOrder;
|
||||
mediaFilter: MediaFilter;
|
||||
favoritesOnly: boolean;
|
||||
zoomPreset: ZoomPreset;
|
||||
selectedImage: ImageRecord | null;
|
||||
indexingProgress: Record<number, IndexProgress>;
|
||||
cacheDir: string;
|
||||
|
||||
loadFolders: () => Promise<void>;
|
||||
addFolder: (path: string) => Promise<void>;
|
||||
removeFolder: (folderId: number) => Promise<void>;
|
||||
reindexFolder: (folderId: number) => Promise<void>;
|
||||
selectFolder: (folderId: number | null) => void;
|
||||
loadImages: (reset?: boolean) => Promise<void>;
|
||||
loadMoreImages: () => Promise<void>;
|
||||
setSearch: (search: string) => void;
|
||||
setSort: (sort: SortOrder) => void;
|
||||
setMediaFilter: (filter: MediaFilter) => void;
|
||||
setFavoritesOnly: (favoritesOnly: boolean) => void;
|
||||
setZoomPreset: (zoomPreset: ZoomPreset) => void;
|
||||
openImage: (image: ImageRecord) => void;
|
||||
closeImage: () => void;
|
||||
updateImageDetails: (imageId: number, updates: { favorite?: boolean; rating?: number }) => Promise<void>;
|
||||
setCacheDir: (dir: string) => void;
|
||||
subscribeToProgress: () => Promise<UnlistenFn>;
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 200;
|
||||
|
||||
function matchesSearch(image: ImageRecord, search: string): boolean {
|
||||
if (!search) return true;
|
||||
return image.filename.toLowerCase().includes(search.toLowerCase());
|
||||
}
|
||||
|
||||
function matchesFilters(
|
||||
image: ImageRecord,
|
||||
selectedFolderId: number | null,
|
||||
mediaFilter: MediaFilter,
|
||||
favoritesOnly: boolean,
|
||||
search: string,
|
||||
): boolean {
|
||||
const matchesFolder = selectedFolderId === null || image.folder_id === selectedFolderId;
|
||||
const matchesMedia = mediaFilter === "all" || image.media_kind === mediaFilter;
|
||||
const matchesFavorite = !favoritesOnly || image.favorite;
|
||||
return matchesFolder && matchesMedia && matchesFavorite && matchesSearch(image, search);
|
||||
}
|
||||
|
||||
function compareNullableNumber(a: number | null, b: number | null): number {
|
||||
return (a ?? 0) - (b ?? 0);
|
||||
}
|
||||
|
||||
function compareNullableDate(a: string | null, b: string | null): number {
|
||||
return (a ? Date.parse(a) : 0) - (b ? Date.parse(b) : 0);
|
||||
}
|
||||
|
||||
function compareImages(a: ImageRecord, b: ImageRecord, sort: SortOrder): number {
|
||||
switch (sort) {
|
||||
case "name_asc":
|
||||
return a.filename.localeCompare(b.filename);
|
||||
case "name_desc":
|
||||
return b.filename.localeCompare(a.filename);
|
||||
case "date_asc":
|
||||
return compareNullableDate(a.modified_at, b.modified_at);
|
||||
case "date_desc":
|
||||
return compareNullableDate(b.modified_at, a.modified_at);
|
||||
case "size_asc":
|
||||
return compareNullableNumber(a.file_size, b.file_size);
|
||||
case "size_desc":
|
||||
return compareNullableNumber(b.file_size, a.file_size);
|
||||
default:
|
||||
return compareNullableDate(b.modified_at, a.modified_at);
|
||||
}
|
||||
}
|
||||
|
||||
function mergeImages(currentImages: ImageRecord[], newImages: ImageRecord[], sort: SortOrder): ImageRecord[] {
|
||||
const merged = new Map<string, ImageRecord>();
|
||||
|
||||
for (const image of currentImages) {
|
||||
merged.set(image.path, image);
|
||||
}
|
||||
|
||||
for (const image of newImages) {
|
||||
merged.set(image.path, image);
|
||||
}
|
||||
|
||||
return Array.from(merged.values()).sort((a, b) => compareImages(a, b, sort));
|
||||
}
|
||||
|
||||
function replaceImage(images: ImageRecord[], updatedImage: ImageRecord, sort: SortOrder): ImageRecord[] {
|
||||
return mergeImages(images, [updatedImage], sort);
|
||||
}
|
||||
|
||||
export function tileSizeForZoom(zoomPreset: ZoomPreset): number {
|
||||
switch (zoomPreset) {
|
||||
case "compact":
|
||||
return 160;
|
||||
case "detail":
|
||||
return 280;
|
||||
default:
|
||||
return 220;
|
||||
}
|
||||
}
|
||||
|
||||
export const useGalleryStore = create<GalleryState>((set, get) => ({
|
||||
folders: [],
|
||||
selectedFolderId: null,
|
||||
images: [],
|
||||
totalImages: 0,
|
||||
loadedCount: 0,
|
||||
loadingImages: false,
|
||||
search: "",
|
||||
sort: "date_desc",
|
||||
mediaFilter: "all",
|
||||
favoritesOnly: false,
|
||||
zoomPreset: "comfortable",
|
||||
selectedImage: null,
|
||||
indexingProgress: {},
|
||||
cacheDir: "",
|
||||
|
||||
setCacheDir: (cacheDir) => set({ cacheDir }),
|
||||
|
||||
loadFolders: async () => {
|
||||
const folders = await invoke<Folder[]>("get_folders");
|
||||
set({ folders });
|
||||
},
|
||||
|
||||
addFolder: async (path) => {
|
||||
const { cacheDir, loadFolders } = get();
|
||||
await invoke("add_folder", { path, cacheDir });
|
||||
await loadFolders();
|
||||
},
|
||||
|
||||
removeFolder: async (folderId) => {
|
||||
await invoke("remove_folder", { folderId });
|
||||
const { selectedFolderId, loadFolders, loadImages } = get();
|
||||
await loadFolders();
|
||||
if (selectedFolderId === folderId) {
|
||||
set({ selectedFolderId: null });
|
||||
await loadImages(true);
|
||||
}
|
||||
},
|
||||
|
||||
reindexFolder: async (folderId) => {
|
||||
const { cacheDir, loadFolders } = get();
|
||||
await invoke("reindex_folder", { folderId, cacheDir });
|
||||
await loadFolders();
|
||||
},
|
||||
|
||||
selectFolder: (folderId) => {
|
||||
set({ selectedFolderId: folderId, images: [], loadedCount: 0 });
|
||||
void get().loadImages(true);
|
||||
},
|
||||
|
||||
loadImages: async (reset = false) => {
|
||||
const { selectedFolderId, search, sort, loadedCount, mediaFilter, favoritesOnly } = get();
|
||||
set({ loadingImages: true });
|
||||
|
||||
try {
|
||||
const offset = reset ? 0 : loadedCount;
|
||||
const result = await invoke<{
|
||||
images: ImageRecord[];
|
||||
total: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
}>("get_images", {
|
||||
params: {
|
||||
folder_id: selectedFolderId,
|
||||
search: search || null,
|
||||
media_kind: mediaFilter === "all" ? null : mediaFilter,
|
||||
favorites_only: favoritesOnly,
|
||||
sort,
|
||||
offset,
|
||||
limit: PAGE_SIZE,
|
||||
},
|
||||
});
|
||||
|
||||
set((state) => ({
|
||||
images: reset ? result.images : [...state.images, ...result.images],
|
||||
totalImages: result.total,
|
||||
loadedCount: reset ? result.images.length : state.loadedCount + result.images.length,
|
||||
loadingImages: false,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Failed to load media:", error);
|
||||
set({ loadingImages: false });
|
||||
}
|
||||
},
|
||||
|
||||
loadMoreImages: async () => {
|
||||
const { loadedCount, totalImages, loadingImages } = get();
|
||||
if (loadingImages || loadedCount >= totalImages) return;
|
||||
await get().loadImages(false);
|
||||
},
|
||||
|
||||
setSearch: (search) => {
|
||||
set({ search, images: [], loadedCount: 0 });
|
||||
void get().loadImages(true);
|
||||
},
|
||||
|
||||
setSort: (sort) => {
|
||||
set({ sort, images: [], loadedCount: 0 });
|
||||
void get().loadImages(true);
|
||||
},
|
||||
|
||||
setMediaFilter: (mediaFilter) => {
|
||||
set({ mediaFilter, images: [], loadedCount: 0 });
|
||||
void get().loadImages(true);
|
||||
},
|
||||
|
||||
setFavoritesOnly: (favoritesOnly) => {
|
||||
set({ favoritesOnly, images: [], loadedCount: 0 });
|
||||
void get().loadImages(true);
|
||||
},
|
||||
|
||||
setZoomPreset: (zoomPreset) => set({ zoomPreset }),
|
||||
|
||||
openImage: (image) => set({ selectedImage: image }),
|
||||
closeImage: () => set({ selectedImage: null }),
|
||||
|
||||
updateImageDetails: async (imageId, updates) => {
|
||||
const updatedImage = await invoke<ImageRecord>("update_image_details", {
|
||||
params: {
|
||||
image_id: imageId,
|
||||
favorite: updates.favorite ?? null,
|
||||
rating: updates.rating ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
set((state) => ({
|
||||
images: replaceImage(state.images, updatedImage, state.sort),
|
||||
selectedImage: state.selectedImage?.id === updatedImage.id ? updatedImage : state.selectedImage,
|
||||
}));
|
||||
},
|
||||
|
||||
subscribeToProgress: async () => {
|
||||
const unlistenProgress = await listen<IndexProgress>("index-progress", (event) => {
|
||||
const progress = event.payload;
|
||||
set((state) => ({
|
||||
indexingProgress: {
|
||||
...state.indexingProgress,
|
||||
[progress.folder_id]: progress,
|
||||
},
|
||||
}));
|
||||
|
||||
if (progress.done) {
|
||||
void get().loadFolders();
|
||||
|
||||
setTimeout(() => {
|
||||
set((state) => {
|
||||
const next = { ...state.indexingProgress };
|
||||
delete next[progress.folder_id];
|
||||
return { indexingProgress: next };
|
||||
});
|
||||
}, 2000);
|
||||
}
|
||||
});
|
||||
|
||||
const unlistenImages = await listen<IndexedImagesBatch>("indexed-images", (event) => {
|
||||
const batch = event.payload;
|
||||
|
||||
set((state) => {
|
||||
const visibleImages = batch.images.filter((image) =>
|
||||
matchesFilters(
|
||||
image,
|
||||
state.selectedFolderId,
|
||||
state.mediaFilter,
|
||||
state.favoritesOnly,
|
||||
state.search,
|
||||
),
|
||||
);
|
||||
|
||||
if (visibleImages.length === 0) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const images = mergeImages(state.images, visibleImages, state.sort);
|
||||
return {
|
||||
images,
|
||||
loadedCount: images.length,
|
||||
totalImages: Math.max(state.totalImages, images.length),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
unlistenProgress();
|
||||
unlistenImages();
|
||||
};
|
||||
},
|
||||
}));
|
||||
|
||||
appDataDir().then(async (dir) => {
|
||||
useGalleryStore.getState().setCacheDir(await join(dir, "thumbnails"));
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
|
||||
// @ts-expect-error process is a nodejs global
|
||||
const host = process.env.TAURI_DEV_HOST;
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig(async () => ({
|
||||
plugins: [react(), tailwindcss()],
|
||||
|
||||
clearScreen: false,
|
||||
server: {
|
||||
port: 1420,
|
||||
strictPort: true,
|
||||
host: host || false,
|
||||
hmr: host
|
||||
? {
|
||||
protocol: "ws",
|
||||
host,
|
||||
port: 1421,
|
||||
}
|
||||
: undefined,
|
||||
watch: {
|
||||
ignored: ["**/src-tauri/**"],
|
||||
},
|
||||
},
|
||||
}));
|
||||