A notepad pane for Claude Code: notes per repo, per branch or global, that Claude can read, add to and tick off. Tags, due dates, search, pinned context, and…

A notepad pane for Claude Code: your notes sit next to the work, and Claude can read them too.
<img src="docs/demo.svg" alt="claudepad in action: adding notes from the prompt, a global note with a due date, Claude parking a follow-up, a note for the current branch, pinning, and marking a note done with the keyboard" width="640"> <sub>An illustration drawn from the mod's own pane output, not a screen recording.</sub>
Ideas, follow-ups and TODOs pile up while Claude works, and the transcript is a bad place to keep them. claudepad adds a notes pane inside Claude Code, in the terminal or the desktop Code tab. Notes belong to the repo you are in, to the branch you are on, or to you everywhere. Claude can park a follow-up instead of derailing the task, tick off the TODOs it finishes, and keep your pinned notes in mind on every prompt.
In Claude Code:
/plugin marketplace add nwilsson/claudepad
/plugin install claudepad@claudepad
Restart Claude Code, then run /notes.
Requires Claude Code 2.1.296 or later; older versions reject the hook API. Git is optional: it is only used to read the current branch.
Open the pane with /notes, or add a note without leaving the prompt:
/note fix the login redirect #bug
/note -g renew the domain #due:2026-11-01
/note -b ask in review whether the retry belongs here
Or ask Claude:
github.com/you/repo), so they are the same in every clone and subfolder. A repo with no remote goes by its root folder; any other folder by itself./note -b (or 🌿 in the pane) ties a note to the current branch: it shows only while that branch is checked out. Once the branch is merged and deleted, its notes come back to the repo's list, marked (gone)./note -g notes follow you everywhere.add_note, list_notes, complete_note and update_note. Every change Claude makes shows a toast.#due:2026-10-20) are flagged at session start and on the status line, and Claude is told which notes are overdue./note --last saves Claude's last reply as a note.#words are colored, counted and clickable in the tag bar.#tag matches a tag exactly.u/n), or Sort: due.path:line in a note gets an open button for VS Code, Cursor or a JetBrains IDE.NOTES.md: /notes export writes the repo's notes to a Markdown file. From then on the file is followed: edit it in your editor, or let Claude or a git pull change it, and the notes follow within seconds. A deleted line archives its note, with undo.notesFolder option to a git-tracked or synced folder, and notes live there as one JSON file per project, one note per line, so two machines' changes merge cleanly.| Command | What it does |
|---|---|
/notes | Open or close the pane |
/notes find <text> | Search every note; #tag matches a tag |
/notes tags | List your tags, most used first |
/notes export [--force] | Write the repo's notes to NOTES.md; --force replaces a file you wrote |
/notes import [--replace] | Read NOTES.md in; --replace makes the notes exactly the file's |
/notes undo | Bring back the last archived notes |
/note <text> | Add a note for this repo |
/note -g <text> | Add a global note |
/note -b <text> | Add a note for the current branch |
/note --last [text] | Save Claude's last reply, with your text as its first line |
/note | Open the multi-line editor |
With the pane focused (click it, or ctrl+x tab):
| Key | Action |
|---|---|
j / k | Select the next or previous note |
d | Mark the selected note done, or open again |
p | Pin or unpin it |
u / n | Move it up or down |
In the multi-line editor: arrows, Home/End and PgUp/PgDn move, Enter starts a new line, Ctrl+S saves.
| Tool | What Claude can do |
|---|---|
add_note | Add a note for the repo, the current branch (branch: true) or global (global: true) |
list_notes | Read the repo's and global notes, with ids, overdue marks and tags; or search every note |
complete_note | Mark a note done, or open again (done: false) |
update_note | Rewrite a note's text, for example to record progress |
Set these in /config, under claudepad.
| Option | Default | What it does |
|---|---|---|
editor | vscode | What a note's open button opens in: vscode, cursor or jetbrains |
notesFolder | (empty) | A folder to keep notes in instead of the plugin store; absolute, or starting with ~/ |
claudepad is a Claude Code mod: a hooks module that adds the pane, the commands, the status line and Claude's tools. Notes are kept in the mod's own store under your Claude Code config folder, or in your notesFolder, one file per project. Every change reads the stored notes fresh before writing, so two sessions open at once don't overwrite each other.
A repo is recognized by its origin remote, so notes follow it across clones and machines. The current git branch is read when a session starts, before each prompt, and after Claude runs a shell command.
In Claude Code's plugin store, a JSON file under ~/.claude/plugins/store/, unless you set notesFolder. Either way they are plain JSON. /notes export gives you a Markdown copy at any time.
Your pinned notes go with every prompt, and whatever Claude reads with list_notes. Nothing else leaves your machine, except where your notesFolder syncs to.
Yes: point notesFolder at a folder you sync or keep in git. Repo notes match across machines by the repo's remote. If a git merge leaves a conflict in a notes file, claudepad tells you and won't write over it until it's fixed.
Once the branch is deleted, its notes rejoin the repo's list, marked (gone), so nothing is stranded. Move them to the whole repo, or archive them.
Only pinned notes are sent on every prompt, and the pane warns you past about 1k tokens. Everything else reaches Claude only when it asks for it.
Found a bug or want something? Open an issue.
Try it from a clone without installing:
claude --plugin-dir /path/to/claudepad
| Path | What's there |
|---|---|
.claude-plugin/plugin.json | The manifest; marketplace.json lists it |
hooks/register.tsx | Commands, the pane, tools, prompt context, storage, sync |
hooks/notes.ts | The notes logic, with no engine or UI: tags, search, order, Markdown, merge |
hooks/editor.tsx | The multi-line editor component |
types/index.d.ts | The note and state types |
tests/ | Logic tests and engine tests with a mocked store, clock and folder |
ROADMAP.md | What was built, and the decisions behind it |
scripts/demo/ | How docs/demo.svg is captured from the pane and built |
Checks:
claude plugin validate .
npx -p typescript tsc -p . # after the engine has laid .claude-plugin/types
claude plugin test . # tests/*.test.ts(x), in the engine's sandbox
scripts/check.sh runs all three and checks that both manifests carry the same version. CI runs it on every push and pull request, without tsc: the types only exist once the engine has loaded the plugin.
hooks/register.tsx 1457 lines1import { atom, derive, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { ArchiveUndo, EditorSession, FileSeen, Note, Scope } from '../types'
5import type { Editor, FileLink } from './notes'
6import {
7 EDITORS,
8 BRANCH_COMMAND,
9 EXPORT_FILE,
10 EXPORT_MARK,
11 GLOBAL_KEY,
12 LEGACY_KEY,
13 NO_BRANCHES,
14 TAG,
15 asText,
16 baseName,
17 branchMark,
18 doneByWeek,
19 dueOf,
20 editorCommand,
21 fileNameOf,
22 groupByKey,
23 isGlobal,
24 isHere,
25 isArchived,
26 isNotesKey,
27 isOffBranch,
28 keyOf,
29 keyOfProject,
30 keyOfSync,
31 linksOf,
32 live,
33 localDate,
34 matches,
35 mergeImport,
36 migrate,
37 newId,
38 normalize,
39 onBranch,
40 overdue,
41 PINNED_TOKEN_LIMIT,
42 paneOrder,
43 pinnedContext,
44 parseBranches,
45 isAbsolutePath,
46 parseMarkdown,
47 parseNoteArgs,
48 parseNotesFile,
49 plural,
50 preview,
51 remoteId,
52 reorder,
53 resolvePath,
54 sameBranches,
55 statusFor,
56 syncFile,
57 tagCounts,
58 tagged,
59 tokenLabel,
60 tokensOf,
61 tagsOfNote,
62 toMarkdown,
63 toNotesFile,
64 unarchived,
65 withDone,
66} from './notes'
67
68const PANE = 'claudepad'
69const ADD_TOOL = 'mcp__claudepad__add_note'
70const LIST_TOOL = 'mcp__claudepad__list_notes'
71const COMPLETE_TOOL = 'mcp__claudepad__complete_note'
72const UPDATE_TOOL = 'mcp__claudepad__update_note'
73/** The tools that run shell commands, any of which can switch the git branch. */
74const SHELL_TOOLS = ['Bash', 'PowerShell']
75
76const notes = atom({ plugin: 'claudepad', key: 'notes' } as const, [] as Note[])
77const editor = atom({ plugin: 'claudepad', key: 'editor' } as const, null as EditorSession | null)
78const draft = atom({ plugin: 'claudepad', key: 'draft' } as const, '')
79const isLineMode = atom({ plugin: 'claudepad', key: 'isLineMode' } as const, false)
80const EDITOR_MODULE = './editor.tsx'
81
82/** The session's folder, normalized; the pane reads it so a directory change redraws it. */
83const folder = atom({ plugin: 'claudepad', key: 'folder' } as const, '')
84const scope = atom({ plugin: 'claudepad', key: 'scope' } as const, 'project' as Scope)
85const query = atom({ plugin: 'claudepad', key: 'query' } as const, '')
86const activeTag = atom({ plugin: 'claudepad', key: 'tag' } as const, null as string | null)
87const lastArchive = atom({ plugin: 'claudepad', key: 'lastArchive' } as const, null as ArchiveUndo | null)
88const isArchiveView = atom({ plugin: 'claudepad', key: 'isArchiveView' } as const, false)
89const isByDue = atom({ plugin: 'claudepad', key: 'isByDue' } as const, false)
90const branches = atom({ plugin: 'claudepad', key: 'branches' } as const, NO_BRANCHES)
91const fileSeen = atom({ plugin: 'claudepad', key: 'fileSeen' } as const, null as FileSeen | null)
92const isPinnedHeavy = atom({ plugin: 'claudepad', key: 'isPinnedHeavy' } as const, false)
93const selected = atom({ plugin: 'claudepad', key: 'selected' } as const, null as string | null)
94
95/** Open pinned notes in every project, worked out again only when the notes change. */
96const pinned = derive([notes], list => live(list).filter(note => note.isPinned && !note.isDone))
97
98/** How long the pane offers to undo an archive. */
99const UNDO_MS = 5000
100
101/** How often NOTES.md is checked for outside edits. */
102const POLL_MS = 3000
103
104/** The most open buttons one note gets, one per file it mentions. */
105const MAX_LINKS = 3
106
107const TAG_COLORS = ['#e5a50a', '#3584e4', '#c061cb', '#2ec27e', '#e66100', '#1c9fb8', '#e01b24']
108
109/** The same tag gets the same color everywhere. */
110const colorOf = (tag: string) => {
111 let hash = 0
112 for (const ch of tag) hash = (hash * 31 + ch.codePointAt(0)!) >>> 0
113 return TAG_COLORS[hash % TAG_COLORS.length]!
114}
115
116/**
117 * The project the session is in, as notes are filed under it: a git
118 * repository by its remote (see remoteId), so its notes follow it to every
119 * clone and machine; a repository with no remote by its root folder; any other
120 * folder by itself. `others` are the folders this project's notes were filed
121 * under before (the repository root and the session folder), which adopt moves.
122 */
123const identify = async ($: EngineInterface) => {
124 const cwd = normalize(await $.session.cwd())
125 const repo = await $.session.repo().catch(() => null)
126 if (!repo) return { project: cwd, others: [] as string[] }
127 const root = normalize(repo.root)
128 const project = repo.remote ? remoteId(repo.remote) : root
129 return { project, others: [...new Set([root, cwd])].filter(other => other !== project) }
130}
131
132/** The session's project, as session.start or the last directory change worked it out (see identify). */
133const projectOf = async ($: EngineInterface) => (await read($, folder)) || (await identify($)).project
134
135/** Sets the status line from `all`, leaving out the notes of other branches. */
136const showStatus = async ($: EngineInterface, all: readonly Note[], project: string) =>
137 $.ui.status(statusFor(onBranch(all, project, await read($, branches)), project, localDate(Date.now())))
138
139/**
140 * Reads the session folder's git branches again; resolves true when they
141 * changed. Not a repository, or no git, is no branches.
142 */
143const readBranches = async ($: EngineInterface) => {
144 let found = NO_BRANCHES
145 try {
146 const { exitCode, stdout } = await $.process.run(BRANCH_COMMAND, { timeoutMs: 5000 })
147 if (exitCode === 0) found = parseBranches(stdout)
148 } catch {
149 // git missing or too slow: as outside a repository.
150 }
151 if (sameBranches(found, await read($, branches))) return false
152 await update($, branches, () => found)
153 return true
154}
155
156/** Reads the branches again and, when they changed, recounts the status line. */
157const refreshBranches = async ($: EngineInterface) => {
158 if (await readBranches($)) await showStatus($, await read($, notes), await projectOf($))
159}
160
161/** The saved notes, each with its tags (a note saved before tags were stored gets them here). */
162const fromStore = (saved: unknown) =>
163 Array.isArray(saved) ? (saved as Note[]).map(note => (note.tags ? note : tagged(note))) : []
164
165/** The `notesFolder` option, as written; empty keeps notes in the plugin store. Set by register. */
166let notesFolderOption = ''
167
168/** Where notes are kept: the plugin store, or a notes folder with a file per key (see fileNameOf). */
169type NotesStore = {
170 /** The notes folder, or undefined for the plugin store. */
171 folder?: string
172 /** The keys that hold notes. */
173 keys: () => Promise<string[]>
174 /** A key's notes as saved, undefined when it has none; rejects for a file that no longer reads as notes. */
175 get: (key: string) => Promise<unknown>
176 set: (key: string, list: readonly Note[]) => Promise<void>
177 /** Empties a key: the plugin store drops it; a file, which cannot be deleted, is left with no notes. */
178 clear: (key: string) => Promise<void>
179}
180
181const pluginStore = ($: EngineInterface): NotesStore => ({
182 keys: async () => (await $.store.keys()).filter(isNotesKey),
183 get: key => $.store.get(key),
184 set: (key, list) => $.store.set(key, list),
185 clear: key => $.store.delete(key),
186})
187
188/** The notes folder's files, as one store. A file that does not read as notes is reported once per load, and never written over. */
189const folderStore = ($: EngineInterface, folder: string): NotesStore => {
190 const pathOf = (key: string) => `${folder}/${fileNameOf(key)}`
191 const readFile = async (path: string) => {
192 const text = await $.fs.read(path).catch(() => undefined)
193 if (typeof text !== 'string') return undefined
194 try {
195 return parseNotesFile(text)
196 } catch {
197 throw new Error(`claudepad: ${path} no longer reads as notes (a git merge conflict left in it?). Fix it to see its notes again.`)
198 }
199 }
200 return {
201 folder,
202 keys: async () => {
203 const keys: string[] = []
204 for (const entry of await $.fs.list(folder).catch(() => [])) {
205 if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
206 const file = await readFile(`${folder}/${entry.name}`).catch((err: Error) => {
207 $.ui.toast(err.message, { timeoutMs: 10000 })
208 return undefined
209 })
210 // Only the file a key names counts: a copy under another name is not read.
211 if (file && isNotesKey(file.key) && fileNameOf(file.key) === entry.name) keys.push(file.key)
212 }
213 return keys
214 },
215 get: async key => (await readFile(pathOf(key)))?.notes,
216 set: (key, list) => $.fs.write(pathOf(key), toNotesFile(key, list)),
217 clear: key => $.fs.write(pathOf(key), toNotesFile(key, [])),
218 }
219}
220
221/** The notes folder the option names, `~` as the home folder, or '' for none. */
222const notesFolderOf = async ($: EngineInterface) => {
223 const folder = notesFolderOption.replace(/[\\/]+$/, '')
224 if (!/^~([\\/]|$)/.test(folder)) return folder
225 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')) ?? ''
226 return `${home.replace(/[\\/]+$/, '')}${folder.slice(1)}`
227}
228
229const notesStore = async ($: EngineInterface) => {
230 const folder = await notesFolderOf($)
231 return folder === '' ? pluginStore($) : folderStore($, folder)
232}
233
234/** Notes still under the plugin store's old single key move to their per-project keys there. */
235const migrateLegacy = async ($: EngineInterface) => {
236 const keys = await $.store.keys()
237 if (!keys.includes(LEGACY_KEY)) return
238 const stored = new Map<string, Note[]>()
239 for (const key of keys.filter(isNotesKey)) stored.set(key, fromStore(await $.store.get(key)))
240 for (const [key, list] of migrate(fromStore(await $.store.get(LEGACY_KEY)), stored)) {
241 // `migrate` only adds, so a key it left alone has as many notes as before.
242 if (list.length !== stored.get(key)?.length) await $.store.set(key, list)
243 }
244 await $.store.delete(LEGACY_KEY)
245}
246
247/**
248 * The first time a notes folder is used, with no notes files in it yet, the
249 * plugin store's notes are copied in. They stay in the plugin store, for
250 * going back by clearing the option.
251 */
252const fillFolder = async ($: EngineInterface, store: NotesStore) => {
253 const files = await $.fs.list(store.folder!).catch(() => [])
254 if (files.some(entry => entry.name.endsWith('.json'))) return
255 const plugin = pluginStore($)
256 let copied = 0
257 for (const key of await plugin.keys()) {
258 const list = fromStore(await plugin.get(key))
259 if (list.length === 0) continue
260 await store.set(key, list)
261 copied += list.length
262 }
263 if (copied > 0) $.ui.toast(`📝 Copied ${plural(copied, 'note')} into ${store.folder}`)
264}
265
266/**
267 * Reads every note from the store into the session, and refreshes the status
268 * line for `project`.
269 */
270const reload = async ($: EngineInterface, project: string) => {
271 await migrateLegacy($)
272 const store = await notesStore($)
273 if (store.folder !== undefined) await fillFolder($, store)
274 const all: Note[] = []
275 for (const key of await store.keys()) {
276 try {
277 all.push(...fromStore(await store.get(key)))
278 } catch (err) {
279 $.ui.toast(err instanceof Error ? err.message : String(err), { timeoutMs: 10000 })
280 }
281 }
282 await update($, notes, () => all)
283 await showStatus($, all, project)
284}
285
286/**
287 * Moves the notes filed under the folders this project was known by before
288 * (see identify) to the project, with their NOTES.md sync record, and says so.
289 */
290const adopt = async ($: EngineInterface, project: string, others: readonly string[]) => {
291 const store = await notesStore($)
292 let moved = 0
293 for (const other of others) {
294 const list = fromStore(await store.get(keyOfProject(other)).catch(() => undefined))
295 if (list.length === 0) continue
296 // After the project's own notes, in the order they were written.
297 await change($, [keyOfProject(other), keyOfProject(project)], all => [
298 ...all.filter(note => note.project !== other),
299 ...all.filter(note => note.project === other).map(note => ({ ...note, project })),
300 ])
301 moved += list.length
302 const synced = await $.store.get(keyOfSync(other))
303 if (synced !== undefined && (await $.store.get(keyOfSync(project))) === undefined) {
304 await $.store.set(keyOfSync(project), synced)
305 }
306 }
307 if (moved > 0) {
308 $.ui.toast(`📝 ${plural(moved, 'note')} of ${baseName(others[0]!)} now go with the repository, as ${project}`)
309 }
310}
311
312/**
313 * Changes the notes stored under `keys`, and refreshes the status line. It
314 * starts from the store as it is now, not this session's copy, so a note
315 * another session added there survives; and it reads and writes only those
316 * keys, so changes to other projects never meet. `fn` gets those keys' notes
317 * and may return only notes that belong under them.
318 */
319const change = async ($: EngineInterface, keys: readonly string[], fn: (list: Note[]) => Note[]) => {
320 const touched = [...new Set(keys)]
321 const store = await notesStore($)
322 const before: Note[] = []
323 // A notes file that no longer reads as notes stops the change: it is never written over.
324 for (const key of touched) before.push(...fromStore(await store.get(key)))
325 const written = fn(before)
326 const groups = groupByKey(written)
327 const stray = [...groups.keys()].find(key => !touched.includes(key))
328 if (stray !== undefined) {
329 throw new Error(`claudepad: a change returned a note for ${stray}, outside ${touched.join(', ')}`)
330 }
331 for (const key of touched) {
332 const list = groups.get(key)
333 await (list ? store.set(key, list) : store.clear(key))
334 }
335 const all = await update($, notes, current => [
336 ...current.filter(note => !touched.includes(keyOf(note))),
337 ...written,
338 ])
339 await showStatus($, all, await projectOf($))
340 return written
341}
342
343/**
344 * Changes one note, under the key this session last saw it in; resolves to the
345 * note as written, or undefined when there is no such note (any longer).
346 */
347const changeNote = async ($: EngineInterface, id: string, fn: (note: Note) => Note) => {
348 const seen = (await read($, notes)).find(note => note.id === id)
349 if (!seen) return undefined
350 const written = await change($, [keyOf(seen)], all => all.map(note => (note.id === id ? fn(note) : note)))
351 return written.find(note => note.id === id)
352}
353
354/** Changes the notes with these ids, across whichever keys they are under. */
355const changeNotes = async ($: EngineInterface, ids: readonly string[], fn: (note: Note) => Note) => {
356 const seen = (await read($, notes)).filter(note => ids.includes(note.id))
357 if (seen.length === 0) return []
358 const written = await change($, seen.map(keyOf), all => all.map(note => (ids.includes(note.id) ? fn(note) : note)))
359 return written.filter(note => ids.includes(note.id))
360}
361
362/**
363 * Archives notes and keeps them for undo: the pane offers an undo button for
364 * UNDO_MS, and /notes undo restores them until the next archive. `label` says
365 * what was archived, for the toast and the pane.
366 */
367const archiveNotes = async ($: EngineInterface, ids: readonly string[], label: string) => {
368 const now = Date.now()
369 const archived = await changeNotes($, ids, note => (isArchived(note) ? note : { ...note, archivedAt: now }))
370 if (archived.length === 0) return
371 const archiveId = newId()
372 const noteIds = archived.map(note => note.id)
373 await update($, lastArchive, () => ({ id: archiveId, noteIds, label, isOffered: true }))
374 $.ui.toast(`🗄 Archived: ${label} (undo in the pane, or /notes undo)`, { timeoutMs: UNDO_MS })
375 // Hides only this archive's button: a later one, even of the same note, has its own timer.
376 $.clock.after(UNDO_MS, () => {
377 void update($, lastArchive, last => (last?.id === archiveId ? { ...last, isOffered: false } : last))
378 })
379}
380
381/** Takes the last archive's notes out of the archive again. */
382const undoArchive = async ($: EngineInterface) => {
383 const last = await read($, lastArchive)
384 if (!last) return 'Nothing to undo.'
385 await changeNotes($, last.noteIds, unarchived)
386 await update($, lastArchive, () => null)
387 return `📝 Restored: ${last.label}`
388}
389
390/** Deletes an archived note for good: the only delete there is. */
391const purgeNote = async ($: EngineInterface, id: string) => {
392 const seen = (await read($, notes)).find(note => note.id === id)
393 if (!seen || !isArchived(seen)) return
394 await change($, [keyOf(seen)], all => all.filter(note => note.id !== id))
395 await update($, lastArchive, last => (last ? { ...last, noteIds: last.noteIds.filter(other => other !== id) } : last))
396}
397
398/** Where a note in `where` goes: a branch note only while a branch is checked out, else the project's. */
399const placeOf = async ($: EngineInterface, where: Scope) => {
400 if (where === 'global') return { project: null }
401 const project = await projectOf($)
402 const branch = where === 'branch' ? (await read($, branches)).current : null
403 return branch === null ? { project } : { project, branch }
404}
405
406/** What a note's place is called: `global`, the project's folder name, or that and its branch. */
407const placeName = (note: Note) =>
408 isGlobal(note) ? 'global' : `${baseName(note.project ?? '')}${note.branch === undefined ? '' : ` 🌿 ${note.branch}`}`
409
410/** What kind of note it is: `global`, `project`, or its branch. */
411const kindOf = (note: Note) => (isGlobal(note) ? 'global' : note.branch === undefined ? 'project' : `🌿 ${note.branch}`)
412
413const addNote = async ($: EngineInterface, text: string, author: Note['author'], where: Scope) => {
414 const note = tagged({
415 id: newId(),
416 text: text.trim(),
417 isDone: false,
418 isPinned: false,
419 author,
420 createdAt: Date.now(),
421 ...(await placeOf($, where)),
422 })
423 await change($, [keyOf(note)], list => [...list, note])
424 return note
425}
426
427/**
428 * Saves Claude's last reply in the main conversation (its last message with
429 * text) as a note of yours, with `text`, if any, as the first line.
430 */
431const saveLastReply = async ($: EngineInterface, text: string, where: Scope) => {
432 const rows = await $.session.messages()
433 const reply = rows.findLast(row => row.role === 'assistant' && row.text.trim() !== '')?.text.trim()
434 if (reply === undefined) return 'No reply from Claude yet to save.'
435 const note = await addNote($, text === '' ? reply : `${text}\n\n${reply}`, 'you', where)
436 return `📝 Saved Claude's last reply as a ${kindOf(note)} note: ${preview(reply)}`
437}
438
439/**
440 * Opens a file a note mentions in `editor`. A relative path is under the
441 * note's own folder: for this project's and the global notes, the repository
442 * root, else the session's folder, spelled as the host spells it; for another
443 * project's, its folder, which a project known by its remote does not have
444 * here. A failure is a toast.
445 */
446const openLink = async ($: EngineInterface, editor: Editor, note: Note, link: FileLink) => {
447 const isOurs = isGlobal(note) || isHere(note, await projectOf($))
448 const repo = isOurs ? await $.session.repo().catch(() => null) : null
449 const folder = isOurs ? (repo?.root ?? (await $.session.cwd())) : isAbsolutePath(note.project!) ? note.project! : null
450 if (folder === null && !isAbsolutePath(link.path)) {
451 $.ui.toast(`Couldn't open ${link.text}: it is under ${note.project}, which is not open here.`)
452 return
453 }
454 const argv = editorCommand(editor, resolvePath(link.path, folder ?? ''), link)
455 const failed = (why: string) => $.ui.toast(`Couldn't open ${link.text} with ${argv[0]}: ${why}`)
456 try {
457 const { exitCode, stderr } = await $.process.run(argv, { timeoutMs: 15000 })
458 if (exitCode !== 0) failed(stderr.trim().split('\n')[0] || `exit code ${exitCode}`)
459 } catch (err) {
460 failed(err instanceof Error ? err.message : String(err))
461 }
462}
463
464const openPane = ($: EngineInterface) =>
465 $.ui.open({ id: PANE, title: 'claudepad', focus: true })
466
467/**
468 * Writes this project's and the global notes to NOTES.md in the session's
469 * folder. A NOTES.md this mod did not write is left alone unless `force`.
470 */
471const exportNotes = async ($: EngineInterface, force: boolean) => {
472 const existing = await $.fs.read(EXPORT_FILE).catch(() => undefined)
473 if (typeof existing === 'string' && !existing.startsWith(EXPORT_MARK) && !force) {
474 return {
475 isWritten: false,
476 message: `${EXPORT_FILE} already exists and wasn't written by the notepad. Run /notes export --force to replace it.`,
477 }
478 }
479 const project = await projectOf($)
480 const markdown = toMarkdown(await read($, notes), project, Date.now(), await read($, branches))
481 await $.fs.write(EXPORT_FILE, markdown)
482 await markSynced($, project, markdown)
483 return { isWritten: true, message: `📝 Exported notes to ${EXPORT_FILE} in ${baseName(project)}.` }
484}
485
486/**
487 * Records `markdown` as the project's NOTES.md in sync with the notes, so the
488 * poll compares later edits with it, and the file's time as seen, so the poll
489 * does not read this write back.
490 */
491const markSynced = async ($: EngineInterface, project: string, markdown: string) => {
492 await $.store.set(keyOfSync(project), markdown)
493 const stat = await $.fs.stat(EXPORT_FILE).catch(() => undefined)
494 if (stat) await update($, fileSeen, () => ({ project, mtimeMs: stat.mtimeMs }))
495}
496
497/**
498 * Checks the session folder's NOTES.md for edits made outside the notepad (an
499 * editor, Claude, git) and applies them (see syncFile). Only a file the export
500 * wrote is followed; it is read only when its time changed. The first time a
501 * project's file is seen it is only recorded, since there is nothing to
502 * compare it with.
503 */
504const pollFile = async ($: EngineInterface) => {
505 const project = await projectOf($)
506 const stat = await $.fs.stat(EXPORT_FILE).catch(() => undefined)
507 if (stat?.kind !== 'file') return
508 const seen = await read($, fileSeen)
509 if (seen?.project === project && seen.mtimeMs === stat.mtimeMs) return
510 await update($, fileSeen, () => ({ project, mtimeMs: stat.mtimeMs }))
511 const markdown = await $.fs.read(EXPORT_FILE).catch(() => undefined)
512 if (typeof markdown !== 'string' || !markdown.startsWith(EXPORT_MARK)) return
513 const saved = await $.store.get(keyOfSync(project))
514 if (saved === markdown) return
515 await $.store.set(keyOfSync(project), markdown)
516 if (typeof saved !== 'string') return
517
518 const known = await read($, branches)
519 let result: ReturnType<typeof syncFile> | undefined
520 await change($, [keyOfProject(project), GLOBAL_KEY], all => {
521 result = syncFile(all, parseMarkdown(saved), parseMarkdown(markdown), project, Date.now(), known)
522 return result.list
523 })
524 const { added, restored, updated, archive } = result!
525 const parts = [
526 added && `${added} added`,
527 restored && `${restored} back from the archive`,
528 updated && `${updated} updated`,
529 ].filter(Boolean)
530 if (parts.length > 0) $.ui.toast(`📝 ${EXPORT_FILE} changed: ${parts.join(', ')}`)
531 if (archive.length > 0) {
532 await archiveNotes($, archive, `${plural(archive.length, 'note')} removed from ${EXPORT_FILE}`)
533 }
534}
535
536/** Reads NOTES.md from the session's folder into the notepad (see mergeImport). */
537const importNotes = async ($: EngineInterface, replace: boolean) => {
538 const markdown = await $.fs.read(EXPORT_FILE).catch(() => undefined)
539 if (typeof markdown !== 'string') {
540 return `No ${EXPORT_FILE} in this folder to import.`
541 }
542 const parsed = parseMarkdown(markdown)
543 if (parsed.length === 0) {
544 return `${EXPORT_FILE} has no list items to import (notes are lines starting with "- ").`
545 }
546 const project = await projectOf($)
547 const known = await read($, branches)
548 let counts = { added: 0, updated: 0, removed: 0 }
549 await change($, [keyOfProject(project), GLOBAL_KEY], all => {
550 const { list, ...merged } = mergeImport(all, parsed, project, replace, Date.now(), known)
551 counts = merged
552 return list
553 })
554 // The notes now hold the file: later edits to it are what the poll applies.
555 await markSynced($, project, markdown)
556 const { added, updated, removed } = counts
557 if (replace) {
558 return `📝 Replaced ${plural(removed, 'note')} with ${plural(parsed.length, 'note')} from ${EXPORT_FILE}.`
559 }
560 const unchanged = parsed.length - added - updated
561 return `📝 Imported ${EXPORT_FILE}: ${added} added, ${updated} updated, ${unchanged} unchanged.`
562}
563
564/** Opens the multi-line editor on a note's text, or on '' for a new note. */
565const openEditor = async ($: EngineInterface, id: string, initial: string) => {
566 await update($, draft, () => initial)
567 await update($, editor, () => ({ id, initial, line: null }))
568}
569
570const closeEditor = async ($: EngineInterface) => {
571 await update($, editor, () => null)
572 await update($, draft, () => '')
573}
574
575/** Saves the editor's text (or `text`, the editor's own last word) and closes it. */
576const saveEditor = async ($: EngineInterface, text?: string) => {
577 const session = await read($, editor)
578 if (!session) return 'Nothing to save.'
579 // Drop blank lines at the start and whitespace at the end of every line.
580 const body = (text ?? (await read($, draft)))
581 .split('\n')
582 .map(line => line.trimEnd())
583 .join('\n')
584 .replace(/^\n+|\n+$/g, '')
585 if (body.trim() === '') return 'The note is empty: nothing saved.'
586 if (session.id === 'new') {
587 await addNote($, body, 'you', await read($, scope))
588 } else {
589 await changeNote($, session.id, note => tagged({ ...note, text: body }))
590 }
591 await closeEditor($)
592 return session.id === 'new' ? '📝 Note added.' : '📝 Note saved.'
593}
594
595export const register: Register = (on, options) => {
596 // The mod's `editor` option: which editor a note's file reference opens in.
597 const linkEditor: Editor = EDITORS.find(name => name === options.editor) ?? 'vscode'
598 // The mod's `notesFolder` option: a folder to keep notes in instead of the plugin store.
599 notesFolderOption = typeof options.notesFolder === 'string' ? options.notesFolder.trim() : ''
600
601 on('session.start', async ($, e, next) => {
602 const { project, others } = await identify($)
603 await update($, folder, () => project)
604 await readBranches($)
605 await adopt($, project, others)
606 await reload($, project)
607 // NOTES.md edits made since the last session, then any made during this one.
608 await pollFile($).catch(() => undefined)
609 $.clock.every(POLL_MS, () => void pollFile($).catch(() => undefined))
610 // Overdue notes, here (on this branch) and global, are the first thing the session shows.
611 const shown = onBranch(await read($, notes), project, await read($, branches))
612 const late = overdue(shown, project, localDate(Date.now()))
613 if (late.length === 1) {
614 $.ui.toast(`⏰ Overdue: ${preview(late[0]!.text)}`, { timeoutMs: 8000 })
615 } else if (late.length > 1) {
616 const more = late.length > 3 ? ` · and ${late.length - 3} more` : ''
617 const named = late.slice(0, 3).map(note => preview(note.text))
618 $.ui.toast(`⏰ ${late.length} overdue notes: ${named.join(' · ')}${more}`, { timeoutMs: 8000 })
619 }
620
621 await $.command.register({
622 name: 'notes',
623 description:
624 'Open or close the notepad pane; /notes find <text> searches, /notes tags lists tags, /notes export and /notes import sync NOTES.md, /notes undo restores the last archived notes',
625 argumentHint: '[find <text> | tags | export | import | undo]',
626 })
627 await $.command.register({
628 name: 'note',
629 description:
630 "Add a note for this project (-g for a global note, -b for the current git branch only, #words become tags; --last saves Claude's last reply)",
631 argumentHint: '[-g | -b] [--last] <text>',
632 immediate: true,
633 })
634 await $.tool.register({
635 name: 'add_note',
636 description:
637 "Add a note to the user's notepad (a sidebar they keep across sessions). Use it for follow-ups, TODOs or things to remember later that are not worth doing now. Notes belong to the current project unless `global` is true (use global only for things unrelated to this project). Keep each note short and self-contained. Tag notes with #hashtags in the text (for example #bug, #idea, #todo); prefer tags the user already uses, which list_notes reports.",
638 inputSchema: {
639 type: 'object',
640 properties: {
641 text: { type: 'string', description: 'The note, one or two lines, with any #tags inline.' },
642 global: {
643 type: 'boolean',
644 description: 'True for a note not tied to this project. Default false.',
645 },
646 branch: {
647 type: 'boolean',
648 description:
649 "True for a note about the work on the current git branch only: it is listed while that branch is checked out, and with the project's notes again once the branch is deleted. Default false.",
650 },
651 },
652 required: ['text'],
653 },
654 })
655 await $.tool.register({
656 name: 'list_notes',
657 description:
658 "List the notes in the user's notepad: this project's notes and the global ones, with whether each is done or pinned, and each note's id (for complete_note and update_note). Notes of another git branch of this project are left out until it is checked out; a note marked (branch name) belongs to that branch. A note with a #due:YYYY-MM-DD date is marked (overdue) or (due today) while open, and a list with dated notes ends with today's date. With `query`, search every note (all projects) for notes containing all of its words; a #word in the query matches that tag exactly. Also lists the tags in use.",
659 inputSchema: {
660 type: 'object',
661 properties: {
662 query: {
663 type: 'string',
664 description: 'Optional words to search for, case-insensitive; #tag matches a tag (e.g. "#bug login").',
665 },
666 },
667 },
668 })
669 await $.tool.register({
670 name: 'complete_note',
671 description:
672 "Mark a note in the user's notepad done, for example a TODO you have just finished, or (with `done: false`) open again. Take the id from list_notes or add_note. Only mark a note done when the work it describes is actually finished.",
673 inputSchema: {
674 type: 'object',
675 properties: {
676 id: { type: 'string', description: "The note's id, as list_notes shows it." },
677 done: { type: 'boolean', description: 'False to reopen a done note. Default true.' },
678 },
679 required: ['id'],
680 },
681 })
682 await $.tool.register({
683 name: 'update_note',
684 description:
685 "Replace the text of a note in the user's notepad, for example to record progress or correct it. Take the id from list_notes or add_note. Keep the note's #tags unless they no longer apply.",
686 inputSchema: {
687 type: 'object',
688 properties: {
689 id: { type: 'string', description: "The note's id, as list_notes shows it." },
690 text: { type: 'string', description: 'The new text, with any #tags inline.' },
691 },
692 required: ['id', 'text'],
693 },
694 })
695
696 return next(e)
697 })
698
699 // A new folder has its own notes: read them fresh (other sessions may have
700 // written since), recount the status line and redraw the pane.
701 on('classic.CwdChanged', async ($, e, next) => {
702 const { project, others } = await identify($)
703 await update($, folder, () => project)
704 await readBranches($)
705 await adopt($, project, others)
706 await reload($, project)
707 return next(e)
708 })
709
710 // A shell command may have switched, made or deleted a branch: read them again.
711 on('classic.PostToolBatch', async ($, e, next) => {
712 if (e.tool_calls.some(call => SHELL_TOOLS.includes(call.tool_name))) await refreshBranches($)
713 return next(e)
714 })
715
716 // /notes toggles the pane.
717 on('command.run', { command: 'notes' }, async ($, e) => {
718 const find = /^\s*(find|search)\b\s*/i.exec(e.args)
719 if (find) {
720 const text = e.args.slice(find[0].length).trim()
721 if (text === '') {
722 return { text: 'Usage: /notes find <text>' }
723 }
724 await update($, query, () => text)
725 return {
726 text: asText(await read($, notes), await projectOf($), {
727 search: text,
728 today: localDate(Date.now()),
729 branches: await read($, branches),
730 }),
731 }
732 }
733 const exportArgs = /^\s*export\b(.*)$/i.exec(e.args)
734 if (exportArgs) {
735 const force = /(^|\s)(-f|--force)(\s|$)/.test(exportArgs[1] ?? '')
736 return { text: (await exportNotes($, force)).message }
737 }
738 const importArgs = /^\s*import\b(.*)$/i.exec(e.args)
739 if (importArgs) {
740 const replace = /(^|\s)--replace(\s|$)/.test(importArgs[1] ?? '')
741 return { text: await importNotes($, replace) }
742 }
743 if (/^\s*undo\s*$/i.test(e.args)) {
744 return { text: await undoArchive($) }
745 }
746 if (/^\s*tags\s*$/i.test(e.args)) {
747 const counts = tagCounts(await read($, notes))
748 return {
749 text:
750 counts.length === 0
751 ? 'No tags yet. Add #words to a note, e.g. /note fix login #bug'
752 : `Tags: ${counts.map(([tag, n]) => `#${tag} (${n})`).join(' ')}`,
753 }
754 }
755 const isUp = (await $.ui.panes()).some(pane => pane.id === PANE)
756 if (isUp) {
757 await $.ui.close({ id: PANE })
758 return { text: 'Notepad closed.' }
759 }
760 await refreshBranches($)
761 await openPane($)
762 return { text: 'Notepad opened.' }
763 })
764
765 // /note <text> adds to this project; /note -g <text> adds a global note.
766 on('command.run', { command: 'note' }, async ($, e) => {
767 const { text, where, isLast } = parseNoteArgs(e.args)
768 if (isLast) {
769 return { text: await saveLastReply($, text, where) }
770 }
771 if (text === '') {
772 // A bare /note (or /note -g) opens the multi-line editor on a new note.
773 await update($, scope, () => where)
774 await openEditor($, 'new', '')
775 await openPane($)
776 return { text: 'Multi-line editor opened. Or add a quick note with /note <text> (-g for global).' }
777 }
778 const note = await addNote($, text, 'you', where)
779 return { text: `📝 Noted (${placeName(note)}): ${text}` }
780 })
781
782 // Claude-aware: pinned notes (this project's and global) ride along with every prompt.
783 on('prompt.submit', async ($, e, next) => {
784 // The branch may have changed outside the session since the last prompt.
785 await refreshBranches($)
786 const block = pinnedContext(await read($, pinned), await projectOf($), await read($, branches))
787 // Pinned notes ride along with every prompt: say so once when they grow past the limit.
788 const isHeavy = block !== undefined && tokensOf(block) > PINNED_TOKEN_LIMIT
789 if (isHeavy && !(await read($, isPinnedHeavy))) {
790 $.ui.toast(
791 `📌 Pinned notes add about ${tokenLabel(tokensOf(block))} tokens to every prompt. Unpin what Claude doesn't need each time.`,
792 { timeoutMs: 8000 },
793 )
794 }
795 await update($, isPinnedHeavy, () => isHeavy)
796 if (block === undefined) {
797 return next(e)
798 }
799 return next({ ...e, context: [...(e.context ?? []), block] })
800 })
801
802 // Claude-aware: tools so Claude can write and read notes.
803 on('tool.call', { tool: ADD_TOOL }, async ($, e) => {
804 const input = e as unknown as { text?: unknown; global?: unknown; branch?: unknown }
805 const text = String(input.text ?? '').trim()
806 if (text === '') {
807 return { deny: 'add_note needs non-empty text.' }
808 }
809 const where: Scope = input.global === true ? 'global' : input.branch === true ? 'branch' : 'project'
810 const note = await addNote($, text, 'claude', where)
811 $.ui.toast(`📝 Claude added a ${kindOf(note)} note: ${text.slice(0, 60)}`)
812 const place = isGlobal(note) ? 'global' : note.branch === undefined ? 'project' : `branch ${note.branch}`
813 // Asked for a branch outside one: say where it went instead.
814 const fellBack = where === 'branch' && note.branch === undefined ? '; no git branch is checked out, so it is a project note' : ''
815 return { result: `Added to the notepad (${place}${fellBack}): ${text} (id: ${note.id})` }
816 })
817
818 on('tool.call', { tool: LIST_TOOL }, async ($, e) => {
819 const search = (e as unknown as { query?: unknown }).query
820 return {
821 result: asText(await read($, notes), await projectOf($), {
822 search: typeof search === 'string' ? search : '',
823 withIds: true,
824 today: localDate(Date.now()),
825 branches: await read($, branches),
826 }),
827 }
828 })
829
830 on('tool.call', { tool: COMPLETE_TOOL }, async ($, e) => {
831 const input = e as unknown as { id?: unknown; done?: unknown }
832 const id = String(input.id ?? '').trim()
833 const isDone = input.done !== false
834 const note = await changeNote($, id, found => withDone(found, isDone, Date.now()))
835 if (!note) {
836 return { deny: `No note with id "${id}". list_notes shows each note's id.` }
837 }
838 const what = isDone ? 'done' : 'open again'
839 $.ui.toast(`📝 Claude marked a note ${what}: ${preview(note.text)}`)
840 return { result: `Marked ${what}: ${preview(note.text)}` }
841 })
842
843 on('tool.call', { tool: UPDATE_TOOL }, async ($, e) => {
844 const input = e as unknown as { id?: unknown; text?: unknown }
845 const id = String(input.id ?? '').trim()
846 const text = String(input.text ?? '').trim()
847 if (text === '') {
848 return { deny: 'update_note needs non-empty text.' }
849 }
850 const note = await changeNote($, id, found => tagged({ ...found, text }))
851 if (!note) {
852 return { deny: `No note with id "${id}". list_notes shows each note's id.` }
853 }
854 $.ui.toast(`📝 Claude updated a note: ${preview(note.text)}`)
855 return { result: `Updated the note (id: ${note.id}): ${note.text}` }
856 })
857
858 // The editor surface module posts its text as it changes, and on Ctrl+S.
859 on('ui.message', async ($, e, next) => {
860 if (e.requestId !== PANE || !e.element.startsWith('editor-')) {
861 return next(e)
862 }
863 const data = e.data as { type?: unknown; text?: unknown } | null
864 if (typeof data?.text !== 'string') {
865 return {}
866 }
867 const text = data.text
868 if (data.type === 'draft') {
869 await update($, draft, () => text)
870 } else if (data.type === 'save') {
871 $.ui.toast(await saveEditor($, text))
872 }
873 return {}
874 })
875
876 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
877 const els = $.ui.resolve(e)
878 const { Box, Text, Button } = els
879 const Input = 'Input' in els ? els.Input : undefined
880 // Reading the atom (not just the session) redraws the pane after a directory change.
881 const project = (await read($, folder)) || (await projectOf($))
882 const list = await read($, notes)
883 const known = await read($, branches)
884 // A branch note needs a branch checked out; without one it is the project's.
885 const chosen = await read($, scope)
886 const where = chosen === 'branch' && known.current === null ? 'project' : chosen
887 const placeLabel =
888 where === 'global' ? 'global' : `${baseName(project)}${where === 'branch' ? ` 🌿 ${known.current}` : ''}`
889
890 const session = await read($, editor)
891 if (session) {
892 const Client = 'Client' in els ? els.Client : undefined
893 const isLines = !Client || (await read($, isLineMode))
894 const isNew = session.id === 'new'
895 const heading = isNew ? `✎ New note (${placeLabel})` : '✎ Editing note'
896 const save = async () => $.ui.toast(await saveEditor($))
897
898 // Line mode: the draft as numbered lines, one Input adding or replacing a line.
899 const lineView = async () => {
900 const text = await read($, draft)
901 const all = text === '' ? [] : text.split('\n')
902 const setLines = (fn: (lines: string[]) => string[]) =>
903 update($, draft, current => fn(current === '' ? [] : current.split('\n')).join('\n'))
904 const editLine = (line: number | null) =>
905 update($, editor, current => (current ? { ...current, line } : current))
906 const target = session.line !== null && session.line < all.length ? session.line : null
907 return (
908 <Box flexDirection="column">
909 {all.length === 0 && <Text dimColor>Empty. Type the first line below and press Enter.</Text>}
910 {all.map((line, i) => (
911 <Box key={`line-${i}`} gap={1}>
912 <Text dimColor={target !== null && target !== i} bold={target === i}>
913 {`${String(i + 1).padStart(String(all.length).length)} │ ${line}`}
914 </Text>
915 <Button key={`line-edit-${i}`} plain dimColor onPress={() => editLine(i)}>
916 edit
917 </Button>
918 <Button
919 key={`line-del-${i}`}
920 plain
921 dimColor
922 onPress={async () => {
923 await setLines(lines => lines.filter((_, at) => at !== i))
924 await editLine(null)
925 }}
926 >
927 ×
928 </Button>
929 </Box>
930 ))}
931 {Input && (
932 <Input
933 key={target === null ? `line-add-${all.length}` : `line-set-${target}`}
934 label={target === null ? `${all.length + 1} + ` : `${target + 1} ✎ `}
935 placeholder={target === null ? 'Next line; Enter adds it (empty adds a blank line)' : 'Enter replaces the line; empty deletes it'}
936 value={target === null ? '' : all[target] ?? ''}
937 submitLabel={target === null ? 'add line' : 'replace'}
938 autoFocus
939 onSubmit={async value => {
940 if (target === null) {
941 await setLines(lines => [...lines, value])
942 } else {
943 await setLines(lines =>
944 value === '' ? lines.filter((_, at) => at !== target) : lines.map((l, at) => (at === target ? value : l)),
945 )
946 await editLine(null)
947 }
948 }}
949 />
950 )}
951 {target !== null && (
952 <Button key="line-stop" plain dimColor onPress={() => editLine(null)}>
953 back to adding lines
954 </Button>
955 )}
956 </Box>
957 )
958 }
959
960 return (
961 <Box flexDirection="column">
962 <Text bold>{heading}</Text>
963 {isLines || !Client ? (
964 await lineView()
965 ) : (
966 <Box flexDirection="column">
967 <Client key={`editor-${session.id}`} module="./editor.tsx" props={{ text: session.initial }} />
968 <Text dimColor>
969 Click the box to type · Enter new line · Ctrl+S save · arrows, Home/End, PgUp/PgDn move · Esc leaves the box
970 </Text>
971 </Box>
972 )}
973 <Box marginTop={1} gap={2}>
974 <Button key="editor-save" variant="primary" onPress={save}>
975 Save
976 </Button>
977 <Button key="editor-cancel" role="dismiss" onPress={() => closeEditor($)}>
978 Cancel
979 </Button>
980 {Client && (
981 <Button
982 key="editor-mode"
983 plain
984 dimColor
985 onPress={async () => {
986 const text = await read($, draft)
987 // Back to the full editor: it reopens on the text as it stands now.
988 await update($, editor, current => (current ? { ...current, initial: text, line: null } : current))
989 await update($, isLineMode, value => !value)
990 }}
991 >
992 {isLines ? 'switch to full editor' : 'switch to line editor'}
993 </Button>
994 )}
995 </Box>
996 </Box>
997 )
998 }
999
1000 const undo = await read($, lastArchive)
1001 const undoLine = undo?.isOffered && (
1002 <Box marginTop={1} gap={1}>
1003 <Text dimColor>🗄 Archived: {undo.label}</Text>
1004 <Button key="undo-archive" plain onPress={async () => $.ui.toast(await undoArchive($))}>
1005 undo
1006 </Button>
1007 </Box>
1008 )
1009 // This project's and the global notes, archived ones included.
1010 const scoped = list.filter(note => isGlobal(note) || isHere(note, project))
1011
1012 if (await read($, isArchiveView)) {
1013 const weeks = doneByWeek(scoped)
1014 const shelved = paneOrder(scoped.filter(note => isArchived(note) && !note.isDone))
1015 const archiveRow = (note: Note) => (
1016 <Box key={`arow-${note.id}`} gap={1}>
1017 <Text dimColor={isArchived(note)}>
1018 {`${note.isDone ? '☑' : '☐'} ${preview(note.text)}${isGlobal(note) ? ' (global)' : branchMark(note, project, known)}${isArchived(note) ? ' · archived' : ''}`}
1019 </Text>
1020 {isArchived(note)
1021 ? [
1022 <Button key={`restore-${note.id}`} plain dimColor onPress={() => changeNotes($, [note.id], unarchived)}>
1023 restore
1024 </Button>,
1025 <Button key={`purge-${note.id}`} plain dimColor onPress={() => purgeNote($, note.id)}>
1026 delete for good
1027 </Button>,
1028 ]
1029 : [
1030 <Button
1031 key={`archive-${note.id}`}
1032 plain
1033 dimColor
1034 onPress={() => archiveNotes($, [note.id], preview(note.text))}
1035 >
1036 archive
1037 </Button>,
1038 ]}
1039 </Box>
1040 )
1041 return (
1042 <Box flexDirection="column">
1043 <Box gap={2}>
1044 <Text bold>🗄 Archive: {baseName(project)} and global</Text>
1045 <Button key="archive-back" plain onPress={() => update($, isArchiveView, () => false)}>
1046 ← back to notes
1047 </Button>
1048 </Box>
1049 {undoLine}
1050 {weeks.length === 0 && shelved.length === 0 && <Text dimColor>Nothing done or archived yet.</Text>}
1051 {weeks.map(([week, done]) => (
1052 <Box key={`week-${week ?? 'earlier'}`} flexDirection="column" marginTop={1}>
1053 <Box>
1054 <Text bold>{week === null ? 'Earlier' : `Week of ${week}`}</Text>
1055 <Text dimColor> ({plural(done.length, 'note')} done)</Text>
1056 </Box>
1057 {done.map(archiveRow)}
1058 </Box>
1059 ))}
1060 {shelved.length > 0 && (
1061 <Box marginTop={1}>
1062 <Text bold>Archived, not done</Text>
1063 </Box>
1064 )}
1065 {shelved.map(archiveRow)}
1066 </Box>
1067 )
1068 }
1069
1070 const search = (await read($, query)).trim()
1071 const tag = await read($, activeTag)
1072 const isSearching = search !== '' || tag !== null
1073 const shown = (note: Note) =>
1074 (search === '' || matches(note, search)) && (tag === null || tagsOfNote(note).includes(tag))
1075
1076 // The lists show live notes; archived ones are in the archive view. Other
1077 // branches' notes show only in a search, with the other projects'.
1078 const current = live(list)
1079 const allHere = current.filter(note => isHere(note, project) && !isOffBranch(note, project, known))
1080 const allGlobal = current.filter(isGlobal)
1081 const byDue = await read($, isByDue)
1082 const here = paneOrder(allHere.filter(shown), byDue)
1083 const global = paneOrder(allGlobal.filter(shown), byDue)
1084 // Only while searching: matches from every other project too.
1085 const elsewhere = isSearching
1086 ? paneOrder(
1087 current.filter(
1088 note =>
1089 !isGlobal(note) && (!isHere(note, project) || isOffBranch(note, project, known)) && shown(note),
1090 ),
1091 byDue,
1092 )
1093 : []
1094 // The sort choice shows once a note here or global has a due date (or while sorting by one).
1095 const isDated = byDue || [...allHere, ...allGlobal].some(note => dueOf(note.text) !== undefined)
1096
1097 const submit = async (value: string) => {
1098 const text = value.trim()
1099 if (text !== '') {
1100 await addNote($, text, 'you', where)
1101 }
1102 }
1103
1104 const toggle = (id: string, field: 'isDone' | 'isPinned') =>
1105 changeNote($, id, note =>
1106 field === 'isDone' ? withDone(note, !note.isDone, Date.now()) : { ...note, isPinned: !note.isPinned },
1107 )
1108
1109 // A global note moves to this project; a project note to global (a branch note
1110 // goes back to the whole project first). The change spans both keys.
1111 const move = (moved: Note) => {
1112 const to = isGlobal(moved) ? project : null
1113 return change($, [keyOf(moved), keyOfProject(to)], all =>
1114 all.map(note => (note.id === moved.id ? { ...note, project: to } : note)),
1115 )
1116 }
1117
1118 // A project note moves onto the checked-out branch, a branch note back to the whole project.
1119 const rebranch = (moved: Note) =>
1120 changeNote($, moved.id, note => {
1121 const { branch: _, ...rest } = note
1122 return moved.branch === undefined && known.current !== null ? { ...rest, branch: known.current } : rest
1123 })
1124
1125 const today = localDate(Date.now())
1126
1127 /**
1128 * The note's text with each #tag drawn in its color. A `#due:` date is
1129 * drawn whole: red once overdue, amber on the day.
1130 */
1131 const withTags = (text: string, isDone: boolean) => {
1132 const parts: (string | ReturnType<typeof h>)[] = []
1133 let at = 0
1134 for (const m of text.matchAll(TAG)) {
1135 const start = m.index! + m[1]!.length
1136 if (start > at) parts.push(text.slice(at, start))
1137 const tag = m[2]!.toLowerCase()
1138 let end = m.index! + m[0].length
1139 const date = tag === 'due' ? /^:(\d{4}-\d{2}-\d{2})/.exec(text.slice(end))?.[1] : undefined
1140 if (date) end += date.length + 1
1141 const word = text.slice(start, end)
1142 const color = date && date < today ? '#e01b24' : date === today ? '#e5a50a' : colorOf(tag)
1143 parts.push(isDone ? word : <Text color={color} bold={date !== undefined && date <= today}>{word}</Text>)
1144 at = end
1145 }
1146 if (at < text.length) parts.push(text.slice(at))
1147 return parts
1148 }
1149
1150 // The keys: j and k select a note down the lists, d and p act on it, u and n move it.
1151 const order = [...here, ...global, ...elsewhere]
1152 const pickedId = await read($, selected)
1153 const picked = order.find(note => note.id === pickedId)
1154 const step = (by: -1 | 1) => {
1155 const at = picked ? order.indexOf(picked) : by > 0 ? -1 : order.length
1156 const next = order[Math.min(order.length - 1, Math.max(0, at + by))]
1157 return update($, selected, () => next?.id ?? null)
1158 }
1159 // Only this project's and the global notes move, and not while sorted by due date.
1160 const sectionOf = (note: Note) =>
1161 byDue ? undefined : here.includes(note) ? here : global.includes(note) ? global : undefined
1162 const canMove = (note: Note, by: -1 | 1) => {
1163 const section = sectionOf(note)
1164 return section !== undefined && reorder(section, note.id, by) !== undefined
1165 }
1166 const moveBy = async (note: Note, by: -1 | 1) => {
1167 const section = sectionOf(note)
1168 const ranks = section && reorder(section, note.id, by)
1169 if (!ranks) return
1170 await change($, [keyOf(note)], all =>
1171 all.map(other => (ranks.has(other.id) ? { ...other, order: ranks.get(other.id)! } : other)),
1172 )
1173 }
1174
1175 const row = (note: Note) => (
1176 <Box key={`row-${note.id}`} flexDirection="column" marginTop={1}>
1177 <Text dimColor={note.isDone} strikethrough={note.isDone} bold={note.isPinned || note === picked}>
1178 {note === picked ? '▸ ' : ''}
1179 {note.isDone ? '☑' : '☐'} {note.isPinned ? '📌 ' : ''}
1180 {note.author === 'claude' ? '🤖 ' : ''}
1181 {withTags(note.text, note.isDone)}
1182 {!isGlobal(note) && !isHere(note, project) ? ` (${baseName(note.project ?? '')})` : ''}
1183 {branchMark(note, project, known)}
1184 </Text>
1185 <Box gap={1}>
1186 <Button key={`done-${note.id}`} plain dimColor onPress={() => toggle(note.id, 'isDone')}>
1187 {note.isDone ? 'undo' : 'done'}
1188 </Button>
1189 <Button key={`pin-${note.id}`} plain dimColor onPress={() => toggle(note.id, 'isPinned')}>
1190 {note.isPinned ? 'unpin' : 'pin'}
1191 </Button>
1192 <Button
1193 key={`send-${note.id}`}
1194 plain
1195 dimColor
1196 onPress={() => void $.prompt.fill({ text: note.text, mode: 'insert' })}
1197 >
1198 → prompt
1199 </Button>
1200 <Button key={`edit-${note.id}`} plain dimColor onPress={() => openEditor($, note.id, note.text)}>hooks/notes.ts 772 lines1// The notes logic, with no engine or UI: tags, search, folders, ordering,
2// the text and Markdown formats, and the NOTES.md import merge.
3
4import type { Branches, Note, Scope } from '../types'
5
6/** A tag is `#` then letters, digits, `_` or `-`, at the start or after a space. */
7export const TAG = /(^|\s)#([\p{L}\p{N}_-]+)/gu
8
9/** The note's tags, lowercased, each once, without the `#`. */
10export const tagsOf = (text: string) => [...new Set([...text.matchAll(TAG)].map(m => m[2]!.toLowerCase()))]
11
12/** The note with its tags stored; call it whenever the text is written. */
13export const tagged = (note: Note): Note => ({ ...note, tags: tagsOf(note.text) })
14
15/** The note's stored tags, or its text's for a note saved before tags were stored. */
16export const tagsOfNote = (note: Note) => note.tags ?? tagsOf(note.text)
17
18/** Each tag in `list` with how many notes carry it, most used first. */
19export const tagCounts = (list: readonly Note[]) => {
20 const counts = new Map<string, number>()
21 for (const note of list) {
22 for (const tag of tagsOfNote(note)) counts.set(tag, (counts.get(tag) ?? 0) + 1)
23 }
24 return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
25}
26
27/**
28 * Every word of the query appears in the note, in any order, any case;
29 * a `#word` must be one of the note's tags exactly.
30 */
31export const matches = (note: Note, text: string) => {
32 const haystack = note.text.toLowerCase()
33 const tags = tagsOfNote(note)
34 return text
35 .toLowerCase()
36 .split(/\s+/)
37 .filter(Boolean)
38 .every(word =>
39 word.startsWith('#') && word.length > 1 ? tags.includes(word.slice(1)) : haystack.includes(word),
40 )
41}
42
43export const newId = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`
44
45/** One spelling per folder, so `E:\Code\X` and `e:/code/x/` match. */
46export const normalize = (path: string) => path.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
47
48export const baseName = (path: string) => path.split('/').pop() || path
49
50/**
51 * A repository's identity from its remote URL, the same from every clone and
52 * machine: host and path, lowercased, without scheme, user, port or `.git`.
53 * `git@github.com:o/r.git` and `https://github.com/O/r` are both
54 * `github.com/o/r`. A remote that is a local path is that path, normalized.
55 */
56export const remoteId = (remote: string) => {
57 const url = remote.trim().replace(/\/+$/, '').replace(/\.git$/i, '')
58 // A local path, or a file:// URL of one (file:///e:/x is e:/x).
59 const local = url.replace(/^file:\/\//i, '').replace(/^\/([a-z]:)/i, '$1')
60 if (/^([a-z]:)?[\\/]/i.test(local)) return normalize(local)
61 // scheme://[user@]host[:port]/path
62 const withScheme = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]*@)?([^/:]+)(?::\d+)?(\/.*)?$/i.exec(url)
63 if (withScheme) return `${withScheme[1]}${withScheme[2] ?? ''}`.toLowerCase()
64 // scp-like: [user@]host:path
65 const scp = /^(?:[^@/]+@)?([^:/]+):\/?(.+)$/.exec(url)
66 return (scp ? `${scp[1]}/${scp[2]}` : url).replace(/\\/g, '/').toLowerCase()
67}
68
69export const isGlobal = (note: Note) => note.project == null
70
71export const isHere = (note: Note, project: string) => note.project === project
72
73export const isArchived = (note: Note) => note.archivedAt != null
74
75/** No repository, or no branches read yet: no branch is checked out, and none exists. */
76export const NO_BRANCHES: Branches = { current: null, all: [] }
77
78/** The command whose output `parseBranches` reads. */
79export const BRANCH_COMMAND = ['git', 'branch', '--format=%(HEAD)%(refname:short)'] as const
80
81/**
82 * Reads `git branch --format=%(HEAD)%(refname:short)`: a line per local
83 * branch, the checked-out one starting with `*`. A detached HEAD's line,
84 * `*(HEAD detached at …)`, is no branch, so none is current then.
85 */
86export const parseBranches = (stdout: string): Branches => {
87 let current: string | null = null
88 const all: string[] = []
89 for (const line of stdout.split(/\r?\n/)) {
90 const name = line.slice(1).trim()
91 if (name === '' || name.startsWith('(')) continue
92 all.push(name)
93 if (line.startsWith('*')) current = name
94 }
95 return { current, all }
96}
97
98/** Whether two reads of the branches agree. */
99export const sameBranches = (a: Branches, b: Branches) =>
100 a.current === b.current && a.all.length === b.all.length && a.all.every((name, i) => name === b.all[i])
101
102/**
103 * A note of this project's that belongs to another branch, one that still
104 * exists: left out of the lists, counts, context and export until that branch
105 * is checked out. A search still finds it.
106 */
107export const isOffBranch = (note: Note, project: string, branches: Branches) =>
108 isHere(note, project) &&
109 note.branch !== undefined &&
110 note.branch !== branches.current &&
111 branches.all.includes(note.branch)
112
113/** A branch note whose branch no longer exists (merged and deleted, say): listed with the project's again. */
114export const isBranchGone = (note: Note, branches: Branches) =>
115 note.branch !== undefined && !branches.all.includes(note.branch)
116
117/** The notes this project shows on its current branch: all but the other branches' (see isOffBranch). */
118export const onBranch = (list: readonly Note[], project: string, branches: Branches) =>
119 list.filter(note => !isOffBranch(note, project, branches))
120
121/** ` 🌿 name` for a branch note, with `(gone)` once a branch of this project no longer exists. */
122export const branchMark = (note: Note, project: string, branches: Branches) =>
123 note.branch === undefined
124 ? ''
125 : ` 🌿 ${note.branch}${isHere(note, project) && isBranchGone(note, branches) ? ' (gone)' : ''}`
126
127/** The notes not archived: what every list, count and export shows. */
128export const live = (list: readonly Note[]) => list.filter(note => !isArchived(note))
129
130/** The note marked done or open as of `now`; `doneAt` follows, and stays when nothing changes. */
131export const withDone = (note: Note, isDone: boolean, now: number): Note => {
132 if (note.isDone === isDone) return note
133 const changed: Note = { ...note, isDone }
134 if (isDone) changed.doneAt = now
135 else delete changed.doneAt
136 return changed
137}
138
139/** The note out of the archive. */
140export const unarchived = (note: Note): Note => {
141 const restored = { ...note }
142 delete restored.archivedAt
143 return restored
144}
145
146/** The store key of the global notes; each project's are under `project:` and its folder. */
147export const GLOBAL_KEY = 'global'
148const PROJECT_PREFIX = 'project:'
149/** The old layout: every note under this one key. */
150export const LEGACY_KEY = 'notes'
151/** The store refuses keys over 256 characters: a longer folder is cut here and hashed. */
152const MAX_PATH_IN_KEY = 200
153
154/** FNV-1a over the UTF-16 code units, 32 bits, as 8 hex digits. */
155const fnv = (text: string, seed: number) => {
156 let hash = seed
157 for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) >>> 0
158 return hash.toString(16).padStart(8, '0')
159}
160
161/** The store key of a project's notes (or the global ones, for null). */
162export const keyOfProject = (project: string | null | undefined) =>
163 project == null
164 ? GLOBAL_KEY
165 : project.length <= MAX_PATH_IN_KEY
166 ? `${PROJECT_PREFIX}${project}`
167 : `${PROJECT_PREFIX}${project.slice(0, MAX_PATH_IN_KEY)}…${fnv(project, 0x811c9dc5)}${fnv(project, 0x9e3779b9)}`
168
169export const keyOf = (note: Note) => keyOfProject(note.project)
170
171/** The store key of the project's NOTES.md as last synced (see syncFile): `sync:` and the folder, as keyOfProject spells it. */
172export const keyOfSync = (project: string) => `sync:${keyOfProject(project).slice(PROJECT_PREFIX.length)}`
173
174/** A store key that holds notes in the per-project layout. */
175export const isNotesKey = (key: string) => key === GLOBAL_KEY || key.startsWith(PROJECT_PREFIX)
176
177/**
178 * The file a store key's notes live in, in a notes folder: the key with
179 * anything but letters, digits, `.`, `_` and `-` as `_` (cut to 80
180 * characters), then a hash of the whole key, so two keys never share a file.
181 * `project:github.com/o/r` is `project_github.com_o_r-1a2b3c4d.json`.
182 */
183export const fileNameOf = (key: string) => {
184 const readable = key.replace(/[^\w.-]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 80)
185 return `${readable}-${fnv(key, 0x811c9dc5)}.json`
186}
187
188/**
189 * A notes folder file: its key, then one note per line, so git can merge two
190 * machines' changes to different notes.
191 */
192export const toNotesFile = (key: string, list: readonly Note[]) =>
193 list.length === 0
194 ? `{"key": ${JSON.stringify(key)}, "notes": []}\n`
195 : `{"key": ${JSON.stringify(key)}, "notes": [\n${list.map(note => JSON.stringify(note)).join(',\n')}\n]}\n`
196
197/** A notes folder file's key and notes; throws on a file that is not one (a merge conflict left in it, say). */
198export const parseNotesFile = (text: string) => {
199 const parsed: unknown = JSON.parse(text)
200 const file = parsed as { key?: unknown; notes?: unknown }
201 if (typeof file?.key !== 'string' || !Array.isArray(file.notes)) throw new Error('not a notes file')
202 return { key: file.key, notes: file.notes as Note[] }
203}
204
205/** The notes by store key, each key's in list order. */
206export const groupByKey = (list: readonly Note[]) => {
207 const groups = new Map<string, Note[]>()
208 for (const note of list) {
209 const key = keyOf(note)
210 const group = groups.get(key)
211 if (group) group.push(note)
212 else groups.set(key, [note])
213 }
214 return groups
215}
216
217/**
218 * Folds the old single-key list into the per-key layout. A note already stored
219 * under some key keeps that copy; any other joins the end of its key's list.
220 * Running it again on what it returned changes nothing.
221 */
222export const migrate = (legacy: readonly Note[], stored: ReadonlyMap<string, readonly Note[]>) => {
223 const result = new Map([...stored].map(([key, list]) => [key, [...list]]))
224 const ids = new Set([...stored.values()].flat().map(note => note.id))
225 for (const note of legacy) {
226 if (ids.has(note.id)) continue
227 ids.add(note.id)
228 const key = keyOf(note)
229 result.set(key, [...(result.get(key) ?? []), note])
230 }
231 return result
232}
233
234export const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
235
236/** Continuation lines of a multi-line note, indented to sit under its first line. */
237export const indented = (text: string, by: string) => text.replace(/\n/g, `\n${by}`)
238
239/** A note's first line, cut to fit a toast or a pane line. */
240export const preview = (text: string) => {
241 const first = text.split('\n')[0]!
242 return first.length > 60 ? `${first.slice(0, 59)}…` : first
243}
244
245/**
246 * A due date in a note: `#due:` then YYYY-MM-DD, ending at a space or
247 * punctuation. Its `#due` is an ordinary tag too, so the tag bar finds every
248 * dated note.
249 */
250const DUE = /(?:^|\s)#due:(\d{4})-(\d{2})-(\d{2})(?![\p{L}\p{N}_-])/u
251
252/** The note's due date as YYYY-MM-DD, or undefined when it has none (or not a real date). */
253export const dueOf = (text: string) => {
254 const m = DUE.exec(text)
255 if (!m) return undefined
256 const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])]
257 const date = new Date(Date.UTC(year, month - 1, day))
258 return date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? `${m[1]}-${m[2]}-${m[3]}` : undefined
259}
260
261/** A `path:line` (or `path:line:column`) a note mentions, as written. */
262export type FileLink = { path: string; line: number; column?: number; text: string }
263
264/**
265 * A file reference: a path whose last part has an extension, then `:line`
266 * and maybe `:column`, standing alone (after a space or an opening bracket or
267 * quote, before a space or punctuation). A drive letter is allowed.
268 */
269const LINK = /(^|[\s([`'"])((?:[A-Za-z]:)?[\w.~/\\-]*[\w~]\.[A-Za-z0-9]+):(\d+)(?::(\d+))?(?=$|[\s)\]`'",.;!?])/g
270
271/** The file references in a note's text, in order. */
272export const linksOf = (text: string): FileLink[] =>
273 [...text.matchAll(LINK)].map(m => ({
274 path: m[2]!,
275 line: Number(m[3]),
276 ...(m[4] === undefined ? {} : { column: Number(m[4]) }),
277 text: m[0].slice(m[1]!.length),
278 }))
279
280/** A path from a drive or file system root; a project known by its remote (`github.com/o/r`) is not one. */
281export const isAbsolutePath = (path: string) => /^([A-Za-z]:[\\/]|[\\/])/.test(path)
282
283/** `path` as an absolute path: as it is when absolute, else under `folder`. */
284export const resolvePath = (path: string, folder: string) =>
285 isAbsolutePath(path) ? path : `${folder.replace(/[\\/]+$/, '')}/${path.replace(/^\.[\\/]/, '')}`
286
287/** The editors a link can open in; the mod's `editor` option picks one. */
288export const EDITORS = ['vscode', 'cursor', 'jetbrains'] as const
289export type Editor = (typeof EDITORS)[number]
290
291/** The command that opens `path` at the link's line (and column) in `editor`. */
292export const editorCommand = (editor: Editor, path: string, link: Pick<FileLink, 'line' | 'column'>) => {
293 const at = `${path}:${link.line}${link.column === undefined ? '' : `:${link.column}`}`
294 switch (editor) {
295 case 'vscode':
296 return ['code', '-g', at]
297 case 'cursor':
298 return ['cursor', '-g', at]
299 case 'jetbrains':
300 return [
301 'idea',
302 '--line',
303 String(link.line),
304 ...(link.column === undefined ? [] : ['--column', String(link.column)]),
305 path,
306 ]
307 }
308}
309
310/** The date at `ms` on the local calendar, as YYYY-MM-DD, which compares as text. */
311export const localDate = (ms: number) => {
312 const date = new Date(ms)
313 const pad = (n: number) => String(n).padStart(2, '0')
314 return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
315}
316
317/** The Monday that starts the local week `ms` falls in, as YYYY-MM-DD. */
318export const weekOf = (ms: number) => {
319 const date = new Date(ms)
320 date.setHours(12, 0, 0, 0)
321 date.setDate(date.getDate() - ((date.getDay() + 6) % 7))
322 return localDate(date.getTime())
323}
324
325/**
326 * The done notes by the week they were finished, newest week first and the
327 * latest finished first within it. Notes done before `doneAt` was kept come
328 * last, under a null week.
329 */
330export const doneByWeek = (list: readonly Note[]) => {
331 const groups = new Map<string | null, Note[]>()
332 const done = list.filter(note => note.isDone).sort((a, b) => (b.doneAt ?? 0) - (a.doneAt ?? 0))
333 for (const note of done) {
334 const week = note.doneAt === undefined ? null : weekOf(note.doneAt)
335 groups.set(week, [...(groups.get(week) ?? []), note])
336 }
337 return [...groups].sort(([a], [b]) => (a === null ? 1 : b === null ? -1 : b.localeCompare(a)))
338}
339
340/** This project's and the global open notes due before `today`, earliest first. */
341export const overdue = (list: readonly Note[], project: string, today: string) =>
342 live(list)
343 .filter(note => !note.isDone && (isGlobal(note) || isHere(note, project)))
344 .map(note => ({ note, due: dueOf(note.text) }))
345 .filter((item): item is { note: Note; due: string } => item.due !== undefined && item.due < today)
346 .sort((a, b) => a.due.localeCompare(b.due))
347 .map(item => item.note)
348
349/** The status line: open notes here and global, and how many are overdue when `today` is given. */
350export const statusFor = (list: readonly Note[], project: string, today?: string) => {
351 const open = live(list).filter(note => !note.isDone)
352 const here = open.filter(note => isHere(note, project)).length
353 const global = open.filter(isGlobal).length
354 if (here === 0 && global === 0) return undefined
355 const late = today === undefined ? 0 : overdue(list, project, today).length
356 return `📝 ${here} here · ${global} global${late ? ` · ⏰ ${late} overdue` : ''}`
357}
358
359/** Earliest due date first, notes with none after. */
360const byDue = (a: Note, b: Note) => {
361 const [first, second] = [dueOf(a.text), dueOf(b.text)]
362 if (first === second) return 0
363 if (first === undefined) return 1
364 if (second === undefined) return -1
365 return first.localeCompare(second)
366}
367
368/** A note's place among notes alike: where it was moved to, else when it was made. */
369export const rankOf = (note: Note) => note.order ?? note.createdAt
370
371/**
372 * The pane's order: pinned first, then open before done, then each note's
373 * place (see rankOf). With `isByDue`, earliest due date before place, and
374 * notes with none last.
375 */
376export const paneOrder = (list: readonly Note[], isByDue = false) =>
377 [...list].sort(
378 (a, b) =>
379 Number(b.isPinned) - Number(a.isPinned) ||
380 Number(a.isDone) - Number(b.isDone) ||
381 (isByDue ? byDue(a, b) : 0) ||
382 rankOf(a) - rankOf(b),
383 )
384
385/** The export's order: open before done, then pinned first, then each note's place. */
386export const exportOrder = (list: readonly Note[]) =>
387 [...list].sort(
388 (a, b) =>
389 Number(a.isDone) - Number(b.isDone) ||
390 Number(b.isPinned) - Number(a.isPinned) ||
391 rankOf(a) - rankOf(b),
392 )
393
394/**
395 * Moving the note `id` one place up (`by` -1) or down (+1) in `shown`, a list
396 * in pane order: the new `order` of each note that changes, by id. It swaps
397 * places with its neighbor, which must be alike (both pinned or not, both done
398 * or not), since the pane keeps those apart; else undefined, as at either end.
399 */
400export const reorder = (shown: readonly Note[], id: string, by: -1 | 1) => {
401 const at = shown.findIndex(note => note.id === id)
402 const note = shown[at]
403 const other = shown[at + by]
404 if (!note || !other || other.isPinned !== note.isPinned || other.isDone !== note.isDone) return undefined
405 const [mine, theirs] = [rankOf(note), rankOf(other)]
406 // Two notes made in the same millisecond share a place: step past it instead.
407 return mine === theirs
408 ? new Map([[note.id, theirs + by]])
409 : new Map([
410 [note.id, theirs],
411 [other.id, mine],
412 ])
413}
414
415const NOTE_FLAG = /^\s*(-g|--global|-b|--branch|--last)(?=\s|$)/
416
417/**
418 * `/note [-g | --global | -b | --branch] [--last] [text]`, flags in any order
419 * before the text: -g makes a global note, -b a note of the current branch
420 * (the later of the two wins), --last saves Claude's last reply (with the
421 * text, if any, as its first line).
422 */
423export const parseNoteArgs = (args: string): { text: string; where: Scope; isLast: boolean } => {
424 let rest = args
425 let where: Scope = 'project'
426 let isLast = false
427 for (let flag = NOTE_FLAG.exec(rest); flag; flag = NOTE_FLAG.exec(rest)) {
428 if (flag[1] === '--last') isLast = true
429 else where = flag[1] === '-b' || flag[1] === '--branch' ? 'branch' : 'global'
430 rest = rest.slice(flag[0].length)
431 }
432 return { text: rest.trim(), where, isLast }
433}
434
435/** ` (overdue)` or ` (due today)` for an open note, measured against `today`; else nothing. */
436const dueMark = (note: Note, today: string | undefined) => {
437 const due = today === undefined || note.isDone ? undefined : dueOf(note.text)
438 return due === undefined || due > today! ? '' : due === today ? ' (due today)' : ' (overdue)'
439}
440
441export type TextOptions = {
442 /** Words to search every note for; empty lists this project's and the global notes. */
443 search?: string
444 /** Ends each note's line with its id, which complete_note and update_note take (for Claude's tools). */
445 withIds?: boolean
446 /**
447 * The local date, YYYY-MM-DD: marks open notes overdue or due today and,
448 * when a listed note has a due date, ends the text with it, so a reader
449 * without a calendar can still judge the others.
450 */
451 today?: string
452 /** The project's branches: which notes the listing leaves out, and which branches are gone. */
453 branches?: Branches
454}
455
456/**
457 * The notes as /notes find and list_notes give them: this project's (those
458 * of other branches left out) and global, or a search over all.
459 */
460export const asText = (all: readonly Note[], project: string, options: TextOptions = {}) => {
461 const { search = '', withIds = false, today, branches = NO_BRANCHES } = options
462 const list = live(all)
463 // One line per note (more for a multi-line one), with its marks.
464 const lines = (shown: readonly Note[]) =>
465 shown
466 .map(
467 note =>
468 `- [${note.isDone ? 'x' : ' '}]${note.isPinned ? ' (pinned)' : ''} ${indented(note.text, ' ')}` +
469 dueMark(note, today) +
470 (note.branch === undefined
471 ? ''
472 : ` (branch ${note.branch}${isHere(note, project) && isBranchGone(note, branches) ? ', since deleted' : ''})`) +
473 (withIds ? ` (id: ${note.id})` : ''),
474 )
475 .join('\n')
476 const dated = (shown: readonly Note[]) =>
477 today !== undefined && shown.some(note => dueOf(note.text) !== undefined) ? ['', `Today is ${today}.`] : []
478 if (search.trim() !== '') {
479 // Oldest first, whatever order the store keys hold the projects in.
480 const found = list.filter(note => matches(note, search)).sort((a, b) => a.createdAt - b.createdAt)
481 return found.length === 0
482 ? `No notes match "${search.trim()}".`
483 : [
484 `${plural(found.length, 'note')} matching "${search.trim()}":`,
485 ...found.map(note => {
486 const where = isGlobal(note) ? 'global' : isHere(note, project) ? 'this project' : baseName(note.project ?? '')
487 return `${lines([note])} (${where})`
488 }),
489 ...dated(found),
490 ].join('\n')
491 }
492 const here = onBranch(list, project, branches).filter(note => isHere(note, project))
493 const global = list.filter(isGlobal)
494 return [
495 `Notes for this project (${baseName(project)}${branches.current === null ? '' : `, on branch ${branches.current}`}):`,
496 here.length ? lines(here) : '(none)',
497 '',
498 'Global notes:',
499 global.length ? lines(global) : '(none)',
500 '',
501 `Tags in use: ${tagCounts(list).map(([tag, n]) => `#${tag} (${n})`).join(', ') || '(none)'}`,
502 ...dated([...here, ...global]),
503 ].join('\n')
504}
505
506export const EXPORT_FILE = 'NOTES.md'
507/** First line of every export, so a later export knows the file is ours to replace. */
508export const EXPORT_MARK = '<!-- exported by the claudepad mod for Claude Code; re-exporting replaces this file -->'
509
510/** A heading that starts with this holds a branch's notes: `## 🌿 name`. */
511const BRANCH_MARK = '🌿'
512
513/**
514 * This project's and the global notes as a NOTES.md, dated `now`. The notes
515 * of the current branch, and of any branch since deleted, each get a section
516 * of their own; other branches' notes are left out.
517 */
518export const toMarkdown = (all: readonly Note[], project: string, now = Date.now(), branches = NO_BRANCHES) => {
519 const list = onBranch(live(all), project, branches)
520 // A multi-line note: its first line on the checkbox, the rest indented two
521 // spaces beneath (a blank line inside it as two spaces, so it stays inside).
522 const item = (note: Note) => {
523 const [first = '', ...rest] = note.text.split('\n')
524 return [
525 `- [${note.isDone ? 'x' : ' '}] ${note.isPinned ? '📌 ' : ''}${first}` +
526 (note.author === 'claude' ? ' _(added by Claude)_' : ''),
527 ...rest.map(line => ` ${line}`),
528 ].join('\n')
529 }
530 const section = (title: string, subset: Note[]) => [
531 `## ${title}`,
532 '',
533 ...(subset.length ? exportOrder(subset).map(item) : ['_No notes._']),
534 '',
535 ]
536 const here = list.filter(note => isHere(note, project))
537 const global = list.filter(isGlobal)
538 const tags = tagCounts([...here, ...global])
539 // The current branch first, then any gone ones by name.
540 const named = [...new Set(here.flatMap(note => (note.branch === undefined ? [] : [note.branch])))].sort(
541 (a, b) => Number(b === branches.current) - Number(a === branches.current) || a.localeCompare(b),
542 )
543 return [
544 EXPORT_MARK,
545 `# Notes: ${baseName(project)}`,
546 '',
547 `_Exported ${new Date(now).toISOString().slice(0, 10)}. ${plural(here.length, 'project note')}, ${plural(global.length, 'global note')}._`,
548 '',
549 ...section(baseName(project), here.filter(note => note.branch === undefined)),
550 ...named.flatMap(name => section(`${BRANCH_MARK} ${name}`, here.filter(note => note.branch === name))),
551 ...section('Global', global),
552 ...(tags.length ? ['## Tags', '', tags.map(([tag, n]) => `\`#${tag}\` (${n})`).join(' · '), ''] : []),
553 ].join('\n')
554}
555
556export type ParsedNote = Pick<Note, 'text' | 'isDone' | 'isPinned' | 'author' | 'branch'> & {
557 where: 'project' | 'global'
558}
559
560/**
561 * Reads the notes out of a NOTES.md: every `- [ ]`/`- [x]` checkbox and every
562 * plain `-`/`*` bullet. Items under a `## Global` heading are global, under a
563 * `## 🌿 name` heading the project's on that branch, all others the
564 * project's; a `## Tags` section is skipped. Understands the export's 📌 and
565 * "(added by Claude)" marks, and any hand-written list.
566 */
567export const parseMarkdown = (markdown: string): ParsedNote[] => {
568 const found: ParsedNote[] = []
569 let where: ParsedNote['where'] = 'project'
570 let branch: string | undefined
571 let isSkipped = false
572 // The item an indented, non-bullet line continues (a multi-line note).
573 let current: ParsedNote | null = null
574 for (const raw of markdown.split(/\r?\n/)) {
575 const heading = /^#{2,6}\s+(.*)$/.exec(raw)
576 if (heading) {
577 const text = heading[1]!.trim()
578 const title = text.toLowerCase().replace(/^[^\p{L}\p{N}]+/u, '')
579 isSkipped = title === 'tags'
580 where = title === 'global' ? 'global' : 'project'
581 branch = text.startsWith(BRANCH_MARK) ? text.slice(BRANCH_MARK.length).trim() || undefined : undefined
582 current = null
583 continue
584 }
585 if (isSkipped) continue
586 const item = /^\s*[-*+]\s+(?:\[([ xX])\]\s+)?(.*\S)\s*$/.exec(raw)
587 if (!item) {
588 if (current && /^\s/.test(raw)) {
589 current.text += `\n${raw.replace(/^ {1,2}/, '').trimEnd()}`
590 } else {
591 current = null
592 }
593 continue
594 }
595 let text = item[2]!
596 const isPinned = text.startsWith('📌')
597 if (isPinned) text = text.replace(/^📌\s*/u, '')
598 const byClaude = /\s*_\(added by Claude\)_$/.exec(text)
599 if (byClaude) text = text.slice(0, byClaude.index)
600 text = text.trim()
601 if (text === '') {
602 current = null
603 continue
604 }
605 current = {
606 text,
607 isDone: item[1] === 'x' || item[1] === 'X',
608 isPinned,
609 author: byClaude ? 'claude' : 'you',
610 where,
611 ...(branch === undefined ? {} : { branch }),
612 }
613 found.push(current)
614 }
615 return found.map(note => ({ ...note, text: note.text.trimEnd() }))
616}
617
618/** Text as import compares it, so spacing and case changes still match a note. */
619const looseText = (text: string) => text.replace(/\s+/g, ' ').trim().toLowerCase()
620
621/** A note's scope, branch and loose text, as one key; neither loose text nor a branch name holds a newline. */
622const importKey = (where: ParsedNote['where'], branch: string | undefined, text: string) =>
623 `${where}\n${branch ?? ''}\n${looseText(text)}`
624
625/**
626 * The notes after importing `parsed` into `project`. By default it merges: a
627 * note already here (same text, scope and branch) takes the file's done and
628 * pinned marks, a new one is added, and nothing is deleted. With `replace`,
629 * this project's and the global notes become exactly the file's, except the
630 * notes of other branches (see isOffBranch), which the file cannot hold. New
631 * notes are dated from `now`, one millisecond apart, in the file's order.
632 */
633export const mergeImport = (
634 all: readonly Note[],
635 parsed: readonly ParsedNote[],
636 project: string,
637 replace: boolean,
638 now: number,
639 branches = NO_BRANCHES,
640) => {
641 const kept = replace
642 ? all.filter(note => !(isGlobal(note) || isHere(note, project)) || isOffBranch(note, project, branches))
643 : all
644 const list = [...kept]
645 // Where each of this project's and the global notes stands, by key; the
646 // first of two alike wins. A note the file adds joins it, so a line the
647 // file repeats matches that note.
648 const at = new Map<string, number>()
649 list.forEach((note, i) => {
650 const where = isGlobal(note) ? 'global' : isHere(note, project) ? 'project' : null
651 const key = where && importKey(where, note.branch, note.text)
652 if (key && !at.has(key)) at.set(key, i)
653 })
654 let added = 0
655 let updated = 0
656 parsed.forEach((item, i) => {
657 const key = importKey(item.where, item.where === 'global' ? undefined : item.branch, item.text)
658 const index = replace ? undefined : at.get(key)
659 const match = index === undefined ? undefined : list[index]
660 if (index !== undefined && match) {
661 // An archived note stays archived: an old file must not bring it back.
662 if (!isArchived(match) && (match.isDone !== item.isDone || match.isPinned !== item.isPinned)) {
663 list[index] = { ...withDone(match, item.isDone, now), isPinned: item.isPinned }
664 updated += 1
665 }
666 return
667 }
668 at.set(key, list.length)
669 list.push(
670 tagged({
671 id: newId(),
672 text: item.text,
673 isDone: item.isDone,
674 ...(item.isDone ? { doneAt: now } : {}),
675 isPinned: item.isPinned,
676 author: item.author,
677 createdAt: now + i,
678 project: item.where === 'global' ? null : project,
679 ...(item.where === 'global' || item.branch === undefined ? {} : { branch: item.branch }),
680 }),
681 )
682 added += 1
683 })
684 return { list, added, updated, removed: all.length - kept.length }
685}
686
687/** A file line's match key, as the import compares it. */
688const parsedKey = (item: ParsedNote) =>
689 importKey(item.where, item.where === 'global' ? undefined : item.branch, item.text)
690
691/** A note's match key when it is this project's or global; undefined for another project's. */
692const noteKey = (note: Note, project: string) =>
693 isGlobal(note)
694 ? importKey('global', undefined, note.text)
695 : isHere(note, project)
696 ? importKey('project', note.branch, note.text)
697 : undefined
698
699/**
700 * An outside edit of the exported NOTES.md, from `before` (the file as last
701 * synced) to `after`. Only what the edit changed applies, so a line left as
702 * it was never undoes a change made in the notepad since: a line new to the
703 * file adds a note, or brings back the archived note it matches; a line whose
704 * done or pinned mark changed passes it on, as an import merges it; and a
705 * line gone from the file archives its note. The archive is left to the
706 * caller, which offers undo: `archive` names the notes. Only this project's
707 * notes (those of other branches never match) and the global ones are touched.
708 */
709export const syncFile = (
710 all: readonly Note[],
711 before: readonly ParsedNote[],
712 after: readonly ParsedNote[],
713 project: string,
714 now: number,
715 branches = NO_BRANCHES,
716) => {
717 // Each line's marks as last synced, by key; the first of two alike.
718 const marks = new Map<string, string>()
719 for (const item of before) {
720 if (!marks.has(parsedKey(item))) marks.set(parsedKey(item), `${item.isDone} ${item.isPinned}`)
721 }
722 const was = new Set(marks.keys())
723 const is = new Set(after.map(parsedKey))
724 const changed = after.filter(item => marks.get(parsedKey(item)) !== `${item.isDone} ${item.isPinned}`)
725 // A line put back in the file restores the note it archived, the first of two alike.
726 const back = new Set<string>()
727 const list = all.map(note => {
728 const key = noteKey(note, project)
729 if (!isArchived(note) || key === undefined || !is.has(key) || was.has(key) || back.has(key)) return note
730 back.add(key)
731 return unarchived(note)
732 })
733 const merged = mergeImport(list, changed, project, false, now, branches)
734 const archive = merged.list
735 .filter(note => {
736 const key = noteKey(note, project)
737 return !isArchived(note) && key !== undefined && was.has(key) && !is.has(key)
738 })
739 .map(note => note.id)
740 return { list: merged.list, added: merged.added, updated: merged.updated, restored: back.size, archive }
741}
742
743/** About how many tokens `text` takes in a prompt: one per four characters, as a rule of thumb. */
744export const tokensOf = (text: string) => Math.ceil(text.length / 4)
745
746/** Past this many tokens, pinned notes get a warning: they ride along with every prompt. */
747export const PINNED_TOKEN_LIMIT = 1000
748
749/** A token count as a warning says it: `850`, `1.2k`. */
750export const tokenLabel = (n: number) => (n < 1000 ? String(n) : `${(n / 1000).toFixed(1)}k`)
751
752/**
753 * What every prompt carries of the pinned notes: the open pinned ones of this
754 * project (other branches' left out) and global ones; undefined with none.
755 */
756export const pinnedContext = (list: readonly Note[], project: string, branches = NO_BRANCHES) => {
757 const shown = live(list).filter(
758 note =>
759 note.isPinned &&
760 !note.isDone &&
761 (isGlobal(note) || isHere(note, project)) &&
762 !isOffBranch(note, project, branches),
763 )
764 if (shown.length === 0) return undefined
765 const where = (note: Note) =>
766 isGlobal(note) ? '' : note.branch === undefined ? ' (this project)' : ` (this project, branch ${note.branch})`
767 return (
768 "The user's pinned notes from their notepad (standing context; keep them in mind):\n" +
769 shown.map(note => `- ${indented(note.text, ' ')}${where(note)}`).join('\n')
770 )
771}
772hooks/editor.tsx 165 lines1// The notepad's multi-line editor: a surface module drawn by a `Client` in
2// the pane. It runs on the drawing side, keeps the text and cursor in its
3// own local state, and posts to the hooks module: `{ type: 'draft', text }`
4// on every change, `{ type: 'save', text }` on Ctrl+S.
5import type { ClientKeyEvent, ClientModule } from 'claude-code'
6
7type Props = { text: string }
8type State = { lines: string[]; row: number; col: number }
9
10/** Lines drawn at once; the window follows the cursor. */
11const WINDOW = 14
12
13/** Key names that are never typed text. */
14const SPECIAL = new Set([
15 'up', 'down', 'left', 'right', 'return', 'enter', 'tab', 'backspace', 'delete',
16 'pageup', 'pagedown', 'home', 'end', 'escape', 'insert',
17])
18
19const fromText = (text: string): State => {
20 const lines = text.split('\n')
21 const row = lines.length - 1
22 return { lines, row, col: lines[row]!.length }
23}
24
25const toText = (state: State) => state.lines.join('\n')
26
27const insert = (state: State, typed: string): State => {
28 const pieces = typed.replace(/\r\n?/g, '\n').split('\n')
29 const line = state.lines[state.row]!
30 const before = line.slice(0, state.col)
31 const after = line.slice(state.col)
32 const last = pieces.length - 1
33 const added = pieces.map((piece, i) =>
34 (i === 0 ? before : '') + piece + (i === last ? after : ''),
35 )
36 const lines = [...state.lines.slice(0, state.row), ...added, ...state.lines.slice(state.row + 1)]
37 const row = state.row + last
38 const col = (last === 0 ? before.length : 0) + pieces[last]!.length
39 return { lines, row, col }
40}
41
42/** The next state for one key, or 'save', or the same state when nothing changes. */
43const apply = (state: State, event: ClientKeyEvent): State | 'save' => {
44 const { lines, row, col } = state
45 const line = lines[row]!
46 const key = event.key
47
48 if (event.ctrl && key.toLowerCase() === 's') return 'save'
49
50 switch (key) {
51 case 'return':
52 case 'enter':
53 return insert(state, '\n')
54 case 'tab':
55 return insert(state, ' ')
56 case 'backspace':
57 if (col > 0) {
58 const next = [...lines]
59 next[row] = line.slice(0, col - 1) + line.slice(col)
60 return { lines: next, row, col: col - 1 }
61 }
62 if (row > 0) {
63 const above = lines[row - 1]!
64 const next = [...lines.slice(0, row - 1), above + line, ...lines.slice(row + 1)]
65 return { lines: next, row: row - 1, col: above.length }
66 }
67 return state
68 case 'delete':
69 if (col < line.length) {
70 const next = [...lines]
71 next[row] = line.slice(0, col) + line.slice(col + 1)
72 return { lines: next, row, col }
73 }
74 if (row < lines.length - 1) {
75 const next = [...lines.slice(0, row), line + lines[row + 1]!, ...lines.slice(row + 2)]
76 return { lines: next, row, col }
77 }
78 return state
79 case 'left':
80 if (col > 0) return { lines, row, col: col - 1 }
81 if (row > 0) return { lines, row: row - 1, col: lines[row - 1]!.length }
82 return state
83 case 'right':
84 if (col < line.length) return { lines, row, col: col + 1 }
85 if (row < lines.length - 1) return { lines, row: row + 1, col: 0 }
86 return state
87 case 'up':
88 if (row === 0) return { lines, row, col: 0 }
89 return { lines, row: row - 1, col: Math.min(col, lines[row - 1]!.length) }
90 case 'down':
91 if (row === lines.length - 1) return { lines, row, col: line.length }
92 return { lines, row: row + 1, col: Math.min(col, lines[row + 1]!.length) }
93 case 'pageup': {
94 const to = Math.max(0, row - WINDOW)
95 return { lines, row: to, col: Math.min(col, lines[to]!.length) }
96 }
97 case 'pagedown': {
98 const to = Math.min(lines.length - 1, row + WINDOW)
99 return { lines, row: to, col: Math.min(col, lines[to]!.length) }
100 }
101 case 'home':
102 return { lines, row, col: 0 }
103 case 'end':
104 return { lines, row, col: line.length }
105 }
106
107 // Anything else that isn't a named key is text: one character, or a paste.
108 if (event.ctrl || event.meta || SPECIAL.has(key) || key === '') return state
109 return insert(state, key)
110}
111
112const Editor: ClientModule<Props, State> = (props, surface) => {
113 const { Box, Text } = surface.elements
114 const state = surface.state ?? fromText(props.text)
115
116 surface.onKey(event => {
117 const current = surface.state ?? fromText(props.text)
118 const next = apply(current, event)
119 if (next === 'save') {
120 surface.post({ type: 'save', text: toText(current) })
121 return
122 }
123 if (next !== current) {
124 surface.setState(next)
125 surface.post({ type: 'draft', text: toText(next) })
126 }
127 })
128
129 const start = Math.max(0, Math.min(state.row - Math.floor(WINDOW / 2), state.lines.length - WINDOW))
130 const shown = state.lines.slice(start, start + WINDOW)
131 const gutter = String(state.lines.length).length
132
133 return (
134 <Box flexDirection="column" borderStyle="round" paddingX={1}>
135 {start > 0 && <Text dimColor>{` ↑ ${start} more`}</Text>}
136 {shown.map((line, i) => {
137 const row = start + i
138 const number = <Text dimColor>{`${String(row + 1).padStart(gutter)} │ `}</Text>
139 if (row !== state.row) {
140 return (
141 <Text>
142 {number}
143 {line}
144 </Text>
145 )
146 }
147 const at = line[state.col] ?? ' '
148 return (
149 <Text>
150 {number}
151 {line.slice(0, state.col)}
152 <Text inverse>{at}</Text>
153 {line.slice(state.col + 1)}
154 </Text>
155 )
156 })}
157 {start + WINDOW < state.lines.length && (
158 <Text dimColor>{` ↓ ${state.lines.length - start - WINDOW} more`}</Text>
159 )}
160 </Box>
161 )
162}
163
164export default Editor
165types/index.d.ts 106 lines1export type Note = {
2 id: string
3 /** The note; may span several lines. */
4 text: string
5 isDone: boolean
6 /** When it was last marked done; notes done before this was kept have none. */
7 doneAt?: number
8 isPinned: boolean
9 /**
10 * When it was archived: hidden from the lists, the status line, pinned
11 * context and export, and shown in the pane's archive view until restored
12 * or deleted for good.
13 */
14 archivedAt?: number
15 /** Who wrote it: the person, or Claude through the add_note tool. */
16 author: 'you' | 'claude'
17 createdAt: number
18 /**
19 * Its place among notes alike (pinned or not, done or not) once moved up or
20 * down in the pane; until then its `createdAt` is its place.
21 */
22 order?: number
23 /**
24 * The note's tags, lowercased, without the `#`, stored whenever its text is
25 * written. Notes saved before tags were stored have none until loaded.
26 */
27 tags?: string[]
28 /**
29 * The project folder the note belongs to (normalized path), or null for a
30 * global note. Notes saved before projects existed have none: global.
31 */
32 project?: string | null
33 /**
34 * The git branch the note belongs to, within its project: listed only while
35 * that branch is checked out, or once it no longer exists. None for a note
36 * of the whole project, and always none for a global note.
37 */
38 branch?: string
39}
40
41/** Where the pane's input adds new notes: the current branch, the project, or global. */
42export type Scope = 'branch' | 'project' | 'global'
43
44/** The project's git branches, as last read: the checked-out one (null when none is) and every local one. */
45export type Branches = { current: string | null; all: string[] }
46
47/** The session folder's NOTES.md as the last poll saw it: whose folder, and its modification time. */
48export type FileSeen = { project: string; mtimeMs: number }
49
50/** The multi-line editor while it is open. */
51export type EditorSession = {
52 /** The note being edited, or 'new' for a note not saved yet. */
53 id: string
54 /** The text the editor opened with. */
55 initial: string
56 /** Line mode only: the line the input edits, or null to add a line. */
57 line: number | null
58}
59
60/** The last archive (one note, or every one `clear done` swept), kept for undo. */
61export type ArchiveUndo = {
62 /** This archive's own id: the same note archived again is a new archive. */
63 id: string
64 /** The notes it archived. */
65 noteIds: string[]
66 /** What it archived, as the pane and the toasts say it. */
67 label: string
68 /** While the pane shows its undo button (a few seconds after the archive). */
69 isOffered: boolean
70}
71
72declare module 'claude-code' {
73 interface PluginState {
74 claudepad: {
75 notes: Note[]
76 /** The open multi-line editor, or null. */
77 editor: EditorSession | null
78 /** The editor's current text, kept as it is typed. */
79 draft: string
80 /** Use the line-by-line editor even where the full editor can draw. */
81 isLineMode: boolean
82 /** The session's folder, normalized; empty before session.start. */
83 folder: string
84 scope: Scope
85 /** The pane's search text; empty shows every note. */
86 query: string
87 /** The tag the pane filters on (lowercase, no `#`), or null for all. */
88 tag: string | null
89 /** The last archive, until it is undone or another one replaces it. */
90 lastArchive: ArchiveUndo | null
91 /** The pane shows the archive view (done notes by week, archived notes). */
92 isArchiveView: boolean
93 /** The pane lists notes by due date (earliest first) instead of by when they were added. */
94 isByDue: boolean
95 /** The session folder's git branches, read again whenever they may have changed. */
96 branches: Branches
97 /** NOTES.md as the last poll saw it, so an unchanged file is not read again. */
98 fileSeen: FileSeen | null
99 /** The pinned notes were over the context limit at the last prompt, so the warning is not repeated. */
100 isPinnedHeavy: boolean
101 /** The note the pane's keys act on (j/k move it), or null for none. */
102 selected: string | null
103 }
104 }
105}
106