snapshot of https://github.com/mountain-loop/yaak.git (main, 2026-09-23; blobs > 131072B omitted)
This commit is contained in:
481
apps/yaak-client/components/git/GitCommitDialog.tsx
Normal file
481
apps/yaak-client/components/git/GitCommitDialog.tsx
Normal file
@@ -0,0 +1,481 @@
|
||||
import type { GitStatusEntry } from "@yaakapp-internal/git";
|
||||
import { useGit } from "@yaakapp-internal/git";
|
||||
import type {
|
||||
Environment,
|
||||
Folder,
|
||||
GrpcRequest,
|
||||
HttpRequest,
|
||||
WebsocketRequest,
|
||||
Workspace,
|
||||
} from "@yaakapp-internal/models";
|
||||
import { Banner, HStack, Icon, InlineCode, SplitLayout } from "@yaakapp-internal/ui";
|
||||
import classNames from "classnames";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { modelToYaml } from "../../lib/diffYaml";
|
||||
import { trackFeatureUsage } from "../../lib/featureFeedback";
|
||||
import { resolvedModelName } from "../../lib/resolvedModelName";
|
||||
import { showConfirm } from "../../lib/confirm";
|
||||
import { showErrorToast } from "../../lib/toast";
|
||||
import { sync } from "../../init/sync";
|
||||
import { CommercialUseBanner } from "../CommercialUseBanner";
|
||||
import { Button } from "../core/Button";
|
||||
import type { CheckboxProps } from "../core/Checkbox";
|
||||
import { Checkbox } from "../core/Checkbox";
|
||||
import type { CheckboxTreeNode } from "../core/CheckboxTree";
|
||||
import { CheckboxTree } from "../core/CheckboxTree";
|
||||
import { DiffViewer } from "../core/Editor/DiffViewer";
|
||||
import { Input } from "../core/Input";
|
||||
import { Separator } from "../core/Separator";
|
||||
import { EmptyStateText } from "../EmptyStateText";
|
||||
import { useGitCallbacks } from "./callbacks";
|
||||
import { handlePushResult } from "./git-util";
|
||||
|
||||
interface Props {
|
||||
syncDir: string;
|
||||
onDone: () => void;
|
||||
workspace: Workspace;
|
||||
}
|
||||
|
||||
interface CommitTreeNode {
|
||||
model: HttpRequest | GrpcRequest | WebsocketRequest | Folder | Environment | Workspace;
|
||||
status: GitStatusEntry;
|
||||
children: CommitTreeNode[];
|
||||
ancestors: CommitTreeNode[];
|
||||
}
|
||||
|
||||
export function GitCommitDialog({ syncDir, onDone, workspace }: Props) {
|
||||
const callbacks = useGitCallbacks(syncDir);
|
||||
const [{ status }, { commit, commitAndPush, add, unstage, restore }] = useGit(syncDir, callbacks);
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [commitError, setCommitError] = useState<string | null>(null);
|
||||
const [message, setMessage] = useState<string>("");
|
||||
const [selectedEntry, setSelectedEntry] = useState<GitStatusEntry | null>(null);
|
||||
|
||||
const handleCreateCommit = async () => {
|
||||
setCommitError(null);
|
||||
try {
|
||||
await commit.mutateAsync({ message });
|
||||
trackFeatureUsage("git-sync");
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setCommitError(String(err));
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateCommitAndPush = async () => {
|
||||
setIsPushing(true);
|
||||
try {
|
||||
const r = await commitAndPush.mutateAsync({ message });
|
||||
handlePushResult(r);
|
||||
trackFeatureUsage("git-sync");
|
||||
onDone();
|
||||
} catch (err) {
|
||||
showErrorToast({
|
||||
id: "git-commit-and-push-error",
|
||||
title: "Error committing and pushing",
|
||||
message: String(err),
|
||||
});
|
||||
} finally {
|
||||
setIsPushing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const { internalEntries, externalEntries, allEntries } = useMemo(() => {
|
||||
const allEntries = [];
|
||||
const yaakEntries = [];
|
||||
const externalEntries = [];
|
||||
|
||||
for (const entry of status.data?.entries ?? []) {
|
||||
allEntries.push(entry);
|
||||
if (entry.next == null && entry.prev == null) {
|
||||
externalEntries.push(entry);
|
||||
} else {
|
||||
yaakEntries.push(entry);
|
||||
}
|
||||
}
|
||||
return { internalEntries: yaakEntries, externalEntries, allEntries };
|
||||
}, [status.data?.entries]);
|
||||
|
||||
const hasAddedAnything = allEntries.find((e) => e.staged) != null;
|
||||
const hasAnythingToAdd = allEntries.find((e) => e.status !== "current") != null;
|
||||
|
||||
const tree: CommitTreeNode | null = useMemo(() => {
|
||||
const next = (
|
||||
model: CommitTreeNode["model"],
|
||||
ancestors: CommitTreeNode[],
|
||||
): CommitTreeNode | null => {
|
||||
const statusEntry = internalEntries?.find((s) => s.relaPath.includes(model.id));
|
||||
if (statusEntry == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const node: CommitTreeNode = {
|
||||
model,
|
||||
status: statusEntry,
|
||||
children: [],
|
||||
ancestors,
|
||||
};
|
||||
|
||||
for (const entry of internalEntries) {
|
||||
const childModel = entry.next ?? entry.prev;
|
||||
|
||||
// Should never happen because we're iterating internalEntries
|
||||
if (childModel == null) continue;
|
||||
|
||||
// TODO: Figure out why not all of these show up
|
||||
if ("folderId" in childModel && childModel.folderId != null) {
|
||||
if (childModel.folderId === model.id) {
|
||||
const c = next(childModel, [...ancestors, node]);
|
||||
if (c != null) node.children.push(c);
|
||||
}
|
||||
} else if ("workspaceId" in childModel && childModel.workspaceId === model.id) {
|
||||
const c = next(childModel, [...ancestors, node]);
|
||||
if (c != null) node.children.push(c);
|
||||
} else {
|
||||
// Do nothing
|
||||
}
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
return next(workspace, []);
|
||||
}, [workspace, internalEntries]);
|
||||
|
||||
const treeNode: CheckboxTreeNode<CommitTreeNode> | null = useMemo(() => {
|
||||
const toTreeNode = (n: CommitTreeNode): CheckboxTreeNode<CommitTreeNode> => ({
|
||||
key: n.status.relaPath + n.status.status + n.status.staged,
|
||||
data: n,
|
||||
children: n.children.map(toTreeNode),
|
||||
});
|
||||
return tree == null ? null : toTreeNode(tree);
|
||||
}, [tree]);
|
||||
|
||||
const checkNode = useCallback(
|
||||
(treeNode: CommitTreeNode) => {
|
||||
const checked = nodeCheckedStatus(treeNode);
|
||||
const newChecked = checked === "indeterminate" ? true : !checked;
|
||||
setCheckedAndChildren(treeNode, newChecked, unstage.mutate, add.mutate);
|
||||
// TODO: Also ensure parents are added properly
|
||||
},
|
||||
[add.mutate, unstage.mutate],
|
||||
);
|
||||
|
||||
const checkEntry = useCallback(
|
||||
(entry: GitStatusEntry) => {
|
||||
if (entry.staged) unstage.mutate({ relaPaths: [entry.relaPath] });
|
||||
else add.mutate({ relaPaths: [entry.relaPath] });
|
||||
},
|
||||
[add.mutate, unstage.mutate],
|
||||
);
|
||||
|
||||
const handleSelectChild = useCallback(
|
||||
(entry: GitStatusEntry) => {
|
||||
if (entry === selectedEntry) {
|
||||
setSelectedEntry(null);
|
||||
} else {
|
||||
setSelectedEntry(entry);
|
||||
}
|
||||
},
|
||||
[selectedEntry],
|
||||
);
|
||||
|
||||
const handleDiscardChanges = useCallback(
|
||||
async (entry: GitStatusEntry) => {
|
||||
const confirmed = await showConfirm({
|
||||
id: "git-restore-commit-entry",
|
||||
title: "Discard Changes",
|
||||
description: "Do you really want to discard uncommitted changes for the selected item?",
|
||||
confirmText: "Discard",
|
||||
color: "danger",
|
||||
});
|
||||
if (!confirmed) return;
|
||||
|
||||
await restore.mutateAsync({ relaPaths: [entry.relaPath] });
|
||||
await sync({ force: true });
|
||||
setSelectedEntry(null);
|
||||
},
|
||||
[restore],
|
||||
);
|
||||
|
||||
if (tree == null || treeNode == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!hasAnythingToAdd) {
|
||||
return (
|
||||
<div className="h-full px-6 pb-4">
|
||||
<EmptyStateText>No changes since last commit</EmptyStateText>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full px-2 pb-4">
|
||||
<SplitLayout
|
||||
storageKey="commit-horizontal"
|
||||
layout="horizontal"
|
||||
defaultRatio={0.6}
|
||||
firstSlot={({ style }) => (
|
||||
<div style={style} className="h-full px-4 flex flex-col gap-3">
|
||||
<CommercialUseBanner source="git-commit" title="Using Git for work?" />
|
||||
<SplitLayout
|
||||
className="min-h-0 flex-1"
|
||||
storageKey="commit-vertical"
|
||||
layout="vertical"
|
||||
defaultRatio={0.35}
|
||||
firstSlot={({ style: innerStyle }) => (
|
||||
<div
|
||||
style={innerStyle}
|
||||
className="h-full overflow-y-auto pb-3 pr-0.5 transform-cpu"
|
||||
>
|
||||
<CheckboxTree
|
||||
node={treeNode}
|
||||
checked={(n) => nodeCheckedStatus(n.data)}
|
||||
onCheck={(n) => checkNode(n.data)}
|
||||
checkboxTitle={(n) =>
|
||||
nodeCheckedStatus(n.data) ? "Unstage change" : "Stage change"
|
||||
}
|
||||
isRelevant={(n) => n.data.status.status !== "current"}
|
||||
canSelectRow={(n) => n.data.status.status !== "current"}
|
||||
onSelectRow={(n) => handleSelectChild(n.data.status)}
|
||||
isRowSelected={(n) => selectedEntry?.relaPath === n.data.status.relaPath}
|
||||
renderRow={(n) => <CommitTreeRow node={n.data} />}
|
||||
/>
|
||||
{externalEntries.find((e) => e.status !== "current") && (
|
||||
<>
|
||||
<Separator className="mt-3 mb-1">Other files</Separator>
|
||||
{externalEntries.map((entry) => (
|
||||
<ExternalTreeNode
|
||||
key={entry.relaPath + entry.status}
|
||||
entry={entry}
|
||||
relaDir={status.data?.relaDir ?? ""}
|
||||
onCheck={checkEntry}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
secondSlot={({ style: innerStyle }) => (
|
||||
<div style={innerStyle} className="grid grid-rows-[minmax(0,1fr)_auto] gap-3 pb-2">
|
||||
<Input
|
||||
className="text-base! font-sans rounded-md"
|
||||
placeholder="Commit message..."
|
||||
onChange={setMessage}
|
||||
stateKey={null}
|
||||
label="Commit message"
|
||||
fullHeight
|
||||
multiLine
|
||||
hideLabel
|
||||
/>
|
||||
{commitError && <Banner color="danger">{commitError}</Banner>}
|
||||
<HStack alignItems="center" space={2}>
|
||||
<InlineCode>{status.data?.headRefShorthand}</InlineCode>
|
||||
<HStack space={2} className="ml-auto">
|
||||
<Button
|
||||
color="secondary"
|
||||
size="sm"
|
||||
onClick={handleCreateCommit}
|
||||
disabled={!hasAddedAnything || message.trim().length === 0}
|
||||
isLoading={isPushing}
|
||||
>
|
||||
Commit
|
||||
</Button>
|
||||
<Button
|
||||
color="primary"
|
||||
size="sm"
|
||||
disabled={!hasAddedAnything || message.trim().length === 0}
|
||||
onClick={handleCreateCommitAndPush}
|
||||
isLoading={isPushing}
|
||||
>
|
||||
Commit and Push
|
||||
</Button>
|
||||
</HStack>
|
||||
</HStack>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
secondSlot={({ style }) => (
|
||||
<div style={style} className="h-full px-4 border-l border-l-border-subtle">
|
||||
{selectedEntry ? (
|
||||
<DiffPanel entry={selectedEntry} onDiscardChanges={handleDiscardChanges} />
|
||||
) : (
|
||||
<EmptyStateText>Select a change to view diff</EmptyStateText>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CommitTreeRow({ node }: { node: CommitTreeNode }) {
|
||||
return (
|
||||
<>
|
||||
{node.model.model !== "http_request" &&
|
||||
node.model.model !== "grpc_request" &&
|
||||
node.model.model !== "websocket_request" ? (
|
||||
<Icon
|
||||
color="secondary"
|
||||
icon={
|
||||
node.model.model === "folder"
|
||||
? "folder"
|
||||
: node.model.model === "environment"
|
||||
? "variable"
|
||||
: "house"
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<span aria-hidden className="w-4" />
|
||||
)}
|
||||
<div className="truncate flex-1">{resolvedModelName(node.model)}</div>
|
||||
{node.status.status !== "current" && (
|
||||
<InlineCode
|
||||
className={classNames(
|
||||
"py-0 bg-transparent w-24 text-center shrink-0",
|
||||
node.status.status === "modified" && "text-info",
|
||||
node.status.status === "untracked" && "text-success",
|
||||
node.status.status === "removed" && "text-danger",
|
||||
)}
|
||||
>
|
||||
{node.status.status}
|
||||
</InlineCode>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ExternalTreeNode({
|
||||
entry,
|
||||
relaDir,
|
||||
onCheck,
|
||||
}: {
|
||||
entry: GitStatusEntry;
|
||||
relaDir: string;
|
||||
onCheck: (entry: GitStatusEntry) => void;
|
||||
}) {
|
||||
if (entry.status === "current") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Show paths relative to the sync directory when inside it
|
||||
const displayPath = entry.relaPath.startsWith(`${relaDir}/`)
|
||||
? entry.relaPath.slice(relaDir.length + 1)
|
||||
: entry.relaPath;
|
||||
|
||||
return (
|
||||
<Checkbox
|
||||
fullWidth
|
||||
className="h-xs w-full hover:bg-surface-highlight rounded-sm px-1 group"
|
||||
checked={entry.staged}
|
||||
onChange={() => onCheck(entry)}
|
||||
title={
|
||||
<div className="grid grid-cols-[auto_minmax(0,1fr)_auto] gap-1 w-full items-center">
|
||||
<Icon color="secondary" icon="file_code" />
|
||||
<div className="truncate">{displayPath}</div>
|
||||
<InlineCode
|
||||
className={classNames(
|
||||
"py-0 ml-auto bg-transparent w-24 text-center",
|
||||
entry.status === "modified" && "text-info",
|
||||
entry.status === "untracked" && "text-success",
|
||||
entry.status === "removed" && "text-danger",
|
||||
)}
|
||||
>
|
||||
{entry.status}
|
||||
</InlineCode>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function nodeCheckedStatus(root: CommitTreeNode): CheckboxProps["checked"] {
|
||||
let numVisited = 0;
|
||||
let numChecked = 0;
|
||||
let numCurrent = 0;
|
||||
|
||||
const visitChildren = (n: CommitTreeNode) => {
|
||||
numVisited += 1;
|
||||
if (n.status.status === "current") {
|
||||
numCurrent += 1;
|
||||
} else if (n.status.staged) {
|
||||
numChecked += 1;
|
||||
}
|
||||
for (const child of n.children) {
|
||||
visitChildren(child);
|
||||
}
|
||||
};
|
||||
|
||||
visitChildren(root);
|
||||
|
||||
if (numVisited === numChecked + numCurrent) {
|
||||
return true;
|
||||
}
|
||||
if (numChecked === 0) {
|
||||
return false;
|
||||
}
|
||||
return "indeterminate";
|
||||
}
|
||||
|
||||
function setCheckedAndChildren(
|
||||
node: CommitTreeNode,
|
||||
checked: boolean,
|
||||
unstage: (args: { relaPaths: string[] }) => void,
|
||||
add: (args: { relaPaths: string[] }) => void,
|
||||
) {
|
||||
const toAdd: string[] = [];
|
||||
const toUnstage: string[] = [];
|
||||
|
||||
const next = (node: CommitTreeNode) => {
|
||||
for (const child of node.children) {
|
||||
next(child);
|
||||
}
|
||||
|
||||
if (node.status.status === "current") {
|
||||
// Nothing required
|
||||
} else if (checked && !node.status.staged) {
|
||||
toAdd.push(node.status.relaPath);
|
||||
} else if (!checked && node.status.staged) {
|
||||
toUnstage.push(node.status.relaPath);
|
||||
}
|
||||
};
|
||||
|
||||
next(node);
|
||||
|
||||
if (toAdd.length > 0) add({ relaPaths: toAdd });
|
||||
if (toUnstage.length > 0) unstage({ relaPaths: toUnstage });
|
||||
}
|
||||
|
||||
function DiffPanel({
|
||||
entry,
|
||||
onDiscardChanges,
|
||||
}: {
|
||||
entry: GitStatusEntry;
|
||||
onDiscardChanges: (entry: GitStatusEntry) => void | Promise<void>;
|
||||
}) {
|
||||
const prevYaml = modelToYaml(entry.prev);
|
||||
const nextYaml = modelToYaml(entry.next);
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="text-text-subtle mb-2 px-1 grid items-center gap-2 grid-cols-[minmax(0,1fr)_auto]">
|
||||
<div className="min-w-0 truncate">
|
||||
{resolvedModelName(entry.next ?? entry.prev)} ({entry.status})
|
||||
</div>
|
||||
<Button
|
||||
className="ml-auto"
|
||||
color="warning"
|
||||
size="2xs"
|
||||
variant="border"
|
||||
onClick={() => onDiscardChanges(entry)}
|
||||
>
|
||||
Discard Changes
|
||||
</Button>
|
||||
</div>
|
||||
<DiffViewer original={prevYaml ?? ""} modified={nextYaml ?? ""} className="flex-1 min-h-0" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user