tui.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. // WIDGET DEFINITIONS ---------------------------------------------------------
  118. // ----------------------------------------------------------------------------
  119. // interface definition for widgets
  120. type widget interface {
  121. update(tea.Msg) (widget, tea.Cmd) // implements widget specific update life cycles
  122. render() tea.Msg // renders content
  123. keyhelp() string // renders key usage
  124. }
  125. // -------- edit widget definitions -----------------------------------------
  126. // ----------------------------------------------------------------------------
  127. // TODO(create widget) implement description field in create.create
  128. type ( // Type definitions for use in tea.Msg life cycle for create widget.
  129. createResult Issue // type wrapper for create.create() result
  130. writeResult any // type wrapper for create.write() result
  131. editorResult struct { // type wrapper for create.editor() result
  132. err error // any error returned by InvokeEditor
  133. issue Issue // the data in the template file
  134. }
  135. )
  136. // data struct for create widget
  137. type inputField struct {
  138. input textinput.Model
  139. title string
  140. }
  141. // struct definition for edit widget
  142. type edit struct {
  143. inputFields []inputField
  144. Path string
  145. selected int
  146. err error // not implemented
  147. }
  148. // constructor for create widget
  149. func newEditBlank(path string, placeholder string) widget { // TODO DEPRECATE
  150. spawnInput := func(f bool) textinput.Model {
  151. ti := textinput.New()
  152. ti.Placeholder = placeholder
  153. if f {
  154. ti.Focus()
  155. }
  156. ti.CharLimit = 80
  157. ti.Width = 30
  158. return ti
  159. }
  160. var inputs []inputField
  161. for i, t := range [4]string{"title", "status", "tags", "blockers"} {
  162. if i == 0 {
  163. inputs = append(inputs, inputField{title: t, input: spawnInput(true)})
  164. } else {
  165. inputs = append(inputs, inputField{title: t, input: spawnInput(false)})
  166. }
  167. switch t {
  168. case "title":
  169. parsed := parsePathToHuman(path)
  170. if parsed == "." {
  171. parsed = ""
  172. }
  173. inputs[i].input.SetValue(parsed)
  174. case "status":
  175. inputs[i].input.SetValue("open")
  176. }
  177. }
  178. return edit{
  179. inputFields: inputs,
  180. Path: path,
  181. selected: 0,
  182. err: nil,
  183. }
  184. }
  185. func newEditWidget(path string) widget {
  186. // data prep
  187. var e edit
  188. var issue Issue
  189. var err error
  190. if IsIssue(path) { // if path is existing issue, load Issue from path
  191. issue, err = Issue{}.NewFromPath(path)
  192. if err != nil {
  193. return e
  194. }
  195. } else { // if path is not existing issue, create new Issue with sensible defaults
  196. issue = Issue{
  197. Path: path, Title: parsePathToHuman(path),
  198. Status: Field{Path: "/status", Data: "open"},
  199. }
  200. }
  201. // anon function for spawning instantiated textinput.Model's
  202. spawnInput := func(f bool) textinput.Model {
  203. ti := textinput.New()
  204. if f {
  205. ti.Focus()
  206. }
  207. ti.CharLimit = 80
  208. ti.Width = 30
  209. return ti
  210. }
  211. // inputFields data prep
  212. var fields []inputField
  213. var input textinput.Model
  214. // title
  215. input = spawnInput(true)
  216. input.SetValue(issue.Title)
  217. input.Placeholder = "title"
  218. fields = append(fields, inputField{input: input, title: "title"})
  219. // status
  220. input = spawnInput(false)
  221. input.SetValue(issue.Status.Data)
  222. input.Placeholder = "status"
  223. fields = append(fields, inputField{input: input, title: "status"})
  224. // tags
  225. input = spawnInput(false)
  226. input.SetValue(issue.Tags.AsString())
  227. input.Placeholder = "tags, separated by comma"
  228. fields = append(fields, inputField{input: input, title: "tags"})
  229. // blockedby
  230. input = spawnInput(false)
  231. input.SetValue(issue.Blockedby.AsString())
  232. input.Placeholder = "blockers, separated by comma"
  233. fields = append(fields, inputField{input: input, title: "blockedby"})
  234. e.inputFields = fields
  235. return e
  236. }
  237. // init cmd for create widget
  238. func (e edit) init() tea.Cmd { return textinput.Blink }
  239. // update cmd for create widget
  240. func (e edit) update(msg tea.Msg) (widget, tea.Cmd) {
  241. var cmds []tea.Cmd
  242. var cmd tea.Cmd
  243. // simple anon functions to increment the selected index
  244. incrementSelected := func() {
  245. if e.selected < len(e.inputFields) {
  246. e.selected++
  247. for i := 0; i < len(e.inputFields); i++ {
  248. if i == e.selected {
  249. e.inputFields[i].input.Focus()
  250. } else {
  251. e.inputFields[i].input.Blur()
  252. }
  253. }
  254. } else {
  255. e.selected = 0
  256. e.inputFields[e.selected].input.Focus()
  257. }
  258. }
  259. decrementSelected := func() {
  260. if e.selected != 0 {
  261. e.selected--
  262. for i := 0; i < len(e.inputFields); i++ {
  263. if i == e.selected {
  264. e.inputFields[i].input.Focus()
  265. } else {
  266. e.inputFields[i].input.Blur()
  267. }
  268. }
  269. } else {
  270. for i := 0; i < len(e.inputFields); i++ {
  271. e.inputFields[i].input.Blur()
  272. }
  273. e.selected = len(e.inputFields)
  274. }
  275. }
  276. switch msg := msg.(type) { // keybinding handler
  277. case tea.KeyMsg:
  278. switch msg.String() {
  279. case "tab":
  280. incrementSelected()
  281. case "shift+tab":
  282. decrementSelected()
  283. case "enter":
  284. if e.selected == len(e.inputFields) { // confirm create
  285. e.selected++
  286. } else if e.selected == len(e.inputFields)+1 { // confirmed
  287. cmds = append(cmds, e.createIssueObject)
  288. } else {
  289. incrementSelected()
  290. }
  291. case "esc": // reset
  292. for i, field := range e.inputFields {
  293. field.input.Reset()
  294. switch field.title {
  295. case "title":
  296. parsed := parsePathToHuman(e.Path)
  297. if parsed == "." {
  298. parsed = ""
  299. }
  300. field.input.SetValue(parsed)
  301. case "status":
  302. field.input.SetValue("open")
  303. }
  304. e.inputFields[i] = field
  305. }
  306. }
  307. case createResult:
  308. cmds = append(cmds, e.editBlankDescription(Issue(msg)))
  309. case editorResult:
  310. if msg.err != nil {
  311. e.err = msg.err
  312. } else {
  313. cmds = append(cmds, e.write(msg.issue))
  314. }
  315. case writeResult:
  316. switch value := msg.(type) {
  317. case bool:
  318. if !value {
  319. } else {
  320. cmds = append(cmds, func() tea.Msg { return loadPath(e.Path) })
  321. }
  322. case error:
  323. e.selected = -100
  324. e.err = value
  325. }
  326. }
  327. for i, ti := range e.inputFields {
  328. e.inputFields[i].input, cmd = ti.input.Update(msg)
  329. cmds = append(cmds, cmd)
  330. }
  331. cmds = append(cmds, cmd)
  332. return e, tea.Batch(cmds...)
  333. }
  334. // A tea.Cmd to translate createIssueObject.inputs to a new Issue object
  335. func (e edit) createIssueObject() tea.Msg {
  336. data := make(map[string]string)
  337. commaSplit := func(t string) []string {
  338. s := strings.Split(t, ",")
  339. for i, v := range s {
  340. s[i] = strings.TrimLeft(v, " \t\n")
  341. s[i] = strings.TrimRight(s[i], " \t\n")
  342. s[i] = parseHumanToPath(s[i])
  343. }
  344. return s
  345. }
  346. for _, field := range e.inputFields {
  347. data[field.title] = field.input.Value()
  348. }
  349. var newIssue = Issue{
  350. Path: e.Path,
  351. Tags: VariadicField{Path: "/tags"},
  352. Blockedby: VariadicField{Path: "/blockedby"},
  353. }
  354. for key, value := range data {
  355. switch key {
  356. case "title":
  357. newIssue.Title = value
  358. if parsePathToHuman(newIssue.Path) != value {
  359. dir, _ := filepath.Split(newIssue.Path)
  360. newIssue.Path = filepath.Join(dir, value)
  361. }
  362. case "status":
  363. newIssue.Status = Field{Path: "/status", Data: value}
  364. case "description":
  365. newIssue.Description = Field{Path: "/description", Data: value}
  366. case "tags":
  367. splitTags := commaSplit(value)
  368. for _, tag := range splitTags {
  369. newIssue.Tags.Fields = append(newIssue.Tags.Fields, Field{Path: tag})
  370. }
  371. case "blockers":
  372. splitBlockedby := commaSplit(value)
  373. for _, blocker := range splitBlockedby {
  374. newIssue.Blockedby.Fields = append(
  375. newIssue.Blockedby.Fields, Field{Path: blocker},
  376. )
  377. }
  378. }
  379. }
  380. return createResult(newIssue)
  381. }
  382. // Wraps a tea.Cmd function, passes an initialized Issue to WriteIssue()
  383. func (e edit) write(issue Issue) tea.Cmd {
  384. return func() tea.Msg {
  385. result, err := WriteIssue(issue, false)
  386. if err != nil {
  387. return writeResult(err)
  388. }
  389. return writeResult(result)
  390. }
  391. }
  392. // Calls InvokeEditor via EditTemplate using DescriptionTemplate, reports output
  393. // and errors
  394. //
  395. // WARNING! THIS METHOD HANGS UNTIL THE USER KILLS THE EDITOR!
  396. func (e edit) editBlankDescription(issue Issue) tea.Cmd {
  397. data, err := EditTemplate(DescriptionTemplate, InvokeEditor)
  398. var output string
  399. for _, line := range data {
  400. output = output + line
  401. }
  402. issue.Description = Field{Path: "/description", Data: output}
  403. return func() tea.Msg {
  404. return editorResult{issue: issue, err: err}
  405. }
  406. }
  407. // does this just call InvokeEditor?
  408. func (e edit) editExistingDescription(issue Issue) tea.Cmd { return func() tea.Msg { return "" } }
  409. // render cmd for create widget
  410. func (e edit) render() tea.Msg {
  411. if e.err != nil {
  412. return fmt.Sprintf("failed to create issue... %s", e.err.Error())
  413. }
  414. borderStyle := lipgloss.NewStyle().
  415. BorderStyle(lipgloss.NormalBorder()).
  416. Margin(1).
  417. Padding(0, 1)
  418. ulStyle := lipgloss.NewStyle().Underline(true)
  419. var output string
  420. for _, field := range e.inputFields {
  421. output = output + fmt.Sprintf(
  422. "\n%s:%s",
  423. field.title,
  424. borderStyle.Render(field.input.View()),
  425. )
  426. }
  427. output = strings.TrimLeft(output, "\n")
  428. if e.selected < len(e.inputFields) {
  429. output = output + borderStyle.Render("press enter to submit...")
  430. } else if e.selected == len(e.inputFields) {
  431. output = output + borderStyle.Render(ulStyle.Render("press enter to submit..."))
  432. } else if e.selected == len(e.inputFields)+1 {
  433. confirmPrompt := fmt.Sprintf(
  434. "create issue titled \"%s\"?\n\n%s",
  435. ulStyle.Render(e.inputFields[0].input.Value()),
  436. ulStyle.Render("press enter to write description..."),
  437. )
  438. output = output + borderStyle.Render(confirmPrompt)
  439. }
  440. return output
  441. }
  442. // keyhelp cmd for create widget
  443. func (e edit) keyhelp() string {
  444. var output string
  445. output = output + "\ntab/shift+tab: down/up\t\tenter: input value\t\tesc: reset\t\tctrl+e: quit"
  446. return output
  447. }
  448. // -------- Issue widget definitions ------------------------------------------
  449. // ----------------------------------------------------------------------------
  450. // enforce widget interface compliance
  451. func (i Issue) update(tea.Msg) (widget, tea.Cmd) { return i, nil }
  452. // render cmd for Issue widget
  453. func (i Issue) render() tea.Msg {
  454. var output string
  455. // title
  456. output = output + titleStyle.Render(i.Title)
  457. // status
  458. output = output + fmt.Sprintf("\n%s", statusStyle.Render(i.Status.Data))
  459. // variadics
  460. var tags string
  461. for _, field := range i.Tags.Fields {
  462. tags = tags + field.Path + ", "
  463. }
  464. tags = strings.TrimRight(tags, ", ")
  465. var blockedby string
  466. for _, field := range i.Blockedby.Fields {
  467. blockedby = blockedby + field.Path + ", "
  468. }
  469. blockedby = strings.TrimRight(blockedby, ", ")
  470. if len(i.Tags.Fields) > 0 {
  471. output = output + variadicTitleStyle.Render("\n\nTags:")
  472. output = output + fmt.Sprintf("\n%s", variadicDataStyle.Render(tags))
  473. }
  474. if len(i.Blockedby.Fields) > 0 {
  475. output = output + variadicTitleStyle.Render("\n\nBlockedby:")
  476. output = output + fmt.Sprintf("\n%s", variadicDataStyle.Render(blockedby))
  477. }
  478. // description
  479. output = output + titleStyle.Render("\n\nDescription:\n")
  480. output = output + fmt.Sprintf("\n%s", i.Description.Data)
  481. return borderStyle.Render(output)
  482. }
  483. // keyhelp cmd for Issue widget
  484. func (i Issue) keyhelp() string {
  485. var output string
  486. output = output + "\nj/k: down/up\t\tctrl+c: quit"
  487. return output
  488. }
  489. // -------- IssueCollection widget definitions --------------------------------
  490. // ----------------------------------------------------------------------------
  491. type ( // Type definitions for use in tea.Msg life cycle for IssueCollection widget.
  492. loadPath string // thrown when user selects a path to load.
  493. createInCollectionMsg string //thrown when user opts to create new issue in collection
  494. )
  495. // enforce widget interface compliance
  496. func (ic IssueCollection) update(msg tea.Msg) (widget, tea.Cmd) {
  497. switch msg := msg.(type) {
  498. case tea.KeyMsg:
  499. switch msg.String() {
  500. case "j":
  501. if ic.selection+1 < len(ic.Collection) {
  502. ic.selection = ic.selection + 1
  503. } else {
  504. ic.selection = 0
  505. }
  506. return ic, ic.render
  507. case "k":
  508. if ic.selection != 0 {
  509. ic.selection = ic.selection - 1
  510. } else {
  511. ic.selection = len(ic.Collection) - 1
  512. }
  513. return ic, ic.render
  514. case "enter":
  515. ic.Path = ic.Collection[ic.selection].Path
  516. return ic, ic.sendLoad
  517. case "q":
  518. return ic, tea.Quit
  519. case "c":
  520. return ic, ic.newIssueInCollection
  521. }
  522. }
  523. return ic, nil
  524. }
  525. func (ic IssueCollection) sendLoad() tea.Msg { return loadPath(ic.Path) }
  526. func (ic IssueCollection) newIssueInCollection() tea.Msg { return createInCollectionMsg(ic.Path) }
  527. // render cmd for IssueCollection widget
  528. func (ic IssueCollection) render() tea.Msg {
  529. var output string
  530. if ic.selection == -1 {
  531. }
  532. var left string
  533. output = output + "Issues in " + ic.Path + "...\n\n"
  534. for i, issue := range ic.Collection {
  535. // pointer render
  536. if i == ic.selection {
  537. left = left + pointerStyle.Render("-> ")
  538. } else {
  539. left = left + pointerStyle.Render(" ")
  540. }
  541. // index render
  542. left = left + "[" + indexStyle.Render(fmt.Sprintf("%d", i+1)) + "]: "
  543. // title render
  544. left = left + fmt.Sprintf("%s\n", titleStyle.Render(issue.Title))
  545. }
  546. output = output + collectionStyleLeft.Render(left)
  547. return output
  548. }
  549. // keyhelp cmd for IssueCollection widget
  550. func (ic IssueCollection) keyhelp() string {
  551. var output string
  552. output = output + "\nj/k: down/up\t\tc: create new issue\t\tenter: select\t\tq/ctrl+c: quit"
  553. return output
  554. }
  555. // -------- createInCollection widget definitions -----------------------------
  556. // ----------------------------------------------------------------------------
  557. type createInCollection struct {
  558. Path string // base path for the new issue
  559. name string // the name input by the user
  560. input textinput.Model // the input widget
  561. }
  562. func (w createInCollection) update(msg tea.Msg) (widget, tea.Cmd) {
  563. var cmds []tea.Cmd
  564. switch msg := msg.(type) {
  565. case tea.KeyMsg:
  566. switch msg.String() {
  567. case "enter":
  568. cmds = append(cmds, w.create)
  569. }
  570. }
  571. var inputCmd tea.Cmd
  572. w.input, inputCmd = w.input.Update(msg)
  573. cmds = append(cmds, inputCmd)
  574. w.name = w.input.Value()
  575. return w, tea.Batch(cmds...)
  576. }
  577. func (w createInCollection) create() tea.Msg {
  578. w.Path = filepath.Join(w.Path, w.name)
  579. return newEditBlank(w.Path, "lorem ipsum")
  580. }
  581. func (w createInCollection) render() tea.Msg {
  582. return borderStyle.Render(fmt.Sprintf("Creating new issue in %s\ntitle: %s",
  583. w.Path, w.input.View()))
  584. }
  585. func (w createInCollection) keyhelp() string { return "enter: submit\t\tctrl+c: quit" }
  586. // tea.Cmd definitions --------------------------------------------------------
  587. // ----------------------------------------------------------------------------
  588. // Handles load logic
  589. func (m Model) load() tea.Msg {
  590. if IsIssue(m.Path) {
  591. issue, err := Issue{}.NewFromPath(m.Path)
  592. if err != nil {
  593. return nil
  594. }
  595. return issue
  596. }
  597. if IsIssueCollection(m.Path) {
  598. collection, err := IssueCollection{}.NewFromPath(m.Path)
  599. if err != nil {
  600. return nil
  601. }
  602. return collection
  603. }
  604. return newEditWidget(m.Path)
  605. }