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: sort by Date Captured or Date Added, Newest or Oldest First

Yashwanth Kamireddia108da5fe4ab
diff --git a/.uiverify/photos-sort.mjs b/.uiverify/photos-sort.mjs
new file mode 100644
index 0000000..2b1af4c
--- /dev/null
+++ b/.uiverify/photos-sort.mjs
@@ -0,0 +1,41 @@
+// Sorting, as Photos offers it: Date Captured or Date Added, Newest or Oldest First, with a
+// check beside what is chosen; the months follow; each view keeps its own sort, and keeps it
+// after a reload. Recents is by date added from the first.
+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 order = () => page.locator(".px-tile").evaluateAll((t) => t.map((x) => x.dataset.id).join(","));
+const months = () => page.locator(".px-month-title").allInnerTexts();
+
+ok((await order()) === "p1,p2,p3,p4,p5", `Library starts newest taken first ${await order()}`);
+await page.getByRole("button", { name: "Sort" }).click();
+const checked = await page.locator('.row-menu [aria-checked="true"]').allInnerTexts();
+ok(checked.map((t) => t.replace("✓", "").trim()).join() === "Date Captured,Newest First", `the menu checks what is chosen ${JSON.stringify(checked)}`);
+await page.locator(".row-menu").getByText("Oldest First").click();
+await page.waitForTimeout(200);
+ok((await order()) === "p5,p4,p3,p2,p1", `Oldest First turns it round ${await order()}`);
+ok(/September/.test((await months())[0]), `and the months with it ${JSON.stringify(await months())}`);
+
+await page.locator(".px-source", { hasText: "Recents" }).click();
+await page.waitForTimeout(250);
+ok((await order()).startsWith("p4"), `Recents is by date added, newest first ${await order()}`);
+ok(/October/.test((await months())[0]), "with each photo under the month it was added");
+
+await page.reload({ waitUntil: "networkidle" });
+await openScreen(page, "Photos");
+await page.waitForTimeout(400);
+ok((await order()) === "p5,p4,p3,p2,p1", "Library keeps its sort after a reload");
+await page.locator(".px-source", { hasText: "Trips" }).click();
+await page.waitForTimeout(250);
+ok((await page.getByRole("button", { name: "Sort" }).count()) === 0, "an album keeps its own order, with no sort to choose");
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 6a97c38..bb65199 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -313,7 +313,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
favorite: false, hidden: false, deleted: false, deletedAt: null, subtype: 0, changeTag: null, ...extra });
const all = (window.__photos ??= [
P("p1", 1792500000, { favorite: true }), P("p2", 1792400000), P("p3", 1792300000, { kind: "video", duration: 12.4, uti: "public.mpeg-4", filename: "clip.mp4" }),
- P("p4", 1789900000), P("p5", 1789800000), P("p6", 1789700000, { deleted: true, deletedAt: 1792600000, expungeAt: Math.floor(Date.now() / 1000) + 2 * 86400 + 600 }),
+ P("p4", 1789900000, { addedAt: 1792700000 }), P("p5", 1789800000), P("p6", 1789700000, { deleted: true, deletedAt: 1792600000, expungeAt: Math.floor(Date.now() / 1000) + 2 * 86400 + 600 }),
]);
const live = all.filter((p) => !p.deleted && !p.hidden);
const views = {
diff --git a/check.sh b/check.sh
index 767c978..d25406e 100755
--- a/check.sh
+++ b/check.sh
@@ -59,6 +59,7 @@ step "photo albums" node .uiverify/photos-albums.mjs
step "photos at scale" node .uiverify/photos-scale.mjs
step "photos drag" node .uiverify/photos-drag.mjs
step "photos keys" node .uiverify/photos-keys.mjs
+step "photos sort" node .uiverify/photos-sort.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
@@ -101,6 +102,7 @@ step "webkit: albums" env ENGINE=webkit node .uiverify/photos-albums.mjs
step "webkit: at scale" env ENGINE=webkit node .uiverify/photos-scale.mjs
step "webkit: drag" env ENGINE=webkit node .uiverify/photos-drag.mjs
step "webkit: keys" env ENGINE=webkit node .uiverify/photos-keys.mjs
+step "webkit: sort" env ENGINE=webkit node .uiverify/photos-sort.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/src/components/RowMenu.tsx b/src/components/RowMenu.tsx
index 53f80b0..abfa9ab 100644
--- a/src/components/RowMenu.tsx
+++ b/src/components/RowMenu.tsx
@@ -6,7 +6,15 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react";
* of its own, opened beside it as macOS opens one; `keep` leaves the menu open after `run`.
*/
export type MenuEntry =
- | { label: string; run?: () => void; danger?: boolean; keep?: boolean; submenu?: MenuEntry[] }
+ | {
+ label: string;
+ run?: () => void;
+ danger?: boolean;
+ keep?: boolean;
+ submenu?: MenuEntry[];
+ /** A choice that is on or off: a check beside it when on, as a Mac menu marks one. */
+ checked?: boolean;
+ }
| null;
type Anchor = { x: number; y: number; alignRight: boolean };
@@ -94,6 +102,7 @@ function Panel({
const box = useRef<HTMLDivElement | null>(null);
const lines = useRef<(HTMLButtonElement | null)[]>([]);
const items = entries.filter((e): e is NonNullable<MenuEntry> => e !== null);
+ const checks = items.some((e) => e.checked !== undefined);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
// Nothing highlighted until the pointer or a key says so, as a Mac menu opens.
const [active, setActive] = useState(focusFirst ? 0 : -1);
@@ -193,7 +202,8 @@ function Panel({
ref={(el) => {
lines.current[index] = el;
}}
- role="menuitem"
+ role={entry.checked === undefined ? "menuitem" : "menuitemcheckbox"}
+ aria-checked={entry.checked}
tabIndex={-1}
aria-haspopup={entry.submenu ? "menu" : undefined}
aria-expanded={entry.submenu ? sub?.index === index : undefined}
@@ -213,6 +223,13 @@ function Panel({
}}
onClick={() => choose(index, false)}
>
+ {/* A menu with choices in it keeps the column for the check on every line, so
+ the words line up whether a line is checked or not. */}
+ {checks && (
+ <span className="row-menu-check" aria-hidden="true">
+ {entry.checked ? "✓" : ""}
+ </span>
+ )}
<span className="row-menu-label">{entry.label}</span>
{entry.submenu && <span className="row-menu-chevron" aria-hidden="true">›</span>}
</button>
diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsx
index 7a2e0bf..67b3431 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, 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, Video, X, type LucideIcon } from "lucide-react";
import {
api,
messageOf,
@@ -64,6 +64,21 @@ const pickedWords = (list: Photo[]) => {
type Flag = "favorite" | "deleted" | "hidden" | "expunged";
+/** How a view is sorted, as Photos offers it: by the date taken or the date added, either way. */
+type Sort = { by: "taken" | "added"; oldest: boolean };
+const SORTS_KEY = "quince.photos.sort";
+const defaultSort = (view: PhotoView): Sort => ({ by: view === "recents" ? "added" : "taken", oldest: false });
+const sortKey = (p: Photo, by: Sort["by"]) => (by === "added" ? (p.addedAt ?? p.takenAt) : p.takenAt);
+const sortList = (list: Photo[], s: Sort) =>
+ [...list].sort((a, b) => (sortKey(b, s.by) - sortKey(a, s.by)) * (s.oldest ? -1 : 1) || (a.id < b.id ? -1 : 1));
+const readSorts = (): Partial<Record<PhotoView, Sort>> => {
+ try {
+ return JSON.parse(window.localStorage.getItem(SORTS_KEY) ?? "{}") ?? {};
+ } catch {
+ return {};
+ }
+};
+
/**
* How long a photo in Recently Deleted has left, in Photos' words: "29 days left" (or, on a
* tile, "29 days"), then hours, then minutes; red under four days, as Photos turns it.
@@ -239,13 +254,35 @@ export function PhotosView() {
/** An album being named in the sidebar: a new one (with the photos to put in it), or a rename. */
const [naming, setNaming] = useState<{ id: string | null; then: string[]; draft: string } | null>(null);
+ // Each view keeps the sort chosen for it, on this machine. Albums keep their own order, and
+ // Recently Deleted its own, as in Photos.
+ const [sorts, setSorts] = useState(readSorts);
+ const sortable = !album && view !== "recentlyDeleted";
+ const sort = sortable ? (sorts[view] ?? defaultSort(view)) : null;
+ const sortRef = useRef(sort);
+ sortRef.current = sort;
+ const chooseSort = (next: Sort) => {
+ setSorts((all) => {
+ const was = { ...all, [view]: next };
+ try {
+ window.localStorage.setItem(SORTS_KEY, JSON.stringify(was));
+ } catch {
+ // Kept for this run only.
+ }
+ return was;
+ });
+ };
+ useEffect(() => {
+ if (sort) setPhotos((list) => (list ? sortList(list, sort) : list));
+ }, [sort?.by, sort?.oldest]); // eslint-disable-line react-hooks/exhaustive-deps
+
const read = useCallback(async () => {
const [list, c, a] = await Promise.all([
album ? api.photosInAlbum(album.id) : api.photosList(view),
api.photosCounts(),
api.photosAlbums(),
]);
- setPhotos(list);
+ setPhotos(sortRef.current ? sortList(list, sortRef.current) : list);
setCounts(Object.fromEntries(c));
setAlbums(a);
// An album deleted elsewhere is not left open, empty.
@@ -260,13 +297,13 @@ export function PhotosView() {
const out: { label: string; items: { photo: Photo; index: number }[] }[] = [];
if (album) return [{ label: "", items: (photos ?? []).map((photo, index) => ({ photo, index })) }];
(photos ?? []).forEach((photo, index) => {
- const label = monthOf(view === "recents" ? (photo.addedAt ?? photo.takenAt) : photo.takenAt);
+ const label = monthOf(sortKey(photo, sort?.by ?? "taken"));
const last = out[out.length - 1];
if (last && last.label === label) last.items.push({ photo, index });
else out.push({ label, items: [{ photo, index }] });
});
return out;
- }, [photos, view, album]);
+ }, [photos, sort?.by, album]);
const shown = open !== null ? photos?.[open] ?? null : null;
@@ -1209,6 +1246,31 @@ export function PhotosView() {
)}
</div>
)}
+ {sort && (
+ <div className="px-capsule">
+ <button
+ className="px-cap"
+ aria-label="Sort"
+ aria-haspopup="menu"
+ title="Sort"
+ onClick={(e) => {
+ const box = e.currentTarget.getBoundingClientRect();
+ setMenu({
+ at: { x: box.right, y: box.bottom + 6, alignRight: true },
+ entries: [
+ { label: "Date Captured", checked: sort.by === "taken", run: () => chooseSort({ ...sort, by: "taken" }) },
+ { label: "Date Added", checked: sort.by === "added", run: () => chooseSort({ ...sort, by: "added" }) },
+ null,
+ { label: "Newest First", checked: !sort.oldest, run: () => chooseSort({ ...sort, oldest: false }) },
+ { label: "Oldest First", checked: sort.oldest, run: () => chooseSort({ ...sort, oldest: true }) },
+ ],
+ });
+ }}
+ >
+ <ArrowDownUp size={16} strokeWidth={1.9} aria-hidden="true" />
+ </button>
+ </div>
+ )}
<div className="px-capsule" role="group" aria-label="Zoom">
<button className="px-cap" aria-label="Zoom Out" title="Zoom Out (Ctrl −)" disabled={zoom === 0} onClick={() => setZoom((z) => Math.max(0, z - 1))}>
<Minus size={15} strokeWidth={2.2} aria-hidden="true" />
diff --git a/src/styles/app.css b/src/styles/app.css
index 3c900d4..7ef05b3 100644
--- a/src/styles/app.css
+++ b/src/styles/app.css
@@ -1837,6 +1837,8 @@
font: inherit; font-size: var(--t-13); text-align: left; cursor: default; white-space: nowrap;
}
.row-menu-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
+/* The check column: a Mac menu marks a choice that is on with a check before its name. */
+.row-menu-check { flex: none; width: 12px; margin: 0 -6px 0 -4px; font-size: 12px; font-weight: 600; text-align: center; }
.row-menu-chevron { flex: none; margin-right: -4px; font-size: 15px; line-height: 1; color: var(--text-2); }
.row-menu-item.is-active { background: var(--sys-blue, #0a84ff); color: #fff; }
.row-menu-item.is-active .row-menu-chevron { color: #fff; }