diff --git a/.helder/config.default.json b/.helder/config.default.json index 1f201ad..c857303 100644 --- a/.helder/config.default.json +++ b/.helder/config.default.json @@ -6,14 +6,13 @@ "editor": { "autoSave": false, "tabSize": 4, - "wordWrap": "markdown", - "copyOnSelect": true + "wordWrap": "markdown" }, "git": { "confirmDiscard": true, "confirmStage": false, "confirmUnstage": false, - "defaultDiffMode": "diff", + "defaultDiffMode": "updated", "refreshInterval": 10000 }, "files": { diff --git a/CLAUDE.md b/CLAUDE.md index bc41b39..c5e7b3d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,11 +4,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project state -**Phase 1 is scaffolded.** An `electron-vite` + React 18 + TypeScript app now lives at the repo root (`src/main`, `src/preload`, `src/renderer`). The prototype has been ported faithfully and renders against the **mock data** — full UI, git panel, four diff modes + Split, search, and the *simulated* terminals are all working. IBM Plex Mono + IBM Plex Sans are bundled locally via `@fontsource/ibm-plex-mono` and `@fontsource/ibm-plex-sans`; Prism is wired with the correct `markup-templating`→`php` load order; the renderer↔main clipboard bridge is in place (`src/preload/index.ts`). +**Phase 1 is scaffolded.** An `electron-vite` + React 18 + TypeScript app now lives at the repo root (`src/main`, `src/preload`, `src/renderer`). The prototype has been ported faithfully and renders against the **mock data** — full UI, git panel, the view modes, search, and the *simulated* terminals are all working. IBM Plex Mono + IBM Plex Sans are bundled locally via `@fontsource/ibm-plex-mono` and `@fontsource/ibm-plex-sans`; Prism is wired with the correct `markup-templating`→`php` load order; the renderer↔main clipboard bridge is in place (`src/preload/index.ts`). **Phase 2 (real integrations) — complete; DESIGN.md fully implemented.** The app is feature-complete against the functional spec (the only intentional exception is the separate Go-to-File overlay — `⌘P` aliases the unified search instead, per the resolved decision). Editor is writable (save · autosave · dirty tabs · discard); session restore brings back open tabs/active/view modes; close-dirty prompts Save/Don't-Save/Cancel. There's a vitest suite (`npm test`, 51 tests) + ESLint + electron-builder packaging. All over IPC through the preload bridge (`src/preload/index.ts`): - **Filesystem** — tree + in-memory content index, `chokidar` watch (`src/main/fs-service.ts`). The tree/index/search share one source of truth: `rg --files` (honors gitignore + `files.exclude`, includes dotfiles), with a recursive-walk fallback when ripgrep is unavailable. -- **Git** — `simple-git`: status→A/M/D/R, the four diff views from HEAD-vs-worktree pairs, stage/unstage/commit/discard (`src/main/git-service.ts`). +- **Git** — `simple-git`: status→A/M/D/R, the diff views from HEAD-vs-worktree pairs, stage/unstage/commit/discard (`src/main/git-service.ts`). - **Terminals** — real PTYs via `node-pty` (`src/main/pty-service.ts`) rendered with `@xterm/xterm` (`src/renderer/src/terminals.tsx`). Agent pane is a shell that auto-launches `claude`; bottom pane is a plain shell. Pass-on-to-Agent writes bracketed paste (`\x1b[200~ … \x1b[201~`) to the agent PTY. node-pty is native — `npm run rebuild` (also a `postinstall`) rebuilds it for Electron; it's N-API so the binary is portable. - **Config** — `.helder/` per project (`src/main/config.ts`): `config.default.json` regenerated on launch (full defaults / live docs), sparse `config.json` deep-merged over it, and `theme.css` (created once, never overwritten) injected over the built-in dark theme. The **code font + size are CSS vars** (`--code-font`/`--code-size`/`--term-size`) the editor + xterm read, overridable from `theme.css`. ai command/autoLaunch + shell flow from config into the PTYs; a `.helder` file watcher hot-reloads config/theme. @@ -17,7 +17,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co The renderer consumes FS/git/config/search via the store in `src/renderer/src/project.tsx` (`useProject` / `useProjectActions`), which falls back to the mock + default config when `window.helder` is absent (browser preview). `src/main/index.ts` registers all IPC handlers + the debounced watchers. -- **Editing** — the `code`/`updated` modes are a writable buffer: a transparent textarea over a Prism-highlighted `
` with a scroll-synced gutter (`CodeEditor` in `editor.tsx`). `⌘S` saves to disk (`fs:write`), `editor.autoSave` debounce-saves on change, tabs show the dirty dot, and the git-row context menu has **Discard changes** gated by `git.confirmDiscard`. Original/Diff/Split stay read-only review views.
+- **Editing** — the `code`/`updated` modes are a writable buffer: a transparent textarea over a Prism-highlighted `
` with a scroll-synced gutter (`CodeEditor` in `editor.tsx`). `⌘S` saves to disk (`fs:write`), `editor.autoSave` debounce-saves on change, tabs show the dirty dot, and the git-row context menu has **Discard changes** gated by `git.confirmDiscard`. Original stays a read-only review view; Actual marks the changed lines in place, and Diff is the full-screen side-by-side view.
 
 README steps 1–7 plus config + editing are all implemented for real. The editable overlay keeps the caret in view (the textarea is overflow-hidden under the scroller, so `CodeEditor` scrolls the container on input/keyup/click).
 
@@ -47,9 +47,9 @@ A dark-only (no light mode, no theme toggle) Electron desktop code workbench for
 - **Prism PHP load order:** `prism-php` requires `prism-markup-templating` to be loaded **first**, or every `Prism.highlight` call throws and silently falls back to plain text.
 - **Preload must be CommonJS `index.cjs`** and `main` must load `../preload/index.cjs` (see `electron.vite.config.ts` preload `rollupOptions.output`). If they mismatch (or you let it build as `.mjs`), Electron silently loads no preload, `window.helder` is undefined, and the renderer silently falls back to mock data + the "terminal not available" message. Keep the filename and the `main` path in sync.
 - **chokidar is pinned to v3 on purpose — do NOT bump to v4/v5.** chokidar ≥4 dropped the `fsevents` addon and watches recursively via libuv's native `fs.watch({recursive:true})`. On macOS that recursive watcher poisons the process's file descriptors, so every later `child_process.spawn` (i.e. every `git` call) fails with `spawn EBADF` (errno -9) and the git column silently stops updating. v3 uses the `fsevents` native addon instead and has no such conflict. If you must move to v4+, switch the main project watcher to `usePolling: true` (the only other config proven to avoid the EBADF here).
-- **Word wrap swaps the buffer's layout, it is not just a CSS switch** (`editor.wordWrap`: `markdown` default / `on` / `off`). Unwrapped, `CodeEditor` renders one highlighted blob and a separate gutter column that follows the scroll. Wrapped, a fixed 20px-per-line gutter no longer lines up, so each line becomes a `.ce-line` block and the number is a CSS counter on `::before` — that keeps it on the first visual row and leaves folded rows blank. Two things bite here: `.ce-inner` must drop `width:max-content` (and `.editor` its `max-content` grid track), or a folded line still measures its full unfolded width and never breaks; and the textarea and the `
` must fold identically — same width, padding, font, `white-space:pre-wrap`, `overflow-wrap:break-word` — or the caret drifts off the text. Split view stays unwrapped on purpose: its panes align row by row.
+- **Word wrap swaps the buffer's layout, it is not just a CSS switch** (`editor.wordWrap`: `markdown` default / `on` / `off`). Unwrapped, `CodeEditor` renders one highlighted blob and a separate gutter column that follows the scroll. Wrapped, a fixed 20px-per-line gutter no longer lines up, so each line becomes a `.ce-line` block and the number is a CSS counter on `::before` — that keeps it on the first visual row and leaves folded rows blank. Two things bite here: `.ce-inner` must drop `width:max-content` (and `.editor` its `max-content` grid track), or a folded line still measures its full unfolded width and never breaks; and the textarea and the `
` must fold identically — same width, padding, font, `white-space:pre-wrap`, `overflow-wrap:break-word` — or the caret drifts off the text. The full-screen Diff never wraps on purpose: its two panes align row by row. The hover original panel must fold at the same points as the editor, or the old line does not stay level with the current line.
 - **Pass on to Agent uses bracketed paste.** Write inserts to the agent PTY wrapped in `\x1b[200~ … \x1b[201~` so the `claude` CLI treats it as *pasted, unsubmitted* input. Insert must never submit — it lands as a new line so the user can stack several references before sending.
-- **The four diff view modes (Original / Updated / Diff / Split) all derive from one original-text + updated-text pair per changed file.** The prototype computes this with an LCS line diff (`buildDiff()` in `design/src/data.js`); production should prefer real `git diff` output but keep the same four derived views and the same color language everywhere: **red = removed/changed-from, green = added/changed-to**, syntax highlighting on in all modes.
+- **The three view modes (Actual / Original / Diff), plus Preview for markdown, all derive from one original-text + updated-text pair per changed file.** The prototype computes the pair with an LCS line diff (`buildDiff()` in `design/src/data.js`); production should prefer real `git diff` output. **Actual is the writable buffer, and it marks the changed lines in place.** A marked row takes the teal `--add` tint, a 2px `--add` left rule, and a teal line number. There is no `+` glyph, no sign column, and no second row. The removed lines appear on hover: `mouseenter` on a marked line opens a 496px panel with a 2px `--del` left border over the agent + terminal column, and `mouseleave` closes it. The panel holds the whole original file and scrolls so the previous version of the hovered line sits level with the hovered line. There is no click, no pin, and no animation. A pure deletion has no current line to mark, so the neighbouring current line takes a 2px `--del` rule on its edge and opens the same panel. **Diff is the full-screen side-by-side view**: it covers the whole application, original left, updated right, lines aligned, and `Esc` returns to the previous mode. The old separate **Split** button is gone, and the `Diff` segment opens that view instead. `git.defaultDiffMode` defaults to `'updated'` (Actual), so a click on a changed git row opens the file in Actual. The git context menu's **Open diff** is the explicit way into the full-screen view. The colour language is token-based everywhere: **teal `--add` is what the file holds now, amber-deep `--del` is what it held before** — never green, never red. Syntax highlighting stays on in all modes. The design source for the marked lines and the hover panel is `design_handoff_helder_inline_diff/` (README.md + `03b-in-pane-diff.html`).
 - **The agent pane is just a terminal running the `claude` CLI** (`ai.command`, default `claude`, auto-launched when `ai.autoLaunch` is on). The bottom pane is a normal shell PTY. The prototype's simulated agent session (`agentSeed`, `runAgent`, `bootAgent` in `terminals.jsx`) exists only to show the visual style — keep the styling, drop the fakery.
 - **Chrome budget:** title bar + tab strip + panel headers + status bar combined should stay ≈10% of vertical height. Keep it minimal.
 - **`console.*` is not a log — use the logger.** Helder runs one process per project window, and every window past the first is spawned by `spawnInstance()` with `stdio: 'ignore'`; launched from Finder there's no terminal either. Console output is therefore discarded in real use. Log through `src/main/logger.ts` (main) or `src/renderer/src/log.ts` → `rlog` (renderer, forwarded over IPC to the same file). Never add a bare `catch {}` on an IPC/FS/git path: log the cause, then handle it.
@@ -104,7 +104,7 @@ The older `design_handoff_helder_workbench/` prototype is superseded by `docs/de
 1. Electron shell + frameless dark window; port tokens to CSS vars; bundle IBM Plex.
 2. Static layout: four resizable columns + title/status bars.
 3. Real file tree + open files into tabs (read-only) with Prism highlighting.
-4. Git panel from `git status` (read-only) → staging + commit → the four diff modes + Split.
+4. Git panel from `git status` (read-only) → staging + commit → the three view modes, the hover original panel, and the full-screen Diff.
 5. Search (ripgrep + fuzzy).
 6. Terminals via node-pty + xterm.js; run `claude` in the agent pane.
 7. Copy reference + Pass-on-to-Agent (clipboard + bracketed-paste into the agent PTY).
diff --git a/DESIGN.md b/DESIGN.md
index 70ede56..f72cc04 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -64,19 +64,20 @@ Two stacked sections, each with its own header and count:
 
 Each row, identical in both sections:
 
-- A status letter on the far left: `A` added, `M` modified, `D` deleted, each in its own color (added green, modified amber, deleted red).
+- A status letter on the far left: `A` added, `M` modified, `D` deleted, each in its own color (added teal, modified amber, deleted amber-deep).
 - A file-type icon, then the file name.
 - The dimmed relative path, aligned to the right of the name.
-- Change counts at the far right: additions in green (`+N`) and deletions in red (`-N`).
+- Change counts at the far right: additions in teal (`+N`) and deletions in amber-deep (`-N`).
 - Deleted files are shown with the file name struck through and dimmed.
 - Rows have default, hover, and selected states. The selected row is the file currently open in the editor.
 
 ### Interactions
 
-- **Left-click** a row opens that file in the editor.
+- **Left-click** a row opens that file in the editor, in **Actual**. It does not open the full-screen Diff.
 - **Right-click** a row opens a context menu, designed to grow over time:
-  - In CHANGES (unstaged): **Stage file**, and **Discard changes**.
-  - In STAGED: **Unstage file**.
+  - In CHANGES (unstaged): **Open diff**, **Stage file**, and **Discard changes**.
+  - In STAGED: **Open diff**, and **Unstage file**.
+  - **Open diff** is the explicit way into the full-screen Diff (section 5).
 - **Hover quick action**: on hover, an unstaged row shows a `+` to stage it in one click, and a staged row shows a `-` to unstage it.
 - Optional section actions: **Stage all** on the CHANGES header and **Unstage all** on the STAGED header.
 - **Discard** is a destructive action. It asks for confirmation first (controlled by `git.confirmDiscard`, default on). Discarding reverts a modified file to its committed state and restores a deleted file.
@@ -124,24 +125,26 @@ The third and widest column. Tabs on top, a view toolbar under them, and the cod
 A row under the tabs:
 
 - On the left, a status summary for the active file, for example `Modified +6 -2`.
-- On the right, a four-segment control: **Original | Updated | Diff | Split**. The active segment is highlighted. This control appears only for files that have changes relative to their committed state. Its starting mode follows `git.defaultDiffMode` (default `Diff`).
+- On the right, a segmented control: **Actual | Original | Diff**, with a fourth segment, **Preview**, on markdown files only. The active segment is highlighted. This control appears only for files that have changes relative to their committed state. Its starting mode follows `git.defaultDiffMode` (default `Actual`).
 
 ### View modes
 
-All four are presentations of the same change set for the file:
+All are presentations of the same change set for the file:
 
-1. **Original**: the file as it was before the change, read-only. Changed and removed lines get a red bar in the left gutter. No inline plus or minus markers.
-2. **Updated**: the current, editable version of the file. Added and changed lines get a green bar in the left gutter.
-3. **Diff**: a single pane, unified inline diff. Removed lines are red with a `-`, added lines are green with a `+`, shown in sequence.
-4. **Split**: the editor expands to full screen, covering the other columns. The original file is on the left and the updated file is on the right, lines aligned. Removals are marked red on the left, additions green on the right. `Esc`, or a collapse control in the corner, returns to the normal layout and the previously active mode.
+1. **Actual**: the current, editable version of the file. It marks the changed lines in place, with a teal tint, a 2px teal left rule, and a teal line number. There is no sign column, no `+` or `-` pair, and no removed line inline. A pure deletion has no current line to mark, so the neighbouring current line carries a 2px amber-deep rule on its top edge, or on its bottom edge at the end of the file.
+2. **Original**: the file as it was before the change, read-only. Changed and removed lines get an amber-deep bar in the left gutter. No inline plus or minus markers.
+3. **Diff**: the editor expands to full screen, covering the other columns. The original file is on the left and the updated file is on the right, lines aligned. `Esc`, or a collapse control in the corner, returns to the normal layout and the previously active mode.
+4. **Preview**: markdown files only. It shows the rendered document instead of the source.
 
-Shared rules: red always means removed or changed-from, green always means added or changed-to. Syntax highlighting stays on in all four modes. Line numbers follow `editor.lineNumbers` (default absolute).
+**In Actual, the removed lines appear on hover.** The pointer enters a marked line, and a panel opens over the agent and terminal column: 496px wide, with a 2px amber-deep left border. The panel holds the whole original file, and it scrolls so that the previous version of the hovered line sits level with the hovered line. The pointer leaves the line, and the panel closes. There is no click, no pin, and no animation.
+
+Shared rules: teal is what the file holds now, amber-deep is what it held before. There is no green and no red anywhere. Syntax highlighting stays on in all modes. Line numbers follow `editor.lineNumbers` (default absolute).
 
 ### Editing behavior
 
 - A file with no changes opens directly in a normal editable view with no view-mode control, since there is nothing to diff.
 - Editing follows the editor settings: indentation, indent width, trim trailing whitespace, insert final newline, word wrap, indent guides, whitespace rendering, and active-line highlight, all read from configuration (section 10).
-- **Word wrap** follows `editor.wordWrap`: `markdown` (default), `on`, or `off`. When it is on, a line too wide for the pane folds onto the next row instead of scrolling sideways. Only the first row of a folded line carries a line number; the rows below it stay blank. Split view never wraps, because its two panes align row by row.
+- **Word wrap** follows `editor.wordWrap`: `markdown` (default), `on`, or `off`. When it is on, a line too wide for the pane folds onto the next row instead of scrolling sideways. Only the first row of a folded line carries a line number; the rows below it stay blank. The hover panel folds at the same points as the editor, so each old line stays level with its current line. Diff never wraps, because its two panes align row by row.
 
 ### Right-click in code
 
@@ -152,8 +155,8 @@ Right-clicking inside the code area, with or without a selection, shows a contex
 
 ### File-state behavior in the view modes
 
-- **Added file**: only the Updated content exists. Original is empty, Diff shows everything as added (green), Split shows an empty left and the file on the right.
-- **Deleted file**: only the Original content exists. Updated is empty, Diff shows everything as removed (red), Split shows the file on the left and an empty right.
+- **Added file**: only the Actual content exists. Actual marks every line as added, Original is empty, and Diff shows an empty left pane with the file on the right.
+- **Deleted file**: only the Original content exists. Actual is empty and has no line to mark, and Diff shows the file on the left with an empty right pane.
 - **Binary or unsupported file**: cannot be shown as editable text. The editor shows a short placeholder stating the file cannot be displayed, and the view-mode control is not shown.
 
 ---
@@ -186,7 +189,7 @@ The bottom pane of the fourth column.
 A bar across the bottom of the window. All items are **display only** for now; none are clickable.
 
 - On the left: the current branch and the working-tree line totals, for example `feat/payments-balance  +50 -38`.
-- On the right: cursor position (`Ln, Col`), indentation (`Spaces: 4`), encoding (`UTF-8`), language (`PHP`), and the active view mode (`Diff`).
+- On the right: cursor position (`Ln, Col`), indentation (`Spaces: 4`), encoding (`UTF-8`), language (`PHP`), and the active view mode (`Actual`).
 
 ---
 
diff --git a/README.md b/README.md
index 2acc619..e8030c6 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,7 @@ See what the agent changes, while it changes it — then hand it back exactly th
 [![React](https://img.shields.io/badge/React-18-18202B?style=flat-square)](https://react.dev)
 [![TypeScript](https://img.shields.io/badge/TypeScript-5.5-18202B?style=flat-square)](https://typescriptlang.org)
 [![Tests](https://img.shields.io/badge/tests-155%20passing-8FBFB4?style=flat-square)](#development)
+
 [![Vibe coded](https://img.shields.io/badge/vibe%20coded-100%25-E8913A?style=flat-square)](#fully-vibe-coded)
 
 The Helder workspace: source control, explorer, editor and the Claude Code agent in four columns
@@ -50,7 +51,7 @@ Four resizable columns, between a thin title bar and a status bar.
 |---|---|
 | **A · Source Control** | Commit box, staged list, changes list, per-file `+/−` counts |
 | **B · Explorer** | File tree with type icons and inline change badges |
-| **C · Editor** | Tabs, syntax highlighting, and four views of every changed file |
+| **C · Editor** | Tabs, syntax highlighting, and three views of every changed file |
 | **D · Agent + Shell** | A live Claude Code terminal over a normal shell |
 
 Every boundary is a splitter. Positions survive a restart, together with your open tabs and view modes.
@@ -67,15 +68,19 @@ Stack five of them, add your sentence, then press Enter once. Under the hood Hel
 
 Right-click gives you the same reference on the clipboard. The Explorer offers it at file level.
 
-### Four views of one change
+### Three views of one change
 
-Every changed file derives four views from one original-and-updated pair. `⌘M` cycles them.
+Every changed file derives three views from one original-and-updated pair. `⌘M` cycles them. A markdown file adds **Preview**.
 
-**Actual** · **Original** · **Diff** · **Split**
+**Actual** · **Original** · **Diff**
+
+**Actual** is the live buffer. It shows the file as it is now, with only the changed lines marked. Hover a marked line, and the whole original file appears over the agent column. It holds the matching scroll position, so the old line sits level with the new one.
+
+**Diff** goes full screen over the whole app. The original is on the left, the updated file is on the right, and the lines align. `Esc` returns to the view you came from.
 
 Added is teal, removed is amber-deep. There is no green and no red anywhere: the diff reads on shape and on a 2px rule, not on alarm.
 
-Split view: original on the left, updated on the right, with the changed line marked
+Diff view: original on the left, updated on the right, with the changed line marked
 
 ### Git, in the columns you already read
 
@@ -110,7 +115,7 @@ Press `?` in the title bar for the full list.
 | `⌘F` | Search contents and names |
 | `⌘→` | Pass the selection to the agent |
 | `⌘N` · `⌘P` | Open the project note · pass the whole note |
-| `⌘M` | Cycle Actual · Original · Diff · Split |
+| `⌘M` | Cycle Actual · Original · Diff |
 | `⌘C` · `⌘↵` | Focus the commit message · commit the staged files |
 | `⌘P` | Push the current branch |
 | `⌘S` | Save this file |
diff --git a/src/main/config.ts b/src/main/config.ts
index 49a115d..e1aa350 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -10,6 +10,7 @@ import { join } from 'node:path'
  *                         and FONT SIZE live here (as CSS vars), not in the JSON
  * Effective value = config.json over config.default.json, merged key by key.
  */
+/** View a changed file opens in. 'diff' is the full-screen side-by-side overlay. */
 export type DiffMode = 'original' | 'updated' | 'diff'
 /** Soft wrap of long lines: never, always, or only in Markdown files. */
 export type WordWrap = 'off' | 'on' | 'markdown'
@@ -55,7 +56,7 @@ export interface HelderConfig {
 export const DEFAULTS: HelderConfig = {
   ai: { command: 'claude', autoLaunch: true },
   editor: { autoSave: false, tabSize: 4, wordWrap: 'markdown' },
-  git: { confirmDiscard: true, confirmStage: false, confirmUnstage: false, defaultDiffMode: 'diff', refreshInterval: 10000 },
+  git: { confirmDiscard: true, confirmStage: false, confirmUnstage: false, defaultDiffMode: 'updated', refreshInterval: 10000 },
   files: { exclude: [], followGitignore: false },
   terminal: {
     shell: null,
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index 4a7c355..ca2723e 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -2,8 +2,8 @@
 import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
 import { FileTree, GitPanel, Icon, Tip, groupByDir } from './components'
 import type { ContextTarget } from './components'
-import { Editor, SplitView } from './editor'
-import type { Cursor, Mode, Selection } from './editor'
+import { Editor, OriginalPeek, SplitView } from './editor'
+import type { Cursor, Mode, PeekInfo, Selection } from './editor'
 import { Terminal, lid } from './terminals'
 import { ConfirmModal, ContextMenu, HelpModal, HistoryModal, NamePopup, NotesModal, PassPopup, ProjectsModal, SearchModal, SymbolPopup, Toasts } from './overlays'
 import { ProjectLauncher } from './launcher'
@@ -96,8 +96,8 @@ export function App(): React.ReactElement {
 
   const [active, setActive] = useState(null)
   const [tabMode, setTabMode] = useState>({})
-  // Which git row opened each tab. Only Diff and Split follow it: Original and
-  // Actual always show HEAD and the file on disk.
+  // Which git row opened each tab. Only Diff follows it: Original and Actual
+  // always show HEAD and the file on disk.
   const [tabSide, setTabSide] = useState>({})
   const [openDirs, setOpenDirs] = useState>(new Set())
   const [cursor, setCursor] = useState(null)
@@ -114,7 +114,7 @@ export function App(): React.ReactElement {
   const [histInitSel, setHistInitSel] = useState(0)
   const [menu, setMenu] = useState(null)
   const [toasts, setToasts] = useState([])
-  const [splitFor, setSplitFor] = useState(null)
+  const [peek, setPeek] = useState(null)
   const [commitMsg, setCommitMsg] = useState('')
   const [passPopup, setPassPopup] = useState<{ x: number; y: number; ref: string; code?: string } | null>(null)
   const [newFilePopup, setNewFilePopup] = useState<{ x: number; y: number; dir: string } | null>(null)
@@ -540,7 +540,6 @@ export function App(): React.ReactElement {
     setTabSide(remapKeys)
     setOpenDirs((d) => new Set([...d].map(remap)))
     setActive((a) => (a ? remap(a) : a))
-    setSplitFor((s) => (s ? remap(s) : s))
     setCursor((c) => (c ? { ...c, path: remap(c.path) } : c))
     actions.refresh()
     toast(isDir ? 'Renamed folder' : 'Renamed file', next)
@@ -556,6 +555,18 @@ export function App(): React.ReactElement {
   }
 
   const defaultMode: Mode = proj.config.git.defaultDiffMode
+  const mode: Mode = (active && tabMode[active]) || (active && proj.diffs[active] ? defaultMode : 'code')
+  // Which half the open tab shows. Also lights up the matching git row.
+  const activeSide: DiffSide | null = (active && tabSide[active]) || null
+  /* Diff is a full-screen overlay, so Esc has to put the pane back where it was.
+   * Any entry point counts — the segment, a git row, ⌘M — so this just trails
+   * the last mode that was not Diff. */
+  const preDiff = useRef('updated')
+  useEffect(() => { if (mode !== 'diff') preDiff.current = mode }, [mode])
+  const splitOpen = !!active && mode === 'diff' && !!proj.diffs[active] && !HL.isImage(active)
+  function closeSplit(): void {
+    if (active) setTabMode((m) => ({ ...m, [active]: preDiff.current }))
+  }
   function stageGuarded(p: string): void {
     if (proj.config.git.confirmStage && !window.confirm(`Stage ${p}?`)) return
     actions.stage(p)
@@ -612,11 +623,11 @@ export function App(): React.ReactElement {
     setHistory((h) => [path, ...h.filter((p) => p !== path)].slice(0, 100))
     reloadFromDisk(path)
     setActive(path)
-    // Git rows open the diff; explorer / recent-files open the updated view.
-    // Unchanged files only have the plain editable "code" view.
+    // A changed file lands in the Actual view. Only an explicit `diff` request
+    // opens the full-screen overlay. Unchanged files have the "code" view only.
     const openMode: Mode = changed ? (opts.diff ? 'diff' : 'updated') : 'code'
     setTabMode((m) => ({ ...m, [path]: openMode }))
-    // Remember which git row this came from, so Diff/Split show that half. An
+    // Remember which git row this came from, so Diff shows that half. An
     // explorer click carries no side and falls back to the whole file.
     setTabSide((m) => {
       const n = { ...m }
@@ -631,7 +642,6 @@ export function App(): React.ReactElement {
       // so scroll its container to centre the target line. Line height is 20px with
       // a 6px top pad; retry across a few frames until the content has rendered (the
       // file may still be loading for a freshly-opened unchanged file).
-      setSplitFor(null)
       setTabMode((m) => ({ ...m, [path]: changed ? 'updated' : 'code' }))
       setCursor({ path, line: opts.line, col: 1 })
       setSelection(null)
@@ -759,9 +769,9 @@ export function App(): React.ReactElement {
     }
     return false
   }
-  // ↵ inside Git/Explorer: open the selected file (git → diff), toggle a folder.
+  // ↵ inside Git/Explorer: open the selected file, toggle a folder.
   function openPanelSelection(): boolean {
-    if (activePanel === 'git' && gitSelRow) { openFile(gitSelRow.path, { diff: true, side: gitSelRow.staged ? 'staged' : 'unstaged' }); return true }
+    if (activePanel === 'git' && gitSelRow) { openFile(gitSelRow.path, { side: gitSelRow.staged ? 'staged' : 'unstaged' }); return true }
     if (activePanel === 'tree' && treeSelItem) {
       if (treeSelItem.type === 'dir') toggleDir(treeSelItem.path)
       else openFile(treeSelItem.path)
@@ -771,23 +781,21 @@ export function App(): React.ReactElement {
   }
 
   // ⌘M cycles the active file through whatever views it supports: a changed file
-  // runs Updated → Original → Diff → Split (+ Preview for markdown); an unchanged
-  // markdown file toggles Code ↔ Preview. Plain unchanged files have one view, so
-  // there's nothing to cycle.
+  // runs Actual → Original → Diff (+ Preview for markdown); an unchanged markdown
+  // file toggles Code ↔ Preview. Plain unchanged files have one view, so there's
+  // nothing to cycle.
   function cycleMode(): void {
     if (!active) return
     reloadFromDisk(active)
     const md = HL.langFor(active) === 'markdown'
     const hasDiff = !!proj.diffs[active]
-    const order: (Mode | 'split')[] = hasDiff
-      ? ['updated', 'original', 'diff', 'split', ...(md ? (['preview'] as const) : [])]
+    const order: Mode[] = hasDiff
+      ? ['updated', 'original', 'diff', ...(md ? (['preview'] as const) : [])]
       : md ? ['code', 'preview'] : ['code']
     if (order.length < 2) return
-    const cur = splitFor === active ? 'split' : (tabMode[active] || (hasDiff ? defaultMode : 'code'))
+    const cur = tabMode[active] || (hasDiff ? defaultMode : 'code')
     const idx = order.indexOf(cur)
-    const next = order[(idx < 0 ? 0 : idx + 1) % order.length]
-    if (next === 'split') setSplitFor(active)
-    else { setTabMode((m) => ({ ...m, [active]: next as Mode })); setSplitFor(null) }
+    setTabMode((m) => ({ ...m, [active]: order[(idx < 0 ? 0 : idx + 1) % order.length] }))
   }
   function focusCommit(): void {
     document.querySelector('.commit-input')?.focus()
@@ -892,7 +900,7 @@ export function App(): React.ReactElement {
         if (openPanelSelection()) { e.preventDefault(); return }
       }
       if (e.key === 'Escape') {
-        if (splitFor) setSplitFor(null)
+        if (splitOpen) closeSplit()
         // Closing the note saves it there and then, rather than leaving the text
         // to wait for the next blur.
         else if (overlay === 'notes') { setOverlay(null); saveNote() }
@@ -963,7 +971,7 @@ export function App(): React.ReactElement {
     }
     window.addEventListener('keydown', onKey)
     return () => window.removeEventListener('keydown', onKey)
-  }, [active, splitFor, overlay, focusZone, history, tabMode, commitMsg, proj, selection, confirm, menu, activePanel, gitNav, treeNav, gitSel, treeSel])
+  }, [active, splitOpen, overlay, focusZone, history, tabMode, commitMsg, proj, selection, confirm, menu, activePanel, gitNav, treeNav, gitSel, treeSel])
 
   // ⌘R (View → Refresh, main process sends `view:refresh`) reloads the three
   // left columns: git status (A) + the file tree (B) via a full project reload,
@@ -1017,10 +1025,6 @@ export function App(): React.ReactElement {
     // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [proj.config.git.refreshInterval])
 
-  const mode: Mode = (active && tabMode[active]) || (active && proj.diffs[active] ? defaultMode : 'code')
-  // Which half the open tab shows. Also lights up the matching git row.
-  const activeSide: DiffSide | null = (active && tabSide[active]) || null
-
   const crumb = active ? active.split('/') : []
   // Whole-project line counts, shown in the status bar next to the branch.
   const totals = proj.changes.reduce((a, c) => ({ add: a.add + c.add, del: a.del + c.del }), { add: 0, del: 0 })
@@ -1128,9 +1132,8 @@ export function App(): React.ReactElement {
 
         
{ setFocusZone('editor'); setActivePanel('editor') }}> { if (active) { setTabMode((mm) => ({ ...mm, [active]: m })); setSplitFor(null); reloadFromDisk(active) } }} - onContext={openMenu} - onSplit={(p) => setSplitFor(p)} splitOpen={splitFor === active} + setMode={(m) => { if (active) { setTabMode((mm) => ({ ...mm, [active]: m })); reloadFromDisk(active) } }} + onContext={openMenu} onPeek={setPeek} cursor={cursor} selection={selection} setCursor={setCursor} setSelection={setSelection} flash={lineFlash && lineFlash.path === active ? lineFlash : null} bufferText={bufferText(active)} onEdit={onEdit} onSymbol={openSymbol} /> @@ -1145,6 +1148,10 @@ export function App(): React.ReactElement { {/* keyed by root so the PTYs respawn in the new cwd when the project switches */} {proj.ready && { setFocusZone('terminal'); setActivePanel('terminal') }} />} + + {/* The hover reveal of Diff mode. It belongs to the body row, so it + covers the agent column and stops at the status bar. */} + {peek && }
{/* status bar — display only: nothing here is clickable */} @@ -1166,7 +1173,7 @@ export function App(): React.ReactElement { {/* overlays */} - {splitFor && setSplitFor(null)} onContext={openMenu} />} + {splitOpen && } {passPopup && { window.dispatchEvent(new CustomEvent('agentPaste', { detail: payload })) diff --git a/src/renderer/src/components.tsx b/src/renderer/src/components.tsx index 3be8b82..0817980 100644 --- a/src/renderer/src/components.tsx +++ b/src/renderer/src/components.tsx @@ -119,7 +119,7 @@ function GitRow({ c, activePath, activeSide, ctxPath, kbdId, onOpen, onContext, return (
onOpen(c.path, { diff: true, side })} + onClick={() => onOpen(c.path, { side })} onContextMenu={(e) => onContext(e, { path: c.path, kind: 'git', staged })} title={c.path}> {c.status} diff --git a/src/renderer/src/diff.ts b/src/renderer/src/diff.ts index 20b569d..5806e0e 100644 --- a/src/renderer/src/diff.ts +++ b/src/renderer/src/diff.ts @@ -1,7 +1,7 @@ -/* Line-based LCS diff — the single source for the four view modes. - * Original / Updated / Diff / Split all derive from one (original, updated) - * text pair per changed file, whether that pair comes from the mock or from - * real `git diff` (original = HEAD:path, updated = working tree). */ +/* Line-based LCS diff — the single source for the view modes. Actual, Original + * and the side-by-side Diff all derive from one (original, updated) text pair + * per changed file, whether that pair comes from the mock or from real + * `git diff` (original = HEAD:path, updated = working tree). */ import type { Diff, DiffRow, GitStatus, SideLine, SplitRow } from './types' interface Op { t: 'same' | 'del' | 'add'; a?: number; b?: number } diff --git a/src/renderer/src/editor.tsx b/src/renderer/src/editor.tsx index ca55ed6..ec60633 100644 --- a/src/renderer/src/editor.tsx +++ b/src/renderer/src/editor.tsx @@ -1,5 +1,5 @@ -/* Editor: four view modes (Original / Updated / Diff / Split) + line selection */ -import React, { Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +/* Editor: four view modes (Actual / Original / Diff / Preview) + line selection */ +import React, { Fragment, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { Diff, DiffSide, ViewLine } from './types' import { rowId } from './types' import { useProject } from './project' @@ -57,6 +57,20 @@ function climbToLine(node: Node | null): HTMLElement | null { return el || null } +/** A line the file-level diff changed, as the editable buffer needs it. */ +export interface ChangeMark { + line: number + /** The line itself is new or rewritten: tint the row, lift its number. */ + tint: boolean + /** A removed run owns no line here, so its rule sits on an edge of this one. */ + gap: 'above' | 'below' | null +} +/** A mark plus the geometry of its line, in `.ce-inner` coordinates. */ +interface Band extends ChangeMark { top: number; height: number } +/** The line box of `.ce-pre` and its top padding — the unwrapped arithmetic. */ +const LINE_H = 20 +const PAD_TOP = 10 + /* Editable buffer: a transparent textarea over a Prism-highlighted
, with a
  * scroll-synced line-number gutter. Live highlighting while typing.
  *
@@ -68,42 +82,48 @@ function climbToLine(node: Node | null): HTMLElement | null {
  *    the number is a CSS counter on `::before`, which keeps it on the first
  *    visual row and leaves the folded rows unnumbered. Highlighting is then per
  *    line (like the diff views), so multi-line tokens don't carry over. */
-function CodeEditor({ path, text, lang, wrap, flash, onChange, onContext, onSymbol }: {
+function CodeEditor({ path, text, lang, wrap, flash, marks, onHover, onChange, onContext, onSymbol }: {
   path: string
   text: string
   lang: string | null
   wrap: boolean
   /** Line to paint orange for a second after a jump. */
   flash: FlashLine | null
+  /** Changed lines of this file, from the HEAD-vs-disk diff. */
+  marks: ChangeMark[]
+  /** The marked line under the pointer, with its top in the pane's viewport. */
+  onHover: (h: { line: number; top: number } | null) => void
   onChange: (text: string) => void
   onContext: OnContext
   onSymbol: OnSymbol
 }): React.ReactElement {
   const scrollRef = useRef(null)
+  const innerRef = useRef(null)
   const gutterRef = useRef(null)
   const preRef = useRef(null)
   const tabSize = useProject().config.editor.tabSize
   const symVer = useSymbols() // re-highlight once the declared-name list lands
   const metaDown = useMetaKey()
+  const tinted = useMemo(() => new Set(marks.filter((m) => m.tint).map((m) => m.line)), [marks])
   const html = useMemo(
     () => (wrap
-      ? text.split('\n').map((l) => `
${HL.hlLine(l, lang)}
`).join('') + ? text.split('\n').map((l, i) => `
${HL.hlLine(l, lang)}
`).join('') : HL.hlText(text, lang) + '\n'), // symVer is not read here: HL marks the known class tokens from a module-level // set, so this is what recomputes the HTML when that set lands. // eslint-disable-next-line react-hooks/exhaustive-deps - [text, lang, wrap, symVer], + [text, lang, wrap, symVer, tinted], ) - /* One text block, not one element per line: the font is monospace and every - * row is exactly 20px, so the numbers land on the same grid a list of divs - * gave — for one node instead of thousands on a long file. Nothing styles a - * single number today; the day something must, this goes back to spans. */ + /* One block of markup, not one element per line: the font is monospace and + * every row is exactly 20px, so the numbers land on the same grid a list of + * divs gave — for one node instead of thousands on a long file. Only a + * changed number needs an element of its own. */ const gutter = useMemo(() => { const n = text.split('\n').length - let out = '1' - for (let i = 2; i <= n; i++) out += '\n' + i - return out - }, [text]) + const out: string[] = [] + for (let i = 1; i <= n; i++) out.push(tinted.has(i) ? `${i}` : String(i)) + return out.join('\n') + }, [text, tinted]) // The band sits behind the text, so it needs the geometry of the line. Unwrapped // that is arithmetic; wrapped, a line can be several rows tall, so measure it. const [flashBox, setFlashBox] = useState<{ top: number; height: number } | null>(null) @@ -113,9 +133,56 @@ function CodeEditor({ path, text, lang, wrap, flash, onChange, onContext, onSymb setFlashBox(row ? { top: row.offsetTop, height: row.offsetHeight } : { top: 6 + (flash.line - 1) * 20, height: 20 }) }, [flash, wrap, text]) + // A folded line is as tall as the rows it spans, so a width change moves every + // band under it. Nothing else here depends on the pane width. + const [paneW, setPaneW] = useState(0) + useEffect(() => { + const el = scrollRef.current + if (!wrap || !el || typeof ResizeObserver === 'undefined') return + const ro = new ResizeObserver(() => setPaneW(el.clientWidth)) + ro.observe(el) + return () => ro.disconnect() + }, [wrap]) + /* The change bands. They go behind the transparent textarea, so each one needs + * the geometry of its line the way the flash band does: arithmetic while the + * buffer is one blob, measured once a line can fold. */ + const [bands, setBands] = useState([]) + useLayoutEffect(() => { + if (!marks.length) { setBands([]); return } + const kids = preRef.current?.children + setBands(marks.map((m) => { + const row = wrap ? (kids?.[m.line - 1] as HTMLElement | undefined) : undefined + return row + ? { ...m, top: row.offsetTop, height: row.offsetHeight } + : { ...m, top: PAD_TOP + (m.line - 1) * LINE_H, height: LINE_H } + })) + }, [marks, wrap, text, paneW]) + + /* The hover reveal. The pointer lands on the textarea rather than on a row, so + * the line comes from the bands — the same geometry that drew the tint. */ + const hoverRef = useRef(null) + function report(list: Band[], line: number | null): void { + const b = line == null ? undefined : list.find((x) => x.line === line) + hoverRef.current = b ? b.line : null + onHover(b && scrollRef.current ? { line: b.line, top: b.top - scrollRef.current.scrollTop } : null) + } + function onMove(e: React.MouseEvent): void { + if (!bands.length && hoverRef.current == null) return + const box = innerRef.current?.getBoundingClientRect() + if (!box) return + const y = e.clientY - box.top + const hit = bands.find((b) => y >= b.top && y < b.top + b.height) + const line = hit ? hit.line : null + if (line !== hoverRef.current) report(bands, line) + } + // An edit moves the bands under a held pointer; the panel follows them. + // eslint-disable-next-line react-hooks/exhaustive-deps + useLayoutEffect(() => { if (hoverRef.current != null) report(bands, hoverRef.current) }, [bands]) + function onScroll(): void { const s = scrollRef.current if (s && gutterRef.current) gutterRef.current.style.transform = `translateY(${-s.scrollTop}px)` + if (hoverRef.current != null) report(bands, hoverRef.current) } // The textarea is overflow-hidden under the scroller, so keep the caret line // in view by scrolling the container ourselves (6px top pad, 20px line-height). @@ -209,11 +276,20 @@ function CodeEditor({ path, text, lang, wrap, flash, onChange, onContext, onSymb
{!wrap && (
-
{gutter}
+
)} -
-
+ {/* No marks, no hover: an unchanged file pays nothing for the reveal. */} +
{ if (hoverRef.current != null) report(bands, null) } : undefined}> +
+ {bands.map((b) => ( + + {b.tint &&
} + {b.gap &&
} + + ))} {flash && flashBox &&
}