Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Photos: search, as icloud.com's toolbar has it

Yashwanth Kamireddi32c8298815da
diff --git a/.uiverify/photos-search.mjs b/.uiverify/photos-search.mjs
new file mode 100644
index 0000000..bb5e62a
--- /dev/null
+++ b/.uiverify/photos-search.mjs
@@ -0,0 +1,42 @@
+// Search, as icloud.com's toolbar has it: what is typed finds photos by name, title, caption,
+// keyword, year or month, as it is typed; the title says what was searched and how many;
+// nothing found says so; Escape or a view chosen ends it; the letters are words, not keys.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });
+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null });
+const page = await ctx.newPage();
+page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await openScreen(page, "Photos");
+await page.waitForTimeout(400);
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+const ids = () => page.locator(".px-tile").evaluateAll((t) => t.map((x) => x.dataset.id).join());
+const field = page.getByLabel("Search Photos");
+
+await field.click();
+await page.keyboard.type("beach");
+await page.waitForTimeout(400);
+ok((await ids()) === "p2", `a keyword finds its photo ${await ids()}`);
+ok((await page.locator(".px-bar h1").innerText()) === "“beach”" && (await page.locator(".px-span").innerText()) === "1 Result",
+ "the title says what was searched and how many");
+ok((await page.evaluate(() => (window.__flags ?? []).length)) === 0, "the letters typed are words, not keys");
+await field.fill("september 2026");
+await page.waitForTimeout(400);
+ok((await ids()) === "p4,p5", `a month and year find that month's ${await ids()}`);
+await field.fill("nothing like this");
+await page.waitForTimeout(400);
+ok((await page.locator(".px-tile").count()) === 0 && /No photos match/.test(await page.locator(".px-empty").innerText()), "nothing found says so");
+await page.keyboard.press("Escape");
+await page.waitForTimeout(400);
+ok((await field.inputValue()) === "" && (await page.locator(".px-tile").count()) === 5 && (await page.locator(".px-bar h1").innerText()) === "Library",
+ "Escape ends the search, back to the library");
+await field.fill("img_p3");
+await page.waitForTimeout(400);
+await page.locator(".px-source", { hasText: "Favorites" }).click();
+await page.waitForTimeout(300);
+ok((await field.inputValue()) === "" && (await page.locator(".px-bar h1").innerText()) === "Favorites", "choosing a view ends it too");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 230a4fc..b2f892c 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -372,6 +372,18 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (p) p.keywords = args.keywords;
return p;
}
+ case "photos_search": {
+ const months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
+ const words = args.query.toLowerCase().split(/\s+/).filter(Boolean);
+ return (window.__photos ?? [])
+ .filter((p) => !p.deleted && !p.hidden)
+ .filter((p) => {
+ const d = new Date(p.takenAt * 1000);
+ const hay = [p.filename, p.title, p.caption, ...(p.keywords ?? []), String(d.getFullYear()), months[d.getMonth()]].filter(Boolean).join(" ").toLowerCase();
+ return words.every((w) => hay.includes(w));
+ })
+ .sort((a, b) => b.takenAt - a.takenAt);
+ }
case "photo_set_date": {
(window.__dates ??= []).push(args);
const p = (window.__photos ?? []).find((x) => x.id === args.id);
diff --git a/check.sh b/check.sh
index 279c40b..9890ed3 100755
--- a/check.sh
+++ b/check.sh
@@ -70,6 +70,7 @@ step "filmstrip" node .uiverify/photos-strip.mjs
step "place & keywords" node .uiverify/photos-info.mjs
step "download options" node .uiverify/photos-download.mjs
step "adjust date" node .uiverify/photos-date.mjs
+step "photo search" node .uiverify/photos-search.mjs
step "notes delete" node .uiverify/notes-delete.mjs
step "empty today" node .uiverify/reminders-empty.mjs
step "calendar keys" node .uiverify/calendar-keys.mjs
@@ -123,6 +124,7 @@ step "webkit: filmstrip" env ENGINE=webkit node .uiverify/photos-strip.mjs
step "webkit: place & keywords" env ENGINE=webkit node .uiverify/photos-info.mjs
step "webkit: downloads" env ENGINE=webkit node .uiverify/photos-download.mjs
step "webkit: adjust date" env ENGINE=webkit node .uiverify/photos-date.mjs
+step "webkit: search" env ENGINE=webkit node .uiverify/photos-search.mjs
step "webkit: delete" env ENGINE=webkit node .uiverify/notes-delete.mjs
step "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjs
step "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjs
diff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rs
index b9421c4..c15bf34 100644
--- a/crates/quince-core/src/photos.rs
+++ b/crates/quince-core/src/photos.rs
@@ -256,6 +256,55 @@ impl Library {
Ok(rows.collect::<std::result::Result<_, _>>()?)
}
+ /// Photos found by what is typed, as Photos' search finds them: every word must match the
+ /// file's name, title, caption or a keyword, or the year or month it was taken ("2025",
+ /// "march"). Deleted and hidden photos are not searched. Newest first, at most `limit`.
+ pub fn search_photos(&self, query: &str, limit: usize) -> Result<Vec<Photo>> {
+ let words: Vec<String> = query
+ .split_whitespace()
+ .map(|w| w.to_lowercase())
+ .filter(|w| !w.is_empty())
+ .take(8)
+ .collect();
+ if words.is_empty() {
+ return Ok(Vec::new());
+ }
+ // One condition per word, each its own parameter: what is typed is never part of the SQL.
+ let one = "(LOWER(COALESCE(filename, '')) LIKE ?{n} ESCAPE '\\'
+ OR LOWER(COALESCE(title, '')) LIKE ?{n} ESCAPE '\\'
+ OR LOWER(COALESCE(caption, '')) LIKE ?{n} ESCAPE '\\'
+ OR LOWER(COALESCE(keywords, '')) LIKE ?{n} ESCAPE '\\'
+ OR strftime('%Y', taken_at, 'unixepoch', 'localtime') LIKE ?{n} ESCAPE '\\'
+ OR (CASE strftime('%m', taken_at, 'unixepoch', 'localtime')
+ WHEN '01' THEN 'january' WHEN '02' THEN 'february' WHEN '03' THEN 'march'
+ WHEN '04' THEN 'april' WHEN '05' THEN 'may' WHEN '06' THEN 'june'
+ WHEN '07' THEN 'july' WHEN '08' THEN 'august' WHEN '09' THEN 'september'
+ WHEN '10' THEN 'october' WHEN '11' THEN 'november' ELSE 'december' END)
+ LIKE ?{n} ESCAPE '\\')";
+ let conditions: Vec<String> = (1..=words.len())
+ .map(|n| one.replace("{n}", &n.to_string()))
+ .collect();
+ let sql = format!(
+ "SELECT {COLUMNS} FROM photos WHERE deleted = 0 AND hidden = 0 AND {}
+ ORDER BY taken_at DESC, id LIMIT {}",
+ conditions.join(" AND "),
+ limit.min(50_000)
+ );
+ let patterns: Vec<String> = words
+ .iter()
+ .map(|w| {
+ let escaped = w
+ .replace('\\', "\\\\")
+ .replace('%', "\\%")
+ .replace('_', "\\_");
+ format!("%{escaped}%")
+ })
+ .collect();
+ let mut stmt = self.conn.prepare(&sql)?;
+ let rows = stmt.query_map(rusqlite::params_from_iter(patterns.iter()), row_to_photo)?;
+ Ok(rows.collect::<std::result::Result<_, _>>()?)
+ }
+
/// Which photos a view holds, and in what order.
fn view_query(view: View) -> (&'static str, &'static str) {
match view {
@@ -606,6 +655,25 @@ mod tests {
for (view, n) in lib.photo_counts().unwrap() {
assert_eq!(n as usize, lib.photos(view).unwrap().len(), "{view:?}");
}
+ // Search finds by name and by month, every word, and leaves the hidden and deleted out.
+ let found = |q: &str| {
+ lib.search_photos(q, 100)
+ .unwrap()
+ .into_iter()
+ .map(|p| p.id)
+ .collect::<Vec<_>>()
+ };
+ assert_eq!(found("B.JPG"), ["b"]);
+ assert_eq!(
+ found("jpg january 1970"),
+ ["c", "b", "a"],
+ "every word, the newest first"
+ );
+ assert!(found("e.jpg").is_empty(), "the hidden one is not found");
+ assert!(
+ found("100%").is_empty(),
+ "what is typed is matched as text, never as a pattern"
+ );
assert_eq!(
ids(&lib, View::Hidden),
["e"],
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 385e0d7..83ab103 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -3788,6 +3788,7 @@ fn main() {
photos::photo_set_keywords,
photos::photo_open_map,
photos::photo_set_date,
+ photos::photos_search,
photos::photo_download,
note_table_add_row,
note_table_remove,
diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rs
index b32a0c0..a103d0f 100644
--- a/src-tauri/src/photos.rs
+++ b/src-tauri/src/photos.rs
@@ -251,6 +251,17 @@ pub async fn photos_albums(
.collect())
}
+/// Photos found by what is typed in the search field, from the library on this machine: every
+/// word in a name, title, caption, keyword, year or month.
+#[tauri::command]
+pub async fn photos_search(query: String, data: State<'_, Data>) -> UiResult<Vec<Photo>> {
+ data.0
+ .lock()
+ .await
+ .search_photos(&query, 20_000)
+ .map_err(|e| e.to_string())
+}
+
/// One album's photos, in its order.
#[tauri::command]
pub async fn photos_in_album(album: String, data: State<'_, Data>) -> UiResult<Vec<Photo>> {
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index 54778a1..e72a0d7 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -110,6 +110,8 @@ export const api = {
photoOpenMap: (id: string) => invoke<void>("photo_open_map", { id }),
/** When it was taken, in unix seconds. */
photoSetDate: (id: string, takenAt: number) => invoke<Photo>("photo_set_date", { id, takenAt }),
+ /** Every word in a name, title, caption, keyword, year or month; newest first. */
+ photosSearch: (query: string) => invoke<Photo[]>("photos_search", { query }),
/** Photos and videos (or folders of them) into the library. Answers the batch; progress
* arrives as PHOTO_UPLOAD events, in the same shape as Drive's. */
/** Into the library, and into `album` too when one is open. */
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index 2dfd3ef..84b1687 100644
--- a/src/screens/PhotosView.tsx
+++ b/src/screens/PhotosView.tsx
@@ -7,7 +7,7 @@ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useStat
import { listen } from "@tauri-apps/api/event";
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { open as openFileDialog } from "@tauri-apps/plugin-dialog";
-import { ChevronLeft, ChevronRight, CopyMinus, CopyPlus, Download, Clock, Heart, ImagePlus, Images, Info, Minus, Play, Plus, RotateCcw, Scan, Trash2, EyeOff, ArrowDownUp, MonitorPlay, Square, RectangleHorizontal, Star, Layers, Video, X, type LucideIcon } from "lucide-react";
+import { ChevronLeft, ChevronRight, CopyMinus, CopyPlus, Download, Clock, Heart, ImagePlus, Images, Info, Minus, Play, Plus, RotateCcw, Scan, Trash2, EyeOff, ArrowDownUp, MonitorPlay, Square, RectangleHorizontal, Star, Layers, Search as SearchIcon, Video, X, type LucideIcon } from "lucide-react";
import {
api,
messageOf,
@@ -366,9 +366,20 @@ export function PhotosView() {
// The view the photos on screen belong to. A view chosen changes the title, the months and
// the order only when its photos arrive, all with them — not a frame before, over the last
// view's photos.
- const [drawn, setDrawn] = useState<{ view: PhotoView; album: PhotoAlbum | null }>({ view, album });
+ const [drawn, setDrawn] = useState<{ view: PhotoView; album: PhotoAlbum | null; query: string }>({ view, album, query: "" });
+ // What is typed in the search field, and — a moment after the typing stops — what is searched.
+ const [query, setQuery] = useState("");
+ const [searching, setSearching] = useState("");
+ useEffect(() => {
+ const t = window.setTimeout(() => setSearching(query.trim()), 140);
+ return () => window.clearTimeout(t);
+ }, [query]);
+ const endSearch = () => {
+ setQuery("");
+ setSearching("");
+ };
const [sorts, setSorts] = useState(readSorts);
- const sortable = !drawn.album && drawn.view !== "recentlyDeleted" && drawn.view !== "rated";
+ const sortable = !drawn.query && !drawn.album && drawn.view !== "recentlyDeleted" && drawn.view !== "rated";
const sort = sortable ? (sorts[drawn.view] ?? defaultSort(drawn.view)) : null;
const chooseSort = (next: Sort) => {
setSorts((all) => {
@@ -395,18 +406,18 @@ export function PhotosView() {
const read = useCallback(async () => {
const mine = ++reads.current;
const [list, c, a] = await Promise.all([
- album ? api.photosInAlbum(album.id) : api.photosList(view),
+ searching ? api.photosSearch(searching) : album ? api.photosInAlbum(album.id) : api.photosList(view),
api.photosCounts(),
api.photosAlbums(),
]);
if (mine !== reads.current) return;
setPhotos(list);
- setDrawn({ view, album });
+ setDrawn({ view, album, query: searching });
setCounts(Object.fromEntries(c));
setAlbums(a);
// An album deleted elsewhere is not left open, empty.
if (album && !a.some(([x]) => x.id === album.id)) setAlbum(null);
- }, [view, album]);
+ }, [view, album, searching]);
useEffect(() => {
read().catch((e) => setError(messageOf(e)));
}, [read, revision]);
@@ -1420,7 +1431,9 @@ export function PhotosView() {
return () => window.removeEventListener("keydown", onKey);
}, []);
- const title = drawn.album
+ const title = drawn.query
+ ? `“${drawn.query}”`
+ : drawn.album
? (album?.id === drawn.album.id ? album.name : drawn.album.name)
: [...VIEWS, ...MEDIA, ...UTILITIES].find((v) => v.key === drawn.view)?.label ?? "Photos";
// A view arrives at its top, not wherever the last one was scrolled to.
@@ -1438,6 +1451,7 @@ export function PhotosView() {
setView(v.key);
setAlbum(null);
setAlbumsPage(false);
+ endSearch();
setOpen(null);
}}
>
@@ -1465,6 +1479,7 @@ export function PhotosView() {
aria-current={albumsPage}
onClick={() => {
setAlbumsPage(true);
+ endSearch();
setOpen(null);
}}
>
@@ -1492,6 +1507,7 @@ export function PhotosView() {
onClick={() => {
setAlbum(a);
setAlbumsPage(false);
+ endSearch();
setOpen(null);
}}
onDoubleClick={() => setNaming({ id: a.id, then: [], draft: a.name })}
@@ -1606,7 +1622,11 @@ export function PhotosView() {
{selected.length > 0 ? (
<p className="px-span px-picked">{pickedWords(selected)}</p>
) : (
- (here ?? span) && <p className="px-span">{here ?? span}</p>
+ drawn.query ? (
+ <p className="px-span">{photos?.length === 1 ? "1 Result" : `${(photos?.length ?? 0).toLocaleString()} Results`}</p>
+ ) : (
+ (here ?? span) && <p className="px-span">{here ?? span}</p>
+ )
)}
</div>
{view === "recentlyDeleted" && !album && photos && photos.length > 0 && (
@@ -1678,6 +1698,32 @@ export function PhotosView() {
<ImagePlus size={16} strokeWidth={1.9} aria-hidden="true" />
</button>
</div>
+ {/* Search, as icloud.com's toolbar has it: names, titles, captions, keywords, years and
+ months, from the library on this machine — nothing typed leaves it. */}
+ <label className="px-capsule px-search">
+ <SearchIcon size={15} strokeWidth={2} aria-hidden="true" />
+ <input
+ type="search"
+ aria-label="Search Photos"
+ placeholder="Search Photos"
+ value={query}
+ spellCheck={false}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ e.stopPropagation();
+ endSearch();
+ e.currentTarget.blur();
+ }
+ }}
+ />
+ {query && (
+ <button className="px-search-clear" aria-label="Clear Search" onClick={endSearch}>
+ <X size={11} strokeWidth={3} aria-hidden="true" />
+ </button>
+ )}
+ </label>
</header>
{error && (
@@ -1688,7 +1734,9 @@ export function PhotosView() {
{photos && photos.length === 0 && (
<p className="px-empty">
- {album
+ {drawn.query
+ ? `No photos match “${drawn.query}”. Search finds names, titles, captions, keywords, years and months.`
+ : album
? "This album is empty. Photos added to it on any device show here."
: view === "recentlyDeleted"
? "Nothing deleted. Photos you delete stay here for 30 days."
diff --git a/src/styles/photos.css b/src/styles/photos.css
index 1eb016a..c6f939b 100644
--- a/src/styles/photos.css
+++ b/src/styles/photos.css
@@ -840,3 +840,33 @@
.px-sheet-button.is-primary { background: var(--accent); color: #fff; }
.px-sheet-button.is-primary:hover:not(:disabled) { background: var(--accent-strong); }
.px-sheet-button:disabled { opacity: 0.45; }
+
+/* The search field, a capsule at the toolbar's end as icloud.com's. */
+.px-search { align-items: center; gap: 6px; width: 200px; padding: 0 10px; color: var(--text-2); cursor: text; }
+.px-search input {
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+ border: 0;
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+ font-size: var(--t-13);
+ outline: none;
+}
+.px-search input::-webkit-search-cancel-button { display: none; }
+.px-search input::placeholder { color: var(--text-3); }
+.px-search:focus-within { box-shadow: var(--glass-float), 0 0 0 3px var(--accent-ring); }
+.px-search-clear {
+ display: grid;
+ place-items: center;
+ width: 16px;
+ height: 16px;
+ padding: 0;
+ border: 0;
+ border-radius: 50%;
+ background: var(--text-3);
+ color: var(--sheet);
+ cursor: default;
+}
+@media (max-width: 1000px) { .px-search { width: 140px; } }