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: folders and Portrait on screen; photos and videos kept on disk ahead of opening
Yashwanth Kamireddi22dba4477864
diff --git a/.uiverify/photos-albums.mjs b/.uiverify/photos-albums.mjsindex 1ff6135..7e0c17b 100644--- a/.uiverify/photos-albums.mjs+++ b/.uiverify/photos-albums.mjs@@ -21,7 +21,7 @@ const albumNames = () => page.locator(".px-albums .px-source").evaluateAll((els)// while the chevron only opens the list in the sidebar; a card opens its album.await page.locator(".px-parent", { hasText: "Albums" }).click();await page.waitForTimeout(200);-ok((await page.locator(".px-albums-head h1").innerText()) === "Albums" && (await page.locator(".px-albums-head .px-span").innerText()) === "1 Album",+ok((await page.locator(".px-albums-head h1").innerText()) === "Albums" && (await page.locator(".px-albums-head .px-span").innerText()) === "1 Item","Albums opens the Albums page");ok((await page.locator(".px-card").count()) === 1 && /Trips[\s\S]*2 items/.test(await page.locator(".px-card").innerText()),`each album a card with its name and count ${JSON.stringify(await page.locator(".px-card").innerText())}`);@@ -35,7 +35,8 @@ ok((await page.locator(".px-bar h1").innerText()) === "Trips" && (await page.locawait page.locator(".px-source", { hasText: "Library" }).first().click();await page.waitForTimeout(250);-await page.getByRole("button", { name: "New Album" }).click();+await page.locator(".px-side").getByRole("button", { name: "New Album" }).click();+await page.locator(".row-menu").getByText("New Album", { exact: true }).click();await page.getByLabel("Album name").fill("Beach");await page.keyboard.press("Enter");await page.waitForTimeout(250);@@ -93,10 +94,40 @@ await page.waitForTimeout(200);ok((await page.locator(".px").getAttribute("data-drop-label")) === "Add to Library", "in the library, Add to Library");await page.evaluate(() => window.__emit?.("quince://photo-upload", { id: "B1:0", batch: "B1", name: "ferry.jpg", within: "", folder: false, error: null, state: "cancelled", sent: 0, total: 1 }));await page.evaluate(() => { window.__albumFail = true; });-await page.getByRole("button", { name: "New Album" }).click();+await page.locator(".px-side").getByRole("button", { name: "New Album" }).click();+await page.locator(".row-menu").getByText("New Album", { exact: true }).click();await page.getByLabel("Album name").fill("Nope");await page.keyboard.press("Enter");await page.waitForTimeout(300);ok(!(await albumNames()).includes("Nope") && (await page.locator(".notice").count()) === 1, "an album iCloud refuses goes away again, and says why");++// Folders, as icloud.com has them: New Folder, named in place; an album made in it sits in it;+// the folder's page shows what it holds; deleting it takes what it holds with it.+await page.evaluate(() => { window.__albumFail = false; });+await page.locator(".px-side").getByRole("button", { name: "New Album" }).click();+await page.locator(".row-menu").getByText("New Folder", { exact: true }).click();+await page.getByLabel("Album name").fill("Holidays");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+const made = await page.evaluate(() => window.__albumCalls.filter((c) => c.cmd === "photos_album_create").at(-1).args);+ok(made.name === "Holidays" && made.folder === true, `New Folder makes a folder ${JSON.stringify(made)}`);+const folderRow = page.locator(".px-parent", { hasText: "Holidays" });+ok((await folderRow.count()) === 1, "and it stands in the sidebar as a folder");+await folderRow.click({ button: "right" });+await page.locator(".row-menu").getByText("New Album", { exact: true }).click();+await page.getByLabel("Album name").fill("Goa");+await page.keyboard.press("Enter");+await page.waitForTimeout(300);+const inner = await page.evaluate(() => window.__albumCalls.filter((c) => c.cmd === "photos_album_create").at(-1).args);+ok(inner.name === "Goa" && typeof inner.parent === "string" && inner.parent.startsWith("AL"), `an album made in it is made in it ${JSON.stringify(inner)}`);+await folderRow.click();+await page.waitForTimeout(250);+ok((await page.locator(".px-albums-head h1").innerText()) === "Holidays" && /Goa/.test(await page.locator(".px-cards").innerText()),+ "the folder's page shows what it holds");+await folderRow.click({ button: "right" });+await page.locator(".row-menu").getByText("Delete Folder").click();+await page.waitForTimeout(300);+ok((await page.locator(".px-parent", { hasText: "Holidays" }).count()) === 0 && (await page.locator(".px-source", { hasText: "Goa" }).count()) === 0,+ "deleting the folder takes what it holds with it");await b.close();process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/photos-real.mjs b/.uiverify/photos-real.mjsindex 1262eb9..f026ea3 100644--- a/.uiverify/photos-real.mjs+++ b/.uiverify/photos-real.mjs@@ -76,5 +76,12 @@ ok(/Panoramas\s*1/.test(await page.locator(".px-source", { hasText: "Panoramas"await page.locator(".px-source", { hasText: "Panoramas" }).click();await page.waitForTimeout(300);ok((await page.locator(".px-tile").evaluateAll((t) => t.map((x) => x.dataset.id).join())) === "p4", "holding the panorama");+// A Portrait (Apple's customRenderedValue 8) the same way.+await page.evaluate(() => { window.__photos.find((p) => p.id === "p2").rendered = 8; });+await page.locator(".px-source", { hasText: "Recents" }).first().click();+await page.waitForTimeout(300);+await page.locator(".px-source", { hasText: "Portrait" }).click();+await page.waitForTimeout(300);+ok((await page.locator(".px-tile").evaluateAll((t) => t.map((x) => x.dataset.id).join())) === "p2", "Portrait holds the portrait");await b.close();process.exitCode = failures ? 1 : (process.exitCode ?? 0);diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 7b176de..140a805 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -318,7 +318,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteconst live = all.filter((p) => !p.deleted && !p.hidden);const views = {library: live, recents: live, favorites: live.filter((p) => p.favorite), videos: live.filter((p) => p.kind === "video"),- screenshots: live.filter((p) => p.subtype === 3), panoramas: live.filter((p) => p.subtype === 1), recentlyDeleted: all.filter((p) => p.deleted),+ screenshots: live.filter((p) => p.subtype === 3), panoramas: live.filter((p) => p.subtype === 1), portrait: live.filter((p) => p.rendered === 8), recentlyDeleted: all.filter((p) => p.deleted),hidden: all.filter((p) => !p.deleted && p.hidden),rated: live.filter((p) => (p.rating ?? 0) > 0).sort((a, b) => b.rating - a.rating || b.takenAt - a.takenAt),};@@ -344,12 +344,20 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteconst albums = (window.__albums ??= [{ id: "AL1", name: "Trips", position: 0, changeTag: null, items: ["p4", "p2"] }]);const find = (id) => albums.find((x) => x.id === id);if (cmd === "photos_album_create") {- const made = { id: `AL${albums.length + 1}`, name: args.name, position: -1, changeTag: "t1" };+ const made = { id: `AL${albums.length + 1}`, name: args.name, position: -1, changeTag: "t1", folder: !!args.folder, parent: args.parent ?? null };albums.unshift({ ...made, items: [] });return made;}if (cmd === "photos_album_rename") find(args.id).name = args.name;- if (cmd === "photos_album_delete") albums.splice(albums.indexOf(find(args.id)), 1);+ if (cmd === "photos_album_delete") {+ // A folder goes with everything in it, as the app's own backend deletes it.+ const gone = new Set([args.id]);+ for (let grew = true; grew; ) {+ grew = false;+ for (const x of albums) if (x.parent && gone.has(x.parent) && !gone.has(x.id)) { gone.add(x.id); grew = true; }+ }+ for (let i = albums.length - 1; i >= 0; i--) if (gone.has(albums[i].id)) albums.splice(i, 1);+ }if (cmd === "photos_album_add") find(args.album).items.push(...args.ids.filter((i) => !find(args.album).items.includes(i)));if (cmd === "photos_album_remove") find(args.album).items = find(args.album).items.filter((i) => !args.ids.includes(i));return null;diff --git a/crates/quince-icloud/src/photos.rs b/crates/quince-icloud/src/photos.rsindex 22109c7..9c51de9 100644--- a/crates/quince-icloud/src/photos.rs+++ b/crates/quince-icloud/src/photos.rs@@ -689,6 +689,54 @@ pub async fn remove_from_album(Ok(())}+/// A file fetched from `url` to `path`, streamed: written to a part file of its own and moved+/// into place only once whole, so a large video is never held in memory and a half-written file+/// is never where a whole one is looked for. A refused fetch leaves nothing behind. Answers false+/// when Apple refused the link (so the caller may ask for a fresh one), true when it is there.+pub async fn fetch_to_file(+ http: &reqwest::Client,+ url: &str,+ path: &std::path::Path,+) -> Result<bool> {+ use futures_util::StreamExt;+ use tokio::io::AsyncWriteExt;+ let response =+ http.get(url).send().await.map_err(|e| {+ crate::Error::Protocol(format!("the picture could not be fetched: {e}"))+ })?;+ if !response.status().is_success() {+ return Ok(false);+ }+ if let Some(dir) = path.parent() {+ tokio::fs::create_dir_all(dir).await.ok();+ }+ let partial = path.with_extension(format!("{}.part", uuid::Uuid::new_v4().simple()));+ let mut out = tokio::fs::File::create(&partial)+ .await+ .map_err(|e| crate::Error::Protocol(e.to_string()))?;+ let mut body = response.bytes_stream();+ let written: std::result::Result<(), String> = async {+ while let Some(chunk) = body.next().await {+ out.write_all(&chunk.map_err(|e| e.to_string())?)+ .await+ .map_err(|e| e.to_string())?;+ }+ out.flush().await.map_err(|e| e.to_string())+ }+ .await;+ drop(out);+ if let Err(e) = written {+ tokio::fs::remove_file(&partial).await.ok();+ return Err(crate::Error::Protocol(format!(+ "the picture broke off: {e}"+ )));+ }+ tokio::fs::rename(&partial, path)+ .await+ .map_err(|e| crate::Error::Protocol(e.to_string()))?;+ Ok(true)+}+/// Which file a download takes, as icloud.com's Download Options offer them.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]#[serde(rename_all = "camelCase")]@@ -1113,4 +1161,54 @@ mod tests {"the folder deleted takes the album inside with it");}++ /// A picture fetched to disk arrives whole under its name, through a part file; a refused+ /// link leaves nothing, and says so, so a fresh link can be asked for.+ #[tokio::test]+ async fn pictures_are_fetched_whole_to_disk() {+ use wiremock::matchers::path;+ use wiremock::{Mock, MockServer, ResponseTemplate};+ let server = MockServer::start().await;+ let body: Vec<u8> = (0..3_000_000u32).map(|i| (i % 251) as u8).collect();+ Mock::given(path("/ok"))+ .respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone()))+ .mount(&server)+ .await;+ Mock::given(path("/gone"))+ .respond_with(ResponseTemplate::new(403))+ .mount(&server)+ .await;+ let dir =+ std::env::temp_dir().join(format!("quince-fetch-{}", uuid::Uuid::new_v4().simple()));+ let http = reqwest::Client::new();+ let target = dir.join("full").join("A1");+ assert!(+ fetch_to_file(&http, &format!("{}/ok", server.uri()), &target)+ .await+ .unwrap()+ );+ assert_eq!(+ std::fs::read(&target).unwrap(),+ body,+ "every byte, in order"+ );+ let other = dir.join("full").join("A2");+ assert!(+ !fetch_to_file(&http, &format!("{}/gone", server.uri()), &other)+ .await+ .unwrap()+ );+ assert!(!other.exists(), "a refused link leaves nothing");+ let leftovers: Vec<_> = std::fs::read_dir(dir.join("full"))+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| {+ e.path()+ .extension()+ .is_some_and(|x| x.to_string_lossy().ends_with("part"))+ })+ .collect();+ assert!(leftovers.is_empty(), "no part file left behind");+ std::fs::remove_dir_all(&dir).ok();+ }}diff --git a/probe/examples/photos_fetch_to_file.rs b/probe/examples/photos_fetch_to_file.rsnew file mode 100644index 0000000..84d8d17--- /dev/null+++ b/probe/examples/photos_fetch_to_file.rs@@ -0,0 +1,46 @@+//! Live, read-only: a photo's whole picture fetched to a file in a folder named on the command+//! line with Quince's own fetch_to_file, and compared with the same link fetched directly.+use anyhow::{anyhow, Result};+use quince_icloud::photos::{fetch_to_file, links_of, CONTAINER, ZONE};++#[tokio::main]+async fn main() -> Result<()> {+ let mut args = std::env::args().skip(1);+ let out = std::path::PathBuf::from(args.next().ok_or_else(|| anyhow!("out dir"))?);+ let id = args.next().ok_or_else(|| anyhow!("asset id"))?;+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");+ let mut client = quince_auth::Client::new(&dir)?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let ck = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ck"))?;+ let http = client.http().clone();+ let zc =+ quince_icloud::cloudkit::ZoneClient::new(&http, &ck, CONTAINER, client.service_params());+ let a = zc+ .lookup_record(ZONE, &id)+ .await?+ .ok_or_else(|| anyhow!("gone"))?;+ let m = a+ .pointer("/fields/masterRef/value/recordName")+ .and_then(|v| v.as_str())+ .ok_or_else(|| anyhow!("no master"))?;+ let master = zc+ .lookup_record(ZONE, m)+ .await?+ .ok_or_else(|| anyhow!("no master"))?;+ let url = links_of(&master).full.ok_or_else(|| anyhow!("no full"))?;+ let target = out.join("full").join(&id);+ println!("fetched: {}", fetch_to_file(&http, &url, &target).await?);+ let direct = http.get(&url).send().await?.bytes().await?;+ let on_disk = std::fs::read(&target)?;+ println!(+ "{} bytes on disk, identical to a direct fetch: {}",+ on_disk.len(),+ on_disk == direct.as_ref()+ );+ Ok(())+}diff --git a/src-tauri/src/photos.rs b/src-tauri/src/photos.rsindex 1f94f72..c704572 100644--- a/src-tauri/src/photos.rs+++ b/src-tauri/src/photos.rs@@ -157,9 +157,17 @@ fn cache_path(app: &AppHandle, id: &str, size: Size) -> PathBuf {/// One picture of a photo: from the disk cache, or fetched from Apple once and kept.pub async fn picture(app: &AppHandle, id: &str, size: Size) -> Result<Vec<u8>, String> {+ let path = cached(app, id, size).await?;+ tokio::fs::read(&path).await.map_err(|e| e.to_string())+}++/// One picture (or video) of a photo in the disk cache, fetched from Apple once if it is not+/// there, and its path. Streamed to a part file and moved into place: a large video is never+/// held whole in memory, and a half-written file is never served.+pub async fn cached(app: &AppHandle, id: &str, size: Size) -> Result<PathBuf, String> {let path = cache_path(app, id, size);- if let Ok(bytes) = tokio::fs::read(&path).await {- return Ok(bytes);+ if tokio::fs::metadata(&path).await.is_ok() {+ return Ok(path);}let photo = {let data = app.state::<Data>();@@ -173,35 +181,73 @@ pub async fn picture(app: &AppHandle, id: &str, size: Size) -> Result<Vec<u8>, Slet (http, root, params) = crate::cloudkit_context(&auth).await?;// A cached link first; a fresh one from Apple when it has none or Apple refuses the old.let fetch = |url: String| {- let http = http.clone();+ let (http, path) = (http.clone(), path.clone());async move {- let r = http.get(&url).send().await.map_err(|e| e.to_string())?;- if !r.status().is_success() {- return Err(format!("Apple answered {}", r.status()));- }- r.bytes()+ quince_icloud::photos::fetch_to_file(&http, &url, &path).await- .map(|b| b.to_vec()).map_err(|e| e.to_string())}};- let cached = fresh_links(&photo.master).and_then(|l| size.pick(&l));- let bytes = match cached {- Some(url) => match fetch(url).await {- Ok(b) => b,- Err(_) => fetch(new_link(&http, &root, params, &photo, size).await?).await?,- },- None => fetch(new_link(&http, &root, params, &photo, size).await?).await?,+ let done = match fresh_links(&photo.master).and_then(|l| size.pick(&l)) {+ Some(url) => fetch(url).await.unwrap_or(false),+ None => false,};- if let Some(dir) = path.parent() {- tokio::fs::create_dir_all(dir).await.ok();+ if !done && !fetch(new_link(&http, &root, params, &photo, size).await?).await? {+ return Err("Apple did not send that picture.".into());}- // Written beside and moved into place, so a half-written picture is never served.- let partial = path.with_extension("part");- if tokio::fs::write(&partial, &bytes).await.is_ok() {- tokio::fs::rename(&partial, &path).await.ok();+ Ok(path)+}++/// Keeps the newest photos' whole pictures, and videos, on disk ahead of being opened — as+/// Photos on a Mac keeps originals — so a photo opens at full quality and a video plays at once,+/// never waiting on the network. Newest first, two at a time, at most 600 and 3 GB a pass, after+/// each sync; one pass at a time; what is on disk already is skipped.+pub fn keep_ahead(app: AppHandle) {+ static RUNNING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);+ if RUNNING.swap(true, std::sync::atomic::Ordering::SeqCst) {+ return;}- Ok(bytes)+ tauri::async_runtime::spawn(async move {+ use futures_util::StreamExt;+ let newest = {+ let data = app.state::<Data>();+ let library = data.0.lock().await;+ library.photos(View::Library).unwrap_or_default()+ };+ let wanted: Vec<(String, Size)> = newest+ .into_iter()+ .take(600)+ .map(|p| {+ let size = if p.kind == quince_core::photos::Kind::Video {+ Size::Original+ } else {+ Size::Full+ };+ (p.id, size)+ })+ .filter(|(id, size)| !cache_path(&app, id, *size).exists())+ .collect();+ let budget = std::sync::atomic::AtomicU64::new(3 * 1024 * 1024 * 1024);+ futures_util::stream::iter(wanted)+ .for_each_concurrent(2, |(id, size)| {+ let (app, budget) = (app.clone(), &budget);+ async move {+ if budget.load(std::sync::atomic::Ordering::Relaxed) == 0 {+ return;+ }+ if let Ok(path) = cached(&app, &id, size).await {+ let len = tokio::fs::metadata(&path).await.map_or(0, |m| m.len());+ let _ = budget.fetch_update(+ std::sync::atomic::Ordering::Relaxed,+ std::sync::atomic::Ordering::Relaxed,+ |b| Some(b.saturating_sub(len)),+ );+ }+ }+ })+ .await;+ RUNNING.store(false, std::sync::atomic::Ordering::SeqCst);+ });}async fn new_link(@@ -663,7 +709,7 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui} else {Size::Video};- let bytes = picture(&app, &id, size).await?;+ let source = cached(&app, &id, size).await?;let name = photo.filename.filter(|n| !n.contains('/') && !n.starts_with('.'))@@ -673,8 +719,11 @@ pub async fn photo_play(id: String, app: AppHandle, data: State<'_, Data>) -> Ui.await.map_err(|e| e.to_string())?;let path = dir.join(name);- if tokio::fs::metadata(&path).await.is_err() {- tokio::fs::write(&path, bytes)+ // Under its own name for the player, linked to the cached file rather than copied.+ if tokio::fs::metadata(&path).await.is_err()+ && tokio::fs::hard_link(&source, &path).await.is_err()+ {+ tokio::fs::copy(&source, &path).await.map_err(|e| e.to_string())?;}@@ -806,7 +855,8 @@ pub async fn photo_open_map(id: String, app: AppHandle, data: State<'_, Data>) -/// paused for a session coming back starts again.#[tauri::command]pub async fn photos_counts(app: AppHandle, data: State<'_, Data>) -> UiResult<Vec<(View, i64)>> {- work(app);+ work(app.clone());+ keep_ahead(app);data.0.lock().awaitdiff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 67d1e2c..be7789a 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -116,7 +116,9 @@ export const api = {* arrives as PHOTO_UPLOAD events, in the same shape as Drive's. *//** Into the library, and into `album` too when one is open. */photosUpload: (paths: string[], album?: string) => invoke<string>("photos_upload", { paths, album: album ?? null }),- photosAlbumCreate: (name: string) => invoke<PhotoAlbum>("photos_album_create", { name }),+ /** An album — or a folder — at the top or in the folder `parent`. */+ photosAlbumCreate: (name: string, parent?: string, folder?: boolean) =>+ invoke<PhotoAlbum>("photos_album_create", { name, parent: parent ?? null, folder: folder ?? false }),photosAlbumRename: (id: string, name: string) => invoke<void>("photos_album_rename", { id, name }),photosAlbumDelete: (id: string) => invoke<void>("photos_album_delete", { id }),photosAlbumAdd: (album: string, ids: string[]) => invoke<void>("photos_album_add", { album, ids }),@@ -571,9 +573,18 @@ export function pictureSrc(id: string, size: "thumb" | "medium" | "full" | "origreturn convertFileSrc(`pic/${id}/${size}`, "quince");}-export type PhotoAlbum = { id: string; name: string; position: number; changeTag: string | null };+export type PhotoAlbum = {+ id: string;+ name: string;+ position: number;+ changeTag: string | null;+ /** A folder of albums, not an album of photos. */+ folder?: boolean;+ /** The folder it sits in; none at the top. */+ parent?: string | null;+};-export type PhotoView = "library" | "favorites" | "videos" | "screenshots" | "panoramas" | "recents" | "hidden" | "rated" | "recentlyDeleted";+export type PhotoView = "library" | "favorites" | "videos" | "screenshots" | "panoramas" | "portrait" | "recents" | "hidden" | "rated" | "recentlyDeleted";export type Photo = {id: string;diff --git a/src/screens/PhotosView.tsx b/src/screens/PhotosView.tsxindex dc53688..273f09d 100644--- a/src/screens/PhotosView.tsx+++ b/src/screens/PhotosView.tsx@@ -7,7 +7,7 @@ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useStatimport { 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, Search as SearchIcon, 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, Folder as FolderIcon, Aperture, Video, X, type LucideIcon } from "lucide-react";import {api,messageOf,@@ -36,6 +36,7 @@ const VIEWS: { key: PhotoView; label: string; Icon: LucideIcon }[] = [/** Photos' Media Types: the library by what kind of picture each is. */const MEDIA: typeof VIEWS = [{ key: "videos", label: "Videos", Icon: Video },+ { key: "portrait", label: "Portrait", Icon: Aperture },{ key: "panoramas", label: "Panoramas", Icon: RectangleHorizontal },{ key: "screenshots", label: "Screenshots", Icon: Scan },];@@ -161,6 +162,8 @@ function Filmstrip({ photos, at, onPick }: { photos: Photo[]; at: number; onPick* cache (and on disk); this is only which are known to be ready.*/const decodedFull = new Set<string>();+/** The rest on a tile before its whole picture is fetched (see Tile). */+let resting: number | undefined;const warming = new Map<string, Promise<boolean>>();function warm(id: string): Promise<boolean> {if (decodedFull.has(id)) return Promise.resolve(true);@@ -233,6 +236,18 @@ const Tile = memo(function Tile({act.pick(index, e);}}onDoubleClick={() => act.open(index)}+ // A pointer that rests on a photo starts its whole picture on the way, so opening it is+ // instant: by the double-click it is decoded. Only after a moment's rest — passing over+ // the grid fetches nothing.+ onPointerEnter={() => {+ if (photo.kind === "video") return;+ window.clearTimeout(resting);+ resting = window.setTimeout(() => void warm(photo.id), 140);+ }}+ onPointerLeave={() => window.clearTimeout(resting)}+ onPointerDown={() => {+ if (photo.kind !== "video") void warm(photo.id);+ }}draggableonDragStart={(e) => act.drag(photo, e)}onDragEnd={act.dragEnd}@@ -390,7 +405,10 @@ export function PhotosView() {const [dropping, setDropping] = useState(false);const [menu, setMenu] = useState<{ at: { x: number; y: number; alignRight: boolean }; entries: MenuEntry[] } | null>(null);/** 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);+ const [naming, setNaming] = useState<{ id: string | null; then: string[]; draft: string; folder?: boolean; parent?: string | null } | null>(null);+ /** Folders open in the sidebar, and the folder whose page is showing (none: the top). */+ const [openFolders, setOpenFolders] = useState<Set<string>>(new Set());+ const [folderPage, setFolderPage] = useState<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.@@ -789,12 +807,12 @@ export function PhotosView() {* Albums, as Photos keeps them: every change shows at once and goes to iCloud behind it; a* refusal puts the list back and says why. A new album sorts first, as Photos puts it.*/- const createAlbum = async (name: string, then: string[]) => {+ const createAlbum = async (name: string, then: string[], folder = false, parent: string | null = null) => {const before = albums;- const temp: PhotoAlbum = { id: `new:${Date.now()}`, name, position: -1, changeTag: null };+ const temp: PhotoAlbum = { id: `new:${Date.now()}`, name, position: -1, changeTag: null, folder, parent };setAlbums((list) => [[temp, then.length], ...list]);try {- const made = await api.photosAlbumCreate(name);+ const made = await api.photosAlbumCreate(name, parent ?? undefined, folder);setAlbums((list) => list.map((x) => (x[0].id === temp.id ? [made, x[1]] : x)));if (then.length) await api.photosAlbumAdd(made.id, then);read().catch(() => {});@@ -819,9 +837,25 @@ export function PhotosView() {};const deleteAlbum = async (a: PhotoAlbum) => {- if (!window.confirm(`Delete the album “${a.name}”?\n\nThe photos in it stay in your library.`)) return;+ // A folder, in icloud.com's words: it goes with every album in it.+ const words = a.folder+ ? `Delete the folder “${a.name}”?\n\nThis will also delete all albums inside this folder. The photos in them stay in your library.`+ : `Delete the album “${a.name}”?\n\nThe photos in it stay in your library.`;+ if (!window.confirm(words)) return;const before = albums;- setAlbums((list) => list.filter((x) => x[0].id !== a.id));+ // Everything under a folder goes with it, here as on iCloud.+ const gone = new Set([a.id]);+ for (let grew = true; grew; ) {+ grew = false;+ for (const [x] of albums) {+ if (x.parent && gone.has(x.parent) && !gone.has(x.id)) {+ gone.add(x.id);+ grew = true;+ }+ }+ }+ setAlbums((list) => list.filter((x) => !gone.has(x[0].id)));+ if (folderPage && gone.has(folderPage)) setFolderPage(a.parent ?? null);if (album?.id === a.id) setAlbum(null);try {await api.photosAlbumDelete(a.id);@@ -1011,7 +1045,7 @@ export function PhotosView() {};const albumEntries = (ids: string[]): MenuEntry[] => [- ...albums.filter(([a]) => a.id !== album?.id && !a.id.startsWith("new:")).map(([a]) => ({ label: a.name, run: () => void addTo(a, ids) })),+ ...albums.filter(([a]) => !a.folder && a.id !== album?.id && !a.id.startsWith("new:")).map(([a]) => ({ label: a.name, run: () => void addTo(a, ids) })),...(albums.length ? [null] : []),{ label: "New Album…", run: () => setNaming({ id: null, then: ids, draft: "" }) },];@@ -1113,7 +1147,7 @@ export function PhotosView() {window.setTimeout(() => ghost.remove(), 0);}};- const dropTarget = (a: PhotoAlbum) => ({+ const dropTarget = (a: PhotoAlbum) => (a.folder ? {} : {onDragOver: (e: React.DragEvent) => {if (!dragging2.current || a.id.startsWith("new:") || album?.id === a.id) return;e.preventDefault();@@ -1166,7 +1200,7 @@ export function PhotosView() {const name = naming.draft.trim();setNaming(null);if (!name) return;- if (naming.id === null) void createAlbum(name, naming.then);+ if (naming.id === null) void createAlbum(name, naming.then, naming.folder ?? false, naming.parent ?? null);else {const a = albums.find(([x]) => x.id === naming.id)?.[0];if (a) void renameAlbum(a, name);@@ -1471,6 +1505,129 @@ export function PhotosView() {}, [drawn]);const across = ACROSS[zoom];+ // A new album or folder, at the top or in a folder: named in place in the sidebar.+ const startNew = (parent: string | null, folder: boolean) => {+ if (!branches.albums) branch("albums");+ if (parent) setOpenFolders((open) => new Set(open).add(parent));+ setNaming({ id: null, then: [], draft: "", folder, parent });+ };+ const newIn = (parent: string | null, at: { x: number; y: number; alignRight: boolean }) =>+ setMenu({+ at,+ entries: [+ { label: "New Album", run: () => startNew(parent, false) },+ { label: "New Folder", run: () => startNew(parent, true) },+ ],+ });+ const openFolder = (id: string | null) => {+ setAlbumsPage(true);+ setFolderPage(id);+ endSearch();+ setOpen(null);+ };++ /** The albums and folders in one folder (or at the top), folders open to theirs, nested. */+ const albumRows = (parent: string | null, depth: number): React.ReactNode[] => {+ const rows: React.ReactNode[] = [];+ const indent = { "--depth": depth } as React.CSSProperties;+ if (naming?.id === null && (naming.parent ?? null) === parent) {+ rows.push(<span key="new" className="px-depth" style={indent}>{nameField}</span>);+ }+ for (const [a, n, cover] of albums) {+ if ((a.parent ?? null) !== parent) continue;+ if (naming?.id === a.id) {+ rows.push(<span key={a.id} className="px-depth" style={indent}>{nameField}</span>);+ continue;+ }+ if (a.folder) {+ const isOpen = openFolders.has(a.id);+ rows.push(+ <div key={a.id} className="px-parent-row px-depth" style={indent}>+ <button+ className="px-twisty"+ aria-label={isOpen ? `Hide ${a.name}` : `Show ${a.name}`}+ aria-expanded={isOpen}+ onClick={() =>+ setOpenFolders((open) => {+ const next = new Set(open);+ if (next.has(a.id)) next.delete(a.id);+ else next.add(a.id);+ return next;+ })+ }+ >+ <ChevronRight className="px-chevron" size={12} strokeWidth={2.4} aria-hidden="true" />+ </button>+ <button+ className="px-source px-parent"+ aria-current={albumsPage && folderPage === a.id}+ onClick={() => openFolder(a.id)}+ onDoubleClick={() => setNaming({ id: a.id, then: [], draft: a.name })}+ onContextMenu={(e) => {+ e.preventDefault();+ if (a.id.startsWith("new:")) return;+ setMenu({+ at: { x: e.clientX, y: e.clientY, alignRight: false },+ entries: [+ { label: "New Album", run: () => startNew(a.id, false) },+ { label: "New Folder", run: () => startNew(a.id, true) },+ null,+ { label: "Rename Folder", run: () => setNaming({ id: a.id, then: [], draft: a.name }) },+ null,+ { label: "Delete Folder", danger: true, run: () => void deleteAlbum(a) },+ ],+ });+ }}+ >+ <FolderIcon size={16} strokeWidth={1.8} className="px-glyph" aria-hidden="true" />+ <span className="px-label">{a.name}</span>+ </button>+ </div>,+ );+ if (isOpen) rows.push(...albumRows(a.id, depth + 1));+ continue;+ }+ rows.push(+ <button+ key={a.id}+ className="px-source px-depth"+ style={indent}+ aria-current={!albumsPage && album?.id === a.id}+ onClick={() => {+ setAlbum(a);+ setAlbumsPage(false);+ endSearch();+ 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;+ setMenu({+ at: { x: e.clientX, y: e.clientY, alignRight: false },+ entries: [+ { label: "Rename Album", run: () => setNaming({ id: a.id, then: [], draft: a.name }) },+ null,+ { label: "Delete Album", danger: true, run: () => void deleteAlbum(a) },+ ],+ });+ }}+ >+ {cover ? (+ <img className="px-cover" src={pictureSrc(cover, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />+ ) : (+ <AlbumGlyph />+ )}+ <span className="px-label">{a.name}</span>+ {n ? <span className="px-count">{n}</span> : null}+ </button>,+ );+ }+ return rows;+ };+const source = (v: (typeof VIEWS)[number]) => (<buttonkey={v.key}@@ -1505,9 +1662,10 @@ export function PhotosView() {</button><buttonclassName="px-source px-parent"- aria-current={albumsPage}+ aria-current={albumsPage && folderPage === null}onClick={() => {setAlbumsPage(true);+ setFolderPage(null);endSearch();setOpen(null);}}@@ -1515,56 +1673,16 @@ export function PhotosView() {<AlbumGlyph /><span className="px-label">Albums</span></button>- <button className="px-side-add" aria-label="New Album" title="New Album" onClick={() => {- if (!branches.albums) branch("albums");- setNaming({ id: null, then: [], draft: "" });+ <button className="px-side-add" aria-label="New Album" title="New Album or Folder" aria-haspopup="menu" onClick={(e) => {+ const b = e.currentTarget.getBoundingClientRect();+ newIn(null, { x: b.left, y: b.bottom + 4, alignRight: false });}}><Plus size={14} strokeWidth={2} aria-hidden="true" /></button></div>{branches.albums && (<div className="px-albums px-children" role="group" aria-label="Albums">- {naming?.id === null && nameField}- {albums.map(([a, n, cover]) =>- naming?.id === a.id ? (- <span key={a.id}>{nameField}</span>- ) : (- <button- key={a.id}- className="px-source"- aria-current={!albumsPage && album?.id === a.id}- onClick={() => {- setAlbum(a);- setAlbumsPage(false);- endSearch();- 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;- setMenu({- at: { x: e.clientX, y: e.clientY, alignRight: false },- entries: [- { label: "Rename Album", run: () => setNaming({ id: a.id, then: [], draft: a.name }) },- null,- { label: "Delete Album", danger: true, run: () => void deleteAlbum(a) },- ],- });- }}- >- {cover ? (- <img className="px-cover" src={pictureSrc(cover, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />- ) : (- <AlbumGlyph />- )}- <span className="px-label">{a.name}</span>- {n ? <span className="px-count">{n}</span> : null}- </button>- ),- )}+ {albumRows(null, 0)}</div>)}<button className="px-source px-parent" aria-expanded={branches.media} onClick={() => branch("media")}>@@ -1584,64 +1702,96 @@ export function PhotosView() {<section className="px-main" aria-label={albumsPage ? "Albums" : title} data-page={albumsPage ? "albums" : undefined}>{albumsPage && (<div className="px-albums-page">- <header className="px-albums-head">- <div className="px-heading">- <h1>Albums</h1>- <p className="px-span">{albums.length === 1 ? "1 Album" : `${albums.length} Albums`}</p>- </div>- <div className="px-capsule">- <button className="px-cap" aria-label="New Album" title="New Album" onClick={() => {- if (!branches.albums) branch("albums");- setNaming({ id: null, then: [], draft: "" });- }}>- <Plus size={16} strokeWidth={2} aria-hidden="true" />- </button>- </div>- </header>- {albums.length === 0 ? (- <p className="px-empty">No albums yet. Make one with +, then add photos to it from their menu or by dragging them onto it.</p>- ) : (- <div className="px-cards" role="list">- {albums.map(([a, n, cover]) => (- <button- key={a.id}- role="listitem"- className="px-card"- onClick={() => {- setAlbum(a);- setAlbumsPage(false);- }}- {...dropTarget(a)}- data-drop={dropOn === a.id || undefined}- onContextMenu={(e) => {- e.preventDefault();- if (a.id.startsWith("new:")) return;- setMenu({- at: { x: e.clientX, y: e.clientY, alignRight: false },- entries: [- { label: "Rename Album", run: () => {- if (!branches.albums) branch("albums");- setNaming({ id: a.id, then: [], draft: a.name });- } },- null,- { label: "Delete Album", danger: true, run: () => void deleteAlbum(a) },- ],- });- }}- >- <span className="px-card-pic">- {cover ? (- <img src={pictureSrc(cover, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />- ) : (- <AlbumGlyph />- )}- </span>- <span className="px-card-name">{a.name}</span>- <span className="px-card-count">{n === 1 ? "1 item" : `${n} items`}</span>- </button>- ))}- </div>- )}+ {(() => {+ // This page's level: the top, or a folder's own albums and folders.+ const here = albums.filter(([a]) => (a.parent ?? null) === folderPage);+ const folder = folderPage ? albums.find(([a]) => a.id === folderPage)?.[0] : undefined;+ const held = (id: string) => albums.filter(([a]) => a.parent === id).length;+ return (+ <>+ <header className="px-albums-head">+ {folder && (+ <div className="px-capsule">+ <button className="px-cap" aria-label="Back" title="Back" onClick={() => openFolder(folder.parent ?? null)}>+ <ChevronLeft size={17} strokeWidth={2} aria-hidden="true" />+ </button>+ </div>+ )}+ <div className="px-heading">+ <h1>{folder ? folder.name : "Albums"}</h1>+ <p className="px-span">{here.length === 1 ? "1 Item" : `${here.length} Items`}</p>+ </div>+ <div className="px-capsule">+ <button+ className="px-cap"+ aria-label="New Album or Folder"+ title="New Album or Folder"+ aria-haspopup="menu"+ onClick={(e) => {+ const b = e.currentTarget.getBoundingClientRect();+ newIn(folderPage, { x: b.right, y: b.bottom + 6, alignRight: true });+ }}+ >+ <Plus size={16} strokeWidth={2} aria-hidden="true" />+ </button>+ </div>+ </header>+ {here.length === 0 ? (+ <p className="px-empty">+ {folder ? "This folder is empty. Make an album in it with +." : "No albums yet. Make one with +, then add photos to it from their menu or by dragging them onto it."}+ </p>+ ) : (+ <div className="px-cards" role="list">+ {here.map(([a, n, cover]) => (+ <button+ key={a.id}+ role="listitem"+ className={`px-card${a.folder ? " is-folder" : ""}`}+ onClick={() => {+ if (a.folder) return openFolder(a.id);+ setAlbum(a);+ setAlbumsPage(false);+ }}+ {...dropTarget(a)}+ data-drop={dropOn === a.id || undefined}+ onContextMenu={(e) => {+ e.preventDefault();+ if (a.id.startsWith("new:")) return;+ const kind = a.folder ? "Folder" : "Album";+ setMenu({+ at: { x: e.clientX, y: e.clientY, alignRight: false },+ entries: [+ { label: `Rename ${kind}`, run: () => {+ if (!branches.albums) branch("albums");+ if (a.parent) setOpenFolders((open) => new Set(open).add(a.parent!));+ setNaming({ id: a.id, then: [], draft: a.name });+ } },+ null,+ { label: `Delete ${kind}`, danger: true, run: () => void deleteAlbum(a) },+ ],+ });+ }}+ >+ <span className="px-card-pic">+ {a.folder ? (+ <FolderIcon className="px-glyph" size={44} strokeWidth={1.4} aria-hidden="true" />+ ) : cover ? (+ <img src={pictureSrc(cover, "thumb")} alt="" loading="lazy" decoding="async" draggable={false} />+ ) : (+ <AlbumGlyph />+ )}+ </span>+ <span className="px-card-name">{a.name}</span>+ <span className="px-card-count">+ {a.folder ? (held(a.id) === 1 ? "1 album" : `${held(a.id)} albums`) : n === 1 ? "1 item" : `${n} items`}+ </span>+ </button>+ ))}+ </div>+ )}+ </>+ );+ })()}</div>)}{/* As in Photos on macOS 26: the title and the controls float over the library, whichdiff --git a/src/styles/photos.css b/src/styles/photos.cssindex c6f939b..6d4d066 100644--- a/src/styles/photos.css+++ b/src/styles/photos.css@@ -870,3 +870,10 @@cursor: default;}@media (max-width: 1000px) { .px-search { width: 140px; } }++/* Folders nest: each level a step in, as the Mac sidebar steps them. */+.px-albums .px-depth.px-source,+.px-albums .px-depth .px-naming { padding-left: calc(30px + var(--depth, 0) * 14px); }+.px-albums .px-parent-row.px-depth .px-twisty { left: calc(10px + var(--depth, 0) * 14px); }+.px-albums .px-parent-row.px-depth .px-parent { padding-left: calc(30px + var(--depth, 0) * 14px); }+.px-card.is-folder .px-card-pic { color: var(--accent); }