feat: diff file multi line comment

This commit is contained in:
Carlos Florêncio
2026-01-24 23:11:15 +00:00
committed by GitHub
parent 3b9abea3ca
commit d6e2380bdf
15 changed files with 1604 additions and 2 deletions
@@ -0,0 +1,97 @@
'use client';
import { useState, useEffect } from 'react';
import { SplitSide } from '@git-diff-view/react';
import { findRowsInRangeWithLineNumbers, groupByConsecutiveRowIndices } from './dom-utils';
import type { DiffComment } from './types';
interface CommentRangeIndicatorProps {
comment: DiffComment;
wrapperRef: React.RefObject<HTMLDivElement | null>;
viewMode: 'split' | 'unified';
}
interface IndicatorRect {
top: number;
height: number;
left: number | string;
width: string;
}
export function CommentRangeIndicator({
comment,
wrapperRef,
viewMode,
}: CommentRangeIndicatorProps) {
const [indicators, setIndicators] = useState<IndicatorRect[]>([]);
useEffect(() => {
const updatePosition = () => {
const wrapper = wrapperRef.current;
if (!wrapper) return;
const rowsWithNumbers = findRowsInRangeWithLineNumbers(wrapper, viewMode, comment.side, comment.startLine, comment.endLine);
if (rowsWithNumbers.length === 0) {
setIndicators([]);
return;
}
const wrapperRect = wrapper.getBoundingClientRect();
const left = viewMode === 'split' && comment.side === SplitSide.old ? 0 : viewMode === 'split' ? '50%' : 0;
const width = viewMode === 'split' ? '50%' : '100%';
// Group rows by consecutive row indices (split view) or all together (unified view)
const groups = viewMode === 'split'
? groupByConsecutiveRowIndices(rowsWithNumbers)
: [rowsWithNumbers.map(r => r.row)];
const newIndicators: IndicatorRect[] = groups.map((group) => {
const firstRect = group[0].getBoundingClientRect();
const lastRect = group[group.length - 1].getBoundingClientRect();
return {
top: firstRect.top - wrapperRect.top + wrapper.scrollTop,
height: lastRect.bottom - firstRect.top,
left,
width,
};
});
setIndicators(newIndicators);
};
updatePosition();
const wrapper = wrapperRef.current;
wrapper?.addEventListener('scroll', updatePosition);
window.addEventListener('resize', updatePosition);
return () => {
wrapper?.removeEventListener('scroll', updatePosition);
window.removeEventListener('resize', updatePosition);
};
}, [comment, wrapperRef, viewMode]);
if (indicators.length === 0) return null;
return (
<>
{indicators.map((indicator, index) => (
<div
key={index}
style={{
display: 'block',
position: 'absolute',
top: indicator.top,
height: indicator.height,
left: indicator.left,
width: indicator.width,
backgroundColor: 'oklch(0.75 0.12 80 / 15%)',
borderRight: '3px solid oklch(0.7 0.15 80)',
pointerEvents: 'none',
zIndex: 5,
}}
/>
))}
</>
);
}
@@ -0,0 +1,42 @@
'use client';
import { SplitSide } from '@git-diff-view/react';
import { Button } from '@kandev/ui/button';
import { Badge } from '@kandev/ui/badge';
import { IconTrash } from '@tabler/icons-react';
import type { DiffComment } from './types';
interface CommentRendererProps {
comment: DiffComment;
onDelete: (id: string) => void;
}
export function CommentRenderer({ comment, onDelete }: CommentRendererProps) {
const isSingleLine = comment.startLine === comment.endLine;
return (
<div className="p-3 bg-amber-50 dark:bg-amber-950/30 border-t border-amber-200 dark:border-amber-800">
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="text-xs text-muted-foreground mb-1">
{isSingleLine
? `Line ${comment.startLine}`
: `Lines ${comment.startLine}-${comment.endLine}`}
<Badge variant="outline" className="ml-2 text-xs">
{comment.side === SplitSide.old ? 'old' : 'new'}
</Badge>
</div>
<div className="text-sm whitespace-pre-wrap">{comment.content}</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => onDelete(comment.id)}
className="h-6 w-6 p-0 text-destructive hover:text-destructive shrink-0"
>
<IconTrash className="h-3.5 w-3.5" />
</Button>
</div>
</div>
);
}
@@ -0,0 +1,192 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import { SplitSide, type DiffFile } from '@git-diff-view/react';
import { Button } from '@kandev/ui/button';
import { Badge } from '@kandev/ui/badge';
import { Textarea } from '@kandev/ui/textarea';
import type { DiffComment } from './types';
interface InlineCommentWidgetProps {
lineNumber: number;
side: SplitSide;
startLine: number;
diffFile: DiffFile;
wrapperRef: React.RefObject<HTMLDivElement | null>;
viewMode: 'split' | 'unified';
filePath: string;
onSave: (comment: DiffComment) => void;
onCancel: () => void;
onStartLineChange: (startLine: number) => void;
}
export function InlineCommentWidget({
lineNumber,
side,
startLine,
diffFile,
wrapperRef,
viewMode,
filePath,
onSave,
onCancel,
onStartLineChange,
}: InlineCommentWidgetProps) {
const [content, setContent] = useState('');
const coverRef = useRef<HTMLDivElement | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const endLine = lineNumber;
const rangeStart = Math.min(startLine, endLine);
const rangeEnd = Math.max(startLine, endLine);
const isSingleLine = rangeStart === rangeEnd;
// Auto-focus textarea
useEffect(() => {
setTimeout(() => textareaRef.current?.focus(), 50);
}, []);
// Create visual overlay for selected lines (multi-line selection effect)
useEffect(() => {
if (!wrapperRef.current || isSingleLine) return;
let coverItem = coverRef.current;
if (!coverItem) {
coverItem = document.createElement('div');
coverRef.current = coverItem;
coverItem.className = 'diff-multiline-selection-overlay';
}
const updateCover = () => {
const id = diffFile.getId();
const wrapper = document.querySelector(`#diff-root${id}`);
if (!wrapper || !coverItem) return;
const items: HTMLElement[] = [];
for (let i = rangeStart; i <= rangeEnd; i++) {
const lineIndex =
viewMode === 'split'
? diffFile.getSplitLineIndexByLineNumber(i, side)
: diffFile.getUnifiedLineIndexByLineNumber(i, side);
if (lineIndex === undefined) continue;
const lineDom = wrapper.querySelector(`[data-line="${lineIndex + 1}"]`) as HTMLElement;
if (lineDom) {
items.push(lineDom);
}
}
if (items.length === 0) {
coverItem.style.display = 'none';
return;
}
const firstItem = items[0];
const lastItem = items[items.length - 1];
const wrapperEl = wrapperRef.current;
if (!wrapperEl) return;
const wrapperRect = wrapperEl.getBoundingClientRect();
const firstRect = firstItem.getBoundingClientRect();
const lastRect = lastItem.getBoundingClientRect();
coverItem.style.display = 'block';
coverItem.style.top = `${firstRect.top - wrapperRect.top + wrapperEl.scrollTop}px`;
coverItem.style.height = `${lastRect.bottom - firstRect.top}px`;
if (viewMode === 'split') {
coverItem.style.left = side === SplitSide.old ? '0' : '50%';
coverItem.style.width = '50%';
} else {
coverItem.style.left = '0';
coverItem.style.width = '100%';
}
if (!wrapperEl.contains(coverItem)) {
wrapperEl.appendChild(coverItem);
}
};
updateCover();
const unsubscribe = diffFile.subscribe(() => setTimeout(updateCover, 0));
return () => {
coverItem?.remove();
coverRef.current = null;
unsubscribe();
};
}, [rangeStart, rangeEnd, side, diffFile, wrapperRef, viewMode, isSingleLine]);
const handleSubmit = () => {
if (content.trim()) {
const comment: DiffComment = {
id: `${filePath}-${Date.now()}`,
startLine: rangeStart,
endLine: rangeEnd,
side,
content: content.trim(),
createdAt: new Date().toISOString(),
};
onSave(comment);
}
};
return (
<div className="p-3 bg-card border-t border-border">
<div className="space-y-3">
<div className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground">Comment on</span>
{isSingleLine ? (
<span className="font-medium">line {rangeStart}</span>
) : (
<>
<span className="text-muted-foreground">lines</span>
<input
type="number"
min={1}
max={endLine}
value={startLine}
onChange={(e) =>
onStartLineChange(Math.max(1, Math.min(endLine, Number(e.target.value))))
}
className="w-16 px-2 py-0.5 text-center border border-border rounded text-sm bg-background"
/>
<span className="text-muted-foreground">to</span>
<span className="font-medium">{endLine}</span>
</>
)}
<Badge variant="outline" className="text-xs">
{side === SplitSide.old ? 'old' : 'new'}
</Badge>
</div>
<Textarea
ref={textareaRef}
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Add a comment..."
className="min-h-[80px] text-sm resize-none"
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
handleSubmit();
}
if (e.key === 'Escape') {
onCancel();
}
}}
/>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={onCancel}>
Cancel
</Button>
<Button size="sm" onClick={handleSubmit} disabled={!content.trim()}>
Add Comment
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,309 @@
/**
* DOM utilities for @git-diff-view/react library integration.
*
* This module uses the library's stable data attributes for DOM queries:
* - data-line: line number on <tr> elements
* - data-side: "old" | "new" on rows (split view only)
* - data-state: "diff" | "plain" | "hunk" | "widget" | "extend"
*
* These data attributes are more stable than CSS class names across library versions.
*
* Fallback to class-based selectors is provided for unified view where
* data-side is not present.
*/
import { SplitSide } from '@git-diff-view/react';
// Stable data attribute selectors
export const SELECTORS = {
// Row with line number
ROW_WITH_LINE: 'tr[data-line]',
// Split view specific
ROW_OLD_SIDE: 'tr[data-side="old"]',
ROW_NEW_SIDE: 'tr[data-side="new"]',
// Fallback class selectors for unified view
CELL_LINE_NUM: 'td.diff-line-num',
CELL_OLD_NUM: 'td.diff-line-old-num',
CELL_NEW_NUM: 'td.diff-line-new-num',
CELL_OLD_CONTENT: 'td.diff-line-old-content',
CELL_NEW_CONTENT: 'td.diff-line-new-content',
} as const;
// Span indices in unified view line number cell
const UNIFIED_SPAN_OLD_INDEX = 0;
const UNIFIED_SPAN_NEW_INDEX = 2;
export interface LineInfo {
lineNumber: number;
side: SplitSide;
}
/**
* Parse line number from data attribute or text content
*/
function parseLineNumber(value: string | null): number | null {
if (!value) return null;
const match = value.trim().match(/^[+-]?(\d+)$/);
return match ? parseInt(match[1], 10) : null;
}
/**
* Get line info from a row using data attributes (preferred) or class-based fallback
*/
function getLineInfoFromRow(
row: Element,
clickedElement: HTMLElement,
viewMode: 'split' | 'unified'
): LineInfo | null {
if (viewMode === 'split') {
// Check if clicked on a placeholder cell (empty cell on one side) - return null
const isOldPlaceholder = clickedElement.closest('td.diff-line-old-placeholder');
const isNewPlaceholder = clickedElement.closest('td.diff-line-new-placeholder');
if (isOldPlaceholder || isNewPlaceholder) {
return null;
}
// Split view: determine which side was clicked and check if it has a line number
const oldNumCell = row.querySelector(SELECTORS.CELL_OLD_NUM);
const newNumCell = row.querySelector(SELECTORS.CELL_NEW_NUM);
const oldContent = row.querySelector(SELECTORS.CELL_OLD_CONTENT);
const newContent = row.querySelector(SELECTORS.CELL_NEW_CONTENT);
// Check if clicked on old side
if (oldNumCell && (oldNumCell.contains(clickedElement) || oldContent?.contains(clickedElement))) {
const num = parseLineNumber(oldNumCell.textContent);
// Only return if there's actually a line number (not an empty cell)
if (num !== null) return { lineNumber: num, side: SplitSide.old };
// Empty cell on old side - return null to skip
return null;
}
// Check if clicked on new side
if (newNumCell && (newNumCell.contains(clickedElement) || newContent?.contains(clickedElement))) {
const num = parseLineNumber(newNumCell.textContent);
// Only return if there's actually a line number (not an empty cell)
if (num !== null) return { lineNumber: num, side: SplitSide.new };
// Empty cell on new side - return null to skip
return null;
}
// Fallback: try data attributes
const dataLine = row.getAttribute('data-line');
const dataSide = row.getAttribute('data-side');
const lineNumber = parseLineNumber(dataLine);
if (lineNumber !== null && dataSide) {
return {
lineNumber,
side: dataSide === 'old' ? SplitSide.old : SplitSide.new,
};
}
} else {
// Unified view: no data-side, need to parse line number cell
const lineNumCell = row.querySelector(SELECTORS.CELL_LINE_NUM);
if (!lineNumCell) return null;
const spans = lineNumCell.querySelectorAll('span');
// Unified view span layout: [old number] [separator] [new number]
let oldNum: number | null = null;
let newNum: number | null = null;
if (spans[UNIFIED_SPAN_OLD_INDEX]) {
oldNum = parseLineNumber(spans[UNIFIED_SPAN_OLD_INDEX].textContent);
}
if (spans[UNIFIED_SPAN_NEW_INDEX]) {
newNum = parseLineNumber(spans[UNIFIED_SPAN_NEW_INDEX].textContent);
}
// Prefer new side if available (additions show on new side)
if (newNum !== null) {
return { lineNumber: newNum, side: SplitSide.new };
}
if (oldNum !== null) {
return { lineNumber: oldNum, side: SplitSide.old };
}
// Final fallback: parse all text
const text = lineNumCell.textContent?.trim() || '';
const numbers = text.match(/\d+/g);
if (numbers && numbers.length > 0) {
const num = parseInt(numbers[numbers.length - 1], 10);
return {
lineNumber: num,
side: numbers.length > 1 ? SplitSide.new : SplitSide.old,
};
}
}
return null;
}
/**
* Extract line number and side from a DOM element within the diff viewer
*/
export function getLineInfoFromElement(
element: HTMLElement,
wrapper: HTMLElement | null,
viewMode: 'split' | 'unified'
): LineInfo | null {
let current: HTMLElement | null = element;
while (current && current !== wrapper) {
const row = current.closest('tr');
if (row) {
const info = getLineInfoFromRow(row, element, viewMode);
if (info) return info;
}
current = current.parentElement;
}
return null;
}
export interface RowWithLineNumber {
row: HTMLElement;
lineNumber: number;
rowIndex: number; // Index in DOM for detecting visual gaps
}
/**
* Find all rows in a line number range for overlay positioning
*/
export function findRowsInRange(
wrapper: HTMLElement,
viewMode: 'split' | 'unified',
side: SplitSide,
startLine: number,
endLine: number
): HTMLElement[] {
return findRowsInRangeWithLineNumbers(wrapper, viewMode, side, startLine, endLine).map(r => r.row);
}
/**
* Find all rows in a line number range, returning both row and line number
* This allows grouping by consecutive line numbers for split view
*/
export function findRowsInRangeWithLineNumbers(
wrapper: HTMLElement,
viewMode: 'split' | 'unified',
side: SplitSide,
startLine: number,
endLine: number
): RowWithLineNumber[] {
const items: RowWithLineNumber[] = [];
if (viewMode === 'split') {
// Get all rows to track row indices
const allRows = Array.from(wrapper.querySelectorAll('tr'));
const rowIndexMap = new Map<HTMLElement, number>();
allRows.forEach((row, idx) => rowIndexMap.set(row as HTMLElement, idx));
// Split view: use class-based selectors to get line numbers from cells
const sideClass = side === SplitSide.old ? SELECTORS.CELL_OLD_NUM : SELECTORS.CELL_NEW_NUM;
const lineNumCells = wrapper.querySelectorAll(sideClass);
lineNumCells.forEach((cell) => {
const num = parseLineNumber(cell.textContent);
if (num !== null && num >= startLine && num <= endLine) {
const row = cell.closest('tr') as HTMLElement;
if (row) {
const rowIndex = rowIndexMap.get(row) ?? -1;
items.push({ row, lineNumber: num, rowIndex });
}
}
});
// Sort by row index to ensure DOM order
items.sort((a, b) => a.rowIndex - b.rowIndex);
} else {
// Unified view: iterate through all line rows
const allRows = Array.from(wrapper.querySelectorAll('tr'));
const rowIndexMap = new Map<Element, number>();
allRows.forEach((row, idx) => rowIndexMap.set(row, idx));
const rows = wrapper.querySelectorAll(SELECTORS.ROW_WITH_LINE);
rows.forEach((row) => {
const lineNumCell = row.querySelector(SELECTORS.CELL_LINE_NUM);
if (!lineNumCell) return;
const spans = lineNumCell.querySelectorAll('span');
let targetNum: number | null = null;
// Check the appropriate span based on side - NO fallback to avoid matching wrong side
const spanIndex = side === SplitSide.old ? UNIFIED_SPAN_OLD_INDEX : UNIFIED_SPAN_NEW_INDEX;
if (spans[spanIndex]) {
targetNum = parseLineNumber(spans[spanIndex].textContent);
}
// Only use fallback if there are no spans (old library version)
if (targetNum === null && spans.length === 0) {
const text = lineNumCell.textContent?.trim() || '';
const numbers = text.match(/\d+/g);
if (numbers && numbers.length > 0) {
const idx = side === SplitSide.old ? 0 : numbers.length - 1;
targetNum = parseInt(numbers[idx], 10);
}
}
if (targetNum !== null && targetNum >= startLine && targetNum <= endLine) {
const rowIndex = rowIndexMap.get(row) ?? -1;
items.push({ row: row as HTMLElement, lineNumber: targetNum, rowIndex });
}
});
// Sort by row index
items.sort((a, b) => a.rowIndex - b.rowIndex);
}
// Remove duplicates based on row
const seen = new Set<HTMLElement>();
return items.filter(item => {
if (seen.has(item.row)) return false;
seen.add(item.row);
return true;
});
}
/**
* Find a specific row by line number for widget positioning
*/
export function findRowByLineNumber(
wrapper: HTMLElement,
viewMode: 'split' | 'unified',
side: SplitSide,
lineNumber: number
): HTMLElement | null {
const rows = findRowsInRange(wrapper, viewMode, side, lineNumber, lineNumber);
return rows[0] || null;
}
/**
* Group rows into contiguous ranges based on consecutive ROW INDICES.
* This detects visual gaps caused by rows with empty cells on the selected side.
* Used for split view to show separate overlays for non-adjacent rows.
*/
export function groupByConsecutiveRowIndices(items: RowWithLineNumber[]): HTMLElement[][] {
if (items.length === 0) return [];
const groups: HTMLElement[][] = [];
let currentGroup: HTMLElement[] = [items[0].row];
let lastRowIndex = items[0].rowIndex;
for (let i = 1; i < items.length; i++) {
const { row, rowIndex } = items[i];
if (rowIndex === lastRowIndex + 1) {
currentGroup.push(row);
} else {
groups.push(currentGroup);
currentGroup = [row];
}
lastRowIndex = rowIndex;
}
groups.push(currentGroup);
return groups;
}
@@ -0,0 +1,33 @@
/* Custom styles for @git-diff-view/react demo */
/* CSS Custom Properties */
:root {
--diff-selection-bg: oklch(0.85 0.08 260 / 30%);
--diff-selection-border: oklch(0.6 0.15 260);
}
.dark {
--diff-selection-bg: oklch(0.35 0.08 260 / 40%);
--diff-selection-border: oklch(0.65 0.15 260);
}
/* Multi-line selection overlay */
.diff-multiline-selection-overlay {
position: absolute;
background-color: var(--diff-selection-bg);
border: 2px solid var(--diff-selection-border);
border-radius: 2px;
pointer-events: none;
z-index: 10;
}
/* Ensure proper reset for color in widget/extend wrappers */
.diff-line-extend-wrapper,
.diff-line-widget-wrapper {
color: inherit;
}
.diff-line-extend-wrapper *,
.diff-line-widget-wrapper * {
color: inherit;
}
@@ -0,0 +1,311 @@
'use client';
import { useState, useRef, useCallback, useMemo, useEffect } from 'react';
import { DiffView, DiffModeEnum, SplitSide } from '@git-diff-view/react';
import { generateDiffFile } from '@git-diff-view/file';
import { useTheme } from 'next-themes';
import { Button } from '@kandev/ui/button';
import { Badge } from '@kandev/ui/badge';
import { IconLayoutColumns, IconLayoutRows } from '@tabler/icons-react';
import { cn } from '@/lib/utils';
import { useDiffComments } from './use-diff-comments';
import { InlineCommentWidget } from './comment-widget';
import { CommentRenderer } from './comment-renderer';
import { DragSelectionOverlay } from './selection-overlay';
import { CommentRangeIndicator } from './comment-indicator';
import { PositionedCommentWidget } from './multi-line-comment';
import { getLineInfoFromElement } from './dom-utils';
import type { GitDiffViewerProps, ExtendLineData, DragSelectionState } from './types';
import '@git-diff-view/react/styles/diff-view.css';
import './git-diff-viewer.css';
export function GitDiffViewer({
oldContent,
newContent,
filePath,
language = 'typescript',
defaultViewMode = 'split',
showToolbar = true,
enableComments = true,
comments: externalComments,
onCommentAdd,
onCommentDelete,
className,
}: GitDiffViewerProps) {
const { resolvedTheme } = useTheme();
const [viewMode, setViewMode] = useState<'split' | 'unified'>(defaultViewMode);
const [widgetStartLines, setWidgetStartLines] = useState<Record<string, number>>({});
const widgetStartLinesRef = useRef(widgetStartLines);
useEffect(() => {
widgetStartLinesRef.current = widgetStartLines;
}, [widgetStartLines]);
// Drag selection state for multi-line comments
const [dragSelection, setDragSelection] = useState<DragSelectionState | null>(null);
const [showDragWidget, setShowDragWidget] = useState(false);
const justCompletedMultiLineRef = useRef(false);
const wrapperRef = useRef<HTMLDivElement>(null);
// Comment management
const { comments, addComment, deleteComment } = useDiffComments({
filePath,
externalComments,
onCommentAdd,
onCommentDelete,
});
const diffModeEnum = viewMode === 'split' ? DiffModeEnum.Split : DiffModeEnum.Unified;
const diffTheme = resolvedTheme === 'dark' ? 'dark' : 'light';
// Generate diff file
const diffFile = useMemo(() => {
try {
const file = generateDiffFile(filePath, oldContent, filePath, newContent, language, language);
file.initRaw();
return file;
} catch (e) {
console.error('Failed to generate diff:', e);
return null;
}
}, [filePath, oldContent, newContent, language]);
// Build extendData for displaying existing comments
const extendData = useMemo(() => {
const oldFileData: Record<string, { data: ExtendLineData }> = {};
const newFileData: Record<string, { data: ExtendLineData }> = {};
comments.forEach((comment) => {
const lineKey = String(comment.endLine);
const entry: ExtendLineData = { type: 'comment', comment };
if (comment.side === SplitSide.old) {
oldFileData[lineKey] = { data: entry };
} else {
newFileData[lineKey] = { data: entry };
}
});
return { oldFile: oldFileData, newFile: newFileData };
}, [comments]);
// Mouse handlers for drag selection
const handleMouseDown = useCallback(
(e: React.MouseEvent) => {
if (!enableComments || e.button !== 0) return;
const target = e.target as HTMLElement;
const lineInfo = getLineInfoFromElement(target, wrapperRef.current, viewMode);
if (lineInfo) {
setDragSelection({
startLine: lineInfo.lineNumber,
endLine: lineInfo.lineNumber,
side: lineInfo.side,
isActive: true,
});
setShowDragWidget(false);
justCompletedMultiLineRef.current = false;
}
},
[enableComments, viewMode]
);
const handleMouseMove = useCallback(
(e: React.MouseEvent) => {
if (!dragSelection?.isActive) return;
const target = e.target as HTMLElement;
const lineInfo = getLineInfoFromElement(target, wrapperRef.current, viewMode);
if (lineInfo && lineInfo.side === dragSelection.side && lineInfo.lineNumber !== dragSelection.endLine) {
setDragSelection((prev) => (prev ? { ...prev, endLine: lineInfo.lineNumber } : null));
}
},
[dragSelection, viewMode]
);
const handleMouseUp = useCallback(() => {
if (!dragSelection?.isActive) return;
const { startLine, endLine, side } = dragSelection;
const rangeStart = Math.min(startLine, endLine);
const rangeEnd = Math.max(startLine, endLine);
if (rangeStart !== rangeEnd) {
setDragSelection({ startLine: rangeStart, endLine: rangeEnd, side, isActive: false });
setShowDragWidget(true);
justCompletedMultiLineRef.current = true;
} else {
setDragSelection(null);
}
}, [dragSelection]);
const handleMouseLeave = useCallback(() => {
if (dragSelection?.isActive) {
setDragSelection(null);
}
}, [dragSelection]);
// Prevent library's single-line widget after multi-line selection
const handleClick = useCallback((e: React.MouseEvent) => {
if (justCompletedMultiLineRef.current) {
e.stopPropagation();
e.preventDefault();
justCompletedMultiLineRef.current = false;
}
}, []);
// Handle widget line rendering for single-line comments
const renderWidgetLine = useCallback(
(props: { side: SplitSide; lineNumber: number; onClose: () => void }) => {
if (!diffFile || !enableComments) return null;
const widgetKey = `${filePath}-${props.side}-${props.lineNumber}`;
const startLine = widgetStartLinesRef.current[widgetKey] ?? props.lineNumber;
return (
<InlineCommentWidget
key={widgetKey}
lineNumber={props.lineNumber}
side={props.side}
startLine={startLine}
diffFile={diffFile}
wrapperRef={wrapperRef}
viewMode={viewMode}
filePath={filePath}
onSave={(comment) => {
addComment(comment.startLine, comment.endLine, comment.side, comment.content);
setWidgetStartLines((prev) => {
const next = { ...prev };
delete next[widgetKey];
return next;
});
props.onClose();
}}
onCancel={() => {
setWidgetStartLines((prev) => {
const next = { ...prev };
delete next[widgetKey];
return next;
});
props.onClose();
}}
onStartLineChange={(newStartLine) => {
setWidgetStartLines((prev) => ({ ...prev, [widgetKey]: newStartLine }));
}}
/>
);
},
[filePath, diffFile, viewMode, enableComments, addComment]
);
// Render existing comments inline
const renderExtendLine = useCallback(
(lineData: { data: ExtendLineData }) => {
if (!lineData.data) return null;
return <CommentRenderer comment={lineData.data.comment} onDelete={(id) => deleteComment(id)} />;
},
[deleteComment]
);
if (!diffFile) {
return (
<div className={cn('flex items-center justify-center p-6', className)}>
<div className="text-muted-foreground">Failed to generate diff</div>
</div>
);
}
return (
<div className={cn('space-y-4', className)}>
{showToolbar && (
<div className="flex items-center justify-between">
<Badge variant="secondary" className="rounded-full text-xs">
{filePath}
</Badge>
<div className="inline-flex rounded-md border border-border overflow-hidden">
<Button
type="button"
variant="ghost"
size="sm"
className={cn('h-7 px-2 text-xs rounded-none cursor-pointer', viewMode === 'unified' && 'bg-muted')}
onClick={() => setViewMode('unified')}
>
<IconLayoutRows className="h-3.5 w-3.5" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className={cn('h-7 px-2 text-xs rounded-none cursor-pointer', viewMode === 'split' && 'bg-muted')}
onClick={() => setViewMode('split')}
>
<IconLayoutColumns className="h-3.5 w-3.5" />
</Button>
</div>
</div>
)}
{/* Outer container for positioning widget outside overflow */}
<div className="relative">
<div
ref={wrapperRef}
className="relative border border-border rounded-lg overflow-x-auto select-none"
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseLeave}
onClickCapture={handleClick}
>
{/* Comment range indicators */}
{enableComments &&
comments.map((comment) => (
<CommentRangeIndicator key={comment.id} comment={comment} wrapperRef={wrapperRef} viewMode={viewMode} />
))}
{/* Drag selection overlay */}
{enableComments && dragSelection && diffFile && (
<DragSelectionOverlay selection={dragSelection} wrapperRef={wrapperRef} viewMode={viewMode} />
)}
<DiffView
diffFile={diffFile}
diffViewWrap={false}
diffViewTheme={diffTheme}
diffViewHighlight
diffViewMode={diffModeEnum}
diffViewFontSize={12}
diffViewAddWidget={enableComments}
onAddWidgetClick={() => {}}
renderWidgetLine={renderWidgetLine}
extendData={extendData}
renderExtendLine={renderExtendLine}
/>
</div>
{/* Multi-line comment widget - outside overflow container */}
{enableComments && showDragWidget && dragSelection && !dragSelection.isActive && diffFile && (
<PositionedCommentWidget
selection={dragSelection}
diffFile={diffFile}
wrapperRef={wrapperRef}
viewMode={viewMode}
onSave={(content) => {
addComment(dragSelection.startLine, dragSelection.endLine, dragSelection.side, content);
setDragSelection(null);
setShowDragWidget(false);
}}
onCancel={() => {
setDragSelection(null);
setShowDragWidget(false);
}}
/>
)}
</div>
</div>
);
}
@@ -0,0 +1,10 @@
export { GitDiffViewer } from './git-diff-viewer';
export { useDiffComments } from './use-diff-comments';
export type {
DiffComment,
GitDiffViewerProps,
DragSelectionState,
ExtendLineData,
CommentWidgetProps,
SplitSide,
} from './types';
@@ -0,0 +1,126 @@
'use client';
import { useState, useEffect, useRef } from 'react';
import { SplitSide, type DiffFile } from '@git-diff-view/react';
import { Button } from '@kandev/ui/button';
import { Badge } from '@kandev/ui/badge';
import { Textarea } from '@kandev/ui/textarea';
import { findRowByLineNumber } from './dom-utils';
import type { DragSelectionState } from './types';
interface MultiLineCommentInputProps {
startLine: number;
endLine: number;
side: SplitSide;
onSave: (content: string) => void;
onCancel: () => void;
}
export function MultiLineCommentInput({
startLine,
endLine,
side,
onSave,
onCancel,
}: MultiLineCommentInputProps) {
const [content, setContent] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
textareaRef.current?.focus();
}, []);
return (
<div className="space-y-3">
<div className="flex items-center gap-2 text-sm">
<span className="text-muted-foreground">Comment on lines</span>
<span className="font-medium">{startLine}</span>
<span className="text-muted-foreground">to</span>
<span className="font-medium">{endLine}</span>
<Badge variant="outline" className="text-xs">
{side === SplitSide.old ? 'old' : 'new'}
</Badge>
</div>
<Textarea
ref={textareaRef}
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Add a comment..."
className="min-h-[80px] text-sm resize-none"
onKeyDown={(e) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
if (content.trim()) onSave(content.trim());
}
if (e.key === 'Escape') {
onCancel();
}
}}
/>
<div className="flex justify-end gap-2">
<Button variant="outline" size="sm" onClick={onCancel}>
Cancel
</Button>
<Button size="sm" onClick={() => content.trim() && onSave(content.trim())} disabled={!content.trim()}>
Add Comment
</Button>
</div>
</div>
);
}
interface PositionedCommentWidgetProps {
selection: DragSelectionState;
diffFile: DiffFile;
wrapperRef: React.RefObject<HTMLDivElement | null>;
viewMode: 'split' | 'unified';
onSave: (content: string) => void;
onCancel: () => void;
}
export function PositionedCommentWidget({
selection,
diffFile,
wrapperRef,
viewMode,
onSave,
onCancel,
}: PositionedCommentWidgetProps) {
const [position, setPosition] = useState<{ top: number; left: number | string; width: string } | null>(null);
useEffect(() => {
const wrapper = wrapperRef.current;
if (!wrapper) return;
const endRow = findRowByLineNumber(wrapper, viewMode, selection.side, selection.endLine);
if (endRow) {
const wrapperRect = wrapper.getBoundingClientRect();
const rowRect = endRow.getBoundingClientRect();
setPosition({
top: rowRect.bottom - wrapperRect.top + wrapper.scrollTop,
left: viewMode === 'split' && selection.side === SplitSide.old ? 0 : viewMode === 'split' ? '50%' : 0,
width: viewMode === 'split' ? '50%' : '100%',
});
}
}, [selection, diffFile, wrapperRef, viewMode]);
if (!position) return null;
return (
<div
className="absolute z-30 bg-card border border-border rounded shadow-lg p-3"
style={{ top: position.top, left: position.left, width: position.width }}
>
<MultiLineCommentInput
startLine={selection.startLine}
endLine={selection.endLine}
side={selection.side}
onSave={onSave}
onCancel={onCancel}
/>
</div>
);
}
@@ -0,0 +1,98 @@
'use client';
import { useState, useEffect } from 'react';
import { SplitSide } from '@git-diff-view/react';
import { findRowsInRangeWithLineNumbers, groupByConsecutiveRowIndices } from './dom-utils';
import type { DragSelectionState } from './types';
interface DragSelectionOverlayProps {
selection: DragSelectionState;
wrapperRef: React.RefObject<HTMLDivElement | null>;
viewMode: 'split' | 'unified';
}
interface OverlayRect {
top: number;
height: number;
left: number | string;
width: string;
}
export function DragSelectionOverlay({
selection,
wrapperRef,
viewMode,
}: DragSelectionOverlayProps) {
const [overlays, setOverlays] = useState<OverlayRect[]>([]);
useEffect(() => {
const updatePosition = () => {
const wrapper = wrapperRef.current;
if (!wrapper) return;
const rangeStart = Math.min(selection.startLine, selection.endLine);
const rangeEnd = Math.max(selection.startLine, selection.endLine);
const rowsWithNumbers = findRowsInRangeWithLineNumbers(wrapper, viewMode, selection.side, rangeStart, rangeEnd);
if (rowsWithNumbers.length === 0) {
setOverlays([]);
return;
}
const wrapperRect = wrapper.getBoundingClientRect();
const left = viewMode === 'split' && selection.side === SplitSide.old ? 0 : viewMode === 'split' ? '50%' : 0;
const width = viewMode === 'split' ? '50%' : '100%';
// Group rows by consecutive row indices (split view) or all together (unified view)
const groups = viewMode === 'split'
? groupByConsecutiveRowIndices(rowsWithNumbers)
: [rowsWithNumbers.map(r => r.row)];
const newOverlays: OverlayRect[] = groups.map((group) => {
const firstRect = group[0].getBoundingClientRect();
const lastRect = group[group.length - 1].getBoundingClientRect();
return {
top: firstRect.top - wrapperRect.top + wrapper.scrollTop,
height: lastRect.bottom - firstRect.top,
left,
width,
};
});
setOverlays(newOverlays);
};
updatePosition();
const wrapper = wrapperRef.current;
wrapper?.addEventListener('scroll', updatePosition);
return () => wrapper?.removeEventListener('scroll', updatePosition);
}, [selection, wrapperRef, viewMode]);
if (overlays.length === 0) return null;
return (
<>
{overlays.map((overlay, index) => (
<div
key={index}
className="diff-multiline-selection-overlay"
style={{
display: 'block',
position: 'absolute',
top: overlay.top,
height: overlay.height,
left: overlay.left,
width: overlay.width,
backgroundColor: 'oklch(0.35 0.08 260 / 40%)',
border: '2px solid oklch(0.65 0.15 260)',
borderRadius: 2,
pointerEvents: 'none',
zIndex: 10,
}}
/>
))}
</>
);
}
@@ -0,0 +1,77 @@
import type { SplitSide, DiffFile } from '@git-diff-view/react';
/**
* Comment attached to a line range in a diff
*/
export interface DiffComment {
id: string;
startLine: number;
endLine: number;
side: SplitSide;
content: string;
createdAt: string;
}
/**
* Extended line data for the library's extendData prop
*/
export interface ExtendLineData {
type: 'comment';
comment: DiffComment;
}
/**
* Props for the main GitDiffViewer component
*/
export interface GitDiffViewerProps {
/** Old file content */
oldContent: string;
/** New file content */
newContent: string;
/** File path (used for comment storage key) */
filePath: string;
/** File language for syntax highlighting (e.g., 'tsx', 'typescript') */
language?: string;
/** Initial view mode */
defaultViewMode?: 'split' | 'unified';
/** Whether to show the toolbar */
showToolbar?: boolean;
/** Whether to enable comments */
enableComments?: boolean;
/** External comments (if managing state externally) */
comments?: DiffComment[];
/** Callback when a comment is added */
onCommentAdd?: (comment: DiffComment) => void;
/** Callback when a comment is deleted */
onCommentDelete?: (commentId: string) => void;
/** Additional class name for the container */
className?: string;
}
/**
* Selection state during drag
*/
export interface DragSelectionState {
startLine: number;
endLine: number;
side: SplitSide;
isActive: boolean;
}
/**
* Props for comment widget components
*/
export interface CommentWidgetProps {
lineNumber: number;
side: SplitSide;
startLine: number;
diffFile: DiffFile;
wrapperRef: React.RefObject<HTMLDivElement | null>;
viewMode: 'split' | 'unified';
filePath: string;
onSave: (comment: DiffComment) => void;
onCancel: () => void;
onStartLineChange: (startLine: number) => void;
}
export { SplitSide };
@@ -0,0 +1,102 @@
import { useState, useCallback, useEffect } from 'react';
import type { DiffComment } from './types';
import { SplitSide } from '@git-diff-view/react';
const STORAGE_KEY_PREFIX = 'git-diff-comments';
function getStorageKey(filePath: string): string {
return `${STORAGE_KEY_PREFIX}:${filePath}`;
}
function loadComments(filePath: string): DiffComment[] {
if (typeof window === 'undefined') return [];
try {
const raw = window.localStorage.getItem(getStorageKey(filePath));
if (!raw) return [];
return JSON.parse(raw) as DiffComment[];
} catch {
return [];
}
}
function saveComments(filePath: string, comments: DiffComment[]): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(getStorageKey(filePath), JSON.stringify(comments));
} catch {
// Ignore write failures
}
}
export interface UseDiffCommentsOptions {
/** File path for localStorage key */
filePath: string;
/** External comments (controlled mode) */
externalComments?: DiffComment[];
/** Callback when comment is added (controlled mode) */
onCommentAdd?: (comment: DiffComment) => void;
/** Callback when comment is deleted (controlled mode) */
onCommentDelete?: (commentId: string) => void;
}
export interface UseDiffCommentsReturn {
comments: DiffComment[];
addComment: (startLine: number, endLine: number, side: SplitSide, content: string) => void;
deleteComment: (commentId: string) => void;
}
export function useDiffComments({
filePath,
externalComments,
onCommentAdd,
onCommentDelete,
}: UseDiffCommentsOptions): UseDiffCommentsReturn {
const isControlled = externalComments !== undefined;
const [internalComments, setInternalComments] = useState<DiffComment[]>(() => {
if (isControlled) return [];
return loadComments(filePath);
});
// Persist internal comments to localStorage
useEffect(() => {
if (!isControlled) {
saveComments(filePath, internalComments);
}
}, [filePath, internalComments, isControlled]);
const comments = isControlled ? externalComments : internalComments;
const addComment = useCallback(
(startLine: number, endLine: number, side: SplitSide, content: string) => {
const newComment: DiffComment = {
id: `${filePath}-${Date.now()}`,
startLine,
endLine,
side,
content,
createdAt: new Date().toISOString(),
};
if (isControlled && onCommentAdd) {
onCommentAdd(newComment);
} else {
setInternalComments((prev) => [...prev, newComment]);
}
},
[filePath, isControlled, onCommentAdd]
);
const deleteComment = useCallback(
(commentId: string) => {
if (isControlled && onCommentDelete) {
onCommentDelete(commentId);
} else {
setInternalComments((prev) => prev.filter((c) => c.id !== commentId));
}
},
[isControlled, onCommentDelete]
);
return { comments, addComment, deleteComment };
}