feat: improve monaco comments (#241)
This commit is contained in:
Generated
+5
-5
@@ -231,8 +231,8 @@ importers:
|
||||
specifier: ^4.7.0
|
||||
version: 4.7.0(monaco-editor@0.55.1)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@pierre/diffs':
|
||||
specifier: ^1.0.10
|
||||
version: 1.0.10(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
specifier: ^1.0.11
|
||||
version: 1.0.11(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@tabler/icons-react':
|
||||
specifier: ^3.36.1
|
||||
version: 3.36.1(react@19.2.3)
|
||||
@@ -1527,8 +1527,8 @@ packages:
|
||||
'@open-draft/until@2.1.0':
|
||||
resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
|
||||
|
||||
'@pierre/diffs@1.0.10':
|
||||
resolution: {integrity: sha512-ahkpfS30NfaB+PBxnf0/Mc20ySBRTQmM28a7Ojpd0UZixmTyhGhJfBFjvmhX8dSzR22lB3h3OIMMxpB4yYTIOQ==}
|
||||
'@pierre/diffs@1.0.11':
|
||||
resolution: {integrity: sha512-j6zIEoyImQy1HfcJqbrDwP0O5I7V2VNXAaw53FqQ+SykRfaNwABeZHs9uibXO4supaXPmTx6LEH9Lffr03e1Tw==}
|
||||
peerDependencies:
|
||||
react: ^18.3.1 || ^19.0.0
|
||||
react-dom: ^18.3.1 || ^19.0.0
|
||||
@@ -7531,7 +7531,7 @@ snapshots:
|
||||
|
||||
'@open-draft/until@2.1.0': {}
|
||||
|
||||
'@pierre/diffs@1.0.10(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
|
||||
'@pierre/diffs@1.0.11(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
|
||||
dependencies:
|
||||
'@shikijs/core': 3.22.0
|
||||
'@shikijs/engine-javascript': 3.22.0
|
||||
|
||||
+63
-18
@@ -650,21 +650,37 @@
|
||||
|
||||
/* Monaco Editor - Comment decorations */
|
||||
.monaco-comment-line {
|
||||
background-color: rgba(99, 102, 241, 0.15) !important;
|
||||
background-color: rgba(99, 102, 241, 0.12) !important;
|
||||
}
|
||||
|
||||
/* Lines-decoration lane for commented lines — clickable bar */
|
||||
.monaco-comment-bar {
|
||||
cursor: pointer !important;
|
||||
background-color: rgba(99, 102, 241, 0.12) !important;
|
||||
border-left: 3px solid rgba(99, 102, 241, 0.6) !important;
|
||||
}
|
||||
|
||||
.monaco-comment-glyph {
|
||||
background-color: rgba(99, 102, 241, 0.2);
|
||||
cursor: pointer;
|
||||
.monaco-comment-bar:hover {
|
||||
background-color: rgba(99, 102, 241, 0.25) !important;
|
||||
}
|
||||
|
||||
.monaco-comment-glyph::after {
|
||||
/* Chat bubble icon on the bar (first line of a comment only) */
|
||||
.monaco-comment-bar-icon {
|
||||
cursor: pointer !important;
|
||||
position: relative !important;
|
||||
background-color: rgba(99, 102, 241, 0.12) !important;
|
||||
border-left: 3px solid rgba(99, 102, 241, 0.6) !important;
|
||||
}
|
||||
.monaco-comment-bar-icon:hover {
|
||||
background-color: rgba(99, 102, 241, 0.25) !important;
|
||||
}
|
||||
.monaco-comment-bar-icon::after {
|
||||
content: '';
|
||||
display: block;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
margin: auto;
|
||||
background: rgba(99, 102, 241, 0.9);
|
||||
mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z'/></svg>");
|
||||
-webkit-mask-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z'/></svg>");
|
||||
@@ -672,12 +688,9 @@
|
||||
-webkit-mask-size: contain;
|
||||
}
|
||||
|
||||
.monaco-comment-glyph:hover {
|
||||
background-color: rgba(99, 102, 241, 0.35);
|
||||
}
|
||||
|
||||
.monaco-comment-glyph-bg {
|
||||
background-color: rgba(99, 102, 241, 0.2);
|
||||
/* Line number bg tint for commented lines */
|
||||
.monaco-comment-line-number {
|
||||
background-color: rgba(99, 102, 241, 0.12) !important;
|
||||
}
|
||||
|
||||
/* TipTap Plan Editor Styles */
|
||||
@@ -930,21 +943,53 @@
|
||||
color: oklch(0.65 0.2 20);
|
||||
}
|
||||
|
||||
/* Monaco Editor - Diff gutter indicators */
|
||||
/* Monaco Editor - Diff gutter indicators (colors from --git-addition / --git-deletion CSS vars) */
|
||||
.monaco-diff-added-gutter {
|
||||
width: 3px !important;
|
||||
margin-left: 3px;
|
||||
background-color: #10b981 !important;
|
||||
background-color: rgb(var(--git-addition)) !important;
|
||||
}
|
||||
.monaco-diff-modified-gutter {
|
||||
width: 3px !important;
|
||||
margin-left: 3px;
|
||||
background-color: #3b82f6 !important;
|
||||
background-color: rgb(var(--git-addition)) !important;
|
||||
}
|
||||
.monaco-diff-deleted-gutter {
|
||||
width: 0 !important;
|
||||
margin-left: 2px;
|
||||
border-left: 4px solid #f43f5e !important;
|
||||
border-left: 4px solid rgb(var(--git-deletion)) !important;
|
||||
}
|
||||
|
||||
/* Monaco Editor - Gutter comment hint ("+" hover on decoration lane) */
|
||||
.monaco-gutter-comment-hint {
|
||||
cursor: pointer !important;
|
||||
position: relative !important;
|
||||
}
|
||||
.monaco-gutter-comment-hint::after {
|
||||
content: '+';
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
color: #fff;
|
||||
border-radius: 3px;
|
||||
background-color: rgb(99 102 241); /* indigo-500 */
|
||||
}
|
||||
|
||||
/* Monaco Editor - Gutter line selection highlight */
|
||||
.monaco-gutter-selected-line {
|
||||
background-color: rgb(139 92 246 / 0.15) !important;
|
||||
}
|
||||
.monaco-gutter-selected-deco {
|
||||
background-color: rgb(139 92 246 / 0.15) !important;
|
||||
}
|
||||
|
||||
/* Monaco Editor - Peek view / references widget overrides */
|
||||
|
||||
@@ -8,6 +8,7 @@ import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
import { CommandRegistryProvider } from "@/lib/commands/command-registry";
|
||||
import { CommandPanel } from "@/components/command-panel";
|
||||
import { GlobalCommands } from "@/components/global-commands";
|
||||
import { DiffWorkerPoolProvider } from "@/components/diff-worker-pool-provider";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Kandev - AI Kanban",
|
||||
@@ -67,6 +68,7 @@ export default function RootLayout({
|
||||
) : null}
|
||||
<StateProvider>
|
||||
<ThemeProvider>
|
||||
<DiffWorkerPoolProvider>
|
||||
<TooltipProvider>
|
||||
<ToastProvider>
|
||||
<CommandRegistryProvider>
|
||||
@@ -77,6 +79,7 @@ export default function RootLayout({
|
||||
</CommandRegistryProvider>
|
||||
</ToastProvider>
|
||||
</TooltipProvider>
|
||||
</DiffWorkerPoolProvider>
|
||||
</ThemeProvider>
|
||||
</StateProvider>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
'use client';
|
||||
|
||||
import { type ReactNode, useEffect } from 'react';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from '@pierre/diffs/react';
|
||||
import { PIERRE_THEME } from '@/lib/theme/colors';
|
||||
|
||||
const LANGS = [
|
||||
'javascript', 'typescript', 'jsx', 'tsx', 'json', 'css', 'html',
|
||||
'markdown', 'python', 'go', 'rust', 'java', 'yaml', 'toml', 'bash', 'sql',
|
||||
] as const;
|
||||
|
||||
const workerFactory = () =>
|
||||
new Worker(new URL('@pierre/diffs/worker/worker.js', import.meta.url), { type: 'module' });
|
||||
|
||||
function ThemeSync() {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const pool = useWorkerPool();
|
||||
useEffect(() => {
|
||||
pool?.setRenderOptions({
|
||||
theme: resolvedTheme === 'dark' ? PIERRE_THEME.dark : PIERRE_THEME.light,
|
||||
});
|
||||
}, [pool, resolvedTheme]);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<WorkerPoolContextProvider
|
||||
poolOptions={{ workerFactory, poolSize: 4 }}
|
||||
highlighterOptions={{
|
||||
langs: [...LANGS],
|
||||
theme: PIERRE_THEME.dark,
|
||||
lineDiffType: 'word',
|
||||
}}
|
||||
>
|
||||
<ThemeSync />
|
||||
{children}
|
||||
</WorkerPoolContextProvider>
|
||||
);
|
||||
}
|
||||
@@ -29,23 +29,38 @@ export function CommentDisplay({
|
||||
|
||||
if (compact) {
|
||||
return (
|
||||
<div className="group flex items-start gap-2 rounded border border-border bg-muted/50 px-2 py-1.5 text-xs">
|
||||
<div
|
||||
className={`group flex items-start gap-2 rounded border border-border bg-muted/50 px-2 py-1.5 text-xs${onEdit ? ' cursor-pointer hover:bg-muted/80' : ''}`}
|
||||
onClick={onEdit}
|
||||
>
|
||||
<IconMessage className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-muted-foreground">{lineRange}</span>
|
||||
<span className="mx-1 text-muted-foreground">·</span>
|
||||
<span className="break-words">{comment.annotation}</span>
|
||||
</div>
|
||||
{onDelete && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onDelete}
|
||||
className="h-4 w-4 shrink-0 cursor-pointer p-0 opacity-0 hover:text-destructive group-hover:opacity-100"
|
||||
>
|
||||
<IconTrash className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex shrink-0 gap-0.5 opacity-0 group-hover:opacity-100">
|
||||
{onEdit && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => { e.stopPropagation(); onEdit(); }}
|
||||
className="h-4 w-4 cursor-pointer p-0"
|
||||
>
|
||||
<IconEdit className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
{onDelete && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={(e) => { e.stopPropagation(); onDelete(); }}
|
||||
className="h-4 w-4 cursor-pointer p-0 hover:text-destructive"
|
||||
>
|
||||
<IconTrash className="h-3 w-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, type ReactNode } from 'react';
|
||||
import { cn } from '@kandev/ui/lib/utils';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from '@kandev/ui/tooltip';
|
||||
import { IconCopy, IconTextWrap, IconLayoutRows, IconLayoutColumns, IconPencil, IconArrowBackUp } from '@tabler/icons-react';
|
||||
import type { RenderHeaderMetadataProps } from '@pierre/diffs';
|
||||
import type { ViewMode } from '@/hooks/use-global-view-mode';
|
||||
|
||||
interface DiffHeaderToolbarOptions {
|
||||
filePath: string;
|
||||
diff?: string;
|
||||
wordWrap: boolean;
|
||||
onToggleWordWrap: () => void;
|
||||
viewMode: ViewMode;
|
||||
onToggleViewMode: () => void;
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
onRevert?: (filePath: string) => void;
|
||||
}
|
||||
|
||||
export function useDiffHeaderToolbar({
|
||||
filePath,
|
||||
diff,
|
||||
wordWrap,
|
||||
onToggleWordWrap,
|
||||
viewMode,
|
||||
onToggleViewMode,
|
||||
onOpenFile,
|
||||
onRevert,
|
||||
}: DiffHeaderToolbarOptions) {
|
||||
const renderHeaderMetadata = useCallback(
|
||||
(props: RenderHeaderMetadataProps): ReactNode => {
|
||||
const resolvedPath = props.fileDiff?.name || filePath;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => navigator.clipboard.writeText(diff || '')}
|
||||
>
|
||||
<IconCopy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Copy diff</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{onRevert && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => onRevert(resolvedPath)}
|
||||
>
|
||||
<IconArrowBackUp className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Revert changes</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
'h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100',
|
||||
wordWrap && 'opacity-100 bg-muted'
|
||||
)}
|
||||
onClick={onToggleWordWrap}
|
||||
>
|
||||
<IconTextWrap className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Toggle word wrap</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={onToggleViewMode}
|
||||
>
|
||||
{viewMode === 'split' ? (
|
||||
<IconLayoutRows className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<IconLayoutColumns className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{viewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{onOpenFile && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => onOpenFile(resolvedPath)}
|
||||
>
|
||||
<IconPencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
[filePath, diff, wordWrap, onToggleWordWrap, viewMode, onToggleViewMode, onOpenFile, onRevert]
|
||||
);
|
||||
|
||||
return renderHeaderMetadata;
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import { useEditorProvider } from '@/hooks/use-editor-resolver';
|
||||
import { DiffViewer as PierreDiffViewer, DiffViewInline as PierreDiffViewInline } from './diff-viewer';
|
||||
import { MonacoDiffViewer } from '@/components/editors/monaco/monaco-diff-viewer';
|
||||
import type { FileDiffData, DiffComment } from '@/lib/diff/types';
|
||||
import type { RevertBlockInfo } from './diff-viewer';
|
||||
export type { RevertBlockInfo };
|
||||
|
||||
interface DiffViewerResolverProps {
|
||||
data: FileDiffData;
|
||||
@@ -18,7 +20,11 @@ interface DiffViewerResolverProps {
|
||||
hideHeader?: boolean;
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
onRevert?: (filePath: string) => void;
|
||||
enableAcceptReject?: boolean;
|
||||
onRevertBlock?: (filePath: string, info: RevertBlockInfo) => void;
|
||||
wordWrap?: boolean;
|
||||
editable?: boolean;
|
||||
onModifiedContentChange?: (filePath: string, content: string) => void;
|
||||
}
|
||||
|
||||
export const DiffViewerResolved = memo(function DiffViewerResolved(props: DiffViewerResolverProps) {
|
||||
|
||||
@@ -1,27 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback, useMemo, memo, useSyncExternalStore, type ReactNode } from 'react';
|
||||
import { useState, useCallback, useEffect, useMemo, useRef, memo, type ReactNode } from 'react';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { FileDiff } from '@pierre/diffs/react';
|
||||
import { parsePatchFiles, parseDiffFromFile } from '@pierre/diffs';
|
||||
import type { FileDiffOptions, FileDiffMetadata, DiffLineAnnotation, RenderHeaderMetadataProps, AnnotationSide, SelectedLineRange } from '@pierre/diffs';
|
||||
import type { FileDiffOptions, FileDiffMetadata, DiffLineAnnotation, AnnotationSide, SelectedLineRange } from '@pierre/diffs';
|
||||
import { cn } from '@kandev/ui/lib/utils';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from '@kandev/ui/tooltip';
|
||||
import { IconCopy, IconTextWrap, IconLayoutRows, IconLayoutColumns, IconPencil, IconPlus, IconArrowBackUp } from '@tabler/icons-react';
|
||||
import { IconPlus } from '@tabler/icons-react';
|
||||
import type { FileDiffData, DiffComment } from '@/lib/diff/types';
|
||||
import { buildDiffComment, useCommentActions } from '@/lib/diff/comment-utils';
|
||||
import { FONT } from '@/lib/theme/colors';
|
||||
import { useGlobalViewMode } from '@/hooks/use-global-view-mode';
|
||||
import { useDiffComments } from './use-diff-comments';
|
||||
import { CommentForm } from './comment-form';
|
||||
import { CommentDisplay } from './comment-display';
|
||||
import { useDiffHeaderToolbar } from './diff-header-toolbar';
|
||||
import { HunkActionBar } from './hunk-action-bar';
|
||||
|
||||
/**
|
||||
* Check if Go code contains patterns that trigger catastrophic regex backtracking
|
||||
* in shiki's JavaScript regex engine.
|
||||
*
|
||||
* Bug: The Go TextMate grammar has a regex pattern that causes O(2^n) backtracking
|
||||
* when struct fields contain `interface{}` with struct tags like `json:"..."`.
|
||||
*
|
||||
* See: https://github.com/shikijs/textmate-grammars-themes/pull/183
|
||||
*/
|
||||
function hasProblematicGoPattern(content: string | undefined): boolean {
|
||||
if (!content) return false;
|
||||
@@ -29,103 +27,59 @@ function hasProblematicGoPattern(content: string | undefined): boolean {
|
||||
return problematicPattern.test(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is a Go file based on extension
|
||||
*/
|
||||
function isGoFile(filePath: string): boolean {
|
||||
return filePath.endsWith('.go');
|
||||
}
|
||||
|
||||
// Local storage key for global diff view mode
|
||||
const DIFF_VIEW_MODE_KEY = 'diff-view-mode';
|
||||
const DEFAULT_VIEW_MODE = 'unified' as const;
|
||||
|
||||
// Custom event for syncing view mode across components
|
||||
const VIEW_MODE_CHANGE_EVENT = 'diff-view-mode-change';
|
||||
|
||||
type ViewMode = 'split' | 'unified';
|
||||
|
||||
// Helper to get view mode from localStorage
|
||||
function getStoredViewMode(): ViewMode {
|
||||
if (typeof window === 'undefined') return DEFAULT_VIEW_MODE;
|
||||
const stored = localStorage.getItem(DIFF_VIEW_MODE_KEY);
|
||||
return stored === 'split' || stored === 'unified' ? stored : DEFAULT_VIEW_MODE;
|
||||
}
|
||||
|
||||
// Helper to set view mode in localStorage and dispatch event
|
||||
function setStoredViewMode(mode: ViewMode): void {
|
||||
localStorage.setItem(DIFF_VIEW_MODE_KEY, mode);
|
||||
window.dispatchEvent(new CustomEvent(VIEW_MODE_CHANGE_EVENT, { detail: mode }));
|
||||
}
|
||||
|
||||
// Hook to subscribe to global view mode changes
|
||||
function useGlobalViewMode(): [ViewMode, (mode: ViewMode) => void] {
|
||||
const subscribe = useCallback((callback: () => void) => {
|
||||
window.addEventListener(VIEW_MODE_CHANGE_EVENT, callback);
|
||||
window.addEventListener('storage', callback);
|
||||
return () => {
|
||||
window.removeEventListener(VIEW_MODE_CHANGE_EVENT, callback);
|
||||
window.removeEventListener('storage', callback);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const getSnapshot = useCallback(() => getStoredViewMode(), []);
|
||||
const getServerSnapshot = useCallback(() => DEFAULT_VIEW_MODE, []);
|
||||
|
||||
const viewMode = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
|
||||
return [viewMode, setStoredViewMode];
|
||||
}
|
||||
export type RevertBlockInfo = {
|
||||
/** 1-based line number in the new file where additions start */
|
||||
addStart: number;
|
||||
/** Number of addition lines to remove (0 for pure deletions) */
|
||||
addCount: number;
|
||||
/** Original lines to restore (empty for pure additions) */
|
||||
oldLines: string[];
|
||||
};
|
||||
|
||||
interface DiffViewerProps {
|
||||
/** Diff data to display */
|
||||
data: FileDiffData;
|
||||
/** Enable line selection for comments */
|
||||
enableComments?: boolean;
|
||||
/** Session ID for comment storage */
|
||||
sessionId?: string;
|
||||
/** Callback when comment is added */
|
||||
onCommentAdd?: (comment: DiffComment) => void;
|
||||
/** Callback when comment is deleted */
|
||||
onCommentDelete?: (commentId: string) => void;
|
||||
/** External comments (controlled mode) */
|
||||
comments?: DiffComment[];
|
||||
/** Additional class name */
|
||||
className?: string;
|
||||
/** Whether to show in compact mode (smaller text, no header) */
|
||||
compact?: boolean;
|
||||
/** Whether to hide the file header and toolbar */
|
||||
hideHeader?: boolean;
|
||||
/** Callback to open file in editor */
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
/** External word wrap override (controlled mode) */
|
||||
onRevert?: (filePath: string) => void;
|
||||
enableAcceptReject?: boolean;
|
||||
onRevertBlock?: (filePath: string, info: RevertBlockInfo) => Promise<void> | void;
|
||||
wordWrap?: boolean;
|
||||
}
|
||||
|
||||
type AnnotationMetadata = {
|
||||
type: 'comment' | 'new-comment-form';
|
||||
type: 'comment' | 'new-comment-form' | 'hunk-actions';
|
||||
comment?: DiffComment;
|
||||
isEditing?: boolean;
|
||||
changeBlockId?: string;
|
||||
};
|
||||
|
||||
// Custom comparison for memo - only re-render if actual content changes
|
||||
function arePropsEqual(prevProps: DiffViewerProps, nextProps: DiffViewerProps): boolean {
|
||||
// Compare data by content, not reference
|
||||
if (prevProps.data.filePath !== nextProps.data.filePath) return false;
|
||||
if (prevProps.data.diff !== nextProps.data.diff) return false;
|
||||
if (prevProps.data.oldContent !== nextProps.data.oldContent) return false;
|
||||
if (prevProps.data.newContent !== nextProps.data.newContent) return false;
|
||||
|
||||
// Compare other props
|
||||
if (prevProps.enableComments !== nextProps.enableComments) return false;
|
||||
if (prevProps.sessionId !== nextProps.sessionId) return false;
|
||||
if (prevProps.compact !== nextProps.compact) return false;
|
||||
if (prevProps.hideHeader !== nextProps.hideHeader) return false;
|
||||
if (prevProps.className !== nextProps.className) return false;
|
||||
if (prevProps.onOpenFile !== nextProps.onOpenFile) return false;
|
||||
if (prevProps.onRevert !== nextProps.onRevert) return false;
|
||||
if (prevProps.enableAcceptReject !== nextProps.enableAcceptReject) return false;
|
||||
if (prevProps.onRevertBlock !== nextProps.onRevertBlock) return false;
|
||||
if (prevProps.wordWrap !== nextProps.wordWrap) return false;
|
||||
|
||||
// Comments array - compare by length and IDs
|
||||
const prevComments = prevProps.comments;
|
||||
const nextComments = nextProps.comments;
|
||||
if (prevComments !== nextComments) {
|
||||
@@ -151,20 +105,20 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
compact = false,
|
||||
hideHeader = false,
|
||||
onOpenFile,
|
||||
onRevert,
|
||||
enableAcceptReject = false,
|
||||
onRevertBlock,
|
||||
wordWrap: wordWrapProp,
|
||||
}: DiffViewerProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const [selectedLines, setSelectedLines] = useState<SelectedLineRange | null>(null);
|
||||
const [showCommentForm, setShowCommentForm] = useState(false);
|
||||
|
||||
// Global view mode (synced via localStorage)
|
||||
const [globalViewMode, setGlobalViewMode] = useGlobalViewMode();
|
||||
|
||||
// Local state for word wrap (per-diff), overridable via prop
|
||||
const [wordWrapLocal, setWordWrap] = useState(false);
|
||||
const wordWrap = wordWrapProp ?? wordWrapLocal;
|
||||
|
||||
// Use internal comment management if sessionId provided
|
||||
const {
|
||||
comments: internalComments,
|
||||
addComment,
|
||||
@@ -182,8 +136,49 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
|
||||
const comments = externalComments || internalComments;
|
||||
|
||||
// Create annotations from comments + new comment form
|
||||
const annotations = useMemo<DiffLineAnnotation<AnnotationMetadata>[]>(() => {
|
||||
// Parse initial diff metadata
|
||||
const initialDiffMetadata = useMemo<FileDiffMetadata | null>(() => {
|
||||
let result: FileDiffMetadata | null = null;
|
||||
if (data.diff) {
|
||||
const parsed = parsePatchFiles(data.diff);
|
||||
result = parsed[0]?.files[0] ?? null;
|
||||
} else if (data.oldContent || data.newContent) {
|
||||
result = parseDiffFromFile(
|
||||
{ name: data.filePath, contents: data.oldContent },
|
||||
{ name: data.filePath, contents: data.newContent }
|
||||
);
|
||||
}
|
||||
|
||||
if (result && isGoFile(data.filePath)) {
|
||||
const contentToCheck = data.newContent || data.oldContent || data.diff;
|
||||
if (hasProblematicGoPattern(contentToCheck)) {
|
||||
result = { ...result, lang: 'text' };
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data.diff, data.oldContent, data.newContent, data.filePath]);
|
||||
|
||||
const fileDiffMetadata = initialDiffMetadata;
|
||||
|
||||
// Per-change-block revert info: changeBlockId → { addStart, addCount, oldLines }
|
||||
const revertInfoRef = useRef<Map<string, RevertBlockInfo>>(new Map());
|
||||
|
||||
const handleRevertBlock = useCallback(
|
||||
async (changeBlockId: string) => {
|
||||
const info = revertInfoRef.current.get(changeBlockId);
|
||||
if (!info) return;
|
||||
await onRevertBlock?.(data.filePath, info);
|
||||
},
|
||||
[data.filePath, onRevertBlock]
|
||||
);
|
||||
|
||||
// Map from "side:lineNumber" → changeBlockId for hover detection
|
||||
const changeLineMapRef = useRef<Map<string, string>>(new Map());
|
||||
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Annotations: comments, new comment form, and hunk accept/reject
|
||||
const { annotations, lineMap, revertMap } = useMemo(() => {
|
||||
const result: DiffLineAnnotation<AnnotationMetadata>[] = comments.map((comment) => ({
|
||||
side: comment.side,
|
||||
lineNumber: comment.endLine,
|
||||
@@ -194,21 +189,73 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
},
|
||||
}));
|
||||
|
||||
// Add new comment form annotation at the selected line
|
||||
if (showCommentForm && selectedLines) {
|
||||
result.push({
|
||||
side: (selectedLines.side || 'additions') as AnnotationSide,
|
||||
lineNumber: Math.max(selectedLines.start, selectedLines.end),
|
||||
metadata: {
|
||||
type: 'new-comment-form' as const,
|
||||
},
|
||||
metadata: { type: 'new-comment-form' as const },
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [comments, editingCommentId, showCommentForm, selectedLines]);
|
||||
// Add undo annotations per change block within each hunk.
|
||||
// Also build a line → changeBlockId mapping for hover detection,
|
||||
// and a changeBlockId → RevertBlockInfo mapping for workspace revert.
|
||||
const newLineMap = new Map<string, string>();
|
||||
const newRevertMap = new Map<string, RevertBlockInfo>();
|
||||
if (enableAcceptReject && fileDiffMetadata) {
|
||||
let blockIdx = 0;
|
||||
for (let hi = 0; hi < fileDiffMetadata.hunks.length; hi++) {
|
||||
const hunk = fileDiffMetadata.hunks[hi];
|
||||
if (hunk.additionCount === 0 && hunk.deletionCount === 0) continue;
|
||||
let addLine = hunk.additionStart;
|
||||
let delLine = hunk.deletionStart;
|
||||
let lastCtxAdd = addLine > 1 ? addLine - 1 : addLine;
|
||||
let lastCtxDel = delLine > 1 ? delLine - 1 : delLine;
|
||||
for (const content of hunk.hunkContent) {
|
||||
if (content.type === 'context') {
|
||||
const len = content.lines.length;
|
||||
lastCtxAdd = addLine + len - 1;
|
||||
lastCtxDel = delLine + len - 1;
|
||||
addLine += len;
|
||||
delLine += len;
|
||||
} else {
|
||||
const aLen = content.additions.length;
|
||||
const dLen = content.deletions.length;
|
||||
if (aLen > 0 || dLen > 0) {
|
||||
const cbId = `cb-${blockIdx++}`;
|
||||
const side: AnnotationSide = aLen > 0 ? 'additions' : 'deletions';
|
||||
const lineNumber = side === 'additions' ? lastCtxAdd : lastCtxDel;
|
||||
result.push({
|
||||
side,
|
||||
lineNumber,
|
||||
metadata: { type: 'hunk-actions', changeBlockId: cbId },
|
||||
});
|
||||
for (let l = 0; l < aLen; l++) newLineMap.set(`additions:${addLine + l}`, cbId);
|
||||
for (let l = 0; l < dLen; l++) newLineMap.set(`deletions:${delLine + l}`, cbId);
|
||||
newRevertMap.set(cbId, {
|
||||
addStart: addLine,
|
||||
addCount: aLen,
|
||||
// Pierre stores lines with trailing \n — strip them since
|
||||
// we splice into an array produced by split('\n')
|
||||
oldLines: content.deletions.map(l => l.replace(/\r?\n$/, '')),
|
||||
});
|
||||
}
|
||||
addLine += aLen;
|
||||
delLine += dLen;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { annotations: result, lineMap: newLineMap, revertMap: newRevertMap };
|
||||
}, [comments, editingCommentId, showCommentForm, selectedLines, enableAcceptReject, fileDiffMetadata]);
|
||||
|
||||
// Sync maps to refs outside of render (avoids react-hooks/refs violation)
|
||||
useEffect(() => {
|
||||
changeLineMapRef.current = lineMap;
|
||||
revertInfoRef.current = revertMap;
|
||||
}, [lineMap, revertMap]);
|
||||
|
||||
// Stable handler for line selection - only fires when selection is complete
|
||||
const handleLineSelectionEnd = useCallback(
|
||||
(range: SelectedLineRange | null) => {
|
||||
setSelectedLines(range);
|
||||
@@ -219,60 +266,105 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
[enableComments]
|
||||
);
|
||||
|
||||
// Handler for comment submission
|
||||
const handleCommentSubmit = useCallback(
|
||||
(content: string) => {
|
||||
if (!selectedLines) return;
|
||||
|
||||
if (onCommentAdd && externalComments !== undefined) {
|
||||
const comment: DiffComment = {
|
||||
id: `${data.filePath}-${Date.now()}`,
|
||||
sessionId: sessionId || '',
|
||||
onCommentAdd(buildDiffComment({
|
||||
filePath: data.filePath,
|
||||
startLine: Math.min(selectedLines.start, selectedLines.end),
|
||||
endLine: Math.max(selectedLines.start, selectedLines.end),
|
||||
sessionId: sessionId || '',
|
||||
startLine: selectedLines.start,
|
||||
endLine: selectedLines.end,
|
||||
side: (selectedLines.side || 'additions') as DiffComment['side'],
|
||||
codeContent: '',
|
||||
annotation: content,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'pending',
|
||||
};
|
||||
onCommentAdd(comment);
|
||||
}));
|
||||
} else if (sessionId) {
|
||||
addComment(selectedLines, content);
|
||||
}
|
||||
|
||||
setShowCommentForm(false);
|
||||
setSelectedLines(null);
|
||||
},
|
||||
[selectedLines, sessionId, data.filePath, addComment, onCommentAdd, externalComments]
|
||||
);
|
||||
|
||||
// Handler for comment deletion
|
||||
const handleCommentDelete = useCallback(
|
||||
(commentId: string) => {
|
||||
if (onCommentDelete && externalComments !== undefined) {
|
||||
onCommentDelete(commentId);
|
||||
} else {
|
||||
removeComment(commentId);
|
||||
}
|
||||
},
|
||||
[removeComment, onCommentDelete, externalComments]
|
||||
);
|
||||
const { handleCommentDelete, handleCommentUpdate } = useCommentActions({
|
||||
removeComment, updateComment, setEditingComment,
|
||||
onCommentDelete, externalComments,
|
||||
});
|
||||
|
||||
// Handle comment update
|
||||
const handleCommentUpdate = useCallback(
|
||||
(commentId: string, content: string) => {
|
||||
updateComment(commentId, { annotation: content });
|
||||
setEditingComment(null);
|
||||
},
|
||||
[updateComment, setEditingComment]
|
||||
);
|
||||
// Show/hide undo buttons when hovering change lines (direct DOM, no re-renders)
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const activeBlockRef = useRef<string | null>(null);
|
||||
const isHoveringButtonRef = useRef(false);
|
||||
|
||||
const setBlockVisible = useCallback((cbId: string | null, visible: boolean) => {
|
||||
if (!cbId) return;
|
||||
const btn = wrapperRef.current?.querySelector(`[data-cb="${cbId}"] [data-undo-btn]`);
|
||||
if (btn instanceof HTMLElement) {
|
||||
btn.style.opacity = visible ? '1' : '0';
|
||||
btn.style.pointerEvents = visible ? 'auto' : 'none';
|
||||
}
|
||||
}, []);
|
||||
|
||||
const showBlock = useCallback((cbId: string) => {
|
||||
if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); hideTimeoutRef.current = null; }
|
||||
if (activeBlockRef.current === cbId) return;
|
||||
setBlockVisible(activeBlockRef.current, false);
|
||||
activeBlockRef.current = cbId;
|
||||
setBlockVisible(cbId, true);
|
||||
}, [setBlockVisible]);
|
||||
|
||||
const hideBlock = useCallback(() => {
|
||||
if (hideTimeoutRef.current) clearTimeout(hideTimeoutRef.current);
|
||||
hideTimeoutRef.current = setTimeout(() => {
|
||||
if (isHoveringButtonRef.current) return; // Don't hide while mouse is on the button
|
||||
setBlockVisible(activeBlockRef.current, false);
|
||||
activeBlockRef.current = null;
|
||||
}, 200);
|
||||
}, [setBlockVisible]);
|
||||
|
||||
const onButtonEnter = useCallback(() => {
|
||||
isHoveringButtonRef.current = true;
|
||||
if (hideTimeoutRef.current) { clearTimeout(hideTimeoutRef.current); hideTimeoutRef.current = null; }
|
||||
}, []);
|
||||
|
||||
const onButtonLeave = useCallback(() => {
|
||||
isHoveringButtonRef.current = false;
|
||||
hideBlock();
|
||||
}, [hideBlock]);
|
||||
|
||||
const showBlockRef = useRef(showBlock);
|
||||
const hideBlockRef = useRef(hideBlock);
|
||||
useEffect(() => { showBlockRef.current = showBlock; }, [showBlock]);
|
||||
useEffect(() => { hideBlockRef.current = hideBlock; }, [hideBlock]);
|
||||
|
||||
const onLineEnter = useCallback((props: { lineType?: string; lineNumber?: number; annotationSide?: string }) => {
|
||||
const { lineType, lineNumber, annotationSide } = props;
|
||||
if (!lineType?.startsWith('change-') || lineNumber == null) { hideBlockRef.current(); return; }
|
||||
const side = lineType === 'change-deletion' ? 'deletions' : 'additions';
|
||||
const key = `${annotationSide ?? side}:${lineNumber}`;
|
||||
const cbId = changeLineMapRef.current.get(key);
|
||||
if (cbId) showBlockRef.current(cbId);
|
||||
else hideBlockRef.current();
|
||||
}, []);
|
||||
|
||||
const onLineLeave = useCallback(() => { hideBlockRef.current(); }, []);
|
||||
|
||||
// Render annotation callback
|
||||
const renderAnnotation = useCallback(
|
||||
(annotation: DiffLineAnnotation<AnnotationMetadata>): ReactNode => {
|
||||
const { type, comment, isEditing } = annotation.metadata;
|
||||
const { type, comment, isEditing, changeBlockId } = annotation.metadata;
|
||||
|
||||
if (type === 'hunk-actions' && changeBlockId) {
|
||||
return (
|
||||
<HunkActionBar
|
||||
key={changeBlockId}
|
||||
changeBlockId={changeBlockId}
|
||||
onRevert={() => handleRevertBlock(changeBlockId)}
|
||||
onMouseEnter={onButtonEnter}
|
||||
onMouseLeave={onButtonLeave}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (type === 'new-comment-form') {
|
||||
return (
|
||||
@@ -316,115 +408,33 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
|
||||
return null;
|
||||
},
|
||||
[setEditingComment, handleCommentDelete, handleCommentUpdate, handleCommentSubmit]
|
||||
[setEditingComment, handleCommentDelete, handleCommentUpdate, handleCommentSubmit, handleRevertBlock, onButtonEnter, onButtonLeave]
|
||||
);
|
||||
|
||||
// Render header metadata toolbar for each diff file
|
||||
const renderHeaderMetadata = useCallback(
|
||||
(props: RenderHeaderMetadataProps): ReactNode => {
|
||||
const filePath = props.fileDiff?.name || data.filePath;
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Copy diff button */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => navigator.clipboard.writeText(data.diff || '')}
|
||||
>
|
||||
<IconCopy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Copy diff</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{/* Revert button (non-functional placeholder) */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => {
|
||||
// TODO: Implement revert functionality
|
||||
}}
|
||||
>
|
||||
<IconArrowBackUp className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Revert changes</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{/* Word wrap toggle */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(
|
||||
'h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100',
|
||||
wordWrap && 'opacity-100 bg-muted'
|
||||
)}
|
||||
onClick={() => setWordWrap(!wordWrap)}
|
||||
>
|
||||
<IconTextWrap className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Toggle word wrap</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{/* Split/Unified toggle (global) */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => setGlobalViewMode(globalViewMode === 'split' ? 'unified' : 'split')}
|
||||
>
|
||||
{globalViewMode === 'split' ? (
|
||||
<IconLayoutRows className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<IconLayoutColumns className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{globalViewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
{/* Open in editor button */}
|
||||
{onOpenFile && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => onOpenFile(filePath)}
|
||||
>
|
||||
<IconPencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
[data.filePath, data.diff, wordWrap, globalViewMode, setGlobalViewMode, onOpenFile]
|
||||
const toggleViewMode = useCallback(
|
||||
() => setGlobalViewMode(globalViewMode === 'split' ? 'unified' : 'split'),
|
||||
[globalViewMode, setGlobalViewMode]
|
||||
);
|
||||
|
||||
// Render hover utility (+) icon for adding comments
|
||||
const toggleWordWrap = useCallback(
|
||||
() => setWordWrap((v) => !v),
|
||||
[]
|
||||
);
|
||||
|
||||
const renderHeaderMetadata = useDiffHeaderToolbar({
|
||||
filePath: data.filePath,
|
||||
diff: data.diff,
|
||||
wordWrap,
|
||||
onToggleWordWrap: toggleWordWrap,
|
||||
viewMode: globalViewMode,
|
||||
onToggleViewMode: toggleViewMode,
|
||||
onOpenFile,
|
||||
onRevert,
|
||||
});
|
||||
|
||||
const renderHoverUtility = useCallback(
|
||||
(): ReactNode => {
|
||||
// Only show when comments are enabled
|
||||
if (!enableComments) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex h-5 w-5 cursor-pointer items-center justify-center rounded border border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
@@ -437,74 +447,50 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
[enableComments]
|
||||
);
|
||||
|
||||
// Determine if header/toolbar should be shown
|
||||
const showHeader = !hideHeader && !compact;
|
||||
|
||||
const options = useMemo<FileDiffOptions<AnnotationMetadata>>(
|
||||
() => ({
|
||||
diffStyle: globalViewMode,
|
||||
themeType: resolvedTheme === 'dark' ? 'dark' : 'light',
|
||||
theme: {
|
||||
dark: 'github-dark-high-contrast',
|
||||
light: 'github-light',
|
||||
},
|
||||
enableLineSelection: enableComments,
|
||||
hunkSeparators: 'simple',
|
||||
enableHoverUtility: enableComments,
|
||||
diffIndicators: 'none',
|
||||
onLineSelectionEnd: handleLineSelectionEnd,
|
||||
onLineEnter,
|
||||
onLineLeave,
|
||||
disableFileHeader: !showHeader,
|
||||
lineDiffType: 'word',
|
||||
overflow: wordWrap ? 'wrap' : 'scroll',
|
||||
unsafeCSS: `
|
||||
/* Make container backgrounds transparent, but NOT diff line backgrounds
|
||||
* Only target the root container and specific UI elements, not the diff content itself */
|
||||
[data-diffs-root] {
|
||||
background: transparent !important;
|
||||
/* Override Pierre's inline theme — both CSS vars AND direct background-color */
|
||||
pre[data-diffs] {
|
||||
background-color: var(--background) !important;
|
||||
--diffs-bg: var(--background) !important;
|
||||
--diffs-bg-context: var(--background) !important;
|
||||
--diffs-bg-buffer: var(--background) !important;
|
||||
--diffs-bg-separator: var(--card) !important;
|
||||
--diffs-bg-hover: var(--muted) !important;
|
||||
--diffs-fg: var(--foreground) !important;
|
||||
--diffs-fg-number: var(--muted-foreground) !important;
|
||||
--diffs-addition-color-override: rgb(var(--git-addition)) !important;
|
||||
--diffs-deletion-color-override: rgb(var(--git-deletion)) !important;
|
||||
--diffs-font-size: ${FONT.size}px !important;
|
||||
--diffs-font-family: ${FONT.mono} !important;
|
||||
}
|
||||
|
||||
/* Reduce icon size */
|
||||
[data-change-icon] {
|
||||
width: 12px !important;
|
||||
height: 12px !important;
|
||||
}
|
||||
|
||||
/* Adjust header padding */
|
||||
[data-diffs-header] {
|
||||
padding-inline: 12px !important;
|
||||
background: var(--card) !important;
|
||||
}
|
||||
`,
|
||||
}),
|
||||
[globalViewMode, resolvedTheme, enableComments, showHeader, handleLineSelectionEnd, wordWrap]
|
||||
[globalViewMode, resolvedTheme, enableComments, showHeader, handleLineSelectionEnd, wordWrap, onLineEnter, onLineLeave]
|
||||
);
|
||||
|
||||
// Compute FileDiffMetadata from either diff string or content
|
||||
const fileDiffMetadata = useMemo<FileDiffMetadata | null>(() => {
|
||||
let result: FileDiffMetadata | null = null;
|
||||
if (data.diff) {
|
||||
const parsed = parsePatchFiles(data.diff);
|
||||
result = parsed[0]?.files[0] ?? null;
|
||||
} else if (data.oldContent || data.newContent) {
|
||||
result = parseDiffFromFile(
|
||||
{ name: data.filePath, contents: data.oldContent },
|
||||
{ name: data.filePath, contents: data.newContent }
|
||||
);
|
||||
}
|
||||
|
||||
// Fix for shiki Go grammar catastrophic backtracking bug (PR #183)
|
||||
// Disable syntax highlighting for Go files with interface{} + struct tags
|
||||
if (result && isGoFile(data.filePath)) {
|
||||
const contentToCheck = data.newContent || data.oldContent || data.diff;
|
||||
if (hasProblematicGoPattern(contentToCheck)) {
|
||||
result = { ...result, lang: 'text' };
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data.diff, data.oldContent, data.newContent, data.filePath]);
|
||||
|
||||
// Only pass selectedLines when we have a completed selection (form shown)
|
||||
// During drag, let FileDiff manage its own internal state
|
||||
const controlledSelection = showCommentForm ? selectedLines : null;
|
||||
|
||||
if (!fileDiffMetadata) {
|
||||
@@ -520,7 +506,7 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('diff-viewer relative', className)}>
|
||||
<div ref={wrapperRef} className={cn('diff-viewer', className)}>
|
||||
<FileDiff
|
||||
fileDiff={fileDiffMetadata}
|
||||
options={options}
|
||||
@@ -529,11 +515,6 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
renderAnnotation={renderAnnotation}
|
||||
renderHeaderMetadata={showHeader ? renderHeaderMetadata : undefined}
|
||||
renderHoverUtility={renderHoverUtility}
|
||||
style={{
|
||||
'--diffs-addition-color-override': 'rgb(var(--git-addition))',
|
||||
'--diffs-deletion-color-override': 'rgb(var(--git-deletion))',
|
||||
'--diffs-font-size': '12px',
|
||||
} as React.CSSProperties}
|
||||
className={cn(
|
||||
'rounded-md border border-border/50',
|
||||
compact && 'text-xs'
|
||||
@@ -543,11 +524,7 @@ export const DiffViewer = memo(function DiffViewer({
|
||||
);
|
||||
}, arePropsEqual);
|
||||
|
||||
/**
|
||||
* Compact inline diff viewer for chat messages.
|
||||
* This is a convenience wrapper around DiffViewer with compact defaults.
|
||||
* @deprecated Use DiffViewer with compact={true} instead
|
||||
*/
|
||||
/** Compact inline diff viewer for chat messages (Pierre implementation). */
|
||||
export function DiffViewInline({
|
||||
data,
|
||||
className,
|
||||
|
||||
@@ -4,33 +4,24 @@ import { memo, useMemo } from 'react';
|
||||
import { DiffViewerResolved as DiffViewer } from './diff-viewer-resolver';
|
||||
import { transformGitDiff } from '@/lib/diff';
|
||||
import type { DiffComment } from '@/lib/diff/types';
|
||||
import type { RevertBlockInfo } from './diff-viewer-resolver';
|
||||
|
||||
interface FileDiffViewerProps {
|
||||
/** File path */
|
||||
filePath: string;
|
||||
/** Raw diff content */
|
||||
diff: string;
|
||||
/** File status (M, A, D, etc.) */
|
||||
status?: string;
|
||||
/** Enable line selection for comments */
|
||||
enableComments?: boolean;
|
||||
/** Session ID for comment storage */
|
||||
sessionId?: string;
|
||||
/** Callback when comment is added */
|
||||
onCommentAdd?: (comment: DiffComment) => void;
|
||||
/** Callback when comment is deleted */
|
||||
onCommentDelete?: (commentId: string) => void;
|
||||
/** External comments (controlled mode) */
|
||||
comments?: DiffComment[];
|
||||
/** Additional class name */
|
||||
className?: string;
|
||||
/** Whether to show in compact mode */
|
||||
compact?: boolean;
|
||||
/** Whether to hide the file header */
|
||||
hideHeader?: boolean;
|
||||
/** Callback to open file in editor */
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
/** External word wrap override */
|
||||
onRevert?: (filePath: string) => void;
|
||||
enableAcceptReject?: boolean;
|
||||
onRevertBlock?: (filePath: string, info: RevertBlockInfo) => void;
|
||||
wordWrap?: boolean;
|
||||
}
|
||||
|
||||
@@ -56,9 +47,11 @@ export const FileDiffViewer = memo(function FileDiffViewer({
|
||||
compact,
|
||||
hideHeader,
|
||||
onOpenFile,
|
||||
onRevert,
|
||||
enableAcceptReject,
|
||||
onRevertBlock,
|
||||
wordWrap,
|
||||
}: FileDiffViewerProps) {
|
||||
// Memoize the transformation - only recalculates when raw data changes
|
||||
const data = useMemo(
|
||||
() => transformGitDiff(filePath, diff, status),
|
||||
[filePath, diff, status]
|
||||
@@ -76,6 +69,9 @@ export const FileDiffViewer = memo(function FileDiffViewer({
|
||||
compact={compact}
|
||||
hideHeader={hideHeader}
|
||||
onOpenFile={onOpenFile}
|
||||
onRevert={onRevert}
|
||||
enableAcceptReject={enableAcceptReject}
|
||||
onRevertBlock={onRevertBlock}
|
||||
wordWrap={wordWrap}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { IconArrowBackUp, IconLoader2 } from '@tabler/icons-react';
|
||||
|
||||
interface HunkActionBarProps {
|
||||
changeBlockId: string;
|
||||
onRevert: () => Promise<void> | void;
|
||||
onMouseEnter: () => void;
|
||||
onMouseLeave: () => void;
|
||||
}
|
||||
|
||||
export function HunkActionBar({ changeBlockId, onRevert, onMouseEnter, onMouseLeave }: HunkActionBarProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleClick = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await onRevert();
|
||||
// Don't setLoading(false) on success — the diff will re-render
|
||||
// and unmount this component when the git status refreshes
|
||||
} catch {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
data-cb={changeBlockId}
|
||||
style={{
|
||||
position: 'relative',
|
||||
zIndex: 10,
|
||||
width: '100%',
|
||||
overflow: 'visible',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
data-undo-btn=""
|
||||
style={{ opacity: 0, pointerEvents: 'none', transition: 'opacity 150ms' }}
|
||||
className="absolute top-1 right-2"
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
className="h-6 gap-1 px-2 text-xs cursor-pointer rounded border border-border/60 bg-background text-muted-foreground shadow-sm hover:text-red-500 hover:bg-red-500/10 hover:border-red-500/30"
|
||||
onClick={handleClick}
|
||||
>
|
||||
{loading
|
||||
? <IconLoader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
: <IconArrowBackUp className="h-3.5 w-3.5" />}
|
||||
Undo
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
export { DiffViewerResolved as DiffViewer } from './diff-viewer-resolver';
|
||||
export { DiffViewInlineResolved as DiffViewInline } from './diff-viewer-resolver';
|
||||
export { FileDiffViewer } from './file-diff-viewer';
|
||||
export type { RevertBlockInfo } from './diff-viewer-resolver';
|
||||
export { CommentForm } from './comment-form';
|
||||
export { CommentDisplay } from './comment-display';
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
'use client';
|
||||
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
|
||||
import {
|
||||
IconLoader2,
|
||||
IconPlugConnected,
|
||||
IconPlugOff,
|
||||
IconAlertTriangle,
|
||||
} from '@tabler/icons-react';
|
||||
import type { LspStatus } from '@/lib/lsp/lsp-client-manager';
|
||||
|
||||
type StaticConfig = { tooltip: string; clickable: boolean };
|
||||
|
||||
const ICON_CLS = 'h-3.5 w-3.5';
|
||||
|
||||
const ICONS: Record<string, React.ReactNode> = {
|
||||
disabled: <IconPlugOff className={`${ICON_CLS} text-muted-foreground/50`} />,
|
||||
connecting: <IconLoader2 className={`${ICON_CLS} animate-spin text-muted-foreground`} />,
|
||||
installing: <IconLoader2 className={`${ICON_CLS} animate-spin text-amber-500`} />,
|
||||
starting: <IconLoader2 className={`${ICON_CLS} animate-spin text-blue-500`} />,
|
||||
ready: <IconPlugConnected className={`${ICON_CLS} text-emerald-500`} />,
|
||||
stopping: <IconLoader2 className={`${ICON_CLS} animate-spin text-muted-foreground`} />,
|
||||
unavailable: <IconPlugOff className={`${ICON_CLS} text-muted-foreground`} />,
|
||||
error: <IconAlertTriangle className={`${ICON_CLS} text-yellow-500`} />,
|
||||
};
|
||||
|
||||
const STATIC_CONFIGS: Record<string, StaticConfig> = {
|
||||
disabled: { tooltip: 'LSP: Off \u2014 click to start', clickable: true },
|
||||
connecting: { tooltip: 'LSP: Connecting...', clickable: true },
|
||||
installing: { tooltip: 'LSP: Installing language server...', clickable: false },
|
||||
starting: { tooltip: 'LSP: Starting language server...', clickable: true },
|
||||
ready: { tooltip: 'LSP: Connected \u2014 click to stop', clickable: true },
|
||||
stopping: { tooltip: 'LSP: Stopping...', clickable: false },
|
||||
};
|
||||
|
||||
function getConfig(status: LspStatus): { icon: React.ReactNode; tooltip: string; clickable: boolean } | null {
|
||||
const icon = ICONS[status.state];
|
||||
if (!icon) return null;
|
||||
|
||||
const sc = STATIC_CONFIGS[status.state];
|
||||
if (sc) return { icon, ...sc };
|
||||
|
||||
// Dynamic tooltip for unavailable/error states
|
||||
const reason = 'reason' in status ? status.reason : null;
|
||||
if (status.state === 'unavailable') return { icon, tooltip: `LSP: ${reason ?? 'Unavailable'}`, clickable: true };
|
||||
if (status.state === 'error') return { icon, tooltip: `LSP: ${reason ?? 'Error'}`, clickable: true };
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function LspStatusButton({
|
||||
status,
|
||||
lspLanguage,
|
||||
onToggle,
|
||||
}: {
|
||||
status: LspStatus;
|
||||
lspLanguage: string | null;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
if (!lspLanguage) return null;
|
||||
|
||||
const c = getConfig(status);
|
||||
if (!c) return null;
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer"
|
||||
onClick={c.clickable ? onToggle : undefined}
|
||||
disabled={!c.clickable}
|
||||
>
|
||||
{c.icon}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{c.tooltip}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
export type ContextMenuState = {
|
||||
x: number;
|
||||
y: number;
|
||||
lineNumber: number;
|
||||
side: 'original' | 'modified';
|
||||
isChangedLine: boolean;
|
||||
lineContent: string;
|
||||
} | null;
|
||||
|
||||
interface DiffViewerContextMenuProps {
|
||||
contextMenu: NonNullable<ContextMenuState>;
|
||||
onCopyAllChanged: () => void;
|
||||
onClose: () => void;
|
||||
onRevert?: (filePath: string) => void;
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
// Matches shadcn ContextMenuContent / ContextMenuItem class names.
|
||||
// We can't use the full Radix ContextMenu tree because the menu is opened
|
||||
// programmatically from Monaco's onContextMenu event at arbitrary coordinates.
|
||||
const menuCls = 'fixed z-50 min-w-32 rounded-lg border bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 p-1';
|
||||
const itemCls = 'flex w-full cursor-default select-none items-center gap-2 rounded-md px-2 py-1 text-xs outline-hidden focus:bg-accent focus:text-accent-foreground hover:bg-accent hover:text-accent-foreground';
|
||||
const separatorCls = 'bg-border/50 -mx-1 my-1 h-px';
|
||||
|
||||
export function DiffViewerContextMenu({
|
||||
contextMenu,
|
||||
onCopyAllChanged,
|
||||
onClose,
|
||||
onRevert,
|
||||
filePath,
|
||||
}: DiffViewerContextMenuProps) {
|
||||
return (
|
||||
<div
|
||||
role="menu"
|
||||
className={menuCls}
|
||||
style={{ left: contextMenu.x, top: contextMenu.y }}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button role="menuitem" className={itemCls} onClick={onCopyAllChanged}>
|
||||
Copy all changed lines
|
||||
</button>
|
||||
{contextMenu.isChangedLine && (
|
||||
<button
|
||||
role="menuitem"
|
||||
className={itemCls}
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(contextMenu.lineContent);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Copy line {contextMenu.lineNumber}
|
||||
</button>
|
||||
)}
|
||||
{onRevert && (
|
||||
<>
|
||||
<div className={separatorCls} />
|
||||
<button
|
||||
role="menuitem"
|
||||
className={`${itemCls} text-destructive focus:text-destructive`}
|
||||
onClick={() => {
|
||||
onRevert(filePath);
|
||||
onClose();
|
||||
}}
|
||||
>
|
||||
Revert all changes
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { cn } from '@kandev/ui/lib/utils';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from '@kandev/ui/tooltip';
|
||||
import {
|
||||
IconCopy,
|
||||
IconTextWrap,
|
||||
IconLayoutRows,
|
||||
IconLayoutColumns,
|
||||
IconPencil,
|
||||
IconArrowBackUp,
|
||||
IconFoldDown,
|
||||
IconFold,
|
||||
} from '@tabler/icons-react';
|
||||
import type { FileDiffData } from '@/lib/diff/types';
|
||||
import type { ViewMode } from '@/hooks/use-global-view-mode';
|
||||
|
||||
interface DiffViewerToolbarProps {
|
||||
data: FileDiffData;
|
||||
foldUnchanged: boolean;
|
||||
setFoldUnchanged: (v: boolean) => void;
|
||||
wordWrap: boolean;
|
||||
setWordWrap: (v: boolean) => void;
|
||||
globalViewMode: ViewMode;
|
||||
setGlobalViewMode: (v: ViewMode) => void;
|
||||
onCopyDiff: () => void;
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
onRevert?: (filePath: string) => void;
|
||||
}
|
||||
|
||||
const iconBtn = 'h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100';
|
||||
|
||||
export function DiffViewerToolbar({
|
||||
data,
|
||||
foldUnchanged,
|
||||
setFoldUnchanged,
|
||||
wordWrap,
|
||||
setWordWrap,
|
||||
globalViewMode,
|
||||
setGlobalViewMode,
|
||||
onCopyDiff,
|
||||
onOpenFile,
|
||||
onRevert,
|
||||
}: DiffViewerToolbarProps) {
|
||||
return (
|
||||
<div className="flex items-center justify-between px-3 py-1.5 border-b border-border/50 bg-card/50 rounded-t-md text-xs text-muted-foreground">
|
||||
<span className="font-mono truncate">{data.filePath}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className={iconBtn} onClick={onCopyDiff}>
|
||||
<IconCopy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Copy diff</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(iconBtn, foldUnchanged && 'opacity-100 bg-muted')}
|
||||
onClick={() => setFoldUnchanged(!foldUnchanged)}
|
||||
>
|
||||
{foldUnchanged ? <IconFoldDown className="h-3.5 w-3.5" /> : <IconFold className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{foldUnchanged ? 'Show all lines' : 'Fold unchanged lines'}</TooltipContent>
|
||||
</Tooltip>
|
||||
{onRevert && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className={iconBtn} onClick={() => onRevert(data.filePath)}>
|
||||
<IconArrowBackUp className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Revert changes</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(iconBtn, wordWrap && 'opacity-100 bg-muted')}
|
||||
onClick={() => setWordWrap(!wordWrap)}
|
||||
>
|
||||
<IconTextWrap className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Toggle word wrap</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn(iconBtn)}
|
||||
onClick={() => setGlobalViewMode(globalViewMode === 'split' ? 'unified' : 'split')}
|
||||
>
|
||||
{globalViewMode === 'split' ? <IconLayoutRows className="h-3.5 w-3.5" /> : <IconLayoutColumns className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{globalViewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'}</TooltipContent>
|
||||
</Tooltip>
|
||||
{onOpenFile && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className={iconBtn} onClick={() => onOpenFile(data.filePath)}>
|
||||
<IconPencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import Editor, { type OnMount, type OnChange } from '@monaco-editor/react';
|
||||
import type { editor as monacoEditor, IDisposable } from 'monaco-editor';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { IconDeviceFloppy, IconLoader2, IconTrash, IconTextWrap, IconTextWrapDisabled, IconMessagePlus, IconArrowsDiff, IconPlugConnected, IconPlugOff, IconAlertTriangle } from '@tabler/icons-react';
|
||||
import { IconDeviceFloppy, IconLoader2, IconTrash, IconTextWrap, IconTextWrapDisabled, IconMessagePlus, IconArrowsDiff } from '@tabler/icons-react';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
|
||||
import { formatDiffStats } from '@/lib/utils/file-diff';
|
||||
import { toRelativePath } from '@/lib/utils';
|
||||
@@ -13,19 +13,23 @@ import { getMonacoLanguage } from '@/lib/editor/language-map';
|
||||
import { EDITOR_FONT_FAMILY, EDITOR_FONT_SIZE } from '@/lib/theme/editor-theme';
|
||||
import { useDiffCommentsStore, useFileComments } from '@/lib/state/slices/diff-comments/diff-comments-slice';
|
||||
import type { DiffComment } from '@/lib/diff/types';
|
||||
import { buildDiffComment, useCommentedLines } from '@/lib/diff/comment-utils';
|
||||
import { computeLineDiffStats } from '@/lib/diff';
|
||||
import { useToast } from '@/components/toast-provider';
|
||||
import { EditorCommentPopover } from '@/components/task/editor-comment-popover';
|
||||
import { CommentViewPopover } from '@/components/task/comment-view-popover';
|
||||
import { CommentForm } from '@/components/diff/comment-form';
|
||||
import { CommentDisplay } from '@/components/diff/comment-display';
|
||||
import { diffLines } from 'diff';
|
||||
import { FileActionsDropdown } from '@/components/editors/file-actions-dropdown';
|
||||
import { PanelHeaderBarSplit } from '@/components/task/panel-primitives';
|
||||
import { useAppStore } from '@/components/state-provider';
|
||||
import { useLsp } from '@/hooks/use-lsp';
|
||||
import type { LspStatus } from '@/lib/lsp/lsp-client-manager';
|
||||
import { lspClientManager } from '@/lib/lsp/lsp-client-manager';
|
||||
import { useDockviewStore } from '@/lib/state/dockview-store';
|
||||
import { consumePendingCursorPosition } from '@/hooks/use-file-editors';
|
||||
import { useCommandPanelOpen } from '@/lib/commands/command-registry';
|
||||
import { useGutterComments } from '@/hooks/use-gutter-comments';
|
||||
import { useEditorViewZoneComments } from '@/hooks/use-editor-view-zone-comments';
|
||||
import { LspStatusButton } from '@/components/editors/lsp-status-button';
|
||||
import { initMonacoThemes } from './monaco-init';
|
||||
|
||||
initMonacoThemes();
|
||||
@@ -43,11 +47,10 @@ type MonacoCodeEditorProps = {
|
||||
onDelete?: () => void;
|
||||
};
|
||||
|
||||
type TextSelection = {
|
||||
text: string;
|
||||
type FormZoneRange = {
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
position: { x: number; y: number };
|
||||
codeContent: string;
|
||||
} | null;
|
||||
|
||||
type FloatingButtonPosition = {
|
||||
@@ -55,87 +58,6 @@ type FloatingButtonPosition = {
|
||||
y: number;
|
||||
} | null;
|
||||
|
||||
type CommentViewState = {
|
||||
comments: DiffComment[];
|
||||
position: { x: number; y: number };
|
||||
} | null;
|
||||
|
||||
function LspStatusButton({
|
||||
status,
|
||||
lspLanguage,
|
||||
onToggle,
|
||||
}: {
|
||||
status: LspStatus;
|
||||
lspLanguage: string | null;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
if (!lspLanguage) return null;
|
||||
|
||||
type StateConfig = { icon: React.ReactNode; tooltip: string; clickable: boolean };
|
||||
const configs: Record<string, StateConfig> = {
|
||||
disabled: {
|
||||
icon: <IconPlugOff className="h-3.5 w-3.5 text-muted-foreground/50" />,
|
||||
tooltip: 'LSP: Off \u2014 click to start',
|
||||
clickable: true,
|
||||
},
|
||||
connecting: {
|
||||
icon: <IconLoader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />,
|
||||
tooltip: 'LSP: Connecting...',
|
||||
clickable: true,
|
||||
},
|
||||
installing: {
|
||||
icon: <IconLoader2 className="h-3.5 w-3.5 animate-spin text-amber-500" />,
|
||||
tooltip: 'LSP: Installing language server...',
|
||||
clickable: false,
|
||||
},
|
||||
starting: {
|
||||
icon: <IconLoader2 className="h-3.5 w-3.5 animate-spin text-blue-500" />,
|
||||
tooltip: 'LSP: Starting language server...',
|
||||
clickable: true,
|
||||
},
|
||||
ready: {
|
||||
icon: <IconPlugConnected className="h-3.5 w-3.5 text-emerald-500" />,
|
||||
tooltip: 'LSP: Connected \u2014 click to stop',
|
||||
clickable: true,
|
||||
},
|
||||
stopping: {
|
||||
icon: <IconLoader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />,
|
||||
tooltip: 'LSP: Stopping...',
|
||||
clickable: false,
|
||||
},
|
||||
unavailable: {
|
||||
icon: <IconPlugOff className="h-3.5 w-3.5 text-muted-foreground" />,
|
||||
tooltip: `LSP: ${'reason' in status ? status.reason : 'Unavailable'}`,
|
||||
clickable: true,
|
||||
},
|
||||
error: {
|
||||
icon: <IconAlertTriangle className="h-3.5 w-3.5 text-yellow-500" />,
|
||||
tooltip: `LSP: ${'reason' in status ? status.reason : 'Error'}`,
|
||||
clickable: true,
|
||||
},
|
||||
};
|
||||
|
||||
const c = configs[status.state];
|
||||
if (!c) return null;
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer"
|
||||
onClick={c.clickable ? onToggle : undefined}
|
||||
disabled={!c.clickable}
|
||||
>
|
||||
{c.icon}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{c.tooltip}</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function MonacoCodeEditor({
|
||||
path,
|
||||
originalContent,
|
||||
@@ -158,25 +80,52 @@ export function MonacoCodeEditor({
|
||||
const contentRef = useRef(initialContent);
|
||||
|
||||
const [wrapEnabled, setWrapEnabled] = useState(true);
|
||||
const [textSelection, setTextSelection] = useState<TextSelection>(null);
|
||||
const [formZoneRange, setFormZoneRange] = useState<FormZoneRange>(null);
|
||||
const [floatingButtonPos, setFloatingButtonPos] = useState<FloatingButtonPosition>(null);
|
||||
const [currentSelection, setCurrentSelection] = useState<{ text: string; startLine: number; endLine: number } | null>(null);
|
||||
const [commentView, setCommentView] = useState<CommentViewState>(null);
|
||||
const [showDiffIndicators, setShowDiffIndicators] = useState(true);
|
||||
const [editorInstance, setEditorInstance] = useState<monacoEditor.IStandaloneCodeEditor | null>(null);
|
||||
const editorRef = useRef<monacoEditor.IStandaloneCodeEditor | null>(null);
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const mousePositionRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
|
||||
const onSaveRef = useRef(onSave);
|
||||
onSaveRef.current = onSave;
|
||||
useEffect(() => { onSaveRef.current = onSave; }, [onSave]);
|
||||
const decorationsRef = useRef<monacoEditor.IEditorDecorationsCollection | null>(null);
|
||||
const diffDecorationsRef = useRef<monacoEditor.IEditorDecorationsCollection | null>(null);
|
||||
const disposablesRef = useRef<IDisposable[]>([]);
|
||||
const { toast } = useToast();
|
||||
const { setOpen: setCommandPanelOpen } = useCommandPanelOpen();
|
||||
|
||||
const addComment = useDiffCommentsStore((state) => state.addComment);
|
||||
const removeComment = useDiffCommentsStore((state) => state.removeComment);
|
||||
const updateComment = useDiffCommentsStore((state) => state.updateComment);
|
||||
const editingCommentId = useDiffCommentsStore((state) => state.editingCommentId);
|
||||
const setEditingComment = useDiffCommentsStore((state) => state.setEditingComment);
|
||||
const comments = useFileComments(sessionId ?? '', path);
|
||||
|
||||
// Gutter comment interactions (hover "+", click-to-select)
|
||||
const commentedLines = useCommentedLines(comments);
|
||||
|
||||
const handleGutterSelectionComplete = useCallback(
|
||||
(params: { range: { start: number; end: number }; code: string }) => {
|
||||
setFormZoneRange({
|
||||
startLine: params.range.start,
|
||||
endLine: params.range.end,
|
||||
codeContent: params.code,
|
||||
});
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const { clearGutterSelection } = useGutterComments(
|
||||
editorInstance,
|
||||
{
|
||||
enabled: enableComments && !!sessionId,
|
||||
commentedLines,
|
||||
onSelectionComplete: handleGutterSelectionComplete,
|
||||
}
|
||||
);
|
||||
|
||||
const language = getMonacoLanguage(path);
|
||||
|
||||
// LSP integration
|
||||
@@ -272,10 +221,16 @@ export function MonacoCodeEditor({
|
||||
return () => wrapper.removeEventListener('keydown', handler);
|
||||
}, []);
|
||||
|
||||
// Stable callback refs for ViewZone renders (avoids stale closures)
|
||||
const handleCommentSubmitRef = useRef((_annotation: string) => {});
|
||||
const handleCommentDeleteRef = useRef((_commentId: string) => {});
|
||||
const handleCommentUpdateRef = useRef((_commentId: string, _annotation: string) => {});
|
||||
|
||||
// Handle editor mount
|
||||
const handleEditorDidMount: OnMount = useCallback(
|
||||
(editor, monaco) => {
|
||||
(editor, _monaco) => {
|
||||
editorRef.current = editor;
|
||||
setEditorInstance(editor);
|
||||
decorationsRef.current = editor.createDecorationsCollection([]);
|
||||
diffDecorationsRef.current = editor.createDecorationsCollection([]);
|
||||
|
||||
@@ -286,10 +241,6 @@ export function MonacoCodeEditor({
|
||||
editor.revealLineInCenter(pendingPos.line);
|
||||
}
|
||||
|
||||
// Cmd/Ctrl+S is handled via DOM keydown on the wrapper (see useEffect below)
|
||||
// because Monaco's addCommand registers globally and conflicts when
|
||||
// multiple editor instances exist.
|
||||
|
||||
// Selection change listener for comments
|
||||
if (enableComments && sessionId) {
|
||||
const disposable = editor.onDidChangeCursorSelection(() => {
|
||||
@@ -314,26 +265,31 @@ export function MonacoCodeEditor({
|
||||
disposablesRef.current.push(disposable);
|
||||
}
|
||||
|
||||
// Gutter click for viewing comments
|
||||
// Gutter click on commented lines → toggle editing
|
||||
const glyphDisposable = editor.onMouseDown((e) => {
|
||||
if (e.target.type === 2 /* GUTTER_GLYPH_MARGIN */ || e.target.type === 3 /* GUTTER_LINE_NUMBERS */) {
|
||||
if (e.target.type === 3 || e.target.type === 4) {
|
||||
const lineNumber = e.target.position?.lineNumber;
|
||||
if (!lineNumber) return;
|
||||
|
||||
const lineComments = comments.filter(
|
||||
const { editingCommentId: currentEditing } = useDiffCommentsStore.getState();
|
||||
const fileComments = useDiffCommentsStore.getState().getCommentsForFile(sessionId ?? '', path);
|
||||
const lineComments = fileComments.filter(
|
||||
(c) => lineNumber >= c.startLine && lineNumber <= c.endLine
|
||||
);
|
||||
if (lineComments.length > 0 && e.event.browserEvent) {
|
||||
setCommentView({
|
||||
comments: lineComments,
|
||||
position: { x: e.event.browserEvent.clientX, y: e.event.browserEvent.clientY },
|
||||
});
|
||||
if (lineComments.length > 0) {
|
||||
const firstComment = lineComments[0];
|
||||
// Toggle: if already editing this comment, stop editing
|
||||
if (currentEditing === firstComment.id) {
|
||||
useDiffCommentsStore.getState().setEditingComment(null);
|
||||
} else {
|
||||
useDiffCommentsStore.getState().setEditingComment(firstComment.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
disposablesRef.current.push(glyphDisposable);
|
||||
},
|
||||
[path, enableComments, sessionId, comments]
|
||||
[path, enableComments, sessionId]
|
||||
);
|
||||
|
||||
// Cleanup disposables
|
||||
@@ -370,21 +326,18 @@ export function MonacoCodeEditor({
|
||||
options: {
|
||||
isWholeLine: true,
|
||||
className: 'monaco-comment-line',
|
||||
glyphMarginClassName: firstLines.has(lineNum)
|
||||
? 'monaco-comment-glyph'
|
||||
: 'monaco-comment-glyph-bg',
|
||||
glyphMarginHoverMessage: {
|
||||
value: `${comments.filter((c) => lineNum >= c.startLine && lineNum <= c.endLine).length} comment(s) - click to view`,
|
||||
},
|
||||
lineNumberClassName: 'monaco-comment-line-number',
|
||||
linesDecorationsClassName: firstLines.has(lineNum)
|
||||
? 'monaco-comment-bar-icon'
|
||||
: 'monaco-comment-bar',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
decorationsRef.current.set(decorations);
|
||||
}, [comments]);
|
||||
}, [comments, editorInstance]);
|
||||
|
||||
// Diff gutter indicators — driven by Monaco model change events, not React props.
|
||||
// We compute decorations using contentRef (updated by onChange) + originalContent prop.
|
||||
const updateDiffDecorations = useCallback(() => {
|
||||
if (!diffDecorationsRef.current || !editorRef.current) return;
|
||||
|
||||
@@ -459,17 +412,31 @@ export function MonacoCodeEditor({
|
||||
};
|
||||
}, [updateDiffDecorations]);
|
||||
|
||||
// Show floating button after mouse up
|
||||
// Show floating button at end of selection
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper || !enableComments || !sessionId) return;
|
||||
const editor = editorRef.current;
|
||||
if (!wrapper || !editor || !enableComments || !sessionId) return;
|
||||
|
||||
const handleMouseUp = (e: MouseEvent) => {
|
||||
if ((e.target as HTMLElement).closest('.floating-comment-btn')) return;
|
||||
setTimeout(() => {
|
||||
if (currentSelection) {
|
||||
setFloatingButtonPos({ x: mousePositionRef.current.x, y: mousePositionRef.current.y });
|
||||
}
|
||||
if (!currentSelection) return;
|
||||
const sel = editor.getSelection();
|
||||
if (!sel || sel.isEmpty()) return;
|
||||
// Position at end of selection using editor coordinates
|
||||
// endPos is relative to the editor's DOM container
|
||||
const endPos = editor.getScrolledVisiblePosition({
|
||||
lineNumber: sel.endLineNumber,
|
||||
column: sel.endColumn,
|
||||
});
|
||||
if (!endPos) return;
|
||||
// getScrolledVisiblePosition returns coords relative to the editor DOM node,
|
||||
// which is inside the "relative" container where the button lives.
|
||||
setFloatingButtonPos({
|
||||
x: endPos.left,
|
||||
y: endPos.top + endPos.height,
|
||||
});
|
||||
}, 10);
|
||||
};
|
||||
|
||||
@@ -486,36 +453,80 @@ export function MonacoCodeEditor({
|
||||
};
|
||||
}, [enableComments, sessionId, currentSelection]);
|
||||
|
||||
// Cmd+I for comment popover
|
||||
// Cmd+I to open inline comment form
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper || !enableComments || !sessionId) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'i') {
|
||||
if (!currentSelection || !floatingButtonPos) return;
|
||||
if (!currentSelection) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setTextSelection({ ...currentSelection, position: floatingButtonPos });
|
||||
setFormZoneRange({
|
||||
startLine: currentSelection.startLine,
|
||||
endLine: currentSelection.endLine,
|
||||
codeContent: currentSelection.text,
|
||||
});
|
||||
setFloatingButtonPos(null);
|
||||
}
|
||||
};
|
||||
|
||||
wrapper.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => wrapper.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [enableComments, sessionId, currentSelection, floatingButtonPos]);
|
||||
}, [enableComments, sessionId, currentSelection]);
|
||||
|
||||
// Escape to close popovers
|
||||
// Cmd+K for command panel — capture phase prevents Monaco from swallowing the shortcut
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setCommandPanelOpen(true);
|
||||
}
|
||||
};
|
||||
wrapper.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => wrapper.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [setCommandPanelOpen]);
|
||||
|
||||
// Escape to close inline forms
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
if (textSelection) setTextSelection(null);
|
||||
if (commentView) setCommentView(null);
|
||||
if (formZoneRange) {
|
||||
setFormZoneRange(null);
|
||||
clearGutterSelection();
|
||||
}
|
||||
if (editingCommentId) setEditingComment(null);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [textSelection, commentView]);
|
||||
}, [formZoneRange, editingCommentId, setEditingComment, clearGutterSelection]);
|
||||
|
||||
// Click outside to close editing mode / new comment form
|
||||
useEffect(() => {
|
||||
if (!editingCommentId && !formZoneRange) return;
|
||||
const handleMouseDown = (e: MouseEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (target.closest('[data-comment-zone]')) return;
|
||||
if (editingCommentId) setEditingComment(null);
|
||||
if (formZoneRange) {
|
||||
setFormZoneRange(null);
|
||||
clearGutterSelection();
|
||||
}
|
||||
};
|
||||
// Delay to avoid closing immediately from the click that opened it
|
||||
const timer = setTimeout(() => {
|
||||
document.addEventListener('mousedown', handleMouseDown);
|
||||
}, 0);
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
document.removeEventListener('mousedown', handleMouseDown);
|
||||
};
|
||||
}, [editingCommentId, formZoneRange, setEditingComment, clearGutterSelection]);
|
||||
|
||||
const handleChange: OnChange = useCallback(
|
||||
(value) => {
|
||||
@@ -531,30 +542,32 @@ export function MonacoCodeEditor({
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (!currentSelection || !floatingButtonPos) return;
|
||||
setTextSelection({ ...currentSelection, position: floatingButtonPos });
|
||||
if (!currentSelection) return;
|
||||
setFormZoneRange({
|
||||
startLine: currentSelection.startLine,
|
||||
endLine: currentSelection.endLine,
|
||||
codeContent: currentSelection.text,
|
||||
});
|
||||
setFloatingButtonPos(null);
|
||||
},
|
||||
[currentSelection, floatingButtonPos]
|
||||
[currentSelection]
|
||||
);
|
||||
|
||||
// Comment submit for new comments
|
||||
const handleCommentSubmit = useCallback(
|
||||
(annotation: string) => {
|
||||
if (!textSelection || !sessionId) return;
|
||||
const comment: DiffComment = {
|
||||
id: `${path}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
sessionId,
|
||||
if (!formZoneRange || !sessionId) return;
|
||||
addComment(buildDiffComment({
|
||||
filePath: path,
|
||||
startLine: textSelection.startLine,
|
||||
endLine: textSelection.endLine,
|
||||
sessionId,
|
||||
startLine: formZoneRange.startLine,
|
||||
endLine: formZoneRange.endLine,
|
||||
side: 'additions',
|
||||
codeContent: textSelection.text,
|
||||
annotation,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'pending',
|
||||
};
|
||||
addComment(comment);
|
||||
setTextSelection(null);
|
||||
codeContent: formZoneRange.codeContent,
|
||||
}));
|
||||
setFormZoneRange(null);
|
||||
clearGutterSelection();
|
||||
|
||||
// Clear editor selection
|
||||
const editor = editorRef.current;
|
||||
@@ -565,29 +578,80 @@ export function MonacoCodeEditor({
|
||||
|
||||
toast({ title: 'Comment added', description: 'Your comment will be sent with your next message.' });
|
||||
},
|
||||
[textSelection, sessionId, path, addComment, toast]
|
||||
[formZoneRange, sessionId, path, addComment, clearGutterSelection, toast]
|
||||
);
|
||||
|
||||
const handlePopoverClose = useCallback(() => setTextSelection(null), []);
|
||||
|
||||
const handleDeleteComment = useCallback(
|
||||
(commentId: string) => {
|
||||
if (!sessionId) return;
|
||||
removeComment(sessionId, path, commentId);
|
||||
if (commentView && commentView.comments.length <= 1) {
|
||||
setCommentView(null);
|
||||
} else if (commentView) {
|
||||
setCommentView({
|
||||
...commentView,
|
||||
comments: commentView.comments.filter((c) => c.id !== commentId),
|
||||
});
|
||||
}
|
||||
toast({ title: 'Comment deleted' });
|
||||
},
|
||||
[sessionId, path, removeComment, commentView, toast]
|
||||
[sessionId, path, removeComment, toast]
|
||||
);
|
||||
|
||||
const handleCommentViewClose = useCallback(() => setCommentView(null), []);
|
||||
const handleUpdateComment = useCallback(
|
||||
(commentId: string, annotation: string) => {
|
||||
updateComment(commentId, { annotation });
|
||||
setEditingComment(null);
|
||||
toast({ title: 'Comment updated' });
|
||||
},
|
||||
[updateComment, setEditingComment, toast]
|
||||
);
|
||||
|
||||
// Keep stable refs updated for ViewZone renders
|
||||
useEffect(() => { handleCommentSubmitRef.current = handleCommentSubmit; }, [handleCommentSubmit]);
|
||||
useEffect(() => { handleCommentDeleteRef.current = handleDeleteComment; }, [handleDeleteComment]);
|
||||
useEffect(() => { handleCommentUpdateRef.current = handleUpdateComment; }, [handleUpdateComment]);
|
||||
|
||||
// Inline ViewZones for comments and new comment form
|
||||
useEditorViewZoneComments(
|
||||
editorInstance,
|
||||
[comments, formZoneRange, editingCommentId],
|
||||
(addZone) => {
|
||||
// Existing comments → compact inline display or edit form
|
||||
for (const comment of comments) {
|
||||
const isEditing = editingCommentId === comment.id;
|
||||
const node = isEditing ? (
|
||||
<div className="px-2 py-0.5" data-comment-zone>
|
||||
<CommentForm
|
||||
initialContent={comment.annotation}
|
||||
onSubmit={(c) => handleCommentUpdateRef.current(comment.id, c)}
|
||||
onCancel={() => setEditingComment(null)}
|
||||
isEditing
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="px-2 py-0.5" data-comment-zone>
|
||||
<CommentDisplay
|
||||
comment={comment}
|
||||
onDelete={() => handleCommentDeleteRef.current(comment.id)}
|
||||
onEdit={() => setEditingComment(comment.id)}
|
||||
showCode={false}
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
addZone(comment.endLine, isEditing ? 120 : 32, node);
|
||||
}
|
||||
|
||||
// New comment form
|
||||
if (formZoneRange) {
|
||||
addZone(
|
||||
formZoneRange.endLine, 120,
|
||||
<div className="px-2 py-1" data-comment-zone>
|
||||
<CommentForm
|
||||
onSubmit={(c) => handleCommentSubmitRef.current(c)}
|
||||
onCancel={() => {
|
||||
setFormZoneRange(null);
|
||||
clearGutterSelection();
|
||||
}}
|
||||
/>
|
||||
</div>,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Diff stats — updated via Monaco model events, not React props
|
||||
const [diffStats, setDiffStats] = useState<{ additions: number; deletions: number } | null>(null);
|
||||
@@ -729,7 +793,8 @@ export function MonacoCodeEditor({
|
||||
scrollBeyondLastLine: false,
|
||||
smoothScrolling: true,
|
||||
cursorSmoothCaretAnimation: 'on',
|
||||
glyphMargin: enableComments,
|
||||
glyphMargin: false,
|
||||
lineDecorationsWidth: 10,
|
||||
folding: true,
|
||||
lineNumbers: 'on',
|
||||
renderLineHighlight: 'line',
|
||||
@@ -749,12 +814,12 @@ export function MonacoCodeEditor({
|
||||
/>
|
||||
|
||||
{/* Floating comment button */}
|
||||
{floatingButtonPos && !textSelection && (
|
||||
{floatingButtonPos && !formZoneRange && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="floating-comment-btn fixed z-50 gap-1.5 shadow-lg animate-in fade-in-0 zoom-in-95 duration-100 cursor-pointer"
|
||||
style={{ left: floatingButtonPos.x + 8, top: floatingButtonPos.y + 8 }}
|
||||
className="floating-comment-btn absolute z-50 gap-1.5 shadow-lg animate-in fade-in-0 zoom-in-95 duration-100 cursor-pointer"
|
||||
style={{ left: floatingButtonPos.x + 4, top: floatingButtonPos.y + 2 }}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
onClick={handleFloatingButtonClick}
|
||||
>
|
||||
@@ -762,25 +827,6 @@ export function MonacoCodeEditor({
|
||||
Comment
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{textSelection && (
|
||||
<EditorCommentPopover
|
||||
selectedText={textSelection.text}
|
||||
lineRange={{ start: textSelection.startLine, end: textSelection.endLine }}
|
||||
position={textSelection.position}
|
||||
onSubmit={handleCommentSubmit}
|
||||
onClose={handlePopoverClose}
|
||||
/>
|
||||
)}
|
||||
|
||||
{commentView && (
|
||||
<CommentViewPopover
|
||||
comments={commentView.comments}
|
||||
position={commentView.position}
|
||||
onDelete={handleDeleteComment}
|
||||
onClose={handleCommentViewClose}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,52 +5,23 @@ import { DiffEditor, type DiffOnMount } from '@monaco-editor/react';
|
||||
import type { editor as monacoEditor } from 'monaco-editor';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { cn } from '@kandev/ui/lib/utils';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from '@kandev/ui/tooltip';
|
||||
import { IconCopy, IconTextWrap, IconLayoutRows, IconLayoutColumns, IconPencil, IconArrowBackUp, IconFoldDown, IconFold } from '@tabler/icons-react';
|
||||
import type { FileDiffData, DiffComment } from '@/lib/diff/types';
|
||||
import { buildDiffComment, useCommentedLines, useCommentActions } from '@/lib/diff/comment-utils';
|
||||
import { getMonacoLanguage } from '@/lib/editor/language-map';
|
||||
import { EDITOR_FONT_FAMILY, EDITOR_FONT_SIZE } from '@/lib/theme/editor-theme';
|
||||
import { useDiffComments } from '@/components/diff/use-diff-comments';
|
||||
import { CommentForm } from '@/components/diff/comment-form';
|
||||
import { CommentDisplay } from '@/components/diff/comment-display';
|
||||
import { useCommandPanelOpen } from '@/lib/commands/command-registry';
|
||||
import { useGutterComments } from '@/hooks/use-gutter-comments';
|
||||
import { useDiffEditorHeight } from '@/hooks/use-diff-editor-height';
|
||||
import { useGlobalViewMode } from '@/hooks/use-global-view-mode';
|
||||
import { DiffViewerToolbar } from './diff-viewer-toolbar';
|
||||
import { DiffViewerContextMenu, type ContextMenuState } from './diff-viewer-context-menu';
|
||||
import { useViewZones } from './use-diff-view-zones';
|
||||
import { initMonacoThemes } from './monaco-init';
|
||||
|
||||
initMonacoThemes();
|
||||
|
||||
// Global view mode sync (same as pierre diff-viewer)
|
||||
const DIFF_VIEW_MODE_KEY = 'diff-view-mode';
|
||||
const DEFAULT_VIEW_MODE = 'unified' as const;
|
||||
const VIEW_MODE_CHANGE_EVENT = 'diff-view-mode-change';
|
||||
type ViewMode = 'split' | 'unified';
|
||||
|
||||
function getStoredViewMode(): ViewMode {
|
||||
if (typeof window === 'undefined') return DEFAULT_VIEW_MODE;
|
||||
const stored = localStorage.getItem(DIFF_VIEW_MODE_KEY);
|
||||
return stored === 'split' || stored === 'unified' ? stored : DEFAULT_VIEW_MODE;
|
||||
}
|
||||
|
||||
function setStoredViewMode(mode: ViewMode): void {
|
||||
localStorage.setItem(DIFF_VIEW_MODE_KEY, mode);
|
||||
window.dispatchEvent(new CustomEvent(VIEW_MODE_CHANGE_EVENT, { detail: mode }));
|
||||
}
|
||||
|
||||
function useGlobalViewMode(): [ViewMode, (mode: ViewMode) => void] {
|
||||
const subscribe = useCallback((callback: () => void) => {
|
||||
window.addEventListener(VIEW_MODE_CHANGE_EVENT, callback);
|
||||
window.addEventListener('storage', callback);
|
||||
return () => {
|
||||
window.removeEventListener(VIEW_MODE_CHANGE_EVENT, callback);
|
||||
window.removeEventListener('storage', callback);
|
||||
};
|
||||
}, []);
|
||||
const getSnapshot = useCallback(() => getStoredViewMode(), []);
|
||||
const getServerSnapshot = useCallback(() => DEFAULT_VIEW_MODE, []);
|
||||
const viewMode = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
return [viewMode, setStoredViewMode];
|
||||
}
|
||||
|
||||
// Global folding toggle sync (same pattern as view mode)
|
||||
// Global folding toggle sync
|
||||
const DIFF_FOLD_KEY = 'diff-fold-unchanged';
|
||||
const DEFAULT_FOLD = true;
|
||||
const FOLD_CHANGE_EVENT = 'diff-fold-change';
|
||||
@@ -94,6 +65,8 @@ interface MonacoDiffViewerProps {
|
||||
onOpenFile?: (filePath: string) => void;
|
||||
onRevert?: (filePath: string) => void;
|
||||
wordWrap?: boolean;
|
||||
editable?: boolean;
|
||||
onModifiedContentChange?: (filePath: string, content: string) => void;
|
||||
}
|
||||
|
||||
export function MonacoDiffViewer({
|
||||
@@ -108,6 +81,8 @@ export function MonacoDiffViewer({
|
||||
onOpenFile,
|
||||
onRevert,
|
||||
wordWrap: wordWrapProp,
|
||||
editable,
|
||||
onModifiedContentChange,
|
||||
}: MonacoDiffViewerProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const [globalViewMode, setGlobalViewMode] = useGlobalViewMode();
|
||||
@@ -116,11 +91,26 @@ export function MonacoDiffViewer({
|
||||
const wordWrap = wordWrapProp ?? wordWrapLocal;
|
||||
const diffEditorRef = useRef<monacoEditor.IStandaloneDiffEditor | null>(null);
|
||||
const wrapperRef = useRef<HTMLDivElement>(null);
|
||||
const { setOpen: setCommandPanelOpen } = useCommandPanelOpen();
|
||||
const [modifiedEditor, setModifiedEditor] = useState<monacoEditor.ICodeEditor | null>(null);
|
||||
const [originalEditor, setOriginalEditor] = useState<monacoEditor.ICodeEditor | null>(null);
|
||||
|
||||
// Cmd+K for command panel — capture phase prevents Monaco from swallowing the shortcut
|
||||
useEffect(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setCommandPanelOpen(true);
|
||||
}
|
||||
};
|
||||
wrapper.addEventListener('keydown', handleKeyDown, true);
|
||||
return () => wrapper.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [setCommandPanelOpen]);
|
||||
|
||||
// Fix: reset the DiffEditor model BEFORE @monaco-editor/react's useEffect cleanup
|
||||
// disposes the models. useLayoutEffect cleanup runs before useEffect cleanup,
|
||||
// so the DiffEditorWidget releases model references before models are disposed.
|
||||
// This prevents "TextModel got disposed before DiffEditorWidget model got reset".
|
||||
useLayoutEffect(() => {
|
||||
return () => {
|
||||
try { diffEditorRef.current?.setModel(null); } catch { /* already disposed */ }
|
||||
@@ -128,19 +118,13 @@ export function MonacoDiffViewer({
|
||||
}, []);
|
||||
|
||||
// Context menu state
|
||||
type ContextMenuState = {
|
||||
x: number;
|
||||
y: number;
|
||||
lineNumber: number;
|
||||
side: 'original' | 'modified';
|
||||
isChangedLine: boolean;
|
||||
lineContent: string;
|
||||
} | null;
|
||||
const [contextMenu, setContextMenu] = useState<ContextMenuState>(null);
|
||||
|
||||
// Comment form state
|
||||
const [showCommentForm, setShowCommentForm] = useState(false);
|
||||
const [selectedLineRange, setSelectedLineRange] = useState<{ start: number; end: number; side: string } | null>(null);
|
||||
const [selectedLineRange, setSelectedLineRange] = useState<{
|
||||
start: number; end: number; side: string;
|
||||
} | null>(null);
|
||||
|
||||
const {
|
||||
comments: internalComments,
|
||||
@@ -159,165 +143,165 @@ export function MonacoDiffViewer({
|
||||
|
||||
const comments = externalComments || internalComments;
|
||||
|
||||
// Gutter comment interactions for both sides of the diff
|
||||
const gutterEnabled = !!sessionId && !compact;
|
||||
const commentedLines = useCommentedLines(comments);
|
||||
|
||||
const handleGutterSelect = useCallback(
|
||||
(side: 'additions' | 'deletions') =>
|
||||
(params: { range: { start: number; end: number }; code: string; position: { x: number; y: number } }) => {
|
||||
setSelectedLineRange({ start: params.range.start, end: params.range.end, side });
|
||||
setShowCommentForm(true);
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
const { clearGutterSelection: clearModifiedGutter } = useGutterComments(modifiedEditor, {
|
||||
enabled: gutterEnabled,
|
||||
commentedLines,
|
||||
onSelectionComplete: handleGutterSelect('additions'),
|
||||
});
|
||||
|
||||
const { clearGutterSelection: clearOriginalGutter } = useGutterComments(originalEditor, {
|
||||
enabled: gutterEnabled,
|
||||
commentedLines,
|
||||
onSelectionComplete: handleGutterSelect('deletions'),
|
||||
});
|
||||
|
||||
const language = getMonacoLanguage(data.filePath);
|
||||
const showHeader = !hideHeader && !compact;
|
||||
|
||||
// Parse original/modified content from diff data
|
||||
// When only a unified diff string is provided (e.g. git diffs), reconstruct
|
||||
// the original and modified content by parsing the patch hunks.
|
||||
const { original, modified } = useMemo(() => {
|
||||
if (data.oldContent || data.newContent) {
|
||||
return {
|
||||
original: data.oldContent ?? '',
|
||||
modified: data.newContent ?? '',
|
||||
};
|
||||
return { original: data.oldContent ?? '', modified: data.newContent ?? '' };
|
||||
}
|
||||
|
||||
// Reconstruct from unified diff patch
|
||||
if (data.diff) {
|
||||
const originalLines: string[] = [];
|
||||
const modifiedLines: string[] = [];
|
||||
const lines = data.diff.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
// Skip diff headers
|
||||
if (line.startsWith('diff ') || line.startsWith('index ') ||
|
||||
line.startsWith('--- ') || line.startsWith('+++ ') ||
|
||||
line.startsWith('@@')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (line.startsWith('-')) {
|
||||
originalLines.push(line.slice(1));
|
||||
} else if (line.startsWith('+')) {
|
||||
modifiedLines.push(line.slice(1));
|
||||
} else if (line.startsWith(' ') || line === '') {
|
||||
// Context line (or empty line between hunks)
|
||||
const content = line.startsWith(' ') ? line.slice(1) : line;
|
||||
originalLines.push(content);
|
||||
modifiedLines.push(content);
|
||||
} else if (line.startsWith('\\')) {
|
||||
// "\ No newline at end of file" — skip
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
original: originalLines.join('\n'),
|
||||
modified: modifiedLines.join('\n'),
|
||||
};
|
||||
return parseDiffContent(data.diff);
|
||||
}
|
||||
|
||||
return { original: '', modified: '' };
|
||||
}, [data.oldContent, data.newContent, data.diff]);
|
||||
|
||||
// Auto-fit height
|
||||
const lineHeight = compact ? 16 : 18;
|
||||
const editorHeight = useDiffEditorHeight({
|
||||
modifiedEditor,
|
||||
originalEditor,
|
||||
compact,
|
||||
lineHeight,
|
||||
originalContent: original,
|
||||
modifiedContent: modified,
|
||||
});
|
||||
|
||||
// Stable ref for onModifiedContentChange to avoid stale closures
|
||||
const onModifiedContentChangeRef = useRef(onModifiedContentChange);
|
||||
useEffect(() => { onModifiedContentChangeRef.current = onModifiedContentChange; }, [onModifiedContentChange]);
|
||||
|
||||
const handleDiffEditorMount: DiffOnMount = useCallback((editor) => {
|
||||
diffEditorRef.current = editor;
|
||||
const modEditor = editor.getModifiedEditor();
|
||||
const origEditor = editor.getOriginalEditor();
|
||||
setModifiedEditor(modEditor);
|
||||
setOriginalEditor(origEditor);
|
||||
|
||||
// Register context menu on both sides
|
||||
const modifiedEditor = editor.getModifiedEditor();
|
||||
const originalEditor = editor.getOriginalEditor();
|
||||
// Listen for content changes on modified side (edits + block reverts)
|
||||
if (!compact) {
|
||||
modEditor.onDidChangeModelContent(() => {
|
||||
onModifiedContentChangeRef.current?.(data.filePath, modEditor.getValue());
|
||||
});
|
||||
}
|
||||
|
||||
const handleContextMenu = (side: 'original' | 'modified') => (e: monacoEditor.IEditorMouseEvent) => {
|
||||
if (e.target.position) {
|
||||
// Context menu on both sides
|
||||
modEditor.onContextMenu(handleContextMenuEvent(editor, modEditor, 'modified'));
|
||||
origEditor.onContextMenu(handleContextMenuEvent(editor, origEditor, 'original'));
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [compact, data.filePath]);
|
||||
|
||||
const handleContextMenuEvent = useCallback(
|
||||
(
|
||||
diffEditor: monacoEditor.IStandaloneDiffEditor,
|
||||
targetEditor: monacoEditor.ICodeEditor,
|
||||
side: 'original' | 'modified',
|
||||
) =>
|
||||
(e: monacoEditor.IEditorMouseEvent) => {
|
||||
if (!e.target.position) return;
|
||||
e.event.preventDefault();
|
||||
e.event.stopPropagation();
|
||||
const lineNumber = e.target.position.lineNumber;
|
||||
const targetEditor = side === 'modified' ? modifiedEditor : originalEditor;
|
||||
const model = targetEditor.getModel();
|
||||
const lineContent = model ? model.getLineContent(lineNumber) : '';
|
||||
const lineChanges = editor.getLineChanges();
|
||||
const lineChanges = diffEditor.getLineChanges();
|
||||
let isChangedLine = false;
|
||||
if (lineChanges) {
|
||||
for (const change of lineChanges) {
|
||||
if (side === 'modified') {
|
||||
if (lineNumber >= change.modifiedStartLineNumber && lineNumber <= change.modifiedEndLineNumber) {
|
||||
isChangedLine = true;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
if (lineNumber >= change.originalStartLineNumber && lineNumber <= change.originalEndLineNumber) {
|
||||
isChangedLine = true;
|
||||
break;
|
||||
}
|
||||
const [start, end] = side === 'modified'
|
||||
? [change.modifiedStartLineNumber, change.modifiedEndLineNumber]
|
||||
: [change.originalStartLineNumber, change.originalEndLineNumber];
|
||||
if (lineNumber >= start && lineNumber <= end) {
|
||||
isChangedLine = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
setContextMenu({
|
||||
x: e.event.posx,
|
||||
y: e.event.posy,
|
||||
lineNumber,
|
||||
side,
|
||||
isChangedLine,
|
||||
lineContent,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
modifiedEditor.onContextMenu(handleContextMenu('modified'));
|
||||
originalEditor.onContextMenu(handleContextMenu('original'));
|
||||
}, []);
|
||||
setContextMenu({ x: e.event.posx, y: e.event.posy, lineNumber, side, isChangedLine, lineContent });
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
// Handle comment submission
|
||||
const handleCommentSubmit = useCallback(
|
||||
(content: string) => {
|
||||
if (!selectedLineRange) return;
|
||||
if (onCommentAdd && externalComments !== undefined) {
|
||||
const comment: DiffComment = {
|
||||
id: `${data.filePath}-${Date.now()}`,
|
||||
sessionId: sessionId || '',
|
||||
onCommentAdd(buildDiffComment({
|
||||
filePath: data.filePath,
|
||||
startLine: Math.min(selectedLineRange.start, selectedLineRange.end),
|
||||
endLine: Math.max(selectedLineRange.start, selectedLineRange.end),
|
||||
sessionId: sessionId || '',
|
||||
startLine: selectedLineRange.start,
|
||||
endLine: selectedLineRange.end,
|
||||
side: (selectedLineRange.side || 'additions') as DiffComment['side'],
|
||||
codeContent: '',
|
||||
annotation: content,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'pending',
|
||||
};
|
||||
onCommentAdd(comment);
|
||||
}));
|
||||
} else if (sessionId) {
|
||||
addComment(
|
||||
{
|
||||
start: selectedLineRange.start,
|
||||
end: selectedLineRange.end,
|
||||
side: selectedLineRange.side as 'additions' | 'deletions',
|
||||
},
|
||||
{ start: selectedLineRange.start, end: selectedLineRange.end, side: selectedLineRange.side as 'additions' | 'deletions' },
|
||||
content
|
||||
);
|
||||
}
|
||||
setShowCommentForm(false);
|
||||
setSelectedLineRange(null);
|
||||
clearModifiedGutter();
|
||||
clearOriginalGutter();
|
||||
},
|
||||
[selectedLineRange, sessionId, data.filePath, addComment, onCommentAdd, externalComments]
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[selectedLineRange, sessionId, data.filePath, addComment, onCommentAdd, externalComments, clearModifiedGutter, clearOriginalGutter]
|
||||
);
|
||||
|
||||
const handleCommentDelete = useCallback(
|
||||
(commentId: string) => {
|
||||
if (onCommentDelete && externalComments !== undefined) {
|
||||
onCommentDelete(commentId);
|
||||
} else {
|
||||
removeComment(commentId);
|
||||
}
|
||||
},
|
||||
[removeComment, onCommentDelete, externalComments]
|
||||
);
|
||||
const { handleCommentDelete, handleCommentUpdate } = useCommentActions({
|
||||
removeComment, updateComment, setEditingComment,
|
||||
onCommentDelete, externalComments,
|
||||
});
|
||||
|
||||
const handleCommentUpdate = useCallback(
|
||||
(commentId: string, content: string) => {
|
||||
updateComment(commentId, { annotation: content });
|
||||
setEditingComment(null);
|
||||
},
|
||||
[updateComment, setEditingComment]
|
||||
);
|
||||
// Stable refs for callbacks used inside ViewZone renders
|
||||
const handleCommentSubmitRef = useRef(handleCommentSubmit);
|
||||
useEffect(() => { handleCommentSubmitRef.current = handleCommentSubmit; }, [handleCommentSubmit]);
|
||||
const handleCommentDeleteRef = useRef(handleCommentDelete);
|
||||
useEffect(() => { handleCommentDeleteRef.current = handleCommentDelete; }, [handleCommentDelete]);
|
||||
const handleCommentUpdateRef = useRef(handleCommentUpdate);
|
||||
useEffect(() => { handleCommentUpdateRef.current = handleCommentUpdate; }, [handleCommentUpdate]);
|
||||
|
||||
useViewZones({
|
||||
modifiedEditor, originalEditor, comments, showCommentForm,
|
||||
selectedLineRange, editingCommentId, setEditingComment,
|
||||
handleCommentSubmitRef, handleCommentDeleteRef, handleCommentUpdateRef,
|
||||
clearModifiedGutter, clearOriginalGutter,
|
||||
setShowCommentForm, setSelectedLineRange,
|
||||
});
|
||||
|
||||
// Close context menu on click or Escape
|
||||
useEffect(() => {
|
||||
if (!contextMenu) return;
|
||||
const handleClose = () => setContextMenu(null);
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') setContextMenu(null);
|
||||
};
|
||||
const handleKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') setContextMenu(null); };
|
||||
window.addEventListener('mousedown', handleClose);
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => {
|
||||
@@ -358,88 +342,29 @@ export function MonacoDiffViewer({
|
||||
);
|
||||
}
|
||||
|
||||
// Modified side editable when prop is true or revert is available; compact always read-only
|
||||
const modifiedReadOnly = compact || !(editable || !!onRevert);
|
||||
|
||||
return (
|
||||
<div ref={wrapperRef} className={cn('monaco-diff-viewer relative', className)}>
|
||||
{/* Toolbar */}
|
||||
{showHeader && (
|
||||
<div className="flex items-center justify-between px-3 py-1.5 border-b border-border/50 bg-card/50 rounded-t-md text-xs text-muted-foreground">
|
||||
<span className="font-mono truncate">{data.filePath}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100" onClick={() => navigator.clipboard.writeText(data.diff || '')}>
|
||||
<IconCopy className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Copy diff</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn('h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100', foldUnchanged && 'opacity-100 bg-muted')}
|
||||
onClick={() => setFoldUnchanged(!foldUnchanged)}
|
||||
>
|
||||
{foldUnchanged ? <IconFoldDown className="h-3.5 w-3.5" /> : <IconFold className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{foldUnchanged ? 'Show all lines' : 'Fold unchanged lines'}</TooltipContent>
|
||||
</Tooltip>
|
||||
{onRevert && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100" onClick={() => onRevert(data.filePath)}>
|
||||
<IconArrowBackUp className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Revert changes</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className={cn('h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100', wordWrap && 'opacity-100 bg-muted')}
|
||||
onClick={() => setWordWrap(!wordWrap)}
|
||||
>
|
||||
<IconTextWrap className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Toggle word wrap</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => setGlobalViewMode(globalViewMode === 'split' ? 'unified' : 'split')}
|
||||
>
|
||||
{globalViewMode === 'split' ? <IconLayoutRows className="h-3.5 w-3.5" /> : <IconLayoutColumns className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{globalViewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'}</TooltipContent>
|
||||
</Tooltip>
|
||||
{onOpenFile && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-6 w-6 p-0 cursor-pointer opacity-60 hover:opacity-100" onClick={() => onOpenFile(data.filePath)}>
|
||||
<IconPencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DiffViewerToolbar
|
||||
data={data}
|
||||
foldUnchanged={foldUnchanged}
|
||||
setFoldUnchanged={setFoldUnchanged}
|
||||
wordWrap={wordWrap}
|
||||
setWordWrap={setWordWrap}
|
||||
globalViewMode={globalViewMode}
|
||||
setGlobalViewMode={setGlobalViewMode}
|
||||
onCopyDiff={() => navigator.clipboard.writeText(data.diff || '')}
|
||||
onOpenFile={onOpenFile}
|
||||
onRevert={onRevert}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Diff editor */}
|
||||
<div className={cn('overflow-hidden', showHeader ? 'rounded-b-md' : 'rounded-md', 'border border-border/50')}>
|
||||
<DiffEditor
|
||||
height={compact ? '200px' : '400px'}
|
||||
height={editorHeight}
|
||||
language={language}
|
||||
original={original}
|
||||
modified={modified}
|
||||
@@ -448,10 +373,12 @@ export function MonacoDiffViewer({
|
||||
options={{
|
||||
fontSize: compact ? 11 : EDITOR_FONT_SIZE,
|
||||
fontFamily: EDITOR_FONT_FAMILY,
|
||||
lineHeight: compact ? 16 : 18,
|
||||
lineHeight,
|
||||
minimap: { enabled: false },
|
||||
wordWrap: wordWrap ? 'on' : 'off',
|
||||
readOnly: true,
|
||||
readOnly: modifiedReadOnly,
|
||||
originalEditable: false,
|
||||
renderMarginRevertIcon: !compact && !!onRevert,
|
||||
contextmenu: false,
|
||||
renderSideBySide: globalViewMode === 'split',
|
||||
scrollBeyondLastLine: false,
|
||||
@@ -467,6 +394,7 @@ export function MonacoDiffViewer({
|
||||
folding: !compact,
|
||||
lineNumbers: compact ? 'off' : 'on',
|
||||
glyphMargin: false,
|
||||
lineDecorationsWidth: 10,
|
||||
scrollbar: {
|
||||
verticalScrollbarSize: 8,
|
||||
horizontalScrollbarSize: 8,
|
||||
@@ -482,84 +410,43 @@ export function MonacoDiffViewer({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Comment annotations below the diff */}
|
||||
{comments.length > 0 && (
|
||||
<div className="mt-2 space-y-2">
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} className="px-2">
|
||||
{editingCommentId === comment.id ? (
|
||||
<CommentForm
|
||||
initialContent={comment.annotation}
|
||||
onSubmit={(content) => handleCommentUpdate(comment.id, content)}
|
||||
onCancel={() => setEditingComment(null)}
|
||||
isEditing
|
||||
/>
|
||||
) : (
|
||||
<CommentDisplay
|
||||
comment={comment}
|
||||
onDelete={() => handleCommentDelete(comment.id)}
|
||||
onEdit={() => setEditingComment(comment.id)}
|
||||
showCode={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* New comment form */}
|
||||
{showCommentForm && selectedLineRange && (
|
||||
<div className="mt-2 px-2">
|
||||
<CommentForm
|
||||
onSubmit={handleCommentSubmit}
|
||||
onCancel={() => {
|
||||
setShowCommentForm(false);
|
||||
setSelectedLineRange(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Context menu */}
|
||||
{contextMenu && (
|
||||
<div
|
||||
className="fixed z-50 min-w-[180px] rounded-md border border-border bg-popover text-popover-foreground shadow-md ring-1 ring-border/10 py-1 text-xs"
|
||||
style={{ left: contextMenu.x, top: contextMenu.y }}
|
||||
onMouseDown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<button
|
||||
className="flex w-full items-center px-3 py-1.5 hover:bg-accent hover:text-accent-foreground cursor-pointer"
|
||||
onClick={copyAllChangedLines}
|
||||
>
|
||||
Copy all changed lines
|
||||
</button>
|
||||
{contextMenu.isChangedLine && (
|
||||
<button
|
||||
className="flex w-full items-center px-3 py-1.5 hover:bg-accent hover:text-accent-foreground cursor-pointer"
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(contextMenu.lineContent);
|
||||
setContextMenu(null);
|
||||
}}
|
||||
>
|
||||
Copy line {contextMenu.lineNumber}
|
||||
</button>
|
||||
)}
|
||||
{onRevert && (
|
||||
<>
|
||||
<div className="my-1 border-t border-border" />
|
||||
<button
|
||||
className="flex w-full items-center px-3 py-1.5 hover:bg-accent hover:text-accent-foreground cursor-pointer text-destructive"
|
||||
onClick={() => {
|
||||
onRevert(data.filePath);
|
||||
setContextMenu(null);
|
||||
}}
|
||||
>
|
||||
Revert all changes
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<DiffViewerContextMenu
|
||||
contextMenu={contextMenu}
|
||||
onCopyAllChanged={copyAllChangedLines}
|
||||
onClose={() => setContextMenu(null)}
|
||||
onRevert={onRevert}
|
||||
filePath={data.filePath}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Helpers extracted to keep the main component under lint limits ---
|
||||
|
||||
function parseDiffContent(diff: string): { original: string; modified: string } {
|
||||
const originalLines: string[] = [];
|
||||
const modifiedLines: string[] = [];
|
||||
const lines = diff.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('diff ') || line.startsWith('index ') ||
|
||||
line.startsWith('--- ') || line.startsWith('+++ ') ||
|
||||
line.startsWith('@@') || line.startsWith('\\')) {
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith('-')) {
|
||||
originalLines.push(line.slice(1));
|
||||
} else if (line.startsWith('+')) {
|
||||
modifiedLines.push(line.slice(1));
|
||||
} else {
|
||||
const content = line.startsWith(' ') ? line.slice(1) : line;
|
||||
originalLines.push(content);
|
||||
modifiedLines.push(content);
|
||||
}
|
||||
}
|
||||
|
||||
return { original: originalLines.join('\n'), modified: modifiedLines.join('\n') };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { editor as monacoEditor } from 'monaco-editor';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import type { DiffComment } from '@/lib/diff/types';
|
||||
import { CommentForm } from '@/components/diff/comment-form';
|
||||
import { CommentDisplay } from '@/components/diff/comment-display';
|
||||
import { createElement } from 'react';
|
||||
|
||||
type ViewZoneEntry = { id: string; root: Root; editorSide: 'modified' | 'original' };
|
||||
|
||||
interface UseViewZonesParams {
|
||||
modifiedEditor: monacoEditor.ICodeEditor | null;
|
||||
originalEditor: monacoEditor.ICodeEditor | null;
|
||||
comments: DiffComment[];
|
||||
showCommentForm: boolean;
|
||||
selectedLineRange: { start: number; end: number; side: string } | null;
|
||||
editingCommentId: string | null;
|
||||
setEditingComment: (id: string | null) => void;
|
||||
handleCommentSubmitRef: React.RefObject<(content: string) => void>;
|
||||
handleCommentDeleteRef: React.RefObject<(commentId: string) => void>;
|
||||
handleCommentUpdateRef: React.RefObject<(commentId: string, content: string) => void>;
|
||||
clearModifiedGutter: () => void;
|
||||
clearOriginalGutter: () => void;
|
||||
setShowCommentForm: (v: boolean) => void;
|
||||
setSelectedLineRange: (v: null) => void;
|
||||
}
|
||||
|
||||
function addZone(
|
||||
targetEditor: monacoEditor.ICodeEditor,
|
||||
side: 'modified' | 'original',
|
||||
afterLine: number,
|
||||
heightPx: number,
|
||||
content: React.ReactNode,
|
||||
zones: ViewZoneEntry[],
|
||||
) {
|
||||
const domNode = document.createElement('div');
|
||||
domNode.style.zIndex = '10';
|
||||
const root = createRoot(domNode);
|
||||
root.render(content);
|
||||
let zoneId = '';
|
||||
targetEditor.changeViewZones((accessor) => {
|
||||
zoneId = accessor.addZone({ afterLineNumber: afterLine, heightInPx: heightPx, domNode });
|
||||
});
|
||||
zones.push({ id: zoneId, root, editorSide: side });
|
||||
}
|
||||
|
||||
function removeZones(
|
||||
zones: ViewZoneEntry[],
|
||||
modifiedEditor: monacoEditor.ICodeEditor,
|
||||
originalEditor: monacoEditor.ICodeEditor,
|
||||
) {
|
||||
modifiedEditor.changeViewZones((accessor) => {
|
||||
for (const z of zones) { if (z.editorSide === 'modified') accessor.removeZone(z.id); }
|
||||
});
|
||||
originalEditor.changeViewZones((accessor) => {
|
||||
for (const z of zones) { if (z.editorSide === 'original') accessor.removeZone(z.id); }
|
||||
});
|
||||
const roots = zones.map((z) => z.root);
|
||||
queueMicrotask(() => roots.forEach((r) => r.unmount()));
|
||||
}
|
||||
|
||||
/** Manages inline ViewZones for comments and comment forms */
|
||||
export function useViewZones({
|
||||
modifiedEditor, originalEditor, comments, showCommentForm,
|
||||
selectedLineRange, editingCommentId, setEditingComment,
|
||||
handleCommentSubmitRef, handleCommentDeleteRef, handleCommentUpdateRef,
|
||||
clearModifiedGutter, clearOriginalGutter,
|
||||
setShowCommentForm, setSelectedLineRange,
|
||||
}: UseViewZonesParams) {
|
||||
const viewZonesRef = useRef<ViewZoneEntry[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!modifiedEditor || !originalEditor) return;
|
||||
|
||||
const oldZones = viewZonesRef.current;
|
||||
if (oldZones.length > 0) {
|
||||
removeZones(oldZones, modifiedEditor, originalEditor);
|
||||
viewZonesRef.current = [];
|
||||
}
|
||||
|
||||
const newZones: ViewZoneEntry[] = [];
|
||||
|
||||
for (const comment of comments) {
|
||||
const side = comment.side === 'deletions' ? 'original' : 'modified';
|
||||
const editor = side === 'modified' ? modifiedEditor : originalEditor;
|
||||
const isEditing = editingCommentId === comment.id;
|
||||
const node = isEditing
|
||||
? createElement('div', { className: 'px-2 py-0.5' },
|
||||
createElement(CommentForm, {
|
||||
initialContent: comment.annotation,
|
||||
onSubmit: (c: string) => handleCommentUpdateRef.current?.(comment.id, c),
|
||||
onCancel: () => setEditingComment(null),
|
||||
isEditing: true,
|
||||
})
|
||||
)
|
||||
: createElement('div', { className: 'px-2 py-0.5' },
|
||||
createElement(CommentDisplay, {
|
||||
comment,
|
||||
onDelete: () => handleCommentDeleteRef.current?.(comment.id),
|
||||
onEdit: () => setEditingComment(comment.id),
|
||||
showCode: false,
|
||||
compact: true,
|
||||
})
|
||||
);
|
||||
addZone(editor, side, comment.endLine, isEditing ? 120 : 32, node, newZones);
|
||||
}
|
||||
|
||||
if (showCommentForm && selectedLineRange) {
|
||||
const side = selectedLineRange.side === 'deletions' ? 'original' : 'modified';
|
||||
const editor = side === 'modified' ? modifiedEditor : originalEditor;
|
||||
const node = createElement('div', { className: 'px-2 py-1' },
|
||||
createElement(CommentForm, {
|
||||
onSubmit: (c: string) => handleCommentSubmitRef.current?.(c),
|
||||
onCancel: () => {
|
||||
setShowCommentForm(false);
|
||||
setSelectedLineRange(null);
|
||||
clearModifiedGutter();
|
||||
clearOriginalGutter();
|
||||
},
|
||||
})
|
||||
);
|
||||
addZone(editor, side, Math.max(selectedLineRange.start, selectedLineRange.end), 120, node, newZones);
|
||||
}
|
||||
|
||||
viewZonesRef.current = newZones;
|
||||
|
||||
return () => {
|
||||
try { removeZones(newZones, modifiedEditor, originalEditor); } catch { /* editors may be disposed */ }
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [modifiedEditor, originalEditor, comments, showCommentForm, selectedLineRange, editingCommentId]);
|
||||
}
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
// Re-export the existing Pierre/diffs-based DiffViewer as PierreDiffViewer
|
||||
// The original implementation stays in components/diff/diff-viewer.tsx
|
||||
export { DiffViewer as PierreDiffViewer, DiffViewInline as PierreInlineDiff } from '@/components/diff/diff-viewer';
|
||||
export { DiffViewer as PierreDiffViewer } from '@/components/diff/diff-viewer';
|
||||
|
||||
@@ -10,7 +10,11 @@ import { Checkbox } from '@kandev/ui/checkbox';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
|
||||
import { FileDiffViewer } from '@/components/diff';
|
||||
import type { RevertBlockInfo } from '@/components/diff';
|
||||
import { FileActionsDropdown } from '@/components/editors/file-actions-dropdown';
|
||||
import { getWebSocketClient } from '@/lib/ws/connection';
|
||||
import { requestFileContent, updateFileContent } from '@/lib/ws/workspace-files';
|
||||
import { generateUnifiedDiff, calculateHash } from '@/lib/utils/file-diff';
|
||||
import type { ReviewFile } from './types';
|
||||
|
||||
type ReviewDiffListProps = {
|
||||
@@ -152,6 +156,24 @@ function FileDiffSection({
|
||||
onDiscard(file.path);
|
||||
}, [file.path, onDiscard]);
|
||||
|
||||
const handleRevertBlock = useCallback(async (filePath: string, info: RevertBlockInfo) => {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return;
|
||||
try {
|
||||
const response = await requestFileContent(client, sessionId, filePath);
|
||||
if (response.error) return;
|
||||
const currentContent = response.content;
|
||||
const hash = await calculateHash(currentContent);
|
||||
const lines = currentContent.split('\n');
|
||||
lines.splice(info.addStart - 1, info.addCount, ...info.oldLines);
|
||||
const newContent = lines.join('\n');
|
||||
const diff = generateUnifiedDiff(currentContent, newContent, filePath);
|
||||
await updateFileContent(client, sessionId, filePath, diff, hash);
|
||||
} catch (err) {
|
||||
console.error('Failed to revert change block:', err);
|
||||
}
|
||||
}, [sessionId]);
|
||||
|
||||
return (
|
||||
<div ref={sectionRef} className="border-b border-border">
|
||||
{/* Sentinel for auto-mark-on-scroll */}
|
||||
@@ -233,6 +255,8 @@ function FileDiffSection({
|
||||
diff={file.diff}
|
||||
status={file.status}
|
||||
enableComments
|
||||
enableAcceptReject
|
||||
onRevertBlock={handleRevertBlock}
|
||||
sessionId={sessionId}
|
||||
hideHeader
|
||||
wordWrap={wordWrap}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useRef, useEffect } from 'react';
|
||||
import { IconTrash } from '@tabler/icons-react';
|
||||
import { useRef, useEffect, useState, useCallback } from 'react';
|
||||
import { IconTrash, IconGripHorizontal } from '@tabler/icons-react';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { DiffComment } from '@/lib/diff/types';
|
||||
@@ -21,6 +21,44 @@ export function CommentViewPopover({
|
||||
}: CommentViewPopoverProps) {
|
||||
const popoverRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Draggable position
|
||||
const popoverWidth = 350;
|
||||
const popoverHeight = 200;
|
||||
|
||||
const computeInitial = () => {
|
||||
let left = position.x;
|
||||
let top = position.y;
|
||||
if (left + popoverWidth > window.innerWidth - 16) {
|
||||
left = Math.max(16, window.innerWidth - popoverWidth - 16);
|
||||
}
|
||||
if (top + popoverHeight > window.innerHeight - 16) {
|
||||
top = Math.max(16, position.y - popoverHeight);
|
||||
}
|
||||
return { left, top };
|
||||
};
|
||||
|
||||
const [pos, setPos] = useState(computeInitial);
|
||||
const dragRef = useRef<{ startX: number; startY: number; origLeft: number; origTop: number } | null>(null);
|
||||
|
||||
const onDragStart = useCallback((e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragRef.current = { startX: e.clientX, startY: e.clientY, origLeft: pos.left, origTop: pos.top };
|
||||
|
||||
const onMove = (ev: MouseEvent) => {
|
||||
if (!dragRef.current) return;
|
||||
const dx = ev.clientX - dragRef.current.startX;
|
||||
const dy = ev.clientY - dragRef.current.startY;
|
||||
setPos({ left: dragRef.current.origLeft + dx, top: dragRef.current.origTop + dy });
|
||||
};
|
||||
const onUp = () => {
|
||||
dragRef.current = null;
|
||||
document.removeEventListener('mousemove', onMove);
|
||||
document.removeEventListener('mouseup', onUp);
|
||||
};
|
||||
document.addEventListener('mousemove', onMove);
|
||||
document.addEventListener('mouseup', onUp);
|
||||
}, [pos.left, pos.top]);
|
||||
|
||||
// Close on click outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (e: MouseEvent) => {
|
||||
@@ -28,7 +66,6 @@ export function CommentViewPopover({
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
// Delay adding listener to avoid immediate close
|
||||
const timer = setTimeout(() => {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
}, 100);
|
||||
@@ -50,24 +87,6 @@ export function CommentViewPopover({
|
||||
return () => document.removeEventListener('keydown', handleKeyDown, true);
|
||||
}, [onClose]);
|
||||
|
||||
// Calculate position
|
||||
const popoverWidth = 350;
|
||||
const popoverHeight = 200;
|
||||
const gap = 8;
|
||||
|
||||
let left = position.x + gap;
|
||||
let top = position.y + gap;
|
||||
|
||||
// If would overflow right, shift left
|
||||
if (left + popoverWidth > window.innerWidth - 16) {
|
||||
left = Math.max(16, window.innerWidth - popoverWidth - 16);
|
||||
}
|
||||
|
||||
// If would overflow bottom, position above
|
||||
if (top + popoverHeight > window.innerHeight - 16) {
|
||||
top = Math.max(16, position.y - popoverHeight - gap);
|
||||
}
|
||||
|
||||
// Format line range
|
||||
const formatLineRange = (start: number, end: number) => {
|
||||
return start === end ? `L${start}` : `L${start}-${end}`;
|
||||
@@ -80,11 +99,19 @@ export function CommentViewPopover({
|
||||
'fixed z-50 w-[350px] max-h-[350px] overflow-auto rounded-xl border border-border/50 bg-popover/95 backdrop-blur-sm shadow-xl',
|
||||
'animate-in fade-in-0 zoom-in-95 duration-150'
|
||||
)}
|
||||
style={{
|
||||
left,
|
||||
top,
|
||||
}}
|
||||
style={{ left: pos.left, top: pos.top }}
|
||||
>
|
||||
{/* Drag handle */}
|
||||
<div
|
||||
className="flex items-center justify-between px-3 pt-2 pb-1 cursor-grab active:cursor-grabbing select-none sticky top-0 bg-popover/95 backdrop-blur-sm z-10"
|
||||
onMouseDown={onDragStart}
|
||||
>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{comments.length} comment{comments.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<IconGripHorizontal className="h-3.5 w-3.5 text-muted-foreground/40" />
|
||||
</div>
|
||||
|
||||
{/* Comments list */}
|
||||
<div className="divide-y divide-border/30">
|
||||
{comments.map((comment) => (
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import { IconPlus } from '@tabler/icons-react';
|
||||
import { IconPlus, IconGripHorizontal } from '@tabler/icons-react';
|
||||
import { Button } from '@kandev/ui/button';
|
||||
import { Textarea } from '@kandev/ui/textarea';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -25,6 +25,45 @@ export function EditorCommentPopover({
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const popoverRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Draggable position — starts at computed initial position
|
||||
const popoverWidth = 384;
|
||||
const popoverHeight = 220;
|
||||
|
||||
const computeInitial = () => {
|
||||
let left = position.x;
|
||||
let top = position.y;
|
||||
if (left + popoverWidth > window.innerWidth - 16) {
|
||||
left = Math.max(16, window.innerWidth - popoverWidth - 16);
|
||||
}
|
||||
if (top + popoverHeight > window.innerHeight - 16) {
|
||||
top = Math.max(16, position.y - popoverHeight);
|
||||
}
|
||||
return { left, top };
|
||||
};
|
||||
|
||||
const [pos, setPos] = useState(computeInitial);
|
||||
const dragRef = useRef<{ startX: number; startY: number; origLeft: number; origTop: number } | null>(null);
|
||||
|
||||
// Drag handlers
|
||||
const onDragStart = useCallback((e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragRef.current = { startX: e.clientX, startY: e.clientY, origLeft: pos.left, origTop: pos.top };
|
||||
|
||||
const onMove = (ev: MouseEvent) => {
|
||||
if (!dragRef.current) return;
|
||||
const dx = ev.clientX - dragRef.current.startX;
|
||||
const dy = ev.clientY - dragRef.current.startY;
|
||||
setPos({ left: dragRef.current.origLeft + dx, top: dragRef.current.origTop + dy });
|
||||
};
|
||||
const onUp = () => {
|
||||
dragRef.current = null;
|
||||
document.removeEventListener('mousemove', onMove);
|
||||
document.removeEventListener('mouseup', onUp);
|
||||
};
|
||||
document.addEventListener('mousemove', onMove);
|
||||
document.addEventListener('mouseup', onUp);
|
||||
}, [pos.left, pos.top]);
|
||||
|
||||
// Focus textarea on mount
|
||||
useEffect(() => {
|
||||
textareaRef.current?.focus();
|
||||
@@ -86,73 +125,57 @@ export function EditorCommentPopover({
|
||||
? `Line ${lineRange.start}`
|
||||
: `Lines ${lineRange.start}-${lineRange.end}`;
|
||||
|
||||
// Calculate position - anchor at bottom-right of selection, adjust if would overflow
|
||||
const popoverWidth = 384; // w-96 = 24rem = 384px
|
||||
const popoverHeight = 220; // approximate height of popover
|
||||
const gap = 8;
|
||||
|
||||
// Start at bottom-right of selection
|
||||
let left = position.x + gap;
|
||||
let top = position.y + gap;
|
||||
|
||||
// If would overflow right, shift left
|
||||
if (left + popoverWidth > window.innerWidth - 16) {
|
||||
left = Math.max(16, window.innerWidth - popoverWidth - 16);
|
||||
}
|
||||
|
||||
// If would overflow bottom, position above the selection instead
|
||||
if (top + popoverHeight > window.innerHeight - 16) {
|
||||
top = Math.max(16, position.y - popoverHeight - gap);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={popoverRef}
|
||||
className={cn(
|
||||
'fixed z-50 w-96 rounded-xl border border-border/50 bg-popover/95 backdrop-blur-sm p-4 shadow-xl',
|
||||
'fixed z-50 w-96 rounded-xl border border-border/50 bg-popover/95 backdrop-blur-sm shadow-xl',
|
||||
'animate-in fade-in-0 zoom-in-95 duration-150'
|
||||
)}
|
||||
style={{
|
||||
left,
|
||||
top,
|
||||
}}
|
||||
style={{ left: pos.left, top: pos.top }}
|
||||
>
|
||||
{/* Line range badge */}
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
{/* Drag handle */}
|
||||
<div
|
||||
className="flex items-center justify-between px-4 pt-3 pb-1 cursor-grab active:cursor-grabbing select-none"
|
||||
onMouseDown={onDragStart}
|
||||
>
|
||||
<span className="px-2 py-0.5 rounded-md bg-muted text-xs font-mono text-muted-foreground">
|
||||
{lineRangeText}
|
||||
</span>
|
||||
<IconGripHorizontal className="h-3.5 w-3.5 text-muted-foreground/40" />
|
||||
</div>
|
||||
|
||||
{/* Code preview */}
|
||||
<pre className="mb-3 p-2 rounded-md bg-muted/50 text-xs text-muted-foreground font-mono line-clamp-3 overflow-hidden whitespace-pre-wrap">
|
||||
{previewText}
|
||||
</pre>
|
||||
<div className="px-4 pb-4">
|
||||
{/* Code preview */}
|
||||
<pre className="mb-3 p-2 rounded-md bg-muted/50 text-xs text-muted-foreground font-mono line-clamp-3 overflow-hidden whitespace-pre-wrap">
|
||||
{previewText}
|
||||
</pre>
|
||||
|
||||
{/* Comment input */}
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Add your comment or instruction..."
|
||||
className="min-h-[72px] resize-none text-sm border-border/50 focus:border-primary/50"
|
||||
/>
|
||||
{/* Comment input */}
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={comment}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Add your comment or instruction..."
|
||||
className="min-h-[72px] resize-none text-sm border-border/50 focus:border-primary/50"
|
||||
/>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground/70">
|
||||
⌘+Enter to add
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={isDisabled}
|
||||
className="gap-1.5 cursor-pointer"
|
||||
>
|
||||
<IconPlus className="h-3.5 w-3.5" />
|
||||
Add comment
|
||||
</Button>
|
||||
{/* Actions */}
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground/70">
|
||||
{'\u2318'}+Enter to add
|
||||
</span>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSubmit}
|
||||
disabled={isDisabled}
|
||||
className="gap-1.5 cursor-pointer"
|
||||
>
|
||||
<IconPlus className="h-3.5 w-3.5" />
|
||||
Add comment
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { useAppStore } from '@/components/state-provider';
|
||||
import { useSession } from '@/hooks/domains/session/use-session';
|
||||
import { useSessionAgentctl } from '@/hooks/domains/session/use-session-agentctl';
|
||||
import { getBackendConfig } from '@/lib/config';
|
||||
import { getTerminalTheme } from '@/lib/terminal-theme';
|
||||
import { getTerminalTheme } from '@/lib/theme/terminal-theme';
|
||||
|
||||
type BaseProps = {
|
||||
sessionId?: string | null;
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useAppStore, useAppStoreApi } from '@/components/state-provider';
|
||||
import { getWebSocketClient } from '@/lib/ws/connection';
|
||||
import { useSession } from '@/hooks/domains/session/use-session';
|
||||
import { useSessionAgentctl } from '@/hooks/domains/session/use-session-agentctl';
|
||||
import { getTerminalTheme } from '@/lib/terminal-theme';
|
||||
import { getTerminalTheme } from '@/lib/theme/terminal-theme';
|
||||
|
||||
type ShellTerminalProps = {
|
||||
// Interactive shell mode - requires sessionId
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import type { editor as monacoEditor } from 'monaco-editor';
|
||||
|
||||
interface UseDiffEditorHeightOptions {
|
||||
modifiedEditor: monacoEditor.ICodeEditor | null;
|
||||
originalEditor: monacoEditor.ICodeEditor | null;
|
||||
compact: boolean;
|
||||
lineHeight: number;
|
||||
originalContent: string;
|
||||
modifiedContent: string;
|
||||
}
|
||||
|
||||
const MIN_HEIGHT = 80;
|
||||
const MAX_HEIGHT_NORMAL = 600;
|
||||
const MAX_HEIGHT_COMPACT = 300;
|
||||
|
||||
function clampHeight(h: number, compact: boolean): number {
|
||||
const max = compact ? MAX_HEIGHT_COMPACT : MAX_HEIGHT_NORMAL;
|
||||
return Math.min(Math.max(h, MIN_HEIGHT), max);
|
||||
}
|
||||
|
||||
export function useDiffEditorHeight({
|
||||
modifiedEditor,
|
||||
originalEditor,
|
||||
compact,
|
||||
lineHeight,
|
||||
originalContent,
|
||||
modifiedContent,
|
||||
}: UseDiffEditorHeightOptions): number {
|
||||
// Estimate before editors mount
|
||||
const estimatedHeight = useMemo(() => {
|
||||
const lines = Math.max(
|
||||
originalContent.split('\n').length,
|
||||
modifiedContent.split('\n').length,
|
||||
);
|
||||
return clampHeight(lines * lineHeight + 10, compact);
|
||||
}, [originalContent, modifiedContent, lineHeight, compact]);
|
||||
|
||||
const [editorHeight, setEditorHeight] = useState<number | null>(null);
|
||||
|
||||
// Subscribe to content size changes on both editors
|
||||
useEffect(() => {
|
||||
if (!modifiedEditor || !originalEditor) return;
|
||||
|
||||
const update = () => {
|
||||
const modH = modifiedEditor.getContentHeight();
|
||||
const origH = originalEditor.getContentHeight();
|
||||
setEditorHeight(clampHeight(Math.max(modH, origH), compact));
|
||||
};
|
||||
|
||||
update();
|
||||
|
||||
const d1 = modifiedEditor.onDidContentSizeChange(update);
|
||||
const d2 = originalEditor.onDidContentSizeChange(update);
|
||||
|
||||
return () => {
|
||||
d1.dispose();
|
||||
d2.dispose();
|
||||
setEditorHeight(null);
|
||||
};
|
||||
}, [modifiedEditor, originalEditor, compact]);
|
||||
|
||||
return editorHeight ?? estimatedHeight;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useEffect, useRef, type DependencyList } from 'react';
|
||||
import type { editor as monacoEditor } from 'monaco-editor';
|
||||
import { createRoot, type Root } from 'react-dom/client';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
type ViewZoneEntry = { id: string; root: Root };
|
||||
|
||||
type AddZoneFn = (afterLine: number, heightPx: number, content: ReactNode) => void;
|
||||
|
||||
/**
|
||||
* Manages Monaco ViewZones that render React components inline between editor lines.
|
||||
* Extracted from the diff viewer's inline-comment pattern.
|
||||
*
|
||||
* @param editor The Monaco editor instance (null while mounting)
|
||||
* @param deps Dependency list — zones are rebuilt whenever these change
|
||||
* @param buildZones Callback that receives an `addZone` helper to create zones
|
||||
*/
|
||||
export function useEditorViewZoneComments(
|
||||
editor: monacoEditor.ICodeEditor | null,
|
||||
deps: DependencyList,
|
||||
buildZones: (addZone: AddZoneFn) => void,
|
||||
): void {
|
||||
const zonesRef = useRef<ViewZoneEntry[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!editor) return;
|
||||
|
||||
// Tear down old zones
|
||||
const oldZones = zonesRef.current;
|
||||
if (oldZones.length > 0) {
|
||||
editor.changeViewZones((accessor) => {
|
||||
for (const z of oldZones) accessor.removeZone(z.id);
|
||||
});
|
||||
const staleRoots = oldZones.map((z) => z.root);
|
||||
queueMicrotask(() => staleRoots.forEach((r) => r.unmount()));
|
||||
zonesRef.current = [];
|
||||
}
|
||||
|
||||
// Build new zones
|
||||
const newZones: ViewZoneEntry[] = [];
|
||||
|
||||
const addZone: AddZoneFn = (afterLine, heightPx, content) => {
|
||||
const domNode = document.createElement('div');
|
||||
domNode.style.zIndex = '10';
|
||||
const root = createRoot(domNode);
|
||||
root.render(content);
|
||||
let zoneId = '';
|
||||
editor.changeViewZones((accessor) => {
|
||||
zoneId = accessor.addZone({ afterLineNumber: afterLine, heightInPx: heightPx, domNode });
|
||||
});
|
||||
newZones.push({ id: zoneId, root });
|
||||
};
|
||||
|
||||
buildZones(addZone);
|
||||
zonesRef.current = newZones;
|
||||
|
||||
return () => {
|
||||
try {
|
||||
editor.changeViewZones((accessor) => {
|
||||
for (const z of newZones) accessor.removeZone(z.id);
|
||||
});
|
||||
} catch { /* editor may be disposed */ }
|
||||
const roots = newZones.map((z) => z.root);
|
||||
queueMicrotask(() => roots.forEach((r) => r.unmount()));
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [editor, ...deps]);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
|
||||
export type ViewMode = 'split' | 'unified';
|
||||
|
||||
const DIFF_VIEW_MODE_KEY = 'diff-view-mode';
|
||||
const DEFAULT_VIEW_MODE: ViewMode = 'unified';
|
||||
const VIEW_MODE_CHANGE_EVENT = 'diff-view-mode-change';
|
||||
|
||||
function getStoredViewMode(): ViewMode {
|
||||
if (typeof window === 'undefined') return DEFAULT_VIEW_MODE;
|
||||
const stored = localStorage.getItem(DIFF_VIEW_MODE_KEY);
|
||||
return stored === 'split' || stored === 'unified' ? stored : DEFAULT_VIEW_MODE;
|
||||
}
|
||||
|
||||
function setStoredViewMode(mode: ViewMode): void {
|
||||
localStorage.setItem(DIFF_VIEW_MODE_KEY, mode);
|
||||
window.dispatchEvent(new CustomEvent(VIEW_MODE_CHANGE_EVENT, { detail: mode }));
|
||||
}
|
||||
|
||||
export function useGlobalViewMode(): [ViewMode, (mode: ViewMode) => void] {
|
||||
const subscribe = useCallback((callback: () => void) => {
|
||||
window.addEventListener(VIEW_MODE_CHANGE_EVENT, callback);
|
||||
window.addEventListener('storage', callback);
|
||||
return () => {
|
||||
window.removeEventListener(VIEW_MODE_CHANGE_EVENT, callback);
|
||||
window.removeEventListener('storage', callback);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const getSnapshot = useCallback(() => getStoredViewMode(), []);
|
||||
const getServerSnapshot = useCallback(() => DEFAULT_VIEW_MODE, []);
|
||||
const viewMode = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
|
||||
return [viewMode, setStoredViewMode];
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { useEffect, useRef, useCallback, useState } from 'react';
|
||||
import type { editor as monacoEditor } from 'monaco-editor';
|
||||
|
||||
type SelectionCompleteParams = {
|
||||
range: { start: number; end: number };
|
||||
code: string;
|
||||
position: { x: number; y: number };
|
||||
};
|
||||
|
||||
type UseGutterCommentsOptions = {
|
||||
enabled: boolean;
|
||||
/** Lines that already have comments — skip hover "+" for these */
|
||||
commentedLines: Set<number>;
|
||||
onSelectionComplete: (params: SelectionCompleteParams) => void;
|
||||
};
|
||||
|
||||
const LINE_NUMBERS = 3;
|
||||
const LINE_DECORATIONS = 4;
|
||||
function isGutterTarget(type: number) {
|
||||
return type === LINE_NUMBERS || type === LINE_DECORATIONS;
|
||||
}
|
||||
|
||||
/** Apply selection decorations for a line range (no linesDecorations — avoids overlap with comment bar) */
|
||||
function applySelectionDecos(
|
||||
collection: monacoEditor.IEditorDecorationsCollection | null,
|
||||
start: number,
|
||||
end: number,
|
||||
) {
|
||||
if (!collection) return;
|
||||
const decos: monacoEditor.IModelDeltaDecoration[] = [];
|
||||
for (let l = start; l <= end; l++) {
|
||||
decos.push({
|
||||
range: { startLineNumber: l, startColumn: 1, endLineNumber: l, endColumn: 1 },
|
||||
options: {
|
||||
isWholeLine: true,
|
||||
className: 'monaco-gutter-selected-line',
|
||||
lineNumberClassName: 'monaco-gutter-selected-line',
|
||||
linesDecorationsClassName: 'monaco-gutter-selected-deco',
|
||||
},
|
||||
});
|
||||
}
|
||||
collection.set(decos);
|
||||
}
|
||||
|
||||
/** Show "+" hover hint on the lines-decoration lane (same lane as comment icons) */
|
||||
function showHoverHint(
|
||||
collection: monacoEditor.IEditorDecorationsCollection | null,
|
||||
line: number,
|
||||
) {
|
||||
collection?.set([{
|
||||
range: { startLineNumber: line, startColumn: 1, endLineNumber: line, endColumn: 1 },
|
||||
options: { linesDecorationsClassName: 'monaco-gutter-comment-hint' },
|
||||
}]);
|
||||
}
|
||||
|
||||
/** Get viewport-relative position for the bottom of a line in the editor */
|
||||
export function getLineBottomPosition(
|
||||
editor: monacoEditor.ICodeEditor,
|
||||
lineNumber: number,
|
||||
): { x: number; y: number } | null {
|
||||
const pos = editor.getScrolledVisiblePosition({ lineNumber, column: 1 });
|
||||
const dom = editor.getDomNode();
|
||||
if (!pos || !dom) return null;
|
||||
const rect = dom.getBoundingClientRect();
|
||||
return { x: rect.left + pos.left, y: rect.top + pos.top + pos.height };
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub PR-style gutter interactions for Monaco:
|
||||
* - Hover "+" icon on line numbers (no glyph margin needed)
|
||||
* - Click-and-drag to select line range, shift-click to extend
|
||||
* - Calls onSelectionComplete with the selected code and position
|
||||
*/
|
||||
export function useGutterComments(
|
||||
editor: monacoEditor.ICodeEditor | null,
|
||||
options: UseGutterCommentsOptions,
|
||||
) {
|
||||
const { enabled, commentedLines, onSelectionComplete } = options;
|
||||
|
||||
const [gutterSelection, setGutterSelection] = useState<{ startLine: number; endLine: number } | null>(null);
|
||||
const anchorLineRef = useRef<number | null>(null);
|
||||
const isDraggingRef = useRef(false);
|
||||
const hasSelectionRef = useRef(false);
|
||||
const hoverDecRef = useRef<monacoEditor.IEditorDecorationsCollection | null>(null);
|
||||
const selectionDecRef = useRef<monacoEditor.IEditorDecorationsCollection | null>(null);
|
||||
const callbackRef = useRef(onSelectionComplete);
|
||||
const commentedRef = useRef(commentedLines);
|
||||
|
||||
useEffect(() => { callbackRef.current = onSelectionComplete; }, [onSelectionComplete]);
|
||||
useEffect(() => { commentedRef.current = commentedLines; }, [commentedLines]);
|
||||
useEffect(() => { hasSelectionRef.current = gutterSelection !== null; }, [gutterSelection]);
|
||||
|
||||
const clearGutterSelection = useCallback(() => {
|
||||
setGutterSelection(null);
|
||||
anchorLineRef.current = null;
|
||||
selectionDecRef.current?.set([]);
|
||||
}, []);
|
||||
|
||||
// Hover "+" icon — shown on gutter mousemove
|
||||
useEffect(() => {
|
||||
if (!editor || !enabled) return;
|
||||
hoverDecRef.current = editor.createDecorationsCollection([]);
|
||||
const moveSub = editor.onMouseMove((e) => {
|
||||
const line = e.target.position?.lineNumber;
|
||||
if (!isGutterTarget(e.target.type) || !line || commentedRef.current.has(line) || hasSelectionRef.current) {
|
||||
hoverDecRef.current?.set([]);
|
||||
return;
|
||||
}
|
||||
showHoverHint(hoverDecRef.current, line);
|
||||
});
|
||||
const leaveSub = editor.onMouseLeave(() => hoverDecRef.current?.set([]));
|
||||
return () => { moveSub.dispose(); leaveSub.dispose(); hoverDecRef.current?.set([]); };
|
||||
}, [editor, enabled]);
|
||||
|
||||
// Drag-to-select: mousedown → DOM mousemove → DOM mouseup
|
||||
useEffect(() => {
|
||||
if (!editor || !enabled) return;
|
||||
selectionDecRef.current = editor.createDecorationsCollection([]);
|
||||
|
||||
let dragStart = 0;
|
||||
let dragEnd = 0;
|
||||
|
||||
const finishDrag = () => {
|
||||
if (!isDraggingRef.current) return;
|
||||
isDraggingRef.current = false;
|
||||
document.removeEventListener('mousemove', onDomMouseMove);
|
||||
document.removeEventListener('mouseup', onDomMouseUp);
|
||||
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
const s = Math.min(dragStart, dragEnd);
|
||||
const e = Math.max(dragStart, dragEnd);
|
||||
const code = model.getValueInRange({
|
||||
startLineNumber: s, startColumn: 1,
|
||||
endLineNumber: e, endColumn: model.getLineMaxColumn(e),
|
||||
});
|
||||
setGutterSelection({ startLine: s, endLine: e });
|
||||
// Position popover right below the last selected line
|
||||
const pos = getLineBottomPosition(editor, e) ?? { x: 0, y: 0 };
|
||||
callbackRef.current({ range: { start: s, end: e }, code, position: pos });
|
||||
};
|
||||
|
||||
const onDomMouseMove = (ev: MouseEvent) => {
|
||||
if (!isDraggingRef.current) return;
|
||||
const target = editor.getTargetAtClientPoint(ev.clientX, ev.clientY);
|
||||
const line = target?.position?.lineNumber;
|
||||
if (!line) return;
|
||||
dragEnd = line;
|
||||
const s = Math.min(dragStart, dragEnd);
|
||||
const e = Math.max(dragStart, dragEnd);
|
||||
applySelectionDecos(selectionDecRef.current, s, e);
|
||||
setGutterSelection({ startLine: s, endLine: e });
|
||||
// Clear hover hint during drag — selection decos provide visual feedback
|
||||
hoverDecRef.current?.set([]);
|
||||
};
|
||||
|
||||
const onDomMouseUp = () => finishDrag();
|
||||
|
||||
const mouseDownSub = editor.onMouseDown((e) => {
|
||||
const line = e.target.position?.lineNumber;
|
||||
if (!isGutterTarget(e.target.type) || !line) return;
|
||||
if (commentedRef.current.has(line)) return;
|
||||
|
||||
// Shift-click extends from existing anchor
|
||||
if (e.event.shiftKey && anchorLineRef.current !== null) {
|
||||
dragStart = Math.min(anchorLineRef.current, line);
|
||||
dragEnd = Math.max(anchorLineRef.current, line);
|
||||
applySelectionDecos(selectionDecRef.current, dragStart, dragEnd);
|
||||
finishDrag();
|
||||
return;
|
||||
}
|
||||
|
||||
isDraggingRef.current = true;
|
||||
anchorLineRef.current = line;
|
||||
dragStart = line;
|
||||
dragEnd = line;
|
||||
applySelectionDecos(selectionDecRef.current, line, line);
|
||||
document.addEventListener('mousemove', onDomMouseMove);
|
||||
document.addEventListener('mouseup', onDomMouseUp);
|
||||
});
|
||||
|
||||
return () => {
|
||||
mouseDownSub.dispose();
|
||||
document.removeEventListener('mousemove', onDomMouseMove);
|
||||
document.removeEventListener('mouseup', onDomMouseUp);
|
||||
isDraggingRef.current = false;
|
||||
selectionDecRef.current?.set([]);
|
||||
};
|
||||
}, [editor, enabled]);
|
||||
|
||||
return { gutterSelection, clearGutterSelection };
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useMemo, useCallback } from 'react';
|
||||
import type { DiffComment } from './types';
|
||||
|
||||
/** Build a DiffComment object from common parameters */
|
||||
export function buildDiffComment(params: {
|
||||
filePath: string;
|
||||
sessionId: string;
|
||||
startLine: number;
|
||||
endLine: number;
|
||||
side: DiffComment['side'];
|
||||
annotation: string;
|
||||
codeContent?: string;
|
||||
}): DiffComment {
|
||||
return {
|
||||
id: `${params.filePath}-${Date.now()}`,
|
||||
sessionId: params.sessionId,
|
||||
filePath: params.filePath,
|
||||
startLine: Math.min(params.startLine, params.endLine),
|
||||
endLine: Math.max(params.startLine, params.endLine),
|
||||
side: params.side,
|
||||
codeContent: params.codeContent ?? '',
|
||||
annotation: params.annotation,
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'pending',
|
||||
};
|
||||
}
|
||||
|
||||
/** Compute the set of line numbers that have comments */
|
||||
export function useCommentedLines(comments: DiffComment[]): Set<number> {
|
||||
return useMemo(() => {
|
||||
const set = new Set<number>();
|
||||
for (const c of comments) {
|
||||
for (let l = c.startLine; l <= c.endLine; l++) set.add(l);
|
||||
}
|
||||
return set;
|
||||
}, [comments]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared delete/update callbacks that handle external-vs-internal branching.
|
||||
* Used by both Pierre diff-viewer and Monaco diff-viewer.
|
||||
*/
|
||||
export function useCommentActions(params: {
|
||||
removeComment: (commentId: string) => void;
|
||||
updateComment: (commentId: string, updates: Partial<DiffComment>) => void;
|
||||
setEditingComment: (id: string | null) => void;
|
||||
onCommentDelete?: (commentId: string) => void;
|
||||
onCommentUpdate?: (commentId: string, updates: Partial<DiffComment>) => void;
|
||||
externalComments?: DiffComment[];
|
||||
}) {
|
||||
const { removeComment, updateComment, setEditingComment, onCommentDelete, externalComments } = params;
|
||||
|
||||
const handleCommentDelete = useCallback(
|
||||
(commentId: string) => {
|
||||
if (onCommentDelete && externalComments !== undefined) {
|
||||
onCommentDelete(commentId);
|
||||
} else {
|
||||
removeComment(commentId);
|
||||
}
|
||||
},
|
||||
[removeComment, onCommentDelete, externalComments]
|
||||
);
|
||||
|
||||
const handleCommentUpdate = useCallback(
|
||||
(commentId: string, content: string) => {
|
||||
updateComment(commentId, { annotation: content });
|
||||
setEditingComment(null);
|
||||
},
|
||||
[updateComment, setEditingComment]
|
||||
);
|
||||
|
||||
return { handleCommentDelete, handleCommentUpdate };
|
||||
}
|
||||
@@ -20,9 +20,9 @@ const VALID_PROVIDERS: Record<EditorContext, EditorProvider[]> = {
|
||||
|
||||
const DEFAULT_PROVIDERS: Record<EditorContext, EditorProvider> = {
|
||||
'code-editor': 'monaco',
|
||||
'diff-viewer': 'monaco',
|
||||
'diff-viewer': 'pierre-diffs',
|
||||
'chat-code-block': 'monaco',
|
||||
'chat-diff': 'monaco',
|
||||
'chat-diff': 'pierre-diffs',
|
||||
'plan-editor': 'tiptap',
|
||||
};
|
||||
|
||||
@@ -46,6 +46,16 @@ export const useEditorResolverStore = create<EditorResolverStore>()(
|
||||
getProvider: (context) => get().providers[context],
|
||||
getValidProviders: (context) => VALID_PROVIDERS[context],
|
||||
}),
|
||||
{ name: 'kandev-editor-providers' }
|
||||
{
|
||||
name: 'kandev-editor-providers',
|
||||
version: 1,
|
||||
migrate: (persisted) => {
|
||||
const state = persisted as { providers: Record<EditorContext, EditorProvider> };
|
||||
return {
|
||||
...state,
|
||||
providers: { ...state.providers, 'diff-viewer': 'pierre-diffs', 'chat-diff': 'pierre-diffs' },
|
||||
};
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Centralized theme color palette.
|
||||
*
|
||||
* Change colors here to affect Monaco editor, Pierre diffs, xterm terminal,
|
||||
* and any other component that references these values.
|
||||
*
|
||||
* CSS variables in globals.css (--background, --foreground, --card, etc.)
|
||||
* define the same palette for Tailwind / CSS consumers. Keep them in sync
|
||||
* when changing values here.
|
||||
*/
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core palette — dark
|
||||
// ---------------------------------------------------------------------------
|
||||
export const DARK = {
|
||||
bg: '#141414',
|
||||
fg: '#d4d4d4',
|
||||
card: '#1c1c1c',
|
||||
border: '#2a2a2a',
|
||||
hover: '#333333',
|
||||
popover: '#222222',
|
||||
lineHighlight: '#1c1c1c',
|
||||
lineNumber: '#555555',
|
||||
lineNumberActive: '#888888',
|
||||
selection: '#264f78',
|
||||
selectionInactive: '#3a3d41',
|
||||
cursor: '#d4d4d4',
|
||||
scrollbarShadow: '#00000000',
|
||||
scrollbarThumb: '#64646480',
|
||||
scrollbarThumbHover: '#82828299',
|
||||
scrollbarThumbActive: '#828282bb',
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core palette — light
|
||||
// ---------------------------------------------------------------------------
|
||||
export const LIGHT = {
|
||||
bg: '#ffffff',
|
||||
fg: '#1e1e1e',
|
||||
card: '#ffffff',
|
||||
lineHighlight: '#f5f5f5',
|
||||
lineNumber: '#c0c0c0',
|
||||
lineNumberActive: '#555555',
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Git diff colors (shared across Monaco, Pierre, CSS --git-addition/deletion)
|
||||
// ---------------------------------------------------------------------------
|
||||
export const DIFF_COLORS = {
|
||||
addition: '#10b981', // emerald-500
|
||||
deletion: '#f43f5e', // rose-500
|
||||
/** Alpha variants for Monaco diff backgrounds */
|
||||
additionTextBg: '#10b98126',
|
||||
deletionTextBg: '#f43f5e26',
|
||||
additionLineBg: '#10b98115',
|
||||
deletionLineBg: '#f43f5e15',
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Font stack
|
||||
// ---------------------------------------------------------------------------
|
||||
export const FONT = {
|
||||
mono: '"Geist Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace',
|
||||
size: 12,
|
||||
lineHeight: 18,
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pierre diffs — Shiki syntax-highlighting themes
|
||||
// ---------------------------------------------------------------------------
|
||||
export const PIERRE_THEME = {
|
||||
dark: 'github-dark-high-contrast' as const,
|
||||
light: 'github-light' as const,
|
||||
};
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { editor } from 'monaco-editor';
|
||||
import { DARK, LIGHT, DIFF_COLORS, FONT } from './colors';
|
||||
|
||||
// Semantic token color rules matching VS Code Dark+ / Light+ themes.
|
||||
// These color function names, types, variables, etc. when an LSP server
|
||||
// provides semantic tokens (textDocument/semanticTokens/full).
|
||||
const SEMANTIC_RULES_DARK: editor.ITokenThemeRule[] = [
|
||||
// Types — teal
|
||||
{ token: 'type', foreground: '4EC9B0' },
|
||||
{ token: 'class', foreground: '4EC9B0' },
|
||||
{ token: 'struct', foreground: '4EC9B0' },
|
||||
@@ -12,21 +10,17 @@ const SEMANTIC_RULES_DARK: editor.ITokenThemeRule[] = [
|
||||
{ token: 'enum', foreground: '4EC9B0' },
|
||||
{ token: 'typeParameter', foreground: '4EC9B0' },
|
||||
{ token: 'namespace', foreground: '4EC9B0' },
|
||||
// Functions — yellow
|
||||
{ token: 'function', foreground: 'DCDCAA' },
|
||||
{ token: 'method', foreground: 'DCDCAA' },
|
||||
{ token: 'macro', foreground: 'DCDCAA' },
|
||||
// Variables — light blue
|
||||
{ token: 'variable', foreground: '9CDCFE' },
|
||||
{ token: 'parameter', foreground: '9CDCFE' },
|
||||
{ token: 'property', foreground: '9CDCFE' },
|
||||
{ token: 'enumMember', foreground: '4FC1FF' },
|
||||
// Decorators / annotations
|
||||
{ token: 'decorator', foreground: 'DCDCAA' },
|
||||
];
|
||||
|
||||
const SEMANTIC_RULES_LIGHT: editor.ITokenThemeRule[] = [
|
||||
// Types — dark teal
|
||||
{ token: 'type', foreground: '267f99' },
|
||||
{ token: 'class', foreground: '267f99' },
|
||||
{ token: 'struct', foreground: '267f99' },
|
||||
@@ -34,16 +28,13 @@ const SEMANTIC_RULES_LIGHT: editor.ITokenThemeRule[] = [
|
||||
{ token: 'enum', foreground: '267f99' },
|
||||
{ token: 'typeParameter', foreground: '267f99' },
|
||||
{ token: 'namespace', foreground: '267f99' },
|
||||
// Functions — brown
|
||||
{ token: 'function', foreground: '795E26' },
|
||||
{ token: 'method', foreground: '795E26' },
|
||||
{ token: 'macro', foreground: '795E26' },
|
||||
// Variables — dark blue
|
||||
{ token: 'variable', foreground: '001080' },
|
||||
{ token: 'parameter', foreground: '001080' },
|
||||
{ token: 'property', foreground: '001080' },
|
||||
{ token: 'enumMember', foreground: '0070C1' },
|
||||
// Decorators
|
||||
{ token: 'decorator', foreground: '795E26' },
|
||||
];
|
||||
|
||||
@@ -52,29 +43,29 @@ export const KANDEV_MONACO_DARK: editor.IStandaloneThemeData = {
|
||||
inherit: true,
|
||||
rules: [...SEMANTIC_RULES_DARK],
|
||||
colors: {
|
||||
'editor.background': '#141414',
|
||||
'editor.foreground': '#d4d4d4',
|
||||
'editorGutter.background': '#141414',
|
||||
'editor.lineHighlightBackground': '#1c1c1c',
|
||||
'editorLineNumber.foreground': '#555555',
|
||||
'editorLineNumber.activeForeground': '#888888',
|
||||
'editor.selectionBackground': '#264f78',
|
||||
'editor.inactiveSelectionBackground': '#3a3d41',
|
||||
'editorCursor.foreground': '#d4d4d4',
|
||||
'editorWidget.background': '#222222',
|
||||
'editorWidget.border': '#2a2a2a',
|
||||
'editorSuggestWidget.background': '#222222',
|
||||
'editorSuggestWidget.border': '#2a2a2a',
|
||||
'editorSuggestWidget.selectedBackground': '#264f78',
|
||||
'minimap.background': '#141414',
|
||||
'scrollbar.shadow': '#00000000',
|
||||
'scrollbarSlider.background': '#64646480',
|
||||
'scrollbarSlider.hoverBackground': '#82828299',
|
||||
'scrollbarSlider.activeBackground': '#828282bb',
|
||||
'diffEditor.insertedTextBackground': '#10b98126',
|
||||
'diffEditor.removedTextBackground': '#f43f5e26',
|
||||
'diffEditor.insertedLineBackground': '#10b98115',
|
||||
'diffEditor.removedLineBackground': '#f43f5e15',
|
||||
'editor.background': DARK.bg,
|
||||
'editor.foreground': DARK.fg,
|
||||
'editorGutter.background': DARK.bg,
|
||||
'editor.lineHighlightBackground': DARK.lineHighlight,
|
||||
'editorLineNumber.foreground': DARK.lineNumber,
|
||||
'editorLineNumber.activeForeground': DARK.lineNumberActive,
|
||||
'editor.selectionBackground': DARK.selection,
|
||||
'editor.inactiveSelectionBackground': DARK.selectionInactive,
|
||||
'editorCursor.foreground': DARK.cursor,
|
||||
'editorWidget.background': DARK.popover,
|
||||
'editorWidget.border': DARK.border,
|
||||
'editorSuggestWidget.background': DARK.popover,
|
||||
'editorSuggestWidget.border': DARK.border,
|
||||
'editorSuggestWidget.selectedBackground': DARK.selection,
|
||||
'minimap.background': DARK.bg,
|
||||
'scrollbar.shadow': DARK.scrollbarShadow,
|
||||
'scrollbarSlider.background': DARK.scrollbarThumb,
|
||||
'scrollbarSlider.hoverBackground': DARK.scrollbarThumbHover,
|
||||
'scrollbarSlider.activeBackground': DARK.scrollbarThumbActive,
|
||||
'diffEditor.insertedTextBackground': DIFF_COLORS.additionTextBg,
|
||||
'diffEditor.removedTextBackground': DIFF_COLORS.deletionTextBg,
|
||||
'diffEditor.insertedLineBackground': DIFF_COLORS.additionLineBg,
|
||||
'diffEditor.removedLineBackground': DIFF_COLORS.deletionLineBg,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -83,25 +74,19 @@ export const KANDEV_MONACO_LIGHT: editor.IStandaloneThemeData = {
|
||||
inherit: true,
|
||||
rules: [...SEMANTIC_RULES_LIGHT],
|
||||
colors: {
|
||||
'editor.background': '#ffffff',
|
||||
'editor.foreground': '#1e1e1e',
|
||||
'editorGutter.background': '#ffffff',
|
||||
'editor.lineHighlightBackground': '#f5f5f5',
|
||||
'editorLineNumber.foreground': '#c0c0c0',
|
||||
'editorLineNumber.activeForeground': '#555555',
|
||||
'diffEditor.insertedTextBackground': '#10b98126',
|
||||
'diffEditor.removedTextBackground': '#f43f5e26',
|
||||
'diffEditor.insertedLineBackground': '#10b98115',
|
||||
'diffEditor.removedLineBackground': '#f43f5e15',
|
||||
'editor.background': LIGHT.bg,
|
||||
'editor.foreground': LIGHT.fg,
|
||||
'editorGutter.background': LIGHT.bg,
|
||||
'editor.lineHighlightBackground': LIGHT.lineHighlight,
|
||||
'editorLineNumber.foreground': LIGHT.lineNumber,
|
||||
'editorLineNumber.activeForeground': LIGHT.lineNumberActive,
|
||||
'diffEditor.insertedTextBackground': DIFF_COLORS.additionTextBg,
|
||||
'diffEditor.removedTextBackground': DIFF_COLORS.deletionTextBg,
|
||||
'diffEditor.insertedLineBackground': DIFF_COLORS.additionLineBg,
|
||||
'diffEditor.removedLineBackground': DIFF_COLORS.deletionLineBg,
|
||||
},
|
||||
};
|
||||
|
||||
export const PIERRE_DIFFS_THEME = {
|
||||
dark: 'github-dark-high-contrast' as const,
|
||||
light: 'github-light' as const,
|
||||
};
|
||||
|
||||
export const EDITOR_FONT_FAMILY =
|
||||
'"Geist Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace';
|
||||
export const EDITOR_FONT_SIZE = 12;
|
||||
export const EDITOR_LINE_HEIGHT = 18;
|
||||
export const EDITOR_FONT_FAMILY = FONT.mono;
|
||||
export const EDITOR_FONT_SIZE = FONT.size;
|
||||
export const EDITOR_LINE_HEIGHT = FONT.lineHeight;
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"@kandev/ui": "workspace:*",
|
||||
"@lezer/highlight": "^1.2.3",
|
||||
"@monaco-editor/react": "^4.7.0",
|
||||
"@pierre/diffs": "^1.0.10",
|
||||
"@pierre/diffs": "^1.0.11",
|
||||
"@tabler/icons-react": "^3.36.1",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
|
||||
Reference in New Issue
Block a user