✨ /edit button

This commit is contained in:
Nate Sesti 2023-12-26 20:16:24 -05:00
parent 211d432f74
commit ea002c1cf9
8 changed files with 197 additions and 42 deletions

View file

@ -1,17 +1,97 @@
import { mergeAttributes, Node } from "@tiptap/core";
import { NodeViewWrapper, ReactNodeViewRenderer } from "@tiptap/react";
import { ContextItemWithId } from "core";
import { useDispatch, useSelector } from "react-redux";
import { buttonColor } from "..";
import { setEditingContextItemAtIndex } from "../../redux/slices/stateSlice";
import { RootStore } from "../../redux/store";
import CodeSnippetPreview from "../markdown/CodeSnippetPreview";
const CodeBlockComponent = ({ node, deleteNode }) => {
const CodeBlockComponent = ({
node,
deleteNode,
selected,
editor,
updateAttributes,
}) => {
const dispatch = useDispatch();
const item: ContextItemWithId = node.attrs.item;
const contextItems = useSelector(
(state: RootStore) => state.state.contextItems
);
return (
<NodeViewWrapper className="code-block-with-content">
<CodeSnippetPreview
borderColor={
item.id === contextItems[0]?.id
? "#d0d"
: selected
? buttonColor
: undefined
}
item={item}
onDelete={() => {
deleteNode();
}}
onEdit={async () => {
dispatch(setEditingContextItemAtIndex({ item }));
if (item.id === contextItems[0]?.id) {
// Find and delete the /edit command
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "slashcommand") {
if (el.attrs.id === "/edit") {
editor
.chain()
.deleteRange({ from: index, to: index + 2 })
.focus("end")
.run();
break;
}
}
index += 1;
}
updateAttributes({
item: {
...item,
editing: false,
},
});
} else {
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
}
editor
.chain()
.focus("end")
.insertContent([
{
type: "slashcommand",
attrs: { id: "/edit", label: "/edit" },
},
{ type: "text", text: " " },
])
.run();
updateAttributes({
item: {
...item,
editing: true,
},
});
await new Promise((resolve) => setTimeout(resolve, 100));
editor.commands.focus("end");
}
}}
editing={item.id === contextItems[0]?.id}
/>
</NodeViewWrapper>
);

View file

@ -7,7 +7,7 @@ import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
export type SlashCommandOptions = {
HTMLAttributes: Record<string, any>;
renderLabel: (props: {
renderText: (props: {
options: SlashCommandOptions;
node: ProseMirrorNode;
}) => string;
@ -22,7 +22,7 @@ export const SlashCommand = Node.create<SlashCommandOptions>({
addOptions() {
return {
HTMLAttributes: {},
renderLabel({ options, node }) {
renderText({ options, node }) {
return `${options.suggestion.char}${node.attrs.label ?? node.attrs.id}`;
},
suggestion: {
@ -123,7 +123,7 @@ export const SlashCommand = Node.create<SlashCommandOptions>({
this.options.HTMLAttributes,
HTMLAttributes
),
this.options.renderLabel({
this.options.renderText({
options: this.options,
node,
}),
@ -131,7 +131,7 @@ export const SlashCommand = Node.create<SlashCommandOptions>({
},
renderText({ node }) {
return this.options.renderLabel({
return this.options.renderText({
options: this.options,
node,
});

View file

@ -5,11 +5,6 @@ import Suggestion, { SuggestionOptions } from "@tiptap/suggestion";
export type MentionOptions = {
HTMLAttributes: Record<string, any>;
/** @deprecated use renderText and renderHTML instead */
renderLabel?: (props: {
options: MentionOptions;
node: ProseMirrorNode;
}) => string;
renderText: (props: {
options: MentionOptions;
node: ProseMirrorNode;
@ -143,9 +138,9 @@ export const Mention = Node.create<MentionOptions>({
},
renderHTML({ node, HTMLAttributes }) {
if (this.options.renderLabel !== undefined) {
if (this.options.renderText !== undefined) {
console.warn(
"renderLabel is deprecated use renderText and renderHTML instead"
"renderText is deprecated use renderText and renderHTML instead"
);
return [
"span",
@ -154,7 +149,7 @@ export const Mention = Node.create<MentionOptions>({
this.options.HTMLAttributes,
HTMLAttributes
),
this.options.renderLabel({
this.options.renderText({
options: this.options,
node,
}),
@ -180,11 +175,11 @@ export const Mention = Node.create<MentionOptions>({
},
renderText({ node }) {
if (this.options.renderLabel !== undefined) {
if (this.options.renderText !== undefined) {
console.warn(
"renderLabel is deprecated use renderText and renderHTML instead"
"renderText is deprecated use renderText and renderHTML instead"
);
return this.options.renderLabel({
return this.options.renderText({
options: this.options,
node,
});

View file

@ -17,7 +17,6 @@ import {
} from "..";
import { SearchContext } from "../../App";
import useHistory from "../../hooks/useHistory";
import { setTakenActionTrue } from "../../redux/slices/miscSlice";
import { RootStore } from "../../redux/store";
import { isMetaEquivalentKeyPressed } from "../../util";
import { isJetBrains, postToIde } from "../../util/ide";
@ -169,7 +168,7 @@ function TipTapEditor(props: TipTapEditorProps) {
onOpen,
inSubmenu
),
renderLabel: (props) => {
renderText: (props) => {
return `@${props.node.attrs.label || props.node.attrs.id}`;
},
}),
@ -182,7 +181,7 @@ function TipTapEditor(props: TipTapEditorProps) {
onClose,
onOpen
),
renderLabel: (props) => {
renderText: (props) => {
return props.node.attrs.label;
},
}),
@ -194,7 +193,7 @@ function TipTapEditor(props: TipTapEditorProps) {
style: "font-size: 14px;",
},
},
content: props.editorState || props.content || "",
content: props.editorState || props.content,
},
[
props.availableContextProviders,
@ -246,14 +245,11 @@ function TipTapEditor(props: TipTapEditorProps) {
if (historyLength > 0) {
saveSession();
}
dispatch(setTakenActionTrue(null));
editor.commands.focus("end");
} else if (event.data.type === "focusContinueInputWithoutClear") {
editor.commands.focus("end");
dispatch(setTakenActionTrue(null));
} else if (event.data.type === "focusContinueInputWithNewSession") {
saveSession();
dispatch(setTakenActionTrue(null));
editor.commands.focus("end");
} else if (event.data.type === "highlightedCode") {
if (!ignoreHighlightedCode) {
@ -271,12 +267,25 @@ function TipTapEditor(props: TipTapEditorProps) {
itemId: rif.filepath,
},
};
editor.commands.insertContentAt(0, {
type: "codeBlock",
attrs: {
item,
},
});
let index = 0;
for (const el of editor.getJSON().content) {
if (el.type === "codeBlock") {
index += 2;
} else {
break;
}
}
editor
.chain()
.insertContentAt(index, {
type: "codeBlock",
attrs: {
item,
},
})
.focus("end")
.run();
await new Promise((resolve) => setTimeout(resolve, 100));
editor.commands.focus("end");
}

View file

@ -23,18 +23,24 @@ async function resolveEditorContent(
): Promise<string> {
let paragraphs = [];
let contextItems: MentionAttrs[] = [];
let slashCommand = undefined;
for (const p of editorState?.content) {
if (p.type === "paragraph") {
const [text, ctxItems] = resolveParagraph(p);
const [text, ctxItems, foundSlashCommand] = resolveParagraph(p);
if (foundSlashCommand && typeof slashCommand === "undefined") {
slashCommand = foundSlashCommand;
}
if (text === "") {
continue;
}
paragraphs.push(text);
contextItems.push(...ctxItems);
} else if (p.type === "codeBlock") {
paragraphs.push(
"```" + p.attrs.item.name + "\n" + p.attrs.item.content + "\n```"
);
if (!p.attrs.item.editing) {
paragraphs.push(
"```" + p.attrs.item.name + "\n" + p.attrs.item.content + "\n```"
);
}
} else {
console.warn("Unexpected content type", p.type);
}
@ -64,14 +70,18 @@ async function resolveEditorContent(
contextItemsText += "\n";
}
const finalText = contextItemsText + paragraphs.join("\n");
let finalText = contextItemsText + paragraphs.join("\n");
if (slashCommand) {
finalText = `${slashCommand} ${finalText}`;
}
console.log(finalText, editorState?.content);
return finalText;
}
function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] {
function resolveParagraph(p: JSONContent): [string, MentionAttrs[], string] {
let text = "";
const contextItems = [];
let slashCommand = undefined;
for (const child of p.content || []) {
if (child.type === "text") {
text += child.text;
@ -79,12 +89,16 @@ function resolveParagraph(p: JSONContent): [string, MentionAttrs[]] {
text += `@${child.attrs.label}`;
contextItems.push(child.attrs);
} else if (child.type === "slashcommand") {
text += child.attrs.label;
if (typeof slashCommand === "undefined") {
slashCommand = child.attrs.id;
} else {
text += child.attrs.label;
}
} else {
console.warn("Unexpected child type", child.type);
}
}
return [text, contextItems];
return [text, contextItems, slashCommand];
}
export default resolveEditorContent;

View file

@ -1,6 +1,7 @@
import {
ChevronDownIcon,
ChevronUpIcon,
PaintBrushIcon,
XMarkIcon,
} from "@heroicons/react/24/outline";
import { ContextItemWithId } from "core";
@ -16,10 +17,13 @@ import StyledMarkdownPreview from "./StyledMarkdownPreview";
const MAX_PREVIEW_HEIGHT = 160;
const PreviewMarkdownDiv = styled.div<{ scroll: boolean }>`
const PreviewMarkdownDiv = styled.div<{
scroll: boolean;
borderColor?: string;
}>`
background-color: ${vscEditorBackground};
border-radius: ${defaultBorderRadius};
border: 0.5px solid ${lightGray};
border: 0.5px solid ${(props) => props.borderColor || lightGray};
margin-top: 4px;
margin-bottom: 4px;
overflow: hidden;
@ -47,8 +51,17 @@ const PreviewMarkdownHeader = styled.p`
interface CodeSnippetPreviewProps {
item: ContextItemWithId;
onDelete?: () => void;
onEdit?: () => void;
borderColor?: string;
editing?: boolean;
}
const StyledHeaderButtonWithText = styled(HeaderButtonWithText)<{
color?: string;
}>`
${(props) => props.color && `background-color: ${props.color};`}
`;
function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
const dispatch = useDispatch();
@ -62,6 +75,7 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
scroll={!scrollLocked}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
borderColor={props.borderColor}
>
<PreviewMarkdownHeader
className="flex justify-between cursor-pointer"
@ -97,7 +111,26 @@ function CodeSnippetPreview(props: CodeSnippetPreviewProps) {
{props.item.name}
</div>
<div className="flex items-center">
<HeaderButtonWithText text="Delete" onClick={props.onDelete}>
{props.onEdit && (
<StyledHeaderButtonWithText
text="Edit"
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
props.onEdit();
}}
{...(props.editing && { color: "#f0f4" })}
>
<PaintBrushIcon width="1.2em" height="1.2em" />
</StyledHeaderButtonWithText>
)}
<HeaderButtonWithText
text="Delete"
onClick={(e) => {
e.stopPropagation();
props.onDelete();
}}
>
<XMarkIcon width="1.2em" height="1.2em" />
</HeaderButtonWithText>
</div>

View file

@ -30,7 +30,7 @@ function useChatHandler(dispatch: Dispatch) {
);
const contextItems = useSelector(
(store: RootStore) => store.state.contextItems
(state: RootStore) => state.state.contextItems
);
const history = useSelector((store: RootStore) => store.state.history);
const contextProviders = useSelector(

View file

@ -147,7 +147,30 @@ export const stateSlice = createSlice({
};
}
},
setEditingContextItemAtIndex: (
state,
{
payload: { index, item },
}: {
payload: { index?: number; item: ContextItemWithId };
}
) => {
if (index === undefined) {
if (state.contextItems[0]?.id.itemId === item.id.itemId) {
return {
...state,
contextItems: [],
};
} else {
return {
...state,
contextItems: [{ ...item, editing: true }],
};
}
} else {
// TODO
}
},
addContextItems: (state, action) => {
return {
...state,
@ -410,5 +433,6 @@ export const {
setConfig,
addLogs,
setActive,
setEditingContextItemAtIndex,
} = stateSlice.actions;
export default stateSlice.reducer;