From f49158aeb2fc624cdd3de252f23a3e4295d100e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Tue, 17 Feb 2026 19:37:53 +0000 Subject: [PATCH] feat: improve monaco comments (#241) --- apps/pnpm-lock.yaml | 10 +- apps/web/app/globals.css | 81 ++- apps/web/app/layout.tsx | 3 + .../components/diff-worker-pool-provider.tsx | 41 ++ apps/web/components/diff/comment-display.tsx | 37 +- .../components/diff/diff-header-toolbar.tsx | 127 +++++ .../components/diff/diff-viewer-resolver.tsx | 6 + apps/web/components/diff/diff-viewer.tsx | 519 +++++++++--------- apps/web/components/diff/file-diff-viewer.tsx | 24 +- apps/web/components/diff/hunk-action-bar.tsx | 60 ++ apps/web/components/diff/index.ts | 1 + .../components/editors/lsp-status-button.tsx | 82 +++ .../monaco/diff-viewer-context-menu.tsx | 71 +++ .../editors/monaco/diff-viewer-toolbar.tsx | 118 ++++ .../editors/monaco/monaco-code-editor.tsx | 400 ++++++++------ .../editors/monaco/monaco-diff-viewer.tsx | 507 +++++++---------- .../editors/monaco/use-diff-view-zones.ts | 134 +++++ .../editors/pierre/pierre-diff-viewer.tsx | 2 +- .../components/review/review-diff-list.tsx | 24 + .../components/task/comment-view-popover.tsx | 77 ++- .../task/editor-comment-popover.tsx | 131 +++-- .../components/task/passthrough-terminal.tsx | 2 +- apps/web/components/task/shell-terminal.tsx | 2 +- apps/web/hooks/use-diff-editor-height.ts | 64 +++ .../hooks/use-editor-view-zone-comments.ts | 68 +++ apps/web/hooks/use-global-view-mode.ts | 35 ++ apps/web/hooks/use-gutter-comments.ts | 192 +++++++ apps/web/lib/diff/comment-utils.ts | 73 +++ apps/web/lib/state/editor-resolver-store.ts | 16 +- apps/web/lib/theme/colors.ts | 74 +++ apps/web/lib/theme/editor-theme.ts | 89 ++- apps/web/lib/{ => theme}/terminal-theme.ts | 0 apps/web/package.json | 2 +- 33 files changed, 2128 insertions(+), 944 deletions(-) create mode 100644 apps/web/components/diff-worker-pool-provider.tsx create mode 100644 apps/web/components/diff/diff-header-toolbar.tsx create mode 100644 apps/web/components/diff/hunk-action-bar.tsx create mode 100644 apps/web/components/editors/lsp-status-button.tsx create mode 100644 apps/web/components/editors/monaco/diff-viewer-context-menu.tsx create mode 100644 apps/web/components/editors/monaco/diff-viewer-toolbar.tsx create mode 100644 apps/web/components/editors/monaco/use-diff-view-zones.ts create mode 100644 apps/web/hooks/use-diff-editor-height.ts create mode 100644 apps/web/hooks/use-editor-view-zone-comments.ts create mode 100644 apps/web/hooks/use-global-view-mode.ts create mode 100644 apps/web/hooks/use-gutter-comments.ts create mode 100644 apps/web/lib/diff/comment-utils.ts create mode 100644 apps/web/lib/theme/colors.ts rename apps/web/lib/{ => theme}/terminal-theme.ts (100%) diff --git a/apps/pnpm-lock.yaml b/apps/pnpm-lock.yaml index 4615b67904..6df4707481 100644 --- a/apps/pnpm-lock.yaml +++ b/apps/pnpm-lock.yaml @@ -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 diff --git a/apps/web/app/globals.css b/apps/web/app/globals.css index c9579d1788..97cf5df011 100644 --- a/apps/web/app/globals.css +++ b/apps/web/app/globals.css @@ -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,"); -webkit-mask-image: url("data:image/svg+xml;utf8,"); @@ -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 */ diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index dbc2e18d19..9954c2d7e4 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -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} + @@ -77,6 +79,7 @@ export default function RootLayout({ + diff --git a/apps/web/components/diff-worker-pool-provider.tsx b/apps/web/components/diff-worker-pool-provider.tsx new file mode 100644 index 0000000000..c40d168b00 --- /dev/null +++ b/apps/web/components/diff-worker-pool-provider.tsx @@ -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 ( + + + {children} + + ); +} diff --git a/apps/web/components/diff/comment-display.tsx b/apps/web/components/diff/comment-display.tsx index fb541ee00d..33faadd35b 100644 --- a/apps/web/components/diff/comment-display.tsx +++ b/apps/web/components/diff/comment-display.tsx @@ -29,23 +29,38 @@ export function CommentDisplay({ if (compact) { return ( -
+
{lineRange} · {comment.annotation}
- {onDelete && ( - - )} +
+ {onEdit && ( + + )} + {onDelete && ( + + )} +
); } diff --git a/apps/web/components/diff/diff-header-toolbar.tsx b/apps/web/components/diff/diff-header-toolbar.tsx new file mode 100644 index 0000000000..4857480f52 --- /dev/null +++ b/apps/web/components/diff/diff-header-toolbar.tsx @@ -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 ( +
+ + + + + Copy diff + + + {onRevert && ( + + + + + Revert changes + + )} + + + + + + Toggle word wrap + + + + + + + + {viewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'} + + + + {onOpenFile && ( + + + + + Edit + + )} +
+ ); + }, + [filePath, diff, wordWrap, onToggleWordWrap, viewMode, onToggleViewMode, onOpenFile, onRevert] + ); + + return renderHeaderMetadata; +} diff --git a/apps/web/components/diff/diff-viewer-resolver.tsx b/apps/web/components/diff/diff-viewer-resolver.tsx index f995db1a51..aa8456130c 100644 --- a/apps/web/components/diff/diff-viewer-resolver.tsx +++ b/apps/web/components/diff/diff-viewer-resolver.tsx @@ -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) { diff --git a/apps/web/components/diff/diff-viewer.tsx b/apps/web/components/diff/diff-viewer.tsx index ef42727998..9374f1aded 100644 --- a/apps/web/components/diff/diff-viewer.tsx +++ b/apps/web/components/diff/diff-viewer.tsx @@ -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; 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(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[]>(() => { + // Parse initial diff metadata + const initialDiffMetadata = useMemo(() => { + 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>(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>(new Map()); + const hideTimeoutRef = useRef | null>(null); + + // Annotations: comments, new comment form, and hunk accept/reject + const { annotations, lineMap, revertMap } = useMemo(() => { const result: DiffLineAnnotation[] = 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(); + const newRevertMap = new Map(); + 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(null); + const activeBlockRef = useRef(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): ReactNode => { - const { type, comment, isEditing } = annotation.metadata; + const { type, comment, isEditing, changeBlockId } = annotation.metadata; + + if (type === 'hunk-actions' && changeBlockId) { + return ( + 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 ( -
- {/* Copy diff button */} - - - - - Copy diff - - - {/* Revert button (non-functional placeholder) */} - - - - - Revert changes - - - {/* Word wrap toggle */} - - - - - Toggle word wrap - - - {/* Split/Unified toggle (global) */} - - - - - - {globalViewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'} - - - - {/* Open in editor button */} - {onOpenFile && ( - - - - - Edit - - )} -
- ); - }, - [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 (
>( () => ({ 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(() => { - 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 ( -
+
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} /> ); diff --git a/apps/web/components/diff/hunk-action-bar.tsx b/apps/web/components/diff/hunk-action-bar.tsx new file mode 100644 index 0000000000..5c16c3634b --- /dev/null +++ b/apps/web/components/diff/hunk-action-bar.tsx @@ -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; + 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 ( +
+
+ +
+
+ ); +} diff --git a/apps/web/components/diff/index.ts b/apps/web/components/diff/index.ts index d31f473f95..1a87e65b0c 100644 --- a/apps/web/components/diff/index.ts +++ b/apps/web/components/diff/index.ts @@ -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'; diff --git a/apps/web/components/editors/lsp-status-button.tsx b/apps/web/components/editors/lsp-status-button.tsx new file mode 100644 index 0000000000..18dcf8524a --- /dev/null +++ b/apps/web/components/editors/lsp-status-button.tsx @@ -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 = { + disabled: , + connecting: , + installing: , + starting: , + ready: , + stopping: , + unavailable: , + error: , +}; + +const STATIC_CONFIGS: Record = { + 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 ( + + + + + {c.tooltip} + + ); +} diff --git a/apps/web/components/editors/monaco/diff-viewer-context-menu.tsx b/apps/web/components/editors/monaco/diff-viewer-context-menu.tsx new file mode 100644 index 0000000000..d8b4e5b4df --- /dev/null +++ b/apps/web/components/editors/monaco/diff-viewer-context-menu.tsx @@ -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; + 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 ( +
e.stopPropagation()} + > + + {contextMenu.isChangedLine && ( + + )} + {onRevert && ( + <> +
+ + + )} +
+ ); +} diff --git a/apps/web/components/editors/monaco/diff-viewer-toolbar.tsx b/apps/web/components/editors/monaco/diff-viewer-toolbar.tsx new file mode 100644 index 0000000000..95589b75ef --- /dev/null +++ b/apps/web/components/editors/monaco/diff-viewer-toolbar.tsx @@ -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 ( +
+ {data.filePath} +
+ + + + + Copy diff + + + + + + {foldUnchanged ? 'Show all lines' : 'Fold unchanged lines'} + + {onRevert && ( + + + + + Revert changes + + )} + + + + + Toggle word wrap + + + + + + {globalViewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'} + + {onOpenFile && ( + + + + + Edit + + )} +
+
+ ); +} diff --git a/apps/web/components/editors/monaco/monaco-code-editor.tsx b/apps/web/components/editors/monaco/monaco-code-editor.tsx index 24e95bb190..9795b73df5 100644 --- a/apps/web/components/editors/monaco/monaco-code-editor.tsx +++ b/apps/web/components/editors/monaco/monaco-code-editor.tsx @@ -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 = { - disabled: { - icon: , - tooltip: 'LSP: Off \u2014 click to start', - clickable: true, - }, - connecting: { - icon: , - tooltip: 'LSP: Connecting...', - clickable: true, - }, - installing: { - icon: , - tooltip: 'LSP: Installing language server...', - clickable: false, - }, - starting: { - icon: , - tooltip: 'LSP: Starting language server...', - clickable: true, - }, - ready: { - icon: , - tooltip: 'LSP: Connected \u2014 click to stop', - clickable: true, - }, - stopping: { - icon: , - tooltip: 'LSP: Stopping...', - clickable: false, - }, - unavailable: { - icon: , - tooltip: `LSP: ${'reason' in status ? status.reason : 'Unavailable'}`, - clickable: true, - }, - error: { - icon: , - tooltip: `LSP: ${'reason' in status ? status.reason : 'Error'}`, - clickable: true, - }, - }; - - const c = configs[status.state]; - if (!c) return null; - - return ( - - - - - {c.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(null); + const [formZoneRange, setFormZoneRange] = useState(null); const [floatingButtonPos, setFloatingButtonPos] = useState(null); const [currentSelection, setCurrentSelection] = useState<{ text: string; startLine: number; endLine: number } | null>(null); - const [commentView, setCommentView] = useState(null); const [showDiffIndicators, setShowDiffIndicators] = useState(true); + const [editorInstance, setEditorInstance] = useState(null); const editorRef = useRef(null); const wrapperRef = useRef(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(null); const diffDecorationsRef = useRef(null); const disposablesRef = useRef([]); 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 ? ( +
+ handleCommentUpdateRef.current(comment.id, c)} + onCancel={() => setEditingComment(null)} + isEditing + /> +
+ ) : ( +
+ handleCommentDeleteRef.current(comment.id)} + onEdit={() => setEditingComment(comment.id)} + showCode={false} + compact + /> +
+ ); + addZone(comment.endLine, isEditing ? 120 : 32, node); + } + + // New comment form + if (formZoneRange) { + addZone( + formZoneRange.endLine, 120, +
+ handleCommentSubmitRef.current(c)} + onCancel={() => { + setFormZoneRange(null); + clearGutterSelection(); + }} + /> +
, + ); + } + }, + ); // 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 && ( )} - - {textSelection && ( - - )} - - {commentView && ( - - )}
); diff --git a/apps/web/components/editors/monaco/monaco-diff-viewer.tsx b/apps/web/components/editors/monaco/monaco-diff-viewer.tsx index ca8c6e5b3b..0d8fdd97d7 100644 --- a/apps/web/components/editors/monaco/monaco-diff-viewer.tsx +++ b/apps/web/components/editors/monaco/monaco-diff-viewer.tsx @@ -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(null); const wrapperRef = useRef(null); + const { setOpen: setCommandPanelOpen } = useCommandPanelOpen(); + const [modifiedEditor, setModifiedEditor] = useState(null); + const [originalEditor, setOriginalEditor] = useState(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(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 (
- {/* Toolbar */} {showHeader && ( -
- {data.filePath} -
- - - - - Copy diff - - - - - - {foldUnchanged ? 'Show all lines' : 'Fold unchanged lines'} - - {onRevert && ( - - - - - Revert changes - - )} - - - - - Toggle word wrap - - - - - - {globalViewMode === 'split' ? 'Switch to unified view' : 'Switch to split view'} - - {onOpenFile && ( - - - - - Edit - - )} -
-
+ navigator.clipboard.writeText(data.diff || '')} + onOpenFile={onOpenFile} + onRevert={onRevert} + /> )} - {/* Diff editor */}
- {/* Comment annotations below the diff */} - {comments.length > 0 && ( -
- {comments.map((comment) => ( -
- {editingCommentId === comment.id ? ( - handleCommentUpdate(comment.id, content)} - onCancel={() => setEditingComment(null)} - isEditing - /> - ) : ( - handleCommentDelete(comment.id)} - onEdit={() => setEditingComment(comment.id)} - showCode={false} - /> - )} -
- ))} -
- )} - - {/* New comment form */} - {showCommentForm && selectedLineRange && ( -
- { - setShowCommentForm(false); - setSelectedLineRange(null); - }} - /> -
- )} - - {/* Context menu */} {contextMenu && ( -
e.stopPropagation()} - > - - {contextMenu.isChangedLine && ( - - )} - {onRevert && ( - <> -
- - - )} -
+ setContextMenu(null)} + onRevert={onRevert} + filePath={data.filePath} + /> )}
); } + +// --- 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') }; +} + diff --git a/apps/web/components/editors/monaco/use-diff-view-zones.ts b/apps/web/components/editors/monaco/use-diff-view-zones.ts new file mode 100644 index 0000000000..e86a50403e --- /dev/null +++ b/apps/web/components/editors/monaco/use-diff-view-zones.ts @@ -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([]); + + 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]); +} diff --git a/apps/web/components/editors/pierre/pierre-diff-viewer.tsx b/apps/web/components/editors/pierre/pierre-diff-viewer.tsx index c6d06da4dd..7456e85d05 100644 --- a/apps/web/components/editors/pierre/pierre-diff-viewer.tsx +++ b/apps/web/components/editors/pierre/pierre-diff-viewer.tsx @@ -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'; diff --git a/apps/web/components/review/review-diff-list.tsx b/apps/web/components/review/review-diff-list.tsx index e1b9b96a82..5cbbc4612b 100644 --- a/apps/web/components/review/review-diff-list.tsx +++ b/apps/web/components/review/review-diff-list.tsx @@ -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 (
{/* 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} diff --git a/apps/web/components/task/comment-view-popover.tsx b/apps/web/components/task/comment-view-popover.tsx index 981f37396d..8793eb76a4 100644 --- a/apps/web/components/task/comment-view-popover.tsx +++ b/apps/web/components/task/comment-view-popover.tsx @@ -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(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 */} +
+ + {comments.length} comment{comments.length !== 1 ? 's' : ''} + + +
+ {/* Comments list */}
{comments.map((comment) => ( diff --git a/apps/web/components/task/editor-comment-popover.tsx b/apps/web/components/task/editor-comment-popover.tsx index 4b4fdadb61..04dfff2253 100644 --- a/apps/web/components/task/editor-comment-popover.tsx +++ b/apps/web/components/task/editor-comment-popover.tsx @@ -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(null); const popoverRef = useRef(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 (
- {/* Line range badge */} -
+ {/* Drag handle */} +
{lineRangeText} +
- {/* Code preview */} -
-        {previewText}
-      
+
+ {/* Code preview */} +
+          {previewText}
+        
- {/* Comment input */} -