Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Photos: drag photos onto an album; icloud.com's keys; counts from SQL
Yashwanth Kamireddi267167393de7
diff --git a/.uiverify/photos-drag.mjs b/.uiverify/photos-drag.mjsnew file mode 100644index 0000000..8158c5b--- /dev/null+++ b/.uiverify/photos-drag.mjs@@ -0,0 +1,44 @@+// Photos dragged onto an album in the sidebar go into it, as on a Mac: one photo, or the+// whole selection when the dragged photo is part of it. The album lights while over it; its+// count rises at once; the album being shown is not somewhere to drop.+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 trips = page.locator(".px-albums .px-source", { hasText: "Trips" });+const adds = () => page.evaluate(() => (window.__albumCalls ?? []).filter((c) => c.cmd === "photos_album_add").map((c) => c.args.ids));++await page.locator(".px-tile").nth(0).dragTo(trips);+await page.waitForTimeout(300);+ok(JSON.stringify((await adds()).at(-1)) === JSON.stringify(["p1"]), `one photo dragged onto an album goes into it ${JSON.stringify((await adds()).at(-1))}`);+ok(/3/.test(await trips.innerText()), "and the album's count rises at once");++await page.locator(".px-tile").nth(2).click();+await page.locator(".px-tile").nth(4).click({ modifiers: ["Control"] });+await page.locator(".px-tile").nth(4).dragTo(trips);+await page.waitForTimeout(300);+ok(JSON.stringify((await adds()).at(-1)) === JSON.stringify(["p3", "p5"]), `a selection dragged goes in whole ${JSON.stringify((await adds()).at(-1))}`);++// Over it, the album lights; dragging within the album shown, its own row does not.+const tile = await page.locator(".px-tile").nth(1).boundingBox();+const row = await trips.boundingBox();+await page.mouse.move(tile.x + 20, tile.y + 20);+await page.mouse.down();+await page.mouse.move(row.x + 30, row.y + row.height / 2, { steps: 8 });+await page.waitForTimeout(100);+const lit = await trips.getAttribute("data-drop");+await page.mouse.up();+ok(lit !== null, "the album lights while photos are over it");+await page.waitForTimeout(200);+ok((await trips.getAttribute("data-drop")) === null, "and is plain again after");+ok((await page.locator(".px.is-dropping").count()) === 0, "a drag from the library is not taken for files arriving");+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/photos-keys.mjs b/.uiverify/photos-keys.mjsnew file mode 100644index 0000000..c33f261--- /dev/null+++ b/.uiverify/photos-keys.mjs@@ -0,0 +1,50 @@+// The keys icloud.com's Photos takes, beyond the arrows: F (as well as "."), H to hide, = and −+// for the thumbnails, I for the details; in a photo, Z to zoom and Ctrl+"." to close.+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; });+page.on("dialog", (d) => void d.accept());+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 across = () => page.locator(".px-grid").first().evaluate((g) => getComputedStyle(g).gridTemplateColumns.split(" ").length);++await page.locator(".px-tile").nth(1).click();+await page.keyboard.press("f");+await page.waitForTimeout(200);+ok((await page.evaluate(() => window.__flags.at(-1))).flag === "favorite", "F favorites the selected photo");++const before = await across();+await page.keyboard.press("=");+await page.waitForTimeout(100);+ok((await across()) < before, `= makes the thumbnails bigger ${before} → ${await across()}`);+await page.keyboard.press("-");+await page.waitForTimeout(100);+ok((await across()) === before, "and − back");++await page.keyboard.press("i");+await page.waitForTimeout(600);+ok((await page.locator(".px-viewer").count()) === 1 && (await page.locator(".px-info").count()) === 1, "I opens the photo with its details");+await page.keyboard.press("z");+await page.waitForTimeout(150);+const k = await page.locator(".px-pan").evaluate((el) => new DOMMatrix(getComputedStyle(el).transform).a);+ok(k > 2, `Z zooms in ×${k.toFixed(2)}`);+await page.keyboard.press("z");+await page.waitForTimeout(150);+ok((await page.locator(".px-pan").evaluate((el) => new DOMMatrix(getComputedStyle(el).transform).a)) === 1, "and Z again fits it");+await page.keyboard.press("Control+.");+await page.waitForTimeout(650);+ok((await page.locator(".px-viewer").count()) === 0, 'Ctrl+"." closes the photo');++await page.locator(".px-tile").nth(3).click();+await page.keyboard.press("h");+await page.waitForTimeout(300);+ok((await page.evaluate(() => window.__flags.at(-1))).flag === "hidden" && (await page.locator(".px-tile").count()) === 4, "H hides it, asked first");+await b.close();+process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/check.sh b/check.shindex 3654150..767c978 100755--- a/check.sh+++ b/check.sh@@ -57,6 +57,8 @@ step "reminder ticks" node .uiverify/reminders-tick.mjsstep "photos" node .uiverify/photos.mjsstep "photo albums" node .uiverify/photos-albums.mjsstep "photos at scale" node .uiverify/photos-scale.mjs+step "photos drag" node .uiverify/photos-drag.mjs+step "photos keys" node .uiverify/photos-keys.mjsstep "notes delete" node .uiverify/notes-delete.mjsstep "empty today" node .uiverify/reminders-empty.mjsstep "calendar keys" node .uiverify/calendar-keys.mjs@@ -97,6 +99,8 @@ step "webkit: ticks" env ENGINE=webkit node .uiverify/reminders-tick.mjsstep "webkit: photos" env ENGINE=webkit node .uiverify/photos.mjsstep "webkit: albums" env ENGINE=webkit node .uiverify/photos-albums.mjsstep "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.mjsstep "webkit: delete" env ENGINE=webkit node .uiverify/notes-delete.mjsstep "webkit: row hover" env ENGINE=webkit node .uiverify/row-hover.mjsstep "webkit: fold" env ENGINE=webkit node .uiverify/sidebar-fold.mjsdiff --git a/crates/quince-core/src/photos.rs b/crates/quince-core/src/photos.rsindex dff8034..4a832c3 100644--- a/crates/quince-core/src/photos.rs+++ b/crates/quince-core/src/photos.rs@@ -204,7 +204,17 @@ impl Library {/// A view's photos, newest first.pub fn photos(&self, view: View) -> Result<Vec<Photo>> {- let (filter, order) = match view {+ let (filter, order) = Self::view_query(view);+ let mut stmt = self.conn.prepare(&format!(+ "SELECT {COLUMNS} FROM photos WHERE {filter} ORDER BY {order}, id"+ ))?;+ let rows = stmt.query_map([], 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 {View::Library => ("deleted = 0 AND hidden = 0", "taken_at DESC"),View::Favorites => ("deleted = 0 AND hidden = 0 AND favorite = 1",@@ -224,12 +234,7 @@ impl Library {),View::Hidden => ("deleted = 0 AND hidden = 1", "taken_at DESC"),View::RecentlyDeleted => ("deleted = 1", "COALESCE(deleted_at, taken_at) DESC"),- };- let mut stmt = self.conn.prepare(&format!(- "SELECT {COLUMNS} FROM photos WHERE {filter} ORDER BY {order}, id"- ))?;- let rows = stmt.query_map([], row_to_photo)?;- Ok(rows.collect::<std::result::Result<_, _>>()?)+ }}/// One photo, by asset id, wherever it is (Recently Deleted and hidden included).@@ -252,7 +257,15 @@ impl Library {View::Hidden,View::RecentlyDeleted,] {- out.push((view, self.photos(view)?.len() as i64));+ // Counted where the rows are: a library of twenty thousand is not read seven times+ // over to say how many each view holds.+ let (filter, _) = Self::view_query(view);+ let n: i64 = self.conn.query_row(+ &format!("SELECT COUNT(*) FROM photos WHERE {filter}"),+ [],+ |r| r.get(0),+ )?;+ out.push((view, n));}Ok(out)}@@ -403,6 +416,29 @@ impl Library {Ok(())}+ /// Every album with how many photos it shows (deleted and hidden ones not counted), in+ /// the order the albums are listed.+ pub fn albums_counted(&self) -> Result<Vec<(Album, i64)>> {+ let mut stmt = self.conn.prepare(+ "SELECT a.id, a.name, a.position, a.change_tag,+ (SELECT COUNT(*) FROM photo_album_items i JOIN photos p ON p.id = i.asset+ WHERE i.album = a.id AND p.deleted = 0 AND p.hidden = 0)+ FROM photo_albums a ORDER BY a.position, a.name",+ )?;+ let rows = stmt.query_map([], |r| {+ Ok((+ Album {+ id: r.get(0)?,+ name: r.get(1)?,+ position: r.get(2)?,+ change_tag: r.get(3)?,+ },+ r.get(4)?,+ ))+ })?;+ Ok(rows.collect::<std::result::Result<_, _>>()?)+ }+/// Where the album's last photo sits, so what is added goes after it.pub fn album_last_position(&self, album: &str) -> Result<Option<i64>> {Ok(self.conn.query_row(@@ -480,6 +516,10 @@ mod tests {assert_eq!(ids(&lib, View::Favorites), ["b"]);assert_eq!(ids(&lib, View::Videos), ["c"]);assert_eq!(ids(&lib, View::RecentlyDeleted), ["d"]);+ // Each view's count is how many it shows; the sidebar never reads a view to count it.+ for (view, n) in lib.photo_counts().unwrap() {+ assert_eq!(n as usize, lib.photos(view).unwrap().len(), "{view:?}");+ }assert_eq!(ids(&lib, View::Hidden),["e"],@@ -504,6 +544,18 @@ mod tests {["a", "b"],"in position order, the deleted one not shown");+ lib.replace_albums(&[Album {+ id: "AL".into(),+ name: "Trip".into(),+ position: 0,+ change_tag: None,+ }])+ .unwrap();+ assert_eq!(+ lib.albums_counted().unwrap()[0].1,+ 2,+ "an album's count is what it shows"+ );lib.forget_album_items(&[("AL".into(), "a".into())]).unwrap();assert_eq!(lib.album_photos("AL").unwrap().len(), 1);diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex d61a5d4..e0a7034 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -190,18 +190,16 @@ pub async fn photos_list(view: View, data: State<'_, Data>) -> UiResult<Vec<Photpub async fn photos_albums(data: State<'_, Data>,) -> UiResult<Vec<(quince_core::photos::Album, usize)>> {- let library = data.0.lock().await;- let albums = library.albums().map_err(|e| e.to_string())?;- albums+ let counted = data+ .0+ .lock()+ .await+ .albums_counted()+ .map_err(|e| e.to_string())?;+ Ok(counted.into_iter()- .map(|a| {- let n = library- .album_photos(&a.id)- .map_err(|e| e.to_string())?- .len();- Ok((a, n))- })- .collect()+ .map(|(a, n)| (a, usize::try_from(n).unwrap_or(0)))+ .collect())}/// One album's photos, in its order.diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex 12be2d0..7a2e0bf 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -87,6 +87,8 @@ type Acts = {pick: (index: number, e: React.MouseEvent) => void;open: (index: number) => void;menu: (photo: Photo, e: React.MouseEvent) => void;+ drag: (photo: Photo, e: React.DragEvent) => void;+ dragEnd: () => void;};/**@@ -127,6 +129,9 @@ const Tile = memo(function Tile({act.pick(index, e);}}onDoubleClick={() => act.open(index)}+ draggable+ onDragStart={(e) => act.drag(photo, e)}+ onDragEnd={act.dragEnd}onContextMenu={(e) => {e.preventDefault();act.menu(photo, e);@@ -461,6 +466,13 @@ export function PhotosView() {else if (e.key === "ArrowLeft") step(-1);else if (e.key === "Escape" && lensRef.current.k > 1) unzoom();else if (e.key === "Escape") close();+ // Cmd/Ctrl + "." closes too, as icloud.com's one-up view does.+ else if ((e.ctrlKey || e.metaKey) && e.key === ".") close();+ // Z: fit, or the photo at full size about its middle.+ else if (e.key.toLowerCase() === "z" && !e.ctrlKey && !e.metaKey && current?.kind !== "video") {+ const box = pan.current?.getBoundingClientRect();+ if (box) zoomAt(lensRef.current.k > 1 ? 1 : 2.5, box.left + box.width / 2, box.top + box.height / 2);+ }else if ((e.ctrlKey || e.metaKey) && (e.key === "=" || e.key === "+" || e.key === "-" || e.key === "0") && current?.kind !== "video") {const box = pan.current?.getBoundingClientRect();if (!box) return;@@ -470,8 +482,9 @@ export function PhotosView() {else if (e.key === " " && current?.kind === "video") void play(current);else if (e.key.toLowerCase() === "i" && !e.metaKey && !e.ctrlKey) setInfo((v) => !v);// As in Photos: "." favorites, Delete sends it to Recently Deleted.- else if (e.key === "." && current && view !== "recentlyDeleted") void change(current, "favorite", !current.favorite);- else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "l" && current && view !== "recentlyDeleted") void change(current, "hidden", view !== "hidden");+ // F as well as ".", and H as well as Ctrl+L, as icloud.com takes them.+ else if ((e.key === "." || (e.key.toLowerCase() === "f" && !e.ctrlKey && !e.metaKey)) && current && view !== "recentlyDeleted") void change(current, "favorite", !current.favorite);+ else if (((e.ctrlKey || e.metaKey) ? e.key.toLowerCase() === "l" : e.key.toLowerCase() === "h") && current && view !== "recentlyDeleted") void change(current, "hidden", view !== "hidden");else if ((e.key === "Delete" || e.key === "Backspace") && current && album) void removeFrom([current]);else if ((e.key === "Delete" || e.key === "Backspace") && current && view !== "recentlyDeleted") void change(current, "deleted", true);else if ((e.key === "Delete" || e.key === "Backspace") && current && view === "recentlyDeleted" && !album) void change(current, "expunged", true);@@ -739,10 +752,17 @@ export function PhotosView() {if (album) void removeFrom(selected);else if (view !== "recentlyDeleted") void changeAll(selected, "deleted", true);else void changeAll(selected, "expunged", true);- } else if (ctrl && e.key.toLowerCase() === "l" && selected.length && view !== "recentlyDeleted") {+ } else if (!ctrl && (e.key === "=" || e.key === "+" || e.key === "-")) {+ // = and − size the thumbnails, as in icloud.com's grid.+ setZoom((z) => (e.key === "-" ? Math.max(0, z - 1) : Math.min(ACROSS.length - 1, z + 1)));+ } else if (!ctrl && e.key.toLowerCase() === "i" && selected.length) {+ // I: the selected photo, opened with its details.+ setInfo(true);+ openAt(list.indexOf(selected[0]));+ } else if ((ctrl ? e.key.toLowerCase() === "l" : e.key.toLowerCase() === "h") && selected.length && view !== "recentlyDeleted") {// ⌘L in Photos: hide, or in Hidden, unhide.void changeAll(selected, "hidden", view !== "hidden");- } else if (e.key === "." && selected.length && view !== "recentlyDeleted") {+ } else if ((e.key === "." || (!ctrl && e.key.toLowerCase() === "f")) && selected.length && view !== "recentlyDeleted") {// As Photos: if any is not a favorite, all become favorites; else all stop being.void changeAll(selected, "favorite", selected.some((p) => !p.favorite));} else return;@@ -817,13 +837,72 @@ export function PhotosView() {};// The tiles' handlers, one object for the life of the screen; each call reaches the newest.- const acts = useRef({ pick, openAt, photoMenu });- acts.current = { pick, openAt, photoMenu };+ /*+ * Dragging photos onto an album in the sidebar puts them in it, as on a Mac: what is dragged+ * is the photo, or the whole selection when the photo is part of it.+ */+ const dragging2 = useRef<string[] | null>(null);+ const [dropOn, setDropOn] = useState<string | null>(null);+ const dragFrom = (p: Photo, e: React.DragEvent) => {+ const ids = chosen.has(p.id) ? selected.map((x) => x.id) : [p.id];+ if (!chosen.has(p.id)) {+ setChosen(new Set([p.id]));+ anchor.current = photos?.findIndex((x) => x.id === p.id) ?? null;+ }+ dragging2.current = ids;+ e.dataTransfer.effectAllowed = "copy";+ e.dataTransfer.setData("application/x-quince-photos", ids.join(","));+ // A stack of photos with how many, as Photos drags them.+ const img = e.currentTarget.querySelector("img");+ if (img && typeof e.dataTransfer.setDragImage === "function") {+ const ghost = document.createElement("div");+ ghost.className = "px-ghost";+ const pic = img.cloneNode() as HTMLImageElement;+ ghost.appendChild(pic);+ if (ids.length > 1) {+ const n = document.createElement("span");+ n.textContent = String(ids.length);+ ghost.appendChild(n);+ }+ document.body.appendChild(ghost);+ e.dataTransfer.setDragImage(ghost, 36, 36);+ window.setTimeout(() => ghost.remove(), 0);+ }+ };+ const dropTarget = (a: PhotoAlbum) => ({+ onDragOver: (e: React.DragEvent) => {+ if (!dragging2.current || a.id.startsWith("new:") || album?.id === a.id) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = "copy";+ if (dropOn !== a.id) setDropOn(a.id);+ },+ onDragLeave: (e: React.DragEvent) => {+ // Passing over the row's own symbol or name is not leaving it.+ if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;+ setDropOn((d) => (d === a.id ? null : d));+ },+ onDrop: (e: React.DragEvent) => {+ const ids = dragging2.current;+ dragging2.current = null;+ setDropOn(null);+ if (!ids || a.id.startsWith("new:")) return;+ e.preventDefault();+ void addTo(a, ids);+ },+ });++ const acts = useRef({ pick, openAt, photoMenu, dragFrom });+ acts.current = { pick, openAt, photoMenu, dragFrom };const act = useMemo<Acts>(() => ({pick: (i, e) => acts.current.pick(i, e),open: (i) => acts.current.openAt(i),menu: (p, e) => acts.current.photoMenu(p, { x: e.clientX, y: e.clientY, alignRight: false }),+ drag: (p, e) => acts.current.dragFrom(p, e),+ dragEnd: () => {+ dragging2.current = null;+ setDropOn(null);+ },}),[],);@@ -947,6 +1026,8 @@ export function PhotosView() {try {void getCurrentWebview().onDragDropEvent((event) => {+ // Photos of the library's own being dragged to an album are not files arriving.+ if (dragging2.current) return;if (event.payload.type === "over") setDropping(true);else if (event.payload.type === "leave") setDropping(false);else if (event.payload.type === "drop") {@@ -1070,6 +1151,8 @@ export function PhotosView() {setOpen(null);}}onDoubleClick={() => setNaming({ id: a.id, then: [], draft: a.name })}+ {...dropTarget(a)}+ data-drop={dropOn === a.id || undefined}onContextMenu={(e) => {e.preventDefault();if (a.id.startsWith("new:")) return;diff --git a/src/styles/photos.css b/src/styles/photos.cssindex 826c298..a5b2e97 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -385,3 +385,22 @@color: #fff;}.px-video:hover .px-play { background: rgba(0, 0, 0, 0.65); }++/* An album under photos being dragged to it: lit, as a Mac sidebar lights a drop target. */+.px-source[data-drop] { background: var(--accent-tint); box-shadow: inset 0 0 0 2px var(--accent); }+/* What is dragged: the photo, with how many when it is more than one. */+.px-ghost { position: fixed; top: -200px; left: -200px; width: 72px; height: 72px; }+.px-ghost img { width: 72px; height: 72px; object-fit: cover; border-radius: 8px; box-shadow: 0 6px 18px rgba(0, 0, 0, 0.3); }+.px-ghost span {+ position: absolute;+ top: -6px;+ right: -6px;+ min-width: 22px;+ height: 22px;+ padding: 0 6px;+ border-radius: 11px;+ background: #ff3b30;+ color: #fff;+ font: 600 12px/22px system-ui, sans-serif;+ text-align: center;+}