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.

Drive window: a folder is deleted only as it was shown, a file only as its version shown

Yashwanth Kamireddi0900b8776089
diff --git a/.uiverify/drive-delete-changed.mjs b/.uiverify/drive-delete-changed.mjs
new file mode 100644
index 0000000..3bd1e0e
--- /dev/null
+++ b/.uiverify/drive-delete-changed.mjs
@@ -0,0 +1,57 @@
+// Drive delete of a folder that changed on another device since it was shown: not deleted
+// silently — asked, with what the folder holds now and what was added; kept on Cancel; on
+// "Delete Anyway" deleted as the version just shown. An unchanged folder asks nothing.
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub, openScreen } from "./stub.mjs";
+const b = await engine.launch();
+let failures = 0;
+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };
+
+async function open(changed) {
+ const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });
+ if (changed) await ctx.addInitScript(() => {
+ window.__driveChanged = { "FOLDER::a": { items: 12, added: 3, changed: 0, gone: 0, etag: "w9" } };
+ });
+ const page = await ctx.newPage();
+ page.on("pageerror", (e) => { console.log(`FAIL page error: ${e.message}`); process.exitCode = 1; });
+ await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
+ await openScreen(page, "Drive");
+ await page.waitForTimeout(300);
+ return { ctx, page };
+}
+const del = async (page) => {
+ await page.getByRole("button", { name: "Actions for Downloads" }).click();
+ await page.getByRole("menuitem", { name: "Delete" }).click();
+ await page.waitForTimeout(250);
+};
+const row = (page) => page.locator(".drive-rows .drive-name", { hasText: "Downloads" }).count();
+const sheet = (page) => page.getByRole("alertdialog").or(page.getByRole("dialog"));
+
+{
+ const { ctx, page } = await open(false);
+ await del(page);
+ ok((await sheet(page).count()) === 0, "an unchanged folder is deleted with no question");
+ ok((await page.evaluate(() => window.__driveDeleted ?? [])).includes("FOLDER::a"), "and it is deleted");
+ await ctx.close();
+}
+{
+ const { ctx, page } = await open(true);
+ await del(page);
+ const text = (await sheet(page).count()) ? await sheet(page).first().innerText() : "";
+ ok(/now has 12 items, with 3 items added since it was shown here/.test(text), `a changed folder is asked about as it now stands ${JSON.stringify(text)}`);
+ ok(!(await page.evaluate(() => window.__driveDeleted ?? [])).includes("FOLDER::a"), "nothing deleted before the answer");
+ await page.getByRole("button", { name: "Cancel" }).click();
+ await page.waitForTimeout(250);
+ ok((await row(page)) === 1, "Cancel keeps it, back in its place");
+ ok(!(await page.locator(".drive-error, [role=alert]").filter({ hasText: /kept/ }).count()), "and says no error for it");
+
+ await del(page);
+ await page.getByRole("button", { name: "Delete Anyway" }).click();
+ await page.waitForTimeout(300);
+ ok((await page.evaluate(() => window.__driveDeleted ?? [])).includes("FOLDER::a"), "Delete Anyway deletes the version just shown");
+ ok((await row(page)) === 0, "and it leaves");
+ await ctx.close();
+}
+await b.close();
+if (failures) process.exitCode = 1;
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 7f807c5..4a00741 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -1143,9 +1143,14 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
return null;
}
case "drive_delete": {
+ // A folder changed on another device since it was shown (`__driveChanged[id]`, as
+ // drive::FolderNow): not deleted, but answered as it now stands — unless the delete
+ // names that version (`expect`), as "Delete Anyway" does.
+ const now = window.__driveChanged?.[args.drivewsid];
+ if (now && args.expect !== now.etag) { (window.__driveAsked ??= []).push(args.drivewsid); return { kind: "changed", ...now }; }
(window.__driveDeleted ??= []).push(args.drivewsid);
for (const [k, list] of Object.entries(window.__driveIn ?? {})) window.__driveIn[k] = list.filter((i) => i.drivewsid !== args.drivewsid);
- return null;
+ return { kind: "done" };
}
case "drive_item": return null;
case "auth_two_factor_options": return twoFactor;
diff --git a/check.sh b/check.sh
index c8c6d09..af27ad9 100755
--- a/check.sh
+++ b/check.sh
@@ -87,6 +87,7 @@ step "drive sort" node .uiverify/drive-sort.mjs
step "drive trash" node .uiverify/drive-trash.mjs
step "drive info" node .uiverify/drive-info.mjs
step "drive delete" node .uiverify/drive-delete.mjs
+step "drive delete changed" node .uiverify/drive-delete-changed.mjs
step "notes folders" node .uiverify/notes-folders.mjs
step "list info" node .uiverify/reminders-list-info.mjs
step "reminder date" node .uiverify/reminders-date.mjs
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 6b7b13c..15fdad3 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -850,6 +850,155 @@ pub async fn delete(
))
}
+/// A folder as Apple holds it now, against how it was shown: asked about before it is deleted.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FolderNow {
+ /// Everything in it now.
+ pub items: usize,
+ /// Of those, the ones that were not there when it was shown.
+ pub added: usize,
+ /// Ones that were there, changed since.
+ pub changed: usize,
+ /// Ones shown that are no longer there.
+ pub gone: usize,
+ /// The version of the folder these numbers are of: deleted anyway, only that version is.
+ pub etag: Option<String>,
+}
+
+/// What a delete from the window did.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "camelCase", tag = "kind")]
+pub enum Removed {
+ /// In Recently Deleted.
+ Done,
+ /// Not deleted: the folder is not what was shown. Asked again with this.
+ Changed(FolderNow),
+}
+
+/// How the folder's items now stand against `shown`.
+#[must_use]
+pub fn folder_now(shown: &[DriveItem], now: &[DriveItem], etag: Option<String>) -> FolderNow {
+ let was = |id: &str| shown.iter().find(|s| s.drivewsid == id);
+ FolderNow {
+ items: now.len(),
+ added: now.iter().filter(|n| was(&n.drivewsid).is_none()).count(),
+ changed: now
+ .iter()
+ .filter(|n| was(&n.drivewsid).is_some_and(|s| s.etag != n.etag))
+ .count(),
+ gone: shown
+ .iter()
+ .filter(|s| !now.iter().any(|n| n.drivewsid == s.drivewsid))
+ .count(),
+ etag,
+ }
+}
+
+/// Delete from the window, only what was shown.
+///
+/// A file goes against the version shown (its stored etag): changed since — on another
+/// device — Apple refuses it, and that is said rather than the newer file deleted. A folder
+/// goes only if it is the version shown (`expect`, the version a question already showed, or
+/// else its stored etag — every file landing in it moves its etag on): otherwise nothing is
+/// deleted and its contents as they now stand come back, to be asked about. Taken from the
+/// folder it is in, the latest etag deleted whatever had been added to it on another device.
+///
+/// `shown` is the folder's items as the window last held them.
+pub async fn delete_as_shown(
+ http: &reqwest::Client,
+ root: &str,
+ params: Vec<(String, String)>,
+ item: &DriveItem,
+ shown: &[DriveItem],
+ expect: Option<&str>,
+) -> Result<Removed> {
+ let parent = parent_of(item);
+ let listed = folder_listing(http, root, &params, parent).await?;
+ let Some(current) = listed.iter().find(|i| i.drivewsid == item.drivewsid) else {
+ // Gone already: deleted elsewhere, or by an earlier try of this one.
+ return Ok(Removed::Done);
+ };
+ let changed_words = || {
+ Error::Refused(format!(
+ "“{}” changed on another device since it was shown here, so it wasn’t deleted. Take a look, then delete it again.",
+ item.display_name()
+ ))
+ };
+ let etag = if item.is_container() {
+ let seen = expect.map(str::to_string).or_else(|| item.etag.clone());
+ let unchanged = match (&seen, &current.etag) {
+ (Some(seen), Some(now)) => seen == now,
+ // No version to hold it to: its contents are compared instead.
+ _ => {
+ let now = folder_listing(http, root, &params, &item.drivewsid).await?;
+ let n = folder_now(shown, &now, current.etag.clone());
+ n.added == 0 && n.changed == 0 && n.gone == 0
+ }
+ };
+ if !unchanged {
+ let now = folder_listing(http, root, &params, &item.drivewsid).await?;
+ return Ok(Removed::Changed(folder_now(
+ shown,
+ &now,
+ current.etag.clone(),
+ )));
+ }
+ current.etag.clone()
+ } else {
+ item.etag.clone().or_else(|| current.etag.clone())
+ };
+
+ let url = format!("{}/moveItemsToTrash", root.trim_end_matches('/'));
+ let body = json!({
+ "items": [{ "drivewsid": item.drivewsid, "etag": etag, "clientId": item.drivewsid }],
+ });
+ let reply = post_json(http, &url, &params, &body).await?;
+ let status = reply
+ .get("items")
+ .and_then(Value::as_array)
+ .and_then(|items| {
+ items.iter().find(|i| {
+ i.get("drivewsid").and_then(Value::as_str) == Some(item.drivewsid.as_str())
+ })
+ })
+ .and_then(|a| a.get("status"))
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ match status.as_deref() {
+ Some("OK") | None => {}
+ // Moved on between the look and the delete: a folder is asked about again as it
+ // now stands; a file is not deleted.
+ Some("ETAG_CONFLICT") if item.is_container() => {
+ let listed = folder_listing(http, root, &params, parent).await?;
+ let etag = listed
+ .iter()
+ .find(|i| i.drivewsid == item.drivewsid)
+ .and_then(|i| i.etag.clone());
+ let now = folder_listing(http, root, &params, &item.drivewsid).await?;
+ return Ok(Removed::Changed(folder_now(shown, &now, etag)));
+ }
+ Some("ETAG_CONFLICT") => return Err(changed_words()),
+ Some(other) => {
+ return Err(Error::Refused(format!(
+ "iCloud Drive did not let that be deleted ({other})."
+ )))
+ }
+ }
+ for wait in [0u64, 800, 1500, 2500] {
+ if wait > 0 {
+ tokio::time::sleep(std::time::Duration::from_millis(wait)).await;
+ }
+ let after = folder_listing(http, root, &params, parent).await?;
+ if !after.iter().any(|i| i.drivewsid == item.drivewsid) {
+ return Ok(Removed::Done);
+ }
+ }
+ Err(Error::Refused(
+ "iCloud answered, but the item is still in the folder — try again in a moment.".into(),
+ ))
+}
+
/// Duplicate a file as icloud.com does: `POST {docws}/v1/item/copy/{item_id}` with
/// `{info_to_update:{}}`. Apple names the copy as Finder would — "Plan 2.pdf" — in the same
/// folder. `item_id` is not the drivewsid's tail (that answers 404): it is a field of the
@@ -4470,3 +4619,251 @@ mod copy_tests {
assert!(drive.writes().is_empty());
}
}
+
+#[cfg(test)]
+mod delete_as_shown_tests {
+ use super::*;
+ use std::sync::{Arc, Mutex};
+ use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
+
+ const ROOT_ID: &str = "FOLDER::com.apple.CloudDocs::root";
+ const WORK: &str = "FOLDER::com.apple.CloudDocs::work";
+
+ /// Drive as Apple keeps it: every item with its etag, a folder's etag moving on whenever
+ /// something lands in it, and a delete refused (ETAG_CONFLICT) unless it names the etag
+ /// the item has now.
+ #[derive(Clone, Default)]
+ struct Apple(Arc<Mutex<Vec<Held>>>);
+
+ /// An item as Apple keeps it: its id, its folder, its kind, its etag.
+ type Held = (String, String, &'static str, String);
+
+ impl Apple {
+ fn new() -> Self {
+ let a = Apple::default();
+ a.put(WORK, ROOT_ID, "FOLDER", "w1");
+ a.put("FILE::com.apple.CloudDocs::a", WORK, "FILE", "a1");
+ a.put("FILE::com.apple.CloudDocs::b", WORK, "FILE", "b1");
+ a.put("FILE::com.apple.CloudDocs::plan", ROOT_ID, "FILE", "p1");
+ a
+ }
+ fn put(&self, id: &str, parent: &str, kind: &'static str, etag: &str) {
+ self.0
+ .lock()
+ .unwrap()
+ .push((id.into(), parent.into(), kind, etag.into()));
+ }
+ /// A file added on another device: it lands, and its folder's etag moves on.
+ fn added_elsewhere(&self, id: &str) {
+ self.put(id, WORK, "FILE", "n1");
+ self.bump(WORK);
+ }
+ fn bump(&self, id: &str) {
+ for i in self.0.lock().unwrap().iter_mut().filter(|i| i.0 == id) {
+ i.3.push('+');
+ }
+ }
+ fn has(&self, id: &str) -> bool {
+ self.0.lock().unwrap().iter().any(|i| i.0 == id)
+ }
+ fn item(&self, id: &str) -> DriveItem {
+ let all = self.0.lock().unwrap();
+ let i = all.iter().find(|i| i.0 == id).unwrap();
+ DriveItem {
+ drivewsid: i.0.clone(),
+ parent_id: Some(i.1.clone()),
+ name: i.0.rsplit("::").next().unwrap().into(),
+ extension: None,
+ kind: i.2.into(),
+ size: None,
+ child_count: None,
+ created_at: None,
+ modified_at: None,
+ etag: Some(i.3.clone()),
+ }
+ }
+ fn children(&self, folder: &str) -> Vec<DriveItem> {
+ let ids: Vec<String> = self
+ .0
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|i| i.1 == folder)
+ .map(|i| i.0.clone())
+ .collect();
+ ids.iter().map(|id| self.item(id)).collect()
+ }
+ }
+
+ impl Respond for Apple {
+ fn respond(&self, req: &Request) -> ResponseTemplate {
+ let body: Value = serde_json::from_slice(&req.body).unwrap_or(Value::Null);
+ if req.url.path().ends_with("/retrieveItemDetailsInFolders") {
+ let folder = body[0]["drivewsid"].as_str().unwrap_or_default();
+ let items: Vec<Value> = self
+ .children(folder)
+ .iter()
+ .map(|i| {
+ json!({ "drivewsid": i.drivewsid, "parentId": folder, "name": i.name,
+ "type": i.kind, "etag": i.etag })
+ })
+ .collect();
+ return ResponseTemplate::new(200)
+ .set_body_json(json!([{ "drivewsid": folder, "items": items }]));
+ }
+ if req.url.path().ends_with("/moveItemsToTrash") {
+ let id = body["items"][0]["drivewsid"]
+ .as_str()
+ .unwrap_or_default()
+ .to_string();
+ let sent = body["items"][0]["etag"].as_str().map(str::to_string);
+ let now = self.has(&id).then(|| self.item(&id).etag).flatten();
+ if sent != now {
+ return ResponseTemplate::new(200).set_body_json(
+ json!({ "items": [{ "drivewsid": id, "status": "ETAG_CONFLICT", "etag": now }] }),
+ );
+ }
+ let mut all = self.0.lock().unwrap();
+ all.retain(|i| i.0 != id && i.1 != id);
+ return ResponseTemplate::new(200)
+ .set_body_json(json!({ "items": [{ "drivewsid": id, "status": "OK" }] }));
+ }
+ ResponseTemplate::new(404)
+ }
+ }
+
+ async fn serve(apple: &Apple) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(wiremock::matchers::method("POST"))
+ .respond_with(apple.clone())
+ .mount(&server)
+ .await;
+ server
+ }
+
+ /// Nothing changed since it was shown: deleted at once, no question.
+ #[tokio::test]
+ async fn an_unchanged_folder_is_deleted_at_once() {
+ let apple = Apple::new();
+ let (work, shown) = (apple.item(WORK), apple.children(WORK));
+ let server = serve(&apple).await;
+ let done = delete_as_shown(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &work,
+ &shown,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(done, Removed::Done);
+ assert!(!apple.has(WORK));
+ }
+
+ /// A file added on another device since the folder was shown: nothing is deleted, and the
+ /// folder as it now stands comes back to ask about. Asked and answered for that version,
+ /// it goes; but if it moved on again meanwhile, it is asked about again.
+ #[tokio::test]
+ async fn a_folder_with_a_file_added_elsewhere_is_asked_about() {
+ let apple = Apple::new();
+ let (work, shown) = (apple.item(WORK), apple.children(WORK));
+ apple.added_elsewhere("FILE::com.apple.CloudDocs::new");
+ let server = serve(&apple).await;
+ let http = reqwest::Client::new();
+ let asked = delete_as_shown(&http, &server.uri(), vec![], &work, &shown, None)
+ .await
+ .unwrap();
+ let Removed::Changed(now) = asked else {
+ panic!("deleted a folder holding a file never shown: {asked:?}")
+ };
+ assert_eq!((now.items, now.added, now.changed, now.gone), (3, 1, 0, 0));
+ assert!(apple.has(WORK) && apple.has("FILE::com.apple.CloudDocs::new"));
+
+ // Another lands before the answer: asked again, still nothing deleted.
+ apple.added_elsewhere("FILE::com.apple.CloudDocs::newer");
+ let again = delete_as_shown(
+ &http,
+ &server.uri(),
+ vec![],
+ &work,
+ &shown,
+ now.etag.as_deref(),
+ )
+ .await
+ .unwrap();
+ let Removed::Changed(now) = again else {
+ panic!("deleted past a second change: {again:?}")
+ };
+ assert_eq!((now.items, now.added), (4, 2));
+ assert!(apple.has(WORK));
+
+ // "Delete anyway", for the version just shown: gone.
+ let done = delete_as_shown(
+ &http,
+ &server.uri(),
+ vec![],
+ &work,
+ &shown,
+ now.etag.as_deref(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(done, Removed::Done);
+ assert!(!apple.has(WORK));
+ }
+
+ /// A file changed on another device since it was shown: Apple refuses the delete against
+ /// the version shown, and that is said — the newer file stays.
+ #[tokio::test]
+ async fn a_file_changed_elsewhere_is_not_deleted() {
+ let apple = Apple::new();
+ let plan = apple.item("FILE::com.apple.CloudDocs::plan");
+ apple.bump("FILE::com.apple.CloudDocs::plan");
+ let server = serve(&apple).await;
+ let refused = delete_as_shown(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &plan,
+ &[],
+ None,
+ )
+ .await;
+ match refused {
+ Err(Error::Refused(words)) => {
+ assert!(words.contains("changed on another device"), "{words}")
+ }
+ other => panic!("deleted a newer file: {other:?}"),
+ }
+ assert!(apple.has("FILE::com.apple.CloudDocs::plan"));
+ // As shown, it goes.
+ let now = apple.item("FILE::com.apple.CloudDocs::plan");
+ let done = delete_as_shown(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &now,
+ &[],
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(done, Removed::Done);
+ }
+
+ #[test]
+ fn a_folders_changes_are_counted_against_what_was_shown() {
+ let apple = Apple::new();
+ let shown = apple.children(WORK);
+ apple.bump("FILE::com.apple.CloudDocs::a");
+ apple.added_elsewhere("FILE::com.apple.CloudDocs::c");
+ apple
+ .0
+ .lock()
+ .unwrap()
+ .retain(|i| i.0 != "FILE::com.apple.CloudDocs::b");
+ let now = folder_now(&shown, &apple.children(WORK), None);
+ assert_eq!((now.items, now.added, now.changed, now.gone), (2, 1, 1, 1));
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 7fd6ce1..110a97a 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -5284,28 +5284,48 @@ async fn drive_rename(
settle(resync_drive_folder(&http, &root, params, &data, parent).await)
}
+/// Delete from the window, only what it showed (see `drive::delete_as_shown`): a file as the
+/// version shown, a folder only as the version shown or the one a question since showed
+/// (`expect`). A folder that is not comes back as it now stands, to be asked about.
#[tauri::command]
async fn drive_delete(
drivewsid: String,
+ expect: Option<String>,
auth: State<'_, Auth>,
data: State<'_, Data>,
-) -> UiResult<()> {
- let item = {
+) -> UiResult<quince_icloud::drive::Removed> {
+ let (item, shown) = {
let library = data.0.lock().await;
- library
+ let item = library
.drive_item(&drivewsid)
.map_err(|e| e.to_string())?
- .ok_or("That item is no longer in the local library.")?
+ .ok_or("That item is no longer in the local library.")?;
+ let shown = if item.is_container() {
+ library
+ .drive_children(&item.drivewsid)
+ .map_err(|e| e.to_string())?
+ } else {
+ Vec::new()
+ };
+ (item, shown)
};
let (http, root, params) = drive_context(&auth).await?;
- quince_icloud::drive::delete(&http, &root, params.clone(), &item)
- .await
- .map_err(|e| e.to_string())?;
+ let removed = quince_icloud::drive::delete_as_shown(
+ &http,
+ &root,
+ params.clone(),
+ &item,
+ &shown,
+ expect.as_deref(),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
let parent = item
.parent_id
.as_deref()
.unwrap_or(quince_core::drive::ROOT);
- settle(resync_drive_folder(&http, &root, params, &data, parent).await)
+ settle(resync_drive_folder(&http, &root, params, &data, parent).await)?;
+ Ok(removed)
}
/// Duplicate a file into its own folder, named as Finder names a copy.
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index e8b486a..6719829 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -506,7 +506,10 @@ export const api = {
invoke<void>("drive_create_folder", { parentId, name }),
driveRename: (drivewsid: string, name: string) =>
invoke<void>("drive_rename", { drivewsid, name }),
- driveDelete: (drivewsid: string) => invoke<void>("drive_delete", { drivewsid }),
+ /** Deleted only as shown: a folder that changed since comes back as it now stands, to be
+ * asked about, and goes only as the version `expect` names. */
+ driveDelete: (drivewsid: string, expect: string | null = null) =>
+ invoke<DriveRemoved>("drive_delete", { drivewsid, expect }),
driveTrash: () => invoke<TrashItem[]>("drive_trash"),
driveThumbnails: (folderId: string) => invoke<Record<string, string>>("drive_thumbnails", { folderId }),
driveDuplicate: (drivewsid: string) => invoke<void>("drive_duplicate", { drivewsid }),
@@ -1034,6 +1037,11 @@ export function displayName(c: Contact): string {
return c.methods[0]?.value ?? "No Name";
}
+/** A folder as Apple holds it now against how it was shown (`drive::FolderNow`). */
+export type FolderNow = { items: number; added: number; changed: number; gone: number; etag: string | null };
+/** What a delete from the window did: done, or not — the folder changed since it was shown. */
+export type DriveRemoved = { kind: "done" } | ({ kind: "changed" } & FolderNow);
+
export type DriveItem = {
drivewsid: string;
parentId: string | null;
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 8943ac7..bdf52f3 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -19,6 +19,7 @@ import {
DRIVE_ROOT,
UPLOAD,
type DriveItem,
+ type FolderNow,
type RecentItem,
type TrashItem,
type UploadEvent,
@@ -456,8 +457,28 @@ const copyable = (item: DriveItem) => (item.kind === "FILE" || item.kind === "FO
/** What a paste onto a name already there does: both kept ("Report 2.pdf"), or the one there replaced. */
type Clash = "keep" | "replace" | null;
+/** A delete the person chose not to go on with: the item stays, and nothing is said. */
+const KEPT = "kept";
+
+/** A folder changed since it was shown, said as it now stands: what is in it, and what is new. */
+export function folderNowWords(now: FolderNow): string {
+ const n = (k: number, one: string) => `${k} ${one}${k === 1 ? "" : "s"}`;
+ const since = [
+ now.added ? `${n(now.added, "item")} added` : "",
+ now.changed ? `${n(now.changed, "item")} changed` : "",
+ now.gone ? `${n(now.gone, "item")} removed` : "",
+ ].filter(Boolean);
+ const said = since.length > 1 ? `${since.slice(0, -1).join(", ")} and ${since[since.length - 1]}` : since[0];
+ const holds = `This folder now has ${n(now.items, "item")}`;
+ return said
+ ? `${holds}, with ${said} since it was shown here, on another device. It goes to Recently Deleted with everything in it.`
+ : `${holds}. It changed since it was shown here, on another device. It goes to Recently Deleted with everything in it.`;
+}
+
export function DriveView() {
const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "Drive" }]);
+ // Asked before a folder that changed since it was shown is deleted.
+ const [confirm, confirmSheet] = useConfirm();
/**
* Back and Forward, as Finder's: the folders opened before this one, and those gone back
* from, by whole path. Every way of reaching a folder — a double-click, the path, a search,
@@ -897,10 +918,23 @@ export function DriveView() {
for (const batch of new Set(into.map((u) => u.batch))) await api.driveUploadCancel([], batch).catch(() => {});
}
try {
- await api.driveDelete(item.drivewsid);
+ // Only as shown: a folder changed since (a file added on another device) is asked
+ // about with what it holds now, and goes only as that.
+ let removed = await api.driveDelete(item.drivewsid);
+ while (removed.kind === "changed") {
+ const sure = await confirm({
+ title: `Delete “${driveName(item)}”?`,
+ body: folderNowWords(removed),
+ action: "Delete Anyway",
+ danger: true,
+ symbol: "trash",
+ });
+ if (!sure) throw new Error(KEPT);
+ removed = await api.driveDelete(item.drivewsid, removed.etag);
+ }
} catch (e) {
refused.push(item.drivewsid);
- reason = messageOf(e);
+ if (messageOf(e) !== KEPT) reason = messageOf(e);
}
}
if (refused.length) {
@@ -909,11 +943,11 @@ export function DriveView() {
for (const id of refused) next.delete(goneKey(from, id));
return next;
});
- setError(list.length === 1 ? reason : `${refused.length} of ${list.length} items could not be deleted: ${reason}`);
+ if (reason) setError(list.length === 1 ? reason : `${refused.length} of ${list.length} items could not be deleted: ${reason}`);
}
if (refused.length < list.length) await refresh();
},
- [refresh]
+ [refresh, confirm]
);
const remove = useCallback((item: DriveItem) => removeAll([item]), [removeAll]);
@@ -1055,7 +1089,9 @@ export function DriveView() {
try {
const old = replacing.get(item.drivewsid);
if (old) {
- await api.driveDelete(old.drivewsid).catch((e) => {
+ await api.driveDelete(old.drivewsid).then((removed) => {
+ if (removed.kind === "changed") throw new Error(`“${driveName(old)}” changed on another device since it was shown here, so it wasn’t replaced.`);
+ }).catch((e) => {
// Still there: shown again, and this one not copied over it.
setGone((g) => { const next = new Set(g); next.delete(goneKey(into, old.drivewsid)); return next; });
throw e;
@@ -1297,7 +1333,8 @@ export function DriveView() {
setGone((g) => new Set([...g, ...old.map((o) => goneKey(into, o.drivewsid))]));
for (const o of old) {
try {
- await api.driveDelete(o.drivewsid);
+ const removed = await api.driveDelete(o.drivewsid);
+ if (removed.kind === "changed") throw new Error(`“${driveName(o)}” changed on another device since it was shown here, so it wasn’t replaced. ${folderNowWords(removed).split(".")[0]}.`);
} catch (e) {
// Still there: shown again, and nothing moved over it.
setGone((g) => { const next = new Set(g); for (const x of old) next.delete(goneKey(into, x.drivewsid)); return next; });
@@ -1919,6 +1956,7 @@ export function DriveView() {
/>
)}
+ {confirmSheet}
{asking && (
<ConfirmSheet<"keep" | "replace">
title={asking.items.length === 1