tui.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. // The package defines an extensible TUI via the bubbletea framework.
  2. //
  3. // While the package remains in v0.0.X releases, this TUI may be undocumented.
  4. //
  5. // TODO enable collection recursing (i.e, embedded collections)
  6. //
  7. // TODO enable scroll/viewport logic
  8. package issues
  9. import (
  10. "fmt"
  11. "path/filepath"
  12. "strings"
  13. "github.com/charmbracelet/bubbles/textinput"
  14. tea "github.com/charmbracelet/bubbletea"
  15. "github.com/charmbracelet/lipgloss"
  16. )
  17. // Type and Style definitions -------------------------------------------------
  18. // ----------------------------------------------------------------------------
  19. // [lipgloss] style definitions, stores the currently displayed "widget"
  20. var (
  21. titleStyle = lipgloss.NewStyle().
  22. Bold(true).
  23. Underline(true)
  24. statusStyle = lipgloss.NewStyle().
  25. Faint(true).
  26. Italic(true)
  27. variadicTitleStyle = lipgloss.NewStyle().
  28. Align(lipgloss.Left).
  29. Italic(true)
  30. variadicDataStyle = lipgloss.NewStyle().
  31. Width(40).
  32. BorderStyle(lipgloss.ASCIIBorder())
  33. borderStyle = lipgloss.NewStyle().
  34. Padding(1, 2).
  35. Margin(1).
  36. BorderStyle(lipgloss.NormalBorder())
  37. indexStyle = lipgloss.NewStyle().
  38. Italic(true)
  39. pointerStyle = lipgloss.NewStyle().
  40. Faint(true)
  41. collectionStyleLeft = lipgloss.NewStyle().
  42. Align(lipgloss.Left)
  43. )
  44. // MAIN MODEL DEFINITIONS -----------------------------------------------------
  45. // ----------------------------------------------------------------------------
  46. // The main bubbletea Model
  47. type Model struct {
  48. widget widget
  49. content string
  50. Path string
  51. // viewport viewport.Model
  52. }
  53. // The bubbletea init function
  54. func (m Model) Init() tea.Cmd { return m.load }
  55. // Core tea.Model update loop
  56. func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  57. var cmds []tea.Cmd
  58. // general message handling
  59. switch msg := msg.(type) {
  60. case tea.KeyMsg: // KeyMsg capture that is always present
  61. switch msg.String() {
  62. case "ctrl+c":
  63. cmds = append(cmds, tea.Quit)
  64. }
  65. case widget: // widget is initialized from m.load()
  66. switch T := msg.(type) {
  67. case edit:
  68. m.widget = T
  69. cmds = append(cmds, T.render, T.init())
  70. default:
  71. m.widget = T
  72. cmds = append(cmds, T.render)
  73. }
  74. case loadPath:
  75. m.Path = string(msg)
  76. return m, m.load
  77. case createInCollectionMsg:
  78. wg := createInCollection{Path: string(msg)}
  79. i := textinput.New()
  80. i.Placeholder = "a short title"
  81. i.Focus()
  82. i.CharLimit = 80
  83. i.Width = 30
  84. wg.input = i
  85. return m, func() tea.Msg { return wg }
  86. case string:
  87. m.content = msg
  88. }
  89. // finally, pass msg to widget
  90. var cmd tea.Cmd
  91. switch w := m.widget.(type) {
  92. case edit:
  93. m.widget, cmd = w.update(msg)
  94. cmds = append(cmds, cmd, w.render)
  95. case Issue:
  96. m.widget, cmd = w.update(msg)
  97. cmds = append(cmds, cmd, w.render)
  98. case IssueCollection:
  99. m.widget, cmd = w.update(msg)
  100. cmds = append(cmds, cmd, w.render)
  101. case createInCollection:
  102. m.widget, cmd = w.update(msg)
  103. cmds = append(cmds, cmd, w.render)
  104. }
  105. return m, tea.Batch(cmds...)
  106. }
  107. // Handles top level view functionality
  108. func (m Model) View() string {
  109. var output string
  110. if len(m.content) == 0 {
  111. return "loading..."
  112. }
  113. output = output + m.content
  114. output = output + lipgloss.NewStyle().Faint(true).Margin(1).Render(m.widget.keyhelp())
  115. return output
  116. }
  117. // Handles load logic
  118. func (m Model) load() tea.Msg {
  119. if IsIssue(m.Path) {
  120. issue, err := Issue{}.NewFromPath(m.Path)
  121. if err != nil {
  122. return nil
  123. }
  124. return issue
  125. }
  126. if IsIssueCollection(m.Path) {
  127. collection, err := IssueCollection{}.NewFromPath(m.Path)
  128. if err != nil {
  129. return nil
  130. }
  131. return collection
  132. }
  133. return newEditWidget(m.Path)
  134. }
  135. // WIDGET DEFINITIONS ---------------------------------------------------------
  136. // ----------------------------------------------------------------------------
  137. // interface definition for widgets
  138. type widget interface {
  139. update(tea.Msg) (widget, tea.Cmd) // implements widget specific update life cycles
  140. render() tea.Msg // renders content
  141. keyhelp() string // renders key usage
  142. }
  143. // -------- edit widget definitions -----------------------------------------
  144. // ----------------------------------------------------------------------------
  145. // TODO(create widget) implement description field in create.create
  146. type ( // Type definitions for use in tea.Msg life cycle for create widget.
  147. createResult Issue // type wrapper for create.create() result
  148. writeResult any // type wrapper for create.write() result
  149. editorResult struct { // type wrapper for create.editor() result
  150. err error // any error returned by InvokeEditor
  151. issue Issue // the data in the template file
  152. }
  153. )
  154. // data struct for create widget
  155. type inputField struct {
  156. input textinput.Model
  157. title string
  158. }
  159. // struct definition for edit widget
  160. type edit struct {
  161. inputFields []inputField
  162. Path string
  163. selected int
  164. err error // not implemented
  165. }
  166. func newEditWidget(path string) widget {
  167. // data prep
  168. var e edit
  169. var issue Issue
  170. var err error
  171. if IsIssue(path) { // if path is existing issue, load Issue from path
  172. issue, err = Issue{}.NewFromPath(path)
  173. if err != nil {
  174. return e
  175. }
  176. } else { // if path is not existing issue, create new Issue with sensible defaults
  177. issue = Issue{
  178. Path: path, Title: parsePathToHuman(path),
  179. Status: Field{Path: "/status", Data: "open"},
  180. }
  181. }
  182. // anon function for spawning instantiated textinput.Model's
  183. spawnInput := func(f bool) textinput.Model {
  184. ti := textinput.New()
  185. if f {
  186. ti.Focus()
  187. }
  188. ti.CharLimit = 80
  189. ti.Width = 30
  190. return ti
  191. }
  192. // inputFields data prep
  193. var fields []inputField
  194. var input textinput.Model
  195. // title
  196. input = spawnInput(true)
  197. input.SetValue(issue.Title)
  198. input.Placeholder = "title"
  199. fields = append(fields, inputField{input: input, title: "title"})
  200. // status
  201. input = spawnInput(false)
  202. input.SetValue(issue.Status.Data)
  203. input.Placeholder = "status"
  204. fields = append(fields, inputField{input: input, title: "status"})
  205. // tags
  206. input = spawnInput(false)
  207. input.SetValue(issue.Tags.AsString())
  208. input.Placeholder = "tags, separated by comma"
  209. fields = append(fields, inputField{input: input, title: "tags"})
  210. // blockedby
  211. input = spawnInput(false)
  212. input.SetValue(issue.Blockedby.AsString())
  213. input.Placeholder = "blockers, separated by comma"
  214. fields = append(fields, inputField{input: input, title: "blockers"})
  215. e.inputFields = fields
  216. e.Path = path
  217. return e
  218. }
  219. // init cmd for create widget
  220. func (e edit) init() tea.Cmd { return textinput.Blink }
  221. // update cmd for create widget
  222. func (e edit) update(msg tea.Msg) (widget, tea.Cmd) {
  223. var cmds []tea.Cmd
  224. var cmd tea.Cmd
  225. // simple anon functions to increment the selected index
  226. incrementSelected := func() {
  227. if e.selected < len(e.inputFields) {
  228. e.selected++
  229. for i := 0; i < len(e.inputFields); i++ {
  230. if i == e.selected {
  231. e.inputFields[i].input.Focus()
  232. } else {
  233. e.inputFields[i].input.Blur()
  234. }
  235. }
  236. } else {
  237. e.selected = 0
  238. e.inputFields[e.selected].input.Focus()
  239. }
  240. }
  241. decrementSelected := func() {
  242. if e.selected != 0 {
  243. e.selected--
  244. for i := 0; i < len(e.inputFields); i++ {
  245. if i == e.selected {
  246. e.inputFields[i].input.Focus()
  247. } else {
  248. e.inputFields[i].input.Blur()
  249. }
  250. }
  251. } else {
  252. for i := 0; i < len(e.inputFields); i++ {
  253. e.inputFields[i].input.Blur()
  254. }
  255. e.selected = len(e.inputFields)
  256. }
  257. }
  258. switch msg := msg.(type) { // keybinding handler
  259. case tea.KeyMsg:
  260. switch msg.String() {
  261. case "tab":
  262. incrementSelected()
  263. case "shift+tab":
  264. decrementSelected()
  265. case "enter":
  266. if e.selected == len(e.inputFields) { // confirm create
  267. e.selected++
  268. } else if e.selected == len(e.inputFields)+1 { // confirmed
  269. cmds = append(cmds, e.createIssueObject)
  270. } else {
  271. incrementSelected()
  272. }
  273. case "esc": // reset
  274. for i, field := range e.inputFields {
  275. field.input.Reset()
  276. switch field.title {
  277. case "title":
  278. parsed := parsePathToHuman(e.Path)
  279. if parsed == "." {
  280. parsed = ""
  281. }
  282. field.input.SetValue(parsed)
  283. case "status":
  284. field.input.SetValue("open")
  285. }
  286. e.inputFields[i] = field
  287. }
  288. }
  289. case createResult:
  290. cmds = append(cmds, e.editBlankDescription(Issue(msg)))
  291. case editorResult:
  292. if msg.err != nil {
  293. e.err = msg.err
  294. } else {
  295. cmds = append(cmds, e.write(msg.issue))
  296. }
  297. case writeResult:
  298. switch value := msg.(type) {
  299. case bool:
  300. if !value {
  301. } else {
  302. cmds = append(cmds, func() tea.Msg { return loadPath(e.Path) })
  303. }
  304. case error:
  305. e.selected = -100
  306. e.err = value
  307. }
  308. }
  309. for i, ti := range e.inputFields {
  310. e.inputFields[i].input, cmd = ti.input.Update(msg)
  311. cmds = append(cmds, cmd)
  312. }
  313. cmds = append(cmds, cmd)
  314. return e, tea.Batch(cmds...)
  315. }
  316. // A tea.Cmd to translate createIssueObject.inputs to a new Issue object
  317. func (e edit) createIssueObject() tea.Msg {
  318. data := make(map[string]string)
  319. commaSplit := func(t string) []string {
  320. s := strings.Split(t, ",")
  321. for i, v := range s {
  322. s[i] = strings.TrimLeft(v, " \t\n")
  323. s[i] = strings.TrimRight(s[i], " \t\n")
  324. s[i] = parseHumanToPath(s[i])
  325. }
  326. return s
  327. }
  328. for _, field := range e.inputFields {
  329. data[field.title] = field.input.Value()
  330. }
  331. var newIssue = Issue{
  332. Path: e.Path,
  333. Tags: VariadicField{Path: "/tags"},
  334. Blockedby: VariadicField{Path: "/blockedby"},
  335. }
  336. for key, value := range data {
  337. switch key {
  338. case "title":
  339. newIssue.Title = value
  340. if parsePathToHuman(newIssue.Path) != value {
  341. dir, _ := filepath.Split(newIssue.Path)
  342. newIssue.Path = filepath.Join(dir, value)
  343. }
  344. case "status":
  345. newIssue.Status = Field{Path: "/status", Data: value}
  346. case "description":
  347. newIssue.Description = Field{Path: "/description", Data: value}
  348. case "tags":
  349. splitTags := commaSplit(value)
  350. for _, tag := range splitTags {
  351. newIssue.Tags.Fields = append(newIssue.Tags.Fields, Field{Path: tag})
  352. }
  353. case "blockers":
  354. splitBlockedby := commaSplit(value)
  355. for _, blocker := range splitBlockedby {
  356. newIssue.Blockedby.Fields = append(
  357. newIssue.Blockedby.Fields, Field{Path: blocker},
  358. )
  359. }
  360. }
  361. }
  362. return createResult(newIssue)
  363. }
  364. // Wraps a tea.Cmd function, passes an initialized Issue to WriteIssue()
  365. func (e edit) write(issue Issue) tea.Cmd {
  366. return func() tea.Msg {
  367. result, err := WriteIssue(issue, false)
  368. if err != nil {
  369. return writeResult(err)
  370. }
  371. return writeResult(result)
  372. }
  373. }
  374. // Calls InvokeEditor via EditTemplate using DescriptionTemplate, reports output
  375. // and errors
  376. //
  377. // WARNING! THIS METHOD HANGS UNTIL THE USER KILLS THE EDITOR!
  378. func (e edit) editBlankDescription(issue Issue) tea.Cmd {
  379. data, err := EditTemplate(DescriptionTemplate, InvokeEditor)
  380. var output string
  381. for _, line := range data {
  382. output = output + line
  383. }
  384. issue.Description = Field{Path: "/description", Data: output}
  385. return func() tea.Msg {
  386. return editorResult{issue: issue, err: err}
  387. }
  388. }
  389. // does this just call InvokeEditor?
  390. func (e edit) editExistingDescription(issue Issue) tea.Cmd { return func() tea.Msg { return "" } }
  391. // render cmd for create widget
  392. func (e edit) render() tea.Msg {
  393. if e.err != nil {
  394. return fmt.Sprintf("failed to create issue... %s", e.err.Error())
  395. }
  396. borderStyle := lipgloss.NewStyle().
  397. BorderStyle(lipgloss.NormalBorder()).
  398. Margin(1).
  399. Padding(0, 1)
  400. ulStyle := lipgloss.NewStyle().Underline(true)
  401. var output string
  402. for _, field := range e.inputFields {
  403. output = output + fmt.Sprintf(
  404. "\n%s:%s",
  405. field.title,
  406. borderStyle.Render(field.input.View()),
  407. )
  408. }
  409. output = strings.TrimLeft(output, "\n")
  410. if e.selected < len(e.inputFields) {
  411. output = output + borderStyle.Render("press enter to submit...")
  412. } else if e.selected == len(e.inputFields) {
  413. output = output + borderStyle.Render(ulStyle.Render("press enter to submit..."))
  414. } else if e.selected == len(e.inputFields)+1 {
  415. confirmPrompt := fmt.Sprintf(
  416. "create issue titled \"%s\"?\n\n%s",
  417. ulStyle.Render(e.inputFields[0].input.Value()),
  418. ulStyle.Render("press enter to write description..."),
  419. )
  420. output = output + borderStyle.Render(confirmPrompt)
  421. }
  422. return output
  423. }
  424. // keyhelp cmd for create widget
  425. func (e edit) keyhelp() string {
  426. var output string
  427. output = output + "\ntab/shift+tab: down/up\t\tenter: input value\t\tesc: reset\t\tctrl+e: quit"
  428. return output
  429. }
  430. // -------- Issue widget definitions ------------------------------------------
  431. // ----------------------------------------------------------------------------
  432. // enforce widget interface compliance
  433. func (i Issue) update(tea.Msg) (widget, tea.Cmd) { return i, nil }
  434. // render cmd for Issue widget
  435. func (i Issue) render() tea.Msg {
  436. var output string
  437. // title
  438. output = output + titleStyle.Render(i.Title)
  439. // status
  440. output = output + fmt.Sprintf("\n%s", statusStyle.Render(i.Status.Data))
  441. // variadics
  442. var tags string
  443. for _, field := range i.Tags.Fields {
  444. tags = tags + field.Path + ", "
  445. }
  446. tags = strings.TrimRight(tags, ", ")
  447. var blockedby string
  448. for _, field := range i.Blockedby.Fields {
  449. blockedby = blockedby + field.Path + ", "
  450. }
  451. blockedby = strings.TrimRight(blockedby, ", ")
  452. if len(i.Tags.Fields) > 0 {
  453. output = output + variadicTitleStyle.Render("\n\nTags:")
  454. output = output + fmt.Sprintf("\n%s", variadicDataStyle.Render(tags))
  455. }
  456. if len(i.Blockedby.Fields) > 0 {
  457. output = output + variadicTitleStyle.Render("\n\nBlockedby:")
  458. output = output + fmt.Sprintf("\n%s", variadicDataStyle.Render(blockedby))
  459. }
  460. // description
  461. output = output + titleStyle.Render("\n\nDescription:\n")
  462. output = output + fmt.Sprintf("\n%s", i.Description.Data)
  463. return borderStyle.Render(output)
  464. }
  465. // keyhelp cmd for Issue widget
  466. func (i Issue) keyhelp() string {
  467. var output string
  468. output = output + "\nj/k: down/up\t\tctrl+c: quit"
  469. return output
  470. }
  471. // -------- IssueCollection widget definitions --------------------------------
  472. // ----------------------------------------------------------------------------
  473. type ( // Type definitions for use in tea.Msg life cycle for IssueCollection widget.
  474. loadPath string // thrown when user selects a path to load.
  475. createInCollectionMsg string //thrown when user opts to create new issue in collection
  476. )
  477. // enforce widget interface compliance
  478. func (ic IssueCollection) update(msg tea.Msg) (widget, tea.Cmd) {
  479. switch msg := msg.(type) {
  480. case tea.KeyMsg:
  481. switch msg.String() {
  482. case "j":
  483. if ic.selection+1 < len(ic.Collection) {
  484. ic.selection = ic.selection + 1
  485. } else {
  486. ic.selection = 0
  487. }
  488. return ic, ic.render
  489. case "k":
  490. if ic.selection != 0 {
  491. ic.selection = ic.selection - 1
  492. } else {
  493. ic.selection = len(ic.Collection) - 1
  494. }
  495. return ic, ic.render
  496. case "enter":
  497. ic.Path = ic.Collection[ic.selection].Path
  498. return ic, ic.sendLoad
  499. case "q":
  500. return ic, tea.Quit
  501. case "c":
  502. return ic, ic.newIssueInCollection
  503. }
  504. }
  505. return ic, nil
  506. }
  507. func (ic IssueCollection) sendLoad() tea.Msg { return loadPath(ic.Path) }
  508. func (ic IssueCollection) newIssueInCollection() tea.Msg { return createInCollectionMsg(ic.Path) }
  509. // render cmd for IssueCollection widget
  510. func (ic IssueCollection) render() tea.Msg {
  511. var output string
  512. if ic.selection == -1 {
  513. }
  514. var left string
  515. output = output + "Issues in " + ic.Path + "...\n\n"
  516. for i, issue := range ic.Collection {
  517. // pointer render
  518. if i == ic.selection {
  519. left = left + pointerStyle.Render("-> ")
  520. } else {
  521. left = left + pointerStyle.Render(" ")
  522. }
  523. // index render
  524. left = left + "[" + indexStyle.Render(fmt.Sprintf("%d", i+1)) + "]: "
  525. // title render
  526. left = left + fmt.Sprintf("%s\n", titleStyle.Render(issue.Title))
  527. }
  528. output = output + collectionStyleLeft.Render(left)
  529. return output
  530. }
  531. // keyhelp cmd for IssueCollection widget
  532. func (ic IssueCollection) keyhelp() string {
  533. var output string
  534. output = output + "\nj/k: down/up\t\tc: create new issue\t\tenter: select\t\tq/ctrl+c: quit"
  535. return output
  536. }
  537. // -------- createInCollection widget definitions -----------------------------
  538. // ----------------------------------------------------------------------------
  539. type createInCollection struct {
  540. Path string // base path for the new issue
  541. name string // the name input by the user
  542. input textinput.Model // the input widget
  543. }
  544. func (w createInCollection) update(msg tea.Msg) (widget, tea.Cmd) {
  545. var cmds []tea.Cmd
  546. switch msg := msg.(type) {
  547. case tea.KeyMsg:
  548. switch msg.String() {
  549. case "enter":
  550. cmds = append(cmds, w.create)
  551. }
  552. }
  553. var inputCmd tea.Cmd
  554. w.input, inputCmd = w.input.Update(msg)
  555. cmds = append(cmds, inputCmd)
  556. w.name = w.input.Value()
  557. return w, tea.Batch(cmds...)
  558. }
  559. func (w createInCollection) create() tea.Msg {
  560. w.Path = filepath.Join(w.Path, w.name)
  561. return newEditWidget(w.Path)
  562. }
  563. func (w createInCollection) render() tea.Msg {
  564. return borderStyle.Render(fmt.Sprintf("Creating new issue in %s\ntitle: %s",
  565. w.Path, w.input.View()))
  566. }
  567. func (w createInCollection) keyhelp() string { return "enter: submit\t\tctrl+c: quit" }