import { useEffect, useRef, useState } from 'react' import type { NativeAppCommandEvent } from '../../types' import { createEditorHistory, pushEditorChange, redoEditorChange, undoEditorChange, type EditorHistoryState, } from './editor-history' interface Props { path: string content: string busy?: boolean error?: string onChange: (value: string) => void onSave: () => void onCancel: () => void onReloadFromDisk?: () => void } export default function InlineFileEditor({ path, content, busy = false, error, onChange, onSave, onCancel, onReloadFromDisk }: Props) { const textareaRef = useRef(null) const [history, setHistory] = useState(() => createEditorHistory(content)) const isConflict = Boolean(error && /changed on disk|revision token|reload/i.test(error)) const historyRef = useRef(history) historyRef.current = history const onChangeRef = useRef(onChange) onChangeRef.current = onChange useEffect(() => { setHistory(createEditorHistory(content)) }, [path]) function applyHistory(nextHistory: EditorHistoryState): void { setHistory(nextHistory) onChange(nextHistory.present) } function handleContentChange(nextContent: string): void { const nextHistory = pushEditorChange(history, nextContent) setHistory(nextHistory) onChange(nextContent) } function handleUndo(): void { applyHistory(undoEditorChange(history)) } function handleRedo(): void { applyHistory(redoEditorChange(history)) } function editorHasFocus(): boolean { return document.activeElement === textareaRef.current } useEffect(() => { const handleNativeCommand = (event: Event) => { const command = (event as NativeAppCommandEvent).detail?.command if (!editorHasFocus()) return if (command === 'undo') { event.preventDefault() const next = undoEditorChange(historyRef.current) setHistory(next) onChangeRef.current(next.present) } if (command === 'redo') { event.preventDefault() const next = redoEditorChange(historyRef.current) setHistory(next) onChangeRef.current(next.present) } } window.addEventListener('gitlocal:native-command', handleNativeCommand) return () => window.removeEventListener('gitlocal:native-command', handleNativeCommand) }, []) return (

Edit file

{path}

{error && (

{error}

{isConflict ? (
{onReloadFromDisk ? ( ) : null}
) : null}
)}