▍ humdrum codex / glint v1.0.2
license AGPL-3.0
15.5 KB raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Package app is glint's top-level Bubbletea model. It owns the active mode and
// routes messages to the editor, picker, or preview sub-models.
package app

import (
	"fmt"
	"math"
	"os"
	"path/filepath"
	"strings"
	"time"

	"glint/internal/config"
	"glint/internal/editor"
	"glint/internal/picker"
	"glint/internal/preview"
	"glint/internal/theme"

	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

// Mode selects which sub-view is active.
type Mode int

const (
	ModeEditor Mode = iota
	ModePicker
	ModePreview
	ModeSaveAs
)

// pendingDiscard tracks which open-while-dirty action is awaiting confirmation.
type pendingDiscard int

const (
	discardNone pendingDiscard = iota
	discardPicker
	discardDaily
	discardNew
)

// Canvas layout: a centered, percentage-width text column with a little top air.
const (
	canvasRatio  = 0.75
	canvasMax    = 120
	canvasMin    = 24
	canvasTopPad = 3
)

// App is the root model.
type App struct {
	mode       Mode
	cfg        config.Config
	theme      theme.Theme
	editor     *editor.Editor
	preview    *preview.Model
	picker     *picker.Model
	saveInput  textinput.Model // one-line "save as" prompt for unnamed buffers
	path       string
	pickerRoot string // directory the current picker is browsing
	saveDir    string // where an unnamed buffer's save-as lands ("" → inbox)
	status     string
	width      int
	height     int

	quitArmed bool           // true after a dirty Ctrl+Q, awaiting confirm
	pending   pendingDiscard // armed open-while-dirty confirmation
}

// New builds an App with an empty editor.
func New(cfg config.Config) *App {
	th := theme.Resolve(cfg.Theme)
	ed := editor.New()
	ed.SetTheme(th)
	ti := textinput.New()
	ti.Prompt = "save as › "
	ti.Placeholder = "name…"
	a := &App{
		mode:      ModeEditor,
		cfg:       cfg,
		theme:     th,
		editor:    ed,
		saveInput: ti,
	}
	a.preview = preview.New(a.glamourStyle())
	a.preview.SetBackground(string(th.Background))
	return a
}

// Load reads a file into the editor and switches to edit mode.
func (a *App) Load(path string) error {
	data, err := os.ReadFile(path)
	if err != nil {
		return err
	}
	a.editor.SetContent(data)
	a.path = path
	a.mode = ModeEditor
	a.status = path
	return nil
}

// Start picks the initial view: an explicit path, today's daily note, or the
// picker when neither is given.
func (a *App) Start(path string, daily bool) error {
	switch {
	case path != "":
		return a.Load(path)
	case daily:
		_, cmd := a.openDaily()
		_ = cmd
		return nil
	default:
		_, cmd := a.openPicker()
		_ = cmd
		return nil
	}
}

func (a *App) Init() tea.Cmd { return nil }

// Update routes messages. Global keys are handled first, then mode-specific.
func (a *App) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		a.setSize(msg.Width, msg.Height)
		return a, nil
	case tea.KeyMsg:
		return a.handleKey(msg)
	case tea.MouseMsg:
		return a.handleMouse(msg)
	}
	return a, nil
}

// handleMouse moves the cursor on a left click and scrolls on wheel events.
func (a *App) handleMouse(msg tea.MouseMsg) (tea.Model, tea.Cmd) {
	const step = 3
	if msg.Button == tea.MouseButtonLeft {
		if msg.Action == tea.MouseActionPress && a.mode == ModeEditor {
			// The first editor visual row sits at screen row topPad; a click at
			// screen row Y is that many rows into the viewport.
			vi := a.editor.Scroll + msg.Y - a.topPad() + 1
			col := msg.X - a.leftMargin()
			a.editor.MoveToVisual(vi, col)
		}
		return a, nil
	}
	var delta int
	switch msg.Button {
	case tea.MouseButtonWheelUp:
		delta = -step
	case tea.MouseButtonWheelDown:
		delta = step
	default:
		return a, nil
	}
	switch a.mode {
	case ModePreview:
		return a, a.preview.Update(msg) // the viewport handles wheel scrolling
	case ModePicker:
		key := tea.KeyMsg{Type: tea.KeyDown}
		if delta < 0 {
			key.Type = tea.KeyUp
		}
		for i := 0; i < step; i++ {
			a.picker.Update(key)
		}
	default: // editor / save-as
		a.editor.ScrollBy(delta)
	}
	return a, nil
}

func (a *App) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	// Any key other than a second Ctrl+Q disarms the quit confirmation.
	if msg.Type != tea.KeyCtrlQ {
		a.quitArmed = false
	}
	// Disarm pending-discard unless the same action is being re-pressed.
	repressed := (msg.Type == tea.KeyCtrlF && a.pending == discardPicker) ||
		(msg.Type == tea.KeyCtrlD && a.pending == discardDaily) ||
		(msg.Type == tea.KeyCtrlN && a.pending == discardNew)
	if !repressed {
		a.pending = discardNone
	}

	switch msg.Type {
	case tea.KeyCtrlQ:
		if a.editor.Dirty && !a.quitArmed {
			a.quitArmed = true
			a.status = "Unsaved changes — Ctrl+Q again to quit"
			return a, nil
		}
		return a, tea.Quit
	case tea.KeyCtrlS:
		return a.save()
	case tea.KeyCtrlP:
		return a.togglePreview()
	case tea.KeyCtrlT:
		return a.cycleTheme()
	case tea.KeyCtrlF:
		if a.editor.Dirty && a.pending != discardPicker {
			a.pending = discardPicker
			a.status = "Unsaved changes — Ctrl+F again to discard"
			return a, nil
		}
		a.pending = discardNone
		return a.openPicker()
	case tea.KeyCtrlD:
		if a.editor.Dirty && a.pending != discardDaily {
			a.pending = discardDaily
			a.status = "Unsaved changes — Ctrl+D again to discard"
			return a, nil
		}
		a.pending = discardNone
		return a.openDaily()
	case tea.KeyCtrlN:
		return a.newFile(a.currentDir(), discardNew)
	case tea.KeyEsc:
		a.mode = ModeEditor
		return a, nil
	}

	switch a.mode {
	case ModeEditor:
		a.editor.HandleKey(msg)
	case ModeSaveAs:
		if msg.Type == tea.KeyEnter {
			return a.saveAs()
		}
		var cmd tea.Cmd
		a.saveInput, cmd = a.saveInput.Update(msg)
		return a, cmd
	case ModePreview:
		return a, a.preview.Update(msg)
	case ModePicker:
		if msg.Type == tea.KeyEnter {
			if sel := a.picker.Selected(); sel != "" {
				if err := a.Load(sel); err != nil {
					a.status = "Open failed: " + err.Error()
				}
			}
			return a, nil
		}
		return a, a.picker.Update(msg)
	}
	return a, nil
}

func (a *App) save() (tea.Model, tea.Cmd) {
	if a.mode == ModeSaveAs {
		return a.saveAs() // Ctrl+S confirms an open save-as prompt
	}
	if a.path == "" {
		return a.promptSaveAs() // unnamed buffer → ask for a name
	}
	if err := os.WriteFile(a.path, a.editor.Bytes(), 0o644); err != nil {
		a.status = "Save failed: " + err.Error()
		return a, nil
	}
	a.editor.Dirty = false
	a.status = "Saved " + a.path
	return a, nil
}

// promptSaveAs opens the one-line save-as prompt for an unnamed buffer.
func (a *App) promptSaveAs() (tea.Model, tea.Cmd) {
	a.saveInput.SetValue("")
	a.saveInput.Focus()
	a.mode = ModeSaveAs
	a.status = "Save as — type a name, Enter to save, Esc to cancel"
	return a, nil
}

// saveAs writes the unnamed buffer to a name typed at the prompt, resolved under
// the inbox directory, then binds the buffer to that path.
func (a *App) saveAs() (tea.Model, tea.Cmd) {
	root := a.saveDir
	if root == "" {
		root = a.cfg.InboxRoot()
	}
	p := picker.NewNotePath(root, a.saveInput.Value())
	if p == "" {
		a.status = "Type a name first"
		return a, nil
	}
	if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
		a.status = "Save dir failed: " + err.Error()
		return a, nil
	}
	if err := os.WriteFile(p, a.editor.Bytes(), 0o644); err != nil {
		a.status = "Save failed: " + err.Error()
		return a, nil
	}
	a.path = p
	a.editor.Dirty = false
	a.mode = ModeEditor
	a.status = "Saved " + p
	return a, nil
}

// newFile is the Ctrl+N / Ctrl+I handler: start a new note in dir. From the
// picker with a typed query it creates dir/<query>.md; otherwise it opens a
// blank buffer whose save-as targets dir (confirming discard if the editor is
// dirty, keyed by pend so re-pressing the same key confirms).
func (a *App) newFile(dir string, pend pendingDiscard) (tea.Model, tea.Cmd) {
	if a.mode == ModePicker {
		if q := strings.TrimSpace(a.picker.Query()); q != "" {
			return a.openNoteAt(picker.NewNotePath(dir, q))
		}
		a.startBlankIn(dir)
		return a, nil
	}
	if a.editor.Dirty && a.pending != pend {
		a.pending = pend
		a.status = "Unsaved changes — press again to discard"
		return a, nil
	}
	a.pending = discardNone
	a.startBlankIn(dir)
	return a, nil
}

// startBlankIn opens an empty, unnamed buffer whose save-as targets dir.
func (a *App) startBlankIn(dir string) {
	a.saveDir = dir
	a.editor.SetContent(nil)
	a.path = ""
	a.mode = ModeEditor
	a.status = "New note"
}

// openNoteAt creates the note at p (if absent) and opens it.
func (a *App) openNoteAt(p string) (tea.Model, tea.Cmd) {
	if p == "" {
		a.status = "Type a name first"
		return a, nil
	}
	if _, err := os.Stat(p); os.IsNotExist(err) {
		if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
			a.status = "New note dir failed: " + err.Error()
			return a, nil
		}
		if err := os.WriteFile(p, []byte{}, 0o644); err != nil {
			a.status = "New note failed: " + err.Error()
			return a, nil
		}
	}
	if err := a.Load(p); err != nil {
		a.status = "Open failed: " + err.Error()
	}
	return a, nil
}

// currentDir is the "same directory" for Ctrl+N: the picker root in the picker,
// the open file's folder in the editor, else the working directory.
func (a *App) currentDir() string {
	if a.mode == ModePicker {
		return a.pickerRoot
	}
	if a.path != "" {
		return filepath.Dir(a.path)
	}
	return a.cfg.WorkingDir()
}

// StartNewIn is the `glint -n` entry point: a blank buffer targeting dir when
// name is empty, or a new note created at dir/<name>.md.
func (a *App) StartNewIn(dir, name string) error {
	if strings.TrimSpace(name) == "" {
		a.startBlankIn(dir)
		return nil
	}
	p := picker.NewNotePath(dir, name)
	if _, err := os.Stat(p); os.IsNotExist(err) {
		if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
			return err
		}
		if err := os.WriteFile(p, []byte{}, 0o644); err != nil {
			return err
		}
	}
	return a.Load(p)
}

// StartNew creates a new note in the inbox (kept for callers/tests).
func (a *App) StartNew(name string) error { return a.StartNewIn(a.cfg.InboxRoot(), name) }

// glamourStyle is the explicit config override if set, else the theme's style.
func (a *App) glamourStyle() string {
	if a.cfg.GlamourStyle != "" {
		return a.cfg.GlamourStyle
	}
	return a.theme.GlamourStyle
}

// cycleTheme advances to the next theme and repaints the editor, preview, and
// (if open) the picker.
func (a *App) cycleTheme() (tea.Model, tea.Cmd) {
	a.theme = theme.Next(a.theme.Name)
	a.editor.SetTheme(a.theme)
	a.preview.SetStyle(a.glamourStyle())
	a.preview.SetBackground(string(a.theme.Background))
	// Re-render an open preview so its glamour style follows the new theme
	// (otherwise it keeps the old light/dark block until the next toggle).
	if a.mode == ModePreview {
		_ = a.preview.Render(string(a.editor.Bytes()))
	}
	if a.picker != nil {
		a.picker.SetTheme(a.theme)
		a.picker.SetStyle(a.glamourStyle())
	}
	a.status = "Theme: " + a.theme.Name
	return a, nil
}

// togglePreview switches between the editor and the Glamour read view.
func (a *App) togglePreview() (tea.Model, tea.Cmd) {
	if a.mode == ModePreview {
		a.mode = ModeEditor
		return a, nil
	}
	if err := a.preview.Render(string(a.editor.Bytes())); err != nil {
		a.status = "Preview failed: " + err.Error()
		return a, nil
	}
	a.mode = ModePreview
	return a, nil
}

// contentWidth is the centered text column width: ~65% of the terminal, capped
// for readability and floored so it never collapses, never wider than the term.
func (a *App) contentWidth() int {
	w := int(math.Round(float64(a.width) * canvasRatio))
	if w > canvasMax {
		w = canvasMax
	}
	if w < canvasMin {
		w = canvasMin
	}
	if w > a.width {
		w = a.width
	}
	return w
}

// leftMargin centers the content column in the terminal.
func (a *App) leftMargin() int {
	m := (a.width - a.contentWidth()) / 2
	if m < 0 {
		m = 0
	}
	return m
}

func (a *App) topPad() int { return canvasTopPad }

func (a *App) setSize(w, h int) {
	a.width = w
	a.height = h
	cw := a.contentWidth()
	textRows := h - 1 - a.topPad() // status bar + top pad
	if textRows < 1 {
		textRows = 1
	}
	a.editor.SetSize(cw, textRows)
	a.preview.SetSize(cw, textRows)
	if a.picker != nil {
		a.picker.SetSize(w, h-1) // picker keeps its full-width split
	}
}

// openPicker builds a fresh picker over the working directory and switches to it.
func (a *App) openPicker() (tea.Model, tea.Cmd) {
	return a.openPickerAt(a.cfg.WorkingDir())
}

// openPickerAt opens the picker rooted at dir and records the root.
func (a *App) openPickerAt(dir string) (tea.Model, tea.Cmd) {
	p, err := picker.New(dir, a.theme, a.cfg.DailyPath(time.Now()), a.glamourStyle())
	if err != nil {
		a.status = "Picker failed: " + err.Error()
		return a, nil
	}
	p.SetSize(a.width, a.height-1)
	a.picker = p
	a.pickerRoot = dir
	a.mode = ModePicker
	return a, nil
}

// StartPickerIn opens the picker over dir (used by -v/-i/-d and the default).
func (a *App) StartPickerIn(dir string) error {
	_, _ = a.openPickerAt(dir)
	return nil
}

// StartVault opens the picker over the configured vault.
func (a *App) StartVault() error { return a.StartPickerIn(a.cfg.Vault()) }

// openDaily opens today's daily note, creating the file and directory if needed.
func (a *App) openDaily() (tea.Model, tea.Cmd) {
	path := a.cfg.DailyPath(time.Now())
	if _, err := os.Stat(path); os.IsNotExist(err) {
		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
			a.status = "Daily dir failed: " + err.Error()
			return a, nil
		}
		if err := os.WriteFile(path, []byte{}, 0o644); err != nil {
			a.status = "Daily create failed: " + err.Error()
			return a, nil
		}
	}
	if err := a.Load(path); err != nil {
		a.status = "Daily open failed: " + err.Error()
	}
	return a, nil
}

// View renders the active sub-view. The editor and preview sit in a centered,
// padded column; the picker keeps its own full-width layout.
func (a *App) View() string {
	if a.mode == ModePicker {
		body := a.picker.View()
		if !strings.HasSuffix(body, "\n") {
			body += "\n"
		}
		return body + a.statusBar()
	}

	var body string
	if a.mode == ModePreview {
		body = a.preview.View()
	} else {
		body = a.editor.View() // editor stays visible beneath the save-as prompt
	}
	bottom := a.statusBar()
	if a.mode == ModeSaveAs {
		bottom = a.saveBar()
	}
	return a.paintCanvas(body) + bottom
}

// saveBar renders the save-as prompt as a themed full-width bottom bar.
func (a *App) saveBar() string {
	bar := lipgloss.NewStyle().
		Foreground(a.theme.StatusFg).
		Background(a.theme.StatusBg).
		Width(maxInt(a.width, 1))
	return bar.Render(" " + a.saveInput.View() + " ")
}

// paintCanvas centers body in the theme's paper: a top pad, then each body line
// indented by the left margin, every line filled to the full terminal width with
// the theme background so margins and empty space carry the theme color rather
// than the terminal default. The result is exactly height-1 rows (the status bar
// is the final row) and always ends with a trailing newline before it.
func (a *App) paintCanvas(body string) string {
	bg := lipgloss.NewStyle().Background(a.theme.Background).Width(maxInt(a.width, 1))
	lm := strings.Repeat(" ", a.leftMargin())
	rows := make([]string, 0, a.height)
	for p := 0; p < a.topPad(); p++ {
		rows = append(rows, bg.Render(""))
	}
	for _, ln := range strings.Split(body, "\n") {
		if ln == "" {
			rows = append(rows, bg.Render(""))
		} else {
			rows = append(rows, bg.Render(lm+ln))
		}
	}
	return strings.Join(rows, "\n") + "\n"
}

func (a *App) statusBar() string {
	bar := lipgloss.NewStyle().
		Foreground(a.theme.StatusFg).
		Background(a.theme.StatusBg).
		Width(maxInt(a.width, 1))
	dirty := ""
	if a.editor.Dirty {
		dirty = " ●"
	}
	left := a.status
	if left == "" {
		left = "glint"
	}
	return bar.Render(fmt.Sprintf(" %s%s ", left, dirty))
}

func maxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}