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