feat: update PreToolbar

This commit is contained in:
Test 2024-11-08 09:10:41 -08:00
parent 979c2473c6
commit 39337910f1
23 changed files with 739 additions and 474 deletions

View file

@ -182,23 +182,6 @@ export class ContinueGUIWebviewViewProvider
</head>
<body>
<div id="root"></div>
${`<script>
function log(level, ...args) {
const text = args.map(arg =>
typeof arg === 'object' ? JSON.stringify(arg) : String(arg)
).join(' ');
vscode.postMessage({ messageType: 'log', level, text, messageId: "log" });
}
window.console.log = (...args) => log('log', ...args);
window.console.info = (...args) => log('info', ...args);
window.console.warn = (...args) => log('warn', ...args);
window.console.error = (...args) => log('error', ...args);
window.console.debug = (...args) => log('debug', ...args);
console.debug('Logging initialized');
</script>`}
${
inDevelopmentMode
? `<script type="module">

View file

@ -13,10 +13,10 @@ import { vscBackground, vscInputBackground } from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import useUIConfig from "../../hooks/useUIConfig";
import { RootState } from "../../redux/store";
import { getFontSize, getMetaKeyLabel } from "../../util";
import { getFontSize } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import { CopyButton } from "../markdown/CopyButton";
import StyledMarkdownPreview from "../markdown/StyledMarkdownPreview";
import { CopyButton } from "./CopyButton";
interface StepContainerProps {
item: ChatHistoryItem;
@ -83,9 +83,10 @@ function StepContainer(props: StepContainerProps) {
};
return (
<div className="relative"
<div
className="relative"
style={{
minHeight: props.isLast ? "50vh" : 0
minHeight: props.isLast ? "50vh" : 0,
}}
>
<ContentDiv
@ -95,22 +96,23 @@ function StepContainer(props: StepContainerProps) {
>
{uiConfig?.displayRawMarkdown ? (
<pre
className="whitespace-pre-wrap break-words p-4 max-w-full overflow-x-auto"
className="max-w-full overflow-x-auto whitespace-pre-wrap break-words p-4"
style={{ fontSize: getFontSize() - 2 }}
>
{stripImages(props.item.message.content)}
</pre>
) : (
<StyledMarkdownPreview
showCodeBorder
isRenderingInStepContainer
source={stripImages(props.item.message.content)}
/>
)}
</ContentDiv>
<div className="h-7 mb-2 mx-2 flex items-center justify-end gap-0.5 xs:flex text-xs text-gray-400 pb-0 cursor-default"
<div
className="xs:flex mx-2 mb-2 flex h-7 cursor-default items-center justify-end gap-0.5 pb-0 text-xs text-gray-400"
style={{
opacity: shouldRenderActions ? 1 : 0,
pointerEvents: shouldRenderActions ? "auto" : "none"
pointerEvents: shouldRenderActions ? "auto" : "none",
}}
>
{truncatedEarly && (
@ -145,7 +147,9 @@ function StepContainer(props: StepContainerProps) {
tabIndex={-1}
onClick={() => sendFeedback(true)}
>
<HandThumbUpIcon className={`h-3.5 w-3.5 mx-0.5 ${feedback === true ? 'text-green-400' : 'text-gray-500'}`} />
<HandThumbUpIcon
className={`mx-0.5 h-3.5 w-3.5 ${feedback === true ? "text-green-400" : "text-gray-500"}`}
/>
</ButtonWithTooltip>
<ButtonWithTooltip
@ -153,7 +157,9 @@ function StepContainer(props: StepContainerProps) {
tabIndex={-1}
onClick={() => sendFeedback(false)}
>
<HandThumbDownIcon className={`h-3.5 w-3.5 ${feedback === false ? 'text-red-400' : 'text-gray-500'}`} />
<HandThumbDownIcon
className={`h-3.5 w-3.5 ${feedback === false ? "text-red-400" : "text-gray-500"}`}
/>
</ButtonWithTooltip>
</div>
</div>

View file

@ -1,372 +0,0 @@
import {
ArrowLeftEndOnRectangleIcon,
CheckIcon,
ClipboardIcon,
CommandLineIcon,
PlayIcon,
XMarkIcon,
ChevronDownIcon,
} from "@heroicons/react/24/outline";
import { getBasename } from "core/util";
import { useContext, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import { v4 as uuidv4 } from "uuid";
import {
defaultBorderRadius,
lightGray,
vscEditorBackground,
vscForeground,
} from "..";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useWebviewListener } from "../../hooks/useWebviewListener";
import {
incrementNextCodeBlockToApplyIndex,
updateApplyState,
} from "../../redux/slices/uiStateSlice";
import { RootState } from "../../redux/store";
import { getFontSize, getMetaKeyLabel, isJetBrains } from "../../util";
import ButtonWithTooltip from "../ButtonWithTooltip";
import FileIcon from "../FileIcon";
import { CopyButton as CopyButtonHeader } from "./CopyButton";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
import { defaultModelSelector } from "../../redux/selectors/modelSelectors";
const ToolbarDiv = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
background: inherit;
font-size: ${getFontSize() - 2}px;
padding: 3px;
padding-left: 4px;
padding-right: 4px;
border-bottom: 0.5px solid ${lightGray}80;
margin: 0;
`;
export const ToolbarButton = styled.button`
display: flex;
align-items: center;
border: none;
outline: none;
background: transparent;
color: ${vscForeground};
font-size: ${getFontSize() - 2}px;
&:hover {
cursor: pointer;
}
`;
const HoverDiv = styled.div`
position: sticky;
top: 0;
left: 100%;
height: 0;
width: 0;
overflow: visible;
z-index: 100;
`;
const InnerHoverDiv = styled.div<{ bottom: boolean }>`
position: absolute;
${(props) => (props.bottom ? "bottom: 3px;" : "top: -11px;")}
right: 10px;
display: flex;
padding: 1px 2px;
gap: 4px;
border: 0.5px solid #8888;
border-radius: ${defaultBorderRadius};
background-color: ${vscEditorBackground};
`;
interface CodeBlockToolBarProps {
text: string;
bottom: boolean;
language: string | undefined;
isNextCodeBlock: boolean;
filepath?: string;
isExpanded: boolean;
onToggleExpand: () => void;
}
const terminalLanguages = ["bash", "sh"];
const commonTerminalCommands = [
"npm",
"pnpm",
"yarn",
"bun",
"deno",
"npx",
"cd",
"ls",
"pwd",
"pip",
"python",
"node",
"git",
"curl",
"wget",
"rbenv",
"gem",
"ruby",
"bundle",
];
function isTerminalCodeBlock(language: string | undefined, text: string) {
return (
terminalLanguages.includes(language) ||
((!language || language?.length === 0) &&
(text.trim().split("\n").length === 1 ||
commonTerminalCommands.some((c) => text.trim().startsWith(c))))
);
}
function getTerminalCommand(text: string): string {
return text.startsWith("$ ") ? text.slice(2) : text;
}
function CodeBlockToolBar(props: CodeBlockToolBarProps) {
const ideMessenger = useContext(IdeMessengerContext);
const dispatch = useDispatch();
const defaultModel = useSelector(defaultModelSelector);
const isTerminal = isTerminalCodeBlock(props.language, props.text);
const [isCopied, setIsCopied] = useState(false);
const streamIdRef = useRef<string | null>(null);
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
const applyState = useSelector(
(store: RootState) =>
store.uiState.applyStates.find(
(state) => state.streamId === streamIdRef.current,
)?.status ?? "closed",
);
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
async () => {
await ideMessenger.request("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
filepath: props.filepath,
});
dispatch(incrementNextCodeBlockToApplyIndex({}));
},
[props.isNextCodeBlock, props.text],
!props.isNextCodeBlock,
);
async function onClickCopy() {
if (isJetBrains()) {
await ideMessenger.request("copyText", { text: props.text });
} else {
await navigator.clipboard.writeText(props.text);
}
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
}
async function onClickApply() {
if (isTerminal) {
await ideMessenger.ide.runCommand(getTerminalCommand(props.text));
return;
}
if (!props.filepath) return;
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "streaming",
}),
);
ideMessenger.post("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text: props.text,
streamId: streamIdRef.current,
filepath: props.filepath,
});
}
function onClickHeader() {
// TODO: Need to turn into relative or fq path
ideMessenger.post("showFile", {
filepath: props.filepath,
});
}
function onClickAccept() {
ideMessenger.post("acceptDiff", { filepath: props.filepath });
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "closed",
}),
);
}
function onClickReject() {
ideMessenger.post("rejectDiff", { filepath: props.filepath });
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "closed",
}),
);
}
// Currently we only use the "old" apply logic in JetBrains. This check can be removed once
// we implement the "new" lazy apply logic.
if (!props.filepath || isJetBrains()) {
return (
<HoverDiv>
<InnerHoverDiv bottom={props.bottom || false}>
{!isJetBrains() && isTerminal && (
<ButtonWithTooltip
text="Run in terminal"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
<CommandLineIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
)}
<ButtonWithTooltip
text="Apply"
style={{ backgroundColor: vscEditorBackground }}
onClick={onClickApply}
>
<PlayIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
<ButtonWithTooltip
text="Insert at cursor"
style={{ backgroundColor: vscEditorBackground }}
onClick={() =>
ideMessenger.post("insertAtCursor", { text: props.text })
}
>
<ArrowLeftEndOnRectangleIcon className="h-4 w-4 text-gray-400" />
</ButtonWithTooltip>
<CopyButtonHeader text={props.text} />
</InnerHoverDiv>
</HoverDiv>
);
}
return (
<ToolbarDiv>
<div className="flex max-w-[50%] items-center">
<div
onClick={props.onToggleExpand}
className="flex cursor-pointer items-center justify-center"
>
<ChevronDownIcon
className={`h-4 w-4 text-gray-400 ${
props.isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
</div>
{props.filepath && (
<div
className="flex cursor-pointer items-center gap-1"
onClick={onClickHeader}
>
<FileIcon height="20px" width="20px" filename={props.filepath} />
<span className="truncate">{getBasename(props.filepath)}</span>
</div>
)}
</div>
<div className="flex items-center gap-1">
<ToolbarButton onClick={onClickCopy}>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
{isCopied ? (
<>
<CheckIcon className="h-3 w-3 text-green-500 hover:brightness-125" />
<span className="hidden sm:inline">Copied</span>
</>
) : (
<>
<ClipboardIcon className="h-3 w-3 hover:brightness-125" />
<span className="xs:inline hidden">Copy</span>
</>
)}
</div>
</ToolbarButton>
<div className="flex">
{applyState === "closed" ? (
<ToolbarButton onClick={onClickApply} style={{ color: lightGray }}>
<div
className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125"
style={{ color: lightGray }}
>
<PlayIcon className="h-3 w-3" />
<span className="xs:inline hidden">Apply</span>
</div>
</ToolbarButton>
) : applyState === "done" ? (
<>
<ToolbarButtonWithTooltip
onClick={onClickReject}
tooltipContent={`${getMetaKeyLabel()}⇧⌫`}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Reject</span>
</div>
</ToolbarButtonWithTooltip>
<ToolbarButtonWithTooltip
onClick={onClickAccept}
tooltipContent={`${getMetaKeyLabel()}⇧⏎`}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Accept</span>
</div>
</ToolbarButtonWithTooltip>
</>
) : (
<div className="mr-2 flex items-center">
<svg
className="h-4 w-4 animate-spin text-gray-400"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="2"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
</div>
)}
</div>
</div>
</ToolbarDiv>
);
}
export default CodeBlockToolBar;

View file

@ -83,7 +83,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
borderColor={props.borderColor}
>
<PreviewMarkdownHeader
className="flex justify-between cursor-pointer"
className="flex cursor-pointer justify-between"
onClick={() => {
if (props.item.id.providerTitle === "file") {
ideMessenger.post("showFile", {
@ -139,7 +139,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
<div
contentEditable={false}
className={
collapsed ? "max-h-[33vh] overflow-hidden m-0" : "overflow-auto m-0"
collapsed ? "m-0 max-h-[33vh] overflow-hidden" : "m-0 overflow-auto"
}
ref={codeBlockRef}
>
@ -147,13 +147,12 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
source={`${fence}${getMarkdownLanguageTagForFile(
props.item.description,
)}\n${content}\n${fence}`}
showCodeBorder={false}
/>
</div>
{(codeBlockRef.current?.scrollHeight ?? 0) > MAX_PREVIEW_HEIGHT && (
<ButtonWithTooltip
className="bottom-1 right-2 absolute"
className="absolute bottom-1 right-2"
text={collapsed ? "Expand" : "Collapse"}
>
{collapsed ? (

View file

@ -1,7 +1,7 @@
import { RangeInFile } from "core";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useContext } from "react";
import { getBasename } from "core/util";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import FileIcon from "../FileIcon";
interface FilenameLinkProps {
@ -21,11 +21,11 @@ function FilenameLink({ rif }: FilenameLinkProps) {
return (
<div
className="inline-flex items-center align-middle hover:bg-stone-800 rounded-md py-0.5 pl-0 pr-1 mb-0.5 cursor-pointer gap-0.5"
className="mb-0.5 inline-flex cursor-pointer items-center gap-0.5 rounded-md py-0.5 pl-0 pr-1 align-middle hover:bg-stone-800"
onClick={onClick}
>
<FileIcon filename={rif.filepath} height="20px" width="20px" />
<span className="align-middle underline underline-offset-2 decoration-gray-600">
<span className="align-middle underline decoration-gray-600 underline-offset-2">
{getBasename(rif.filepath)}
</span>
</div>

View file

@ -0,0 +1,52 @@
import { CheckIcon, XMarkIcon, PlayIcon } from "@heroicons/react/24/outline";
import Spinner from "./Spinner";
import { vscForeground } from "../..";
const ApplyButton = ({
applyState,
onClickApply,
onClickAccept,
onClickReject,
}) => {
switch (applyState) {
case "closed":
return (
<button
className={`flex items-center border-none bg-transparent text-sm text-[${vscForeground}] outline-none hover:brightness-125`}
onClick={onClickApply}
>
<div className="flex items-center gap-1">
<PlayIcon className="h-3 w-3" />
<span className="xs:inline hidden">Apply</span>
</div>
</button>
);
case "done":
return (
<>
<button
className={`text-[${vscForeground}] flex items-center border-none bg-transparent text-sm outline-none hover:brightness-125`}
onClick={onClickReject}
>
<XMarkIcon className="mr-1 h-4 w-4 text-red-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Reject</span>
</div>
</button>
<button
className={`text-[${vscForeground}] flex items-center border-none bg-transparent text-sm outline-none hover:brightness-125`}
onClick={onClickAccept}
>
<CheckIcon className="mr-1 h-4 w-4 text-green-500 hover:brightness-125" />
<div className="flex items-center gap-1 transition-colors duration-200 hover:brightness-125">
<span>Accept</span>
</div>
</button>
</>
);
default:
return <Spinner />;
}
};
export default ApplyButton;

View file

@ -0,0 +1,46 @@
import { useEffect, useRef } from "react";
import Spinner from "./Spinner";
import { ApplyState } from "core/protocol/ideWebview";
interface AutoApplyStatusIndicatorsProps {
applyStateStatus: ApplyState["status"];
onGeneratingComplete: () => Promise<void>;
codeBlockContent: string;
isGenerating: boolean;
}
export default function AutoApplyStatusIndicators({
isGenerating,
onGeneratingComplete,
applyStateStatus,
}: AutoApplyStatusIndicatorsProps) {
const wasGeneratingRef = useRef(isGenerating);
useEffect(() => {
if (wasGeneratingRef.current && !isGenerating) {
onGeneratingComplete();
}
wasGeneratingRef.current = isGenerating;
}, [isGenerating, onGeneratingComplete]);
if (isGenerating) {
debugger;
}
return (
<div>
{isGenerating ? (
<span className="inline-flex items-center gap-2 text-stone-500">
Generating
<Spinner />
</span>
) : applyStateStatus === "streaming" ? (
<span className="inline-flex items-center gap-2 text-stone-500">
Applying
<Spinner />
</span>
) : null}
</div>
);
}

View file

@ -0,0 +1,106 @@
import { useContext, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { text } from "stream/consumers";
import { lightGray } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { defaultModelSelector } from "../../../redux/selectors/modelSelectors";
import { updateApplyState } from "../../../redux/slices/uiStateSlice";
import { RootState } from "../../../redux/store";
import { getFontSize, isJetBrains } from "../../../util";
import ApplyStateControls from "./ApplyButton";
import { isTerminalCodeBlock } from "./utils";
import { v4 as uuidv4 } from "uuid";
import { StepContainerPreToolbarProps } from "./StepContainerPreToolbar";
import ApplyButton from "./ApplyButton";
interface CodeBlockActionsProps extends StepContainerPreToolbarProps {
handleApply: () => Promise<void>;
codeBlockContent: string;
}
export default function CodeBlockActions({
filepath,
language,
isGenerating,
}: CodeBlockActionsProps) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const defaultModel = useSelector(defaultModelSelector);
const streamIdRef = useRef<string | null>(null);
const hasFileExtension = /\.[0-9a-z]+$/i.test(filepath);
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
const applyState = useSelector(
(store: RootState) =>
store.uiState.applyStates.find(
(state) => state.streamId === streamIdRef.current,
)?.status ?? "closed",
);
const [isCopied, setIsCopied] = useState(false);
const isTerminal = isTerminalCodeBlock(language, text);
const onClickCopy = async () => {
if (isJetBrains()) {
await ideMessenger.request("copyText", { text });
} else {
await navigator.clipboard.writeText(text);
}
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
};
async function onClickApply() {
if (isTerminal) {
await ideMessenger.ide.runCommand(text);
return;
}
if (!filepath) return;
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "streaming",
}),
);
ideMessenger.post("applyToFile", {
curSelectedModelTitle: defaultModel.title,
text,
streamId: streamIdRef.current,
filepath,
});
}
const onClickHeader = () => ideMessenger.post("showFile", { filepath });
const onClickAccept = () => ideMessenger.post("acceptDiff", { filepath });
const onClickReject = () => ideMessenger.post("rejectDiff", { filepath });
return (
<div
className={`flex items-center justify-between bg-inherit ${getFontSize() - 2}px border-b px-2 py-1 border-${lightGray}80 m-0`}
>
{filepath && (
<FilePathDisplay
filepath={filepath}
onToggleExpand={onToggleExpand}
onClickHeader={onClickHeader}
isExpanded={isExpanded}
/>
)}
<ApplyButton
applyState={applyState}
onClickApply={onClickApply}
onClickAccept={onClickAccept}
onClickReject={onClickReject}
/>
</div>
);
}

View file

@ -0,0 +1,119 @@
import { useContext, useRef, useState } from "react";
import styled from "styled-components";
import { useDispatch, useSelector } from "react-redux";
import { v4 as uuidv4 } from "uuid";
import { lightGray } from "../..";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { defaultModelSelector } from "../../../redux/selectors/modelSelectors";
import { updateApplyState } from "../../../redux/slices/uiStateSlice";
import { RootState } from "../../../redux/store";
import { getFontSize, isJetBrains } from "../../../util";
import ApplyStateControls from "./ApplyButton";
import FileInfo from "./FileInfo";
import { isTerminalCodeBlock } from "./utils";
interface CodeBlockWithToolBarProps {
text: string;
bottom: boolean;
language: string | undefined;
isNextCodeBlock: boolean;
filepath?: string;
isExpanded: boolean;
onToggleExpand: () => void;
isGenerating: boolean;
}
const CodeBlockWithToolBar = ({
bottom,
filepath,
text,
language,
onToggleExpand,
isGenerating,
isExpanded,
}: CodeBlockWithToolBarProps) => {
return "";
// const dispatch = useDispatch();
// const ideMessenger = useContext(IdeMessengerContext);
// const defaultModel = useSelector(defaultModelSelector);
// const streamIdRef = useRef<string | null>(null);
// if (streamIdRef.current === null) {
// streamIdRef.current = uuidv4();
// }
// const applyState = useSelector(
// (store: RootState) =>
// store.uiState.applyStates.find(
// (state) => state.streamId === streamIdRef.current,
// )?.status ?? "closed",
// );
// const [isCopied, setIsCopied] = useState(false);
// const isTerminal = isTerminalCodeBlock(language, text);
// const onClickCopy = async () => {
// if (isJetBrains()) {
// await ideMessenger.request("copyText", { text });
// } else {
// await navigator.clipboard.writeText(text);
// }
// setIsCopied(true);
// setTimeout(() => setIsCopied(false), 2000);
// };
// async function onClickApply() {
// if (isTerminal) {
// await ideMessenger.ide.runCommand(text);
// return;
// }
// if (!filepath) return;
// dispatch(
// updateApplyState({
// streamId: streamIdRef.current,
// status: "streaming",
// }),
// );
// ideMessenger.post("applyToFile", {
// curSelectedModelTitle: defaultModel.title,
// text,
// streamId: streamIdRef.current,
// filepath,
// });
// }
// const onClickHeader = () => ideMessenger.post("showFile", { filepath });
// const onClickAccept = () => ideMessenger.post("acceptDiff", { filepath });
// const onClickReject = () => ideMessenger.post("rejectDiff", { filepath });
// return (
// <div
// className={`flex items-center justify-between bg-inherit ${getFontSize() - 2}px border-b px-2 py-1 border-${lightGray}80 m-0`}
// >
// {filepath && (
// <FileInfo
// filepath={filepath}
// onToggleExpand={onToggleExpand}
// onClickHeader={onClickHeader}
// isExpanded={isExpanded}
// />
// )}
// <ApplyStateControls
// applyState={applyState}
// isGenerating={isGenerating}
// isCopied={isCopied}
// onClickCopy={onClickCopy}
// onClickApply={onClickApply}
// onClickAccept={onClickAccept}
// onClickReject={onClickReject}
// />
// </div>
// );
};
export default CodeBlockWithToolBar;

View file

@ -0,0 +1,55 @@
import { ChevronDownIcon } from "@heroicons/react/24/outline";
import { getBasename } from "core/util";
import FileIcon from "../../FileIcon";
import { useContext } from "react";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
export interface FileInfoProps {
filepath: string;
isExpanded: boolean;
onClickExpand: () => void;
numLines: number;
}
const FileInfo = ({
filepath,
isExpanded,
onClickExpand,
numLines,
}: FileInfoProps) => {
const ideMessenger = useContext(IdeMessengerContext);
// TODO: Need to turn into relative or fq path
function onClickFileName() {
ideMessenger.post("showFile", {
filepath,
});
}
return (
<div className="flex max-w-[20%] items-center">
<div
onClick={onClickExpand}
className="flex cursor-pointer items-center justify-center"
>
<ChevronDownIcon
className={`h-4 w-4 text-gray-400 ${
isExpanded ? "rotate-0" : "-rotate-90"
}`}
/>
</div>
<div
className="flex cursor-pointer items-center gap-1"
onClick={onClickFileName}
>
<FileIcon height="20px" width="20px" filename={filepath} />
<span className="mr-1 truncate">{getBasename(filepath)}</span>
<span className="truncate text-xs text-stone-500">
({numLines} lines)
</span>
</div>
</div>
);
};
export default FileInfo;

View file

@ -2,10 +2,10 @@ import { debounce } from "lodash";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius, vscEditorBackground } from "..";
import useUIConfig from "../../hooks/useUIConfig";
import { RootState } from "../../redux/store";
import CodeBlockToolBar from "./CodeBlockToolbar";
import { defaultBorderRadius, vscEditorBackground } from "../..";
import useUIConfig from "../../../hooks/useUIConfig";
import { RootState } from "../../../redux/store";
import CodeBlockWithToolBar from "./CodeBlockToolbar(OLD)";
const TopDiv = styled.div`
outline: 0.5px solid rgba(153, 153, 152);
@ -36,6 +36,7 @@ function PreWithToolbar(props: {
language: string | null;
codeBlockIndex: number;
filepath?: string | undefined;
isGenerating?: boolean;
}) {
const uiConfig = useUIConfig();
const toolbarBottom = uiConfig?.codeBlockToolbarPosition == "bottom";
@ -71,7 +72,7 @@ function PreWithToolbar(props: {
onMouseLeave={() => setHovering(false)}
>
{!!props.filepath ? (
<CodeBlockToolBar
<CodeBlockWithToolBar
isNextCodeBlock={nextCodeBlockIndex === props.codeBlockIndex}
text={copyValue}
bottom={toolbarBottom}
@ -79,16 +80,18 @@ function PreWithToolbar(props: {
filepath={props.filepath}
isExpanded={isExpanded}
onToggleExpand={() => setIsExpanded(!isExpanded)}
isGenerating={props.isGenerating}
/>
) : (
hovering && (
<CodeBlockToolBar
<CodeBlockWithToolBar
isNextCodeBlock={nextCodeBlockIndex === props.codeBlockIndex}
text={copyValue}
bottom={toolbarBottom}
language={props.language}
isExpanded={isExpanded}
onToggleExpand={() => setIsExpanded(!isExpanded)}
isGenerating={props.isGenerating}
/>
)
)}

View file

@ -0,0 +1,27 @@
/**
* Custom spinner since HeroIcons doesn't have a good one
*/
const Spinner = () => (
<svg
className="animate-spin-slow h-4 w-4 text-stone-500"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="2"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
);
export default Spinner;

View file

@ -0,0 +1,177 @@
import { debounce } from "lodash";
import { useContext, useEffect, useRef, useState } from "react";
import AutoApplyStatusIndicators from "./AutoApplyStatusIndicators";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import {
incrementNextCodeBlockToApplyIndex,
updateApplyState,
} from "../../../redux/slices/uiStateSlice";
import CodeBlockActions from "./CodeBlockActions";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../../redux/store";
import { IdeMessengerContext } from "../../../context/IdeMessenger";
import {
childrenToText,
getTerminalCommand,
isTerminalCodeBlock,
} from "./utils";
import { v4 as uuidv4 } from "uuid";
import { defaultModelSelector } from "../../../redux/selectors/modelSelectors";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "../..";
import { getFontSize } from "../../../util";
import FileInfo from "./FileInfo";
import styled from "styled-components";
const TopDiv = styled.div`
outline: 1px solid rgba(153, 153, 152);
outline-offset: -0.5px;
border-radius: ${defaultBorderRadius};
margin-bottom: 8px;
background-color: ${vscEditorBackground};
`;
const ToolbarDiv = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
background: inherit;
font-size: ${getFontSize() - 2}px;
padding: 3px;
padding-left: 4px;
padding-right: 4px;
border-bottom: 0.5px solid ${lightGray}80;
margin: 0;
`;
export interface StepContainerPreToolbarProps {
language: string;
filepath: string;
isGenerating: boolean;
codeBlockIndex: number; // To track which codeblock we are applying
children: any;
}
export default function StepContainerPreToolbar(
props: StepContainerPreToolbarProps,
) {
const dispatch = useDispatch();
const ideMessenger = useContext(IdeMessengerContext);
const streamIdRef = useRef<string | null>(null);
const defaultModel = useSelector(defaultModelSelector);
const [isExpanded, setIsExpanded] = useState(false);
const [codeBlockContent, setCodeBlockContent] = useState("");
const nextCodeBlockIndex = useSelector(
(state: RootState) => state.uiState.nextCodeBlockToApplyIndex,
);
const applyStateStatus = useSelector(
(store: RootState) =>
store.uiState.applyStates.find(
(state) => state.streamId === streamIdRef.current,
)?.status ?? "closed",
);
const isMultifileEdit = true; // TODO: Pull from Redux state
const numLinesGenerated = 10; // TODO: Calculate from codeBlockContent
const isTerminal = isTerminalCodeBlock(props.language, codeBlockContent);
const isNextCodeBlock = nextCodeBlockIndex === props.codeBlockIndex;
const hasFileExtension = /\.[0-9a-z]+$/i.test(props.filepath);
if (streamIdRef.current === null) {
streamIdRef.current = uuidv4();
}
// Handle apply keyboard shortcut
useWebviewListener(
"applyCodeFromChat",
handleApply,
[isNextCodeBlock, codeBlockContent],
!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();
};
}
}, [props.children, codeBlockContent]);
async function handleApply() {
if (applyStateStatus === "streaming") return;
if (isTerminal) {
ideMessenger.ide.runCommand(getTerminalCommand(codeBlockContent));
} else {
await ideMessenger.request("applyToFile", {
text: codeBlockContent,
streamId: streamIdRef.current,
curSelectedModelTitle: defaultModel.title,
filepath: props.filepath,
});
dispatch(
updateApplyState({
streamId: streamIdRef.current,
status: "streaming",
}),
);
}
dispatch(incrementNextCodeBlockToApplyIndex({}));
}
function onClickExpand() {
setIsExpanded(!isExpanded);
}
// If we don't have a file extension, we don't render any toolbar
if (!hasFileExtension) {
return props.children;
}
return (
<TopDiv>
<ToolbarDiv>
<FileInfo
filepath={props.filepath}
onClickExpand={onClickExpand}
isExpanded={isExpanded}
numLines={numLinesGenerated}
/>
{isMultifileEdit ? (
<AutoApplyStatusIndicators
isGenerating={props.isGenerating}
applyStateStatus={applyStateStatus}
onGeneratingComplete={handleApply}
codeBlockContent={codeBlockContent}
/>
) : (
<CodeBlockActions
{...props}
handleApply={handleApply}
codeBlockContent={codeBlockContent}
/>
)}
</ToolbarDiv>
{isExpanded && (
<div
className={`overflow-hidden overflow-y-auto ${
isExpanded ? "max-h-[400px] opacity-100" : "max-h-0 opacity-0"
}`}
>
{props.children}
</div>
)}
</TopDiv>
);
}

View file

@ -1,7 +1,7 @@
import { useMemo } from "react";
import { ToolbarButton } from "./CodeBlockToolbar";
import { ToolbarButton } from "./CodeBlockToolbar(OLD)";
import { Tooltip } from "react-tooltip";
import { lightGray } from "..";
import { lightGray } from "../..";
export function ToolbarButtonWithTooltip({
onClick,

View file

@ -0,0 +1 @@
export { default } from "./StepContainerPreToolbar";

View file

@ -0,0 +1,54 @@
const terminalLanguages = ["bash", "sh"];
const commonTerminalCommands = [
"npm",
"pnpm",
"yarn",
"bun",
"deno",
"npx",
"cd",
"ls",
"pwd",
"pip",
"python",
"node",
"git",
"curl",
"wget",
"rbenv",
"gem",
"ruby",
"bundle",
];
export function getTerminalCommand(text: string): string {
return text.startsWith("$ ") ? text.slice(2) : text;
}
export function isTerminalCodeBlock(
language: string | undefined,
text: string,
) {
return (
terminalLanguages.includes(language) ||
((!language || language?.length === 0) &&
(text.trim().split("\n").length === 1 ||
commonTerminalCommands.some((c) => text.trim().startsWith(c))))
);
}
function childToText(child: any) {
if (typeof child === "string") {
return child;
} else if (child?.props) {
return childToText(child.props?.children);
} else if (Array.isArray(child)) {
return childrenToText(child);
} else {
return "";
}
}
export function childrenToText(children: any) {
return children.map((child: any) => childToText(child)).join("");
}

View file

@ -13,13 +13,13 @@ import {
} from "..";
import { getFontSize } from "../../util";
import "./katex.css";
import FilenameLink from "./FilenameLink";
import "./markdown.css";
import PreWithToolbar from "./PreWithToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
import { useSelector } from "react-redux";
import { memoizedContextItemsSelector } from "../../redux/slices/stateSlice";
import { ctxItemToRifWithContents } from "core/commands/util";
import FilenameLink from "./FilenameLink";
import StepContainerPreToolbar from "./StepContainerPreToolbar";
import { SyntaxHighlightedPre } from "./SyntaxHighlightedPre";
const StyledMarkdown = styled.div<{
fontSize?: number;
@ -53,9 +53,19 @@ const StyledMarkdown = styled.div<{
}
background-color: ${vscBackground};
font-family: var(--vscode-font-family), system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell,
"Open Sans", "Helvetica Neue", sans-serif;
font-family:
var(--vscode-font-family),
system-ui,
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
"Open Sans",
"Helvetica Neue",
sans-serif;
font-size: ${(props) => props.fontSize || getFontSize()}px;
padding-left: 8px;
padding-right: 8px;
@ -80,7 +90,7 @@ const StyledMarkdown = styled.div<{
interface StyledMarkdownPreviewProps {
source?: string;
className?: string;
showCodeBorder?: boolean;
isRenderingInStepContainer?: boolean; // Currently only used to control the rendering of codeblocks
scrollLocked?: boolean;
}
@ -122,17 +132,27 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
remarkPlugins: [
remarkMath,
() => {
return (tree) => {
return (tree: any) => {
const lastNode = tree.children[tree.children.length - 1];
const lastCodeNode = lastNode.type === "code" ? lastNode : null;
visit(tree, "code", (node: any) => {
if (!node.lang) {
node.lang === "javascript";
node.lang = "javascript";
} else if (node.lang.includes(".")) {
node.lang = node.lang.split(".").slice(-1)[0];
}
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
if (lastCodeNode === node) {
node.data.hProperties.isGenerating = true;
} else {
node.data.hProperties.isGenerating = false;
}
if (node.meta) {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.filepath = node.meta;
}
});
@ -164,26 +184,31 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
],
rehypeReactOptions: {
components: {
a: ({ node, ...props }) => {
a: ({ node, ...aProps }) => {
return (
<a {...props} target="_blank">
{props.children}
<a {...aProps} target="_blank">
{aProps.children}
</a>
);
},
pre: ({ node, ...preProps }) => {
const { className, filepath } = preProps?.children?.[0]?.props;
const { className, filepath, isGenerating } =
preProps?.children?.[0]?.props;
return props.showCodeBorder ? (
<PreWithToolbar
if (!filepath || !props.isRenderingInStepContainer) {
return <SyntaxHighlightedPre {...preProps} />;
}
// We use a custom toolbar for codeblocks in the step container
return (
<StepContainerPreToolbar
codeBlockIndex={preProps.codeBlockIndex}
language={getLanuageFromClassName(className)}
filepath={filepath}
isGenerating={isGenerating}
>
<SyntaxHighlightedPre {...preProps}></SyntaxHighlightedPre>
</PreWithToolbar>
) : (
<SyntaxHighlightedPre {...preProps}></SyntaxHighlightedPre>
<SyntaxHighlightedPre {...preProps} />
</StepContainerPreToolbar>
);
},
code: ({ node, ...codeProps }) => {

View file

@ -1,8 +1,20 @@
import { useContext } from "react";
import styled from "styled-components";
import { defaultBorderRadius, vscForeground } from "..";
import { vscForeground, defaultBorderRadius } from "..";
import { VscThemeContext } from "../../context/VscTheme";
const generateThemeStyles = (theme: any) => {
return Object.keys(theme)
.map((key) => {
return `
& ${key} {
color: ${theme[key]};
}
`;
})
.join("");
};
const StyledPre = styled.pre<{ theme: any }>`
& .hljs {
color: ${vscForeground};
@ -12,20 +24,10 @@ const StyledPre = styled.pre<{ theme: any }>`
margin-bottom: 0;
border-radius: 0 0 ${defaultBorderRadius} ${defaultBorderRadius} !important;
${(props) =>
Object.keys(props.theme)
.map((key, index) => {
return `
& ${key} {
color: ${props.theme[key]};
}
`;
})
.join("")}
${(props) => generateThemeStyles(props.theme)}
`;
export const SyntaxHighlightedPre = (props: any) => {
export const SyntaxHighlightedPre = () => {
const currentTheme = useContext(VscThemeContext);
return <StyledPre {...props} theme={currentTheme} />;
return <StyledPre theme={currentTheme} />;
};

View file

@ -1,18 +0,0 @@
import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
function VSCodeFileLink(props: { path: string; text?: string }) {
const ideMessenger = useContext(IdeMessengerContext);
return (
<a
href={`file://${props.path}`}
onClick={() => {
ideMessenger.post("openFile", { path: props.path });
}}
>
{props.text || props.path}
</a>
);
}
export default VSCodeFileLink;

View file

@ -86,7 +86,7 @@ function ConfigureProvider() {
<FormProvider {...formMethods}>
<div className="overflow-y-scroll">
<div
className="items-center flex m-0 p-0 sticky top-0"
className="sticky top-0 m-0 flex items-center p-0"
style={{
borderBottom: `0.5px solid ${lightGray}`,
backgroundColor: vscBackground,
@ -97,9 +97,9 @@ function ConfigureProvider() {
width="1.2em"
height="1.2em"
onClick={() => navigate("/addModel")}
className="inline-block ml-4 cursor-pointer"
className="ml-4 inline-block cursor-pointer"
/>
<h3 className="text-lg font-bold m-2 inline-block">
<h3 className="m-2 inline-block text-lg font-bold">
Configure provider
</h3>
</div>
@ -139,7 +139,7 @@ function ConfigureProvider() {
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
className="m-2 rounded-md border-2 border-gray-200 p-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}
@ -169,7 +169,7 @@ function ConfigureProvider() {
<Input
type={d.inputType}
id={d.key}
className="border-2 border-gray-200 rounded-md p-2 m-2"
className="m-2 rounded-md border-2 border-gray-200 p-2"
placeholder={d.placeholder ?? d.label}
defaultValue={d.defaultValue}
min={d.min}

View file

@ -4,9 +4,9 @@ import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import { table } from "table";
import { lightGray, vscBackground, vscInputBackground } from "../components";
import { CopyButton } from "../components/markdown/CopyButton";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useNavigationListener } from "../hooks/useNavigationListener";
import { CopyButton } from "../components/gui/CopyButton";
const Th = styled.th`
padding: 0.5rem;

View file

@ -22,7 +22,7 @@ module.exports = {
},
extend: {
animation: {
"spin-slow": "spin 10s linear infinite",
"spin-slow": "spin 6s linear infinite",
},
colors: {
"vsc-background": "rgb(var(--vsc-background) / <alpha-value>)",