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: a paste onto a name already there asks Keep Both or Replace, as Finder

Yashwanth Kamireddif0f3a5a308e8
diff --git a/.uiverify/drive-copy-name.test.mjs b/.uiverify/drive-copy-name.test.mjs
index 033fd39..cc182b0 100644
--- a/.uiverify/drive-copy-name.test.mjs
+++ b/.uiverify/drive-copy-name.test.mjs
@@ -2,7 +2,7 @@
// copy_name (crates/quince-icloud/src/drive.rs), which names the real one.
import { test } from "node:test";
import assert from "node:assert/strict";
-import { copyName } from "../src/lib/clipboard.ts";
+import { copyName, keepBothName } from "../src/lib/clipboard.ts";
test("its own name where that is free", () => {
assert.equal(copyName("Report", "pdf", []), "Report.pdf");
@@ -22,3 +22,9 @@ test("a copy of a copy counts on, never “copy copy”", () => {
assert.equal(copyName("copy", "txt", ["copy.txt"]), "copy copy.txt");
assert.equal(copyName("Hard copy 2b", null, ["Hard copy 2b"]), "Hard copy 2b copy");
});
+
+test("Keep Both, as Finder: “Name 2”, then “Name 3”, whatever the case of what is there", () => {
+ assert.equal(keepBothName("Report", "pdf", ["Report.pdf"]), "Report 2.pdf");
+ assert.equal(keepBothName("Report", "pdf", ["report.pdf", "REPORT 2.PDF"]), "Report 3.pdf");
+ assert.equal(keepBothName("Trip", null, ["Trip"]), "Trip 2");
+});
diff --git a/.uiverify/drive-info.mjs b/.uiverify/drive-info.mjs
index 2cd76ff..a9eb904 100644
--- a/.uiverify/drive-info.mjs
+++ b/.uiverify/drive-info.mjs
@@ -5,7 +5,7 @@ const b = await engine.launch();
const ctx = await b.newContext({ viewport: { width: 1200, height: 800 } });
await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });
const page = await ctx.newPage();
-await page.goto("http://localhost:4173", { waitUntil: "networkidle" });
+await page.goto(process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });
await openScreen(page, "Drive");
await page.waitForTimeout(300);
let failures = 0;
@@ -33,7 +33,7 @@ ok(JSON.stringify(forFile) === JSON.stringify(["Download a Copy", "Get Info", "D
`a file's menu adds Duplicate ${JSON.stringify(forFile)}`);
await page.getByRole("menuitem", { name: "Duplicate" }).click();
await page.waitForTimeout(200);
-ok(JSON.stringify(await page.evaluate(() => window.__dups)) === JSON.stringify(["FILE::d"]), "Duplicate asks Apple for a copy of that file");
+ok(JSON.stringify(await page.evaluate(() => (window.__driveCopies ?? []).map((c) => c.drivewsid))) === JSON.stringify(["FILE::d"]), "Duplicate asks Apple for a copy of that file");
await page.keyboard.press("Escape");
await page.waitForTimeout(100);
ok((await page.getByRole("menu").count()) === 0, "and Escape puts it away");
diff --git a/.uiverify/drive-keys.mjs b/.uiverify/drive-keys.mjs
index 426840a..590ce59 100644
--- a/.uiverify/drive-keys.mjs
+++ b/.uiverify/drive-keys.mjs
@@ -50,7 +50,7 @@ await page.waitForTimeout(200);
ok(!(await inDownloads()), "with nothing ahead, Ctrl-] stays where it is");
// Ctrl-D duplicates the chosen file beside itself, as Finder's Command-D.
-const before = await page.evaluate(() => (window.__dups ?? []).length);
+const before = await page.evaluate(() => (window.__driveCopies ?? []).length);
const firstFile = await page.evaluate(() => {
const rows = [...document.querySelectorAll("button.drive-row-hit")];
const i = rows.findIndex((r) => /\.\w+$/.test(r.querySelector(".drive-name")?.textContent ?? ""));
@@ -60,7 +60,7 @@ if (firstFile >= 0) {
await page.locator("button.drive-row-hit").nth(firstFile).click();
await page.keyboard.press("Control+d");
await page.waitForTimeout(300);
- ok((await page.evaluate(() => (window.__dups ?? []).length)) === before + 1, "Ctrl-D duplicates the chosen file");
+ ok((await page.evaluate(() => (window.__driveCopies ?? []).length)) === before + 1, "Ctrl-D duplicates the chosen file");
} else ok(false, "a file to duplicate is in the fixture");
await b.close();
process.exitCode = failures ? 1 : 0;
diff --git a/.uiverify/drive-paste-clash.mjs b/.uiverify/drive-paste-clash.mjs
new file mode 100644
index 0000000..c429b41
--- /dev/null
+++ b/.uiverify/drive-paste-clash.mjs
@@ -0,0 +1,120 @@
+// Pasting onto a name the folder already has, as Finder: a question first — Keep Both names the
+// one pasted "Name 2", Replace sends the one there to Recently Deleted, Cancel leaves both as
+// they were — for a copy (Ctrl-V) and for a move (Ctrl-Alt-V). Never overwritten silently, never
+// refused. Duplicate (Ctrl-D) and a paste where it was copied name the copy alike: "Name copy".
+//
+// URL=http://localhost:4173 ENGINE=webkit node .uiverify/drive-paste-clash.mjs
+import { engine } from "./engine.mjs";
+import { SERVICES, installStub } 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, driveFixture: true });
+await ctx.addInitScript(() => {
+ const ROOT = "FOLDER::com.apple.CloudDocs::root";
+ const DL = "FOLDER::com.apple.CloudDocs::dl";
+ const item = (id, name, kind, extension = null, parentId = ROOT) => ({
+ drivewsid: `${kind}::com.apple.CloudDocs::${id}`, parentId, name, extension, kind,
+ size: kind === "FILE" ? 2048 : null, childCount: null, createdAt: 1787000000, modifiedAt: 1788600000, etag: "e",
+ });
+ window.__driveIn = {
+ [ROOT]: [item("dl", "Downloads", "FOLDER"), item("plan", "Semester Plan", "FILE", "pdf"), item("notes", "Notes", "FILE", "txt")],
+ [DL]: [item("old", "Semester Plan", "FILE", "pdf", DL), item("budget", "Budget", "FILE", "xlsx", DL)],
+ };
+});
+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 page.locator(".nav-item", { hasText: "Drive" }).click();
+await page.locator("button.drive-row-hit", { hasText: "Semester Plan" }).waitFor();
+let failures = 0;
+const ok = (pass, what) => { console.log(`${pass ? "PASS" : "FAIL"} ${what}`); if (!pass) failures++; };
+const ROOT = "FOLDER::com.apple.CloudDocs::root";
+const DL = "FOLDER::com.apple.CloudDocs::dl";
+const PLAN = "FILE::com.apple.CloudDocs::plan";
+const row = (name) => page.locator("button.drive-row-hit", { hasText: name }).first();
+const names = () => page.locator(".drive-rows .drive-name").allInnerTexts();
+const standIn = (name) => page.locator(".drive-rows li.is-busy", { hasText: name });
+const settled = () => page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });
+const got = (key) => page.evaluate((k) => window[k] ?? [], key);
+const sheet = page.getByRole("alertdialog");
+const answer = (name) => sheet.getByRole("button", { name, exact: true }).click();
+const asked = () => sheet.waitFor({ timeout: 1500 }).then(() => true, () => false);
+
+await row("Semester Plan").click();
+await page.keyboard.press("Control+c");
+await row("Downloads").dblclick();
+await row("Budget").waitFor();
+await page.waitForTimeout(100);
+
+// Ctrl-V onto "Semester Plan.pdf": asked first, nothing done until answered.
+await page.keyboard.press("Control+v");
+ok(await asked(), "a paste onto a name already here asks first");
+const title = await sheet.locator("h2").innerText().catch(() => "");
+ok(/Semester Plan\.pdf/.test(title), `naming the item (${title})`);
+const buttons = await sheet.getByRole("button").allInnerTexts();
+ok(["Keep Both", "Replace", "Cancel"].every((n) => buttons.includes(n)), `with Keep Both, Replace and Cancel ${JSON.stringify(buttons)}`);
+ok((await got("__driveCopies")).length === 0, "and nothing is copied while it asks");
+
+// Cancel: nothing.
+await answer("Cancel");
+await page.waitForTimeout(200);
+ok((await got("__driveCopies")).length === 0 && (await names()).filter((n) => n === "Semester Plan.pdf").length === 1, "Cancel leaves the folder as it was");
+
+// Keep Both: copied, and named "Semester Plan 2.pdf".
+await page.evaluate(() => { window.__driveCopyDelay = 400; });
+await page.keyboard.press("Control+v");
+await asked();
+await answer("Keep Both");
+await standIn("Semester Plan 2.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "Keep Both shows the copy at once as “Semester Plan 2.pdf”"), () => ok(false, "Keep Both shows the copy at once as “Semester Plan 2.pdf”"));
+await settled();
+await page.waitForTimeout(200);
+const renames = await got("__driveNames");
+ok(renames.at(-1)?.name === "Semester Plan 2.pdf", `and names the real copy so ${JSON.stringify(renames.at(-1))}`);
+const kept = await names();
+ok(kept.includes("Semester Plan.pdf") && kept.includes("Semester Plan 2.pdf"), `both are in the folder ${JSON.stringify(kept)}`);
+ok(!(await got("__driveDeleted")).length, "and nothing was deleted");
+
+// Replace: the one here to Recently Deleted, the copy takes its name.
+await page.keyboard.press("Control+v");
+await asked();
+await answer("Replace");
+await standIn("Semester Plan.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "Replace shows the copy at once where the one there was"), () => ok(false, "Replace shows the copy at once where the one there was"));
+await settled();
+await page.waitForTimeout(200);
+ok(JSON.stringify(await got("__driveDeleted")) === JSON.stringify(["FILE::com.apple.CloudDocs::old"]), `Replace sends the one here to Recently Deleted ${JSON.stringify(await got("__driveDeleted"))}`);
+ok((await got("__driveCopies")).length === 2, "and copies the pasted one");
+const replaced = await names();
+ok(replaced.filter((n) => n === "Semester Plan.pdf").length === 1 && !replaced.includes("Semester Plan copy.pdf"), `under its own name ${JSON.stringify(replaced)}`);
+
+// Ctrl-Alt-V onto a name already here: asked too, and Keep Both moves it as "Semester Plan 3.pdf".
+await page.keyboard.press("Control+Alt+v");
+ok(await asked(), "a move onto a name already here asks first, rather than refusing");
+await answer("Keep Both");
+await page.waitForFunction(() => (window.__moves ?? []).length === 1, null, { timeout: 3000 }).catch(() => {});
+const moved = (await got("__moves"))[0];
+const named = (await got("__driveNames")).at(-1);
+ok(moved?.drivewsid === PLAN && moved?.destinationId === DL, `and moves it here ${JSON.stringify(moved)}`);
+ok(named?.drivewsid === PLAN && named?.name === "Semester Plan 3.pdf", `named “Semester Plan 3.pdf” ${JSON.stringify(named)}`);
+await settled().catch(() => {});
+
+// Duplicate and a paste where it was copied: the same name rule, "Notes copy.txt" then "copy 2".
+await page.locator(".drive-rows").click({ position: { x: 5, y: 5 } }).catch(() => {});
+await page.keyboard.press("Control+ArrowUp");
+await row("Notes").waitFor();
+await row("Notes").click();
+await page.keyboard.press("Control+d");
+await standIn("Notes copy.txt").waitFor({ timeout: 1000 }).then(() => ok(true, "Ctrl-D shows the copy as “Notes copy.txt”"), () => ok(false, "Ctrl-D shows the copy as “Notes copy.txt”"));
+const dup = (await got("__driveCopies")).at(-1);
+ok(dup?.drivewsid === "FILE::com.apple.CloudDocs::notes" && dup?.destinationId === ROOT, `made as a copy beside itself, the way Paste makes one ${JSON.stringify(dup)}`);
+await settled();
+await page.waitForTimeout(150);
+ok((await names()).includes("Notes copy.txt"), "and it is “Notes copy.txt” once made");
+await row("Notes").click();
+await page.keyboard.press("Control+c");
+await page.keyboard.press("Control+v");
+await standIn("Notes copy 2.txt").waitFor({ timeout: 1000 }).then(() => ok(true, "and is named “Notes copy 2.txt”, as a second duplicate would be"), () => ok(false, "and is named “Notes copy 2.txt”, as a second duplicate would be"));
+ok(await sheet.count() === 0, "a paste where it was copied does not ask");
+await settled();
+
+await b.close();
+process.exitCode = failures ? 1 : (process.exitCode ?? 0);
diff --git a/.uiverify/drive-paste.mjs b/.uiverify/drive-paste.mjs
index a596081..647fc99 100644
--- a/.uiverify/drive-paste.mjs
+++ b/.uiverify/drive-paste.mjs
@@ -69,23 +69,26 @@ const first = (await copies()).at(-1);
ok(first?.drivewsid === PLAN && first?.destinationId === DL, `Apple is asked to copy it here ${JSON.stringify(first)}`);
ok((await names()).includes("Semester Plan.pdf"), "the copy is in the folder once Apple has it");
-// Pasted again where its name is taken: "Semester Plan copy.pdf", then "copy 2".
-await page.evaluate(() => { window.__driveCopyName = "Semester Plan copy"; });
+// Pasted again where its name is taken: Finder's question, and Keep Both names it "Semester
+// Plan 2.pdf", then "Semester Plan 3.pdf" (drive-paste-clash.mjs has the rest of it).
+const keepBoth = () => page.getByRole("alertdialog").getByRole("button", { name: "Keep Both" }).click();
await page.keyboard.press("Control+v");
-await standIn("Semester Plan copy.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "a second paste is named “Semester Plan copy.pdf”"), () => ok(false, "a second paste is named “Semester Plan copy.pdf”"));
+await keepBoth();
+await standIn("Semester Plan 2.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "a second paste, both kept, is named “Semester Plan 2.pdf”"), () => ok(false, "a second paste, both kept, is named “Semester Plan 2.pdf”"));
await page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });
-await page.evaluate(() => { window.__driveCopyName = "Semester Plan copy 2"; });
await page.keyboard.press("Control+v");
-await standIn("Semester Plan copy 2.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "a third, “Semester Plan copy 2.pdf”"), () => ok(false, "a third, “Semester Plan copy 2.pdf”"));
+await keepBoth();
+await standIn("Semester Plan 3.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "a third, “Semester Plan 3.pdf”"), () => ok(false, "a third, “Semester Plan 3.pdf”"));
await page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });
ok((await copies()).length === 3, "each paste is one copy");
// Refused: the row that showed goes again, and the reason is said.
-await page.evaluate(() => { window.__driveCopyFail = "iCloud Drive turned this down."; window.__driveCopyName = "Semester Plan copy 3"; });
+await page.evaluate(() => { window.__driveCopyFail = "iCloud Drive turned this down."; });
await page.keyboard.press("Control+v");
-await standIn("Semester Plan copy 3.pdf").waitFor({ timeout: 1000 }).catch(() => {});
+await keepBoth();
+await standIn("Semester Plan 4.pdf").waitFor({ timeout: 1000 }).catch(() => {});
ok(await errorShown("turned this down"), "a copy Apple refuses says why");
-ok(!(await names()).includes("Semester Plan copy 3.pdf"), "and its row is gone again");
+ok(!(await names()).includes("Semester Plan 4.pdf"), "and its row is gone again");
await page.evaluate(() => { window.__driveCopyFail = null; window.__driveCopyDelay = 0; });
await dismissErrors();
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 618658e..e50dc7c 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -1016,7 +1016,13 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
if (window.__driveCopyFail) throw window.__driveCopyFail;
const from = [...driveItems, ...Object.values(window.__driveIn ?? {}).flat()].find((i) => i.drivewsid === args.drivewsid);
const into = window.__driveIn?.[args.destinationId];
- if (from && into) into.push({ ...from, drivewsid: `${from.drivewsid}-copy${window.__driveCopies.length}`, parentId: args.destinationId, name: window.__driveCopyName ?? from.name });
+ // Named as the backend's copy_name names it, unless the test names it.
+ const full = (i) => (i.extension ? `${i.name}.${i.extension}` : i.name).toLowerCase();
+ const free = (stem) => !into || !into.some((i) => full(i) === full({ ...from, name: stem }));
+ const base = from?.name.match(/^(.+) copy(?: \d+)?$/)?.[1] ?? from?.name;
+ let stem = from?.name;
+ if (from && !free(stem)) { stem = `${base} copy`; for (let n = 2; !free(stem); n++) stem = `${base} copy ${n}`; }
+ if (from && into) into.push({ ...from, drivewsid: `${from.drivewsid}-copy${window.__driveCopies.length}`, parentId: args.destinationId, name: window.__driveCopyName ?? stem });
return null;
}
// The desktop's clipboard as the backend reads it: files copied in the file manager, or text.
@@ -1097,8 +1103,18 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "drive_download": return "/home/user/Downloads/file.pdf";
case "download_reveal": (window.__revealed ??= []).push(args.path); return null;
case "drive_move": (window.__moves ??= []).push(args); await new Promise((r) => setTimeout(r, 600)); return null;
- case "drive_create_folder": case "drive_rename": (window.__driveNames ??= []).push(args); return null;
- case "drive_delete": return null;
+ case "drive_create_folder": case "drive_rename": {
+ (window.__driveNames ??= []).push(args);
+ // Renamed where a test keeps folders of its own (__driveIn).
+ const it = cmd === "drive_rename" && Object.values(window.__driveIn ?? {}).flat().find((i) => i.drivewsid === args.drivewsid);
+ if (it) it.name = it.extension && args.name.endsWith(`.${it.extension}`) ? args.name.slice(0, -(it.extension.length + 1)) : args.name;
+ return null;
+ }
+ case "drive_delete": {
+ (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;
+ }
case "drive_item": return null;
case "auth_two_factor_options": return twoFactor;
case "auth_resend_code": return null;
diff --git a/src/lib/clipboard.ts b/src/lib/clipboard.ts
index fb98e3e..d79169d 100644
--- a/src/lib/clipboard.ts
+++ b/src/lib/clipboard.ts
@@ -42,3 +42,13 @@ export function copyName(stem: string, extension: string | null, taken: Iterable
if (free(`${base} copy${ext}`)) return `${base} copy${ext}`;
for (let n = 2; ; n++) if (free(`${base} copy ${n}${ext}`)) return `${base} copy ${n}${ext}`;
}
+
+/**
+ * The name Finder's Keep Both gives an item put into a folder where its name is taken:
+ * "Report 2.pdf", then "Report 3.pdf". Compared without regard to case, as `copyName`.
+ */
+export function keepBothName(stem: string, extension: string | null, taken: Iterable<string>): string {
+ const ext = extension ? `.${extension}` : "";
+ const used = new Set([...taken].map((t) => t.toLocaleLowerCase()));
+ for (let n = 2; ; n++) if (!used.has(`${stem} ${n}${ext}`.toLocaleLowerCase())) return `${stem} ${n}${ext}`;
+}
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 3b9f2f6..0937bc8 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -3,7 +3,7 @@ import { overlayOpen, useActiveRef, useScreenActive } from "../lib/screen";
import { useModalFocus } from "../lib/focus";
import { useRevision } from "../lib/sync";
import { toastSaved, useErrorToast } from "../components/Toast";
-import { useConfirm } from "../components/Confirm";
+import { ConfirmSheet, useConfirm } from "../components/Confirm";
import { EmptyState } from "../components/EmptyState";
import { Spinner } from "../components/Spinner";
import { PaneTitle } from "../components/PaneTitle";
@@ -32,7 +32,7 @@ import { dateText, timeText } from "../lib/when";
import { Clock } from "lucide-react";
import { useReveal } from "../lib/reveal";
import { keepSame } from "../lib/same";
-import { copyName, copyText } from "../lib/clipboard";
+import { copyName, copyText, keepBothName } from "../lib/clipboard";
import { useChosen, useIsChosen, type Chosen } from "../lib/chosen";
/** iCloud Drive's own four orders, as its "by Name" menu offers them. */
@@ -451,6 +451,9 @@ function sameItems(a: DriveItem[], b: DriveItem[]): boolean {
*/
const copyable = (item: DriveItem) => (item.kind === "FILE" || item.kind === "FOLDER") && acceptsUploads(item.drivewsid);
+/** What a paste onto a name already there does: both kept ("Report 2.pdf"), or the one there replaced. */
+type Clash = "keep" | "replace" | null;
+
export function DriveView() {
const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "Drive" }]);
/**
@@ -898,18 +901,21 @@ export function DriveView() {
const remove = useCallback((item: DriveItem) => removeAll([item]), [removeAll]);
/**
- * Duplicate, as Finder: the copy lands beside the original as "Name 2", and shows as being
- * made at once — Apple decides its name, so the row is a stand-in until it answers.
+ * Duplicate, as Finder: the copy lands beside the original as "Name copy", named as Copy and
+ * Paste names one in its own folder (the same backend copy), and shows as being made at once.
*/
const duplicate = useCallback(
async (item: DriveItem) => {
setError(null);
// By the item as well as the moment: several duplicated at once share a millisecond.
const key = `copy-${item.drivewsid}-${Date.now()}`;
- const ext = item.extension ? `.${item.extension}` : "";
- setPending((p) => [...p, { key, folder: here.id, name: `${item.name} copy${ext}`, doing: "Duplicating…" }]);
+ const taken = [
+ ...itemsRef.current.map(driveName),
+ ...pendingRef.current.filter((p) => p.folder === here.id).map((p) => p.name),
+ ];
+ setPending((p) => [...p, { key, folder: here.id, name: copyName(item.name, item.extension, taken), doing: "Duplicating…" }]);
try {
- await api.driveDuplicate(item.drivewsid);
+ await api.driveCopy(item.drivewsid, here.id);
await refresh();
} catch (e) {
setError(messageOf(e));
@@ -970,6 +976,20 @@ export function DriveView() {
* Ctrl-V in any folder puts copies there. Kept across folders, and for more than one paste.
*/
const [clip, setClip] = useState<{ items: DriveItem[]; from: string; text: string | null } | null>(null);
+ /** What has the name of each of `list` in the folder open, by the item pasted. */
+ const clashesHere = (list: DriveItem[]) => {
+ const here = new Map(itemsRef.current.map((i) => [driveName(i).toLocaleLowerCase(), i]));
+ const out = new Map<string, DriveItem>();
+ for (const i of list) {
+ const there = here.get(driveName(i).toLocaleLowerCase());
+ if (there && there.drivewsid !== i.drivewsid) out.set(i.drivewsid, there);
+ }
+ return out;
+ };
+ /** Finder's question when a pasted name is taken: Keep Both, Replace, or Cancel (null). */
+ const [asking, setAsking] = useState<{ items: DriveItem[]; answer: (how: Clash) => void } | null>(null);
+ const askClash = (items: DriveItem[]) =>
+ new Promise<Clash>((answer) => setAsking({ items, answer: (how) => { setAsking(null); answer(how); } }));
const clipRef = useRef(clip);
clipRef.current = clip;
const copyItems = useCallback(async (list: DriveItem[]) => {
@@ -987,7 +1007,7 @@ export function DriveView() {
* fails leaves, with the reason; the rest still land.
*/
const copyHere = useCallback(
- async (list: DriveItem[]) => {
+ async (list: DriveItem[], clash: Clash = null) => {
setError(null);
const into = hereRef.current;
const inside = trailRef.current.map((c) => c.id);
@@ -996,13 +1016,18 @@ export function DriveView() {
const copying = list.filter((i) => !inside.includes(i.drivewsid));
if (insideItself) setError(`\u201c${driveName(insideItself)}\u201d can\u2019t be copied into a folder inside itself.`);
if (copying.length === 0) return;
+ // Replace: what has the name goes to Recently Deleted first, so the copy takes its name.
+ const replacing = clash === "replace" ? clashesHere(copying) : new Map<string, DriveItem>();
+ if (replacing.size) setGone((g) => new Set([...g, ...[...replacing.values()].map((o) => goneKey(into, o.drivewsid))]));
const taken = new Set([
- ...itemsRef.current.map(driveName),
+ ...itemsRef.current.filter((i) => ![...replacing.values()].includes(i)).map(driveName),
...pendingRef.current.filter((p) => p.folder === into).map((p) => p.name),
]);
const batch = `paste-${Date.now()}`;
+ const kept = clash === "keep" ? clashesHere(copying) : new Map<string, DriveItem>();
const shown = copying.map((item, i) => {
- const name = copyName(item.name, isContainer(item) ? null : item.extension, taken);
+ const ext = isContainer(item) ? null : item.extension;
+ const name = kept.has(item.drivewsid) ? keepBothName(item.name, ext, taken) : copyName(item.name, ext, taken);
taken.add(name);
return { key: `${batch}:${i}`, folder: into, name, doing: "Copying…" };
});
@@ -1011,7 +1036,18 @@ export function DriveView() {
let reason = "";
for (const [i, item] of copying.entries()) {
try {
+ const old = replacing.get(item.drivewsid);
+ if (old) await api.driveDelete(old.drivewsid);
+ // Kept both: the backend names the copy as Finder names a copy ("Report copy.pdf"),
+ // and it is then named as Keep Both names it ("Report 2.pdf").
+ const listed = async () => { const l = await api.driveChildren(into); return Array.isArray(l) ? l : []; };
+ const before = kept.has(item.drivewsid) ? await listed() : null;
await api.driveCopy(item.drivewsid, into);
+ if (before) {
+ const named = copyName(item.name, isContainer(item) ? null : item.extension, before.map(driveName)).toLocaleLowerCase();
+ const made = (await listed()).find((x) => !before.some((b) => b.drivewsid === x.drivewsid) && driveName(x).toLocaleLowerCase() === named);
+ if (made && driveName(made) !== shown[i].name) await api.driveRename(made.drivewsid, shown[i].name);
+ }
// The backend has read the folder again: the library has the copy, so no new look.
if (into === hereRef.current) await refresh(false);
} catch (e) {
@@ -1210,27 +1246,54 @@ export function DriveView() {
if (!c) return;
// Something else copied since (text in another app): that is what is on the clipboard.
if (c.text !== null && board?.text != null && board.text !== c.text) return;
- if (!move) {
- await copyHere(c.items);
- return;
- }
const into = hereRef.current;
- if (c.from === into) return;
+ if (move && c.from === into) return;
const inside = trailRef.current.map((t) => t.id);
- const names = new Set(itemsRef.current.map((i) => driveName(i).toLocaleLowerCase()));
- const clash = c.items.find((i) => names.has(driveName(i).toLocaleLowerCase()));
const insideItself = c.items.find((i) => inside.includes(i.drivewsid));
- if (clash || insideItself) {
- setError(
- clash
- ? `An item named \u201c${driveName(clash)}\u201d is already in this folder, so nothing was moved.`
- : `\u201c${driveName(insideItself!)}\u201d can\u2019t be moved into a folder inside itself.`,
- );
+ if (move && insideItself) {
+ setError(`\u201c${driveName(insideItself)}\u201d can\u2019t be moved into a folder inside itself.`);
+ return;
+ }
+ // Pasted where it was copied, a copy is a duplicate ("Report copy.pdf"), as in Finder.
+ // Anywhere else a name already there is a question first: Keep Both or Replace.
+ const clashing = c.from === into ? [] : [...clashesHere(c.items.filter((i) => !inside.includes(i.drivewsid))).keys()];
+ let how: Clash = null;
+ if (clashing.length) {
+ how = await askClash(c.items.filter((i) => clashing.includes(i.drivewsid)));
+ if (!how) return;
+ }
+ if (!move) {
+ await copyHere(c.items, how);
return;
}
// Moved, it is no longer where it was copied: nothing is left to paste.
setClip(null);
- await moveAll(c.items, into, c.from);
+ const clashes = clashesHere(c.items);
+ if (how === "replace" && clashes.size) {
+ const old = [...clashes.values()];
+ setGone((g) => new Set([...g, ...old.map((o) => goneKey(into, o.drivewsid))]));
+ for (const o of old) await api.driveDelete(o.drivewsid).catch(() => {});
+ }
+ let going = c.items;
+ if (how === "keep" && clashes.size) {
+ // Named as Keep Both names it before it goes, so the folder never holds two of one name.
+ const taken = new Set(itemsRef.current.map(driveName));
+ const renamed = new Map<string, DriveItem>();
+ for (const item of c.items.filter((i) => clashes.has(i.drivewsid))) {
+ const ext = isContainer(item) ? null : item.extension;
+ const name = keepBothName(item.name, ext, taken);
+ taken.add(name);
+ try {
+ await api.driveRename(item.drivewsid, name);
+ } catch (e) {
+ setError(messageOf(e));
+ return;
+ }
+ renamed.set(item.drivewsid, { ...item, name: ext ? name.slice(0, -(ext.length + 1)) : name });
+ }
+ going = c.items.map((i) => renamed.get(i.drivewsid) ?? i);
+ }
+ await moveAll(going, into, c.from);
};
const chooseAndUpload = useCallback(
@@ -1746,7 +1809,9 @@ export function DriveView() {
aria-label={here.name}
>
{pending
- .filter((p) => p.folder === here.id && !items.some((i) => driveName(i) === p.name))
+ // Shown until a row of its name is there — not one leaving (a Replace's): that one
+ // goes at once, and the copy taking its place shows as being made.
+ .filter((p) => p.folder === here.id && !items.some((i) => driveName(i) === p.name && !gone.has(goneKey(here.id, i.drivewsid))))
.map((p) => (
<li key={p.key} className="drive-row is-busy" aria-busy="true">
<span className="drive-row-hit">
@@ -1819,6 +1884,20 @@ export function DriveView() {
/>
)}
+ {asking && (
+ <ConfirmSheet<"keep" | "replace">
+ title={asking.items.length === 1
+ ? `\u201c${driveName(asking.items[0])}\u201d is already in this folder`
+ : `${asking.items.length} items with these names are already in this folder`}
+ choices={[
+ { label: "Keep Both", value: "keep", primary: true, focus: true },
+ { label: "Replace", value: "replace", danger: true },
+ ]}
+ onAnswer={(how) => asking.answer(how)}
+ onCancel={() => asking.answer(null)}
+ />
+ )}
+
{menu && (() => {
// A right-click on the selection is for all of it, as Finder's menu is.
const many = pickedItems.length > 1 && picked.includes(menu.item.drivewsid) ? pickedItems : null;