Elffuss BraidHub

kikocis/continue public

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