diff --git a/README.md b/README.md index 222491e..ec3d62c 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,8 @@ Selecting lines updates the URL: `A` addresses the additions side and `D` the deletions side. Live `dp reviews --json` output includes the corresponding URL for each comment. -Text diffs are editable without switching modes. Edits stay in the browser until +Text diffs are editable without switching modes: click into a file's code to +start editing it. Edits stay in the browser until you click **Commit** in the top-right toolbar or press **Cmd+S** (**Ctrl+S** on Windows/Linux). Yellow dots identify edited files; the expanded Diff Stats panel includes **Unsaved files** and live addition/deletion diff --git a/ui/src/App.tsx b/ui/src/App.tsx index b1568b3..691a5bc 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -2,8 +2,10 @@ import { type CodeViewItem, type CodeViewLineSelection, type CodeViewOptions, + type DiffLineEventBaseProps, type SelectedLineRange, } from '@pierre/diffs'; +import type { Editor } from '@pierre/diffs/edit'; import { CodeView, EditProvider, @@ -26,6 +28,7 @@ import { type AnnotationMeta, type DraftComment, } from './annotations'; +import { characterAtPoint } from './caretFromPoint'; import { CommentCard } from './components/CommentCard'; import { FileHeader, FileHeadersProvider } from './components/FileHeader'; import { Sidebar } from './components/Sidebar'; @@ -40,10 +43,16 @@ type Connection = 'connected' | 'connecting' | 'reconnecting' | 'ended'; const NARROW_VIEW_QUERY = '(max-width: 767px)'; const CODE_VIEW_LAYOUT = { paddingTop: 0, gap: 1, paddingBottom: 16 }; +// How long to wait for a lazily activated editor to attach and hydrate +// before dropping the pending caret placement. +const EDIT_FOCUS_TIMEOUT_MS = 10_000; const CODE_VIEW_UNSAFE_CSS = ` [data-diffs-header][data-sticky] { top: 0; } + [data-interactive-lines] [data-line] { + cursor: text; + } `; export function App() { @@ -245,6 +254,54 @@ export function App() { () => new Map(displayedFiles.map((file) => [file.path, file])), [displayedFiles], ); + + // Files enter edit mode lazily (on first click into their code), so + // scrolling never attaches editors or hydrates full file contents. The + // clicked file's editor attaches asynchronously; poll until its document + // is ready, then place the caret near the clicked line. + const editFocusFrameRef = useRef(null); + const cancelEditFocus = useCallback(() => { + if (editFocusFrameRef.current !== null) { + cancelAnimationFrame(editFocusFrameRef.current); + editFocusFrameRef.current = null; + } + }, []); + useEffect(() => cancelEditFocus, [cancelEditFocus]); + const focusEditorWhenReady = useStableCallback( + (itemId: string, lineNumber: number, character: number) => { + cancelEditFocus(); + const deadline = Date.now() + EDIT_FOCUS_TIMEOUT_MS; + const tick = () => { + editFocusFrameRef.current = null; + const editor = viewerRef.current?.getEditor(itemId) as Editor | undefined; + if (editor?.getFile() !== undefined) { + editor.focus({ lineNumber, character, preventScroll: true }); + return; + } + if (Date.now() < deadline) editFocusFrameRef.current = requestAnimationFrame(tick); + }; + tick(); + }, + ); + const handleLineClick = useStableCallback( + (line: DiffLineEventBaseProps & { event: PointerEvent }, itemId: string) => { + // Number-column clicks drive line selection for comments, not editing. + if (line.numberColumn) return; + const path = itemId.slice(2); + if (edits.pendingAction !== null || edits.editingPaths.has(path)) return; + const summary = filesByPath.get(path); + if (!summary || summary.binary || summary.kind === 'deleted') return; + // Don't hijack an in-progress text selection (copying from the diff). + const selection = window.getSelection(); + if (selection !== null && !selection.isCollapsed) return; + edits.startEditing(path); + focusEditorWhenReady( + itemId, + line.lineNumber, + characterAtPoint(line.lineElement, line.event.clientX, line.event.clientY), + ); + }, + ); const fileHeaderState = useMemo( () => ({ files: filesByPath, dirtyPaths: edits.dirtyPaths }), [filesByPath, edits.dirtyPaths], @@ -271,6 +328,7 @@ export function App() { const summary = filesByPath.get(path); const editable = edits.editorReady && + (edits.editingPaths.has(path) || edit !== undefined) && summary !== undefined && !summary.binary && summary.kind !== 'deleted'; @@ -293,6 +351,7 @@ export function App() { [ displayedParsedFiles, edits.edits, + edits.editingPaths, edits.editorReady, annotationsByPath, collapsedPaths, @@ -483,6 +542,9 @@ export function App() { onGutterUtilityClick(range, context) { if (context.item.type === 'diff') handleGutterClick(range, context.item.id); }, + onLineClick(line, context) { + if (context.item.type === 'diff') handleLineClick(line, context.item.id); + }, loadDiffFiles: edits.loadDiffFiles, }), [ @@ -491,6 +553,7 @@ export function App() { view.theme, view.lineHeight, handleGutterClick, + handleLineClick, edits.loadDiffFiles, ], ); diff --git a/ui/src/caretFromPoint.ts b/ui/src/caretFromPoint.ts new file mode 100644 index 0000000..9ef9243 --- /dev/null +++ b/ui/src/caretFromPoint.ts @@ -0,0 +1,27 @@ +interface CaretDocument extends Document { + caretPositionFromPoint?( + x: number, + y: number, + options?: { shadowRoots?: ShadowRoot[] }, + ): { offsetNode: Node; offset: number } | null; + caretRangeFromPoint?(x: number, y: number): Range | null; +} + +/** Return the character offset within a rendered code line at a pointer position. */ +export function characterAtPoint(lineElement: HTMLElement, x: number, y: number): number { + const owner = lineElement.ownerDocument as CaretDocument; + const root = lineElement.getRootNode(); + const position = owner.caretPositionFromPoint?.(x, y, { + shadowRoots: root instanceof ShadowRoot ? [root] : undefined, + }); + const range = owner.caretRangeFromPoint?.(x, y); + const node = position?.offsetNode ?? range?.startContainer; + const offset = position?.offset ?? range?.startOffset; + if (node === undefined || offset === undefined) return 0; + if (node !== lineElement && !lineElement.contains(node)) return 0; + + const prefix = owner.createRange(); + prefix.selectNodeContents(lineElement); + prefix.setEnd(node, offset); + return prefix.toString().length; +} diff --git a/ui/src/useEdits.ts b/ui/src/useEdits.ts index 14c1150..00c4928 100644 --- a/ui/src/useEdits.ts +++ b/ui/src/useEdits.ts @@ -89,6 +89,7 @@ export function useEdits({ onEditStart, }: UseEditsOptions) { const [edits, setEdits] = useState>(new Map()); + const [editingPaths, setEditingPaths] = useState>(() => new Set()); const [pendingAction, setPendingAction] = useState<'commit' | 'discard' | null>(null); const [error, setError] = useState(null); const [loadingCount, setLoadingCount] = useState(0); @@ -107,12 +108,10 @@ export function useEdits({ () => new Map(parsedFiles.map((file) => [file.path, file])), [parsedFiles], ); - const hasEditableFiles = (patch?.files ?? []).some( - (file) => !file.binary && file.kind !== 'deleted', - ); - + // Load the editor module lazily, once the first file enters edit mode. + const wantsEditor = editingPaths.size > 0; useEffect(() => { - if (!hasEditableFiles || editorReady) return; + if (!wantsEditor || editorReady) return; // The effect owns the loading state for this import. // oxlint-disable-next-line react/set-state-in-effect setLoadingCount((count) => count + 1); @@ -124,13 +123,24 @@ export function useEdits({ ); }) .finally(() => setLoadingCount((count) => Math.max(0, count - 1))); - }, [editorReady, hasEditableFiles]); + }, [editorReady, wantsEditor]); + + const startEditing = useStableCallback((path: string) => { + if (actionPendingRef.current) return; + setEditingPaths((previous) => { + if (previous.has(path)) return previous; + const next = new Set(previous); + next.add(path); + return next; + }); + }); const reset = useStableCallback(() => { editsRef.current.clear(); requestsRef.current = new WeakMap(); payloadsRef.current = new WeakMap(); setEdits(new Map()); + setEditingPaths(new Set()); setError(null); }); @@ -285,12 +295,14 @@ export function useEdits({ if (files.length === 0) { editsRef.current.clear(); setEdits(new Map()); + setEditingPaths(new Set()); return; } const result = await api.applyEdits(action, { filter: activeFilter, files }); prepareForRefresh(); editsRef.current.clear(); setEdits(new Map()); + setEditingPaths(new Set()); requestsRef.current = new WeakMap(); payloadsRef.current = new WeakMap(); await loadPatch(activeFilter); @@ -318,6 +330,8 @@ export function useEdits({ return { edits, + editingPaths, + startEditing, dirtyPaths, reset, pendingAction,