Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
63 changes: 63 additions & 0 deletions ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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';
Expand All @@ -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() {
Expand Down Expand Up @@ -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<number | null>(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<AnnotationMeta> | 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],
Expand All @@ -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';
Expand All @@ -293,6 +351,7 @@ export function App() {
[
displayedParsedFiles,
edits.edits,
edits.editingPaths,
edits.editorReady,
annotationsByPath,
collapsedPaths,
Expand Down Expand Up @@ -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,
}),
[
Expand All @@ -491,6 +553,7 @@ export function App() {
view.theme,
view.lineHeight,
handleGutterClick,
handleLineClick,
edits.loadDiffFiles,
],
);
Expand Down
27 changes: 27 additions & 0 deletions ui/src/caretFromPoint.ts
Original file line number Diff line number Diff line change
@@ -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;
}
26 changes: 20 additions & 6 deletions ui/src/useEdits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export function useEdits({
onEditStart,
}: UseEditsOptions) {
const [edits, setEdits] = useState<ReadonlyMap<string, LocalEdit>>(new Map());
const [editingPaths, setEditingPaths] = useState<ReadonlySet<string>>(() => new Set());
const [pendingAction, setPendingAction] = useState<'commit' | 'discard' | null>(null);
const [error, setError] = useState<string | null>(null);
const [loadingCount, setLoadingCount] = useState(0);
Expand All @@ -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);
Expand All @@ -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);
});

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -318,6 +330,8 @@ export function useEdits({

return {
edits,
editingPaths,
startEditing,
dirtyPaths,
reset,
pendingAction,
Expand Down