Elffuss BraidHub

kikocis/continue public

94488b344dec · 8.6 KiBRawPermalink
1import { Editor, EditorContent, JSONContent } from "@tiptap/react";
2import { ContextProviderDescription, InputModifiers } from "core";
3import { modelSupportsImages } from "core/llm/autodetect";
4import { useCallback, useContext, useEffect, useRef, useState } from "react";
5import { IdeMessengerContext } from "../../../context/IdeMessenger";
6import useIsOSREnabled from "../../../hooks/useIsOSREnabled";
7import useUpdatingRef from "../../../hooks/useUpdatingRef";
8import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
9import { selectSelectedChatModel } from "../../../redux/slices/configSlice";
10import InputToolbar, { ToolbarOptions } from "../InputToolbar";
11import { ComboBoxItem } from "../types";
12import { DragOverlay, InputBoxDiv } from "./components";
13import { useMainEditor } from "./MainEditorProvider";
14import "./TipTapEditor.css";
15import { handleImageFile } from "./utils";
16import { createEditorConfig, getPlaceholderText } from "./utils/editorConfig";
17import { useEditorEventHandlers } from "./utils/keyHandlers";
18
19export interface TipTapEditorProps {
20 availableContextProviders: ContextProviderDescription[];
21 availableSlashCommands: ComboBoxItem[];
22 isMainInput: boolean;
23 onEnter: (
24 editorState: JSONContent,
25 modifiers: InputModifiers,
26 editor: Editor,
27 ) => void;
28 editorState?: JSONContent;
29 toolbarOptions?: ToolbarOptions;
30 placeholder?: string;
31 historyKey: string;
32
33 // TODO: This isn't actually used anywhere in this component, but it appears
34 // to be pulled into some of our TipTap extensions.
35 inputId: string;
36}
37
38export const TIPPY_DIV_ID = "tippy-js-div";
39
40export function TipTapEditor(props: TipTapEditorProps) {
41 const dispatch = useAppDispatch();
42 const mainEditorContext = useMainEditor();
43
44 const ideMessenger = useContext(IdeMessengerContext);
45 const isOSREnabled = useIsOSREnabled();
46
47 const defaultModel = useAppSelector(selectSelectedChatModel);
48 const isStreaming = useAppSelector((state) => state.session.isStreaming);
49 const historyLength = useAppSelector((store) => store.session.history.length);
50 const isInEdit = useAppSelector((store) => store.session.isInEdit);
51
52 const { editor, onEnterRef } = createEditorConfig({
53 props,
54 ideMessenger,
55 dispatch,
56 });
57
58 // Register the main editor with the provider
59 useEffect(() => {
60 if (props.isMainInput && editor) {
61 mainEditorContext.setMainEditor(editor);
62 mainEditorContext.setInputId(props.inputId);
63 mainEditorContext.onEnterRef.current = onEnterRef.current;
64 }
65 }, [editor, props.isMainInput, props.inputId, mainEditorContext, onEnterRef]);
66
67 const [shouldHideToolbar, setShouldHideToolbar] = useState(true);
68
69 useEffect(() => {
70 if (!editor) {
71 return;
72 }
73 const placeholder = getPlaceholderText(props.placeholder, historyLength);
74
75 editor.extensionManager.extensions.filter(
76 (extension) => extension.name === "placeholder",
77 )[0].options["placeholder"] = placeholder;
78
79 editor.view.dispatch(editor.state.tr);
80 }, [editor, props.placeholder, historyLength]);
81
82 useEffect(() => {
83 if (props.isMainInput) {
84 editor?.commands.clearContent(true);
85 }
86 }, [editor, props.isMainInput]);
87
88 useEffect(() => {
89 if (isInEdit) {
90 setShouldHideToolbar(false);
91 }
92 }, [isInEdit]);
93
94 const editorFocusedRef = useUpdatingRef(editor?.isFocused, [editor]);
95
96 useEffect(() => {
97 if (props.isMainInput) {
98 /**
99 * I have a strong suspicion that many of the other focus
100 * commands are redundant, especially the ones inside
101 * useTimeout.
102 */
103 editor?.commands.focus();
104 }
105 }, [props.isMainInput, editor]);
106
107 // Re-focus main input after done generating
108 useEffect(() => {
109 if (editor && !isStreaming && props.isMainInput && document.hasFocus()) {
110 editor.commands.focus(undefined, { scrollIntoView: false });
111 }
112 }, [props.isMainInput, isStreaming, editor]);
113
114 const [showDragOverMsg, setShowDragOverMsg] = useState(false);
115
116 const [activeKey, setActiveKey] = useState<string | null>(null);
117
118 const insertCharacterWithWhitespace = useCallback(
119 (char: string) => {
120 if (!editor) {
121 return;
122 }
123 const text = editor.getText();
124 if (!text.endsWith(char)) {
125 if (text.length > 0 && !text.endsWith(" ")) {
126 editor.commands.insertContent(` ${char}`);
127 } else {
128 editor.commands.insertContent(char);
129 }
130 }
131 },
132 [editor],
133 );
134
135 const { handleKeyUp, handleKeyDown } = useEditorEventHandlers({
136 editor,
137 isOSREnabled: isOSREnabled,
138 editorFocusedRef,
139 setActiveKey,
140 });
141
142 const blurTimeout = useRef<NodeJS.Timeout | null>(null);
143 const cancelBlurTimeout = useCallback(() => {
144 if (blurTimeout.current) {
145 clearTimeout(blurTimeout.current);
146 blurTimeout.current = null;
147 }
148 }, [blurTimeout]);
149
150 const handleBlur = useCallback(
151 (e: React.FocusEvent) => {
152 if (isInEdit) {
153 return;
154 }
155 // Check if the new focus target is within our InputBoxDiv
156 const currentTarget = e.currentTarget;
157 const relatedTarget = e.relatedTarget as Node | null;
158
159 if (relatedTarget && currentTarget?.contains(relatedTarget)) {
160 return;
161 }
162 // Otherwise give e.g. listboxes a chance to cancel the hiding
163 blurTimeout.current = setTimeout(() => {
164 setShouldHideToolbar(true);
165 }, 100);
166 },
167 [isInEdit, blurTimeout],
168 );
169
170 const handleFocus = useCallback(() => {
171 cancelBlurTimeout();
172 setShouldHideToolbar(false);
173 }, [cancelBlurTimeout]);
174
175 return (
176 <InputBoxDiv
177 onFocus={handleFocus}
178 onBlur={handleBlur}
179 onKeyDown={handleKeyDown}
180 onKeyUp={handleKeyUp}
181 className={shouldHideToolbar ? "cursor-default" : "cursor-text"}
182 onClick={() => {
183 editor?.commands.focus();
184 }}
185 onDragOver={(event) => {
186 event.preventDefault();
187 setShowDragOverMsg(true);
188 }}
189 onDragLeave={(e) => {
190 if (e.relatedTarget === null) {
191 if (e.shiftKey) {
192 setShowDragOverMsg(false);
193 } else {
194 setTimeout(() => setShowDragOverMsg(false), 2000);
195 }
196 }
197 }}
198 onDragEnter={() => {
199 setShowDragOverMsg(true);
200 }}
201 onDrop={(event) => {
202 if (
203 !defaultModel ||
204 !modelSupportsImages(
205 defaultModel.provider,
206 defaultModel.model,
207 defaultModel.title,
208 defaultModel.capabilities,
209 )
210 ) {
211 return;
212 }
213 setShowDragOverMsg(false);
214 let file = event.dataTransfer.files[0];
215 void handleImageFile(ideMessenger, file).then((result) => {
216 if (!editor) {
217 return;
218 }
219 if (result) {
220 const [_, dataUrl] = result;
221 const { schema } = editor.state;
222 const node = schema.nodes.image.create({ src: dataUrl });
223 const tr = editor.state.tr.insert(0, node);
224 editor.view.dispatch(tr);
225 }
226 });
227 event.preventDefault();
228 }}
229 >
230 <div className="px-2.5 pb-1 pt-2">
231 <EditorContent
232 className={`scroll-container overflow-y-scroll ${props.isMainInput ? "max-h-[70vh]" : ""}`}
233 spellCheck={false}
234 editor={editor}
235 onClick={(event) => {
236 event.stopPropagation();
237 }}
238 />
239 <InputToolbar
240 isMainInput={props.isMainInput}
241 toolbarOptions={props.toolbarOptions}
242 activeKey={activeKey}
243 hidden={shouldHideToolbar && !props.isMainInput}
244 onAddContextItem={() => insertCharacterWithWhitespace("@")}
245 onEnter={onEnterRef.current}
246 onImageFileSelected={(file) => {
247 void handleImageFile(ideMessenger, file).then((result) => {
248 if (!editor) {
249 return;
250 }
251 if (result) {
252 const [_, dataUrl] = result;
253 const { schema } = editor.state;
254 const node = schema.nodes.image.create({ src: dataUrl });
255 editor.commands.command(({ tr }) => {
256 tr.insert(0, node);
257 return true;
258 });
259 }
260 });
261 }}
262 disabled={isStreaming}
263 />
264 </div>
265
266 {showDragOverMsg &&
267 modelSupportsImages(
268 defaultModel?.provider || "",
269 defaultModel?.model || "",
270 defaultModel?.title,
271 defaultModel?.capabilities,
272 ) && (
273 <DragOverlay show={showDragOverMsg} setShow={setShowDragOverMsg} />
274 )}
275 <div id={TIPPY_DIV_ID} className="fixed z-50" />
276 </InputBoxDiv>
277 );
278}