feat: toolbar header for all codeblocks

This commit is contained in:
Patrick Erichsen 2025-04-10 22:38:44 -07:00
parent c74e796103
commit 635f7cb168
13 changed files with 161 additions and 289 deletions

View file

@ -11,8 +11,6 @@ import type {
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
openUrl: [string, void];
// We pass the `curSelectedModel` because we currently cannot access the
// default model title in the GUI from JB
applyToFile: [
{
text: string;

View file

@ -4,9 +4,9 @@ import { useMemo } from "react";
import { themeIcons } from "seti-file-icons";
export interface FileIconProps {
filename: string;
height: `${number}px`;
width: `${number}px`;
filename: string;
}
export default function FileIcon({ filename, height, width }: FileIconProps) {

View file

@ -1,138 +0,0 @@
import {
ArrowLeftEndOnRectangleIcon,
CommandLineIcon,
PlayIcon,
} from "@heroicons/react/24/outline";
import { useContext, useRef, useState } from "react";
import { v4 as uuidv4 } from "uuid";
import {
defaultBorderRadius,
vscCommandCenterInactiveBorder,
vscEditorBackground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import { useAppSelector } from "../../redux/hooks";
import { selectUIConfig } from "../../redux/slices/configSlice";
import { isJetBrains } from "../../util";
import { CopyIconButton } from "../gui/CopyIconButton";
import HeaderButtonWithToolTip from "../gui/HeaderButtonWithToolTip";
import { getTerminalCommand, isTerminalCodeBlock } from "./utils";
interface StepContainerPreActionButtonsProps {
language: string | null;
codeBlockContent: string;
codeBlockIndex: number;
children: any;
}
export default function StepContainerPreActionButtons({
language,
codeBlockContent,
codeBlockIndex,
children,
}: StepContainerPreActionButtonsProps) {
const [hovering, setHovering] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
const uiConfig = useAppSelector(selectUIConfig);
const streamIdRef = useRef<string | null>(null);
const nextCodeBlockIndex = useAppSelector(
(state) => state.session.codeBlockApplyStates.curIndex,
);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const isBottomToolbarPosition =
uiConfig?.codeBlockToolbarPosition == "bottom";
const toolTipPlacement = isBottomToolbarPosition ? "top" : "bottom";
const shouldRunTerminalCmd =
!isJetBrains() && isTerminalCodeBlock(language, codeBlockContent);
const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex;
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
function onClickApply() {
if (!streamIdRef.current) {
return;
}
ideMessenger.post("applyToFile", {
streamId: streamIdRef.current,
text: codeBlockContent,
});
}
async function onClickRunTerminal(): Promise<void> {
if (shouldRunTerminalCmd) {
return ideMessenger.ide.runCommand(getTerminalCommand(codeBlockContent));
}
}
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
async () => onClickApply(),
[isNextCodeBlock, codeBlockContent],
!isNextCodeBlock,
);
return (
<div
tabIndex={-1}
onMouseEnter={() => setHovering(true)}
onMouseLeave={() => setHovering(false)}
className="bg-vsc-editor-background relative my-2.5"
style={{
border: `1px solid ${vscCommandCenterInactiveBorder}`,
borderRadius: defaultBorderRadius,
}}
>
<div className="h-full w-full overflow-hidden rounded-md">{children}</div>
{hovering && !isStreaming && (
<div
className="bg-vsc-editor-background z-100 absolute right-3 z-50 flex -translate-y-1/2 gap-1.5 px-1 py-0.5"
style={{
top: !isBottomToolbarPosition ? 0 : "100%",
border: `1px solid ${vscCommandCenterInactiveBorder}`,
borderRadius: defaultBorderRadius,
}}
>
{shouldRunTerminalCmd && (
<HeaderButtonWithToolTip
text="Run in terminal"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickRunTerminal}
tooltipPlacement={toolTipPlacement}
>
<CommandLineIcon className="h-4 w-4 text-gray-400" />
</HeaderButtonWithToolTip>
)}
<HeaderButtonWithToolTip
text="Apply"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
tooltipPlacement={toolTipPlacement}
>
<PlayIcon className="h-4 w-4 text-gray-400" />
</HeaderButtonWithToolTip>
<HeaderButtonWithToolTip
text="Insert at cursor"
style={{ backgroundColor: vscEditorBackground }}
onClick={() =>
ideMessenger.post("insertAtCursor", { text: codeBlockContent })
}
tooltipPlacement={toolTipPlacement}
>
<ArrowLeftEndOnRectangleIcon className="h-4 w-4 text-gray-400" />
</HeaderButtonWithToolTip>
<CopyIconButton
text={codeBlockContent}
tooltipPlacement={toolTipPlacement}
/>
</div>
)}
</div>
);
}

View file

@ -37,12 +37,12 @@ export default function ApplyActions(props: ApplyActionsProps) {
const applyButton = (text: string) => (
<button
className={`flex items-center border-none bg-transparent text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
className={`flex items-center border-none bg-transparent pl-0 text-xs text-[${vscForeground}] cursor-pointer outline-none hover:brightness-125`}
onClick={props.onClickApply}
style={{ color: lightGray }}
>
<div className="flex items-center gap-1 text-gray-400">
<PlayIcon className="h-3 w-3" />
<PlayIcon className="h-3.5 w-3.5" />
<span className="xs:inline hidden">{text}</span>
</div>
</button>
@ -53,7 +53,7 @@ export default function ApplyActions(props: ApplyActionsProps) {
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">
Applying changes
Applying
<div>
<Spinner />
</div>

View file

@ -1,6 +1,6 @@
import { CheckIcon, ClipboardIcon } from "@heroicons/react/24/outline";
import { lightGray } from "../..";
import useCopy from "../../../hooks/useCopy";
import { lightGray, vscForeground } from "../..";
interface CopyButtonProps {
text: string;
@ -11,23 +11,17 @@ export default function CopyButton({ text }: CopyButtonProps) {
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={`flex cursor-pointer items-center border-none bg-transparent text-xs outline-none hover:brightness-125`}
onClick={copyText}
>
<div
className="max-2xs:hidden flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
{copied ? (
<>
<CheckIcon className="h-3 w-3 text-green-500 hover:brightness-125" />
<span className="max-sm:hidden">Copied</span>
</>
<CheckIcon className="h-3.5 w-3.5 text-green-500 hover:brightness-125" />
) : (
<>
<ClipboardIcon className="h-3 w-3 hover:brightness-125" />
<span className="text-gray-400 max-sm:hidden">Copy</span>
</>
<ClipboardIcon className="h-3.5 w-3.5 hover:brightness-125" />
)}
</div>
</div>

View file

@ -1,41 +1,25 @@
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { getLastNPathParts } from "core/util/uri";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import FileIcon from "../../FileIcon";
export interface FileInfoProps {
relativeFilepath: string;
filepath: string;
onClick: () => void;
range?: string;
}
const FileInfo = ({ relativeFilepath, range }: FileInfoProps) => {
const ideMessenger = useContext(IdeMessengerContext);
async function onClickFileName() {
const fileUri = await inferResolvedUriFromRelativePath(
relativeFilepath,
ideMessenger.ide,
);
ideMessenger.post("showFile", {
filepath: fileUri,
});
}
export const FileInfo = ({ filepath, range, onClick }: FileInfoProps) => {
return (
<div
className="flex cursor-pointer flex-row items-center gap-0.5"
onClick={onClickFileName}
onClick={onClick}
>
<div>
<FileIcon height="20px" width="20px" filename={relativeFilepath} />
<FileIcon height="20px" width="20px" filename={filepath} />
</div>
<span className="line-clamp-1 break-all hover:underline">
{getLastNPathParts(relativeFilepath, 1)}
{getLastNPathParts(filepath, 1)}
{range && ` ${range}`}
</span>
</div>
);
};
export default FileInfo;

View file

@ -0,0 +1,25 @@
import { ArrowLeftEndOnRectangleIcon } from "@heroicons/react/24/outline";
import { lightGray } from "../..";
/**
* Button that inserts code at the current cursor position
*/
interface InsertButtonProps {
onInsert: () => void;
}
export default function InsertButton({ onInsert }: InsertButtonProps) {
return (
<div
className={`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>
</div>
);
}

View file

@ -1,7 +1,6 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { inferResolvedUriFromRelativePath } from "core/util/ideUtils";
import { debounce } from "lodash";
import { useContext, useEffect, useRef, useState } from "react";
import { useContext, useState } from "react";
import styled from "styled-components";
import {
defaultBorderRadius,
@ -11,17 +10,17 @@ import {
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { useAppSelector } from "../../../redux/hooks";
import { selectSelectedChatModel } from "../../../redux/slices/configSlice";
import {
selectApplyStateByStreamId,
selectIsInEditMode,
} from "../../../redux/slices/sessionSlice";
import { getFontSize } from "../../../util";
import { childrenToText, isTerminalCodeBlock } from "../utils";
import { isTerminalCodeBlock } from "../utils";
import ApplyActions from "./ApplyActions";
import CopyButton from "./CopyButton";
import FileInfo from "./FileInfo";
import { FileInfo } from "./FileInfo";
import GeneratingCodeLoader from "./GeneratingCodeLoader";
import InsertButton from "./InsertButton";
import RunInTerminalButton from "./RunInTerminalButton";
const TopDiv = styled.div`
@ -50,7 +49,7 @@ const ToolbarDiv = styled.div<{ isExpanded: boolean }>`
export interface StepContainerPreToolbarProps {
codeBlockContent: string;
language: string | null;
relativeFilepath: string;
relativeFilepath?: string;
isGeneratingCodeBlock: boolean;
codeBlockIndex: number; // To track which codeblock we are applying
codeBlockStreamId: string;
@ -60,47 +59,91 @@ export interface StepContainerPreToolbarProps {
disableManualApply?: boolean;
}
export default function StepContainerPreToolbar(
props: StepContainerPreToolbarProps,
) {
export default function StepContainerPreToolbar({
codeBlockContent,
language,
relativeFilepath,
isGeneratingCodeBlock,
codeBlockIndex,
codeBlockStreamId,
range,
children,
expanded,
disableManualApply,
}: StepContainerPreToolbarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const wasGeneratingRef = useRef(props.isGeneratingCodeBlock);
const isInEditMode = useAppSelector(selectIsInEditMode);
const [isExpanded, setIsExpanded] = useState(
props.expanded ?? (isInEditMode ? false : true),
expanded ?? (isInEditMode ? false : true),
);
const [codeBlockContent, setCodeBlockContent] = useState("");
// 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 nextCodeBlockIndex = useAppSelector(
(state) => state.session.codeBlockApplyStates.curIndex,
);
const applyState = useAppSelector((state) =>
selectApplyStateByStreamId(state, props.codeBlockStreamId),
selectApplyStateByStreamId(state, codeBlockStreamId),
);
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.relativeFilepath);
const isNextCodeBlock = nextCodeBlockIndex === codeBlockIndex;
const hasFileExtension =
relativeFilepath && /\.[0-9a-z]+$/i.test(relativeFilepath);
const selectedChatModel = useAppSelector(selectSelectedChatModel);
const displayFilepath = relativeFilepath ?? resolvedFileUri;
async function getFileUri() {
// If we've already resolved a file URI (from clicking apply), use that
if (resolvedFileUri) {
return resolvedFileUri;
}
// If a relative filepath was provided, try to resolve it
if (relativeFilepath) {
return await inferResolvedUriFromRelativePath(
relativeFilepath,
ideMessenger.ide,
);
}
// If no filepath was provided, get the current file
const currentFile = await ideMessenger.ide.getCurrentFile();
if (currentFile) {
return currentFile.path;
}
return undefined;
}
async function onClickApply() {
if (!selectedChatModel) {
const fileUri = await getFileUri();
if (!fileUri) {
ideMessenger.ide.showToast(
"error",
"Could not resolve filepath to apply changes",
);
return;
}
let fileUri = await inferResolvedUriFromRelativePath(
props.relativeFilepath,
ideMessenger.ide,
);
setResolvedFileUri(fileUri);
ideMessenger.post("applyToFile", {
streamId: props.codeBlockStreamId,
streamId: codeBlockStreamId,
filepath: fileUri,
text: codeBlockContent,
});
}
function onClickInsertAtCursor() {
ideMessenger.post("insertAtCursor", { text: codeBlockContent });
}
// TODO: This logic should be moved to a thunk
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
@ -109,64 +152,42 @@ export default function StepContainerPreToolbar(
!isNextCodeBlock,
);
useEffect(() => {
if (codeBlockContent === "") {
setCodeBlockContent(childrenToText(props.children.props.children));
} else {
const debouncedEffect = debounce(() => {
setCodeBlockContent(childrenToText(props.children.props.children));
}, 100);
debouncedEffect();
return () => {
debouncedEffect.cancel();
};
async function handleDiffAction(action: "accept" | "reject") {
const filepath = await getFileUri();
if (!filepath) {
ideMessenger.ide.showToast(
"error",
`Could not resolve filepath to ${action} changes`,
);
return;
}
}, [props.children, codeBlockContent]);
// useEffect(() => {
// const hasCompletedGenerating =
// wasGeneratingRef.current && !isGeneratingCodeBlock;
// wasGeneratingRef.current = isGeneratingCodeBlock;
// if (hasCompletedGenerating) {
// if (props.autoApply) {
// onClickApply();
// }
// }
// }, [wasGeneratingRef, isGeneratingCodeBlock, props.autoApply]);
async function onClickAcceptApply() {
const fileUri = await inferResolvedUriFromRelativePath(
props.relativeFilepath,
ideMessenger.ide,
);
ideMessenger.post("acceptDiff", {
filepath: fileUri,
streamId: props.codeBlockStreamId,
ideMessenger.post(`${action}Diff`, {
filepath,
streamId: codeBlockStreamId,
});
setResolvedFileUri(undefined);
}
async function onClickRejectApply() {
const fileUri = await inferResolvedUriFromRelativePath(
props.relativeFilepath,
ideMessenger.ide,
);
ideMessenger.post("rejectDiff", {
filepath: fileUri,
streamId: props.codeBlockStreamId,
});
}
function onClickFilename() {
if (resolvedFileUri) {
ideMessenger.post("showFile", {
filepath: resolvedFileUri,
});
}
function onClickExpand() {
setIsExpanded(!isExpanded);
if (relativeFilepath) {
ideMessenger.post("showFile", {
filepath: relativeFilepath,
});
}
}
// We want until there is an extension in the filepath to avoid rendering
// an incomplete filepath
if (!hasFileExtension) {
return props.children;
// an incomplete filepath
if (relativeFilepath && !hasFileExtension) {
return children;
}
return (
@ -174,35 +195,42 @@ export default function StepContainerPreToolbar(
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
<div className="flex max-w-72 flex-row items-center">
<ChevronDownIcon
onClick={onClickExpand}
onClick={() => setIsExpanded(!isExpanded)}
className={`h-3.5 w-3.5 flex-shrink-0 cursor-pointer text-gray-400 hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
<FileInfo
relativeFilepath={props.relativeFilepath}
range={props.range}
/>
{displayFilepath ? (
<FileInfo
filepath={displayFilepath}
range={range}
onClick={onClickFilename}
/>
) : (
<span className="ml-2 capitalize text-gray-400">{language}</span>
)}
</div>
<div className="flex items-center gap-3 max-sm:gap-1.5">
{props.isGeneratingCodeBlock ? (
<div className="flex items-center gap-2.5">
{isGeneratingCodeBlock ? (
<GeneratingCodeLoader
showLineCount={!isExpanded}
codeBlockContent={codeBlockContent}
/>
) : (
<>
<CopyButton text={props.codeBlockContent} />
{isTerminalCodeBlock(props.language, props.codeBlockContent) ? (
<RunInTerminalButton command={props.codeBlockContent} />
<InsertButton onInsert={onClickInsertAtCursor} />
<CopyButton text={codeBlockContent} />
{isTerminalCodeBlock(language, codeBlockContent) ? (
<RunInTerminalButton command={codeBlockContent} />
) : (
<ApplyActions
disableManualApply={props.disableManualApply}
disableManualApply={disableManualApply}
applyState={applyState}
onClickApply={onClickApply}
onClickAccept={onClickAcceptApply}
onClickReject={onClickRejectApply}
onClickAccept={() => handleDiffAction("accept")}
onClickReject={() => handleDiffAction("reject")}
/>
)}
</>
@ -211,13 +239,7 @@ export default function StepContainerPreToolbar(
</ToolbarDiv>
{isExpanded && (
<div
className={`overflow-hidden overflow-y-auto ${
isExpanded ? "opacity-100" : "max-h-0 opacity-0"
}`}
>
{props.children}
</div>
<div className="overflow-hidden overflow-y-auto">{children}</div>
)}
</TopDiv>
);

View file

@ -22,7 +22,6 @@ import { ToolTip } from "../gui/Tooltip";
import FilenameLink from "./FilenameLink";
import "./katex.css";
import "./markdown.css";
import StepContainerPreActionButtons from "./StepContainerPreActionButtons";
import StepContainerPreToolbar from "./StepContainerPreToolbar";
import SymbolLink from "./SymbolLink";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
@ -301,6 +300,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const preChildProps = preProps?.children?.[0]?.props ?? {};
const { className, range } = preChildProps;
// TODO: what is this when we odnt have one?
const relativeFilePath = preChildProps["data-relativefilepath"];
const codeBlockContent = preChildProps["data-codeblockcontent"];
@ -310,22 +311,10 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const language = getLanguageFromClassName(className);
if (!relativeFilePath) {
return (
<StepContainerPreActionButtons
language={language}
codeBlockContent={codeBlockContent}
codeBlockIndex={codeBlockIndex}
>
<SyntaxHighlightedPre {...preProps} />
</StepContainerPreActionButtons>
);
}
const isGeneratingCodeBlock =
preChildProps["data-islastcodeblock"] &&
isLastItemRef.current &&
!isStreamingRef.current;
isStreamingRef.current;
if (codeblockState.current[codeBlockIndex] === undefined) {
codeblockState.current[codeBlockIndex] = {
@ -337,7 +326,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
isGeneratingCodeBlock;
}
// We use a custom toolbar for codeblocks in the step container
return (
<StepContainerPreToolbar
codeBlockContent={codeBlockContent}

View file

@ -11,9 +11,9 @@ export function CreateFile(props: CreateFileToolCallProps) {
return props.relativeFilepath ? (
<StyledMarkdownPreview
isRenderingInStepContainer={true}
isRenderingInStepContainer
disableManualApply
source={src}
disableManualApply={true}
/>
) : null;
}

View file

@ -29,9 +29,9 @@ export function EditFile(props: EditToolCallProps) {
return (
<>
<StyledMarkdownPreview
isRenderingInStepContainer={true}
isRenderingInStepContainer
disableManualApply
source={src}
disableManualApply={true}
singleCodeblockStreamId={applyState?.streamId}
expandCodeblocks={false}
/>

View file

@ -9,7 +9,7 @@ interface RunTerminalCommandToolCallProps {
export function RunTerminalCommand(props: RunTerminalCommandToolCallProps) {
return (
<StyledMarkdownPreview
isRenderingInStepContainer={true}
isRenderingInStepContainer
source={`\`\`\`bash .sh\n${props.command ?? ""}\n\`\`\``}
/>
);

View file

@ -7,7 +7,6 @@ class Calculator {
this.result += number;
return this;
}
subtract(number) {
return this;
}