From 5b121b131a43d6674ddb14fd443faf1bb1a2d4a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C5=ABdolfs=20O=C5=A1i=C5=86=C5=A1?= Date: Thu, 18 Jun 2026 14:31:10 +0200 Subject: [PATCH] Add a diff actions menu with copy and save to disk Replace the file-header and whole-diff copy buttons with a popover menu offering "Copy to clipboard" and "Save to disk". --- crates/radicle-tauri/src/commands/diff.rs | 22 ++++ crates/radicle-tauri/src/lib.rs | 1 + crates/test-http-api/src/api.rs | 28 +++++ src/components/CopyButton.svelte | 46 ------- src/components/DiffActions.svelte | 101 ++++++++++++++++ src/components/DiffRow.svelte | 9 +- src/lib/diffText.ts | 140 +++++++++++++++++++--- src/lib/invoke.ts | 15 +++ src/views/repo/RepoCommit.svelte | 7 +- 9 files changed, 300 insertions(+), 69 deletions(-) delete mode 100644 src/components/CopyButton.svelte create mode 100644 src/components/DiffActions.svelte diff --git a/crates/radicle-tauri/src/commands/diff.rs b/crates/radicle-tauri/src/commands/diff.rs index c2eae9b8b..968058a5b 100644 --- a/crates/radicle-tauri/src/commands/diff.rs +++ b/crates/radicle-tauri/src/commands/diff.rs @@ -2,6 +2,7 @@ use radicle::identity; use radicle_types as types; use radicle_types::error::Error; use radicle_types::traits::repo::Repo; +use tauri_plugin_dialog::DialogExt; use crate::AppState; @@ -13,3 +14,24 @@ pub async fn get_diff( ) -> Result { ctx.get_diff(rid, options) } + +#[tauri::command] +pub async fn save_diff_to_disk( + app_handle: tauri::AppHandle, + name: String, + content: String, +) -> Result<(), Error> { + let Some(path) = app_handle + .dialog() + .file() + .set_file_name(name) + .blocking_save_file() + else { + // User cancelled the save dialog. + return Ok(()); + }; + let path = path.into_path()?; + std::fs::write(path, content)?; + + Ok(()) +} diff --git a/crates/radicle-tauri/src/lib.rs b/crates/radicle-tauri/src/lib.rs index 1faad32a9..576f44ab5 100644 --- a/crates/radicle-tauri/src/lib.rs +++ b/crates/radicle-tauri/src/lib.rs @@ -58,6 +58,7 @@ pub fn run() { cob::save_embed_by_path, cob::save_embed_to_disk, diff::get_diff, + diff::save_diff_to_disk, repo::get_commit_diff, inbox::clear_notifications, inbox::notification_count, diff --git a/crates/test-http-api/src/api.rs b/crates/test-http-api/src/api.rs index 6f1a49e64..acdca12ee 100644 --- a/crates/test-http-api/src/api.rs +++ b/crates/test-http-api/src/api.rs @@ -96,6 +96,7 @@ pub fn router(ctx: Context) -> Router { .route("/repo_tree", post(tree_handler)) .route("/repo_blob", post(blob_handler)) .route("/get_diff", post(diff_handler)) + .route("/save_diff_to_disk", post(save_diff_handler)) .route("/get_commit_diff", post(commit_diff_handler)) .route("/list_repo_commits", post(list_repo_commits_handler)) .route("/repo_commit_count", post(repo_commit_count_handler)) @@ -312,6 +313,33 @@ async fn diff_handler( Ok::<_, Error>(Json(info)) } +#[derive(Serialize, Deserialize)] +struct SaveDiffBody { + pub name: String, + pub content: String, +} + +/// Mirrors the Tauri `save_diff_to_disk` command. There is no native save +/// dialog on this driver, so the file lands in the OS temp directory under +/// the suggested name (reduced to its basename — the server is reachable +/// over the network, so `name` must not traverse paths). The web frontend +/// normally falls back to a browser download instead of calling this; the +/// route exists to keep the command surface mirrored and testable. +async fn save_diff_handler( + Json(SaveDiffBody { name, content }): Json, +) -> impl IntoResponse { + let name = PathBuf::from(name); + let Some(file_name) = name.file_name() else { + return Err(Error::Io(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "suggested file name has no basename component", + ))); + }; + std::fs::write(std::env::temp_dir().join(file_name), content)?; + + Ok::<_, Error>(Json(())) +} + #[derive(Serialize, Deserialize)] struct CommitDiffBody { pub rid: identity::RepoId, diff --git a/src/components/CopyButton.svelte b/src/components/CopyButton.svelte deleted file mode 100644 index 5d42b50de..000000000 --- a/src/components/CopyButton.svelte +++ /dev/null @@ -1,46 +0,0 @@ - - - - - diff --git a/src/components/DiffActions.svelte b/src/components/DiffActions.svelte new file mode 100644 index 000000000..2c709fe50 --- /dev/null +++ b/src/components/DiffActions.svelte @@ -0,0 +1,101 @@ + + + + + + {#snippet toggle(onclick)} + + {/snippet} + + {#snippet popover()} + + {/snippet} + diff --git a/src/components/DiffRow.svelte b/src/components/DiffRow.svelte index eb7a5abe7..fa22870e7 100644 --- a/src/components/DiffRow.svelte +++ b/src/components/DiffRow.svelte @@ -11,11 +11,11 @@ rangeAnchorsFromCodeLocation, } from "@app/lib/diffComments"; import type { DiffRow } from "@app/lib/diffRows"; - import { fileDiffToText } from "@app/lib/diffText"; + import { fileDiffName, fileDiffToText } from "@app/lib/diffText"; import * as roles from "@app/lib/roles"; import CommentToggleInput from "@app/components/CommentToggleInput.svelte"; - import CopyButton from "@app/components/CopyButton.svelte"; + import DiffActions from "@app/components/DiffActions.svelte"; import Icon from "@app/components/Icon.svelte"; import Path from "@app/components/Path.svelte"; import ThreadComponent from "@app/components/Thread.svelte"; @@ -479,7 +479,10 @@ {/if} {/if} - fileDiffToText(row.file)} title="Copy file diff" /> + fileDiffToText(row.file)} + fileName={fileDiffName(row.file)} + title="File diff actions" /> {:else if row.type === "hunk-header"}
diff --git a/src/lib/diffText.ts b/src/lib/diffText.ts index 22095d42b..4ff8244c8 100644 --- a/src/lib/diffText.ts +++ b/src/lib/diffText.ts @@ -1,15 +1,30 @@ import type { Diff } from "@bindings/diff/Diff"; +import type { EofNewLine } from "@bindings/diff/EofNewLine"; import type { FileDiff } from "@bindings/diff/FileDiff"; +import type { FileMode } from "@bindings/diff/FileMode"; +import type { Hunk } from "@bindings/diff/Hunk"; // Selection across off-screen lines isn't possible once the diff is -// virtualized, so these build copyable unified-diff text straight from the -// model for the "copy file" / "copy diff" buttons. +// virtualized, so these build copyable patch text straight from the model for +// the "copy" / "save to disk" actions. The output is `git diff` format that +// `git apply` accepts (binary files excepted — their bytes aren't available). -function filePath(file: FileDiff): string { - if (file.status === "moved" || file.status === "copied") { - return `${file.oldPath} → ${file.newPath}`; +const NULL_OID = "0000000000000000000000000000000000000000"; +const NO_NEWLINE = "\\ No newline at end of file"; + +function gitMode(mode: FileMode): string { + switch (mode) { + case "blob": + return "100644"; + case "blobExecutable": + return "100755"; + case "link": + return "120000"; + case "tree": + return "040000"; + case "commit": + return "160000"; } - return file.path; } // Diff line/header text from the backend keeps its trailing newline; strip it @@ -18,23 +33,112 @@ function stripEol(s: string): string { return s.replace(/\r?\n$/, ""); } -export function fileDiffToText(file: FileDiff): string { - const lines: string[] = [filePath(file)]; - if (file.diff.type === "plain") { - for (const hunk of file.diff.hunks) { - lines.push(stripEol(hunk.header)); - for (const m of hunk.lines) { - const prefix = - m.type === "addition" ? "+" : m.type === "deletion" ? "-" : " "; - lines.push(`${prefix}${stripEol(m.line)}`); +// The hunk headers and content lines, with "\ No newline at end of file" +// markers placed after the last line of whichever side lacks a trailing +// newline (mirroring what git itself emits). +function hunkBody(hunks: Hunk[], eof: EofNewLine): string[] { + const out: string[] = []; + let lastOld = -1; + let lastNew = -1; + for (const hunk of hunks) { + out.push(stripEol(hunk.header)); + for (const m of hunk.lines) { + if (m.type === "addition") { + out.push(`+${stripEol(m.line)}`); + lastNew = out.length - 1; + } else if (m.type === "deletion") { + out.push(`-${stripEol(m.line)}`); + lastOld = out.length - 1; + } else { + out.push(` ${stripEol(m.line)}`); + lastOld = out.length - 1; + lastNew = out.length - 1; } } - } else if (file.diff.type === "binary") { - lines.push("Binary file"); } + + const marks = new Set(); + if ((eof === "oldMissing" || eof === "bothMissing") && lastOld >= 0) { + marks.add(lastOld); + } + if ((eof === "newMissing" || eof === "bothMissing") && lastNew >= 0) { + marks.add(lastNew); + } + // Insert from the back so earlier indices stay valid. + for (const i of [...marks].sort((a, b) => b - a)) { + out.splice(i + 1, 0, NO_NEWLINE); + } + return out; +} + +export function fileDiffToText(file: FileDiff): string { + const lines: string[] = []; + + if (file.status === "added") { + lines.push(`diff --git a/${file.path} b/${file.path}`); + lines.push(`new file mode ${gitMode(file.new.mode)}`); + lines.push(`index ${NULL_OID}..${file.new.oid}`); + lines.push("--- /dev/null"); + lines.push(`+++ b/${file.path}`); + } else if (file.status === "deleted") { + lines.push(`diff --git a/${file.path} b/${file.path}`); + lines.push(`deleted file mode ${gitMode(file.old.mode)}`); + lines.push(`index ${file.old.oid}..${NULL_OID}`); + lines.push(`--- a/${file.path}`); + lines.push("+++ /dev/null"); + } else if (file.status === "modified") { + lines.push(`diff --git a/${file.path} b/${file.path}`); + if (file.old.mode !== file.new.mode) { + lines.push(`old mode ${gitMode(file.old.mode)}`); + lines.push(`new mode ${gitMode(file.new.mode)}`); + lines.push(`index ${file.old.oid}..${file.new.oid}`); + } else { + lines.push( + `index ${file.old.oid}..${file.new.oid} ${gitMode(file.new.mode)}`, + ); + } + lines.push(`--- a/${file.path}`); + lines.push(`+++ b/${file.path}`); + } else { + // moved or copied + const verb = file.status === "moved" ? "rename" : "copy"; + const hasHunks = file.diff.type === "plain" && file.diff.hunks.length > 0; + lines.push(`diff --git a/${file.oldPath} b/${file.newPath}`); + if (!hasHunks) { + lines.push("similarity index 100%"); + } + lines.push(`${verb} from ${file.oldPath}`); + lines.push(`${verb} to ${file.newPath}`); + if (hasHunks) { + lines.push( + `index ${file.old.oid}..${file.new.oid} ${gitMode(file.new.mode)}`, + ); + lines.push(`--- a/${file.oldPath}`); + lines.push(`+++ b/${file.newPath}`); + } + } + + if (file.diff.type === "plain") { + lines.push(...hunkBody(file.diff.hunks, file.diff.eof)); + } else if (file.diff.type === "binary") { + lines.push("Binary files differ"); + } + return lines.join("\n"); } export function diffToText(diff: Diff): string { - return diff.files.map(fileDiffToText).join("\n\n"); + // git output concatenates file sections with no separator; end with a + // trailing newline so `git apply` reads the final hunk cleanly. + return diff.files.map(fileDiffToText).join("\n") + "\n"; +} + +// A default filename for saving a single file's diff to disk. +export function fileDiffName(file: FileDiff): string { + const path = + file.status === "moved" || file.status === "copied" + ? file.newPath + : file.path; + const base = path.split("/").pop() || "file"; + return `${base}.diff`; } diff --git a/src/lib/invoke.ts b/src/lib/invoke.ts index 286aa9bf5..aee87eb3d 100644 --- a/src/lib/invoke.ts +++ b/src/lib/invoke.ts @@ -212,4 +212,19 @@ export async function writeToClipboard( } } +export async function saveToDisk(fileName: string, text: string) { + if (window.__TAURI_INTERNALS__) { + // The backend opens the native save dialog and writes the file. + await tauri.invoke("save_diff_to_disk", { name: fileName, content: text }); + } else { + // No native dialog outside Tauri (test/http mode): trigger a download. + const url = URL.createObjectURL(new Blob([text], { type: "text/plain" })); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = fileName; + anchor.click(); + URL.revokeObjectURL(url); + } +} + export { InvokeError }; diff --git a/src/views/repo/RepoCommit.svelte b/src/views/repo/RepoCommit.svelte index 9a6475b92..30177b2b6 100644 --- a/src/views/repo/RepoCommit.svelte +++ b/src/views/repo/RepoCommit.svelte @@ -15,7 +15,7 @@ } from "@app/lib/utils"; import Changeset from "@app/components/Changeset.svelte"; - import CopyButton from "@app/components/CopyButton.svelte"; + import DiffActions from "@app/components/DiffActions.svelte"; import DiffStatBadge from "@app/components/DiffStatBadge.svelte"; import ExternalLink from "@app/components/ExternalLink.svelte"; import Icon from "@app/components/Icon.svelte"; @@ -229,7 +229,10 @@ {pluralize("file", diff.stats.filesChanged)} changed
- diffToText(diff)} title="Copy diff" /> + diffToText(diff)} + fileName={`${formatOid(commit.id)}.diff`} + title="Diff actions" />