✨ TipTap code selection

This commit is contained in:
Nate Sesti 2023-12-24 14:12:22 -05:00
parent 41557d379e
commit a0a1fc0f1d
15 changed files with 323 additions and 184 deletions

View file

@ -2,6 +2,10 @@ import DOMPurify from "dompurify";
import { themeIcons } from "seti-file-icons";
const FileIcon = ({ filename, height, width }) => {
const filenameParts = filename.includes(" (")
? filename.split(" ")
: [filename, ""];
filenameParts.pop();
const getIcon = themeIcons({
blue: "#268bd2",
grey: "#657b83",
@ -16,7 +20,7 @@ const FileIcon = ({ filename, height, width }) => {
ignore: "#586e75",
});
// Sanitize the SVG string before rendering it
const { svg, color } = getIcon(filename);
const { svg, color } = getIcon(filenameParts.join(" "));
const sanitizedSVG = DOMPurify.sanitize(svg);
return (

View file

@ -2,40 +2,38 @@ import { Tooltip } from "react-tooltip";
import styled, { keyframes } from "styled-components";
import { getFontSize } from "../util";
export const VSC_SECONDARY_DARK_VAR = "--vscode-input-background";
export const VSC_BACKGROUND_VAR = "--vscode-sideBar-background";
export const VSC_FOREGROUND_VAR = "--vscode-editor-foreground";
export const VSC_BUTTON_BACKGROUND_VAR = "--vscode-button-background";
export const VSC_EDITOR_BACKGROUND_VAR = "--vscode-editor-background";
export const VSC_THEME_COLOR_VARS = [
VSC_SECONDARY_DARK_VAR,
VSC_BACKGROUND_VAR,
VSC_FOREGROUND_VAR,
VSC_BUTTON_BACKGROUND_VAR,
VSC_EDITOR_BACKGROUND_VAR,
];
export const defaultBorderRadius = "5px";
export const lightGray = "#646464";
export const buttonColor = "#1bbe84";
export const buttonColorHover = "#1bbe84a8";
export const secondaryDark = "var(--vscode-input-background, rgb(45 45 45))";
export const secondaryDark = `var(${VSC_SECONDARY_DARK_VAR}, rgb(45 45 45))`;
// export const vscBackground = "var(--vscode-editor-background, rgb(30 30 30))";
export const vscBackground = "var(--vscode-sideBar-background, rgb(30 30 30))";
export const vscForeground = "var(--vscode-editor-foreground, #fff)";
export const vscButtonBackground = "var(--vscode-button-background, #1bbe84)";
export const vscBackground = `var(${VSC_BACKGROUND_VAR}, rgb(30 30 30))`;
export const vscForeground = `var(${VSC_FOREGROUND_VAR}, #fff)`;
export const vscButtonBackground = `var(${VSC_BUTTON_BACKGROUND_VAR}, #1bbe84)`;
export const vscEditorBackground = `var(${VSC_EDITOR_BACKGROUND_VAR}, rgb(30 30 30))`;
if (typeof document !== "undefined") {
const cachedForeground = localStorage.getItem("--vscode-editor-foreground");
const cachedBackground = localStorage.getItem("--vscode-editor-background");
const cachedSecondaryDark = localStorage.getItem(
"--vscode-list-hoverBackground"
);
if (cachedForeground) {
document.body.style.setProperty(
"--vscode-editor-foreground",
cachedForeground
);
}
if (cachedBackground) {
document.body.style.setProperty(
"--vscode-editor-background",
cachedBackground
);
}
if (cachedSecondaryDark) {
document.body.style.setProperty(
"--vscode-list-hoverBackground",
cachedSecondaryDark
);
for (const colorVar of VSC_THEME_COLOR_VARS) {
const cached = localStorage.getItem(colorVar);
if (cached) {
document.body.style.setProperty(colorVar, cached);
}
}
}

View file

@ -0,0 +1,54 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
import { ContextItemWithId } from "core";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
const CodeBlockComponent = ({ node, deleteNode }) => {
const item: ContextItemWithId = node.attrs.item;
return (
<NodeViewWrapper className="code-block-with-content">
<CodeSnippetPreview
item={item}
onDelete={() => {
deleteNode();
}}
/>
</NodeViewWrapper>
);
};
export default Node.create({
name: "codeBlock",
group: "block",
content: "inline*",
atom: true,
selectable: true,
parseHTML() {
return [
{
tag: "code-block",
},
];
},
addAttributes() {
return {
item: {
default: "",
},
};
},
renderHTML({ HTMLAttributes }) {
return ["code-block", mergeAttributes(HTMLAttributes), 0];
},
addNodeView() {
return ReactNodeViewRenderer(CodeBlockComponent);
},
});

View file

@ -1151,10 +1151,7 @@ const ComboBox = React.forwardRef((props: ComboBoxProps, ref) => {
{showContextToggleOn && selectedContextItems.length > 0 && (
<div>
{selectedContextItems.map((item) => (
<CodeSnippetPreview
index={props.index}
item={item}
></CodeSnippetPreview>
<CodeSnippetPreview item={item}></CodeSnippetPreview>
))}
</div>
)}

View file

@ -4,6 +4,7 @@ import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { RootStore } from "../../redux/store";
import TipTapEditor from "./TipTapEditor";
import { ComboBoxItemType } from "./types";
const gradient = keyframes`
0% {
@ -62,6 +63,7 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
return {
title: `/${cmd.name}`,
description: cmd.description,
type: "slashCommand" as ComboBoxItemType,
};
}) || []
);

View file

@ -1,21 +0,0 @@
interface InlineSpanProps {
color?: string;
children: React.ReactNode;
}
function InlineSpan(props: InlineSpanProps) {
return (
<span
style={{
color: props.color,
float: "right",
textAlign: "right",
}}
className="whitespace-nowrap overflow-hidden overflow-ellipsis ml-2"
>
{props.children}
</span>
);
}
export default InlineSpan;

View file

@ -1,7 +1,7 @@
import styled from "styled-components";
import { defaultBorderRadius, lightGray, secondaryDark } from "..";
const StyledDiv = styled.div`
const StyledDiv = styled.div<{ hidden?: boolean }>`
position: absolute;
display: flex;
gap: 4px;
@ -10,6 +10,8 @@ const StyledDiv = styled.div`
width: calc(100% - 10px);
background-color: ${secondaryDark};
${(props) => (props.hidden ? "display: none;" : "")}
align-items: center;
z-index: 50;
font-size: 10px;

View file

@ -2,6 +2,7 @@ import {
ArrowUpOnSquareIcon,
AtSymbolIcon,
BeakerIcon,
ChevronDoubleRightIcon,
Cog6ToothIcon,
CommandLineIcon,
ExclamationCircleIcon,
@ -24,7 +25,7 @@ import {
vscForeground,
} from "..";
import FileIcon from "../FileIcon";
import { ComboBoxItem } from "./types";
import { ComboBoxItem, ComboBoxItemType } from "./types";
const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
file: FolderIcon,
@ -45,11 +46,21 @@ const ICONS_FOR_DROPDOWN: { [key: string]: any } = {
"/issue": ExclamationCircleIcon,
};
function DropdownIcon(props: { provider: string; className?: string }) {
function DropdownIcon(props: {
provider: string;
className?: string;
type: ComboBoxItemType;
}) {
const Icon = ICONS_FOR_DROPDOWN[props.provider];
if (!Icon) {
return (
return props.type === "contextProvider" ? (
<AtSymbolIcon className={props.className} height="1.2em" width="1.2em" />
) : (
<ChevronDoubleRightIcon
className={props.className}
height="1.2em"
width="1.2em"
/>
);
}
return <Icon className={props.className} height="1.2em" width="1.2em" />;
@ -89,15 +100,26 @@ const ItemDiv = styled.div`
interface MentionListProps {
items: ComboBoxItem[];
command: (item: ComboBoxItem) => void;
subMenuTitle?: string;
enterSubmenu?: () => void;
}
const MentionList = forwardRef((props: MentionListProps, ref) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const [subMenuTitle, setSubMenuTitle] = useState<string | undefined>(
undefined
);
const selectItem = (index) => {
const item = props.items[index];
if (item.id === "file") {
setSubMenuTitle("Files - Type to search");
props.enterSubmenu(); // TODO: how to pass this prop?
return;
}
if (item) {
props.command(item);
}
@ -142,6 +164,7 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
return (
<ItemsDiv>
{subMenuTitle && <ItemDiv>{subMenuTitle}</ItemDiv>}
{props.items.length ? (
props.items.map((item, index) => (
<ItemDiv
@ -153,15 +176,20 @@ const MentionList = forwardRef((props: MentionListProps, ref) => {
>
<span className="flex justify-between w-full items-center">
<div className="flex items-center justify-center">
{props.subMenuTitle && (
{item.type === "file" && (
<FileIcon
height="20px"
width="20px"
filename={item.title}
></FileIcon>
)}
{/* <DropdownIcon provider={item.title} className="mr-2" /> */}
<DropdownIcon provider={item.id} className="mr-2" />
{item.type !== "file" && (
<DropdownIcon
provider={item.id}
type={item.type}
className="mr-2"
/>
)}
{item.title}
{" "}
</div>

View file

@ -23,3 +23,7 @@
height: 0;
pointer-events: none;
}
.gap-cursor {
border-top: 1px solid white;
}

View file

@ -5,8 +5,8 @@ import Paragraph from "@tiptap/extension-paragraph";
import Placeholder from "@tiptap/extension-placeholder";
import Text from "@tiptap/extension-text";
import { EditorContent, JSONContent, useEditor } from "@tiptap/react";
import { IContextProvider } from "core";
import { useEffect, useState } from "react";
import { ContextItemWithId, IContextProvider, RangeInFile } from "core";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";
import {
@ -15,10 +15,13 @@ import {
secondaryDark,
vscForeground,
} from "..";
import { SearchContext } from "../../App";
import useHistory from "../../hooks/useHistory";
import { setTakenActionTrue } from "../../redux/slices/miscSlice";
import { RootStore } from "../../redux/store";
import { postToIde } from "../../util/ide";
import { isMetaEquivalentKeyPressed } from "../../util";
import { isJetBrains, postToIde } from "../../util/ide";
import CodeBlockExtension from "./CodeBlockExtension";
import { SlashCommand } from "./CommandsExtension";
import InputToolbar from "./InputToolbar";
import "./TipTapEditor.css";
@ -34,7 +37,7 @@ const InputBoxDiv = styled.div`
border-radius: ${defaultBorderRadius};
margin: 0;
height: auto;
width: 100%;
width: calc(100% - 18px);
background-color: ${secondaryDark};
color: ${vscForeground};
z-index: 1;
@ -66,13 +69,13 @@ interface TipTapEditorProps {
function TipTapEditor(props: TipTapEditorProps) {
const dispatch = useDispatch();
const [miniSearch, firstResults] = useContext(SearchContext);
const historyLength = useSelector(
(store: RootStore) => store.state.history.length
);
const contextProviders = useSelector(
(state: RootStore) => state.state.config.contextProviders || []
);
const [inputFocused, setInputFocused] = useState(false);
const { saveSession } = useHistory(dispatch);
@ -93,10 +96,11 @@ function TipTapEditor(props: TipTapEditorProps) {
// Enter: () =>
// this.editor.commands.first(({ commands }) => [
// () => {
// props.onEnter(collectInput(editor));
// props.onEnter(this.editor.getJSON());
// return true;
// },
// ]),
// Enter: () => true,
"Shift-Enter": () =>
this.editor.commands.first(({ commands }) => [
@ -124,7 +128,22 @@ function TipTapEditor(props: TipTapEditorProps) {
HTMLAttributes: {
class: "mention",
},
suggestion: getMentionSuggestion(props.availableContextProviders),
suggestion: getMentionSuggestion(
props.availableContextProviders,
miniSearch,
firstResults,
() => {
const contents = editor.getText();
const indexOfAt = contents.lastIndexOf("@");
editor.commands.deleteRange({
from: indexOfAt,
to: contents.length,
});
editor.commands.focus();
}
),
renderLabel: (props) => {
return `@${props.node.attrs.label || props.node.attrs.id}`;
},
@ -138,6 +157,7 @@ function TipTapEditor(props: TipTapEditorProps) {
return props.node.attrs.label;
},
}),
CodeBlockExtension,
],
editorProps: {
attributes: {
@ -147,18 +167,39 @@ function TipTapEditor(props: TipTapEditorProps) {
},
content: props.editorState || props.content || "",
},
[props.availableContextProviders, historyLength]
[props.availableContextProviders, historyLength, miniSearch, firstResults]
);
const [inputFocused, setInputFocused] = useState(false);
// This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview
const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false);
useEffect(() => {
if (!editor) return;
const handleKeyDown = (event: any) => {
if (
isMetaEquivalentKeyPressed(event) &&
(isJetBrains() ? event.code === "KeyJ" : event.code === "KeyM")
) {
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
// IDE event listeners
useEffect(() => {
if (props.isMainInput) {
editor.commands.focus();
editor?.commands.focus();
}
const handler = (event: any) => {
const handler = async (event: any) => {
if (!editor) return;
if (event.data.type === "focusContinueInput") {
editor.commands.focus();
if (historyLength > 0) {
@ -178,13 +219,39 @@ function TipTapEditor(props: TipTapEditorProps) {
} else if (event.data.type === "focusContinueInputWithNewSession") {
saveSession();
dispatch(setTakenActionTrue(null));
} else if (event.data.type === "highlightedCode") {
if (!ignoreHighlightedCode) {
const rif: RangeInFile & { contents: string } =
event.data.rangeInFileWithContents;
const basename = rif.filepath.split(/[\\/]/).pop();
const item: ContextItemWithId = {
content: rif.contents,
name: `${basename} (${rif.range.start.line + 1}-${
rif.range.end.line + 1
})`,
description: rif.filepath,
id: {
providerTitle: "file",
itemId: rif.filepath,
},
};
editor.commands.insertContentAt(0, {
type: "codeBlock",
attrs: {
item,
},
});
await new Promise((resolve) => setTimeout(resolve, 100));
editor.commands.focus("end");
}
setIgnoreHighlightedCode(false);
}
};
window.addEventListener("message", handler);
return () => {
window.removeEventListener("message", handler);
};
}, [editor, props.isMainInput, historyLength]);
}, [editor, props.isMainInput, historyLength, ignoreHighlightedCode]);
return (
<InputBoxDiv>
@ -193,9 +260,14 @@ function TipTapEditor(props: TipTapEditorProps) {
onFocus={() => {
setInputFocused(true);
}}
onBlur={(e) => {
onBlur={() => {
setInputFocused(false);
}}
// onKeyDown={(e) => {
// if (e.key === "Enter") {
// props.onEnter(editor.getJSON());
// }
// }}
/>
<InputToolbar
hidden={!(inputFocused || props.isMainInput)}

View file

@ -1,12 +1,17 @@
import { ReactRenderer } from "@tiptap/react";
import { IContextProvider } from "core";
import MiniSearch from "minisearch";
import tippy from "tippy.js";
import MentionList from "./MentionList";
import { ComboBoxItem } from "./types";
import { ComboBoxItem, ComboBoxItemType } from "./types";
function getSuggestion(items: (props: { query: string }) => ComboBoxItem[]) {
function getSuggestion(
items: (props: { query: string }) => ComboBoxItem[],
enterSubmenu: () => void = () => {}
) {
return {
items,
allowSpaces: true,
render: () => {
let component;
let popup;
@ -14,7 +19,7 @@ function getSuggestion(items: (props: { query: string }) => ComboBoxItem[]) {
return {
onStart: (props) => {
component = new ReactRenderer(MentionList, {
props,
props: { ...props, enterSubmenu },
editor: props.editor,
});
@ -65,11 +70,45 @@ function getSuggestion(items: (props: { query: string }) => ComboBoxItem[]) {
};
}
function getFileItems(
query: string,
miniSearch: MiniSearch,
firstResults: any[]
) {
let res: any[] = miniSearch.search(query.trim() === "" ? "/" : query, {
prefix: true,
fuzzy: 1,
});
if (res.length === 0) {
res = firstResults;
}
return (
res?.slice(0, 20).map((hit) => {
const item = {
title: hit.basename,
description: hit.basename,
id: hit.id,
content: hit.id,
label: hit.basename,
type: "file" as ComboBoxItemType,
};
return item;
}) || []
);
}
export function getMentionSuggestion(
availableContextProviders: IContextProvider[]
availableContextProviders: IContextProvider[],
miniSearch: MiniSearch,
firstResults: any[],
enterSubmenu: () => void
) {
const items = ({ query }) => {
return (
if (query.startsWith("file ")) {
return getFileItems(query.substring(5), miniSearch, firstResults);
}
const mainResults =
availableContextProviders
?.filter(
(provider) =>
@ -86,11 +125,16 @@ export function getMentionSuggestion(
id: provider.description.title,
title: provider.description.displayTitle,
label: provider.description.displayTitle,
type: "contextProvider" as ComboBoxItemType,
}))
.sort((c, _) => (c.id === "file" ? -1 : 1)) || []
);
.sort((c, _) => (c.id === "file" ? -1 : 1)) || [];
if (mainResults.length === 0) {
return getFileItems(query, miniSearch, firstResults);
}
return mainResults;
};
return getSuggestion(items);
return getSuggestion(items, enterSubmenu);
}
export function getCommandSuggestion(availableSlashCommands: ComboBoxItem[]) {
@ -107,6 +151,7 @@ export function getCommandSuggestion(availableSlashCommands: ComboBoxItem[]) {
id: provider.title,
title: provider.title,
label: provider.title,
type: "slashCommand" as ComboBoxItemType,
}));
};
return getSuggestion(items);

View file

@ -1,12 +1,9 @@
export type ComboBoxItemType = "contextProvider" | "slashCommand" | "file";
export interface ComboBoxItem {
title: string;
description: string;
id?: string;
content?: string;
type: ComboBoxItemType;
}
export type DropdownState =
| "contextProviders"
| "closed"
| "slashCommands"
| "files";

View file

@ -1,41 +1,43 @@
import {
ChevronDownIcon,
ChevronUpIcon,
TrashIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
import React from "react";
import { useDispatch } from "react-redux";
import styled from "styled-components";
import { defaultBorderRadius, lightGray, secondaryDark } from "..";
import { deleteContextWithIds } from "../../redux/slices/stateSlice";
import { defaultBorderRadius, lightGray, vscEditorBackground } from "..";
import { getFontSize, getMarkdownLanguageTagForFile } from "../../util";
import { postToIde } from "../../util/ide";
import FileIcon from "../FileIcon";
import HeaderButtonWithText from "../HeaderButtonWithText";
import StyledMarkdownPreview from "./StyledMarkdownPreview";
const MAX_PREVIEW_HEIGHT = 160;
const PreviewMarkdownDiv = styled.div<{ scroll: boolean }>`
padding: 0px;
background-color: ${secondaryDark};
background-color: ${vscEditorBackground};
border-radius: ${defaultBorderRadius};
margin: 8px;
border: 0.5px solid ${lightGray};
margin-top: 4px;
margin-bottom: 4px;
overflow: hidden;
position: relative;
& div {
background-color: ${secondaryDark};
background-color: ${vscEditorBackground};
}
& code {
overflow: ${(props) => (props.scroll ? "scroll" : "hidden")} !important;
overflow-y: ${(props) => (props.scroll ? "scroll" : "hidden")} !important;
}
`;
const PreviewMarkdownHeader = styled.p`
margin: 0;
padding: 4px 8px;
border-bottom: 1px solid ${lightGray};
padding: 2px 6px;
border-bottom: 0.5px solid ${lightGray};
word-break: break-all;
font-size: ${getFontSize()}px;
display: flex;
@ -44,7 +46,7 @@ const PreviewMarkdownHeader = styled.p`
interface CodeSnippetPreviewProps {
item: ContextItemWithId;
index: number;
onDelete?: () => void;
}
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
@ -53,6 +55,8 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
const [scrollLocked, setScrollLocked] = React.useState(true);
const [hovered, setHovered] = React.useState(false);
const codeBlockRef = React.useRef<HTMLPreElement>(null);
return (
<PreviewMarkdownDiv
scroll={!scrollLocked}
@ -93,31 +97,22 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
{props.item.name}
</div>
<div className="flex items-center">
<HeaderButtonWithText
text="Delete"
onClick={() => {
dispatch(
deleteContextWithIds({
ids: [props.item.id],
index: props.index,
})
);
}}
>
<TrashIcon width="1.2em" height="1.2em" />
<HeaderButtonWithText text="Delete" onClick={props.onDelete}>
<XMarkIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
</div>
</PreviewMarkdownHeader>
<pre className="m-0">
<pre className="m-0" ref={codeBlockRef}>
<StyledMarkdownPreview
source={`\`\`\`${getMarkdownLanguageTagForFile(
props.item.description
)}\n${props.item.content}\n\`\`\``}
maxHeight={200}
maxHeight={MAX_PREVIEW_HEIGHT}
showCodeBorder={false}
/>
</pre>
{hovered && (
{hovered && codeBlockRef.current?.scrollHeight > MAX_PREVIEW_HEIGHT && (
<HeaderButtonWithText
className="bottom-1 right-1 absolute"
text={scrollLocked ? "Scroll" : "Lock Scroll"}

View file

@ -1,12 +1,12 @@
import MarkdownPreview from "@uiw/react-markdown-preview";
import styled from "styled-components";
import {
defaultBorderRadius,
lightGray,
secondaryDark,
vscBackground,
vscEditorBackground,
vscForeground,
} from "..";
import MarkdownPreview from "@uiw/react-markdown-preview";
import { getFontSize } from "../../util";
import LinkableCode from "./LinkableCode";
@ -14,12 +14,12 @@ const StyledMarkdownPreviewComponent = styled(MarkdownPreview)<{
light?: boolean;
fontSize?: number;
maxHeight?: number;
showBorder?: boolean;
}>`
pre {
background-color: ${(props) =>
props.light ? vscBackground : secondaryDark};
props.light ? vscBackground : vscEditorBackground};
border-radius: ${defaultBorderRadius};
/* border: 0.5px solid ${lightGray}; */
max-width: calc(100vw - 24px);
}
@ -28,14 +28,23 @@ const StyledMarkdownPreviewComponent = styled(MarkdownPreview)<{
color: #f78383;
word-wrap: break-word;
border-radius: ${defaultBorderRadius};
background-color: ${secondaryDark};
background-color: ${vscEditorBackground};
}
pre > code {
background-color: ${(props) =>
props.light ? vscBackground : secondaryDark};
props.light ? vscBackground : vscEditorBackground};
color: ${vscForeground};
padding: 12px;
padding: ${(props) => (props.showBorder ? "12px" : "0px 2px")};
border-radius: ${defaultBorderRadius};
${(props) => {
if (props.showBorder) {
return `
border: 0.5px solid ${lightGray};
`;
}
}}
${(props) => {
if (props.maxHeight) {
@ -69,6 +78,7 @@ interface StyledMarkdownPreviewProps {
source?: string;
maxHeight?: number;
className?: string;
showCodeBorder?: boolean;
}
function StyledMarkdownPreview(props: StyledMarkdownPreviewProps) {
@ -93,6 +103,7 @@ function StyledMarkdownPreview(props: StyledMarkdownPreviewProps) {
wrapperElement={{
"data-color-mode": "dark",
}}
showBorder={props.showCodeBorder}
/>
);
}

View file

@ -1,20 +1,16 @@
import { Dispatch } from "@reduxjs/toolkit";
import { useEffect, useState } from "react";
import { useEffect } from "react";
import { setServerStatusMessage } from "../redux/slices/miscSlice";
import { errorPopup, isJetBrains, postToIde } from "../util/ide";
import { errorPopup, postToIde } from "../util/ide";
import {
intermediateToFinalConfig,
serializedToIntermediateConfig,
} from "core/config/load";
import { ExtensionIde } from "core/ide/index";
import { VSC_THEME_COLOR_VARS } from "../components";
import { setVscMachineId } from "../redux/slices/configSlice";
import {
addHighlightedCode,
setConfig,
setInactive,
} from "../redux/slices/stateSlice";
import { isMetaEquivalentKeyPressed } from "../util";
import { setConfig, setInactive } from "../redux/slices/stateSlice";
import useChatHandler from "./useChatHandler";
function useSetup(dispatch: Dispatch<any>) {
@ -64,29 +60,6 @@ function useSetup(dispatch: Dispatch<any>) {
const { streamResponse } = useChatHandler(dispatch);
// This is a mechanism for overriding the IDE keyboard shortcut when inside of the webview
const [ignoreHighlightedCode, setIgnoreHighlightedCode] = useState(false);
useEffect(() => {
const handleKeyDown = (event: any) => {
if (
isMetaEquivalentKeyPressed(event) &&
(isJetBrains() ? event.code === "KeyJ" : event.code === "KeyM")
) {
setIgnoreHighlightedCode(true);
setTimeout(() => {
setIgnoreHighlightedCode(false);
}, 100);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, []);
// IDE event listeners
useEffect(() => {
const eventListener = (event: any) => {
@ -100,18 +73,6 @@ function useSetup(dispatch: Dispatch<any>) {
dispatch(setVscMachineId(event.data.vscMachineId));
// dispatch(setVscMediaUrl(event.data.vscMediaUrl));
break;
case "highlightedCode":
if (ignoreHighlightedCode) {
setIgnoreHighlightedCode(false);
break;
}
dispatch(
addHighlightedCode({
rangeInFileWithContents: event.data.rangeInFileWithContents,
edit: event.data.edit,
})
);
break;
case "serverStatus":
dispatch(setServerStatusMessage(event.data.message));
@ -129,27 +90,17 @@ function useSetup(dispatch: Dispatch<any>) {
};
window.addEventListener("message", eventListener);
return () => window.removeEventListener("message", eventListener);
}, [ignoreHighlightedCode]);
}, []);
// Save theme colors to local storage
useEffect(() => {
if (document.body.style.getPropertyValue("--vscode-editor-foreground")) {
localStorage.setItem(
"--vscode-editor-foreground",
document.body.style.getPropertyValue("--vscode-editor-foreground")
);
}
if (document.body.style.getPropertyValue("--vscode-editor-background")) {
localStorage.setItem(
"--vscode-editor-background",
document.body.style.getPropertyValue("--vscode-editor-background")
);
}
if (document.body.style.getPropertyValue("--vscode-list-hoverBackground")) {
localStorage.setItem(
"--vscode-list-hoverBackground",
document.body.style.getPropertyValue("--vscode-list-hoverBackground")
);
for (const colorVar of VSC_THEME_COLOR_VARS) {
if (document.body.style.getPropertyValue(colorVar)) {
localStorage.setItem(
colorVar,
document.body.style.getPropertyValue(colorVar)
);
}
}
}, []);
}