refactor(patch-editor): streamline patch saving and loading logic

- Removed the local state for saving status and integrated loading state directly from the mutation hook.
- Updated the saveAsPatch function to handle success and error notifications more cleanly.
- Adjusted the file content loading to ensure it retrieves the latest data, improving user experience and consistency in the PatchEditor component.
- Refactored API calls in the patch router to unify patch retrieval logic for applications and composes, enhancing maintainability.
This commit is contained in:
Mauricio Siu
2026-02-17 00:41:46 -06:00
parent 88f387dd83
commit 20320639ce
3 changed files with 36 additions and 76 deletions
@@ -41,7 +41,6 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
const [expandedFolders, setExpandedFolders] = useState<Set<string>>( const [expandedFolders, setExpandedFolders] = useState<Set<string>>(
new Set(), new Set(),
); );
const [isSaving, setIsSaving] = useState(false);
const { data: directories, isLoading: isDirLoading } = const { data: directories, isLoading: isDirLoading } =
api.patch.readRepoDirectories.useQuery( api.patch.readRepoDirectories.useQuery(
@@ -49,27 +48,13 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
{ enabled: !!repoPath }, { enabled: !!repoPath },
); );
const saveAsPatch = api.patch.saveFileAsPatch.useMutation({ const { mutateAsync: saveAsPatch, isLoading: isSavingPatch } =
onSuccess: (result) => { api.patch.saveFileAsPatch.useMutation();
setIsSaving(false);
if (result.deleted) {
toast.success("No changes - patch removed");
} else {
toast.success("Patch saved");
}
setOriginalContent(fileContent);
},
onError: () => {
setIsSaving(false);
toast.error("Failed to save patch");
},
});
// Read file content when selected
const { data: fileData, isFetching: isFileLoading } = const { data: fileData, isFetching: isFileLoading } =
api.patch.readRepoFile.useQuery( api.patch.readRepoFile.useQuery(
{ {
id: id || "", id,
type, type,
repoPath, repoPath,
filePath: selectedFile || "", filePath: selectedFile || "",
@@ -77,8 +62,6 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
{ {
enabled: !!selectedFile, enabled: !!selectedFile,
onSuccess: (data) => { onSuccess: (data) => {
setFileContent(data.content);
setOriginalContent(data.content);
if (data.patchError) { if (data.patchError) {
toast.error(data.patchErrorMessage || "Failed to apply patch"); toast.error(data.patchErrorMessage || "Failed to apply patch");
} }
@@ -104,14 +87,19 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
const handleSave = () => { const handleSave = () => {
if (!selectedFile) return; if (!selectedFile) return;
setIsSaving(true); saveAsPatch({
saveAsPatch.mutate({
id, id,
type, type,
repoPath, repoPath,
filePath: selectedFile, filePath: selectedFile,
content: fileContent, content: fileContent,
}); })
.then(() => {
toast.success("Patch saved");
})
.catch(() => {
toast.error("Failed to save patch");
});
}; };
const hasChanges = fileContent !== originalContent; const hasChanges = fileContent !== originalContent;
@@ -192,8 +180,8 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
</div> </div>
</div> </div>
{selectedFile && ( {selectedFile && (
<Button onClick={handleSave} disabled={isSaving || !hasChanges}> <Button onClick={handleSave} disabled={isSavingPatch || !hasChanges}>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} {isSavingPatch && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
<Save className="mr-2 h-4 w-4" /> <Save className="mr-2 h-4 w-4" />
Save Patch Save Patch
</Button> </Button>
@@ -201,7 +189,6 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
</CardHeader> </CardHeader>
<CardContent className="p-0"> <CardContent className="p-0">
<div className="grid grid-cols-[250px_1fr] border-t h-[600px]"> <div className="grid grid-cols-[250px_1fr] border-t h-[600px]">
{/* File Tree */}
<div className="border-r h-full overflow-hidden"> <div className="border-r h-full overflow-hidden">
<ScrollArea className="h-full"> <ScrollArea className="h-full">
<div className="p-2"> <div className="p-2">
@@ -219,7 +206,6 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
</div> </div>
</ScrollArea> </ScrollArea>
</div> </div>
{/* Editor */}
<div className="h-full overflow-hidden relative"> <div className="h-full overflow-hidden relative">
{isFileLoading ? ( {isFileLoading ? (
<div className="flex items-center justify-center h-full"> <div className="flex items-center justify-center h-full">
@@ -227,7 +213,7 @@ export const PatchEditor = ({ id, type, repoPath, onClose }: Props) => {
</div> </div>
) : selectedFile ? ( ) : selectedFile ? (
<CodeEditor <CodeEditor
value={fileContent} value={fileData?.content || ""}
onChange={(value) => setFileContent(value || "")} onChange={(value) => setFileContent(value || "")}
className="h-full w-full" className="h-full w-full"
wrapperClassName="h-full" wrapperClassName="h-full"
+14 -32
View File
@@ -51,8 +51,8 @@ const getApplicationGitConfig = (
}; };
case "gitea": case "gitea":
return { return {
gitUrl: app.gitea?.gitUrl gitUrl: app.gitea?.giteaUrl
? `${app.gitea.gitUrl}/${app.giteaOwner}/${app.giteaRepository}.git` ? `${app.gitea.giteaUrl}/${app.giteaOwner}/${app.giteaRepository}.git`
: "", : "",
gitBranch: app.giteaBranch || "main", gitBranch: app.giteaBranch || "main",
sshKeyId: null, sshKeyId: null,
@@ -93,8 +93,8 @@ const getComposeGitConfig = (
}; };
case "gitea": case "gitea":
return { return {
gitUrl: compose.gitea?.gitUrl gitUrl: compose.gitea?.giteaUrl
? `${compose.gitea.gitUrl}/${compose.giteaOwner}/${compose.giteaRepository}.git` ? `${compose.gitea.giteaUrl}/${compose.giteaOwner}/${compose.giteaRepository}.git`
: "", : "",
gitBranch: compose.giteaBranch || "main", gitBranch: compose.giteaBranch || "main",
sshKeyId: null, sshKeyId: null,
@@ -343,7 +343,6 @@ export const patchRouter = createTRPCRouter({
) )
.query(async ({ input, ctx }) => { .query(async ({ input, ctx }) => {
let serverId: string | null = null; let serverId: string | null = null;
let patchContent: string | undefined;
if (input.type === "application") { if (input.type === "application") {
const app = await findApplicationById(input.id); const app = await findApplicationById(input.id);
@@ -357,16 +356,6 @@ export const patchRouter = createTRPCRouter({
}); });
} }
serverId = app.serverId; serverId = app.serverId;
// Check if patch exists for this file
const existingPatch = await findPatchByFilePath(
input.filePath,
input.id,
undefined,
);
if (existingPatch?.enabled) {
patchContent = existingPatch.content;
}
} else if (input.type === "compose") { } else if (input.type === "compose") {
const compose = await findComposeById(input.id); const compose = await findComposeById(input.id);
if ( if (
@@ -379,27 +368,22 @@ export const patchRouter = createTRPCRouter({
}); });
} }
serverId = compose.serverId; serverId = compose.serverId;
// Check if patch exists for this file
const existingPatch = await findPatchByFilePath(
input.filePath,
undefined,
input.id,
);
if (existingPatch?.enabled) {
patchContent = existingPatch.content;
}
} else { } else {
throw new TRPCError({ throw new TRPCError({
code: "BAD_REQUEST", code: "BAD_REQUEST",
message: "Either applicationId or composeId must be provided", message: "Either applicationId or composeId must be provided",
}); });
} }
const existingPatch = await findPatchByFilePath(
input.filePath,
input.id,
input.type,
);
return await readPatchRepoFile( return await readPatchRepoFile(
input.repoPath, input.repoPath,
input.filePath, input.filePath,
patchContent, existingPatch?.enabled ? existingPatch?.content : undefined,
serverId, serverId,
); );
}), }),
@@ -461,7 +445,7 @@ export const patchRouter = createTRPCRouter({
const existingPatch = await findPatchByFilePath( const existingPatch = await findPatchByFilePath(
input.filePath, input.filePath,
input.id, input.id,
input.id, input.type,
); );
if (existingPatch) { if (existingPatch) {
await deletePatch(existingPatch.patchId); await deletePatch(existingPatch.patchId);
@@ -473,22 +457,20 @@ export const patchRouter = createTRPCRouter({
const existingPatch = await findPatchByFilePath( const existingPatch = await findPatchByFilePath(
input.filePath, input.filePath,
input.id, input.id,
input.id, input.type,
); );
if (existingPatch) { if (existingPatch) {
// Update existing patch
await updatePatch(existingPatch.patchId, { content: patchContent }); await updatePatch(existingPatch.patchId, { content: patchContent });
return { deleted: false, patchId: existingPatch.patchId }; return { deleted: false, patchId: existingPatch.patchId };
} }
// Create new patch
const newPatch = await createPatch({ const newPatch = await createPatch({
filePath: input.filePath, filePath: input.filePath,
content: patchContent, content: patchContent,
enabled: true, enabled: true,
applicationId: input.id, applicationId: input.type === "application" ? input.id : undefined,
composeId: input.id, composeId: input.type === "compose" ? input.id : undefined,
}); });
return { deleted: false, patchId: newPatch.patchId }; return { deleted: false, patchId: newPatch.patchId };
+8 -16
View File
@@ -76,23 +76,15 @@ export const findPatchesByComposeId = async (composeId: string) => {
export const findPatchByFilePath = async ( export const findPatchByFilePath = async (
filePath: string, filePath: string,
applicationId?: string, id: string,
composeId?: string, type: "application" | "compose",
) => { ) => {
if (applicationId) { return await db.query.patch.findFirst({
return await db.query.patch.findFirst({ where:
where: and( type === "application"
eq(patch.filePath, filePath), ? and(eq(patch.filePath, filePath), eq(patch.applicationId, id))
eq(patch.applicationId, applicationId), : and(eq(patch.filePath, filePath), eq(patch.composeId, id)),
), });
});
}
if (composeId) {
return await db.query.patch.findFirst({
where: and(eq(patch.filePath, filePath), eq(patch.composeId, composeId)),
});
}
return null;
}; };
export const updatePatch = async (patchId: string, data: Partial<Patch>) => { export const updatePatch = async (patchId: string, data: Partial<Patch>) => {