feat: create file button in toolbar

This commit is contained in:
Patrick Erichsen 2025-04-14 11:34:54 -07:00
parent f53a765c19
commit 268f55b001
11 changed files with 198 additions and 72 deletions

View file

@ -1,7 +1,6 @@
import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { useEffect, useState } from "react";
import { lightGray, vscForeground } from "../..";
import { getMetaKeyLabel } from "../../../util";
import Spinner from "../../gui/Spinner";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
@ -14,7 +13,7 @@ interface ApplyActionsProps {
onClickApply: () => void;
}
export default function ApplyActions(props: ApplyActionsProps) {
export function ApplyActions(props: ApplyActionsProps) {
const [hasRejected, setHasRejected] = useState(false);
const [showApplied, setShowApplied] = useState(false);
const isClosed = props.applyState?.status === "closed";
@ -37,11 +36,10 @@ export default function ApplyActions(props: ApplyActionsProps) {
const applyButton = (text: string) => (
<button
className={`flex items-center border-none bg-transparent pl-0 text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
onClick={props.onClickApply}
style={{ color: lightGray }}
>
<div className="flex items-center gap-1 text-gray-400">
<div className="text-lightgray flex items-center gap-1">
<PlayIcon className="h-3.5 w-3.5" />
<span className="xs:inline hidden">{text}</span>
</div>
@ -52,7 +50,7 @@ export default function ApplyActions(props: ApplyActionsProps) {
case "streaming":
return (
<div className="flex items-center rounded bg-zinc-700 pl-2 pr-1">
<span className="inline-flex w-min items-center gap-2 text-center text-xs text-gray-400">
<span className="text-lightgray inline-flex w-min items-center gap-2 text-center text-xs">
Applying
<Spinner />
</span>
@ -61,9 +59,8 @@ export default function ApplyActions(props: ApplyActionsProps) {
case "done":
return (
<div className="flex items-center rounded bg-zinc-700 px-1.5 sm:gap-1">
<span className="max-xs:hidden text-center text-xs text-gray-400">
<span className="max-xs:hidden text-lightgray text-center text-xs">
{`${props.applyState?.numDiffs === 1 ? "1 diff" : `${props.applyState?.numDiffs} diffs`}`}
<span className="max-md:hidden">{` remaining`}</span>
</span>
<div className="flex">

View file

@ -1,23 +1,19 @@
import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline";
import { lightGray } from "../..";
import useCopy from "../../../hooks/useCopy";
interface CopyButtonProps {
text: string;
}
export default function CopyButton({ text }: CopyButtonProps) {
export function CopyButton({ text }: CopyButtonProps) {
const { copyText, copied } = useCopy(text);
return (
<div
className={`flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125`}
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125"
onClick={copyText}
>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
{copied ? (
<CheckIcon className="h-3.5 w-3.5 text-green-500 hover:brightness-125" />
) : (

View file

@ -0,0 +1,22 @@
import { DocumentPlusIcon } from "@heroicons/react/24/outline";
import { vscForeground } from "../..";
interface CreateFileButtonProps {
onClick: () => void;
}
export function CreateFileButton({ onClick }: CreateFileButtonProps) {
return (
<>
<button
className={`text-lightgray flex items-center border-none bg-transparent pl-0 text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
onClick={onClick}
>
<div className="flex items-center gap-1">
<DocumentPlusIcon className="h-3.5 w-3.5 shrink-0" />
<span className="line-clamp-1 break-all">Create file</span>
</div>
</button>
</>
);
}

View file

@ -1,25 +1,42 @@
import { getLastNPathParts } from "core/util/uri";
import FileIcon from "../../FileIcon";
import { ToolTip } from "../../gui/Tooltip";
export interface FileInfoProps {
filepath: string;
onClick: () => void;
onClick?: () => void;
range?: string;
}
const TOOLTIP_ID = "file-info-tooltip";
export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => {
return (
<div
className="flex cursor-pointer flex-row items-center gap-0.5"
onClick={onClick}
>
<div>
<FileIcon height="20px" width="20px" filename={filepath} />
<>
<div
className={`flex select-none flex-row items-center gap-0.5 ${onClick && "cursor-pointer hover:underline"}`}
onClick={onClick}
data-tooltip-id={TOOLTIP_ID}
data-tooltip-content={filepath}
data-tooltip-place="top-end"
>
<div>
<FileIcon height="20px" width="20px" filename={filepath} />
</div>
<span className="line-clamp-1 break-all">
{getLastNPathParts(filepath, 1)}
{range && ` ${range}`}
</span>
</div>
<span className="line-clamp-1 break-all hover:underline">
{getLastNPathParts(filepath, 1)}
{range && ` ${range}`}
</span>
</div>
<ToolTip
id={TOOLTIP_ID}
style={{
maxWidth: "200px",
textAlign: "left",
whiteSpace: "normal",
wordBreak: "break-word",
}}
/>
</>
);
};

View file

@ -5,7 +5,7 @@ export interface GeneratingCodeLoaderProps {
codeBlockContent: string;
}
export default function GeneratingCodeLoader({
export function GeneratingCodeLoader({
showLineCount,
codeBlockContent,
}: GeneratingCodeLoaderProps) {
@ -16,7 +16,7 @@ export default function GeneratingCodeLoader({
: `${numLinesCodeBlock} lines generated`;
return (
<span className="inline-flex items-center gap-2 text-gray-400">
<span className="text-lightgray inline-flex items-center gap-2">
{showLineCount ? linesGeneratedText : "Generating"}
<Spinner />
</span>

View file

@ -1,5 +1,4 @@
import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline";
import { lightGray } from "../..";
/**
* Button that inserts code at the current cursor position
@ -8,17 +7,14 @@ interface InsertButtonProps {
onInsert: () => void;
}
export default function InsertButton({ onInsert }: InsertButtonProps) {
export function InsertButton({ onInsert }: InsertButtonProps) {
return (
<div
className={`flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125`}
className="text-lightgray flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125"
onClick={onInsert}
>
<div
className="max-2xs:hidden flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
<ArrowLeftEndOnRectangleIcon className="h-3.5 w-3.5 hover:brightness-125" />
<div className="max-2xs:hidden flex items-center gap-1 transition-colors duration-200">
<ArrowLeftEndOnRectangleIcon className="h-3.5 w-3.5" />
</div>
</div>
);

View file

@ -7,9 +7,7 @@ interface RunInTerminalButtonProps {
command: string;
}
export default function RunInTerminalButton({
command,
}: RunInTerminalButtonProps) {
export function RunInTerminalButton({ command }: RunInTerminalButtonProps) {
const ideMessenger = useContext(IdeMessengerContext);
function runInTerminal() {
@ -18,7 +16,7 @@ export default function RunInTerminalButton({
return (
<div
className={`flex items-center border-none bg-transparent text-xs text-gray-400 text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
className={`text-lightgray flex items-center border-none bg-transparent text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
onClick={runInTerminal}
>
<div
@ -27,7 +25,7 @@ export default function RunInTerminalButton({
>
<>
<CommandLineIcon className="h-3 w-3 hover:brightness-125" />
<span className="text-gray-400 max-sm:hidden">Run</span>
<span className="text-lightgray max-sm:hidden">Run</span>
</>
</div>
</div>

View file

@ -16,12 +16,13 @@ import {
} from "../../../redux/slices/sessionSlice";
import { getFontSize } from "../../../util";
import { isTerminalCodeBlock } from "../utils";
import ApplyActions from "./ApplyActions";
import CopyButton from "./CopyButton";
import { ApplyActions } from "./ApplyActions";
import { CopyButton } from "./CopyButton";
import { CreateFileButton } from "./CreateFileButton";
import { FileInfo } from "./FileInfo";
import GeneratingCodeLoader from "./GeneratingCodeLoader";
import InsertButton from "./InsertButton";
import RunInTerminalButton from "./RunInTerminalButton";
import { GeneratingCodeLoader } from "./GeneratingCodeLoader";
import { InsertButton } from "./InsertButton";
import { RunInTerminalButton } from "./RunInTerminalButton";
const TopDiv = styled.div`
display: flex;
@ -59,7 +60,7 @@ export interface StepContainerPreToolbarProps {
disableManualApply?: boolean;
}
export function StepContainerPreToolbar({
export default function StepContainerPreToolbar({
codeBlockContent,
language,
relativeFilepath,
@ -77,11 +78,8 @@ export function StepContainerPreToolbar({
expanded ?? (isInEditMode ? false : true),
);
// We store the resolved file URI to ensure we use the same file when
// accepting/rejecting diffs, even if no `relativeFilepath` is provided
const [resolvedFileUri, setResolvedFileUri] = useState<string | undefined>(
undefined,
);
const { fileExists, refreshFileExists } = useFileExists(relativeFilepath);
const nextCodeBlockIndex = useAppSelector(
(state) => state.session.codeBlockApplyStates.curIndex,
);
@ -90,16 +88,27 @@ export function StepContainerPreToolbar({
selectApplyStateByStreamId(state, codeBlockStreamId),
);
/**
* In the case where `relativeFilepath` is defined, this will just be the resolved URI
* of `relativeFilepath`. However, if no `relativeFilepath` is defined, then this will
* be the URI of the currently open file at the time the user clicks "Apply".
*/
const [appliedFileUri, setAppliedFileUri] = useState<string | undefined>(
undefined,
);
const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex;
const hasFileExtension =
relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath);
const displayFilepath = relativeFilepath ?? resolvedFileUri;
// If we are creating a file, we already render that in the button
// so we don't want to dispaly it twice here
const displayFilepath = relativeFilepath ?? appliedFileUri;
async function getFileUri() {
async function getFileUriToApplyTo() {
// If we've already resolved a file URI (from clicking apply), use that
if (resolvedFileUri) {
return resolvedFileUri;
if (appliedFileUri) {
return appliedFileUri;
}
// If a relative filepath was provided, try to resolve it
@ -120,23 +129,24 @@ export function StepContainerPreToolbar({
}
async function onClickApply() {
const fileUri = await getFileUri();
const fileUri = await getFileUriToApplyTo();
if (!fileUri) {
ideMessenger.ide.showToast(
"error",
"Could not resolve filepath to apply changes",
);
return;
}
setResolvedFileUri(fileUri);
// applyToFile will create the file if it doesn't exist
ideMessenger.post("applyToFile", {
streamId: codeBlockStreamId,
filepath: fileUri,
text: codeBlockContent,
});
setAppliedFileUri(fileUri);
refreshFileExists();
}
function onClickInsertAtCursor() {
@ -153,7 +163,7 @@ export function StepContainerPreToolbar({
);
async function handleDiffAction(action: "accept" | "reject") {
const filepath = await getFileUri();
const filepath = await getFileUriToApplyTo();
if (!filepath) {
ideMessenger.ide.showToast(
"error",
@ -167,13 +177,13 @@ export function StepContainerPreToolbar({
streamId: codeBlockStreamId,
});
setResolvedFileUri(undefined);
setAppliedFileUri(undefined);
}
function onClickFilename() {
if (resolvedFileUri) {
if (appliedFileUri) {
ideMessenger.post("showFile", {
filepath: resolvedFileUri,
filepath: appliedFileUri,
});
}
@ -184,8 +194,8 @@ export function StepContainerPreToolbar({
}
}
// We want until there is an extension in the filepath to avoid rendering
// an incomplete filepath
// We wait until there is an extension in the filepath to avoid rendering
// an incomplete filepath
if (relativeFilepath && !hasFileExtension) {
return children;
}
@ -196,7 +206,7 @@ export function StepContainerPreToolbar({
<div className="flex max-w-72 flex-row items-center">
<ChevronDownIcon
onClick={() => setIsExpanded(!isExpanded)}
className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
@ -204,10 +214,12 @@ export function StepContainerPreToolbar({
<FileInfo
filepath={displayFilepath}
range={range}
onClick={onClickFilename}
onClick={fileExists ? onClickFilename : undefined}
/>
) : (
<span className="ml-2 capitalize text-gray-400">{language}</span>
<span className="text-lightgray ml-2 select-none capitalize">
{language}
</span>
)}
</div>
@ -219,11 +231,15 @@ export function StepContainerPreToolbar({
/>
) : (
<>
<InsertButton onInsert={onClickInsertAtCursor} />
<CopyButton text={codeBlockContent} />
<div className="xs:flex hidden items-center gap-2.5">
<InsertButton onInsert={onClickInsertAtCursor} />
<CopyButton text={codeBlockContent} />
</div>
{isTerminalCodeBlock(language, codeBlockContent) ? (
<RunInTerminalButton command={codeBlockContent} />
) : !fileExists ? (
<CreateFileButton onClick={onClickApply} />
) : (
<ApplyActions
disableManualApply={disableManualApply}

2
gui/src/hooks/index.ts Normal file
View file

@ -0,0 +1,2 @@
export * from "./useFileExists";
export * from "./useIdeMessengerRequest";

View file

@ -0,0 +1,45 @@
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { useContext, useEffect, useState } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useIdeMessengerRequest } from "./useIdeMessengerRequest";
/**
* Wrapper around useIdeMessengerRequest specifically for checking file existence.
* We maintain this as a separate hook because the conversion from relative filepath
* to URI requires an async call.
*/
export function useFileExists(filepath?: string) {
const ideMessenger = useContext(IdeMessengerContext);
const [resolvedUri, setResolvedUri] = useState<string | null>(null);
const { result: fileExists, refresh: refreshFileExists } =
useIdeMessengerRequest(
"fileExists",
resolvedUri ? { filepath: resolvedUri } : null,
);
useEffect(() => {
async function resolveUri() {
if (!filepath) {
setResolvedUri(null);
return;
}
try {
const uri = await inferResolvedUriFromRelativePath(
filepath,
ideMessenger.ide,
);
setResolvedUri(uri);
} catch (err) {
console.error("Failed to resolve URI:", err);
}
}
resolveUri();
}, [filepath, ideMessenger.ide]);
console.log({ fileExists, resolvedUri });
return { fileExists, refreshFileExists };
}

View file

@ -0,0 +1,37 @@
import type { FromWebviewProtocol } from "core/protocol";
import type { SuccessWebviewSingleMessage } from "core/protocol/util";
import { useContext, useEffect, useState } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
/**
* Generic hook for making IDE messenger requests with automatic error handling and refresh capability
*/
export function useIdeMessengerRequest<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0] | null,
) {
const ideMessenger = useContext(IdeMessengerContext);
const [result, setResult] = useState<
SuccessWebviewSingleMessage<FromWebviewProtocol[T][1]>["content"] | null
>(null);
async function makeRequest() {
if (!data) {
setResult(null);
return;
}
const response = await ideMessenger.request(messageType, data);
if (response.status === "success") {
setResult(response.content);
} else {
console.error(`Error in ${messageType} request:`, response.error);
}
}
useEffect(() => {
makeRequest();
}, [data, messageType]);
return { result, refresh: makeRequest };
}