2023-08-18 13:17:46 +02:00

62 lines
1.1 KiB
Go

package editor
import (
"os"
"path/filepath"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
)
func New(app *tview.Application) *tview.TextArea {
view := tview.NewTextArea()
view.SetBackgroundColor(tcell.ColorDefault)
view.SetTextStyle(tcell.StyleDefault)
view.SetBorderPadding(0, 0, 1, 1)
source := "Having been erased,\nThe document you're seeking\nMust now be retyped."
home, err := os.UserHomeDir()
if err != nil {
panic(err)
}
data, err := os.ReadFile(filepath.Join(home, ".dash"))
if err == nil {
source = string(data)
}
view.SetText(source, true)
view.SetChangedFunc(func() {
source = view.GetText()
markDirty(view, true)
})
view.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
if event.Key() == tcell.KeyCtrlS {
err := os.WriteFile(filepath.Join(home, ".dash"), []byte(source), 0644)
if err != nil {
panic(err)
}
markDirty(view, false)
return nil
}
return event
})
return view
}
func markDirty(view *tview.TextArea, dirty bool) {
if dirty {
view.SetBackgroundColor(tcell.ColorRed)
} else {
view.SetBackgroundColor(tcell.ColorDefault)
}
}