tui.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. // The package defines an extensible TUI via the bubbletea framework.
  2. //
  3. // TODO enable collection recursing (i.e, embeded collections)
  4. //
  5. // TODO enable scroll/viewport logic
  6. //
  7. // While the package remains in v0.0.X releases, this TUI may be undocumented.
  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. // widget specifc keyhandling
  58. var cmds []tea.Cmd
  59. switch m.widget.(type) {
  60. case IssueCollection: // TODO handle updates to IssueCollection widgets in its own update func
  61. if msg, ok := msg.(tea.KeyMsg); ok {
  62. switch msg.String() {
  63. case "j":
  64. if collection, ok := m.widget.(IssueCollection); ok {
  65. if collection.selection+1 < len(collection.Collection) {
  66. collection.selection = collection.selection + 1
  67. } else {
  68. collection.selection = 0
  69. }
  70. m.widget = collection
  71. return m, collection.render
  72. }
  73. case "k":
  74. // do something only if widget is collection
  75. if collection, ok := m.widget.(IssueCollection); ok {
  76. if collection.selection != 0 {
  77. collection.selection = collection.selection - 1
  78. } else {
  79. collection.selection = len(collection.Collection) - 1
  80. }
  81. m.widget = collection
  82. return m, collection.render
  83. }
  84. case "enter":
  85. if _, ok := m.widget.(IssueCollection); ok {
  86. m.Path = m.widget.(IssueCollection).Collection[m.widget.(IssueCollection).selection].Path
  87. return m, m.load
  88. }
  89. case "q":
  90. cmds = append(cmds, tea.Quit)
  91. }
  92. }
  93. }
  94. // general message handling
  95. switch msg := msg.(type) {
  96. case tea.KeyMsg: // keymsg capture that is always present
  97. switch msg.String() {
  98. case "ctrl+c":
  99. cmds = append(cmds, tea.Quit)
  100. }
  101. case widget: // widget is initialized from m.load()
  102. switch T := msg.(type) {
  103. case create:
  104. m.widget = T
  105. cmds = append(cmds, T.render, T.init())
  106. default:
  107. m.widget = T
  108. cmds = append(cmds, T.render)
  109. }
  110. case string:
  111. m.content = msg
  112. }
  113. // finally, handle input updates if any
  114. if w, ok := m.widget.(create); ok {
  115. var cmd tea.Cmd
  116. m.widget, cmd = w.update(msg)
  117. cmds = append(cmds, cmd, w.render)
  118. }
  119. return m, tea.Batch(cmds...)
  120. }
  121. // Handles top level view functionality
  122. func (m Model) View() string {
  123. var output string
  124. if len(m.content) == 0 {
  125. return "loading..."
  126. }
  127. output = output + m.content
  128. output = output + lipgloss.NewStyle().Faint(true).Margin(1).Render(m.widget.keyhelp())
  129. return output
  130. }
  131. // WIDGET DEFINITIONS ---------------------------------------------------------
  132. // ----------------------------------------------------------------------------
  133. // interface definition for widgets
  134. type widget interface {
  135. render() tea.Msg // renders content
  136. keyhelp() string // renders key usage
  137. }
  138. // -------- creatIssue definitions --------------------------------------------
  139. // ----------------------------------------------------------------------------
  140. // TODO invoke editor for descriptions
  141. // TODO handle reset on esc
  142. // TODO handle errors and display gracefully
  143. // TODO implement description field in create.create
  144. // data struct for createIssue
  145. type inputField struct {
  146. input textinput.Model
  147. title string
  148. }
  149. // struct definition for create widget
  150. type create struct {
  151. inputFields []inputField
  152. Path string
  153. selected int
  154. Err error // not implemented
  155. }
  156. // constructor for create widget
  157. func initialCreateModel(path string, placeholder string) create {
  158. spawnInput := func(f bool) textinput.Model {
  159. ti := textinput.New()
  160. ti.Placeholder = placeholder
  161. if f {
  162. ti.Focus()
  163. }
  164. ti.CharLimit = 80
  165. ti.Width = 30
  166. return ti
  167. }
  168. var inputs []inputField
  169. for i, t := range [4]string{"title", "status", "tags", "blockers"} {
  170. if i == 0 {
  171. inputs = append(inputs, inputField{title: t, input: spawnInput(true)})
  172. } else {
  173. inputs = append(inputs, inputField{title: t, input: spawnInput(false)})
  174. }
  175. switch t {
  176. case "title":
  177. parsed := parsePathToHuman(path)
  178. if parsed == "." {
  179. parsed = ""
  180. }
  181. inputs[i].input.SetValue(parsed)
  182. case "status":
  183. inputs[i].input.SetValue("open")
  184. }
  185. }
  186. return create{
  187. inputFields: inputs,
  188. Path: path,
  189. selected: 0,
  190. Err: nil,
  191. }
  192. }
  193. // init cmd for create widget
  194. func (c create) init() tea.Cmd {
  195. return textinput.Blink
  196. }
  197. // update cmd for create widget
  198. func (c create) update(msg tea.Msg) (create, tea.Cmd) {
  199. var cmds []tea.Cmd
  200. var cmd tea.Cmd
  201. // simple anon funcs to increment the selected index
  202. incrementSelected := func() {
  203. if c.selected < len(c.inputFields) {
  204. c.selected++
  205. for i := 0; i < len(c.inputFields); i++ {
  206. if i == c.selected {
  207. c.inputFields[i].input.Focus()
  208. } else {
  209. c.inputFields[i].input.Blur()
  210. }
  211. }
  212. } else {
  213. c.selected = 0
  214. c.inputFields[c.selected].input.Focus()
  215. }
  216. }
  217. decrementSelected := func() {
  218. if c.selected != 0 {
  219. c.selected--
  220. for i := 0; i < len(c.inputFields); i++ {
  221. if i == c.selected {
  222. c.inputFields[i].input.Focus()
  223. } else {
  224. c.inputFields[i].input.Blur()
  225. }
  226. }
  227. } else {
  228. for i := 0; i < len(c.inputFields); i++ {
  229. c.inputFields[i].input.Blur()
  230. }
  231. c.selected = len(c.inputFields)
  232. }
  233. }
  234. switch msg := msg.(type) { // keybinding handler
  235. case tea.KeyMsg:
  236. switch msg.String() {
  237. case "tab":
  238. incrementSelected()
  239. case "shift+tab":
  240. decrementSelected()
  241. case "enter":
  242. if c.selected == len(c.inputFields) { // confirm create
  243. c.selected++
  244. } else if c.selected == len(c.inputFields)+1 { // confirmed
  245. cmds = append(cmds, c.create)
  246. } else {
  247. incrementSelected()
  248. }
  249. case "esc": // cancel
  250. cmds = append(cmds, tea.Quit)
  251. }
  252. case createResult:
  253. cmds = append(cmds, c.write(Issue(msg)))
  254. case writeResult:
  255. switch value := msg.(type) {
  256. case bool:
  257. if !value {
  258. } else {
  259. cmds = append(cmds, tea.Quit)
  260. }
  261. case error:
  262. panic(value)
  263. }
  264. }
  265. for i, ti := range c.inputFields {
  266. c.inputFields[i].input, cmd = ti.input.Update(msg)
  267. cmds = append(cmds, cmd)
  268. }
  269. cmds = append(cmds, cmd)
  270. return c, tea.Batch(cmds...)
  271. }
  272. // render cmd for create widget
  273. func (c create) render() tea.Msg {
  274. borderStyle := lipgloss.NewStyle().
  275. BorderStyle(lipgloss.NormalBorder()).
  276. Margin(1).
  277. Padding(0, 1)
  278. ulStyle := lipgloss.NewStyle().Underline(true)
  279. var output string
  280. for _, field := range c.inputFields {
  281. output = output + fmt.Sprintf(
  282. "\n%s:%s",
  283. field.title,
  284. borderStyle.Render(field.input.View()),
  285. )
  286. }
  287. output = strings.TrimLeft(output, "\n")
  288. if c.selected < len(c.inputFields) {
  289. output = output + borderStyle.Render("press enter to submit...")
  290. } else if c.selected == len(c.inputFields) {
  291. output = output + borderStyle.Render(ulStyle.Render("press enter to submit..."))
  292. } else if c.selected == len(c.inputFields)+1 {
  293. confirmPrompt := fmt.Sprintf(
  294. "create issue titled \"%s\"?\n\n%s",
  295. ulStyle.Render(c.inputFields[0].input.Value()),
  296. ulStyle.Render("press enter to confirm..."),
  297. )
  298. output = output + borderStyle.Render(confirmPrompt)
  299. }
  300. return output
  301. }
  302. // keyhelp cmd for create widget
  303. func (c create) keyhelp() string {
  304. var output string
  305. output = output + "\ntab/shift+tab: down/up\t\tenter: input value\t\tctrl+c: quit"
  306. return output
  307. }
  308. // -------- Issue widget definitions ------------------------------------------
  309. // ----------------------------------------------------------------------------
  310. // render cmd for Issue widget
  311. func (i Issue) render() tea.Msg {
  312. var output string
  313. // title
  314. output = output + titleStyle.Render(i.Title)
  315. // status
  316. output = output + fmt.Sprintf("\n%s", statusStyle.Render(i.Status.Data))
  317. // variadics
  318. var tags string
  319. for _, field := range i.Tags.Fields {
  320. tags = tags + field.Path + ", "
  321. }
  322. tags = strings.TrimRight(tags, ", ")
  323. var blockedby string
  324. for _, field := range i.Blockedby.Fields {
  325. blockedby = blockedby + field.Path + ", "
  326. }
  327. blockedby = strings.TrimRight(blockedby, ", ")
  328. if len(i.Tags.Fields) > 0 {
  329. output = output + variadicTitleStyle.Render("\n\nTags:")
  330. output = output + fmt.Sprintf("\n%s", variadicDataStyle.Render(tags))
  331. }
  332. if len(i.Blockedby.Fields) > 0 {
  333. output = output + variadicTitleStyle.Render("\n\nBlockedby:")
  334. output = output + fmt.Sprintf("\n%s", variadicDataStyle.Render(blockedby))
  335. }
  336. // description
  337. output = output + titleStyle.Render("\n\nDescription:\n")
  338. output = output + fmt.Sprintf("\n%s", i.Description.Data)
  339. return borderStyle.Render(output)
  340. }
  341. // keyhelp cmd for Issue widget
  342. func (i Issue) keyhelp() string {
  343. var output string
  344. output = output + "\nj/k: down/up\t\tq: quit"
  345. return output
  346. }
  347. // -------- IssueCollection widget definitions --------------------------------
  348. // ----------------------------------------------------------------------------
  349. // render cmd for IssueCollection widget
  350. func (ic IssueCollection) render() tea.Msg {
  351. var output string
  352. var left string
  353. output = output + "Issues in " + ic.Path + "...\n\n"
  354. for i, issue := range ic.Collection {
  355. // pointer render
  356. if i == ic.selection {
  357. left = left + pointerStyle.Render("-> ")
  358. } else {
  359. left = left + pointerStyle.Render(" ")
  360. }
  361. // index render
  362. left = left + "[" + indexStyle.Render(fmt.Sprintf("%d", i+1)) + "]: "
  363. // title render
  364. left = left + fmt.Sprintf("%s\n", titleStyle.Render(issue.Title))
  365. }
  366. output = output + collectionStyleLeft.Render(left)
  367. return output
  368. }
  369. // keyhelp cmd for IssueCollection widget
  370. func (ic IssueCollection) keyhelp() string {
  371. var output string
  372. output = output + "\nj/k: down/up\t\tenter: select\t\tq: quit"
  373. return output
  374. }
  375. // tea.Cmd definitions --------------------------------------------------------
  376. // ----------------------------------------------------------------------------
  377. // Handles load logic
  378. func (m Model) load() tea.Msg {
  379. if IsIssue(m.Path) {
  380. issue, err := Issue{}.NewFromPath(m.Path)
  381. if err != nil {
  382. return nil
  383. }
  384. return issue
  385. }
  386. if IsIssueCollection(m.Path) {
  387. collection, err := IssueCollection{}.NewFromPath(m.Path)
  388. if err != nil {
  389. return nil
  390. }
  391. return collection
  392. }
  393. return initialCreateModel(m.Path, "lorem ipsum")
  394. }
  395. // type wrapper for create.create() result
  396. type createResult Issue
  397. // A tea.Cmd to translate create.inputs to a new Issue object
  398. func (c create) create() tea.Msg {
  399. data := make(map[string]string)
  400. commaSplit := func(t string) []string {
  401. s := strings.Split(t, ",")
  402. for i, v := range s {
  403. s[i] = strings.TrimLeft(v, " \t\n")
  404. s[i] = strings.TrimRight(s[i], " \t\n")
  405. s[i] = parseHumanToPath(s[i])
  406. }
  407. return s
  408. }
  409. for _, field := range c.inputFields {
  410. data[field.title] = field.input.Value()
  411. }
  412. var newIssue = Issue{
  413. Path: c.Path,
  414. Tags: VariadicField{Path: "/tags"},
  415. Blockedby: VariadicField{Path: "/blockedby"},
  416. }
  417. for key, value := range data {
  418. switch key {
  419. case "title":
  420. newIssue.Title = value
  421. if parsePathToHuman(newIssue.Path) != value {
  422. dir, _ := filepath.Split(newIssue.Path)
  423. newIssue.Path = filepath.Join(dir, value)
  424. }
  425. case "status":
  426. newIssue.Status = Field{Path: "/status", Data: value}
  427. case "description":
  428. newIssue.Description = Field{Path: "/description", Data: value}
  429. case "tags":
  430. splitTags := commaSplit(value)
  431. for _, tag := range splitTags {
  432. newIssue.Tags.Fields = append(newIssue.Tags.Fields, Field{Path: tag})
  433. }
  434. case "blockers":
  435. splitBlockedby := commaSplit(value)
  436. for _, blocker := range splitBlockedby {
  437. newIssue.Blockedby.Fields = append(
  438. newIssue.Blockedby.Fields, Field{Path: blocker},
  439. )
  440. }
  441. }
  442. }
  443. return createResult(newIssue)
  444. }
  445. // type wrapper for create.write() result
  446. type writeResult any
  447. // Wraps a tea.Cmd func, passes an initialized Issue to WriteIssue()
  448. func (c create) write(issue Issue) tea.Cmd {
  449. return func() tea.Msg {
  450. result, err := WriteIssue(issue, false)
  451. if err != nil {
  452. return writeResult(err)
  453. }
  454. return writeResult(result)
  455. }
  456. }