Elffuss BraidHub

kikocis/continue public

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