Compare commits
2 Commits
2e84cbd0fa
...
3f5078841d
| Author | SHA1 | Date | |
|---|---|---|---|
| 3f5078841d | |||
| 3d77fdfeff |
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
out/
|
||||
dist/
|
||||
.DS_Store
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
.playwright-mcp/
|
||||
7
.playwright-mcp/console-2026-06-15T08-02-31-469Z.log
Normal file
7
.playwright-mcp/console-2026-06-15T08-02-31-469Z.log
Normal file
@@ -0,0 +1,7 @@
|
||||
[ 282ms] [INFO] You are running a development build of Vue.
|
||||
Make sure to use the production build (*.prod.js) when deploying for production. @ https://unpkg.com/vue@3/dist/vue.global.js:12834
|
||||
[ 292ms] Identifier 'ref' has already been declared
|
||||
[ 293ms] Identifier 'ref' has already been declared
|
||||
[ 293ms] Identifier 'ref' has already been declared
|
||||
[ 293ms] Identifier 'ref' has already been declared
|
||||
[ 298ms] [ERROR] Failed to load resource: the server responded with a status of 404 (File not found) @ http://localhost:8753/favicon.ico:0
|
||||
0
.playwright-mcp/page-2026-06-15T08-02-31-796Z.yml
Normal file
0
.playwright-mcp/page-2026-06-15T08-02-31-796Z.yml
Normal file
28
CLAUDE.md
28
CLAUDE.md
@@ -4,7 +4,26 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Project state
|
||||
|
||||
This is a **greenfield project**. No application code, build setup, or `package.json` exists yet — only a design handoff. The first real task is to scaffold the Electron app and port the prototype. Until then, treat the two handoff documents as the contract:
|
||||
**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. JetBrains Mono is bundled locally via `@fontsource/jetbrains-mono`; 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) — essentially complete.** All over IPC through the preload bridge (`src/preload/index.ts`):
|
||||
- **Filesystem** — tree, in-memory content index, `chokidar` watch (`src/main/fs-service.ts`).
|
||||
- **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`).
|
||||
- **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.
|
||||
|
||||
- **Search** — ripgrep (`@vscode/ripgrep`, bundled binary) for content (`--json`, fixed-string smart-case) and the file-name list (`--files`), via `src/main/search-service.ts`. `SearchModal` calls it debounced and falls back to the in-memory index when `window.helder` is absent.
|
||||
|
||||
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 `<pre>` 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.
|
||||
|
||||
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).
|
||||
|
||||
Not yet done: packaging (electron-builder → .app/.dmg) — `out/` is dev build output only, there is no distributable yet.
|
||||
|
||||
The two handoff documents remain the contract:
|
||||
|
||||
- **`DESIGN.md`** — functional/UX source of truth. Every panel, interaction, state, and edge case at the behavior level. Read this for *what the app does*.
|
||||
- **`design_handoff_helder_workbench/README.md`** — technical source of truth. Structure, design tokens, recommended stack, real-integration mechanics, and the suggested implementation order. Read this for *how to build it*.
|
||||
@@ -69,4 +88,9 @@ Canonical source is the `:root` block in `design_handoff_helder_workbench/design
|
||||
|
||||
## Commands
|
||||
|
||||
No build/lint/test commands exist yet. Once the Electron + Vite toolchain is scaffolded, document the real `dev` / `build` / `lint` / `test` commands here, replacing this note.
|
||||
- `npm run dev` — launch the app in Electron with HMR (`electron-vite dev`).
|
||||
- `npm run build` — type-stripped production build into `out/` (`electron-vite build`). A frontend change is not done until this succeeds.
|
||||
- `npm run preview` / `npm start` — run the built app (`electron-vite preview`).
|
||||
- `npm run typecheck` — `tsc --noEmit` over the renderer (`tsconfig.web.json`) and main/preload (`tsconfig.node.json`). The build itself uses esbuild and does NOT type-check, so run this separately to catch type errors.
|
||||
|
||||
No test/lint runner is wired up yet — add and document them here when introduced.
|
||||
|
||||
24
electron.vite.config.ts
Normal file
24
electron.vite.config.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
main: {
|
||||
plugins: [externalizeDepsPlugin()],
|
||||
build: { outDir: 'out/main' },
|
||||
},
|
||||
preload: {
|
||||
plugins: [externalizeDepsPlugin()],
|
||||
build: { outDir: 'out/preload' },
|
||||
},
|
||||
renderer: {
|
||||
root: 'src/renderer',
|
||||
build: {
|
||||
outDir: 'out/renderer',
|
||||
rollupOptions: {
|
||||
input: resolve(__dirname, 'src/renderer/index.html'),
|
||||
},
|
||||
},
|
||||
plugins: [react()],
|
||||
},
|
||||
})
|
||||
3357
package-lock.json
generated
Normal file
3357
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
41
package.json
Normal file
41
package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "helder",
|
||||
"version": "0.1.0",
|
||||
"description": "Helder — dark-only Electron code workbench for reviewing AI-written code",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./out/main/index.js",
|
||||
"author": "Jonathan van Rij",
|
||||
"scripts": {
|
||||
"dev": "electron-vite dev",
|
||||
"build": "electron-vite build",
|
||||
"preview": "electron-vite preview",
|
||||
"start": "electron-vite preview",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.web.json && tsc --noEmit -p tsconfig.node.json",
|
||||
"rebuild": "electron-rebuild -f -w node-pty",
|
||||
"postinstall": "electron-rebuild -f -w node-pty"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/jetbrains-mono": "^5.0.20",
|
||||
"@vscode/ripgrep": "^1.18.0",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"chokidar": "^5.0.0",
|
||||
"node-pty": "^1.1.0",
|
||||
"prismjs": "^1.29.0",
|
||||
"simple-git": "^3.36.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron/rebuild": "^4.0.4",
|
||||
"@types/prismjs": "^1.26.4",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react": "^4.3.1",
|
||||
"electron": "^31.3.0",
|
||||
"electron-vite": "^2.3.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"typescript": "^5.5.4",
|
||||
"vite": "^5.3.5"
|
||||
}
|
||||
}
|
||||
93
src/main/config.ts
Normal file
93
src/main/config.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/**
|
||||
* Project-scoped settings, living in `.helder/` in the opened project's root.
|
||||
* - config.default.json full built-in defaults, REGENERATED on every launch
|
||||
* (live documentation; the app never reads user edits here)
|
||||
* - config.json sparse — only user-overridden values
|
||||
* - theme.css custom CSS over the built-in dark theme; the CODE FONT
|
||||
* and FONT SIZE live here (as CSS vars), not in the JSON
|
||||
* Effective value = config.json over config.default.json, merged key by key.
|
||||
*/
|
||||
export interface HelderConfig {
|
||||
ai: { command: string; autoLaunch: boolean }
|
||||
editor: { autoSave: boolean; tabSize: number }
|
||||
git: { confirmDiscard: boolean }
|
||||
terminal: { shell: string | null }
|
||||
}
|
||||
|
||||
export const DEFAULTS: HelderConfig = {
|
||||
ai: { command: 'claude', autoLaunch: true },
|
||||
editor: { autoSave: false, tabSize: 4 },
|
||||
git: { confirmDiscard: true },
|
||||
terminal: { shell: null },
|
||||
}
|
||||
|
||||
const THEME_TEMPLATE = `/* Helder theme — custom CSS applied OVER the built-in dark theme.
|
||||
* This file is created once and never overwritten; edit it freely.
|
||||
* The code font and font size live here (not in config.json). Uncomment and
|
||||
* tweak any variable below; you can also override any --token from the built-in
|
||||
* theme (see the design tokens in the app's styles). */
|
||||
:root {
|
||||
/* Code surfaces (editor + terminals) */
|
||||
/* --code-font: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; */
|
||||
/* --code-size: 13px; */ /* editor font size */
|
||||
/* --term-size: 12.5px; */ /* terminal font size */
|
||||
|
||||
/* Example accent override: */
|
||||
/* --accent: #4d8dff; */
|
||||
}
|
||||
`
|
||||
|
||||
let current: HelderConfig = DEFAULTS
|
||||
let themeCss = ''
|
||||
|
||||
function isPlainObject(v: unknown): v is Record<string, unknown> {
|
||||
return !!v && typeof v === 'object' && !Array.isArray(v)
|
||||
}
|
||||
|
||||
function deepMerge<T>(base: T, over: unknown): T {
|
||||
if (!isPlainObject(base) || !isPlainObject(over)) return base
|
||||
const out: Record<string, unknown> = { ...base }
|
||||
for (const key of Object.keys(over)) {
|
||||
const b = (base as Record<string, unknown>)[key]
|
||||
const o = over[key]
|
||||
if (isPlainObject(b) && isPlainObject(o)) out[key] = deepMerge(b, o)
|
||||
else if (o !== undefined) out[key] = o
|
||||
}
|
||||
return out as T
|
||||
}
|
||||
|
||||
/** (Re)resolve config + theme for a project root, regenerating the defaults file. */
|
||||
export async function resolveConfig(root: string): Promise<void> {
|
||||
const dir = join(root, '.helder')
|
||||
try {
|
||||
await mkdir(dir, { recursive: true })
|
||||
// Always regenerate the defaults file — it documents every setting.
|
||||
await writeFile(join(dir, 'config.default.json'), JSON.stringify(DEFAULTS, null, 2) + '\n')
|
||||
|
||||
let override: unknown = {}
|
||||
try { override = JSON.parse(await readFile(join(dir, 'config.json'), 'utf8')) } catch { /* none / invalid */ }
|
||||
current = deepMerge(DEFAULTS, override)
|
||||
|
||||
try {
|
||||
themeCss = await readFile(join(dir, 'theme.css'), 'utf8')
|
||||
} catch {
|
||||
themeCss = THEME_TEMPLATE
|
||||
await writeFile(join(dir, 'theme.css'), THEME_TEMPLATE)
|
||||
}
|
||||
} catch {
|
||||
// Read-only / inaccessible root: fall back to built-in defaults.
|
||||
current = DEFAULTS
|
||||
themeCss = ''
|
||||
}
|
||||
}
|
||||
|
||||
export function getConfig(): HelderConfig {
|
||||
return current
|
||||
}
|
||||
|
||||
export function getThemeCss(): string {
|
||||
return themeCss
|
||||
}
|
||||
117
src/main/fs-service.ts
Normal file
117
src/main/fs-service.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { readdir, readFile, stat, writeFile } from 'node:fs/promises'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
|
||||
export interface FileNode {
|
||||
name: string
|
||||
type: 'dir' | 'file'
|
||||
path: string
|
||||
open?: boolean
|
||||
children?: FileNode[]
|
||||
}
|
||||
|
||||
/** Directories never walked — noise or huge, and not part of "the project". */
|
||||
const IGNORE_DIRS = new Set([
|
||||
'node_modules', '.git', 'out', 'dist', 'build', '.next', '.nuxt',
|
||||
'.cache', 'coverage', 'vendor', '.idea', '.vscode', '.helder', '.turbo',
|
||||
])
|
||||
|
||||
const MAX_FILE_BYTES = 300_000
|
||||
const MAX_INDEXED_FILES = 6000
|
||||
|
||||
function ignored(name: string): boolean {
|
||||
return IGNORE_DIRS.has(name) || name === '.DS_Store'
|
||||
}
|
||||
|
||||
/** Recursive project tree, dirs first then files, alphabetical. */
|
||||
export async function readTree(root: string): Promise<FileNode> {
|
||||
const name = root.split(sep).filter(Boolean).pop() || root
|
||||
return { name, type: 'dir', path: '', open: true, children: await readDir(root, root, 0) }
|
||||
}
|
||||
|
||||
async function readDir(abs: string, root: string, depth: number): Promise<FileNode[]> {
|
||||
let entries: import('node:fs').Dirent[]
|
||||
try {
|
||||
entries = await readdir(abs, { withFileTypes: true })
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const dirs: FileNode[] = []
|
||||
const files: FileNode[] = []
|
||||
for (const e of entries) {
|
||||
if (ignored(e.name)) continue
|
||||
const childAbs = join(abs, e.name)
|
||||
const rel = relative(root, childAbs).split(sep).join('/')
|
||||
if (e.isDirectory()) {
|
||||
dirs.push({
|
||||
name: e.name, type: 'dir', path: rel, open: depth < 1,
|
||||
children: depth < 12 ? await readDir(childAbs, root, depth + 1) : [],
|
||||
})
|
||||
} else if (e.isFile()) {
|
||||
files.push({ name: e.name, type: 'file', path: rel })
|
||||
}
|
||||
}
|
||||
dirs.sort((a, b) => a.name.localeCompare(b.name))
|
||||
files.sort((a, b) => a.name.localeCompare(b.name))
|
||||
return [...dirs, ...files]
|
||||
}
|
||||
|
||||
function looksBinary(buf: Buffer): boolean {
|
||||
const n = Math.min(buf.length, 8000)
|
||||
for (let i = 0; i < n; i++) if (buf[i] === 0) return true
|
||||
return false
|
||||
}
|
||||
|
||||
/** Read a single text file (relative path) → string. */
|
||||
export async function readProjectFile(root: string, rel: string): Promise<string> {
|
||||
const buf = await readFile(join(root, rel))
|
||||
if (looksBinary(buf)) return ''
|
||||
return buf.toString('utf8')
|
||||
}
|
||||
|
||||
/** Write a text file (relative path). Used by the editable buffer's save. */
|
||||
export async function writeProjectFile(root: string, rel: string, content: string): Promise<void> {
|
||||
await writeFile(join(root, rel), content, 'utf8')
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an in-memory content index of all (small, text) files — powers content
|
||||
* search and plain-file viewing without touching disk per keystroke. Capped to
|
||||
* keep large repos sane. PHASE: swap content search to ripgrep when scaling up.
|
||||
*/
|
||||
export async function readAll(root: string): Promise<Record<string, string>> {
|
||||
const out: Record<string, string> = {}
|
||||
let count = 0
|
||||
|
||||
async function walk(abs: string): Promise<void> {
|
||||
if (count >= MAX_INDEXED_FILES) return
|
||||
let entries: import('node:fs').Dirent[]
|
||||
try {
|
||||
entries = await readdir(abs, { withFileTypes: true })
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
for (const e of entries) {
|
||||
if (count >= MAX_INDEXED_FILES) return
|
||||
if (ignored(e.name)) continue
|
||||
const childAbs = join(abs, e.name)
|
||||
if (e.isDirectory()) {
|
||||
await walk(childAbs)
|
||||
} else if (e.isFile()) {
|
||||
try {
|
||||
const s = await stat(childAbs)
|
||||
if (s.size > MAX_FILE_BYTES) continue
|
||||
const buf = await readFile(childAbs)
|
||||
if (looksBinary(buf)) continue
|
||||
const rel = relative(root, childAbs).split(sep).join('/')
|
||||
out[rel] = buf.toString('utf8')
|
||||
count++
|
||||
} catch {
|
||||
/* skip unreadable */
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await walk(root)
|
||||
return out
|
||||
}
|
||||
108
src/main/git-service.ts
Normal file
108
src/main/git-service.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { simpleGit, type SimpleGit } from 'simple-git'
|
||||
|
||||
export type GitStatusLetter = 'A' | 'M' | 'D' | 'R' | 'U'
|
||||
|
||||
export interface GitChange {
|
||||
path: string
|
||||
status: GitStatusLetter
|
||||
staged: boolean
|
||||
original: string
|
||||
updated: string
|
||||
}
|
||||
|
||||
export interface GitLoad {
|
||||
branch: string
|
||||
changes: GitChange[]
|
||||
}
|
||||
|
||||
function git(root: string): SimpleGit {
|
||||
return simpleGit({ baseDir: root, maxConcurrentProcesses: 4 })
|
||||
}
|
||||
|
||||
/** Map a porcelain code pair to our display letter + staged flag. */
|
||||
function classify(index: string, working: string): { letter: GitStatusLetter; staged: boolean } {
|
||||
const staged = index !== ' ' && index !== '?'
|
||||
const code = staged ? index : working
|
||||
let letter: GitStatusLetter
|
||||
switch (code) {
|
||||
case 'A': case 'C': case '?': letter = 'A'; break
|
||||
case 'D': letter = 'D'; break
|
||||
case 'R': letter = 'R'; break
|
||||
case 'U': letter = 'M'; break
|
||||
case 'M': default: letter = 'M'; break
|
||||
}
|
||||
return { letter, staged }
|
||||
}
|
||||
|
||||
async function headText(g: SimpleGit, path: string): Promise<string> {
|
||||
try {
|
||||
return await g.show([`HEAD:${path}`])
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function diskText(root: string, path: string): Promise<string> {
|
||||
try {
|
||||
const buf = await readFile(join(root, path))
|
||||
// skip obvious binaries
|
||||
for (let i = 0; i < Math.min(buf.length, 8000); i++) if (buf[i] === 0) return ''
|
||||
return buf.toString('utf8')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function isRepo(root: string): Promise<boolean> {
|
||||
try {
|
||||
return await git(root).checkIsRepo()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function load(root: string): Promise<GitLoad | null> {
|
||||
const g = git(root)
|
||||
if (!(await isRepo(root))) return null
|
||||
|
||||
const status = await g.status()
|
||||
const branch = status.current || 'HEAD'
|
||||
|
||||
const changes: GitChange[] = []
|
||||
for (const f of status.files) {
|
||||
// simple-git uses path "from -> to" for renames; take the destination.
|
||||
const path = f.path.includes(' -> ') ? f.path.split(' -> ').pop()! : f.path
|
||||
const { letter, staged } = classify(f.index, f.working_dir)
|
||||
const isNew = f.index === '?' || f.index === 'A'
|
||||
const isDeleted = letter === 'D'
|
||||
const original = isNew ? '' : await headText(g, path)
|
||||
const updated = isDeleted ? '' : await diskText(root, path)
|
||||
changes.push({ path, status: letter, staged, original, updated })
|
||||
}
|
||||
|
||||
return { branch, changes }
|
||||
}
|
||||
|
||||
export async function stage(root: string, paths: string[]): Promise<void> {
|
||||
// `git add` stages modifications, additions AND deletions of the given paths.
|
||||
await git(root).add(paths)
|
||||
}
|
||||
|
||||
export async function unstage(root: string, paths: string[]): Promise<void> {
|
||||
try {
|
||||
await git(root).reset(['--', ...paths])
|
||||
} catch {
|
||||
// empty repo (no HEAD yet): fall back to removing from the index.
|
||||
await git(root).raw(['rm', '--cached', '-r', '--', ...paths])
|
||||
}
|
||||
}
|
||||
|
||||
export async function commit(root: string, message: string): Promise<void> {
|
||||
await git(root).commit(message)
|
||||
}
|
||||
|
||||
export async function discard(root: string, paths: string[]): Promise<void> {
|
||||
await git(root).checkout(['--', ...paths])
|
||||
}
|
||||
141
src/main/index.ts
Normal file
141
src/main/index.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { join, sep } from 'node:path'
|
||||
import { app, shell, BrowserWindow, ipcMain } from 'electron'
|
||||
import { watch, type FSWatcher } from 'chokidar'
|
||||
import { getName, getRoot, openDialog } from './project'
|
||||
import { readAll, readProjectFile, readTree, writeProjectFile } from './fs-service'
|
||||
import { commit, discard, load, stage, unstage } from './git-service'
|
||||
import { createPty, killAllPtys, killPty, ptyAvailable, resizePty, writePty } from './pty-service'
|
||||
import { getConfig, getThemeCss, resolveConfig } from './config'
|
||||
import { listFiles, searchContent } from './search-service'
|
||||
|
||||
const isDev = !!process.env['ELECTRON_RENDERER_URL']
|
||||
const isMac = process.platform === 'darwin'
|
||||
|
||||
const WATCH_IGNORE = new Set([
|
||||
'node_modules', '.git', 'out', 'dist', 'build', '.next', '.nuxt',
|
||||
'.cache', 'coverage', 'vendor', '.idea', '.vscode', '.helder', '.turbo',
|
||||
])
|
||||
|
||||
let watcher: FSWatcher | null = null
|
||||
let configWatcher: FSWatcher | null = null
|
||||
let watchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
function broadcast(channel: string): void {
|
||||
for (const w of BrowserWindow.getAllWindows()) w.webContents.send(channel)
|
||||
}
|
||||
|
||||
function startConfigWatcher(): void {
|
||||
if (configWatcher) { configWatcher.close(); configWatcher = null }
|
||||
const root = getRoot()
|
||||
if (!root) return
|
||||
const dir = join(root, '.helder')
|
||||
configWatcher = watch([join(dir, 'config.json'), join(dir, 'theme.css')], { ignoreInitial: true })
|
||||
const reload = (): void => { resolveConfig(root).then(() => broadcast('config:changed')).catch(() => {}) }
|
||||
configWatcher.on('add', reload).on('change', reload).on('unlink', reload)
|
||||
}
|
||||
|
||||
function startWatcher(): void {
|
||||
if (watcher) { watcher.close(); watcher = null }
|
||||
const root = getRoot()
|
||||
if (!root) return
|
||||
watcher = watch(root, {
|
||||
ignoreInitial: true,
|
||||
ignored: (p: string) => p.split(sep).some((seg) => WATCH_IGNORE.has(seg)),
|
||||
})
|
||||
const ping = (): void => {
|
||||
if (watchTimer) clearTimeout(watchTimer)
|
||||
watchTimer = setTimeout(() => broadcast('project:changed'), 250)
|
||||
}
|
||||
watcher.on('add', ping).on('change', ping).on('unlink', ping).on('addDir', ping).on('unlinkDir', ping)
|
||||
}
|
||||
|
||||
function registerIpc(): void {
|
||||
ipcMain.handle('project:current', () => ({ root: getRoot(), name: getName() }))
|
||||
ipcMain.handle('project:open', async (e) => {
|
||||
const win = BrowserWindow.fromWebContents(e.sender)
|
||||
const next = await openDialog(win)
|
||||
if (next) {
|
||||
await resolveConfig(getRoot())
|
||||
startWatcher()
|
||||
startConfigWatcher()
|
||||
}
|
||||
return { root: getRoot(), name: getName() }
|
||||
})
|
||||
|
||||
ipcMain.handle('fs:tree', () => readTree(getRoot()))
|
||||
ipcMain.handle('fs:files', () => readAll(getRoot()))
|
||||
ipcMain.handle('fs:read', (_e, rel: string) => readProjectFile(getRoot(), rel))
|
||||
ipcMain.handle('fs:write', (_e, rel: string, content: string) => writeProjectFile(getRoot(), rel, content))
|
||||
|
||||
ipcMain.handle('git:load', () => load(getRoot()))
|
||||
ipcMain.handle('git:stage', (_e, paths: string[]) => stage(getRoot(), paths))
|
||||
ipcMain.handle('git:unstage', (_e, paths: string[]) => unstage(getRoot(), paths))
|
||||
ipcMain.handle('git:commit', (_e, message: string) => commit(getRoot(), message))
|
||||
ipcMain.handle('git:discard', (_e, paths: string[]) => discard(getRoot(), paths))
|
||||
|
||||
ipcMain.handle('pty:available', () => ptyAvailable())
|
||||
ipcMain.handle('pty:create', (e, kind: 'agent' | 'shell', cols: number, rows: number) => createPty(e.sender, kind, cols, rows))
|
||||
ipcMain.on('pty:write', (_e, id: number, data: string) => writePty(id, data))
|
||||
ipcMain.on('pty:resize', (_e, id: number, cols: number, rows: number) => resizePty(id, cols, rows))
|
||||
ipcMain.on('pty:kill', (_e, id: number) => killPty(id))
|
||||
|
||||
ipcMain.handle('config:get', () => getConfig())
|
||||
ipcMain.handle('config:theme', () => getThemeCss())
|
||||
|
||||
ipcMain.handle('search:content', (_e, query: string) => searchContent(getRoot(), query))
|
||||
ipcMain.handle('search:files', () => listFiles(getRoot()))
|
||||
}
|
||||
|
||||
function createWindow(): void {
|
||||
const win = new BrowserWindow({
|
||||
width: 1680,
|
||||
height: 1040,
|
||||
minWidth: 1100,
|
||||
minHeight: 680,
|
||||
show: false,
|
||||
backgroundColor: '#16171a',
|
||||
titleBarStyle: isMac ? 'hiddenInset' : 'default',
|
||||
trafficLightPosition: isMac ? { x: 14, y: 12 } : undefined,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: false,
|
||||
},
|
||||
})
|
||||
|
||||
win.on('ready-to-show', () => win.show())
|
||||
|
||||
win.webContents.setWindowOpenHandler(({ url }) => {
|
||||
shell.openExternal(url)
|
||||
return { action: 'deny' }
|
||||
})
|
||||
|
||||
if (isDev) {
|
||||
win.loadURL(process.env['ELECTRON_RENDERER_URL'] as string)
|
||||
} else {
|
||||
win.loadFile(join(__dirname, '../renderer/index.html'))
|
||||
}
|
||||
}
|
||||
|
||||
app.whenReady().then(async () => {
|
||||
app.setName('Helder')
|
||||
registerIpc()
|
||||
await resolveConfig(getRoot())
|
||||
startWatcher()
|
||||
startConfigWatcher()
|
||||
createWindow()
|
||||
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow()
|
||||
})
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
if (watcher) { watcher.close(); watcher = null }
|
||||
if (configWatcher) { configWatcher.close(); configWatcher = null }
|
||||
killAllPtys()
|
||||
if (!isMac) app.quit()
|
||||
})
|
||||
|
||||
app.on('before-quit', () => killAllPtys())
|
||||
45
src/main/project.ts
Normal file
45
src/main/project.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { basename } from 'node:path'
|
||||
import { existsSync, statSync } from 'node:fs'
|
||||
import { dialog, BrowserWindow } from 'electron'
|
||||
|
||||
/**
|
||||
* One project per window. The root is resolved (in order) from $HELDER_PROJECT,
|
||||
* a directory passed on argv, or the process working directory — then it can be
|
||||
* changed at runtime via the Open Folder dialog.
|
||||
*/
|
||||
function resolveInitialRoot(): string {
|
||||
const envRoot = process.env.HELDER_PROJECT
|
||||
if (envRoot && existsSync(envRoot) && statSync(envRoot).isDirectory()) return envRoot
|
||||
const argDir = process.argv.slice(1).find((a) => !a.startsWith('-') && existsSync(a) && safeIsDir(a))
|
||||
if (argDir) return argDir
|
||||
return process.cwd()
|
||||
}
|
||||
|
||||
function safeIsDir(p: string): boolean {
|
||||
try { return statSync(p).isDirectory() } catch { return false }
|
||||
}
|
||||
|
||||
let root = resolveInitialRoot()
|
||||
|
||||
export function getRoot(): string {
|
||||
return root
|
||||
}
|
||||
|
||||
export function getName(): string {
|
||||
return root ? basename(root) || root : 'no project'
|
||||
}
|
||||
|
||||
export function setRoot(next: string): void {
|
||||
root = next
|
||||
}
|
||||
|
||||
export async function openDialog(win: BrowserWindow | null): Promise<string | null> {
|
||||
const res = win
|
||||
? await dialog.showOpenDialog(win, { properties: ['openDirectory'] })
|
||||
: await dialog.showOpenDialog({ properties: ['openDirectory'] })
|
||||
if (!res.canceled && res.filePaths[0]) {
|
||||
root = res.filePaths[0]
|
||||
return root
|
||||
}
|
||||
return null
|
||||
}
|
||||
79
src/main/pty-service.ts
Normal file
79
src/main/pty-service.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import type { WebContents } from 'electron'
|
||||
import { getRoot } from './project'
|
||||
import { getConfig } from './config'
|
||||
|
||||
/**
|
||||
* Real PTYs. The agent pane is a shell that auto-launches the `claude` CLI; the
|
||||
* bottom pane is a plain shell. node-pty is a native module — loaded defensively
|
||||
* so the app still launches (with a friendly message) if it wasn't rebuilt for
|
||||
* this Electron via `npm run rebuild`.
|
||||
*
|
||||
* Shell + ai command/autoLaunch come from `.helder/config.json` (terminal.shell,
|
||||
* ai.command, ai.autoLaunch) via the config module.
|
||||
*/
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
type PtyModule = typeof import('node-pty')
|
||||
let pty: PtyModule | null = null
|
||||
try {
|
||||
pty = require('node-pty') as PtyModule
|
||||
} catch (e) {
|
||||
console.error('[helder] node-pty unavailable — run `npm run rebuild`:', (e as Error).message)
|
||||
}
|
||||
|
||||
const terms = new Map<number, import('node-pty').IPty>()
|
||||
let seq = 0
|
||||
|
||||
function defaultShell(): string {
|
||||
const configured = getConfig().terminal.shell
|
||||
if (configured) return configured
|
||||
if (process.platform === 'win32') return process.env.COMSPEC || 'powershell.exe'
|
||||
return process.env.SHELL || '/bin/zsh'
|
||||
}
|
||||
|
||||
export function ptyAvailable(): boolean {
|
||||
return !!pty
|
||||
}
|
||||
|
||||
export function createPty(sender: WebContents, kind: 'agent' | 'shell', cols: number, rows: number): number {
|
||||
if (!pty) return -1
|
||||
const cwd = getRoot() || process.env.HOME || process.cwd()
|
||||
const proc = pty.spawn(defaultShell(), [], {
|
||||
name: 'xterm-color',
|
||||
cols: cols || 80,
|
||||
rows: rows || 24,
|
||||
cwd,
|
||||
env: process.env as { [key: string]: string },
|
||||
})
|
||||
const id = ++seq
|
||||
terms.set(id, proc)
|
||||
|
||||
proc.onData((data) => { if (!sender.isDestroyed()) sender.send('pty:data', { id, data }) })
|
||||
proc.onExit(() => { terms.delete(id); if (!sender.isDestroyed()) sender.send('pty:exit', { id }) })
|
||||
|
||||
const ai = getConfig().ai
|
||||
if (kind === 'agent' && ai.autoLaunch) {
|
||||
// small delay so the shell prompt is ready before we type the command
|
||||
setTimeout(() => { try { proc.write(ai.command + '\r') } catch { /* exited */ } }, 350)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
export function writePty(id: number, data: string): void {
|
||||
terms.get(id)?.write(data)
|
||||
}
|
||||
|
||||
export function resizePty(id: number, cols: number, rows: number): void {
|
||||
try { terms.get(id)?.resize(cols, rows) } catch { /* race with exit */ }
|
||||
}
|
||||
|
||||
export function killPty(id: number): void {
|
||||
const p = terms.get(id)
|
||||
if (p) { try { p.kill() } catch { /* already gone */ } terms.delete(id) }
|
||||
}
|
||||
|
||||
export function killAllPtys(): void {
|
||||
for (const p of terms.values()) { try { p.kill() } catch { /* noop */ } }
|
||||
terms.clear()
|
||||
}
|
||||
87
src/main/search-service.ts
Normal file
87
src/main/search-service.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { relative, sep } from 'node:path'
|
||||
|
||||
/** Content search via ripgrep; file-name list via `rg --files`. Substring
|
||||
* (fixed-string), smart-case — matching the prototype's search semantics. */
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
let rgPath: string | null = null
|
||||
try {
|
||||
rgPath = (require('@vscode/ripgrep') as { rgPath: string }).rgPath
|
||||
} catch (e) {
|
||||
console.error('[helder] @vscode/ripgrep unavailable:', (e as Error).message)
|
||||
}
|
||||
|
||||
export interface ContentHit { no: number; ln: string; ix: number }
|
||||
export interface ContentGroup { path: string; hits: ContentHit[] }
|
||||
|
||||
const IGNORE_GLOBS = ['node_modules', '.git', 'out', 'dist', 'build', '.cache', 'vendor', 'coverage', '.helder']
|
||||
.flatMap((d) => ['--glob', `!${d}`])
|
||||
|
||||
const MAX_FILES = 400
|
||||
const MAX_LINE = 1000
|
||||
|
||||
function toRel(root: string, p: string): string {
|
||||
return relative(root, p).split(sep).join('/')
|
||||
}
|
||||
|
||||
export function searchContent(root: string, query: string): Promise<ContentGroup[]> {
|
||||
return new Promise((resolve) => {
|
||||
if (!rgPath || query.trim().length < 2) return resolve([])
|
||||
const child = spawn(rgPath, [
|
||||
'--json', '--fixed-strings', '--smart-case',
|
||||
'--max-count', '50', '--max-columns', '2000',
|
||||
...IGNORE_GLOBS, '-e', query, '--', root,
|
||||
])
|
||||
const order: string[] = []
|
||||
const groups = new Map<string, ContentGroup>()
|
||||
let buf = ''
|
||||
let done = false
|
||||
const finish = (): void => { if (done) return; done = true; resolve(order.slice(0, MAX_FILES).map((p) => groups.get(p)!)) }
|
||||
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
buf += chunk.toString()
|
||||
let nl: number
|
||||
while ((nl = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, nl); buf = buf.slice(nl + 1)
|
||||
if (!line) continue
|
||||
let msg: { type: string; data: { path?: { text?: string }; lines?: { text?: string }; line_number?: number; submatches?: { start: number }[] } }
|
||||
try { msg = JSON.parse(line) } catch { continue }
|
||||
if (msg.type !== 'match') continue
|
||||
const abs = msg.data.path?.text
|
||||
const text = msg.data.lines?.text
|
||||
if (!abs || text == null) continue
|
||||
const rel = toRel(root, abs)
|
||||
let g = groups.get(rel)
|
||||
if (!g) { if (groups.size >= MAX_FILES) continue; g = { path: rel, hits: [] }; groups.set(rel, g); order.push(rel) }
|
||||
const ln = text.replace(/\n$/, '').slice(0, MAX_LINE)
|
||||
const ix = msg.data.submatches && msg.data.submatches[0] ? msg.data.submatches[0].start : 0
|
||||
g.hits.push({ no: msg.data.line_number || 0, ln, ix: Math.min(ix, ln.length) })
|
||||
}
|
||||
})
|
||||
child.on('close', finish)
|
||||
child.on('error', finish)
|
||||
})
|
||||
}
|
||||
|
||||
export function listFiles(root: string): Promise<string[]> {
|
||||
return new Promise((resolve) => {
|
||||
if (!rgPath) return resolve([])
|
||||
const child = spawn(rgPath, ['--files', ...IGNORE_GLOBS, '--', root])
|
||||
let buf = ''
|
||||
const out: string[] = []
|
||||
let done = false
|
||||
const finish = (): void => { if (done) return; done = true; resolve(out) }
|
||||
child.stdout.on('data', (chunk: Buffer) => {
|
||||
buf += chunk.toString()
|
||||
let nl: number
|
||||
while ((nl = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, nl); buf = buf.slice(nl + 1)
|
||||
if (line) out.push(toRel(root, line))
|
||||
}
|
||||
})
|
||||
child.on('close', () => { if (buf.trim()) out.push(toRel(root, buf.trim())); finish() })
|
||||
child.on('error', finish)
|
||||
})
|
||||
}
|
||||
9
src/preload/index.d.ts
vendored
Normal file
9
src/preload/index.d.ts
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
import type { HelderApi } from './index'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
helder: HelderApi
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
85
src/preload/index.ts
Normal file
85
src/preload/index.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { contextBridge, clipboard, ipcRenderer } from 'electron'
|
||||
|
||||
/**
|
||||
* The single bridge between renderer and main. The renderer NEVER touches the
|
||||
* filesystem, git or the OS clipboard directly — everything goes through here.
|
||||
* (PTYs land here next, for the terminals.)
|
||||
*/
|
||||
const api = {
|
||||
platform: process.platform,
|
||||
|
||||
clipboard: {
|
||||
writeText: (text: string) => clipboard.writeText(text),
|
||||
},
|
||||
|
||||
project: {
|
||||
current: () => ipcRenderer.invoke('project:current'),
|
||||
open: () => ipcRenderer.invoke('project:open'),
|
||||
},
|
||||
|
||||
fs: {
|
||||
tree: () => ipcRenderer.invoke('fs:tree'),
|
||||
files: () => ipcRenderer.invoke('fs:files'),
|
||||
read: (path: string) => ipcRenderer.invoke('fs:read', path),
|
||||
write: (path: string, content: string): Promise<void> => ipcRenderer.invoke('fs:write', path, content),
|
||||
},
|
||||
|
||||
git: {
|
||||
load: () => ipcRenderer.invoke('git:load'),
|
||||
stage: (paths: string[]) => ipcRenderer.invoke('git:stage', paths),
|
||||
unstage: (paths: string[]) => ipcRenderer.invoke('git:unstage', paths),
|
||||
commit: (message: string) => ipcRenderer.invoke('git:commit', message),
|
||||
discard: (paths: string[]) => ipcRenderer.invoke('git:discard', paths),
|
||||
},
|
||||
|
||||
pty: {
|
||||
available: (): Promise<boolean> => ipcRenderer.invoke('pty:available'),
|
||||
create: (kind: 'agent' | 'shell', cols: number, rows: number): Promise<number> =>
|
||||
ipcRenderer.invoke('pty:create', kind, cols, rows),
|
||||
write: (id: number, data: string): void => ipcRenderer.send('pty:write', id, data),
|
||||
resize: (id: number, cols: number, rows: number): void => ipcRenderer.send('pty:resize', id, cols, rows),
|
||||
kill: (id: number): void => ipcRenderer.send('pty:kill', id),
|
||||
onData: (cb: (id: number, data: string) => void): (() => void) => {
|
||||
const h = (_e: unknown, p: { id: number; data: string }): void => cb(p.id, p.data)
|
||||
ipcRenderer.on('pty:data', h)
|
||||
return () => ipcRenderer.removeListener('pty:data', h)
|
||||
},
|
||||
onExit: (cb: (id: number) => void): (() => void) => {
|
||||
const h = (_e: unknown, p: { id: number }): void => cb(p.id)
|
||||
ipcRenderer.on('pty:exit', h)
|
||||
return () => ipcRenderer.removeListener('pty:exit', h)
|
||||
},
|
||||
},
|
||||
|
||||
config: {
|
||||
get: () => ipcRenderer.invoke('config:get'),
|
||||
theme: (): Promise<string> => ipcRenderer.invoke('config:theme'),
|
||||
},
|
||||
|
||||
search: {
|
||||
content: (query: string) => ipcRenderer.invoke('search:content', query),
|
||||
files: (): Promise<string[]> => ipcRenderer.invoke('search:files'),
|
||||
},
|
||||
|
||||
/** Subscribe to "the project changed on disk" pings. Returns an unsubscribe. */
|
||||
onProjectChanged: (cb: () => void): (() => void) => {
|
||||
const handler = (): void => cb()
|
||||
ipcRenderer.on('project:changed', handler)
|
||||
return () => ipcRenderer.removeListener('project:changed', handler)
|
||||
},
|
||||
|
||||
/** Subscribe to .helder config/theme edits. Returns an unsubscribe. */
|
||||
onConfigChanged: (cb: () => void): (() => void) => {
|
||||
const handler = (): void => cb()
|
||||
ipcRenderer.on('config:changed', handler)
|
||||
return () => ipcRenderer.removeListener('config:changed', handler)
|
||||
},
|
||||
}
|
||||
|
||||
if (process.contextIsolated) {
|
||||
contextBridge.exposeInMainWorld('helder', api)
|
||||
} else {
|
||||
;(globalThis as unknown as { helder: typeof api }).helder = api
|
||||
}
|
||||
|
||||
export type HelderApi = typeof api
|
||||
12
src/renderer/index.html
Normal file
12
src/renderer/index.html
Normal file
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Helder</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
356
src/renderer/src/App.tsx
Normal file
356
src/renderer/src/App.tsx
Normal file
@@ -0,0 +1,356 @@
|
||||
/* App shell: 4 resizable columns, keyboard shortcuts, copy-reference, status bar */
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { HL } from './highlight'
|
||||
import { FileTree, GitPanel, Icon } from './components'
|
||||
import type { ContextTarget } from './components'
|
||||
import { Editor, SplitView } from './editor'
|
||||
import type { Cursor, Mode, Selection } from './editor'
|
||||
import { Terminal, lid } from './terminals'
|
||||
import { ContextMenu, PassPopup, SearchModal, Toasts } from './overlays'
|
||||
import type { Menu, Toast } from './overlays'
|
||||
import type { FileNode, GitStatus } from './types'
|
||||
import { useProject, useProjectActions } from './project'
|
||||
|
||||
const NO_COMMITTED = new Set<string>()
|
||||
|
||||
function Splitter({ orientation = 'v', onDelta }: { orientation?: 'v' | 'h'; onDelta: (dx: number, dy: number) => void }): React.ReactElement {
|
||||
const [drag, setDrag] = useState(false)
|
||||
function down(e: React.MouseEvent): void {
|
||||
e.preventDefault()
|
||||
let last = { x: e.clientX, y: e.clientY }
|
||||
setDrag(true)
|
||||
document.body.style.cursor = orientation === 'v' ? 'col-resize' : 'row-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
function mv(ev: MouseEvent): void {
|
||||
onDelta(ev.clientX - last.x, ev.clientY - last.y)
|
||||
last = { x: ev.clientX, y: ev.clientY }
|
||||
}
|
||||
function up(): void {
|
||||
setDrag(false)
|
||||
document.body.style.cursor = ''; document.body.style.userSelect = ''
|
||||
document.removeEventListener('mousemove', mv); document.removeEventListener('mouseup', up)
|
||||
}
|
||||
document.addEventListener('mousemove', mv); document.addEventListener('mouseup', up)
|
||||
}
|
||||
return <div className={'splitter' + (orientation === 'h' ? ' h' : '') + (drag ? ' drag' : '')} onMouseDown={down} />
|
||||
}
|
||||
|
||||
function RightColumn({ width }: { width: number }): React.ReactElement {
|
||||
const [topFrac, setTopFrac] = useState(0.52)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
function delta(_dx: number, dy: number): void {
|
||||
const h = ref.current ? ref.current.clientHeight : 600
|
||||
setTopFrac((f) => Math.max(0.18, Math.min(0.82, (f * h + dy) / h)))
|
||||
}
|
||||
return (
|
||||
<div className="col right-col" style={{ width, flex: '0 0 ' + width + 'px' }}>
|
||||
<div ref={ref} style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
|
||||
<div style={{ flex: '0 0 ' + (topFrac * 100) + '%', minHeight: 0, display: 'flex' }}>
|
||||
<Terminal kind="agent" />
|
||||
</div>
|
||||
<Splitter orientation="h" onDelta={delta} />
|
||||
<div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
|
||||
<Terminal kind="shell" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function clamp(v: number, lo: number, hi: number): number { return Math.max(lo, Math.min(hi, v)) }
|
||||
function ancestors(path: string): string[] {
|
||||
const parts = path.split('/'); const out: string[] = []
|
||||
for (let i = 1; i < parts.length; i++) out.push(parts.slice(0, i).join('/'))
|
||||
return out
|
||||
}
|
||||
function initialOpenDirs(node: FileNode, set: Set<string>): Set<string> {
|
||||
if (node.type === 'dir') {
|
||||
if (node.open && node.path) set.add(node.path)
|
||||
;(node.children || []).forEach((c) => initialOpenDirs(c, set))
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
export function App(): React.ReactElement {
|
||||
const proj = useProject()
|
||||
const actions = useProjectActions()
|
||||
|
||||
const changeMap = useMemo(() => Object.fromEntries(proj.changes.map((c) => [c.path, c.status])) as Record<string, GitStatus>, [proj.changes])
|
||||
const changeSet = useMemo(() => new Set(proj.changes.map((c) => c.path)), [proj.changes])
|
||||
|
||||
const [tabs, setTabs] = useState<{ path: string }[]>([])
|
||||
const [active, setActive] = useState<string | null>(null)
|
||||
const [tabMode, setTabMode] = useState<Record<string, Mode>>({})
|
||||
const [openDirs, setOpenDirs] = useState<Set<string>>(new Set())
|
||||
const [cursor, setCursor] = useState<Cursor | null>(null)
|
||||
const [selection, setSelection] = useState<Selection | null>(null)
|
||||
const [overlay, setOverlay] = useState<'search' | null>(null)
|
||||
const [menu, setMenu] = useState<Menu | null>(null)
|
||||
const [toasts, setToasts] = useState<Toast[]>([])
|
||||
const [splitFor, setSplitFor] = useState<string | null>(null)
|
||||
const [commitMsg, setCommitMsg] = useState('')
|
||||
const [passPopup, setPassPopup] = useState<{ x: number; y: number; ref: string } | null>(null)
|
||||
|
||||
// Editable buffers: path → current text (absent = clean, showing on-disk content).
|
||||
const [buffers, setBuffers] = useState<Record<string, string>>({})
|
||||
const buffersRef = useRef(buffers); buffersRef.current = buffers
|
||||
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
function diskText(path: string): string { return proj.files[path] ?? '' }
|
||||
function bufferText(path: string | null): string { return path ? (buffers[path] ?? diskText(path)) : '' }
|
||||
function isDirty(path: string): boolean { return buffers[path] != null && buffers[path] !== diskText(path) }
|
||||
|
||||
function writeToDisk(path: string, text: string): void {
|
||||
if (window.helder) window.helder.fs.write(path, text).catch(() => toast('Save failed', path))
|
||||
}
|
||||
function saveActive(): void {
|
||||
if (!active) return
|
||||
const text = buffersRef.current[active]
|
||||
if (text == null || text === diskText(active)) return
|
||||
writeToDisk(active, text)
|
||||
toast('Saved', active)
|
||||
}
|
||||
function onEdit(text: string): void {
|
||||
if (!active) return
|
||||
const path = active
|
||||
setBuffers((b) => ({ ...b, [path]: text }))
|
||||
if (proj.config.editor.autoSave) {
|
||||
if (saveTimer.current) clearTimeout(saveTimer.current)
|
||||
saveTimer.current = setTimeout(() => writeToDisk(path, text), 600)
|
||||
}
|
||||
}
|
||||
function doDiscard(path: string): void {
|
||||
if (proj.config.git.confirmDiscard &&
|
||||
!window.confirm(`Discard changes to ${path}?\nThis reverts the file to the last commit and cannot be undone.`)) return
|
||||
actions.discard(path)
|
||||
setBuffers((b) => { const n = { ...b }; delete n[path]; return n })
|
||||
toast('Discarded changes', path)
|
||||
}
|
||||
|
||||
const [gitW, setGitW] = useState(232)
|
||||
const [treeW, setTreeW] = useState(244)
|
||||
const [rightW, setRightW] = useState(444)
|
||||
|
||||
// Seed explorer expansion from the tree's `open` flags once per opened project.
|
||||
const seededRoot = useRef<string | null | undefined>(undefined)
|
||||
useEffect(() => {
|
||||
if (proj.tree && seededRoot.current !== proj.root) {
|
||||
seededRoot.current = proj.root
|
||||
setOpenDirs(initialOpenDirs(proj.tree, new Set()))
|
||||
}
|
||||
}, [proj.tree, proj.root])
|
||||
|
||||
function toast(title: string, ref?: string): void {
|
||||
const id = lid()
|
||||
setToasts((t) => [...t, { id, title, ref }])
|
||||
setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 2300)
|
||||
}
|
||||
async function copyText(text: string, label?: string): Promise<void> {
|
||||
try {
|
||||
if (window.helder && window.helder.clipboard) window.helder.clipboard.writeText(text)
|
||||
else await navigator.clipboard.writeText(text)
|
||||
} catch {
|
||||
const ta = document.createElement('textarea'); ta.value = text
|
||||
ta.style.position = 'fixed'; ta.style.opacity = '0'; document.body.appendChild(ta)
|
||||
ta.select(); try { document.execCommand('copy') } catch { /* noop */ } ta.remove()
|
||||
}
|
||||
toast(label || 'Copied reference', text)
|
||||
}
|
||||
|
||||
const toggleDir = useCallback((p: string) => {
|
||||
setOpenDirs((s) => { const n = new Set(s); n.has(p) ? n.delete(p) : n.add(p); return n })
|
||||
}, [])
|
||||
|
||||
function reveal(path: string): void {
|
||||
setOpenDirs((s) => { const n = new Set(s); ancestors(path).forEach((a) => n.add(a)); return n })
|
||||
}
|
||||
|
||||
function commit(): void {
|
||||
const msg = commitMsg.trim()
|
||||
if (!msg) return
|
||||
actions.commit(msg).then((n) => {
|
||||
if (n > 0) toast(`Committed ${n} file${n > 1 ? 's' : ''}`, msg.length > 34 ? msg.slice(0, 34) + '…' : msg)
|
||||
})
|
||||
setCommitMsg('')
|
||||
}
|
||||
|
||||
function openFile(path: string, opts: { diff?: boolean; line?: number } = {}): void {
|
||||
const changed = !!proj.diffs[path]
|
||||
actions.ensureFile(path)
|
||||
setTabs((t) => t.some((x) => x.path === path) ? t : [...t, { path }])
|
||||
setActive(path)
|
||||
setTabMode((m) => ({ ...m, [path]: opts.diff && changed ? 'diff' : (m[path] || (changed ? 'diff' : 'code')) }))
|
||||
reveal(path)
|
||||
if (opts.line) {
|
||||
// show the current/updated file so line numbers map to search hits
|
||||
setSplitFor(null)
|
||||
setTabMode((m) => ({ ...m, [path]: changed ? 'updated' : 'code' }))
|
||||
setCursor({ path, line: opts.line, col: 1 })
|
||||
setSelection(null)
|
||||
setTimeout(() => {
|
||||
const row = document.querySelector('.editor .ln-row[data-line="' + opts.line + '"]') as HTMLElement | null
|
||||
if (row) { const ed = row.closest('.editor') as HTMLElement; const er = ed.getBoundingClientRect(), rr = row.getBoundingClientRect(); ed.scrollTop += (rr.top - er.top) - ed.clientHeight / 2 }
|
||||
}, 70)
|
||||
}
|
||||
}
|
||||
|
||||
function closeTab(path: string): void {
|
||||
setTabs((t) => {
|
||||
const ix = t.findIndex((x) => x.path === path)
|
||||
const next = t.filter((x) => x.path !== path)
|
||||
if (path === active) {
|
||||
const fallback = next[ix] || next[ix - 1] || next[next.length - 1]
|
||||
setActive(fallback ? fallback.path : null)
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
// ---- context menus ----
|
||||
function openMenu(e: React.MouseEvent, target: ContextTarget): void {
|
||||
e.preventDefault(); e.stopPropagation()
|
||||
const sparkSend = (ref: string): Menu['items'][number] => ({ icon: Icon.spark(), label: 'Send reference to agent', onClick: () => { window.dispatchEvent(new CustomEvent('agentPaste', { detail: ref })); toast('Passed to agent', ref) } })
|
||||
if (target.kind === 'editor') {
|
||||
const ref = target.sel ? `${target.path}:${target.sel.start}-${target.sel.end}` : `${target.path}:${target.line}`
|
||||
const mx = e.clientX, my = e.clientY
|
||||
setMenu({
|
||||
x: mx, y: my, note: ref,
|
||||
items: [
|
||||
{ primary: true, icon: Icon.copy(), label: 'Copy reference', onClick: () => copyText(ref) },
|
||||
{ icon: Icon.spark(), label: 'Pass on to Agent', onClick: () => setPassPopup({ x: mx, y: my, ref }) },
|
||||
],
|
||||
})
|
||||
} else {
|
||||
const isDir = target.kind === 'dir'
|
||||
const ref = isDir ? target.path + '/' : target.path
|
||||
const name = target.path.split('/').pop() as string
|
||||
const items: Menu['items'] = [
|
||||
{ primary: true, icon: Icon.copy(), label: 'Copy reference', onClick: () => copyText(ref) },
|
||||
sparkSend(ref),
|
||||
{ icon: Icon.copy(), label: isDir ? 'Copy folder path' : 'Copy file name', onClick: () => copyText(isDir ? target.path : name, 'Copied') },
|
||||
]
|
||||
if (!isDir) {
|
||||
items.push({ sep: true })
|
||||
if (target.kind === 'git') {
|
||||
const isStaged = proj.staged.has(target.path)
|
||||
items.push(isStaged
|
||||
? { icon: Icon.minus(), label: 'Unstage changes', onClick: () => actions.unstage(target.path) }
|
||||
: { icon: Icon.plus(), label: 'Stage changes', onClick: () => actions.stage(target.path) })
|
||||
items.push({ icon: Icon.diff(), label: 'Open diff', onClick: () => openFile(target.path, { diff: true }) })
|
||||
items.push({ icon: Icon.discard(), label: 'Discard changes', onClick: () => doDiscard(target.path) })
|
||||
}
|
||||
items.push({ icon: Icon.file(), label: 'Open file', onClick: () => openFile(target.path) })
|
||||
items.push({ icon: Icon.reveal(), label: 'Reveal in Explorer', onClick: () => reveal(target.path) })
|
||||
}
|
||||
setMenu({ x: e.clientX, y: e.clientY, note: ref, items })
|
||||
}
|
||||
}
|
||||
|
||||
// ---- shortcuts ----
|
||||
useEffect(() => {
|
||||
function onKey(e: KeyboardEvent): void {
|
||||
const meta = e.metaKey || e.ctrlKey
|
||||
if (meta && e.key.toLowerCase() === 'f') { e.preventDefault(); setOverlay('search') }
|
||||
else if (meta && e.key.toLowerCase() === 's') { e.preventDefault(); saveActive() }
|
||||
else if (meta && e.key.toLowerCase() === 'w') { e.preventDefault(); if (active) closeTab(active) }
|
||||
else if (e.key === 'Escape') { if (splitFor) setSplitFor(null); else { setOverlay(null); setMenu(null) } }
|
||||
}
|
||||
window.addEventListener('keydown', onKey)
|
||||
return () => window.removeEventListener('keydown', onKey)
|
||||
}, [active, splitFor])
|
||||
|
||||
const MODE_LABEL: Record<string, string> = { original: 'orig', updated: 'upd', diff: 'diff', code: '' }
|
||||
const MODE_WORD: Record<string, string> = { original: 'Original', updated: 'Updated', diff: 'Diff' }
|
||||
const resolvedTabs = tabs.map((t) => {
|
||||
const changed = !!proj.diffs[t.path]
|
||||
const m = tabMode[t.path] || (changed ? 'diff' : 'code')
|
||||
return { ...t, changed, modeLabel: splitFor === t.path ? 'split' : MODE_LABEL[m], dirty: isDirty(t.path) }
|
||||
})
|
||||
const mode: Mode = (active && tabMode[active]) || (active && proj.diffs[active] ? 'diff' : 'code')
|
||||
const totals = proj.changes.reduce((a, c) => ({ add: a.add + c.add, del: a.del + c.del }), { add: 0, del: 0 })
|
||||
const activeLang = active ? HL.langLabel(active) : ''
|
||||
|
||||
const crumb = active ? active.split('/') : []
|
||||
const curLine = cursor && active && cursor.path === active ? cursor.line : 1
|
||||
const curCol = cursor && active && cursor.path === active ? cursor.col : 1
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
{/* title bar */}
|
||||
<div className="titlebar">
|
||||
<div className="traffic"><i className="r" /><i className="y" /><i className="g" /></div>
|
||||
<div className="tb-title">{Icon.spark({ style: { color: 'var(--accent)' } })}<b>Helder</b><span style={{ color: 'var(--fg-3)' }}>—</span>
|
||||
<span style={{ color: 'var(--fg-2)', cursor: 'pointer' }} title="Open folder…" onClick={() => actions.openFolder()}>{proj.name}</span>
|
||||
</div>
|
||||
{active && (
|
||||
<div className="tb-crumb">
|
||||
{crumb.map((s, i) => (<React.Fragment key={i}>{i > 0 && <span className="seg"> › </span>}<span style={i === crumb.length - 1 ? { color: 'var(--fg-1)' } : undefined}>{s}</span></React.Fragment>))}
|
||||
</div>
|
||||
)}
|
||||
<div className="tb-spacer" />
|
||||
<div className="tb-actions">
|
||||
<button className="tb-btn" onClick={() => setOverlay('search')}>{Icon.search()} Search <kbd>⌘F</kbd></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* workbench */}
|
||||
<div className="workbench">
|
||||
<div className="col" style={{ width: gitW, flex: '0 0 ' + gitW + 'px' }}>
|
||||
<GitPanel branch={proj.branch} changes={proj.changes} staged={proj.staged} committed={NO_COMMITTED}
|
||||
commitMsg={commitMsg} setCommitMsg={setCommitMsg}
|
||||
onStage={actions.stage} onUnstage={actions.unstage} onStageAll={actions.stageAll} onUnstageAll={actions.unstageAll} onCommit={commit}
|
||||
onOpen={openFile} onContext={openMenu} activePath={active} />
|
||||
</div>
|
||||
<Splitter onDelta={(dx) => setGitW((w) => clamp(w + dx, 160, 460))} />
|
||||
|
||||
<div className="col" style={{ width: treeW, flex: '0 0 ' + treeW + 'px' }}>
|
||||
{proj.tree ? (
|
||||
<FileTree tree={proj.tree} openDirs={openDirs} toggleDir={toggleDir} onOpen={openFile}
|
||||
onContext={openMenu} activePath={active} changeMap={changeMap} committed={NO_COMMITTED} />
|
||||
) : (
|
||||
<div className="phead"><span>Explorer</span></div>
|
||||
)}
|
||||
</div>
|
||||
<Splitter onDelta={(dx) => setTreeW((w) => clamp(w + dx, 160, 520))} />
|
||||
|
||||
<div className="col editor-col">
|
||||
<Editor tabs={resolvedTabs} active={active} mode={mode}
|
||||
setMode={(m) => { if (active) { setTabMode((mm) => ({ ...mm, [active]: m })); setSplitFor(null) } }}
|
||||
onActivate={setActive} onClose={closeTab} onContext={openMenu}
|
||||
onSplit={(p) => setSplitFor(p)} splitOpen={splitFor === active}
|
||||
cursor={cursor} selection={selection} setCursor={setCursor} setSelection={setSelection}
|
||||
bufferText={bufferText(active)} onEdit={onEdit} />
|
||||
</div>
|
||||
<Splitter onDelta={(dx) => setRightW((w) => clamp(w - dx, 280, 780))} />
|
||||
|
||||
<RightColumn width={rightW} />
|
||||
</div>
|
||||
|
||||
{/* status bar */}
|
||||
<div className="statusbar">
|
||||
<div className="sb accent">{Icon.branch({ width: 12, height: 12 })}<span style={{ color: '#0c1320' }}>{proj.branch}</span></div>
|
||||
<div className="sb"><span className="a">+{totals.add}</span> <span className="d">−{totals.del}</span></div>
|
||||
<div className="sb spacer" />
|
||||
{active && <div className="sb">{selection && selection.path === active && selection.start !== selection.end ? `${selection.end - selection.start + 1} lines selected` : `Ln ${curLine}, Col ${curCol}`}</div>}
|
||||
{active && <div className="sb">Spaces: 4</div>}
|
||||
{active && <div className="sb">UTF-8</div>}
|
||||
{active && <div className="sb"><b>{activeLang}</b></div>}
|
||||
{active && proj.diffs[active] && <div className="sb">{splitFor === active ? 'Split' : (MODE_WORD[mode] || '')}</div>}
|
||||
</div>
|
||||
|
||||
{/* overlays */}
|
||||
{splitFor && <SplitView path={splitFor} onClose={() => setSplitFor(null)} onContext={openMenu} />}
|
||||
{passPopup && <PassPopup x={passPopup.x} y={passPopup.y} refStr={passPopup.ref}
|
||||
onConfirm={(text) => {
|
||||
const line = (text && text.trim() ? text.trim() + ' ' : '') + passPopup.ref
|
||||
window.dispatchEvent(new CustomEvent('agentPaste', { detail: line }))
|
||||
setPassPopup(null)
|
||||
toast('Passed to agent', passPopup.ref)
|
||||
}}
|
||||
onCancel={() => setPassPopup(null)} />}
|
||||
{overlay === 'search' && <SearchModal onOpen={openFile} onOpenAt={(p, n) => openFile(p, { line: n })} onClose={() => setOverlay(null)} changeSet={changeSet} />}
|
||||
{menu && <ContextMenu menu={menu} onClose={() => setMenu(null)} />}
|
||||
<Toasts toasts={toasts} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
240
src/renderer/src/components.tsx
Normal file
240
src/renderer/src/components.tsx
Normal file
@@ -0,0 +1,240 @@
|
||||
/* Shared icons, FileIcon, GitPanel, FileTree */
|
||||
import React, { Fragment } from 'react'
|
||||
import type { Change, FileNode, GitStatus } from './types'
|
||||
import { HL } from './highlight'
|
||||
|
||||
type SvgProps = React.SVGProps<SVGSVGElement>
|
||||
|
||||
/* ---- minimal geometric icons ---- */
|
||||
export const Icon: Record<string, (p?: SvgProps) => React.ReactElement> = {
|
||||
search: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><circle cx="7" cy="7" r="4.5" stroke="currentColor" strokeWidth="1.4" /><line x1="10.5" y1="10.5" x2="14" y2="14" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /></svg>),
|
||||
branch: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><circle cx="4" cy="3.5" r="1.8" stroke="currentColor" strokeWidth="1.3" /><circle cx="4" cy="12.5" r="1.8" stroke="currentColor" strokeWidth="1.3" /><circle cx="12" cy="5" r="1.8" stroke="currentColor" strokeWidth="1.3" /><path d="M4 5.3v5.4M5.8 5C9 5 10 6.2 10 9v0" stroke="currentColor" strokeWidth="1.3" fill="none" /></svg>),
|
||||
close: (p) => (<svg width="11" height="11" viewBox="0 0 12 12" fill="none" {...p}><path d="M3 3l6 6M9 3l-6 6" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /></svg>),
|
||||
copy: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><rect x="5" y="5" width="8" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.3" /><path d="M3 11V3a1 1 0 0 1 1-1h6" stroke="currentColor" strokeWidth="1.3" fill="none" /></svg>),
|
||||
terminal: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><path d="M3 4l3 3-3 3M8 11h5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round" /></svg>),
|
||||
spark: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><path d="M8 1.5l1.6 4.9L14.5 8l-4.9 1.6L8 14.5 6.4 9.6 1.5 8l4.9-1.6L8 1.5z" stroke="currentColor" strokeWidth="1.1" fill="none" strokeLinejoin="round" /></svg>),
|
||||
file: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><path d="M4 2h5l3 3v9H4V2z" stroke="currentColor" strokeWidth="1.2" fill="none" /><path d="M9 2v3h3" stroke="currentColor" strokeWidth="1.2" fill="none" /></svg>),
|
||||
reveal: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><path d="M2 4.5h4l1.3 1.5H14V13H2V4.5z" stroke="currentColor" strokeWidth="1.2" fill="none" /></svg>),
|
||||
diff: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><path d="M4 2v8M4 12.5v1.5M2 4h4M2 8h4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" /><path d="M12 14V6M12 3.5V2M10 12h4M10 8h4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" /></svg>),
|
||||
plus: (p) => (<svg width="13" height="13" viewBox="0 0 14 14" fill="none" {...p}><path d="M7 2.5v9M2.5 7h9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg>),
|
||||
minus: (p) => (<svg width="13" height="13" viewBox="0 0 14 14" fill="none" {...p}><path d="M2.5 7h9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /></svg>),
|
||||
check: (p) => (<svg width="13" height="13" viewBox="0 0 14 14" fill="none" {...p}><path d="M2.5 7.5l2.8 3L11.5 3.5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg>),
|
||||
discard: (p) => (<svg width="13" height="13" viewBox="0 0 16 16" fill="none" {...p}><path d="M12.5 5.5A5 5 0 1 0 13 9" stroke="currentColor" strokeWidth="1.3" fill="none" strokeLinecap="round" /><path d="M12.5 2.5v3h-3" stroke="currentColor" strokeWidth="1.3" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>),
|
||||
}
|
||||
|
||||
export const Chevron = ({ open }: { open: boolean }): React.ReactElement => (
|
||||
<svg width="9" height="9" viewBox="0 0 10 10" style={{ transform: open ? 'rotate(90deg)' : 'none', transition: 'transform .12s' }}>
|
||||
<path d="M3.5 2l3.5 3-3.5 3" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
export const FolderIcon = ({ open }: { open: boolean }): React.ReactElement => (
|
||||
<svg className="folder-ic" width="14" height="14" viewBox="0 0 16 16" fill="none">
|
||||
<path d={open ? 'M1.5 4.5h4l1.2 1.4H14V13H2V4.5z' : 'M1.5 4.5h4l1.2 1.4H14V13H1.5V4.5z'}
|
||||
fill={open ? 'rgba(122,131,140,.18)' : 'rgba(122,131,140,.12)'} stroke="currentColor" strokeWidth="1.1" />
|
||||
</svg>
|
||||
)
|
||||
|
||||
export function FileIcon({ path }: { path: string }): React.ReactElement {
|
||||
const ic = HL.iconFor(path)
|
||||
return <span className="ficon" style={{ background: ic.c }}><span>{ic.t}</span></span>
|
||||
}
|
||||
|
||||
/* Shared callback signatures used across panels. */
|
||||
export type OpenFile = (path: string, opts?: { diff?: boolean; line?: number }) => void
|
||||
export interface ContextTarget {
|
||||
path: string
|
||||
kind: 'editor' | 'dir' | 'file' | 'git'
|
||||
staged?: boolean
|
||||
sel?: { start: number; end: number }
|
||||
line?: number
|
||||
}
|
||||
export type OnContext = (e: React.MouseEvent, target: ContextTarget) => void
|
||||
|
||||
/* ============ Git / Source Control panel ============ */
|
||||
function GitRow({ c, staged, activePath, onOpen, onContext, onToggleStage }: {
|
||||
c: Change
|
||||
staged: boolean
|
||||
activePath: string | null
|
||||
onOpen: OpenFile
|
||||
onContext: OnContext
|
||||
onToggleStage: (path: string) => void
|
||||
}): React.ReactElement {
|
||||
const name = c.path.split('/').pop()
|
||||
const dir = c.path.split('/').slice(0, -1).join('/')
|
||||
return (
|
||||
<div className={'git-row' + (activePath === c.path ? ' active' : '')}
|
||||
onClick={() => onOpen(c.path, { diff: true })}
|
||||
onContextMenu={(e) => onContext(e, { path: c.path, kind: 'git', staged })}
|
||||
title={c.path}>
|
||||
<span className={'git-stat ' + c.status}>{c.status}</span>
|
||||
<FileIcon path={c.path} />
|
||||
<span className={'git-name' + (c.deleted ? ' del' : '')}>{name}</span>
|
||||
{dir && <span className="git-dir">{dir}/</span>}
|
||||
<button className="git-act" title={staged ? 'Unstage changes' : 'Stage changes'}
|
||||
onClick={(e) => { e.stopPropagation(); onToggleStage(c.path) }}>
|
||||
{staged ? Icon.minus() : Icon.plus()}
|
||||
</button>
|
||||
<span className="git-delta">
|
||||
{c.add > 0 && <span className="a">+{c.add}</span>}
|
||||
{c.del > 0 && <span className="d">-{c.del}</span>}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function GitPanel({ branch, changes, staged, committed, commitMsg, setCommitMsg, onStage, onUnstage, onStageAll, onUnstageAll, onCommit, onOpen, onContext, activePath }: {
|
||||
branch: string
|
||||
changes: Change[]
|
||||
staged: Set<string>
|
||||
committed: Set<string>
|
||||
commitMsg: string
|
||||
setCommitMsg: (v: string) => void
|
||||
onStage: (path: string) => void
|
||||
onUnstage: (path: string) => void
|
||||
onStageAll: () => void
|
||||
onUnstageAll: () => void
|
||||
onCommit: () => void
|
||||
onOpen: OpenFile
|
||||
onContext: OnContext
|
||||
activePath: string | null
|
||||
}): React.ReactElement {
|
||||
const visible = changes.filter((c) => !committed.has(c.path))
|
||||
const stagedList = visible.filter((c) => staged.has(c.path))
|
||||
const changesList = visible.filter((c) => !staged.has(c.path))
|
||||
const totals = visible.reduce((a, c) => ({ add: a.add + c.add, del: a.del + c.del }), { add: 0, del: 0 })
|
||||
const canCommit = stagedList.length > 0 && commitMsg.trim().length > 0
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<div className="phead">
|
||||
{Icon.branch()}<span>Source Control</span>
|
||||
<span className="ct">{visible.length}</span>
|
||||
</div>
|
||||
|
||||
<div className="commit-box">
|
||||
<textarea className="commit-input" rows={1} value={commitMsg} spellCheck={false}
|
||||
placeholder="Message (⌘↵ to commit)"
|
||||
onChange={(e) => setCommitMsg(e.target.value)}
|
||||
onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) { e.preventDefault(); onCommit() } }} />
|
||||
<button className="commit-btn" disabled={!canCommit} onClick={onCommit}
|
||||
title={canCommit ? 'Commit staged changes' : 'Stage files and write a message to commit'}>
|
||||
{Icon.check()}<span>Commit{stagedList.length ? ' ' + stagedList.length : ''}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="git-body">
|
||||
{visible.length === 0 ? (
|
||||
<div className="git-empty">{Icon.check({ width: 20, height: 20 })}<span>No changes — working tree clean</span></div>
|
||||
) : (
|
||||
<Fragment>
|
||||
<div className="git-group">
|
||||
Staged Changes <span className="gc">{stagedList.length}</span>
|
||||
{stagedList.length > 0 && <button className="grp-act" title="Unstage all" onClick={onUnstageAll}>{Icon.minus()}</button>}
|
||||
</div>
|
||||
{stagedList.length > 0 ? stagedList.map((c) => (
|
||||
<GitRow key={c.path} c={c} staged={true} activePath={activePath}
|
||||
onOpen={onOpen} onContext={onContext} onToggleStage={onUnstage} />
|
||||
)) : (
|
||||
<div className="git-none">Nothing staged — use <span className="key">+</span> to stage a file</div>
|
||||
)}
|
||||
|
||||
<div className="git-divider" />
|
||||
|
||||
<div className="git-group">
|
||||
Changes <span className="gc">{changesList.length}</span>
|
||||
{changesList.length > 0 && <button className="grp-act" title="Stage all" onClick={onStageAll}>{Icon.plus()}</button>}
|
||||
</div>
|
||||
{changesList.length > 0 ? changesList.map((c) => (
|
||||
<GitRow key={c.path} c={c} staged={false} activePath={activePath}
|
||||
onOpen={onOpen} onContext={onContext} onToggleStage={onStage} />
|
||||
)) : (
|
||||
<div className="git-none">All changes staged</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="git-foot">
|
||||
<span className="branch-chip">{Icon.branch()}<b>{branch}</b></span>
|
||||
<span style={{ marginLeft: 'auto', fontFamily: 'var(--mono)' }}>
|
||||
<span className="a" style={{ color: 'var(--add)' }}>+{totals.add}</span>{' '}
|
||||
<span className="d" style={{ color: 'var(--del)' }}>-{totals.del}</span>
|
||||
</span>
|
||||
</div>
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
/* ============ File Tree ============ */
|
||||
function TreeNode({ node, depth, openDirs, toggleDir, onOpen, onContext, activePath, changeMap, committed }: {
|
||||
node: FileNode
|
||||
depth: number
|
||||
openDirs: Set<string>
|
||||
toggleDir: (path: string) => void
|
||||
onOpen: OpenFile
|
||||
onContext: OnContext
|
||||
activePath: string | null
|
||||
changeMap: Record<string, GitStatus>
|
||||
committed: Set<string>
|
||||
}): React.ReactElement {
|
||||
const pad = 10 + depth * 13
|
||||
if (node.type === 'dir') {
|
||||
const isOpen = openDirs.has(node.path) || node.path === ''
|
||||
return (
|
||||
<Fragment>
|
||||
{node.path !== '' && (
|
||||
<div className="tree-row folder" style={{ paddingLeft: pad }}
|
||||
onClick={() => toggleDir(node.path)}
|
||||
onContextMenu={(e) => onContext(e, { path: node.path, kind: 'dir' })}>
|
||||
<span className="tw"><Chevron open={isOpen} /></span>
|
||||
<FolderIcon open={isOpen} />
|
||||
<span className="tree-label">{node.name}</span>
|
||||
</div>
|
||||
)}
|
||||
{isOpen && (node.children || []).map((c) => (
|
||||
<TreeNode key={c.path} node={c} depth={node.path === '' ? 0 : depth + 1}
|
||||
openDirs={openDirs} toggleDir={toggleDir} onOpen={onOpen}
|
||||
onContext={onContext} activePath={activePath} changeMap={changeMap} committed={committed} />
|
||||
))}
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
const status = committed && committed.has(node.path) ? null : changeMap[node.path]
|
||||
return (
|
||||
<div className={'tree-row' + (activePath === node.path ? ' active' : '')}
|
||||
style={{ paddingLeft: pad + 2 }}
|
||||
onClick={() => onOpen(node.path)}
|
||||
onContextMenu={(e) => onContext(e, { path: node.path, kind: 'file' })}
|
||||
title={node.path}>
|
||||
<span className="tw" />
|
||||
<FileIcon path={node.path} />
|
||||
<span className="tree-label" style={status === 'D' ? { textDecoration: 'line-through', color: 'var(--fg-3)' } : undefined}>{node.name}</span>
|
||||
{status && <span className={'tree-badge ' + status}>{status}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function FileTree({ tree, openDirs, toggleDir, onOpen, onContext, activePath, changeMap, committed }: {
|
||||
tree: FileNode
|
||||
openDirs: Set<string>
|
||||
toggleDir: (path: string) => void
|
||||
onOpen: OpenFile
|
||||
onContext: OnContext
|
||||
activePath: string | null
|
||||
changeMap: Record<string, GitStatus>
|
||||
committed: Set<string>
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<Fragment>
|
||||
<div className="phead">
|
||||
<span>Explorer</span>
|
||||
<span style={{ marginLeft: 'auto', color: 'var(--fg-3)', textTransform: 'none', letterSpacing: 0, fontFamily: 'var(--mono)', fontSize: 10.5 }}>{tree.name}</span>
|
||||
</div>
|
||||
<div className="tree-body">
|
||||
<TreeNode node={tree} depth={0} openDirs={openDirs} toggleDir={toggleDir}
|
||||
onOpen={onOpen} onContext={onContext} activePath={activePath} changeMap={changeMap} committed={committed} />
|
||||
</div>
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
665
src/renderer/src/data.ts
Normal file
665
src/renderer/src/data.ts
Normal file
@@ -0,0 +1,665 @@
|
||||
/* Mock project: filesystem tree, file contents, before/after pairs, runtime diff.
|
||||
*
|
||||
* PHASE 2: replace this whole module with real data streamed from the main
|
||||
* process — file tree (chokidar), file contents on demand, and `git diff`
|
||||
* derived original/updated pairs. The four view modes still derive from the
|
||||
* same original/updated text pair per changed file, so keep buildDiff()'s
|
||||
* output shape. */
|
||||
import type { Change, Diff, FileNode, Project } from './types'
|
||||
import { buildDiff } from './diff'
|
||||
|
||||
// ---- working-tree (current / updated) file contents ----------------
|
||||
const F: Record<string, string> = {}
|
||||
|
||||
F['src/Http/Controller/UserController.php'] = `<?php
|
||||
|
||||
namespace App\\Http\\Controller;
|
||||
|
||||
use App\\Service\\PaymentService;
|
||||
use App\\Repository\\UserRepository;
|
||||
use Psr\\Http\\Message\\ResponseInterface;
|
||||
use Psr\\Http\\Message\\ServerRequestInterface;
|
||||
|
||||
final class UserController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserRepository $users,
|
||||
private readonly PaymentService $payments,
|
||||
) {}
|
||||
|
||||
public function show(ServerRequestInterface $request, string $id): ResponseInterface
|
||||
{
|
||||
$user = $this->users->find($id);
|
||||
|
||||
if ($user === null) {
|
||||
return $this->json(['error' => 'user_not_found'], 404);
|
||||
}
|
||||
|
||||
$balance = $this->payments->balanceFor($user);
|
||||
|
||||
return $this->json([
|
||||
'id' => $user->id,
|
||||
'email' => $user->email,
|
||||
'plan' => $user->plan->value,
|
||||
'name' => $user->name,
|
||||
'currency' => $user->currency,
|
||||
'balance' => $balance->toArray(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(ServerRequestInterface $request, string $id): ResponseInterface
|
||||
{
|
||||
$user = $this->users->find($id);
|
||||
if ($user === null) {
|
||||
return $this->json(['error' => 'user_not_found'], 404);
|
||||
}
|
||||
|
||||
$data = (array) $request->getParsedBody();
|
||||
$user->fill($this->onlyFillable($data));
|
||||
$this->users->save($user);
|
||||
|
||||
return $this->json($user->toArray());
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function onlyFillable(array $data): array
|
||||
{
|
||||
$allowed = ['email', 'plan', 'name'];
|
||||
return array_intersect_key($data, array_flip($allowed));
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
F['src/Service/PaymentService.php'] = `<?php
|
||||
|
||||
namespace App\\Service;
|
||||
|
||||
use App\\Entity\\User;
|
||||
use App\\ValueObject\\Money;
|
||||
use App\\Gateway\\PaymentGateway;
|
||||
use Psr\\Log\\LoggerInterface;
|
||||
|
||||
final class PaymentService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PaymentGateway $gateway,
|
||||
private readonly LoggerInterface $logger,
|
||||
) {}
|
||||
|
||||
public function balanceFor(User $user): Money
|
||||
{
|
||||
$cents = $this->gateway->lookupBalance($user->id);
|
||||
return Money::fromCents($cents, $user->currency ?? 'EUR');
|
||||
}
|
||||
|
||||
public function charge(User $user, Money $amount, string $reason): bool
|
||||
{
|
||||
if ($amount->isZero()) {
|
||||
$this->logger->warning('Skipped zero charge', ['user' => $user->id]);
|
||||
return false;
|
||||
}
|
||||
|
||||
$result = $this->gateway->charge($user->paymentToken, $amount->cents());
|
||||
$this->logger->info('Charge attempt', [
|
||||
'user' => $user->id,
|
||||
'amount' => $amount->cents(),
|
||||
'ok' => $result->success,
|
||||
]);
|
||||
|
||||
return $result->success;
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
F['public/assets/app.js'] = `import { createStore } from './store.js';
|
||||
import { mountRouter } from './router.js';
|
||||
|
||||
const store = createStore({
|
||||
user: null,
|
||||
notifications: [],
|
||||
theme: 'dark',
|
||||
});
|
||||
|
||||
async function bootstrap() {
|
||||
const res = await fetch('/api/session', { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const session = await res.json();
|
||||
store.set('user', session.user);
|
||||
store.set('theme', session.user.theme ?? 'dark');
|
||||
}
|
||||
|
||||
mountRouter(document.querySelector('#app'), store);
|
||||
store.subscribe('notifications', renderToasts);
|
||||
}
|
||||
|
||||
function renderToasts(list) {
|
||||
const host = document.querySelector('#toasts');
|
||||
host.replaceChildren(...list.map((n) => {
|
||||
const el = document.createElement('div');
|
||||
el.className = \\\`toast toast--\\\${n.level}\\\`;
|
||||
el.textContent = n.message;
|
||||
return el;
|
||||
}));
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', bootstrap);
|
||||
`
|
||||
|
||||
F['public/assets/store.js'] = `export function createStore(initial = {}) {
|
||||
let state = { ...initial };
|
||||
const subs = new Map();
|
||||
|
||||
return {
|
||||
get: (key) => state[key],
|
||||
set(key, value) {
|
||||
state = { ...state, [key]: value };
|
||||
(subs.get(key) || []).forEach((fn) => fn(value, state));
|
||||
},
|
||||
subscribe(key, fn) {
|
||||
const list = subs.get(key) || [];
|
||||
list.push(fn);
|
||||
subs.set(key, list);
|
||||
return () => subs.set(key, list.filter((f) => f !== fn));
|
||||
},
|
||||
};
|
||||
}
|
||||
`
|
||||
|
||||
F['public/assets/styles.css'] = `:root {
|
||||
--brand: #4d8dff;
|
||||
--ink: #15171a;
|
||||
--paper: #ffffff;
|
||||
--radius: 10px;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, sans-serif;
|
||||
background: var(--ink);
|
||||
color: #e6e8ea;
|
||||
}
|
||||
|
||||
.toast {
|
||||
padding: 10px 14px;
|
||||
border-radius: var(--radius);
|
||||
border-left: 3px solid var(--brand);
|
||||
}
|
||||
|
||||
.toast--error { border-left-color: #e0696a; }
|
||||
.toast--success { border-left-color: #5cbd6b; }
|
||||
`
|
||||
|
||||
F['src/types/api.ts'] = `export type Plan = 'free' | 'pro' | 'enterprise';
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
plan: Plan;
|
||||
currency: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface Balance {
|
||||
cents: number;
|
||||
currency: string;
|
||||
formatted: string;
|
||||
}
|
||||
|
||||
export type ApiResult<T> =
|
||||
| { ok: true; data: T }
|
||||
| { ok: false; error: string; status: number };
|
||||
|
||||
export async function getUser(id: string): Promise<ApiResult<User>> {
|
||||
const res = await fetch(\\\`/api/users/\\\${id}\\\`);
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: 'request_failed', status: res.status };
|
||||
}
|
||||
return { ok: true, data: (await res.json()) as User };
|
||||
}
|
||||
`
|
||||
|
||||
F['scripts/migrate.py'] = `#!/usr/bin/env python3
|
||||
"""Run pending database migrations in order."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from db import connect, applied_migrations
|
||||
|
||||
MIGRATIONS = Path(__file__).parent / "migrations"
|
||||
|
||||
|
||||
def pending(conn):
|
||||
done = applied_migrations(conn)
|
||||
files = sorted(MIGRATIONS.glob("*.sql"))
|
||||
return [f for f in files if f.stem not in done]
|
||||
|
||||
|
||||
def run(conn, migration: Path) -> None:
|
||||
sql = migration.read_text()
|
||||
print(f" -> applying {migration.stem}")
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
cur.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s)",
|
||||
(migration.stem,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
conn = connect()
|
||||
todo = pending(conn)
|
||||
if not todo:
|
||||
print("Database is up to date.")
|
||||
return 0
|
||||
print(f"Applying {len(todo)} migration(s)...")
|
||||
for migration in todo:
|
||||
run(conn, migration)
|
||||
print("Done.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
`
|
||||
|
||||
F['scripts/seed.py'] = `#!/usr/bin/env python3
|
||||
"""Seed the database with demo data for local development."""
|
||||
import random
|
||||
from db import connect
|
||||
|
||||
PLANS = ["free", "pro", "enterprise"]
|
||||
|
||||
|
||||
def seed_users(conn, count: int = 25) -> None:
|
||||
with conn.cursor() as cur:
|
||||
for i in range(count):
|
||||
cur.execute(
|
||||
"INSERT INTO users (email, plan) VALUES (%s, %s)",
|
||||
(f"user{i}@example.com", random.choice(PLANS)),
|
||||
)
|
||||
conn.commit()
|
||||
print(f"Seeded {count} users.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
seed_users(connect())
|
||||
`
|
||||
|
||||
F['templates/dashboard.html'] = `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Dashboard</title>
|
||||
<link rel="stylesheet" href="/assets/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<main id="app" class="layout">
|
||||
<header class="topbar">
|
||||
<h1 class="logo">Console</h1>
|
||||
<nav class="nav">
|
||||
<a href="/users" class="nav__link">Users</a>
|
||||
<a href="/billing" class="nav__link">Billing</a>
|
||||
</nav>
|
||||
</header>
|
||||
<section id="content" class="content"></section>
|
||||
</main>
|
||||
<div id="toasts" class="toast-host"></div>
|
||||
<script type="module" src="/assets/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
F['config/app.json'] = `{
|
||||
"name": "console",
|
||||
"env": "production",
|
||||
"features": {
|
||||
"billing": true,
|
||||
"newDashboard": true,
|
||||
"exportCsv": false
|
||||
},
|
||||
"payment": {
|
||||
"gateway": "stripe",
|
||||
"currency": "EUR",
|
||||
"retryLimit": 3
|
||||
},
|
||||
"logging": {
|
||||
"level": "info",
|
||||
"channel": "stdout"
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
F['composer.json'] = `{
|
||||
"name": "blijnder/console",
|
||||
"type": "project",
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"psr/log": "^3.0",
|
||||
"psr/http-message": "^2.0",
|
||||
"nyholm/psr7": "^1.8"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^11.0",
|
||||
"phpstan/phpstan": "^1.11"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "App\\\\": "src/" }
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
F['package.json'] = `{
|
||||
"name": "console-frontend",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"test": "vitest run",
|
||||
"lint": "eslint ."
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^5.3.0",
|
||||
"vitest": "^2.0.0",
|
||||
"typescript": "^5.5.0"
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
F['README.md'] = `# Console
|
||||
|
||||
Internal admin console. PHP API + small vanilla JS frontend.
|
||||
|
||||
## Getting started
|
||||
|
||||
composer install
|
||||
npm install
|
||||
python scripts/migrate.py
|
||||
npm run dev
|
||||
|
||||
## Layout
|
||||
|
||||
- \\\`src/\\\` PHP application code (PSR-4, \\\`App\\\\\\\` namespace)
|
||||
- \\\`public/\\\` Document root and frontend assets
|
||||
- \\\`scripts/\\\` Python maintenance + migration scripts
|
||||
- \\\`templates/\\\` Server-rendered HTML
|
||||
`
|
||||
|
||||
F['.env'] = `APP_ENV=production
|
||||
APP_DEBUG=false
|
||||
DATABASE_URL=postgres://localhost:5432/console
|
||||
PAYMENT_GATEWAY=stripe
|
||||
PAYMENT_CURRENCY=EUR
|
||||
LOG_LEVEL=info
|
||||
`
|
||||
|
||||
// ---- ORIGINAL (pre-edit) versions of changed files ----------------
|
||||
const O: Record<string, string> = {}
|
||||
|
||||
O['src/Http/Controller/UserController.php'] = `<?php
|
||||
|
||||
namespace App\\Http\\Controller;
|
||||
|
||||
use App\\Service\\PaymentService;
|
||||
use App\\Repository\\UserRepository;
|
||||
use Psr\\Http\\Message\\ResponseInterface;
|
||||
use Psr\\Http\\Message\\ServerRequestInterface;
|
||||
|
||||
final class UserController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserRepository $users,
|
||||
private readonly PaymentService $payments,
|
||||
) {}
|
||||
|
||||
public function show(ServerRequestInterface $request, string $id): ResponseInterface
|
||||
{
|
||||
$user = $this->users->find($id);
|
||||
|
||||
if ($user === null) {
|
||||
return $this->json(['error' => 'user_not_found'], 404);
|
||||
}
|
||||
|
||||
$balance = $this->payments->balanceFor($user);
|
||||
|
||||
return $this->json([
|
||||
'id' => $user->id,
|
||||
'email' => $user->email,
|
||||
'plan' => $user->plan,
|
||||
'balance' => $balance->toArray(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(ServerRequestInterface $request, string $id): ResponseInterface
|
||||
{
|
||||
$user = $this->users->find($id);
|
||||
if ($user === null) {
|
||||
return $this->json(['error' => 'user_not_found'], 404);
|
||||
}
|
||||
|
||||
$data = (array) $request->getParsedBody();
|
||||
$user->fill($this->onlyFillable($data));
|
||||
$this->users->save($user);
|
||||
|
||||
return $this->json($user->toArray());
|
||||
}
|
||||
|
||||
private function onlyFillable(array $data): array
|
||||
{
|
||||
return array_intersect_key($data, array_flip(['email', 'plan']));
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
O['public/assets/app.js'] = `import { createStore } from './store.js';
|
||||
import { mountRouter } from './router.js';
|
||||
|
||||
const store = createStore({
|
||||
user: null,
|
||||
notifications: [],
|
||||
theme: 'dark',
|
||||
});
|
||||
|
||||
async function bootstrap() {
|
||||
const res = await fetch('/api/session');
|
||||
if (res.ok) {
|
||||
const session = await res.json();
|
||||
store.set('user', session.user);
|
||||
}
|
||||
|
||||
mountRouter(document.querySelector('#app'), store);
|
||||
store.subscribe('notifications', renderToasts);
|
||||
}
|
||||
|
||||
function renderToasts(list) {
|
||||
const host = document.querySelector('#toasts');
|
||||
host.replaceChildren(...list.map((n) => {
|
||||
const el = document.createElement('div');
|
||||
el.className = \\\`toast toast--\\\${n.level}\\\`;
|
||||
el.textContent = n.message;
|
||||
return el;
|
||||
}));
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', bootstrap);
|
||||
`
|
||||
|
||||
O['config/app.json'] = `{
|
||||
"name": "console",
|
||||
"env": "production",
|
||||
"features": {
|
||||
"billing": true,
|
||||
"newDashboard": false
|
||||
},
|
||||
"payment": {
|
||||
"gateway": "stripe",
|
||||
"currency": "EUR",
|
||||
"retryLimit": 3
|
||||
},
|
||||
"logging": {
|
||||
"level": "info",
|
||||
"channel": "stdout"
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
O['scripts/migrate.py'] = `#!/usr/bin/env python3
|
||||
"""Run pending database migrations in order."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from db import connect, applied_migrations
|
||||
|
||||
MIGRATIONS = Path(__file__).parent / "migrations"
|
||||
|
||||
|
||||
def pending(conn):
|
||||
done = applied_migrations(conn)
|
||||
files = sorted(MIGRATIONS.glob("*.sql"))
|
||||
return [f for f in files if f.stem not in done]
|
||||
|
||||
|
||||
def run(conn, migration: Path) -> None:
|
||||
sql = migration.read_text()
|
||||
print(f" -> applying {migration.stem}")
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
cur.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s)",
|
||||
(migration.stem,),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
conn = connect()
|
||||
todo = pending(conn)
|
||||
if not todo:
|
||||
print("Database is up to date.")
|
||||
return 0
|
||||
for migration in todo:
|
||||
run(conn, migration)
|
||||
print("Done.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
`
|
||||
|
||||
// PaymentService is a brand-new file (added) -> original is empty
|
||||
O['src/Service/PaymentService.php'] = ''
|
||||
|
||||
// LegacyUser was deleted -> original content, no working-tree version
|
||||
O['src/Model/LegacyUser.php'] = `<?php
|
||||
|
||||
namespace App\\Model;
|
||||
|
||||
/**
|
||||
* @deprecated Superseded by App\\Entity\\User. Kept only for the
|
||||
* legacy billing import; safe to remove once the importer is gone.
|
||||
*/
|
||||
final class LegacyUser
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $id,
|
||||
public readonly string $email,
|
||||
public readonly ?string $plan = null,
|
||||
) {}
|
||||
|
||||
public static function fromRow(array $row): self
|
||||
{
|
||||
return new self(
|
||||
(int) $row['id'],
|
||||
(string) $row['email'],
|
||||
$row['plan'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'email' => $this->email,
|
||||
'plan' => $this->plan,
|
||||
];
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
// ---- file tree (nested) -------------------------------------------
|
||||
const tree: FileNode = {
|
||||
name: 'console', type: 'dir', path: '', open: true, children: [
|
||||
{ name: 'config', type: 'dir', path: 'config', open: false, children: [
|
||||
{ name: 'app.json', type: 'file', path: 'config/app.json' },
|
||||
] },
|
||||
{ name: 'public', type: 'dir', path: 'public', open: true, children: [
|
||||
{ name: 'assets', type: 'dir', path: 'public/assets', open: true, children: [
|
||||
{ name: 'app.js', type: 'file', path: 'public/assets/app.js' },
|
||||
{ name: 'store.js', type: 'file', path: 'public/assets/store.js' },
|
||||
{ name: 'styles.css', type: 'file', path: 'public/assets/styles.css' },
|
||||
] },
|
||||
] },
|
||||
{ name: 'scripts', type: 'dir', path: 'scripts', open: false, children: [
|
||||
{ name: 'migrate.py', type: 'file', path: 'scripts/migrate.py' },
|
||||
{ name: 'seed.py', type: 'file', path: 'scripts/seed.py' },
|
||||
] },
|
||||
{ name: 'src', type: 'dir', path: 'src', open: true, children: [
|
||||
{ name: 'Http', type: 'dir', path: 'src/Http', open: true, children: [
|
||||
{ name: 'Controller', type: 'dir', path: 'src/Http/Controller', open: true, children: [
|
||||
{ name: 'UserController.php', type: 'file', path: 'src/Http/Controller/UserController.php' },
|
||||
] },
|
||||
] },
|
||||
{ name: 'Service', type: 'dir', path: 'src/Service', open: true, children: [
|
||||
{ name: 'PaymentService.php', type: 'file', path: 'src/Service/PaymentService.php' },
|
||||
] },
|
||||
{ name: 'types', type: 'dir', path: 'src/types', open: false, children: [
|
||||
{ name: 'api.ts', type: 'file', path: 'src/types/api.ts' },
|
||||
] },
|
||||
] },
|
||||
{ name: 'templates', type: 'dir', path: 'templates', open: false, children: [
|
||||
{ name: 'dashboard.html', type: 'file', path: 'templates/dashboard.html' },
|
||||
] },
|
||||
{ name: '.env', type: 'file', path: '.env' },
|
||||
{ name: 'composer.json', type: 'file', path: 'composer.json' },
|
||||
{ name: 'package.json', type: 'file', path: 'package.json' },
|
||||
{ name: 'README.md', type: 'file', path: 'README.md' },
|
||||
],
|
||||
}
|
||||
|
||||
// ---- changed files -------------------------------------------------
|
||||
const changeDefs: { path: string; status: Change['status'] }[] = [
|
||||
{ path: 'src/Service/PaymentService.php', status: 'A' },
|
||||
{ path: 'src/Http/Controller/UserController.php', status: 'M' },
|
||||
{ path: 'public/assets/app.js', status: 'M' },
|
||||
{ path: 'config/app.json', status: 'M' },
|
||||
{ path: 'scripts/migrate.py', status: 'M' },
|
||||
{ path: 'src/Model/LegacyUser.php', status: 'D' },
|
||||
]
|
||||
|
||||
const diffs: Record<string, Diff> = {}
|
||||
const changes: Change[] = changeDefs.map((c) => {
|
||||
const orig = O[c.path] != null ? O[c.path] : ''
|
||||
const upd = F[c.path] != null ? F[c.path] : ''
|
||||
const d = buildDiff(orig, upd)
|
||||
diffs[c.path] = Object.assign(d, {
|
||||
deleted: c.status === 'D',
|
||||
added: c.status === 'A',
|
||||
original: orig,
|
||||
updated: upd,
|
||||
})
|
||||
return { path: c.path, status: c.status, add: d.add, del: d.del, deleted: c.status === 'D' }
|
||||
})
|
||||
|
||||
export const PROJECT: Project = {
|
||||
name: 'console',
|
||||
branch: 'feat/payments-balance',
|
||||
files: F,
|
||||
originals: O,
|
||||
tree,
|
||||
diffs,
|
||||
changes,
|
||||
}
|
||||
66
src/renderer/src/diff.ts
Normal file
66
src/renderer/src/diff.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/* 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). */
|
||||
import type { Diff, DiffRow, GitStatus, SideLine, SplitRow } from './types'
|
||||
|
||||
interface Op { t: 'same' | 'del' | 'add'; a?: number; b?: number }
|
||||
|
||||
export function buildDiff(origText: string, updText: string): Omit<Diff, 'deleted' | 'added' | 'original' | 'updated'> {
|
||||
const a = origText === '' ? [] : origText.replace(/\n$/, '').split('\n')
|
||||
const b = updText === '' ? [] : updText.replace(/\n$/, '').split('\n')
|
||||
const n = a.length, m = b.length
|
||||
const dp = Array.from({ length: n + 1 }, () => new Int32Array(m + 1))
|
||||
for (let i = n - 1; i >= 0; i--)
|
||||
for (let j = m - 1; j >= 0; j--)
|
||||
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
|
||||
|
||||
const ops: Op[] = []
|
||||
let i = 0, j = 0
|
||||
while (i < n && j < m) {
|
||||
if (a[i] === b[j]) { ops.push({ t: 'same', a: i, b: j }); i++; j++ }
|
||||
else if (dp[i + 1][j] >= dp[i][j + 1]) { ops.push({ t: 'del', a: i }); i++ }
|
||||
else { ops.push({ t: 'add', b: j }); j++ }
|
||||
}
|
||||
while (i < n) { ops.push({ t: 'del', a: i++ }) }
|
||||
while (j < m) { ops.push({ t: 'add', b: j++ }) }
|
||||
|
||||
const rows: DiffRow[] = [], left: SideLine[] = [], right: SideLine[] = [], split: SplitRow[] = []
|
||||
const delSet = new Set<number>(), addSet = new Set<number>()
|
||||
let add = 0, del = 0
|
||||
for (const op of ops) {
|
||||
if (op.t === 'same') {
|
||||
rows.push({ sign: ' ', oldNo: op.a! + 1, newNo: op.b! + 1, text: a[op.a!] })
|
||||
} else if (op.t === 'del') {
|
||||
rows.push({ sign: '-', oldNo: op.a! + 1, newNo: null, text: a[op.a!] })
|
||||
delSet.add(op.a!); del++
|
||||
} else {
|
||||
rows.push({ sign: '+', oldNo: null, newNo: op.b! + 1, text: b[op.b!] })
|
||||
addSet.add(op.b!); add++
|
||||
}
|
||||
}
|
||||
a.forEach((text, idx) => left.push({ no: idx + 1, text, mark: delSet.has(idx) ? 'del' : null }))
|
||||
b.forEach((text, idx) => right.push({ no: idx + 1, text, mark: addSet.has(idx) ? 'add' : null }))
|
||||
|
||||
// aligned split rows (pair del/add blocks)
|
||||
let dbuf: SideLine[] = [], abuf: SideLine[] = []
|
||||
const flush = (): void => {
|
||||
const k = Math.max(dbuf.length, abuf.length)
|
||||
for (let x = 0; x < k; x++) split.push({ l: dbuf[x] || null, r: abuf[x] || null })
|
||||
dbuf = []; abuf = []
|
||||
}
|
||||
for (const op of ops) {
|
||||
if (op.t === 'same') { flush(); split.push({ l: { no: op.a! + 1, text: a[op.a!] }, r: { no: op.b! + 1, text: b[op.b!] } }) }
|
||||
else if (op.t === 'del') dbuf.push({ no: op.a! + 1, text: a[op.a!], mark: 'del' })
|
||||
else abuf.push({ no: op.b! + 1, text: b[op.b!], mark: 'add' })
|
||||
}
|
||||
flush()
|
||||
|
||||
return { rows, left, right, split, add, del }
|
||||
}
|
||||
|
||||
/** Assemble a full Diff from a status + original/updated pair. */
|
||||
export function makeDiff(status: GitStatus, original: string, updated: string): Diff {
|
||||
const d = buildDiff(original, updated)
|
||||
return { ...d, deleted: status === 'D', added: status === 'A', original, updated }
|
||||
}
|
||||
389
src/renderer/src/editor.tsx
Normal file
389
src/renderer/src/editor.tsx
Normal file
@@ -0,0 +1,389 @@
|
||||
/* Editor: tabs + four view modes (Original / Updated / Diff / Split) + line selection */
|
||||
import React, { Fragment, useEffect, useMemo, useRef } from 'react'
|
||||
import type { Diff, ViewLine } from './types'
|
||||
import { useProject } from './project'
|
||||
import { HL } from './highlight'
|
||||
import { FileIcon, Icon } from './components'
|
||||
import type { OnContext } from './components'
|
||||
|
||||
export interface Cursor { path: string; line: number; col: number }
|
||||
export interface Selection { path: string; start: number; end: number; anchor: number }
|
||||
export type Mode = 'original' | 'updated' | 'diff' | 'code'
|
||||
|
||||
function climbToLine(node: Node | null): HTMLElement | null {
|
||||
let el: HTMLElement | null = node && node.nodeType === 3 ? (node.parentElement as HTMLElement) : (node as HTMLElement | null)
|
||||
while (el && !(el.dataset && el.dataset.line)) el = el.parentElement
|
||||
return el || null
|
||||
}
|
||||
|
||||
interface ResolvedTab { path: string; changed: boolean; modeLabel: string; dirty?: boolean }
|
||||
|
||||
/* Editable buffer: a transparent textarea over a Prism-highlighted <pre>, with a
|
||||
* scroll-synced line-number gutter. Live highlighting while typing. */
|
||||
function CodeEditor({ path, text, lang, onChange, onContext }: {
|
||||
path: string
|
||||
text: string
|
||||
lang: string | null
|
||||
onChange: (text: string) => void
|
||||
onContext: OnContext
|
||||
}): React.ReactElement {
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const gutterRef = useRef<HTMLDivElement>(null)
|
||||
const html = useMemo(() => HL.hlText(text, lang), [text, lang])
|
||||
const count = useMemo(() => text.split('\n').length, [text])
|
||||
|
||||
function onScroll(): void {
|
||||
const s = scrollRef.current
|
||||
if (s && gutterRef.current) gutterRef.current.style.transform = `translateY(${-s.scrollTop}px)`
|
||||
}
|
||||
// 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).
|
||||
function ensureCaretVisible(ta: HTMLTextAreaElement): void {
|
||||
const s = scrollRef.current
|
||||
if (!s) return
|
||||
const line = ta.value.slice(0, ta.selectionStart).split('\n').length - 1
|
||||
const top = 6 + line * 20
|
||||
const bottom = top + 20
|
||||
if (top < s.scrollTop) s.scrollTop = top - 20
|
||||
else if (bottom > s.scrollTop + s.clientHeight) s.scrollTop = bottom - s.clientHeight + 20
|
||||
}
|
||||
function handleContext(e: React.MouseEvent<HTMLTextAreaElement>): void {
|
||||
e.preventDefault()
|
||||
const ta = e.currentTarget
|
||||
const startLine = text.slice(0, ta.selectionStart).split('\n').length
|
||||
const info: Parameters<OnContext>[1] = { path, kind: 'editor', line: startLine }
|
||||
if (ta.selectionEnd > ta.selectionStart) {
|
||||
const endLine = text.slice(0, ta.selectionEnd).split('\n').length
|
||||
if (endLine !== startLine) info.sel = { start: startLine, end: endLine }
|
||||
}
|
||||
onContext(e, info)
|
||||
}
|
||||
return (
|
||||
<div className="code-edit">
|
||||
<div className="ce-gutterwrap">
|
||||
<div className="ce-gutter" ref={gutterRef}>
|
||||
{Array.from({ length: count }, (_, i) => <div key={i}>{i + 1}</div>)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ce-scroll" ref={scrollRef} onScroll={onScroll}>
|
||||
<div className="ce-inner">
|
||||
<textarea className="ce-ta" value={text} spellCheck={false} autoComplete="off"
|
||||
wrap="off"
|
||||
onChange={(e) => { onChange(e.target.value); ensureCaretVisible(e.target) }}
|
||||
onKeyUp={(e) => ensureCaretVisible(e.currentTarget)}
|
||||
onClick={(e) => ensureCaretVisible(e.currentTarget)}
|
||||
onContextMenu={handleContext} />
|
||||
<pre className="ce-pre" aria-hidden dangerouslySetInnerHTML={{ __html: html + '\n' }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EditorTabs({ tabs, active, onActivate, onClose }: {
|
||||
tabs: ResolvedTab[]
|
||||
active: string | null
|
||||
onActivate: (path: string) => void
|
||||
onClose: (path: string) => void
|
||||
}): React.ReactElement {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
const el = ref.current && ref.current.querySelector('.tab.active')
|
||||
if (el) el.scrollIntoView({ block: 'nearest', inline: 'nearest' })
|
||||
}, [active])
|
||||
return (
|
||||
<div className="tabs" ref={ref}>
|
||||
{tabs.map((t) => {
|
||||
const name = t.path.split('/').pop()
|
||||
return (
|
||||
<div key={t.path}
|
||||
className={'tab' + (active === t.path ? ' active' : '') + (t.dirty ? ' dirty' : '')}
|
||||
onClick={() => onActivate(t.path)}
|
||||
onAuxClick={(e) => { if (e.button === 1) { e.preventDefault(); onClose(t.path) } }}
|
||||
title={t.path}>
|
||||
<FileIcon path={t.path} />
|
||||
<span className="tname">{name}</span>
|
||||
{t.changed && <span className="tab-mode">{t.modeLabel}</span>}
|
||||
<span className="tclose" onClick={(e) => { e.stopPropagation(); onClose(t.path) }}>
|
||||
{Icon.close()}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* Generic pane: renders an array of line descriptors with selection + caret + context. */
|
||||
function PaneView({ cacheKey, path, lines, lang, showSign, cursor, selection, setCursor, setSelection, onContext }: {
|
||||
cacheKey: string
|
||||
path: string
|
||||
lines: ViewLine[]
|
||||
lang: string | null
|
||||
showSign: boolean
|
||||
cursor: Cursor | null
|
||||
selection: Selection | null
|
||||
setCursor: (c: Cursor) => void
|
||||
setSelection: (s: Selection | null) => void
|
||||
onContext: OnContext
|
||||
}): React.ReactElement {
|
||||
const anchorRef = useRef<number | null>(null)
|
||||
const html = useMemo(() => lines.map((l) => HL.hlLine(l.text, lang)), [cacheKey])
|
||||
|
||||
function gutterClick(e: React.MouseEvent, no: number | null): void {
|
||||
if (no == null) return
|
||||
e.stopPropagation()
|
||||
if (e.shiftKey && anchorRef.current != null) {
|
||||
const a = anchorRef.current
|
||||
setSelection({ path, start: Math.min(a, no), end: Math.max(a, no), anchor: a })
|
||||
} else {
|
||||
anchorRef.current = no
|
||||
setSelection({ path, start: no, end: no, anchor: no })
|
||||
}
|
||||
setCursor({ path, line: no, col: 1 })
|
||||
}
|
||||
function caretCol(sel: globalThis.Selection): number {
|
||||
try {
|
||||
const el = climbToLine(sel.focusNode)
|
||||
const code = el!.querySelector('.ln-code') as Element
|
||||
const r = document.createRange()
|
||||
r.setStart(code, 0); r.setEnd(sel.focusNode!, sel.focusOffset)
|
||||
return r.toString().length + 1
|
||||
} catch {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
function onMouseUp(): void {
|
||||
const sel = window.getSelection()
|
||||
if (sel && !sel.isCollapsed) {
|
||||
const a = climbToLine(sel.anchorNode), f = climbToLine(sel.focusNode)
|
||||
if (a && f) {
|
||||
const an = +a.dataset.line!, fn = +f.dataset.line!
|
||||
const s = Math.min(an, fn), e = Math.max(an, fn)
|
||||
if (s !== e) { setSelection({ path, start: s, end: e, anchor: an }); setCursor({ path, line: fn, col: caretCol(sel) }); return }
|
||||
}
|
||||
}
|
||||
if (sel && sel.focusNode) {
|
||||
const el = climbToLine(sel.focusNode)
|
||||
if (el) { setCursor({ path, line: +el.dataset.line!, col: caretCol(sel) }); setSelection(null) }
|
||||
}
|
||||
}
|
||||
function handleContext(e: React.MouseEvent): void {
|
||||
e.preventDefault()
|
||||
const sel = window.getSelection()
|
||||
const info: Parameters<OnContext>[1] = { path, kind: 'editor' }
|
||||
const a = sel && sel.anchorNode && climbToLine(sel.anchorNode)
|
||||
const f = sel && sel.focusNode && climbToLine(sel.focusNode)
|
||||
if (sel && !sel.isCollapsed && a && f && +a.dataset.line! !== +f.dataset.line!) {
|
||||
const s = Math.min(+a.dataset.line!, +f.dataset.line!), en = Math.max(+a.dataset.line!, +f.dataset.line!)
|
||||
info.sel = { start: s, end: en }; info.line = s
|
||||
} else if (selection && selection.path === path && selection.start !== selection.end) {
|
||||
info.sel = { start: selection.start, end: selection.end }; info.line = selection.start
|
||||
} else {
|
||||
let no: number | null = null
|
||||
const r = document.caretRangeFromPoint ? document.caretRangeFromPoint(e.clientX, e.clientY) : null
|
||||
const el = r && climbToLine(r.startContainer)
|
||||
if (el) no = +el.dataset.line!
|
||||
info.line = no || (cursor && cursor.path === path ? cursor.line : 1)
|
||||
}
|
||||
setCursor({ path, line: info.line!, col: 1 })
|
||||
onContext(e, info)
|
||||
}
|
||||
|
||||
const curLine = cursor && cursor.path === path ? cursor.line : -1
|
||||
const sel = selection && selection.path === path ? selection : null
|
||||
|
||||
return (
|
||||
<div className={'editor' + (showSign ? ' diff' : '')} onMouseUp={onMouseUp} onContextMenu={handleContext}>
|
||||
{lines.map((l, i) => {
|
||||
const no = l.no
|
||||
const inSel = sel && no != null && no >= sel.start && no <= sel.end
|
||||
const cls = 'ln-row'
|
||||
+ (l.row === 'add' ? ' add' : l.row === 'del' ? ' del' : '')
|
||||
+ (l.row === 'bar-add' ? ' bar-add' : l.row === 'bar-del' ? ' bar-del' : '')
|
||||
+ (no === curLine && !inSel && !l.row ? ' cursor' : '')
|
||||
+ (inSel ? ' selrange' : '')
|
||||
return (
|
||||
<div key={i} data-line={no == null ? undefined : no} className={cls}>
|
||||
<span className="ln-gutter" onClick={(e) => gutterClick(e, no)}>{no == null ? '' : no}</span>
|
||||
{showSign && <span className="ln-sign">{l.sign === ' ' || !l.sign ? '' : l.sign}</span>}
|
||||
<span className="ln-code" dangerouslySetInnerHTML={{ __html: html[i] }} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* Build the line descriptors for a given mode. */
|
||||
function buildLines(mode: Mode, diff: Diff | null, fileText: string | undefined): { lines: ViewLine[]; showSign: boolean } {
|
||||
if (mode === 'original' && diff) return { lines: diff.left.map((l) => ({ no: l.no, text: l.text, row: l.mark === 'del' ? 'bar-del' : null })), showSign: false }
|
||||
if (mode === 'updated' && diff) return { lines: diff.right.map((l) => ({ no: l.no, text: l.text, row: l.mark === 'add' ? 'bar-add' : null })), showSign: false }
|
||||
if (mode === 'diff' && diff) return { lines: diff.rows.map((r) => ({ no: r.newNo || r.oldNo, text: r.text, sign: r.sign, row: r.sign === '+' ? 'add' : r.sign === '-' ? 'del' : null })), showSign: true }
|
||||
// plain file
|
||||
const arr = (fileText || '').replace(/\n$/, '').split('\n')
|
||||
return { lines: arr.map((t, i) => ({ no: i + 1, text: t })), showSign: false }
|
||||
}
|
||||
|
||||
const SEGMENTS: { id: Mode; label: string }[] = [
|
||||
{ id: 'original', label: 'Original' },
|
||||
{ id: 'updated', label: 'Updated' },
|
||||
{ id: 'diff', label: 'Diff' },
|
||||
]
|
||||
|
||||
export function Editor({ tabs, active, mode, setMode, onActivate, onClose, onContext, onSplit, splitOpen, cursor, selection, setCursor, setSelection, bufferText, onEdit }: {
|
||||
tabs: ResolvedTab[]
|
||||
active: string | null
|
||||
mode: Mode
|
||||
setMode: (m: Mode) => void
|
||||
onActivate: (path: string) => void
|
||||
onClose: (path: string) => void
|
||||
onContext: OnContext
|
||||
onSplit: (path: string) => void
|
||||
splitOpen: boolean
|
||||
cursor: Cursor | null
|
||||
selection: Selection | null
|
||||
setCursor: (c: Cursor) => void
|
||||
setSelection: (s: Selection | null) => void
|
||||
bufferText: string
|
||||
onEdit: (text: string) => void
|
||||
}): React.ReactElement {
|
||||
const PROJECT = useProject()
|
||||
const tab = tabs.find((t) => t.path === active)
|
||||
const change = tab ? PROJECT.changes.find((c) => c.path === tab.path) : null
|
||||
const diff = tab ? PROJECT.diffs[tab.path] : null
|
||||
const lang = tab ? HL.langFor(tab.path) : null
|
||||
const effMode: Mode = change ? mode : 'code'
|
||||
|
||||
let built: { lines: ViewLine[]; showSign: boolean } | null = null
|
||||
if (tab) {
|
||||
if (change && diff) built = buildLines(effMode, diff, PROJECT.files[tab.path])
|
||||
else built = buildLines('code', null, PROJECT.files[tab.path])
|
||||
}
|
||||
|
||||
const statusWord = change ? (change.status === 'A' ? 'Added' : change.status === 'D' ? 'Deleted' : 'Modified') : ''
|
||||
const activeSeg = splitOpen ? 'split' : effMode
|
||||
const emptyUpdated = effMode === 'updated' && built && built.lines.length === 0
|
||||
const emptyOriginal = effMode === 'original' && built && built.lines.length === 0
|
||||
// Editable in the live-buffer modes; Original/Diff stay read-only review views.
|
||||
const editable = effMode === 'code' || effMode === 'updated'
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
<EditorTabs tabs={tabs} active={active} onActivate={onActivate} onClose={onClose} />
|
||||
{!tab ? (
|
||||
<div className="empty-ed">
|
||||
<div style={{ opacity: 0.5 }}>{Icon.file({ width: 30, height: 30 })}</div>
|
||||
<div className="big">No file open</div>
|
||||
<div className="klist">
|
||||
<div><span>Search files & content</span><kbd>⌘ F</kbd></div>
|
||||
<div><span>Copy reference</span><kbd>right-click</kbd></div>
|
||||
<div><span>Pass on to Agent</span><kbd>right-click</kbd></div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="editor-wrap">
|
||||
{change && (
|
||||
<div className="diff-bar">
|
||||
<span className={'git-stat ' + change.status} style={{ width: 'auto' }}>{statusWord}</span>
|
||||
{change.add > 0 && <span className="a">+{change.add}</span>}
|
||||
{change.del > 0 && <span className="d">−{change.del}</span>}
|
||||
<div className="seg">
|
||||
{SEGMENTS.map((s) => (
|
||||
<button key={s.id} className={activeSeg === s.id ? 'on' : ''} onClick={() => setMode(s.id)}>{s.label}</button>
|
||||
))}
|
||||
<button className={'split-btn' + (activeSeg === 'split' ? ' on' : '')} onClick={() => onSplit(tab.path)} title="Split — full screen side-by-side">
|
||||
<svg width="11" height="11" viewBox="0 0 12 12" fill="none"><rect x="1" y="1.5" width="10" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.2" /><line x1="6" y1="1.5" x2="6" y2="10.5" stroke="currentColor" strokeWidth="1.2" /></svg>
|
||||
Split
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{emptyUpdated ? (
|
||||
<div className="empty-ed"><div className="big" style={{ color: 'var(--del)' }}>No updated version</div><div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--fg-3)' }}>This file was deleted in the change.</div></div>
|
||||
) : emptyOriginal ? (
|
||||
<div className="empty-ed"><div className="big" style={{ color: 'var(--add)' }}>No original version</div><div style={{ fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--fg-3)' }}>This file is new in the change.</div></div>
|
||||
) : editable ? (
|
||||
<CodeEditor path={tab.path} text={bufferText} lang={lang} onChange={onEdit} onContext={onContext} />
|
||||
) : (
|
||||
built && <PaneView cacheKey={tab.path + ':' + effMode} path={tab.path} lines={built.lines}
|
||||
lang={lang} showSign={built.showSign} cursor={cursor} selection={selection}
|
||||
setCursor={setCursor} setSelection={setSelection} onContext={onContext} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</Fragment>
|
||||
)
|
||||
}
|
||||
|
||||
/* Full-screen side-by-side split view */
|
||||
export function SplitView({ path, onClose, onContext }: {
|
||||
path: string
|
||||
onClose: () => void
|
||||
onContext: OnContext
|
||||
}): React.ReactElement {
|
||||
const PROJECT = useProject()
|
||||
const diff = PROJECT.diffs[path]
|
||||
const lang = HL.langFor(path)
|
||||
const leftRef = useRef<HTMLDivElement>(null), rightRef = useRef<HTMLDivElement>(null)
|
||||
const lock = useRef(false)
|
||||
const change = PROJECT.changes.find((c) => c.path === path)
|
||||
|
||||
const leftHtml = useMemo(() => diff.split.map((r) => r.l ? HL.hlLine(r.l.text, lang) : ''), [path])
|
||||
const rightHtml = useMemo(() => diff.split.map((r) => r.r ? HL.hlLine(r.r.text, lang) : ''), [path])
|
||||
|
||||
function sync(from: HTMLDivElement | null, to: HTMLDivElement | null): void {
|
||||
if (lock.current || !from || !to) return
|
||||
lock.current = true
|
||||
to.scrollTop = from.scrollTop; to.scrollLeft = from.scrollLeft
|
||||
requestAnimationFrame(() => { lock.current = false })
|
||||
}
|
||||
function ctx(e: React.MouseEvent): void {
|
||||
e.preventDefault()
|
||||
let no: number | null = null
|
||||
const r = document.caretRangeFromPoint ? document.caretRangeFromPoint(e.clientX, e.clientY) : null
|
||||
const el = r && climbToLine(r.startContainer)
|
||||
if (el) no = +el.dataset.line!
|
||||
onContext(e, { path, kind: 'editor', line: no || 1 })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="split-overlay">
|
||||
<div className="split-head">
|
||||
<FileIcon path={path} />
|
||||
<span className="sh-name">{path}</span>
|
||||
{change && <span className={'git-stat ' + change.status} style={{ width: 'auto' }}>{change.status === 'A' ? 'Added' : change.status === 'D' ? 'Deleted' : 'Modified'}</span>}
|
||||
{change && change.add > 0 && <span className="a" style={{ fontFamily: 'var(--mono)', color: 'var(--add)' }}>+{change.add}</span>}
|
||||
{change && change.del > 0 && <span className="d" style={{ fontFamily: 'var(--mono)', color: 'var(--del)' }}>−{change.del}</span>}
|
||||
<button className="split-exit" onClick={onClose}>
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M7 1.5h3.5V5M5 10.5H1.5V7M10.5 1.5L7 5M1.5 10.5L5 7" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" /></svg>
|
||||
Collapse <kbd>Esc</kbd>
|
||||
</button>
|
||||
</div>
|
||||
<div className="split-body">
|
||||
<div className="split-pane left">
|
||||
<div className="split-label">Original <span>before</span></div>
|
||||
<div className="editor" ref={leftRef} onScroll={() => sync(leftRef.current, rightRef.current)} onContextMenu={ctx}>
|
||||
{diff.split.map((row, i) => (
|
||||
<div key={i} data-line={row.l ? row.l.no : undefined} className={'ln-row' + (row.l && row.l.mark === 'del' ? ' bar-del' : '') + (!row.l ? ' empty' : '')}>
|
||||
<span className="ln-gutter">{row.l ? row.l.no : ''}</span>
|
||||
<span className="ln-code" dangerouslySetInnerHTML={{ __html: row.l ? leftHtml[i] : '' }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="split-pane right">
|
||||
<div className="split-label">Updated <span>after</span></div>
|
||||
<div className="editor" ref={rightRef} onScroll={() => sync(rightRef.current, leftRef.current)} onContextMenu={ctx}>
|
||||
{diff.split.map((row, i) => (
|
||||
<div key={i} data-line={row.r ? row.r.no : undefined} className={'ln-row' + (row.r && row.r.mark === 'add' ? ' bar-add' : '') + (!row.r ? ' empty' : '')}>
|
||||
<span className="ln-gutter">{row.r ? row.r.no : ''}</span>
|
||||
<span className="ln-code" dangerouslySetInnerHTML={{ __html: row.r ? rightHtml[i] : '' }} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
59
src/renderer/src/env.d.ts
vendored
Normal file
59
src/renderer/src/env.d.ts
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
/// <reference types="vite/client" />
|
||||
import type { FileNode, GitStatus, HelderConfig } from './types'
|
||||
|
||||
interface GitChangeRaw {
|
||||
path: string
|
||||
status: GitStatus
|
||||
staged: boolean
|
||||
original: string
|
||||
updated: string
|
||||
}
|
||||
|
||||
interface HelderBridge {
|
||||
platform: string
|
||||
clipboard: { writeText: (text: string) => void }
|
||||
project: {
|
||||
current: () => Promise<{ root: string | null; name: string }>
|
||||
open: () => Promise<{ root: string | null; name: string }>
|
||||
}
|
||||
fs: {
|
||||
tree: () => Promise<FileNode | null>
|
||||
files: () => Promise<Record<string, string>>
|
||||
read: (path: string) => Promise<string>
|
||||
write: (path: string, content: string) => Promise<void>
|
||||
}
|
||||
git: {
|
||||
load: () => Promise<{ branch: string; changes: GitChangeRaw[] } | null>
|
||||
stage: (paths: string[]) => Promise<void>
|
||||
unstage: (paths: string[]) => Promise<void>
|
||||
commit: (message: string) => Promise<void>
|
||||
discard: (paths: string[]) => Promise<void>
|
||||
}
|
||||
pty: {
|
||||
available: () => Promise<boolean>
|
||||
create: (kind: 'agent' | 'shell', cols: number, rows: number) => Promise<number>
|
||||
write: (id: number, data: string) => void
|
||||
resize: (id: number, cols: number, rows: number) => void
|
||||
kill: (id: number) => void
|
||||
onData: (cb: (id: number, data: string) => void) => () => void
|
||||
onExit: (cb: (id: number) => void) => () => void
|
||||
}
|
||||
config: {
|
||||
get: () => Promise<HelderConfig>
|
||||
theme: () => Promise<string>
|
||||
}
|
||||
search: {
|
||||
content: (query: string) => Promise<{ path: string; hits: { no: number; ln: string; ix: number }[] }[]>
|
||||
files: () => Promise<string[]>
|
||||
}
|
||||
onProjectChanged: (cb: () => void) => () => void
|
||||
onConfigChanged: (cb: () => void) => () => void
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
helder?: HelderBridge
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
115
src/renderer/src/highlight.ts
Normal file
115
src/renderer/src/highlight.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
/* Syntax highlighting (Prism) + file-type icon metadata.
|
||||
*
|
||||
* The default `prismjs` bundle already registers markup, css, clike and
|
||||
* javascript. We add the rest in dependency order. CRITICAL: prism-php requires
|
||||
* prism-markup-templating to be loaded FIRST, or every Prism.highlight() call
|
||||
* throws and silently falls back to plain text. */
|
||||
import Prism from 'prismjs'
|
||||
import 'prismjs/components/prism-markup-templating'
|
||||
import 'prismjs/components/prism-php'
|
||||
import 'prismjs/components/prism-python'
|
||||
import 'prismjs/components/prism-typescript'
|
||||
import 'prismjs/components/prism-jsx'
|
||||
import 'prismjs/components/prism-tsx'
|
||||
import 'prismjs/components/prism-json'
|
||||
import 'prismjs/components/prism-bash'
|
||||
import 'prismjs/components/prism-yaml'
|
||||
import 'prismjs/components/prism-markdown'
|
||||
|
||||
// We drive highlighting manually; no DOM auto-scan.
|
||||
Prism.manual = true
|
||||
|
||||
const EXT_LANG: Record<string, string> = {
|
||||
php: 'php', js: 'javascript', mjs: 'javascript', cjs: 'javascript',
|
||||
jsx: 'jsx', ts: 'typescript', tsx: 'tsx', py: 'python',
|
||||
html: 'markup', xml: 'markup', svg: 'markup', vue: 'markup',
|
||||
css: 'css', scss: 'css', json: 'json', md: 'markdown',
|
||||
sh: 'bash', bash: 'bash', yml: 'yaml', yaml: 'yaml', env: 'bash',
|
||||
}
|
||||
|
||||
function ext(path: string): string {
|
||||
const base = path.split('/').pop() || ''
|
||||
if (base === '.env' || base.startsWith('.env')) return 'env'
|
||||
const i = base.lastIndexOf('.')
|
||||
return i >= 0 ? base.slice(i + 1).toLowerCase() : ''
|
||||
}
|
||||
|
||||
function langFor(path: string): string | null {
|
||||
return EXT_LANG[ext(path)] || null
|
||||
}
|
||||
|
||||
function langLabel(path: string): string {
|
||||
const e = ext(path)
|
||||
const map: Record<string, string> = {
|
||||
php: 'PHP', js: 'JavaScript', mjs: 'JavaScript', ts: 'TypeScript',
|
||||
tsx: 'TypeScript', jsx: 'JavaScript', py: 'Python', html: 'HTML',
|
||||
css: 'CSS', json: 'JSON', md: 'Markdown', sh: 'Shell', env: 'Dotenv',
|
||||
yml: 'YAML', yaml: 'YAML',
|
||||
}
|
||||
return map[e] || (e ? e.toUpperCase() : 'Plain Text')
|
||||
}
|
||||
|
||||
function escapeHtml(s: string): string {
|
||||
return s.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c] as string))
|
||||
}
|
||||
|
||||
// highlight a single line independently (keeps line numbering robust)
|
||||
function hlLine(line: string, lang: string | null): string {
|
||||
if (line === '') return ' '
|
||||
try {
|
||||
const grammar = lang ? Prism.languages[lang] : null
|
||||
if (grammar) return Prism.highlight(line, grammar, lang as string)
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return escapeHtml(line)
|
||||
}
|
||||
|
||||
// highlight a whole multi-line block (for the editable buffer's display layer)
|
||||
function hlText(text: string, lang: string | null): string {
|
||||
try {
|
||||
const grammar = lang ? Prism.languages[lang] : null
|
||||
if (grammar) return Prism.highlight(text, grammar, lang as string)
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return escapeHtml(text)
|
||||
}
|
||||
|
||||
// ---- file-type icon: colored monogram chip --------------------------
|
||||
interface IconMeta { c: string; t: string }
|
||||
|
||||
const ICONS: Record<string, IconMeta> = {
|
||||
php: { c: '#a78bdb', t: 'php' },
|
||||
js: { c: '#e6c860', t: 'js' },
|
||||
mjs: { c: '#e6c860', t: 'js' },
|
||||
ts: { c: '#5a9bd6', t: 'ts' },
|
||||
tsx: { c: '#5a9bd6', t: 'ts' },
|
||||
jsx: { c: '#5a9bd6', t: 'jsx' },
|
||||
py: { c: '#5fa8d6', t: 'py' },
|
||||
html: { c: '#e08b6a', t: '<>' },
|
||||
css: { c: '#5a9bd6', t: '{}' },
|
||||
scss: { c: '#d6699e', t: '{}' },
|
||||
json: { c: '#d8a85c', t: '{}' },
|
||||
md: { c: '#9aa0a8', t: 'md' },
|
||||
env: { c: '#7fc6a0', t: '$' },
|
||||
sh: { c: '#7fc6a0', t: '$' },
|
||||
yml: { c: '#cf7a6a', t: 'yml' },
|
||||
yaml: { c: '#cf7a6a', t: 'yml' },
|
||||
lock: { c: '#8a8f98', t: 'lk' },
|
||||
}
|
||||
|
||||
const NAME_ICONS: Record<string, IconMeta> = {
|
||||
'composer.json': { c: '#a78bdb', t: 'co' },
|
||||
'package.json': { c: '#cf7a6a', t: 'pk' },
|
||||
'README.md': { c: '#5a9bd6', t: 'md' },
|
||||
'.env': { c: '#7fc6a0', t: '$' },
|
||||
}
|
||||
|
||||
function iconFor(path: string): IconMeta {
|
||||
const base = path.split('/').pop() || ''
|
||||
if (NAME_ICONS[base]) return NAME_ICONS[base]
|
||||
return ICONS[ext(path)] || { c: '#7d838c', t: base.slice(0, 2) || '·' }
|
||||
}
|
||||
|
||||
export const HL = { ext, langFor, langLabel, hlLine, hlText, iconFor, escapeHtml }
|
||||
23
src/renderer/src/main.tsx
Normal file
23
src/renderer/src/main.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import React from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
|
||||
// Bundled locally (no Google Fonts CDN in Electron). Weights used by the UI.
|
||||
import '@fontsource/jetbrains-mono/400.css'
|
||||
import '@fontsource/jetbrains-mono/500.css'
|
||||
import '@fontsource/jetbrains-mono/600.css'
|
||||
import '@fontsource/jetbrains-mono/700.css'
|
||||
|
||||
// Initialises Prism + all grammars (correct php load order) as a side effect.
|
||||
import './highlight'
|
||||
import './styles.css'
|
||||
|
||||
import { App } from './App'
|
||||
import { ProjectProvider } from './project'
|
||||
|
||||
createRoot(document.getElementById('root') as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<ProjectProvider>
|
||||
<App />
|
||||
</ProjectProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
267
src/renderer/src/overlays.tsx
Normal file
267
src/renderer/src/overlays.tsx
Normal file
@@ -0,0 +1,267 @@
|
||||
/* Overlays: combined search (content + file names), context menu, toast, pass-popup */
|
||||
import React, { Fragment, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useProject } from './project'
|
||||
import { FileIcon, Icon } from './components'
|
||||
import type { OpenFile } from './components'
|
||||
|
||||
export interface MenuItem {
|
||||
sep?: boolean
|
||||
primary?: boolean
|
||||
icon?: React.ReactElement
|
||||
label?: string
|
||||
kbd?: string
|
||||
onClick?: () => void
|
||||
}
|
||||
export interface Menu { x: number; y: number; note?: string; items: MenuItem[] }
|
||||
export interface Toast { id: number; title: string; ref?: string }
|
||||
interface ContentHit { no: number; ln: string; ix: number }
|
||||
interface ContentGroup { path: string; hits: ContentHit[] }
|
||||
|
||||
export function fuzzy(q: string, str: string): number[] | null {
|
||||
q = q.toLowerCase(); const s = str.toLowerCase()
|
||||
let i = 0; const idx: number[] = []
|
||||
for (let j = 0; j < s.length && i < q.length; j++) {
|
||||
if (s[j] === q[i]) { idx.push(j); i++ }
|
||||
}
|
||||
return i === q.length ? idx : null
|
||||
}
|
||||
|
||||
function Highlight({ text, idx }: { text: string; idx: number[] | null }): React.ReactElement {
|
||||
if (!idx || !idx.length) return <span>{text}</span>
|
||||
const set = new Set(idx)
|
||||
return <span>{text.split('').map((ch, i) => set.has(i) ? <b key={i}>{ch}</b> : <Fragment key={i}>{ch}</Fragment>)}</span>
|
||||
}
|
||||
|
||||
export function SearchModal({ onOpen, onOpenAt, onClose, changeSet }: {
|
||||
onOpen: OpenFile
|
||||
onOpenAt: (path: string, line: number) => void
|
||||
onClose: () => void
|
||||
changeSet: Set<string>
|
||||
}): React.ReactElement {
|
||||
const PROJECT = useProject()
|
||||
const bridge = window.helder
|
||||
const [q, setQ] = useState('')
|
||||
const [sel, setSel] = useState(0)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const leftRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// file-name list: ripgrep `--files` when available, else the in-memory index keys
|
||||
const [allPaths, setAllPaths] = useState<string[]>(() => (bridge ? [] : Object.keys(PROJECT.files)))
|
||||
useEffect(() => {
|
||||
inputRef.current && inputRef.current.focus()
|
||||
if (bridge) bridge.search.files().then((f) => setAllPaths(f.length ? f : Object.keys(PROJECT.files))).catch(() => setAllPaths(Object.keys(PROJECT.files)))
|
||||
}, [])
|
||||
|
||||
// content hits (left): ripgrep (debounced) when available, else in-memory substring grep
|
||||
const [content, setContent] = useState<ContentGroup[]>([])
|
||||
useEffect(() => {
|
||||
const term = q.trim()
|
||||
if (term.length < 2) { setContent([]); return }
|
||||
if (bridge) {
|
||||
let alive = true
|
||||
const t = setTimeout(() => {
|
||||
bridge.search.content(term).then((g) => { if (alive) setContent(g) }).catch(() => { if (alive) setContent([]) })
|
||||
}, 120)
|
||||
return () => { alive = false; clearTimeout(t) }
|
||||
}
|
||||
const low = term.toLowerCase()
|
||||
const groups: ContentGroup[] = []
|
||||
for (const [path, src] of Object.entries(PROJECT.files)) {
|
||||
const lines = src.split('\n')
|
||||
const hits: ContentHit[] = []
|
||||
lines.forEach((ln, i) => {
|
||||
const ix = ln.toLowerCase().indexOf(low)
|
||||
if (ix >= 0) hits.push({ no: i + 1, ln, ix })
|
||||
})
|
||||
if (hits.length) groups.push({ path, hits })
|
||||
}
|
||||
setContent(groups)
|
||||
return
|
||||
}, [q])
|
||||
|
||||
// file-name matches (right)
|
||||
const files = useMemo(() => {
|
||||
const term = q.trim()
|
||||
if (!term) return []
|
||||
const out: { path: string; idx: number[] | null; rank: number; pos: number }[] = []
|
||||
for (const p of allPaths) {
|
||||
const name = p.split('/').pop() as string
|
||||
const ni = fuzzy(term, name)
|
||||
if (ni) { out.push({ path: p, idx: ni, rank: 0, pos: ni[0] }); continue }
|
||||
const pi = fuzzy(term, p)
|
||||
if (pi) out.push({ path: p, idx: null, rank: 1, pos: pi[0] })
|
||||
}
|
||||
out.sort((a, b) => a.rank - b.rank || a.pos - b.pos || a.path.length - b.path.length)
|
||||
return out
|
||||
}, [q, allPaths])
|
||||
|
||||
// flat list of content hits for keyboard nav
|
||||
const flat = useMemo(() => {
|
||||
const arr: { path: string; no: number }[] = []
|
||||
content.forEach((g) => g.hits.forEach((h) => arr.push({ path: g.path, no: h.no })))
|
||||
return arr
|
||||
}, [content])
|
||||
|
||||
const totalHits = flat.length
|
||||
useEffect(() => { setSel(0) }, [q])
|
||||
useEffect(() => {
|
||||
const el = leftRef.current && leftRef.current.querySelector('.sr-line.sel')
|
||||
if (el) el.scrollIntoView({ block: 'nearest' })
|
||||
}, [sel])
|
||||
|
||||
function onKey(e: React.KeyboardEvent): void {
|
||||
if (e.key === 'ArrowDown') { e.preventDefault(); setSel((s) => Math.min(s + 1, flat.length - 1)) }
|
||||
else if (e.key === 'ArrowUp') { e.preventDefault(); setSel((s) => Math.max(s - 1, 0)) }
|
||||
else if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
if (flat[sel]) { onOpenAt(flat[sel].path, flat[sel].no); onClose() }
|
||||
else if (files[0]) { onOpen(files[0].path); onClose() }
|
||||
} else if (e.key === 'Escape') { e.preventDefault(); onClose() }
|
||||
}
|
||||
|
||||
function renderLine(ln: string, ix: number, len: number): React.ReactElement {
|
||||
const pre = ln.slice(0, ix), mid = ln.slice(ix, ix + len), post = ln.slice(ix + len)
|
||||
return <span className="tx">{pre}<mark>{mid}</mark>{post}</span>
|
||||
}
|
||||
|
||||
const term = q.trim()
|
||||
let flatIx = -1
|
||||
|
||||
return (
|
||||
<div className="scrim" onMouseDown={onClose}>
|
||||
<div className="search-modal" onMouseDown={(e) => e.stopPropagation()}>
|
||||
<div className="pi">
|
||||
{Icon.search({ style: { color: 'var(--fg-3)' } })}
|
||||
<input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={onKey}
|
||||
placeholder="Search content and file names…" spellCheck={false} />
|
||||
<span className="mode-chip">{totalHits} hit{totalHits === 1 ? '' : 's'} · {files.length} file{files.length === 1 ? '' : 's'}</span>
|
||||
</div>
|
||||
<div className="search-cols">
|
||||
<div className="sc-left" ref={leftRef}>
|
||||
<div className="sc-head">Content {totalHits > 0 && <span className="sc-ct">{totalHits}</span>}</div>
|
||||
{term.length < 2 && <div className="pempty">Type at least 2 characters</div>}
|
||||
{term.length >= 2 && content.length === 0 && <div className="pempty">No content matches</div>}
|
||||
{content.map((g) => (
|
||||
<Fragment key={g.path}>
|
||||
<div className="sr-file" onClick={() => onOpenAt(g.path, g.hits[0].no)}>
|
||||
<FileIcon path={g.path} />
|
||||
<span className="srf-name">{g.path}</span>
|
||||
<span className="cnt">{g.hits.length}</span>
|
||||
</div>
|
||||
{g.hits.slice(0, 12).map((h) => {
|
||||
flatIx++
|
||||
const me = flatIx
|
||||
return (
|
||||
<div key={h.no} className={'sr-line' + (me === sel ? ' sel' : '')}
|
||||
onMouseEnter={() => setSel(me)}
|
||||
onClick={() => { onOpenAt(g.path, h.no); onClose() }}>
|
||||
<span className="no">{h.no}</span>
|
||||
{renderLine(h.ln, h.ix, term.length)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
<div className="sc-right">
|
||||
<div className="sc-head">Files {files.length > 0 && <span className="sc-ct">{files.length}</span>}</div>
|
||||
{!term && <div className="pempty sm">Start typing…</div>}
|
||||
{term && files.length === 0 && <div className="pempty sm">No file names match</div>}
|
||||
{files.slice(0, 40).map((r) => {
|
||||
const name = r.path.split('/').pop() as string
|
||||
const dir = r.path.split('/').slice(0, -1).join('/')
|
||||
return (
|
||||
<div key={r.path} className="fres" onClick={() => { onOpen(r.path); onClose() }} title={r.path}>
|
||||
<FileIcon path={r.path} />
|
||||
<div className="fres-txt">
|
||||
<span className="fn"><Highlight text={name} idx={r.idx} /></span>
|
||||
{dir && <span className="fd">{dir}/</span>}
|
||||
</div>
|
||||
{changeSet.has(r.path) && <span className="tree-badge M" style={{ fontFamily: 'var(--mono)', fontSize: 10 }}>•</span>}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ContextMenu({ menu, onClose }: { menu: Menu | null; onClose: () => void }): React.ReactElement | null {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => {
|
||||
const h = (e: MouseEvent): void => { if (ref.current && !ref.current.contains(e.target as Node)) onClose() }
|
||||
const k = (e: KeyboardEvent): void => { if (e.key === 'Escape') onClose() }
|
||||
document.addEventListener('mousedown', h)
|
||||
document.addEventListener('keydown', k)
|
||||
return () => { document.removeEventListener('mousedown', h); document.removeEventListener('keydown', k) }
|
||||
}, [])
|
||||
if (!menu) return null
|
||||
const x = Math.min(menu.x, window.innerWidth - 270)
|
||||
const y = Math.min(menu.y, window.innerHeight - (menu.items.length * 34 + 60))
|
||||
return (
|
||||
<div className="ctx" ref={ref} style={{ left: x, top: y }}>
|
||||
{menu.note && <div className="ctx-note">{menu.note}</div>}
|
||||
{menu.items.map((it, i) => it.sep ? <div key={i} className="ctx-sep" /> : (
|
||||
<div key={i} className={'ctx-item' + (it.primary ? ' primary' : '')}
|
||||
onClick={() => { it.onClick && it.onClick(); onClose() }}>
|
||||
<span className="ic">{it.icon}</span>
|
||||
<span>{it.label}</span>
|
||||
{it.kbd && <span className="kc">{it.kbd}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Toasts({ toasts }: { toasts: Toast[] }): React.ReactElement {
|
||||
return (
|
||||
<div className="toast-wrap">
|
||||
{toasts.map((t) => (
|
||||
<div key={t.id} className="toast">
|
||||
{Icon.copy({ style: { color: 'var(--accent)' } })}
|
||||
<span className="tt">{t.title}</span>
|
||||
{t.ref && <span className="tref">{t.ref}</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function PassPopup({ x, y, refStr, onConfirm, onCancel }: {
|
||||
x: number
|
||||
y: number
|
||||
refStr: string
|
||||
onConfirm: (text: string) => void
|
||||
onCancel: () => void
|
||||
}): React.ReactElement {
|
||||
const [text, setText] = useState('')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const boxRef = useRef<HTMLDivElement>(null)
|
||||
useEffect(() => { inputRef.current && inputRef.current.focus() }, [])
|
||||
useEffect(() => {
|
||||
const h = (e: MouseEvent): void => { if (boxRef.current && !boxRef.current.contains(e.target as Node)) onCancel() }
|
||||
const k = (e: KeyboardEvent): void => { if (e.key === 'Escape') { e.preventDefault(); onCancel() } }
|
||||
document.addEventListener('mousedown', h)
|
||||
document.addEventListener('keydown', k, true)
|
||||
return () => { document.removeEventListener('mousedown', h); document.removeEventListener('keydown', k, true) }
|
||||
}, [])
|
||||
const left = Math.min(x, window.innerWidth - 360)
|
||||
const top = Math.min(y + 6, window.innerHeight - 150)
|
||||
const preview = (text.trim() ? text.trim() + ' ' : '') + refStr
|
||||
return (
|
||||
<div className="pass-pop" ref={boxRef} style={{ left, top }}>
|
||||
<div className="pass-head">{Icon.spark()}<span>Pass on to Agent</span><span className="pass-esc">esc</span></div>
|
||||
<input ref={inputRef} className="pass-input" value={text} spellCheck={false}
|
||||
placeholder="Add a note (optional)…"
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); onConfirm(text) }
|
||||
else if (e.key === 'Escape') { e.preventDefault(); onCancel() }
|
||||
}} />
|
||||
<div className="pass-preview"><span className="pp-lbl">inserts</span><code>{preview}</code></div>
|
||||
<div className="pass-foot"><kbd>↵</kbd> insert into agent · <kbd>esc</kbd> cancel</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
186
src/renderer/src/project.tsx
Normal file
186
src/renderer/src/project.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
/* Renderer-side project store. Loads tree / file index / git state from the
|
||||
* main process over the preload bridge and exposes it in the same shape the UI
|
||||
* already consumed from the mock. When window.helder is absent (e.g. a plain
|
||||
* browser preview) it falls back to the mock so the UI still renders. */
|
||||
import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { Change, Diff, FileNode, HelderConfig } from './types'
|
||||
import { DEFAULT_CONFIG } from './types'
|
||||
import { makeDiff } from './diff'
|
||||
import { PROJECT as MOCK } from './data'
|
||||
|
||||
export interface ProjectData {
|
||||
name: string
|
||||
root: string | null
|
||||
branch: string
|
||||
tree: FileNode | null
|
||||
files: Record<string, string>
|
||||
changes: Change[]
|
||||
diffs: Record<string, Diff>
|
||||
staged: Set<string>
|
||||
config: HelderConfig
|
||||
isRepo: boolean
|
||||
ready: boolean
|
||||
}
|
||||
|
||||
/** Inject the project's theme.css over the built-in dark theme. */
|
||||
function applyTheme(css: string): void {
|
||||
let el = document.getElementById('helder-theme') as HTMLStyleElement | null
|
||||
if (!el) {
|
||||
el = document.createElement('style')
|
||||
el.id = 'helder-theme'
|
||||
document.head.appendChild(el)
|
||||
}
|
||||
el.textContent = css || ''
|
||||
}
|
||||
|
||||
export interface ProjectActions {
|
||||
openFolder: () => void
|
||||
refresh: () => void
|
||||
stage: (path: string) => void
|
||||
unstage: (path: string) => void
|
||||
stageAll: () => void
|
||||
unstageAll: () => void
|
||||
commit: (message: string) => Promise<number>
|
||||
discard: (path: string) => void
|
||||
ensureFile: (path: string) => void
|
||||
}
|
||||
|
||||
const MOCK_STAGED = ['src/Service/PaymentService.php', 'config/app.json']
|
||||
|
||||
function mockData(): ProjectData {
|
||||
return {
|
||||
name: MOCK.name, root: null, branch: MOCK.branch,
|
||||
tree: MOCK.tree, files: MOCK.files, changes: MOCK.changes, diffs: MOCK.diffs,
|
||||
staged: new Set(MOCK_STAGED), config: DEFAULT_CONFIG, isRepo: true, ready: true,
|
||||
}
|
||||
}
|
||||
|
||||
const emptyData: ProjectData = {
|
||||
name: 'Loading…', root: null, branch: '—', tree: null, files: {},
|
||||
changes: [], diffs: {}, staged: new Set(), config: DEFAULT_CONFIG, isRepo: false, ready: false,
|
||||
}
|
||||
|
||||
const Ctx = createContext<{ data: ProjectData; actions: ProjectActions }>({
|
||||
data: emptyData,
|
||||
actions: {} as ProjectActions,
|
||||
})
|
||||
|
||||
export function useProject(): ProjectData {
|
||||
return useContext(Ctx).data
|
||||
}
|
||||
export function useProjectActions(): ProjectActions {
|
||||
return useContext(Ctx).actions
|
||||
}
|
||||
|
||||
export function ProjectProvider({ children }: { children: React.ReactNode }): React.ReactElement {
|
||||
const bridge = window.helder
|
||||
const [data, setData] = useState<ProjectData>(emptyData)
|
||||
const dataRef = useRef(data)
|
||||
dataRef.current = data
|
||||
|
||||
async function loadReal(): Promise<void> {
|
||||
if (!bridge) return
|
||||
const [cur, tree, files, git, config, theme] = await Promise.all([
|
||||
bridge.project.current(),
|
||||
bridge.fs.tree(),
|
||||
bridge.fs.files(),
|
||||
bridge.git.load(),
|
||||
bridge.config.get(),
|
||||
bridge.config.theme(),
|
||||
])
|
||||
applyTheme(theme)
|
||||
const changes: Change[] = []
|
||||
const diffs: Record<string, Diff> = {}
|
||||
const staged = new Set<string>()
|
||||
if (git) {
|
||||
for (const c of git.changes) {
|
||||
const d = makeDiff(c.status, c.original, c.updated)
|
||||
diffs[c.path] = d
|
||||
changes.push({ path: c.path, status: c.status, add: d.add, del: d.del, deleted: c.status === 'D' })
|
||||
if (c.staged) staged.add(c.path)
|
||||
}
|
||||
}
|
||||
setData({
|
||||
name: cur.name, root: cur.root, branch: git ? git.branch : '—',
|
||||
tree, files: files || {}, changes, diffs, staged, config, isRepo: !!git, ready: true,
|
||||
})
|
||||
}
|
||||
|
||||
async function loadConfigTheme(): Promise<void> {
|
||||
if (!bridge) return
|
||||
const [config, theme] = await Promise.all([bridge.config.get(), bridge.config.theme()])
|
||||
applyTheme(theme)
|
||||
setData((d) => ({ ...d, config }))
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!bridge) { setData(mockData()); return }
|
||||
loadReal().catch(() => setData((d) => ({ ...d, ready: true })))
|
||||
const offProject = bridge.onProjectChanged(() => { loadReal().catch(() => {}) })
|
||||
const offConfig = bridge.onConfigChanged(() => { loadConfigTheme().catch(() => {}) })
|
||||
return () => { offProject(); offConfig() }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
const actions = useMemo<ProjectActions>(() => {
|
||||
if (!bridge) {
|
||||
// ---- mock-mode actions (preview only) ----
|
||||
const setStaged = (fn: (s: Set<string>) => Set<string>): void =>
|
||||
setData((d) => ({ ...d, staged: fn(new Set(d.staged)) }))
|
||||
return {
|
||||
openFolder: () => {},
|
||||
refresh: () => setData(mockData()),
|
||||
stage: (p) => setStaged((s) => (s.add(p), s)),
|
||||
unstage: (p) => setStaged((s) => (s.delete(p), s)),
|
||||
stageAll: () => setData((d) => ({ ...d, staged: new Set(d.changes.map((c) => c.path)) })),
|
||||
unstageAll: () => setData((d) => ({ ...d, staged: new Set() })),
|
||||
commit: async (_msg) => {
|
||||
const cur = dataRef.current
|
||||
const n = cur.changes.filter((c) => cur.staged.has(c.path)).length
|
||||
setData((d) => ({ ...d, changes: d.changes.filter((c) => !d.staged.has(c.path)), staged: new Set() }))
|
||||
return n
|
||||
},
|
||||
discard: (p) => setData((d) => ({
|
||||
...d,
|
||||
changes: d.changes.filter((c) => c.path !== p),
|
||||
staged: (() => { const s = new Set(d.staged); s.delete(p); return s })(),
|
||||
})),
|
||||
ensureFile: () => {},
|
||||
}
|
||||
}
|
||||
// ---- real git-backed actions ----
|
||||
const after = (op: Promise<unknown>): void => { op.then(() => loadReal()).catch(() => {}) }
|
||||
return {
|
||||
openFolder: () => { bridge.project.open().then(() => loadReal()).catch(() => {}) },
|
||||
refresh: () => { loadReal().catch(() => {}) },
|
||||
stage: (p) => after(bridge.git.stage([p])),
|
||||
unstage: (p) => after(bridge.git.unstage([p])),
|
||||
stageAll: () => {
|
||||
const cur = dataRef.current
|
||||
const unstaged = cur.changes.filter((c) => !cur.staged.has(c.path)).map((c) => c.path)
|
||||
if (unstaged.length) after(bridge.git.stage(unstaged))
|
||||
},
|
||||
unstageAll: () => {
|
||||
const staged = [...dataRef.current.staged]
|
||||
if (staged.length) after(bridge.git.unstage(staged))
|
||||
},
|
||||
commit: async (msg) => {
|
||||
const cur = dataRef.current
|
||||
const n = cur.changes.filter((c) => cur.staged.has(c.path)).length
|
||||
await bridge.git.commit(msg)
|
||||
await loadReal()
|
||||
return n
|
||||
},
|
||||
discard: (p) => after(bridge.git.discard([p])),
|
||||
ensureFile: (path) => {
|
||||
if (dataRef.current.files[path] != null) return
|
||||
bridge.fs.read(path).then((txt) => {
|
||||
setData((d) => (d.files[path] != null ? d : { ...d, files: { ...d.files, [path]: txt } }))
|
||||
}).catch(() => {})
|
||||
},
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
return <Ctx.Provider value={{ data, actions }}>{children}</Ctx.Provider>
|
||||
}
|
||||
417
src/renderer/src/styles.css
Normal file
417
src/renderer/src/styles.css
Normal file
@@ -0,0 +1,417 @@
|
||||
/* ============ Helder — dark, charcoal-neutral (ported from design handoff) ============ */
|
||||
:root {
|
||||
--bg-0:#16171a; /* editor surface (deepest) */
|
||||
--bg-1:#1a1c1f; /* terminals */
|
||||
--bg-2:#1f2226; /* sidebars */
|
||||
--bg-3:#23262b; /* headers / tabs strip */
|
||||
--hover:#2a2e34;
|
||||
--active:#313742;
|
||||
--sel:#2b323d;
|
||||
--border:#2a2d33;
|
||||
--border-2:#34383f;
|
||||
--fg-0:#e6e8ea;
|
||||
--fg-1:#b4bac2;
|
||||
--fg-2:#838a94;
|
||||
--fg-3:#5d636c;
|
||||
--accent:#4d8dff;
|
||||
--accent-soft:rgba(77,141,255,0.16);
|
||||
--accent-line:rgba(77,141,255,0.55);
|
||||
--add:#5cbd6b;
|
||||
--del:#e0696a;
|
||||
--mod:#d8a85c;
|
||||
--ren:#5aa6d6;
|
||||
--add-bg:rgba(92,189,107,0.10);
|
||||
--del-bg:rgba(224,105,106,0.10);
|
||||
/* syntax */
|
||||
--t-key:#c98bdb;
|
||||
--t-str:#94c980;
|
||||
--t-num:#e0a06a;
|
||||
--t-fn:#6aa6f0;
|
||||
--t-com:#5f656e;
|
||||
--t-tag:#7fc6a0;
|
||||
--t-attr:#d8b15c;
|
||||
--t-punc:#9aa0a8;
|
||||
--t-var:#e6e8ea;
|
||||
--t-const:#e08b6a;
|
||||
--t-prop:#6ec0c0;
|
||||
--ui:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
|
||||
--mono:"JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
|
||||
/* code surfaces (editor + terminals) — overridable from .helder/theme.css */
|
||||
--code-font:"JetBrains Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
|
||||
--code-size:13px;
|
||||
--term-size:12.5px;
|
||||
}
|
||||
|
||||
* { box-sizing:border-box; }
|
||||
html,body { margin:0; height:100%; }
|
||||
body {
|
||||
background:var(--bg-0); color:var(--fg-0);
|
||||
font-family:var(--ui); font-size:13px;
|
||||
overflow:hidden; -webkit-font-smoothing:antialiased;
|
||||
}
|
||||
#root { height:100vh; }
|
||||
::selection { background:rgba(77,141,255,0.32); }
|
||||
|
||||
/* scrollbars */
|
||||
::-webkit-scrollbar { width:11px; height:11px; }
|
||||
::-webkit-scrollbar-thumb { background:#393e46; border-radius:6px; border:3px solid transparent; background-clip:content-box; }
|
||||
::-webkit-scrollbar-thumb:hover { background:#4a505a; background-clip:content-box; }
|
||||
::-webkit-scrollbar-corner { background:transparent; }
|
||||
|
||||
/* ============ shell ============ */
|
||||
.app { display:flex; flex-direction:column; height:100vh; }
|
||||
|
||||
.titlebar {
|
||||
height:36px; flex:0 0 36px; display:flex; align-items:center;
|
||||
background:var(--bg-3); border-bottom:1px solid var(--border);
|
||||
padding:0 12px; gap:14px; user-select:none;
|
||||
}
|
||||
.traffic { display:flex; gap:8px; }
|
||||
.traffic i { width:12px; height:12px; border-radius:50%; display:block; }
|
||||
.traffic .r{background:#e0696a;} .traffic .y{background:#d8a85c;} .traffic .g{background:#5cbd6b;}
|
||||
.tb-title { font-size:12px; color:var(--fg-1); display:flex; align-items:center; gap:7px; }
|
||||
.tb-title b { color:var(--fg-0); font-weight:600; }
|
||||
.tb-crumb { color:var(--fg-3); font-size:11.5px; font-family:var(--mono); }
|
||||
.tb-crumb .seg{color:var(--fg-2);}
|
||||
.tb-spacer { flex:1; }
|
||||
.tb-actions { display:flex; gap:6px; align-items:center; }
|
||||
.tb-btn {
|
||||
font-size:11.5px; color:var(--fg-2); background:transparent; border:1px solid transparent;
|
||||
border-radius:6px; padding:4px 9px; cursor:pointer; display:flex; align-items:center; gap:6px;
|
||||
}
|
||||
.tb-btn:hover { background:var(--hover); color:var(--fg-0); }
|
||||
.tb-btn kbd { font-family:var(--mono); font-size:10px; color:var(--fg-3); border:1px solid var(--border-2); border-radius:4px; padding:1px 5px; }
|
||||
|
||||
.workbench { flex:1; display:flex; min-height:0; }
|
||||
|
||||
.col { display:flex; flex-direction:column; height:100%; min-width:0; background:var(--bg-2); }
|
||||
.col.editor-col { flex:1; background:var(--bg-0); min-width:240px; }
|
||||
.col.right-col { background:var(--bg-1); }
|
||||
|
||||
.splitter { flex:0 0 5px; cursor:col-resize; background:transparent; position:relative; z-index:5; }
|
||||
.splitter::after { content:""; position:absolute; inset:0 2px; background:var(--border); transition:background .12s; }
|
||||
.splitter:hover::after, .splitter.drag::after { background:var(--accent-line); }
|
||||
.splitter.h { cursor:row-resize; flex:0 0 5px; width:100%; }
|
||||
|
||||
/* panel header */
|
||||
.phead {
|
||||
height:30px; flex:0 0 30px; display:flex; align-items:center; gap:8px;
|
||||
padding:0 10px 0 12px; font-size:10.5px; letter-spacing:.09em; text-transform:uppercase;
|
||||
color:var(--fg-2); border-bottom:1px solid var(--border); user-select:none;
|
||||
}
|
||||
.phead .ct { margin-left:auto; font-size:10px; color:var(--fg-3); letter-spacing:.02em; text-transform:none;
|
||||
background:var(--bg-3); border:1px solid var(--border); border-radius:9px; padding:0 7px; line-height:16px; }
|
||||
.phead .ico-btn { color:var(--fg-3); cursor:pointer; padding:2px; border-radius:4px; display:flex; }
|
||||
.phead .ico-btn:hover { background:var(--hover); color:var(--fg-1); }
|
||||
|
||||
/* ============ git panel ============ */
|
||||
.commit-box { padding:9px 10px; border-bottom:1px solid var(--border); display:flex; gap:7px; align-items:flex-start; }
|
||||
.commit-input { flex:1; min-width:0; resize:none; background:var(--bg-0); border:1px solid var(--border-2); border-radius:7px; color:var(--fg-0); font-family:var(--ui); font-size:12px; line-height:16px; padding:7px 9px; outline:none; min-height:32px; }
|
||||
.commit-input:focus { border-color:var(--accent-line); }
|
||||
.commit-input::placeholder { color:var(--fg-3); }
|
||||
.commit-btn { flex:0 0 auto; display:flex; align-items:center; gap:6px; background:var(--accent); color:#0c1320; border:0; border-radius:7px; font:inherit; font-size:12px; font-weight:600; padding:0 11px; height:32px; cursor:pointer; }
|
||||
.commit-btn:hover:not(:disabled) { background:#5d97ff; }
|
||||
.commit-btn:disabled { background:var(--bg-3); color:var(--fg-3); cursor:not-allowed; }
|
||||
.git-body { overflow:auto; flex:1; padding:4px 0 10px; }
|
||||
.git-group { padding:8px 12px 3px; font-size:10px; letter-spacing:.06em; text-transform:uppercase; color:var(--fg-3); display:flex; align-items:center; gap:6px; }
|
||||
.git-group .gc { color:var(--fg-3); }
|
||||
.git-group .grp-act { margin-left:auto; display:flex; opacity:0; background:transparent; border:0; color:var(--fg-2); padding:2px; border-radius:4px; cursor:pointer; }
|
||||
.git-group:hover .grp-act { opacity:1; }
|
||||
.git-group .grp-act:hover { background:var(--hover); color:var(--fg-0); }
|
||||
.git-empty { display:flex; flex-direction:column; align-items:center; gap:9px; padding:30px 16px; color:var(--fg-3); font-size:12px; text-align:center; }
|
||||
.git-empty svg { color:var(--add); opacity:.7; }
|
||||
.git-none { padding:5px 14px 9px; font-size:11.5px; color:var(--fg-3); }
|
||||
.git-none .key { font-family:var(--mono); font-size:11px; color:var(--fg-2); border:1px solid var(--border-2); border-radius:4px; padding:0 5px; }
|
||||
.git-divider { height:1px; background:var(--border); margin:8px 12px 2px; }
|
||||
.git-row {
|
||||
display:flex; align-items:center; gap:8px; padding:3px 12px 3px 14px; cursor:pointer; position:relative;
|
||||
}
|
||||
.git-row:hover { background:var(--hover); }
|
||||
.git-row.active { background:var(--sel); }
|
||||
.git-row.active::before { content:""; position:absolute; left:0; top:0; bottom:0; width:2px; background:var(--accent); }
|
||||
.git-stat { width:13px; text-align:center; font-family:var(--mono); font-size:11px; font-weight:600; flex:0 0 13px; }
|
||||
.git-stat.M{color:var(--mod);} .git-stat.A{color:var(--add);} .git-stat.D{color:var(--del);} .git-stat.R{color:var(--ren);} .git-stat.U{color:var(--add);}
|
||||
.git-name { font-size:12.5px; color:var(--fg-1); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.git-row.active .git-name { color:var(--fg-0); }
|
||||
.git-name.del { text-decoration:line-through; color:var(--fg-3); }
|
||||
.git-dir { color:var(--fg-3); font-size:11px; margin-left:auto; padding-left:8px; white-space:nowrap; max-width:42%; overflow:hidden; text-overflow:ellipsis; direction:rtl; }
|
||||
.git-act { flex:0 0 auto; display:none; align-items:center; justify-content:center; width:20px; height:20px; padding:0; background:transparent; border:0; border-radius:5px; color:var(--fg-2); cursor:pointer; margin-left:4px; }
|
||||
.git-row:hover .git-act { display:flex; }
|
||||
.git-act:hover { background:var(--active); color:var(--fg-0); }
|
||||
.git-delta { font-family:var(--mono); font-size:10.5px; display:flex; gap:6px; flex:0 0 auto; }
|
||||
.git-delta .a{color:var(--add);} .git-delta .d{color:var(--del);}
|
||||
.git-foot { border-top:1px solid var(--border); padding:8px 12px; display:flex; align-items:center; gap:8px; font-size:11px; color:var(--fg-2); }
|
||||
.branch-chip { display:flex; align-items:center; gap:6px; color:var(--fg-1); }
|
||||
.branch-chip b { font-weight:600; color:var(--fg-0); }
|
||||
|
||||
/* ============ file tree ============ */
|
||||
.tree-body { overflow:auto; flex:1; padding:4px 0 14px; }
|
||||
.tree-row { display:flex; align-items:center; gap:6px; padding:2px 10px 2px 0; cursor:pointer; white-space:nowrap; position:relative; height:23px; }
|
||||
.tree-row:hover { background:var(--hover); }
|
||||
.tree-row.active { background:var(--sel); }
|
||||
.tree-row.active::before { content:""; position:absolute; left:0; top:0; bottom:0; width:2px; background:var(--accent); }
|
||||
.tw { display:inline-flex; align-items:center; justify-content:center; width:14px; flex:0 0 14px; color:var(--fg-3); font-size:10px; }
|
||||
.tree-label { font-size:12.5px; color:var(--fg-1); overflow:hidden; text-overflow:ellipsis; }
|
||||
.tree-row.active .tree-label { color:var(--fg-0); }
|
||||
.tree-row.folder .tree-label { color:var(--fg-1); }
|
||||
.tree-badge { margin-left:auto; font-family:var(--mono); font-size:10px; font-weight:600; padding-left:8px; }
|
||||
.tree-badge.M{color:var(--mod);} .tree-badge.A{color:var(--add);} .tree-badge.D{color:var(--del);}
|
||||
|
||||
/* file type monogram icon */
|
||||
.ficon { width:15px; height:15px; flex:0 0 15px; border-radius:3.5px; display:inline-flex; align-items:center; justify-content:center;
|
||||
font-family:var(--mono); font-size:7.5px; font-weight:700; color:#11131600; position:relative; }
|
||||
.ficon span { color:#0c0d0f; font-size:7.5px; line-height:1; letter-spacing:-.3px; }
|
||||
.folder-ic { width:15px; height:15px; flex:0 0 15px; display:inline-flex; align-items:center; justify-content:center; color:var(--fg-2); }
|
||||
|
||||
/* ============ editor ============ */
|
||||
.tabs { height:35px; flex:0 0 35px; display:flex; align-items:stretch; background:var(--bg-3); border-bottom:1px solid var(--border); overflow-x:auto; overflow-y:hidden; }
|
||||
.tabs::-webkit-scrollbar { height:0; }
|
||||
.tab {
|
||||
display:flex; align-items:center; gap:7px; padding:0 9px 0 13px; cursor:pointer;
|
||||
border-right:1px solid var(--border); color:var(--fg-2); font-size:12.5px; white-space:nowrap;
|
||||
background:var(--bg-3); position:relative; max-width:230px;
|
||||
}
|
||||
.tab:hover { background:#272b31; }
|
||||
.tab.active { background:var(--bg-0); color:var(--fg-0); }
|
||||
.tab.active::after { content:""; position:absolute; left:0; right:0; top:0; height:2px; background:var(--accent); }
|
||||
.tab .tname { overflow:hidden; text-overflow:ellipsis; }
|
||||
.tab.dirty .tname::after { content:" ●"; color:var(--mod); font-size:10px; }
|
||||
.tab .tclose { width:17px; height:17px; border-radius:4px; display:flex; align-items:center; justify-content:center; color:var(--fg-3); flex:0 0 17px; }
|
||||
.tab .tclose:hover { background:var(--active); color:var(--fg-0); }
|
||||
.tab .tdot { display:none; width:7px; height:7px; border-radius:50%; background:var(--fg-2); }
|
||||
.tab.dirtyclose .tclose { display:none; }
|
||||
.tab.dirtyclose:hover .tclose { display:flex; }
|
||||
.tab.dirtyclose:hover .tdot { display:none; }
|
||||
.tab.dirtyclose .tdot { display:block; }
|
||||
.tab-mode { margin-left:6px; font-size:9.5px; letter-spacing:.05em; text-transform:uppercase; color:var(--fg-3); border:1px solid var(--border-2); border-radius:4px; padding:0 5px; line-height:14px; }
|
||||
|
||||
.editor-wrap { flex:1; min-height:0; display:flex; flex-direction:column; position:relative; }
|
||||
.editor { flex:1; overflow:auto; font-family:var(--code-font); font-size:var(--code-size); line-height:20px; padding:6px 0 40px; }
|
||||
.ln-row { display:flex; align-items:flex-start; min-height:20px; }
|
||||
.ln-row.cursor { background:rgba(255,255,255,0.035); }
|
||||
.ln-row.add { background:var(--add-bg); }
|
||||
.ln-row.del { background:var(--del-bg); }
|
||||
.ln-row.selrange { background:var(--accent-soft); }
|
||||
.ln-gutter { flex:0 0 54px; width:54px; text-align:right; padding-right:14px; color:var(--fg-3); user-select:none; cursor:pointer; font-size:12px; }
|
||||
.ln-row.cursor .ln-gutter { color:var(--fg-1); }
|
||||
.ln-gutter:hover { color:var(--fg-1); }
|
||||
.ln-sign { flex:0 0 14px; width:14px; text-align:center; user-select:none; color:var(--fg-3); }
|
||||
.ln-row.add .ln-sign { color:var(--add); }
|
||||
.ln-row.del .ln-sign { color:var(--del); }
|
||||
.ln-code { flex:1; white-space:pre; padding:0 16px 0 6px; min-width:0; }
|
||||
.editor.diff .ln-code { padding-left:6px; }
|
||||
.empty-ed { flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; color:var(--fg-3); gap:14px; }
|
||||
.empty-ed .big { font-size:13px; }
|
||||
.empty-ed kbd { font-family:var(--mono); font-size:11px; color:var(--fg-2); border:1px solid var(--border-2); border-radius:5px; padding:2px 7px; }
|
||||
.empty-ed .klist { display:flex; flex-direction:column; gap:9px; font-size:12px; }
|
||||
.empty-ed .klist div { display:flex; gap:10px; align-items:center; justify-content:space-between; min-width:230px; }
|
||||
|
||||
.diff-bar { height:26px; flex:0 0 26px; display:flex; align-items:center; gap:12px; padding:0 14px; background:var(--bg-3); border-bottom:1px solid var(--border); font-size:11px; color:var(--fg-2); }
|
||||
.diff-bar .a{color:var(--add);font-family:var(--mono);} .diff-bar .d{color:var(--del);font-family:var(--mono);}
|
||||
.diff-bar .toggle { margin-left:auto; display:flex; border:1px solid var(--border-2); border-radius:6px; overflow:hidden; }
|
||||
.diff-bar .toggle button { background:transparent; border:0; color:var(--fg-2); font:inherit; font-size:11px; padding:2px 10px; cursor:pointer; }
|
||||
.diff-bar .toggle button.on { background:var(--accent-soft); color:var(--fg-0); }
|
||||
|
||||
/* four-segment view control */
|
||||
.diff-bar .seg { margin-left:auto; display:flex; border:1px solid var(--border-2); border-radius:7px; overflow:hidden; }
|
||||
.diff-bar .seg button { background:transparent; border:0; border-right:1px solid var(--border-2); color:var(--fg-2); font:inherit; font-size:11px; padding:3px 12px; cursor:pointer; display:flex; align-items:center; gap:6px; }
|
||||
.diff-bar .seg button:last-child { border-right:0; }
|
||||
.diff-bar .seg button:hover { color:var(--fg-0); background:var(--hover); }
|
||||
.diff-bar .seg button.on { background:var(--accent-soft); color:var(--fg-0); }
|
||||
.diff-bar .seg .split-btn svg { opacity:.85; }
|
||||
|
||||
/* gutter change bars (Original / Updated / Split) */
|
||||
.ln-row.bar-del { box-shadow:inset 2px 0 0 var(--del); }
|
||||
.ln-row.bar-add { box-shadow:inset 2px 0 0 var(--add); }
|
||||
.ln-row.empty { background:repeating-linear-gradient(45deg, rgba(255,255,255,0.015) 0 7px, transparent 7px 14px); }
|
||||
|
||||
/* full-screen split */
|
||||
.split-overlay { position:fixed; inset:0; z-index:60; background:var(--bg-0); display:flex; flex-direction:column; animation:tin .12s ease-out; }
|
||||
.split-head { height:42px; flex:0 0 42px; display:flex; align-items:center; gap:11px; padding:0 16px; background:var(--bg-3); border-bottom:1px solid var(--border); }
|
||||
.split-head .sh-name { font-family:var(--mono); font-size:13px; color:var(--fg-0); }
|
||||
.split-head .git-stat { font-size:11px; }
|
||||
.split-exit { margin-left:auto; display:flex; align-items:center; gap:7px; background:transparent; border:1px solid var(--border-2); border-radius:7px; color:var(--fg-1); font:inherit; font-size:12px; padding:5px 11px; cursor:pointer; }
|
||||
.split-exit:hover { background:var(--hover); color:var(--fg-0); }
|
||||
.split-exit kbd { font-family:var(--mono); font-size:10px; color:var(--fg-3); border:1px solid var(--border-2); border-radius:4px; padding:1px 5px; }
|
||||
.split-body { flex:1; display:flex; min-height:0; }
|
||||
.split-pane { flex:1; min-width:0; display:flex; flex-direction:column; }
|
||||
.split-pane.left { border-right:1px solid var(--border-2); }
|
||||
.split-label { height:27px; flex:0 0 27px; display:flex; align-items:center; gap:9px; padding:0 16px; font-size:10.5px; letter-spacing:.07em; text-transform:uppercase; color:var(--fg-2); background:var(--bg-2); border-bottom:1px solid var(--border); }
|
||||
.split-label span { text-transform:none; letter-spacing:0; color:var(--fg-3); font-family:var(--mono); font-size:10.5px; }
|
||||
|
||||
/* syntax token colors */
|
||||
.ln-code .token.keyword,.ln-code .token.rule,.ln-code .token.atrule,.ln-code .token.important{color:var(--t-key);}
|
||||
.ln-code .token.string,.ln-code .token.attr-value,.ln-code .token.char,.ln-code .token.regex{color:var(--t-str);}
|
||||
.ln-code .token.number,.ln-code .token.unit{color:var(--t-num);}
|
||||
.ln-code .token.function,.ln-code .token.method{color:var(--t-fn);}
|
||||
.ln-code .token.comment,.ln-code .token.prolog,.ln-code .token.doctype,.ln-code .token.cdata{color:var(--t-com);font-style:italic;}
|
||||
.ln-code .token.tag{color:var(--t-tag);}
|
||||
.ln-code .token.attr-name{color:var(--t-attr);}
|
||||
.ln-code .token.punctuation{color:var(--t-punc);}
|
||||
.ln-code .token.operator{color:var(--t-punc);}
|
||||
.ln-code .token.variable,.ln-code .token.symbol{color:var(--t-var);}
|
||||
.ln-code .token.constant,.ln-code .token.boolean,.ln-code .token.builtin{color:var(--t-const);}
|
||||
.ln-code .token.property,.ln-code .token.property-access{color:var(--t-prop);}
|
||||
.ln-code .token.class-name,.ln-code .token.maybe-class-name{color:var(--t-attr);}
|
||||
.ln-code .token.parameter{color:var(--fg-0);}
|
||||
.ln-code .token.namespace{color:var(--fg-2);}
|
||||
.ln-code .token.selector{color:var(--t-tag);}
|
||||
.ln-code .token.entity,.ln-code .token.url{color:var(--t-prop);}
|
||||
.ln-code .token.deleted{color:var(--del);} .ln-code .token.inserted{color:var(--add);}
|
||||
|
||||
/* ============ terminals (right column) ============ */
|
||||
.term-pane { display:flex; flex-direction:column; min-height:0; background:var(--bg-1); }
|
||||
.term-head { height:28px; flex:0 0 28px; display:flex; align-items:center; gap:8px; padding:0 10px; background:var(--bg-3); border-bottom:1px solid var(--border); font-size:11px; color:var(--fg-2); user-select:none; }
|
||||
.term-head .dot { width:7px; height:7px; border-radius:50%; background:var(--fg-3); }
|
||||
.term-head .dot.live { background:var(--add); box-shadow:0 0 0 0 rgba(92,189,107,.5); animation:pulse 2.2s infinite; }
|
||||
@keyframes pulse { 0%{box-shadow:0 0 0 0 rgba(92,189,107,.45);} 70%{box-shadow:0 0 0 5px rgba(92,189,107,0);} 100%{box-shadow:0 0 0 0 rgba(92,189,107,0);} }
|
||||
.term-head .lbl { color:var(--fg-1); font-family:var(--mono); }
|
||||
.term-head .tag { margin-left:auto; font-size:10px; color:var(--fg-3); font-family:var(--mono); }
|
||||
.term-body { flex:1; overflow:auto; padding:8px 12px 12px; font-family:var(--mono); font-size:12.5px; line-height:18px; cursor:text; }
|
||||
.tline { white-space:pre-wrap; word-break:break-word; }
|
||||
.tline.dim{color:var(--fg-3);} .tline.acc{color:var(--accent);} .tline.ok{color:var(--add);} .tline.warn{color:var(--mod);} .tline.err{color:var(--del);}
|
||||
.tline .pfx { color:var(--accent); }
|
||||
.tline .ag { color:#c98bdb; }
|
||||
.tline .tool { color:var(--mod); }
|
||||
.tline .fp { color:var(--t-prop); }
|
||||
.term-card { border:1px solid var(--border-2); border-radius:7px; padding:7px 10px; margin:5px 0; background:rgba(255,255,255,0.02); }
|
||||
.term-card .ch { color:var(--fg-2); font-size:11px; margin-bottom:4px; display:flex; gap:7px; align-items:center; min-width:0; }
|
||||
.term-card .ch span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.term-card .add,.term-card .del { white-space:pre-wrap; word-break:break-word; line-height:17px; }
|
||||
.term-card .add{color:var(--add);} .term-card .del{color:var(--del);}
|
||||
.term-input { display:flex; align-items:center; gap:8px; }
|
||||
.term-input .ip { color:var(--accent); }
|
||||
.term-input .ip.ag { color:#c98bdb; }
|
||||
.term-input input { flex:1; background:transparent; border:0; outline:0; color:var(--fg-0); font-family:var(--mono); font-size:12.5px; caret-color:var(--accent); }
|
||||
.cursor-blink { display:inline-block; width:7px; height:14px; background:var(--accent); margin-left:1px; animation:blink 1.1s step-end infinite; vertical-align:-2px; }
|
||||
@keyframes blink { 50%{opacity:0;} }
|
||||
|
||||
/* ============ overlays ============ */
|
||||
.scrim { position:fixed; inset:0; background:rgba(8,9,11,0.5); z-index:50; display:flex; justify-content:center; align-items:flex-start; padding-top:90px; backdrop-filter:blur(1.5px); }
|
||||
.palette { width:620px; max-width:92vw; background:#212429; border:1px solid var(--border-2); border-radius:11px; box-shadow:0 24px 70px rgba(0,0,0,.55); overflow:hidden; }
|
||||
.palette .pi { display:flex; align-items:center; gap:10px; padding:12px 15px; border-bottom:1px solid var(--border); }
|
||||
.palette .pi input { flex:1; background:transparent; border:0; outline:0; color:var(--fg-0); font-size:15px; font-family:var(--ui); }
|
||||
.palette .pi .mode-chip { font-size:10px; color:var(--fg-3); border:1px solid var(--border-2); border-radius:5px; padding:2px 7px; font-family:var(--mono); }
|
||||
.palette .results { max-height:380px; overflow:auto; padding:6px; }
|
||||
.pres { display:flex; align-items:center; gap:10px; padding:7px 10px; border-radius:7px; cursor:pointer; }
|
||||
.pres.sel { background:var(--accent-soft); }
|
||||
.pres .pn { font-size:13px; color:var(--fg-0); }
|
||||
.pres .pn b { color:var(--accent); font-weight:700; }
|
||||
.pres .pp { font-size:11px; color:var(--fg-3); margin-left:auto; font-family:var(--mono); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:55%; direction:rtl; }
|
||||
.pempty { padding:26px; text-align:center; color:var(--fg-3); font-size:12.5px; }
|
||||
|
||||
/* combined search modal (content + files) */
|
||||
.search-modal { width:940px; max-width:94vw; background:#212429; border:1px solid var(--border-2); border-radius:11px; box-shadow:0 24px 70px rgba(0,0,0,.55); overflow:hidden; display:flex; flex-direction:column; }
|
||||
.search-cols { display:flex; min-height:0; }
|
||||
.sc-left { flex:1 1 auto; min-width:0; max-height:460px; overflow:auto; border-right:1px solid var(--border); padding-bottom:8px; }
|
||||
.sc-right { flex:0 0 256px; min-width:0; max-height:460px; overflow:auto; padding-bottom:8px; background:rgba(0,0,0,0.12); }
|
||||
.sc-head { position:sticky; top:0; z-index:1; background:#212429; padding:9px 14px 6px; font-size:10px; letter-spacing:.07em; text-transform:uppercase; color:var(--fg-3); display:flex; align-items:center; gap:7px; }
|
||||
.sc-right .sc-head { background:#1e2024; }
|
||||
.sc-head .sc-ct { color:var(--fg-2); background:var(--bg-3); border:1px solid var(--border); border-radius:9px; padding:0 7px; line-height:15px; font-size:10px; }
|
||||
.srf-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.pempty.sm { padding:18px 14px; text-align:left; font-size:11.5px; }
|
||||
.fres { display:flex; align-items:center; gap:9px; padding:6px 12px; cursor:pointer; }
|
||||
.fres:hover { background:var(--hover); }
|
||||
.fres-txt { min-width:0; display:flex; flex-direction:column; line-height:1.25; }
|
||||
.fres-txt .fn { font-size:12.5px; color:var(--fg-0); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.fres-txt .fn b { color:var(--accent); font-weight:700; }
|
||||
.fres-txt .fd { font-size:10.5px; color:var(--fg-3); font-family:var(--mono); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
|
||||
/* content search */
|
||||
.search-results { max-height:420px; overflow:auto; padding:4px 0 8px; }
|
||||
.sr-file { padding:7px 14px 3px; font-size:11.5px; color:var(--fg-2); display:flex; align-items:center; gap:8px; cursor:pointer; }
|
||||
.sr-file:hover { color:var(--fg-0); }
|
||||
.sr-file .cnt { margin-left:auto; color:var(--fg-3); font-family:var(--mono); font-size:10.5px; }
|
||||
.sr-line { display:flex; gap:12px; padding:2px 14px 2px 38px; font-family:var(--mono); font-size:12px; cursor:pointer; color:var(--fg-1); }
|
||||
.sr-line:hover { background:var(--hover); }
|
||||
.sr-line.sel { background:var(--accent-soft); }
|
||||
.sr-line .no { color:var(--fg-3); min-width:34px; text-align:right; }
|
||||
.sr-line .tx { white-space:pre; overflow:hidden; text-overflow:ellipsis; }
|
||||
.sr-line mark { background:rgba(216,168,92,.28); color:var(--fg-0); border-radius:2px; }
|
||||
|
||||
/* pass-on-to-agent inline popup */
|
||||
.pass-pop { position:fixed; z-index:85; width:344px; max-width:92vw; background:#23272d; border:1px solid var(--border-2); border-radius:10px; box-shadow:0 18px 48px rgba(0,0,0,.55); padding:11px; animation:popin .12s ease-out; }
|
||||
@keyframes popin { from { transform:translateY(6px); } }
|
||||
.pass-head { display:flex; align-items:center; gap:8px; font-size:12px; color:var(--fg-1); margin-bottom:9px; }
|
||||
.pass-head svg { color:#c98bdb; }
|
||||
.pass-head .pass-esc { margin-left:auto; font-family:var(--mono); font-size:10px; color:var(--fg-3); border:1px solid var(--border-2); border-radius:4px; padding:1px 6px; }
|
||||
.pass-input { width:100%; box-sizing:border-box; background:var(--bg-0); border:1px solid var(--border-2); border-radius:7px; color:var(--fg-0); font-family:var(--ui); font-size:13px; padding:8px 10px; outline:none; }
|
||||
.pass-input:focus { border-color:var(--accent-line); }
|
||||
.pass-input::placeholder { color:var(--fg-3); }
|
||||
.pass-preview { margin-top:9px; display:flex; align-items:center; gap:8px; min-width:0; }
|
||||
.pass-preview .pp-lbl { font-size:10px; text-transform:uppercase; letter-spacing:.06em; color:var(--fg-3); flex:0 0 auto; }
|
||||
.pass-preview code { font-family:var(--mono); font-size:11.5px; color:var(--accent); background:var(--accent-soft); border-radius:5px; padding:3px 7px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.pass-foot { margin-top:9px; font-size:10.5px; color:var(--fg-3); }
|
||||
.pass-foot kbd { font-family:var(--mono); font-size:10px; color:var(--fg-2); border:1px solid var(--border-2); border-radius:4px; padding:0 5px; }
|
||||
|
||||
/* terminal multi-line input */
|
||||
.term-input { align-items:flex-start; }
|
||||
.term-ta { flex:1; background:transparent; border:0; outline:0; color:var(--fg-0); font-family:var(--mono); font-size:12.5px; line-height:18px; caret-color:var(--accent); resize:none; padding:0; margin:0; overflow:hidden; }
|
||||
.term-ta::placeholder { color:var(--fg-3); }
|
||||
|
||||
/* context menu */
|
||||
.ctx { position:fixed; z-index:80; background:#23272d; border:1px solid var(--border-2); border-radius:9px; padding:5px; min-width:248px; box-shadow:0 16px 44px rgba(0,0,0,.5); }
|
||||
.ctx-item { display:flex; align-items:center; gap:10px; padding:7px 10px; border-radius:6px; cursor:pointer; font-size:12.5px; color:var(--fg-1); }
|
||||
.ctx-item:hover { background:var(--accent-soft); color:var(--fg-0); }
|
||||
.ctx-item .kc { margin-left:auto; font-family:var(--mono); font-size:10.5px; color:var(--fg-3); }
|
||||
.ctx-item.primary { color:var(--fg-0); }
|
||||
.ctx-item.primary .ic { color:var(--accent); }
|
||||
.ctx-item .ic { width:15px; display:flex; justify-content:center; color:var(--fg-3); }
|
||||
.ctx-sep { height:1px; background:var(--border); margin:5px 6px; }
|
||||
.ctx-note { padding:4px 11px 7px; font-size:10.5px; color:var(--fg-3); font-family:var(--mono); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
|
||||
/* toast */
|
||||
.toast-wrap { position:fixed; bottom:34px; left:50%; transform:translateX(-50%); z-index:90; display:flex; flex-direction:column; gap:8px; align-items:center; }
|
||||
.toast { background:#23272d; border:1px solid var(--border-2); border-left:3px solid var(--accent); border-radius:9px; padding:9px 14px; box-shadow:0 12px 34px rgba(0,0,0,.45); display:flex; align-items:center; gap:11px; animation:tin .18s ease-out; }
|
||||
@keyframes tin { from{opacity:0; transform:translateY(8px);} }
|
||||
.toast .tt { font-size:12.5px; color:var(--fg-0); }
|
||||
.toast .tref { font-family:var(--mono); font-size:11.5px; color:var(--accent); background:var(--accent-soft); border-radius:5px; padding:2px 8px; }
|
||||
|
||||
/* ============ status bar ============ */
|
||||
.statusbar { height:23px; flex:0 0 23px; display:flex; align-items:center; gap:0; background:var(--bg-3); border-top:1px solid var(--border); font-size:11px; color:var(--fg-2); user-select:none; }
|
||||
.sb { display:flex; align-items:center; gap:6px; padding:0 11px; height:100%; }
|
||||
.sb:hover { background:var(--hover); }
|
||||
.sb.accent { background:var(--accent); color:#0c1320; }
|
||||
.sb.accent:hover { background:#5d97ff; }
|
||||
.sb.spacer { flex:1; }
|
||||
.sb .a{color:var(--add);} .sb .d{color:var(--del);}
|
||||
.sb b { font-weight:600; color:var(--fg-1); }
|
||||
|
||||
/* editable buffer — transparent textarea over a highlighted <pre>, synced gutter */
|
||||
.code-edit { flex:1; min-height:0; display:flex; overflow:hidden; }
|
||||
.ce-gutterwrap { flex:0 0 54px; overflow:hidden; position:relative; }
|
||||
.ce-gutter { padding-top:6px; will-change:transform; }
|
||||
.ce-gutter div { height:20px; line-height:20px; text-align:right; padding-right:14px; color:var(--fg-3); font-family:var(--code-font); font-size:12px; user-select:none; }
|
||||
.ce-scroll { flex:1; min-width:0; overflow:auto; position:relative; }
|
||||
.ce-inner { position:relative; width:max-content; min-width:100%; }
|
||||
.ce-pre, .ce-ta {
|
||||
margin:0; padding:6px 16px 40px 6px; border:0;
|
||||
font-family:var(--code-font); font-size:var(--code-size); line-height:20px;
|
||||
white-space:pre; tab-size:4; -moz-tab-size:4; letter-spacing:0;
|
||||
}
|
||||
.ce-pre { display:block; pointer-events:none; color:var(--fg-0); }
|
||||
.ce-ta {
|
||||
position:absolute; inset:0; resize:none; outline:none; overflow:hidden;
|
||||
background:transparent; color:transparent; caret-color:var(--accent);
|
||||
}
|
||||
.ce-ta::selection { background:rgba(77,141,255,0.32); }
|
||||
|
||||
/* xterm.js host (real terminals) */
|
||||
.term-xterm { flex:1; min-height:0; overflow:hidden; padding:6px 4px 6px 8px; background:var(--bg-1); }
|
||||
.term-xterm .xterm { height:100%; }
|
||||
.term-xterm .xterm-viewport { background:transparent !important; }
|
||||
|
||||
/* ============ Electron chrome integration ============ */
|
||||
/* macOS shows native traffic lights (titleBarStyle: hiddenInset); the prototype's
|
||||
decorative dots are hidden and the bar is made draggable. Interactive controls
|
||||
opt back out of the drag region. */
|
||||
.titlebar { -webkit-app-region: drag; padding-left: 82px; }
|
||||
.titlebar .traffic { display: none; }
|
||||
.titlebar button,
|
||||
.titlebar input,
|
||||
.titlebar textarea,
|
||||
.titlebar .tb-actions { -webkit-app-region: no-drag; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; }
|
||||
}
|
||||
113
src/renderer/src/terminals.tsx
Normal file
113
src/renderer/src/terminals.tsx
Normal file
@@ -0,0 +1,113 @@
|
||||
/* Real terminals: xterm.js in the renderer bound to a node-pty PTY in main.
|
||||
* Agent pane = a shell that auto-launches `claude`; bottom pane = a plain shell.
|
||||
* "Pass on to Agent" arrives via the `agentPaste` window event and is written to
|
||||
* the agent PTY wrapped in bracketed paste (\x1b[200~ … \x1b[201~) so the CLI
|
||||
* treats it as pasted, UNSUBMITTED input — leaving the caret on a fresh line so
|
||||
* references can be stacked before the user hits Enter. */
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { Terminal as XTerm } from '@xterm/xterm'
|
||||
import { FitAddon } from '@xterm/addon-fit'
|
||||
import '@xterm/xterm/css/xterm.css'
|
||||
|
||||
let _lid = 0
|
||||
export const lid = (): number => ++_lid
|
||||
|
||||
const MONO = '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace'
|
||||
|
||||
// ANSI palette mapped onto Helder's charcoal tokens.
|
||||
const THEME = {
|
||||
background: '#1a1c1f',
|
||||
foreground: '#e6e8ea',
|
||||
cursor: '#4d8dff',
|
||||
cursorAccent: '#1a1c1f',
|
||||
selectionBackground: 'rgba(77,141,255,0.32)',
|
||||
black: '#16171a', red: '#e0696a', green: '#5cbd6b', yellow: '#d8a85c',
|
||||
blue: '#4d8dff', magenta: '#c98bdb', cyan: '#6ec0c0', white: '#b4bac2',
|
||||
brightBlack: '#5d636c', brightRed: '#e0696a', brightGreen: '#5cbd6b', brightYellow: '#d8a85c',
|
||||
brightBlue: '#6aa6f0', brightMagenta: '#c98bdb', brightCyan: '#6ec0c0', brightWhite: '#e6e8ea',
|
||||
}
|
||||
|
||||
export function Terminal({ kind }: { kind: 'agent' | 'shell' }): React.ReactElement {
|
||||
const hostRef = useRef<HTMLDivElement>(null)
|
||||
const [live, setLive] = useState(kind === 'agent')
|
||||
|
||||
useEffect(() => {
|
||||
const bridge = window.helder
|
||||
const host = hostRef.current
|
||||
if (!host) return
|
||||
|
||||
const css = getComputedStyle(document.documentElement)
|
||||
const fontFamily = css.getPropertyValue('--code-font').trim() || MONO
|
||||
const fontSize = parseFloat(css.getPropertyValue('--term-size')) || 12.5
|
||||
const term = new XTerm({
|
||||
fontFamily,
|
||||
fontSize,
|
||||
lineHeight: 1.4,
|
||||
cursorBlink: true,
|
||||
theme: THEME,
|
||||
scrollback: 5000,
|
||||
allowProposedApi: true,
|
||||
})
|
||||
const fit = new FitAddon()
|
||||
term.loadAddon(fit)
|
||||
term.open(host)
|
||||
try { fit.fit() } catch { /* host not measured yet */ }
|
||||
|
||||
let disposed = false
|
||||
let id = -1
|
||||
let offData = (): void => {}
|
||||
let offExit = (): void => {}
|
||||
|
||||
function onPaste(e: Event): void {
|
||||
if (kind !== 'agent' || !bridge || id < 0) return
|
||||
const text = (e as CustomEvent<string>).detail
|
||||
bridge.pty.write(id, '\x1b[200~' + text + '\n\x1b[201~')
|
||||
term.focus()
|
||||
}
|
||||
|
||||
if (bridge) {
|
||||
bridge.pty.create(kind, term.cols, term.rows).then((newId) => {
|
||||
if (disposed) { if (newId >= 0) bridge.pty.kill(newId); return }
|
||||
id = newId
|
||||
if (id < 0) {
|
||||
term.write('\r\n \x1b[33mPTY unavailable\x1b[0m — run `npm run rebuild`, then restart.\r\n')
|
||||
setLive(false)
|
||||
return
|
||||
}
|
||||
offData = bridge.pty.onData((tid, data) => { if (tid === id) term.write(data) })
|
||||
offExit = bridge.pty.onExit((tid) => { if (tid === id) { term.write('\r\n\x1b[90m[process exited]\x1b[0m\r\n'); setLive(false) } })
|
||||
term.onData((d) => bridge.pty.write(id, d))
|
||||
term.onResize(({ cols, rows }) => bridge.pty.resize(id, cols, rows))
|
||||
if (kind === 'agent') window.addEventListener('agentPaste', onPaste)
|
||||
})
|
||||
} else {
|
||||
term.write(' \x1b[90mTerminal needs the Electron host (node-pty); not available in browser preview.\x1b[0m\r\n')
|
||||
setLive(false)
|
||||
}
|
||||
|
||||
const ro = new ResizeObserver(() => { try { fit.fit() } catch { /* noop */ } })
|
||||
ro.observe(host)
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
ro.disconnect()
|
||||
offData()
|
||||
offExit()
|
||||
if (kind === 'agent') window.removeEventListener('agentPaste', onPaste)
|
||||
if (bridge && id >= 0) bridge.pty.kill(id)
|
||||
term.dispose()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="term-pane" style={{ flex: 1, minHeight: 0 }} onMouseDown={() => hostRef.current?.querySelector('textarea')?.focus()}>
|
||||
<div className="term-head">
|
||||
<span className={'dot' + (live ? ' live' : '')}></span>
|
||||
<span className="lbl">{kind === 'agent' ? 'claude' : 'zsh'}</span>
|
||||
<span className="tag">{kind === 'agent' ? 'agent session' : '— shell'}</span>
|
||||
</div>
|
||||
<div className="term-xterm" ref={hostRef} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
81
src/renderer/src/types.ts
Normal file
81
src/renderer/src/types.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
export type GitStatus = 'A' | 'M' | 'D' | 'R' | 'U'
|
||||
|
||||
export interface FileNode {
|
||||
name: string
|
||||
type: 'dir' | 'file'
|
||||
path: string
|
||||
open?: boolean
|
||||
children?: FileNode[]
|
||||
}
|
||||
|
||||
export interface DiffRow {
|
||||
sign: string
|
||||
oldNo: number | null
|
||||
newNo: number | null
|
||||
text: string
|
||||
}
|
||||
|
||||
export interface SideLine {
|
||||
no: number
|
||||
text: string
|
||||
mark?: 'add' | 'del' | null
|
||||
}
|
||||
|
||||
export interface SplitRow {
|
||||
l: SideLine | null
|
||||
r: SideLine | null
|
||||
}
|
||||
|
||||
export interface Diff {
|
||||
rows: DiffRow[]
|
||||
left: SideLine[]
|
||||
right: SideLine[]
|
||||
split: SplitRow[]
|
||||
add: number
|
||||
del: number
|
||||
deleted: boolean
|
||||
added: boolean
|
||||
original: string
|
||||
updated: string
|
||||
}
|
||||
|
||||
export interface Change {
|
||||
path: string
|
||||
status: GitStatus
|
||||
add: number
|
||||
del: number
|
||||
deleted: boolean
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
name: string
|
||||
branch: string
|
||||
files: Record<string, string>
|
||||
originals: Record<string, string>
|
||||
tree: FileNode
|
||||
diffs: Record<string, Diff>
|
||||
changes: Change[]
|
||||
}
|
||||
|
||||
/** A line descriptor consumed by the editor PaneView. */
|
||||
export interface ViewLine {
|
||||
no: number | null
|
||||
text: string
|
||||
sign?: string
|
||||
row?: 'add' | 'del' | 'bar-add' | 'bar-del' | null
|
||||
}
|
||||
|
||||
/** Effective project settings (mirrors src/main/config.ts). */
|
||||
export interface HelderConfig {
|
||||
ai: { command: string; autoLaunch: boolean }
|
||||
editor: { autoSave: boolean; tabSize: number }
|
||||
git: { confirmDiscard: boolean }
|
||||
terminal: { shell: string | null }
|
||||
}
|
||||
|
||||
export const DEFAULT_CONFIG: HelderConfig = {
|
||||
ai: { command: 'claude', autoLaunch: true },
|
||||
editor: { autoSave: false, tabSize: 4 },
|
||||
git: { confirmDiscard: true },
|
||||
terminal: { shell: null },
|
||||
}
|
||||
7
tsconfig.json
Normal file
7
tsconfig.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.node.json" },
|
||||
{ "path": "./tsconfig.web.json" }
|
||||
]
|
||||
}
|
||||
18
tsconfig.node.json
Normal file
18
tsconfig.node.json
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022"],
|
||||
"types": ["node", "electron-vite/node"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/main/**/*", "src/preload/**/*", "electron.vite.config.ts"]
|
||||
}
|
||||
21
tsconfig.web.json
Normal file
21
tsconfig.web.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["src/renderer/**/*"]
|
||||
}
|
||||
Reference in New Issue
Block a user