28
src/main/notes-service.ts
Normal file
28
src/main/notes-service.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Project scratch note: a plain text file at `<project>/.notes.txt`.
|
||||
*
|
||||
* Deliberately not JSON and not part of `.helder/`. It is a note the user
|
||||
* writes by hand, so it must stay readable and editable outside Helder.
|
||||
*/
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { logger } from './logger'
|
||||
|
||||
export const NOTES_FILE = '.notes.txt'
|
||||
|
||||
/** The note's text. Empty string when the project has no note yet. */
|
||||
export async function readNote(root: string): Promise<string> {
|
||||
try {
|
||||
return await readFile(join(root, NOTES_FILE), 'utf8')
|
||||
} catch (err) {
|
||||
// ENOENT is the normal "no note yet" case, anything else is worth knowing.
|
||||
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
logger.warn('notes', 'read failed', { root, err: String(err) })
|
||||
}
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function writeNote(root: string, text: string): Promise<void> {
|
||||
await writeFile(join(root, NOTES_FILE), text, 'utf8')
|
||||
}
|
||||
@@ -247,6 +247,24 @@ export function App(): React.ReactElement {
|
||||
const gitSelPath = gitSelRow?.path ?? null
|
||||
const treeSelItem = treeNav[treeSel] ?? null
|
||||
|
||||
// Clicking a row moves the keyboard cursor onto it. Without this the cursor
|
||||
// stays at index 0, so the top row of the list keeps its highlight next to
|
||||
// whichever row the click actually selected.
|
||||
const syncGitSel = (target: EventTarget): void => {
|
||||
const row = (target as HTMLElement).closest?.('.git-row') as HTMLElement | null
|
||||
const id = row?.dataset.rowId
|
||||
if (!id) return
|
||||
const i = gitNav.findIndex((r) => r.id === id)
|
||||
if (i >= 0) setGitSel(i)
|
||||
}
|
||||
const syncTreeSel = (target: EventTarget): void => {
|
||||
const row = (target as HTMLElement).closest?.('.tree-row') as HTMLElement | null
|
||||
const path = row?.dataset.rowPath
|
||||
if (path == null) return
|
||||
const i = treeNav.findIndex((r) => r.path === path)
|
||||
if (i >= 0) setTreeSel(i)
|
||||
}
|
||||
|
||||
// Keep the row cursors in range as the lists shrink/grow.
|
||||
useEffect(() => { setGitSel((s) => Math.min(s, Math.max(0, gitNav.length - 1))) }, [gitNav.length])
|
||||
useEffect(() => { setTreeSel((s) => Math.min(s, Math.max(0, treeNav.length - 1))) }, [treeNav.length])
|
||||
@@ -708,7 +726,7 @@ export function App(): React.ReactElement {
|
||||
}
|
||||
return false
|
||||
}
|
||||
// ⌘→ with the note open hands the whole note to the agent. Same route as the
|
||||
// ⌘P with the note open hands the whole note to the agent. Same route as the
|
||||
// editor's Pass on to Agent: bracketed paste, so nothing is submitted. The note
|
||||
// is saved and closed, so you see the text land in the agent composer.
|
||||
function passNote(): boolean {
|
||||
@@ -761,8 +779,9 @@ export function App(): React.ReactElement {
|
||||
else setMenu(null)
|
||||
return
|
||||
}
|
||||
// ⌘→ with the note open passes the note text to the agent.
|
||||
if (overlay === 'notes' && meta && e.key === 'ArrowRight') { e.preventDefault(); passNote(); return }
|
||||
// ⌘P with the note open passes the note text to the agent. This runs before
|
||||
// the global ⌘P (push), so the note wins while its overlay is up.
|
||||
if (overlay === 'notes' && meta && e.key.toLowerCase() === 'p') { e.preventDefault(); passNote(); return }
|
||||
// Search / help modals own the keyboard while open (they handle their own keys).
|
||||
if (overlay) return
|
||||
|
||||
@@ -933,7 +952,7 @@ export function App(): React.ReactElement {
|
||||
{/* workbench */}
|
||||
<div className="workbench">
|
||||
<div className={'col' + (activePanel === 'git' ? ' panel-active' : '') + flashClass} style={{ width: gitW, flex: '0 0 ' + gitW + 'px' }}
|
||||
onMouseDownCapture={() => setActivePanel('git')}>
|
||||
onMouseDownCapture={(e) => { setActivePanel('git'); syncGitSel(e.target) }}>
|
||||
<GitPanel branch={proj.branch} changes={proj.changes} committed={NO_COMMITTED}
|
||||
commitMsg={commitMsg} setCommitMsg={setCommitMsg}
|
||||
onStage={stageGuarded} onUnstage={unstageGuarded} onStageAll={actions.stageAll} onUnstageAll={actions.unstageAll} onCommit={commit} onPush={push}
|
||||
@@ -943,7 +962,7 @@ export function App(): React.ReactElement {
|
||||
<Splitter onDelta={(dx) => { setAutoResize(false); setGitW((w) => clamp(w + dx, 160, 460)) }} />
|
||||
|
||||
<div className={'col' + (activePanel === 'tree' ? ' panel-active' : '') + flashClass} style={{ width: treeW, flex: '0 0 ' + treeW + 'px' }}
|
||||
onMouseDownCapture={() => setActivePanel('tree')}>
|
||||
onMouseDownCapture={(e) => { setActivePanel('tree'); syncTreeSel(e.target) }}>
|
||||
{proj.tree ? (
|
||||
<FileTree tree={proj.tree} openDirs={openDirs} toggleDir={toggleDir} onOpen={openFile}
|
||||
onContext={openMenu} activePath={active} ctxPath={menu?.path ?? null}
|
||||
|
||||
@@ -88,6 +88,7 @@ function GitRow({ c, activePath, activeSide, ctxPath, kbdId, showDir, onOpen, on
|
||||
const isActive = activePath === c.path && (!activeSide || activeSide === side)
|
||||
return (
|
||||
<div className={'git-row' + (isActive ? ' active' : '') + (ctxPath === c.path ? ' ctx' : '') + (kbdId === c.id ? ' kbd' : '')}
|
||||
data-row-id={c.id}
|
||||
onClick={() => onOpen(c.path, { diff: true, side })}
|
||||
onContextMenu={(e) => onContext(e, { path: c.path, kind: 'git', staged })}
|
||||
title={c.path}>
|
||||
@@ -204,6 +205,7 @@ function TreeNode({ node, depth, openDirs, toggleDir, onOpen, onContext, activeP
|
||||
<Fragment>
|
||||
{node.path !== '' && (
|
||||
<div className={'tree-row folder' + (ctxPath === node.path ? ' ctx' : '') + (kbdPath === node.path ? ' kbd' : '')} style={{ paddingLeft: pad }}
|
||||
data-row-path={node.path}
|
||||
onClick={() => toggleDir(node.path)}
|
||||
onContextMenu={(e) => onContext(e, { path: node.path, kind: 'dir' })}>
|
||||
<span className="tw"><Chevron open={isOpen} /></span>
|
||||
@@ -225,6 +227,7 @@ function TreeNode({ node, depth, openDirs, toggleDir, onOpen, onContext, activeP
|
||||
return (
|
||||
<div className={'tree-row' + (activePath === node.path ? ' active' : '') + (ctxPath === node.path ? ' ctx' : '') + (kbdPath === node.path ? ' kbd' : '')}
|
||||
style={{ paddingLeft: pad + 2 }}
|
||||
data-row-path={node.path}
|
||||
onClick={() => onOpen(node.path)}
|
||||
onContextMenu={(e) => onContext(e, { path: node.path, kind: 'file' })}
|
||||
title={node.path}>
|
||||
|
||||
@@ -48,6 +48,48 @@ function CodeEditor({ path, text, lang, onChange, onContext }: {
|
||||
if (top < s.scrollTop) s.scrollTop = top - 20
|
||||
else if (bottom > s.scrollTop + s.clientHeight) s.scrollTop = bottom - s.clientHeight + 20
|
||||
}
|
||||
/* Tab indents, it does not move focus out of the editor.
|
||||
* Plain Tab on one line inserts spaces. Tab over a multi-line selection
|
||||
* indents every line it touches. Shift+Tab outdents.
|
||||
* We write through execCommand so the browser keeps its own undo history. */
|
||||
function replace(ta: HTMLTextAreaElement, from: number, to: number, text: string): void {
|
||||
ta.setSelectionRange(from, to)
|
||||
if (document.execCommand?.('insertText', false, text)) return
|
||||
// No execCommand (jsdom): splice by hand. Costs the native undo step.
|
||||
onChange(ta.value.slice(0, from) + text + ta.value.slice(to))
|
||||
}
|
||||
function handleTab(e: React.KeyboardEvent<HTMLTextAreaElement>, out: boolean): void {
|
||||
e.preventDefault()
|
||||
const ta = e.currentTarget
|
||||
const pad = ' '.repeat(tabSize)
|
||||
const from = ta.selectionStart
|
||||
const to = ta.selectionEnd
|
||||
if (!out && !ta.value.slice(from, to).includes('\n')) {
|
||||
replace(ta, from, to, pad)
|
||||
ta.setSelectionRange(from + pad.length, from + pad.length)
|
||||
ensureCaretVisible(ta)
|
||||
return
|
||||
}
|
||||
// Rewrite whole lines, so grow the range to the line edges first. A
|
||||
// selection that stops at column 0 leaves that last line alone.
|
||||
const start = ta.value.lastIndexOf('\n', from - 1) + 1
|
||||
const tail = to > from && ta.value[to - 1] === '\n' ? to - 1 : to
|
||||
const nl = ta.value.indexOf('\n', tail)
|
||||
const end = nl === -1 ? ta.value.length : nl
|
||||
const lines = ta.value.slice(start, end).split('\n')
|
||||
const lead = new RegExp(`^(\t| {1,${tabSize}})`)
|
||||
const cut = (line: string): number => (out ? (lead.exec(line)?.[0].length ?? 0) : 0)
|
||||
const next = lines.map((line) => (out ? line.slice(cut(line)) : pad + line)).join('\n')
|
||||
if (next === ta.value.slice(start, end)) return
|
||||
const head = out ? -cut(lines[0]) : pad.length
|
||||
const total = out ? -lines.reduce((n, line) => n + cut(line), 0) : pad.length * lines.length
|
||||
replace(ta, start, end, next)
|
||||
ta.setSelectionRange(Math.max(start, from + head), Math.max(start, to + total))
|
||||
ensureCaretVisible(ta)
|
||||
}
|
||||
function onKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>): void {
|
||||
if (e.key === 'Tab' && !e.metaKey && !e.ctrlKey && !e.altKey) handleTab(e, e.shiftKey)
|
||||
}
|
||||
function handleContext(e: React.MouseEvent<HTMLTextAreaElement>): void {
|
||||
e.preventDefault()
|
||||
const ta = e.currentTarget
|
||||
@@ -72,6 +114,7 @@ function CodeEditor({ path, text, lang, onChange, onContext }: {
|
||||
<textarea className="ce-ta" value={text} spellCheck={false} autoComplete="off"
|
||||
wrap="off" style={{ tabSize }}
|
||||
onChange={(e) => { onChange(e.target.value); ensureCaretVisible(e.target) }}
|
||||
onKeyDown={onKeyDown}
|
||||
onKeyUp={(e) => ensureCaretVisible(e.currentTarget)}
|
||||
onClick={(e) => ensureCaretVisible(e.currentTarget)}
|
||||
onContextMenu={handleContext} />
|
||||
|
||||
@@ -54,6 +54,40 @@ function inline(src: string): string {
|
||||
return s.replace(SENT_RE, (_m, i) => codes[+i])
|
||||
}
|
||||
|
||||
/** Split one GFM table row into cells. A `\|` is a literal pipe, not a divider. */
|
||||
function splitRow(line: string): string[] {
|
||||
const s = line.trim().replace(/^\|/, '').replace(/(?<!\\)\|\s*$/, '')
|
||||
const cells: string[] = []
|
||||
let cur = ''
|
||||
for (let j = 0; j < s.length; j++) {
|
||||
if (s[j] === '\\' && s[j + 1] === '|') { cur += '|'; j++; continue }
|
||||
if (s[j] === '|') { cells.push(cur); cur = ''; continue }
|
||||
cur += s[j]
|
||||
}
|
||||
cells.push(cur)
|
||||
return cells.map((c) => c.trim())
|
||||
}
|
||||
|
||||
/** The `---`/`:---:` row under a table header. Also fixes each column's align. */
|
||||
function tableAligns(line: string): (string | null)[] | null {
|
||||
if (!line.includes('|') && !/^\s*:?-+:?\s*$/.test(line)) return null
|
||||
const cells = splitRow(line)
|
||||
if (!cells.length) return null
|
||||
const aligns: (string | null)[] = []
|
||||
for (const c of cells) {
|
||||
if (!/^:?-{1,}:?$/.test(c)) return null
|
||||
const left = c.startsWith(':'), right = c.endsWith(':')
|
||||
aligns.push(left && right ? 'center' : right ? 'right' : left ? 'left' : null)
|
||||
}
|
||||
return aligns
|
||||
}
|
||||
|
||||
/** One `<td>`/`<th>`, with the column's alignment when the header set one. */
|
||||
function cell(tag: string, text: string, align: string | null): string {
|
||||
const a = align ? ` style="text-align:${align}"` : ''
|
||||
return `<${tag}${a}>` + inline(text) + `</${tag}>`
|
||||
}
|
||||
|
||||
export function renderMarkdown(text: string): string {
|
||||
const lines = text.replace(/\r\n?/g, '\n').split('\n')
|
||||
const out: string[] = []
|
||||
@@ -86,6 +120,28 @@ export function renderMarkdown(text: string): string {
|
||||
|
||||
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(line)) { flushPara(); out.push('<hr />'); i++; continue }
|
||||
|
||||
// GFM table: a header row with pipes, then a `---|---` row with the same
|
||||
// column count. Body rows run until a blank line or a line without a pipe.
|
||||
if (line.includes('|') && i + 1 < lines.length) {
|
||||
const head = splitRow(line)
|
||||
const aligns = tableAligns(lines[i + 1])
|
||||
if (aligns && aligns.length === head.length) {
|
||||
flushPara()
|
||||
i += 2
|
||||
const rows: string[][] = []
|
||||
while (i < lines.length && lines[i].includes('|') && !/^\s*$/.test(lines[i])) {
|
||||
rows.push(splitRow(lines[i])); i++
|
||||
}
|
||||
const body = rows.map((r) => '<tr>' + head.map((_c, n) => cell('td', r[n] ?? '', aligns[n])).join('') + '</tr>').join('')
|
||||
out.push(
|
||||
'<table class="md-table"><thead><tr>' +
|
||||
head.map((c, n) => cell('th', c, aligns[n])).join('') +
|
||||
'</tr></thead>' + (body ? '<tbody>' + body + '</tbody>' : '') + '</table>',
|
||||
)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if (/^\s*>/.test(line)) {
|
||||
flushPara()
|
||||
const buf: string[] = []
|
||||
|
||||
@@ -460,7 +460,7 @@ export function HelpModal({ onClose }: { onClose: () => void }): React.ReactElem
|
||||
*
|
||||
* The overlay only edits the text. Saving is the App's job, because the note
|
||||
* must also be written when the window loses focus with the overlay shut.
|
||||
* ⌘→ (pass the note to the agent) is the App's job too — it owns the shortcut.
|
||||
* ⌘P (pass the note to the agent) is the App's job too — it owns the shortcut.
|
||||
*/
|
||||
export function NotesModal({ text, onChange, onClose }: {
|
||||
text: string
|
||||
@@ -482,7 +482,7 @@ export function NotesModal({ text, onChange, onClose }: {
|
||||
{Icon.note({ style: { color: 'var(--fg-3)' } })}
|
||||
<span className="hist-title">Note</span>
|
||||
<span className="notes-file">.notes.txt</span>
|
||||
<span className="notes-hint">{Icon.spark()} To agent <kbd>⌘→</kbd></span>
|
||||
<span className="notes-hint">{Icon.spark()} To agent <kbd>⌘P</kbd></span>
|
||||
<kbd>esc</kbd>
|
||||
</div>
|
||||
<textarea ref={ref} className="notes-input" spellCheck={false}
|
||||
|
||||
@@ -315,6 +315,11 @@ kbd { flex:0 0 auto; font-family:var(--mono); font-size:11.5px; color:var(--fg-3
|
||||
.md-body pre.md-code { background:var(--bg-1); border:1px solid var(--border); border-radius:8px; padding:12px 14px; overflow:auto; margin:.9em 0; }
|
||||
.md-body pre.md-code code { font-size:var(--code-size); background:none; border:0; padding:0; white-space:pre; }
|
||||
.md-body strong { color:var(--fg-0); font-weight:600; }
|
||||
/* tables scroll on their own so a wide one never widens the whole preview */
|
||||
.md-body table.md-table { display:block; width:max-content; max-width:100%; overflow-x:auto; border-collapse:collapse; margin:.9em 0; font-size:.94em; }
|
||||
.md-body table.md-table th, .md-body table.md-table td { border:1px solid var(--border); padding:5px 10px; text-align:left; vertical-align:top; }
|
||||
.md-body table.md-table th { background:var(--bg-2); color:var(--fg-0); font-weight:600; white-space:nowrap; }
|
||||
.md-body table.md-table tbody tr:nth-child(even) { background:var(--bg-1); }
|
||||
|
||||
/* gutter change bars (Original / Updated / Split) */
|
||||
.ln-row.bar-del { box-shadow:inset 2px 0 0 var(--del); }
|
||||
|
||||
Reference in New Issue
Block a user