Elffuss BraidHub

kikocis/continue public

f997f82ae31e · 9.8 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 const [showDragOverMsg, setShowDragOverMsg] = useState(false);
124
125 const [activeKey, setActiveKey] = useState<string | null>(null);
126
127 const insertCharacterWithWhitespace = useCallback(
128 (char: string) => {
129 if (!editor) {
130 return;
131 }
132 const text = editor.getText();
133 if (!text.endsWith(char)) {
134 if (text.length > 0 && !text.endsWith(" ")) {
135 editor.commands.insertContent(` ${char}`);
136 } else {
137 editor.commands.insertContent(char);
138 }
139 }
140 },
141 [editor],
142 );
143
144 const { handleKeyUp, handleKeyDown } = useEditorEventHandlers({
145 editor,
146 isOSREnabled: isOSREnabled,
147 editorFocusedRef,
148 setActiveKey,
149 });
150
151 const blurTimeout = useRef<NodeJS.Timeout | null>(null);
152 const cancelBlurTimeout = useCallback(() => {
153 if (blurTimeout.current) {
154 clearTimeout(blurTimeout.current);
155 blurTimeout.current = null;
156 }
157 }, [blurTimeout]);
158
159 const handleBlur = useCallback(
160 (e: React.FocusEvent) => {
161 if (isInEdit) {
162 return;
163 }
164 // Check if the new focus target is within our InputBoxDiv
165 const currentTarget = e.currentTarget;
166 const relatedTarget = e.relatedTarget as Node | null;
167
168 if (relatedTarget && currentTarget?.contains(relatedTarget)) {
169 return;
170 }
171 // Otherwise give e.g. listboxes a chance to cancel the hiding
172 blurTimeout.current = setTimeout(() => {
173 setShouldHideToolbar(true);
174 }, 100);
175 },
176 [isInEdit, blurTimeout],
177 );
178
179 const handleFocus = useCallback(() => {
180 cancelBlurTimeout();
181 setShouldHideToolbar(false);
182 }, [cancelBlurTimeout]);
183
184 return (
185 <InputBoxDiv
186 onFocus={handleFocus}
187 onBlur={handleBlur}
188 onKeyDown={handleKeyDown}
189 onKeyUp={handleKeyUp}
190 className={
191 !props.isMainInput && shouldHideToolbar
192 ? "cursor-pointer"
193 : "cursor-text"
194 }
195 onClick={() => {
196 editor?.commands.focus();
197 }}
198 onDragOver={(event) => {
199 event.preventDefault();
200 setShowDragOverMsg(true);
201 }}
202 onDragLeave={(e) => {
203 if (e.relatedTarget === null) {
204 if (e.shiftKey) {
205 setShowDragOverMsg(false);
206 } else {
207 setTimeout(() => setShowDragOverMsg(false), 2000);
208 }
209 }
210 }}
211 onDragEnter={() => {
212 setShowDragOverMsg(true);
213 }}
214 onDrop={(event) => {
215 setShowDragOverMsg(false);
216 if (
217 !defaultModel ||
218 !modelSupportsImages(
219 defaultModel.provider,
220 defaultModel.model,
221 defaultModel.title,
222 defaultModel.capabilities,
223 )
224 ) {
225 return;
226 }
227 let file = event.dataTransfer.files[0];
228 void handleImageFile(ideMessenger, file).then((result) => {
229 if (!editor) {
230 return;
231 }
232 if (result) {
233 const [_, dataUrl] = result;
234 const { schema } = editor.state;
235 const node = schema.nodes.image.create({ src: dataUrl });
236 const tr = editor.state.tr.insert(0, node);
237 editor.view.dispatch(tr);
238 }
239 });
240 event.preventDefault();
241 }}
242 >
243 <div className="px-2.5 pb-1 pt-2">
244 <EditorContent
245 className={`scroll-container overflow-y-scroll ${props.isMainInput ? "max-h-[70vh]" : ""}`}
246 spellCheck={false}
247 editor={editor}
248 onClick={(event) => {
249 event.stopPropagation();
250 }}
251 />
252 <InputToolbar
253 isMainInput={props.isMainInput}
254 toolbarOptions={props.toolbarOptions}
255 activeKey={activeKey}
256 hidden={shouldHideToolbar && !props.isMainInput}
257 onAddContextItem={() => insertCharacterWithWhitespace("@")}
258 onEnter={onEnterRef.current}
259 onImageFileSelected={(file) => {
260 void handleImageFile(ideMessenger, file).then((result) => {
261 if (!editor) {
262 return;
263 }
264 if (result) {
265 const [_, dataUrl] = result;
266 const { schema } = editor.state;
267 const node = schema.nodes.image.create({ src: dataUrl });
268 editor.commands.command(({ tr }) => {
269 tr.insert(0, node);
270 return true;
271 });
272 }
273 });
274 }}
275 disabled={isStreaming}
276 />
277 </div>
278
279 {showDragOverMsg &&
280 modelSupportsImages(
281 defaultModel?.provider || "",
282 defaultModel?.model || "",
283 defaultModel?.title,
284 defaultModel?.capabilities,
285 ) && (
286 <DragOverlay show={showDragOverMsg} setShow={setShowDragOverMsg} />
287 )}
288 <div id={TIPPY_DIV_ID} className="fixed z-50" />
289 </InputBoxDiv>
290 );
291}
292
293function toolbarOptionsEqual(a?: ToolbarOptions, b?: ToolbarOptions) {
294 if (a === b) return true;
295 if (!a || !b) return false;
296 return (
297 a.hideAddContext === b.hideAddContext &&
298 a.hideImageUpload === b.hideImageUpload &&
299 a.hideUseCodebase === b.hideUseCodebase &&
300 a.hideSelectModel === b.hideSelectModel &&
301 a.enterText === b.enterText
302 );
303}
304
305const MemoInner = memo(
306 TipTapEditorInner,
307 (prev, next) =>
308 prev.isMainInput === next.isMainInput &&
309 prev.placeholder === next.placeholder &&
310 prev.historyKey === next.historyKey &&
311 prev.inputId === next.inputId &&
312 toolbarOptionsEqual(prev.toolbarOptions, next.toolbarOptions) &&
313 (prev.availableContextProviders?.length || 0) ===
314 (next.availableContextProviders?.length || 0) &&
315 (prev.availableSlashCommands?.length || 0) ===
316 (next.availableSlashCommands?.length || 0),
317);
318
319export function TipTapEditor(props: TipTapEditorProps) {
320 return (
321 <div className="relative w-full">
322 <MemoInner {...props} />
323 </div>
324 );
325}