mirror of
https://seed.radicle.dev/rad:z4V1sjrXqjvFdnCUbxPFqd5p4DtH5.git
synced 2026-11-21 14:20:42 +08:00
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".
This commit is contained in:
@@ -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<types::diff::Diff, Error> {
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<SaveDiffBody>,
|
||||
) -> 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,
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { writeToClipboard } from "@app/lib/invoke";
|
||||
|
||||
import Icon from "@app/components/Icon.svelte";
|
||||
|
||||
interface Props {
|
||||
// Produces the text lazily, so large content isn't built until clicked.
|
||||
text: () => string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
const { text, title = "Copy" }: Props = $props();
|
||||
|
||||
let copied = $state(false);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
async function copy() {
|
||||
await writeToClipboard(text());
|
||||
copied = true;
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => {
|
||||
copied = false;
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
$effect(() => () => clearTimeout(timer));
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.copy {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
color: var(--color-text-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.copy:hover {
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
</style>
|
||||
|
||||
<button class="copy" {title} onclick={copy}>
|
||||
<Icon name={copied ? "checkmark" : "clipboard"} />
|
||||
</button>
|
||||
@@ -0,0 +1,101 @@
|
||||
<script lang="ts">
|
||||
import type { ComponentProps } from "svelte";
|
||||
|
||||
import { saveToDisk, writeToClipboard } from "@app/lib/invoke";
|
||||
|
||||
import DropdownList from "@app/components/DropdownList.svelte";
|
||||
import DropdownListItem from "@app/components/DropdownListItem.svelte";
|
||||
import Icon from "@app/components/Icon.svelte";
|
||||
import Popover, { closeFocused } from "@app/components/Popover.svelte";
|
||||
|
||||
interface Props {
|
||||
// Built lazily so large diff text isn't materialized until an action runs.
|
||||
text: () => string;
|
||||
// Default filename offered when saving to disk.
|
||||
fileName: string;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
const { text, fileName, title = "Diff actions" }: Props = $props();
|
||||
|
||||
let expanded = $state(false);
|
||||
|
||||
type Action = {
|
||||
label: string;
|
||||
icon: ComponentProps<typeof Icon>["name"];
|
||||
run: () => Promise<void>;
|
||||
};
|
||||
|
||||
const actions: Action[] = [
|
||||
{
|
||||
label: "Copy to clipboard",
|
||||
icon: "copy",
|
||||
run: () => writeToClipboard(text()),
|
||||
},
|
||||
{
|
||||
label: "Save to disk",
|
||||
icon: "download",
|
||||
run: () => saveToDisk(fileName, text()),
|
||||
},
|
||||
];
|
||||
|
||||
async function run(action: Action) {
|
||||
closeFocused();
|
||||
try {
|
||||
await action.run();
|
||||
} catch (e) {
|
||||
console.error(`${action.label} failed`, e);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.trigger {
|
||||
background: none;
|
||||
border: none;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
color: var(--color-text-secondary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.trigger:hover,
|
||||
.trigger.active {
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
.menu {
|
||||
padding: 0.25rem;
|
||||
background-color: var(--color-surface-canvas);
|
||||
border: 1px solid var(--color-border-subtle);
|
||||
border-radius: var(--border-radius-sm);
|
||||
}
|
||||
</style>
|
||||
|
||||
<Popover placement="bottom-end" bind:expanded>
|
||||
{#snippet toggle(onclick)}
|
||||
<button
|
||||
class="trigger"
|
||||
class:active={expanded}
|
||||
{title}
|
||||
{onclick}
|
||||
aria-label={title}>
|
||||
<Icon name="ellipsis-vertical" />
|
||||
</button>
|
||||
{/snippet}
|
||||
|
||||
{#snippet popover()}
|
||||
<div class="menu">
|
||||
<DropdownList items={actions}>
|
||||
{#snippet item(action)}
|
||||
<DropdownListItem
|
||||
selected={false}
|
||||
styleGap="0.5rem"
|
||||
onclick={() => run(action)}>
|
||||
<Icon name={action.icon} />
|
||||
{action.label}
|
||||
</DropdownListItem>
|
||||
{/snippet}
|
||||
</DropdownList>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
@@ -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 @@
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
<CopyButton text={() => fileDiffToText(row.file)} title="Copy file diff" />
|
||||
<DiffActions
|
||||
text={() => fileDiffToText(row.file)}
|
||||
fileName={fileDiffName(row.file)}
|
||||
title="File diff actions" />
|
||||
</div>
|
||||
{:else if row.type === "hunk-header"}
|
||||
<div class="line hunk-header">
|
||||
|
||||
+122
-18
@@ -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<number>();
|
||||
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`;
|
||||
}
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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
|
||||
</div>
|
||||
<DiffStatBadge stats={diff.stats} />
|
||||
<CopyButton text={() => diffToText(diff)} title="Copy diff" />
|
||||
<DiffActions
|
||||
text={() => diffToText(diff)}
|
||||
fileName={`${formatOid(commit.id)}.diff`}
|
||||
title="Diff actions" />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Reference in New Issue
Block a user