feat: diff file multi line comment
This commit is contained in:
Generated
+16
-2
@@ -96,7 +96,7 @@ importers:
|
||||
version: 9.39.2(jiti@2.6.1)
|
||||
eslint-config-next:
|
||||
specifier: 16.1.1
|
||||
version: 16.1.1(@typescript-eslint/parser@8.53.0(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3)
|
||||
version: 16.1.1(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3)
|
||||
tailwindcss:
|
||||
specifier: ^4.0.0
|
||||
version: 4.1.18
|
||||
@@ -281,6 +281,9 @@ importers:
|
||||
'@dnd-kit/utilities':
|
||||
specifier: ^3.2.2
|
||||
version: 3.2.2(react@19.2.3)
|
||||
'@git-diff-view/file':
|
||||
specifier: ^0.0.36
|
||||
version: 0.0.36
|
||||
'@git-diff-view/react':
|
||||
specifier: ^0.0.36
|
||||
version: 0.0.36(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
@@ -404,7 +407,7 @@ importers:
|
||||
version: 9.39.2(jiti@2.6.1)
|
||||
eslint-config-next:
|
||||
specifier: 16.1.1
|
||||
version: 16.1.1(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3)
|
||||
version: 16.1.1(@typescript-eslint/parser@8.53.0(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3))(eslint@9.39.2(jiti@2.6.1))(typescript@5.9.3)
|
||||
happy-dom:
|
||||
specifier: ^20.1.0
|
||||
version: 20.1.0
|
||||
@@ -1033,6 +1036,9 @@ packages:
|
||||
'@git-diff-view/core@0.0.36':
|
||||
resolution: {integrity: sha512-A3mN21C/ZdIJz0J9/PSZvLR1dLBu8BG13tVE+w4A9v8dLS5omkoQVjHM9K5GaoJideMhK/11y6V7CMbMXCPQoQ==}
|
||||
|
||||
'@git-diff-view/file@0.0.36':
|
||||
resolution: {integrity: sha512-3I5GMpZzdTwSurzbz8ZT9HL2xo74W5/o/SgWhUpEWjn2Z6pCZrHLAEzWeYyqewv30YM25PuK/JMODT4S5zhvzw==}
|
||||
|
||||
'@git-diff-view/lowlight@0.0.36':
|
||||
resolution: {integrity: sha512-8H3fUfnW+jw8EEbhEOr0vq5jXxZfbhNgvf9ruY6GljQdymj8j2R69k83gwMB/GltWEMt5o5624d8MxD21vqsZA==}
|
||||
|
||||
@@ -6353,6 +6359,14 @@ snapshots:
|
||||
highlight.js: 11.11.1
|
||||
lowlight: 3.3.0
|
||||
|
||||
'@git-diff-view/file@0.0.36':
|
||||
dependencies:
|
||||
'@git-diff-view/core': 0.0.36
|
||||
diff: 8.0.3
|
||||
fast-diff: 1.3.0
|
||||
highlight.js: 11.11.1
|
||||
lowlight: 3.3.0
|
||||
|
||||
'@git-diff-view/lowlight@0.0.36':
|
||||
dependencies:
|
||||
'@types/hast': 3.0.4
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { ThemeProvider } from 'next-themes';
|
||||
import { TooltipProvider } from '@kandev/ui/tooltip';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { GitDiffViewer } from '@/components/git-diff-view';
|
||||
|
||||
// Sample diffs for demo
|
||||
const BUTTON_DIFF_OLD = `import React from 'react';
|
||||
|
||||
interface ButtonProps {
|
||||
children: React.ReactNode;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function Button({ children, onClick, disabled }: ButtonProps) {
|
||||
return (
|
||||
<button onClick={onClick} disabled={disabled}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}`;
|
||||
|
||||
const BUTTON_DIFF_NEW = `import React from 'react';
|
||||
import { cn } from '../lib/utils';
|
||||
|
||||
interface ButtonProps {
|
||||
children: React.ReactNode;
|
||||
onClick?: (event: React.MouseEvent) => void;
|
||||
variant?: 'primary' | 'secondary';
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
onClick,
|
||||
variant = 'primary',
|
||||
disabled
|
||||
}: ButtonProps) {
|
||||
return (
|
||||
<button className={cn('btn', \`btn-\${variant}\`)} onClick={onClick} disabled={disabled}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}`;
|
||||
|
||||
const FORMAT_DIFF_OLD = '';
|
||||
const FORMAT_DIFF_NEW = `export function formatDate(date: Date): string {
|
||||
return date.toLocaleDateString('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
});
|
||||
}
|
||||
|
||||
export function formatCurrency(amount: number): string {
|
||||
return new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
}).format(amount);
|
||||
}`;
|
||||
|
||||
type DiffExample = 'button' | 'newfile';
|
||||
|
||||
const DIFFS: Record<
|
||||
DiffExample,
|
||||
{ label: string; oldContent: string; newContent: string; path: string; description: string }
|
||||
> = {
|
||||
button: {
|
||||
label: 'Button Component',
|
||||
oldContent: BUTTON_DIFF_OLD,
|
||||
newContent: BUTTON_DIFF_NEW,
|
||||
path: 'src/Button.tsx',
|
||||
description: 'Standard diff with additions and deletions',
|
||||
},
|
||||
newfile: {
|
||||
label: 'New File',
|
||||
oldContent: FORMAT_DIFF_OLD,
|
||||
newContent: FORMAT_DIFF_NEW,
|
||||
path: 'src/utils/format.ts',
|
||||
description: 'Shows a newly created file (all additions)',
|
||||
},
|
||||
};
|
||||
|
||||
function GitDiffViewDemoContent() {
|
||||
const [selectedDiff, setSelectedDiff] = useState<DiffExample>('button');
|
||||
const currentDiff = DIFFS[selectedDiff];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background p-6">
|
||||
<div className="max-w-6xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold">GitDiffViewer Demo</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Diff viewer with inline comments and multi-line selection.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Diff selector */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(DIFFS).map(([key, { label }]) => (
|
||||
<Button
|
||||
key={key}
|
||||
variant={selectedDiff === key ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={() => setSelectedDiff(key as DiffExample)}
|
||||
>
|
||||
{label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Description */}
|
||||
<div className="text-sm text-muted-foreground bg-muted/50 px-3 py-2 rounded">
|
||||
{currentDiff.description}
|
||||
</div>
|
||||
|
||||
{/* Instructions */}
|
||||
<div className="text-xs text-muted-foreground bg-primary/5 border border-primary/20 px-3 py-2 rounded space-y-1">
|
||||
<p>
|
||||
<strong>Single line:</strong> Click the{' '}
|
||||
<span className="font-mono bg-muted px-1 rounded">+</span> button on any line to add a
|
||||
comment.
|
||||
</p>
|
||||
<p>
|
||||
<strong>Multi-line:</strong> Click and drag from one line to another to select a range,
|
||||
then add your comment.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Diff viewer */}
|
||||
<GitDiffViewer
|
||||
oldContent={currentDiff.oldContent}
|
||||
newContent={currentDiff.newContent}
|
||||
filePath={currentDiff.path}
|
||||
language="tsx"
|
||||
defaultViewMode="split"
|
||||
enableComments
|
||||
/>
|
||||
|
||||
{/* Features list */}
|
||||
<div className="p-4 bg-muted rounded-lg space-y-3 text-sm">
|
||||
<h3 className="font-medium">Features:</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h4 className="font-medium text-muted-foreground mb-1">Built-in Features</h4>
|
||||
<ul className="list-disc list-inside space-y-0.5 text-muted-foreground">
|
||||
<li>Syntax highlighting</li>
|
||||
<li>Split and unified view modes</li>
|
||||
<li>Light and dark theme support</li>
|
||||
<li>Add widget (+) buttons on hover</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="font-medium text-muted-foreground mb-1">Comments</h4>
|
||||
<ul className="list-disc list-inside space-y-0.5 text-muted-foreground">
|
||||
<li>Click + to open inline comment widget</li>
|
||||
<li>Click and drag to select multiple lines</li>
|
||||
<li>Visual overlay shows selected range</li>
|
||||
<li>Comments persisted to localStorage</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function GitDiffViewDemo() {
|
||||
return (
|
||||
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
|
||||
<TooltipProvider>
|
||||
<GitDiffViewDemoContent />
|
||||
</TooltipProvider>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { GitDiffViewDemo } from './demo-client';
|
||||
|
||||
export const metadata = {
|
||||
title: 'GitDiffViewer Demo',
|
||||
};
|
||||
|
||||
export default function GitDiffViewDemoPage() {
|
||||
return <GitDiffViewDemo />;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -29,6 +29,7 @@
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@git-diff-view/file": "^0.0.36",
|
||||
"@git-diff-view/react": "^0.0.36",
|
||||
"@kandev/theme": "workspace:*",
|
||||
"@kandev/types": "workspace:*",
|
||||
|
||||
Reference in New Issue
Block a user