feat: handle deletions

This commit is contained in:
Patrick Erichsen 2025-04-03 22:32:28 -07:00
parent dca4685bac
commit 2c8cee9fd4
23 changed files with 154 additions and 170 deletions

View file

@ -34,7 +34,6 @@ export default function FileIcon({ filename, height, width }: FileIconProps) {
ignore: "#586e75",
});
console.log({ file });
// Sanitize the SVG string before rendering it
const { svg, color } = getIcon(file);
const sanitizedSVG = DOMPurify.sanitize(svg);

View file

@ -10,9 +10,8 @@ import { selectDefaultModel } from "../../../redux/slices/configSlice";
import { selectIsInEditMode } from "../../../redux/slices/sessionSlice";
import InputToolbar, { ToolbarOptions } from "../InputToolbar";
import { ComboBoxItem } from "../types";
import { DragOverlay } from "./DragOverlay";
import { DragOverlay, InputBoxDiv } from "./components";
import { useMainEditor } from "./MainEditorProvider";
import { InputBoxDiv } from "./StyledComponents";
import "./TipTapEditor.css";
import { handleImageFile } from "./utils";
import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig";
@ -31,6 +30,9 @@ export interface TipTapEditorProps {
toolbarOptions?: ToolbarOptions;
placeholder?: string;
historyKey: string;
// TODO: This isn't actually used anywhere in this component, but it appears
// to be pulled into some of our TipTap extensions.
inputId: string;
}

View file

@ -87,6 +87,10 @@ export function ExpandablePreview(props: ExpandablePreviewProps) {
const contentRef = useRef<HTMLDivElement>(null);
const [contentDims, setContentDims] = useState({ width: 0, height: 0 });
useEffect(() => {
setHidden(props.initiallyHidden ?? false);
}, [props.initiallyHidden]);
useEffect(() => {
const resizeObserver = new ResizeObserver(() => {
setContentDims({
@ -154,7 +158,6 @@ export function ExpandablePreview(props: ExpandablePreviewProps) {
</div>
</div>
{/* Updated content section */}
{!hidden && (
<ContentContainer expanded={isExpanded}>
<ScrollableContent

View file

@ -0,0 +1,23 @@
import {
NodeViewWrapper as TiptapNodeViewWrapper,
NodeViewWrapperProps as TiptapNodeViewWrapperProps,
} from "@tiptap/react";
import React from "react";
interface NodeViewWrapperProps {
children: React.ReactNode;
}
export const NodeViewWrapper: React.FC<NodeViewWrapperProps> = ({
children,
}) => {
// Not setting this as a "p" will cause issues with foreign keyboards
// See https://github.com/continuedev/continue/issues/3199
const nodeViewWrapperTag: TiptapNodeViewWrapperProps["as"] = "p";
return (
<TiptapNodeViewWrapper className={`mt-0`} as={nodeViewWrapperTag}>
{children}
</TiptapNodeViewWrapper>
);
};

View file

@ -3,12 +3,14 @@ import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import { MentionOptions } from "./types";
export const AddCodeToEditExtension = Node.create<MentionOptions>({
export const AddCodeToEdit = Node.create<MentionOptions>({
name: "add-code-to-edit",
addOptions() {
return {
HTMLAttributes: {},
HTMLAttributes: {
class: "add-code-to-edit",
},
renderHTML({ options, node }) {
return [
"span",

View file

@ -1,8 +1,8 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { CodeblockPreview } from "./CodeblockPreview";
import { CodeBlockPreview } from "./CodeBlockPreview";
export const CodeblockExtension = Node.create({
export const CodeBlock = Node.create({
name: "codeblock",
group: "block",
@ -37,6 +37,6 @@ export const CodeblockExtension = Node.create({
},
addNodeView() {
return ReactNodeViewRenderer(CodeblockPreview);
return ReactNodeViewRenderer(CodeBlockPreview);
},
});

View file

@ -1,8 +1,4 @@
import {
NodeViewProps,
NodeViewWrapper,
NodeViewWrapperProps,
} from "@tiptap/react";
import { NodeViewProps } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { ctxItemToRifWithContents } from "core/commands/util";
import { dedent, getMarkdownLanguageTagForFile } from "core/util";
@ -13,13 +9,14 @@ import { useAppSelector } from "../../../../../redux/hooks";
import FileIcon from "../../../../FileIcon";
import StyledMarkdownPreview from "../../../../markdown/StyledMarkdownPreview";
import { ExpandablePreview } from "../../components/ExpandablePreview";
import { NodeViewWrapper } from "../../components/NodeViewWrapper";
const backticksRegex = /`{3,}/gm;
/**
* Component for displaying a code block in the TipTap editor
*/
export const CodeblockPreview = ({
export const CodeBlockPreview = ({
node,
deleteNode,
selected,
@ -29,10 +26,6 @@ export const CodeblockPreview = ({
const isFirstContextItem = false; // TODO: fix this, decided not worth the insane renders for now
const ideMessenger = useContext(IdeMessengerContext);
// Not setting this as a "p" will cause issues with foreign keyboards
// See https://github.com/continuedev/continue/issues/3199
const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p";
const newestCodeblockForInputId = useAppSelector(
(store) => store.session.newestCodeblockForInput[inputId],
);
@ -41,6 +34,12 @@ export const CodeblockPreview = ({
return newestCodeblockForInputId !== item.id.itemId;
}, [newestCodeblockForInputId, item.id.itemId]);
console.log({
newestCodeblockForInputId,
id: item.id.itemId,
initiallyHidden,
});
const content = useMemo(() => {
return dedent`${item.content}`;
}, [item.content]);
@ -79,10 +78,7 @@ export const CodeblockPreview = ({
: undefined;
return (
<NodeViewWrapper
className="code-block-with-content"
as={nodeViewWrapperTag}
>
<NodeViewWrapper>
<ExpandablePreview
title={item.name}
icon={<FileIcon height="16px" width="16px" filename={item.name} />}

View file

@ -0,0 +1 @@
export * from "./CodeBlock";

View file

@ -1 +0,0 @@
export * from "./CodeblockExtension";

View file

@ -3,12 +3,15 @@ import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import { MentionOptions } from "./types";
export const MentionExtension = Node.create<MentionOptions>({
export const Mention = Node.create<MentionOptions>({
name: "mention",
addOptions() {
return {
HTMLAttributes: {},
HTMLAttributes: {
class: "mention",
},
renderHTML({ options, node }) {
return [
"span",

View file

@ -1,14 +1,14 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { ReactNodeViewRenderer } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { PromptBlockPreview } from "./PromptBlockPreview";
export interface PromptOptions {
export interface PromptBlockOptions {
HTMLAttributes: Record<string, any>;
}
export interface PromptAttributes {
export interface PromptBlockAttributes {
item: ContextItemWithId;
inputId: string;
}
@ -32,13 +32,15 @@ declare module "@tiptap/core" {
/**
* Extension for adding prompt blocks to the Tiptap editor
*/
export const PromptExtension = Node.create<PromptOptions>({
export const PromptBlock = Node.create<PromptBlockOptions>({
name: "prompt-block",
group: "block",
addOptions() {
return {
HTMLAttributes: {},
HTMLAttributes: {
class: "prompt-block",
},
};
},
@ -71,7 +73,8 @@ export const PromptExtension = Node.create<PromptOptions>({
addCommands() {
return {
insertPrompt: (item: ContextItemWithId, inputId: string) =>
insertPrompt:
(item: ContextItemWithId, inputId: string) =>
({ commands }) => {
return commands.insertContent({
type: this.name,
@ -82,27 +85,29 @@ export const PromptExtension = Node.create<PromptOptions>({
});
},
clearPrompt: () => ({ state, commands }) => {
// Find all prompt-block nodes in the document
const promptNodes: { pos: number, node: ProseMirrorNode }[] = [];
state.doc.descendants((node, pos) => {
if (node.type.name === this.name) {
promptNodes.push({ pos, node });
return false; // Don't descend into this node
clearPrompt:
() =>
({ state, commands }) => {
// Find all prompt-block nodes in the document
const promptNodes: { pos: number; node: ProseMirrorNode }[] = [];
state.doc.descendants((node, pos) => {
if (node.type.name === this.name) {
promptNodes.push({ pos, node });
return false; // Don't descend into this node
}
return true;
});
// Delete all found prompt blocks
// We process them in reverse order so that deleting one doesn't affect the position of others
for (let i = promptNodes.length - 1; i >= 0; i--) {
const { pos, node } = promptNodes[i];
commands.deleteRange({ from: pos, to: pos + node.nodeSize });
}
return true;
});
// Delete all found prompt blocks
// We process them in reverse order so that deleting one doesn't affect the position of others
for (let i = promptNodes.length - 1; i >= 0; i--) {
const { pos, node } = promptNodes[i];
commands.deleteRange({ from: pos, to: pos + node.nodeSize });
}
// Return true if we deleted any nodes
return promptNodes.length > 0;
},
// Return true if we deleted any nodes
return promptNodes.length > 0;
},
};
},
});
});

View file

@ -1,32 +1,25 @@
import { ChatBubbleLeftIcon } from "@heroicons/react/24/outline";
import {
NodeViewProps,
NodeViewWrapper,
NodeViewWrapperProps,
} from "@tiptap/react";
import { NodeViewProps } from "@tiptap/react";
import { useContext, useMemo } from "react";
import { vscBadgeBackground } from "../../../..";
import { IdeMessengerContext } from "../../../../../context/IdeMessenger";
import { useAppSelector } from "../../../../../redux/hooks";
import { ExpandablePreview } from "../../components/ExpandablePreview";
import { PromptAttributes } from "./PromptExtension";
import { NodeViewWrapper } from "../../components/NodeViewWrapper";
import { PromptBlockAttributes } from "./PromptBlock";
/**
* Component for prompt blocks in the Tiptap editor
*/
export const PromptBlockPreview = ({
node,
deleteNode,
selected,
editor,
}: NodeViewProps) => {
const { item, inputId } = node.attrs as PromptAttributes;
const { item, inputId } = node.attrs as PromptBlockAttributes;
const ideMessenger = useContext(IdeMessengerContext);
// Not setting this as a "p" will cause issues with foreign keyboards
const nodeViewWrapperTag: NodeViewWrapperProps["as"] = "p";
const newestCodeblockForInputId = useAppSelector(
(store) => store.session.newestCodeblockForInput[inputId],
);
@ -44,26 +37,13 @@ export const PromptBlockPreview = ({
};
const handleDelete = () => {
// Use the clearSlashCommand command to properly clean up everything
if (editor) {
// Make sure this runs after the current event loop cycle
// to avoid React state update conflicts
setTimeout(() => {
editor.commands.clearSlashCommand();
}, 0);
} else {
// Fallback to deleteNode if editor is not available
deleteNode();
}
editor.commands.clearSlashCommand();
};
const borderColor = selected ? vscBadgeBackground : undefined;
return (
<NodeViewWrapper
className="prompt-block-with-content"
as={nodeViewWrapperTag}
>
<NodeViewWrapper>
<ExpandablePreview
title={item.name}
icon={<ChatBubbleLeftIcon className="h-3 w-3 pl-1 pr-0.5" />}
@ -78,4 +58,4 @@ export const PromptBlockPreview = ({
</ExpandablePreview>
</NodeViewWrapper>
);
};
};

View file

@ -0,0 +1 @@
export * from "./PromptBlock";

View file

@ -1 +0,0 @@
export * from "./PromptExtension";

View file

@ -1,13 +1,15 @@
// Adapted from SlashCommand extension (@tiptap/extension-mention/src/mention.ts)
import { mergeAttributes, Node } from "@tiptap/core";
import Document from "@tiptap/extension-document";
import Paragraph from "@tiptap/extension-paragraph";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
import { ContextItemWithId, SlashCommandDescription } from "core";
import { MAIN_EDITOR_INPUT_ID } from "../../../../pages/gui/Chat";
import { ComboBoxItem } from "../../types";
import { PromptExtension } from "./PromptExtension/PromptExtension";
import { PromptBlock } from "./Prompt/PromptBlock";
export type SlashCommandOptions = {
HTMLAttributes: Record<string, any>;
@ -15,11 +17,6 @@ export type SlashCommandOptions = {
suggestion: Omit<SuggestionOptions<ComboBoxItem, ComboBoxItem>, "editor">;
};
export const SLASH_CMD_NAME = "slash-command";
export const SLASH_CMD_SUGGESTION_CHAR = "/";
export const SlashCommandPluginKey = new PluginKey(SLASH_CMD_NAME);
declare module "@tiptap/core" {
interface Commands<ReturnType> {
slashCommand: {
@ -37,18 +34,20 @@ declare module "@tiptap/core" {
}
}
export const SlashCommandExtension = Node.create<SlashCommandOptions>({
name: SLASH_CMD_NAME,
export const SlashCommand = Node.create<SlashCommandOptions>({
name: "slash-command",
addOptions() {
return {
HTMLAttributes: {},
HTMLAttributes: {
class: "mention",
},
renderText({ node }) {
return node.attrs.label ?? node.attrs.id;
},
suggestion: {
char: SLASH_CMD_SUGGESTION_CHAR,
pluginKey: SlashCommandPluginKey,
char: "/",
pluginKey: new PluginKey(this.name),
startOfLine: true,
command: ({ editor, range, props }) => {
// increase range.to by one when the next node is of type "text"
@ -141,12 +140,6 @@ export const SlashCommandExtension = Node.create<SlashCommandOptions>({
];
},
renderText({ node }) {
return this.options.renderText({
node,
});
},
addKeyboardShortcuts() {
return {
Backspace: () => {
@ -211,7 +204,7 @@ export const SlashCommandExtension = Node.create<SlashCommandOptions>({
command: SlashCommandDescription,
inputId: string = MAIN_EDITOR_INPUT_ID,
) =>
({ commands, chain }) => {
({ chain }) => {
if (!command.prompt) {
return false;
}
@ -226,14 +219,17 @@ export const SlashCommandExtension = Node.create<SlashCommandOptions>({
},
};
// Create the document with both a prompt block and the slash command paragraph
// Right now this inserts at the beginning of the document, which removes codeblocks.
// This is the current behavior of slash commands, eg codeblocks aren't sent.
// Once this bug if fixed, we should instead insert prompt block at the beginning of the document
// without clearing the codeblocks.
return chain()
.setContent({
type: "doc",
type: Document.name,
content: [
// First insert the prompt using the PromptExtension command
{
type: PromptExtension.name,
type: PromptBlock.name,
attrs: {
item: contextItem,
inputId,
@ -241,7 +237,7 @@ export const SlashCommandExtension = Node.create<SlashCommandOptions>({
},
// Add the paragraph with the slash command
{
type: "paragraph",
type: Paragraph.name,
content: [
{
type: this.name,
@ -264,29 +260,25 @@ export const SlashCommandExtension = Node.create<SlashCommandOptions>({
clearSlashCommand:
() =>
({ commands, state }) => {
// First clear all prompt blocks using the PromptExtension command
commands.clearPrompt();
({ editor }) => {
editor.commands.clearPrompt();
// Then find and remove all slash command nodes
let found = false;
const slashNodes: { pos: number; node: ProseMirrorNode }[] = [];
editor.commands.command(({ tr, state }) => {
let hasDeleted = false;
state.doc.descendants((node, pos) => {
if (node.type.name === this.name) {
slashNodes.push({ pos, node });
found = true;
}
return true;
// Find all slash command nodes in the document
state.doc.descendants((node, pos) => {
if (node.type.name === this.name) {
// Delete the node at the found position
tr.delete(pos, pos + node.nodeSize);
hasDeleted = true;
}
});
return hasDeleted;
});
// Delete all found slash command nodes in reverse order
for (let i = slashNodes.length - 1; i >= 0; i--) {
const { pos, node } = slashNodes[i];
commands.deleteRange({ from: pos, to: pos + node.nodeSize });
}
return found;
return true;
},
};
},

View file

@ -1,5 +1,5 @@
export * from "./AddCodeToEditExtension";
export * from "./CodeblockExtension";
export * from "./MentionExtension";
export * from "./PromptExtension";
export * from "./SlashCommandExtension";
export * from "./AddCodeToEdit";
export * from "./CodeBlock";
export * from "./Mention";
export * from "./Prompt";
export * from "./SlashCommand";

View file

@ -1,3 +1,4 @@
export * from "./extensions";
export * from "./MainEditorProvider";
export * from "./TipTapEditor";
export * from "./utils";

View file

@ -9,7 +9,7 @@ import {
} from "../../../redux/slices/sessionSlice";
import { AppDispatch } from "../../../redux/store";
import { loadSession, saveCurrentSession } from "../../../redux/thunks/session";
import { CodeblockExtension } from "./extensions";
import { CodeBlock } from "./extensions";
/**
* Hook for setting up main editor specific webview listeners
@ -114,7 +114,7 @@ export function useMainEditorWebviewListeners({
if (el.attrs?.item?.name === contextItem.name) {
return; // Prevent exact duplicate code blocks
}
if (el.type === CodeblockExtension.name) {
if (el.type === CodeBlock.name) {
index += 2;
} else {
break;
@ -124,7 +124,7 @@ export function useMainEditorWebviewListeners({
editor
.chain()
.insertContentAt(index, {
type: CodeblockExtension.name,
type: CodeBlock.name,
attrs: {
item: contextItem,
inputId,
@ -132,6 +132,8 @@ export function useMainEditorWebviewListeners({
})
.run();
console.log("id: ", contextItem.id.itemId);
dispatch(
setNewestCodeblocksForInput({
inputId,

View file

@ -286,10 +286,7 @@ export function createEditorConfig(options: {
},
}),
Text,
ContinueExtensions.MentionExtension.configure({
HTMLAttributes: {
class: "mention",
},
ContinueExtensions.Mention.configure({
suggestion: getContextProviderDropdownOptions(
availableContextProvidersRef,
getSubmenuContextItemsRef,
@ -299,15 +296,8 @@ export function createEditorConfig(options: {
inSubmenuRef,
ideMessenger,
),
renderHTML: (props) => {
return `@${props.node.attrs.label || props.node.attrs.id}`;
},
}),
ContinueExtensions.AddCodeToEditExtension.configure({
HTMLAttributes: {
class: "add-code-to-edit",
},
ContinueExtensions.AddCodeToEdit.configure({
suggestion: {
...getContextProviderDropdownOptions(
availableContextProvidersRef,
@ -343,10 +333,7 @@ export function createEditorConfig(options: {
},
},
}),
ContinueExtensions.SlashCommandExtension.configure({
HTMLAttributes: {
class: "mention",
},
ContinueExtensions.SlashCommand.configure({
suggestion: getSlashCommandDropdownOptions(
availableSlashCommandsRef,
onClose,
@ -355,20 +342,13 @@ export function createEditorConfig(options: {
dispatch,
props.inputId,
),
renderText: (props) => {
return props.node.attrs.label;
},
}),
ContinueExtensions.PromptExtension.configure({
HTMLAttributes: {
class: "prompt-block",
},
}),
ContinueExtensions.CodeblockExtension,
ContinueExtensions.PromptBlock,
ContinueExtensions.CodeBlock,
],
editorProps: {
attributes: {
class: "outline-none -mt-1 overflow-hidden",
class: "outline-none overflow-hidden",
style: `font-size: ${getFontSize()}px;`,
},
},

View file

@ -12,7 +12,7 @@ import { AppDispatch } from "../../../../redux/store";
import AtMentionDropdown from "../../AtMentionDropdown";
import { ComboBoxItem, ComboBoxItemType, ComboBoxSubAction } from "../../types";
import { TIPPY_DIV_ID } from "../TipTapEditor";
import { SlashCommandExtension } from "../extensions";
import { SlashCommand } from "../extensions";
function getSuggestion(
items: (props: { query: string }) => Promise<ComboBoxItem[]>,
@ -220,7 +220,7 @@ export function getSlashCommandDropdownOptions(
id: provider.title,
title: provider.title,
label: provider.title,
type: (provider.type ?? SlashCommandExtension.name) as ComboBoxItemType,
type: (provider.type ?? SlashCommand.name) as ComboBoxItemType,
content: provider.content,
action: () => {
dispatch(

View file

@ -18,11 +18,7 @@ import { renderChatMessage, stripImages } from "core/util/messageContent";
import { getUriFileExtension } from "core/util/uri";
import { IIdeMessenger } from "../../../../context/IdeMessenger";
import { setIsGatheringContext } from "../../../../redux/slices/sessionSlice";
import {
CodeblockExtension,
MentionExtension,
SlashCommandExtension,
} from "../extensions";
import { CodeBlock, Mention, SlashCommand } from "../extensions";
interface MentionAttrs {
label: string;
@ -86,7 +82,7 @@ function processEditorContent(editorState: JSONContent) {
return [...parts, { type: "text", text }];
}
case CodeblockExtension.name: {
case CodeBlock.name: {
if (!p.attrs?.item) {
console.warn("codeBlock has no item attribute");
return parts;
@ -280,10 +276,10 @@ function resolveParagraph(
switch (child.type) {
case Text.name:
return child.text;
case MentionExtension.name:
case Mention.name:
contextItems.push(child.attrs as MentionAttrs);
return child.attrs?.renderInlineAs ?? child.attrs?.label;
case SlashCommandExtension.name:
case SlashCommand.name:
if (!slashCommand) {
slashCommand = child.attrs?.id;
return "";

View file

@ -1,7 +1,7 @@
import { Editor } from "@tiptap/react";
import { KeyboardEvent } from "react";
import { getPlatform, isWebEnvironment } from "../../../util";
import { CodeblockExtension } from "../TipTapEditor/extensions";
import { CodeBlock } from "../TipTapEditor";
const isWebEnv = isWebEnvironment();
@ -104,7 +104,7 @@ export const handleJetBrainsMetaBackspace = (editor: Editor) => {
for (let i = doc.content.childCount - 1; i >= 0; i--) {
const node = doc.content.child(i);
if (node.type.name === CodeblockExtension.name) {
if (node.type.name === CodeBlock.name) {
continue;
}

View file

@ -1,6 +1,6 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ChatHistoryItem, ContextItemWithId } from "core";
import { CodeblockExtension } from "../../components/mainInput/TipTapEditor/extensions";
import { CodeBlock } from "../../components/mainInput/TipTapEditor/extensions";
import { updateFileSymbols } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
@ -26,7 +26,7 @@ export function getContextItemsFromHistory(
.flatMap((item) => item.editorState.content)
.filter(
(content) =>
content?.type === CodeblockExtension.name &&
content?.type === CodeBlock.name &&
content?.attrs?.item?.uri?.value &&
content.attrs.item.uri?.type === "file",
)