glow/ui/stash.go

853 lines
22 KiB
Go
Raw Normal View History

package ui
import (
"errors"
2020-05-13 23:02:39 +00:00
"fmt"
"io/ioutil"
2020-08-18 19:41:57 +00:00
"log"
2020-05-19 00:45:13 +00:00
"math"
2020-05-13 23:02:39 +00:00
"sort"
"strings"
2020-05-19 00:45:13 +00:00
"time"
2020-05-13 23:02:39 +00:00
"github.com/charmbracelet/bubbles/paginator"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/charm"
"github.com/charmbracelet/charm/ui/common"
2020-05-19 00:45:13 +00:00
"github.com/dustin/go-humanize"
runewidth "github.com/mattn/go-runewidth"
"github.com/muesli/reflow/ansi"
2020-05-13 23:02:39 +00:00
te "github.com/muesli/termenv"
)
2020-05-15 00:23:11 +00:00
const (
stashIndent = 1
2020-05-22 02:29:46 +00:00
stashViewItemHeight = 3
2020-06-02 23:44:26 +00:00
stashViewTopPadding = 5
2020-05-22 02:29:46 +00:00
stashViewBottomPadding = 4
stashViewHorizontalPadding = 6
setNotePromptText = "Memo: "
2020-05-15 00:23:11 +00:00
)
var (
stashHelpItemStyle func(string) string = te.Style{}.Foreground(common.NewColorPair("#5C5C5C", "#9B9B9B").Color()).Styled
stashHelpDivider string = te.String(" • ").Foreground(common.NewColorPair("#3C3C3C", "#DDDADA").Color()).String()
)
// MSG
2020-05-22 19:31:54 +00:00
type fetchedMarkdownMsg *markdown
2020-05-15 22:34:42 +00:00
type deletedStashedItemMsg int
// MODEL
2020-05-22 02:29:46 +00:00
// markdownType allows us to differentiate between the types of markdown
// documents we're dealing with, namely stuff the user stashed versus news.
2020-05-21 19:14:33 +00:00
type markdownType int
const (
stashedMarkdown markdownType = iota
2020-05-21 19:14:33 +00:00
newsMarkdown
localMarkdown
2020-05-21 19:14:33 +00:00
)
// markdown wraps charm.Markdown so we can differentiate between stashed items
2020-05-22 02:29:46 +00:00
// and news.
2020-05-21 19:14:33 +00:00
type markdown struct {
markdownType markdownType
localPath string // only relevent to local files
2020-08-21 00:21:52 +00:00
charm.Markdown
2020-05-21 19:14:33 +00:00
}
// Sort documents with local files first, then by date
type markdownsByLocalFirst []*markdown
func (m markdownsByLocalFirst) Len() int { return len(m) }
func (m markdownsByLocalFirst) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
func (m markdownsByLocalFirst) Less(i, j int) bool {
iType := m[i].markdownType
jType := m[j].markdownType
// Local files come first
if iType == localMarkdown && jType != localMarkdown {
return true
}
if iType != localMarkdown && jType == localMarkdown {
return false
}
2020-05-21 19:14:33 +00:00
// If both are local files, sort by filename. Note that we should never
// hit equality here since two files can't have the same path.
if iType == localMarkdown && jType == localMarkdown {
return strings.Compare(m[i].localPath, m[j].localPath) == -1
}
// Neither are local files so sort by date descending
if !m[i].CreatedAt.Equal(m[j].CreatedAt) {
return m[i].CreatedAt.After(m[j].CreatedAt)
}
// If the timestamps also match, sort by ID.
return m[i].ID > m[j].ID
}
2020-05-21 19:14:33 +00:00
type loadedState byte
const (
loadedStash loadedState = 1 << iota
loadedNews
loadedLocalFiles
)
func (s loadedState) done() bool {
2020-08-13 19:37:53 +00:00
return s&loadedStash != 0 && s&loadedNews != 0 && s&loadedLocalFiles != 0
}
type stashState int
const (
stashStateReady stashState = iota
2020-05-15 22:34:42 +00:00
stashStatePromptDelete
2020-05-15 19:08:45 +00:00
stashStateLoadingDocument
2020-05-22 02:29:46 +00:00
stashStateSettingNote
stashStateShowingError
)
type stashModel struct {
cc *charm.Client
state stashState
err error
markdowns []*markdown
spinner spinner.Model
noteInput textinput.Model
terminalWidth int
terminalHeight int
stashFullyLoaded bool // have we loaded everything from the server?
loadingFromNetwork bool // are we currently loading something from the network?
loaded loadedState // what's loaded? we find out with bitmasking
2020-05-15 00:23:11 +00:00
2020-05-21 19:14:33 +00:00
// This is just the index of the current page in view. To get the index
// of the selected item as it relates to the full set of documents we've
// fetched use the mardownIndex() method of this struct.
index int
2020-05-15 00:23:11 +00:00
// This handles the local pagination, which is different than the page
// we're fetching from on the server side
paginator paginator.Model
2020-05-21 19:14:33 +00:00
// Page we're fetching stash items from on the server, which is different
// from the local pagination. Generally, the server will return more items
// than we can display at a time so we can paginate locally without having
// to fetch every time.
2020-05-15 00:23:11 +00:00
page int
2020-08-21 17:39:59 +00:00
showStatusMessage bool
statusMessage string
statusMessageTimer *time.Timer
2020-05-15 00:23:11 +00:00
}
func (m *stashModel) setSize(width, height int) {
2020-05-15 00:23:11 +00:00
m.terminalWidth = width
m.terminalHeight = height
// Update the paginator
perPage := max(1, (m.terminalHeight-stashViewTopPadding-stashViewBottomPadding)/stashViewItemHeight)
2020-05-15 00:23:11 +00:00
m.paginator.PerPage = perPage
2020-05-22 22:42:18 +00:00
m.paginator.SetTotalPages(len(m.markdowns))
2020-05-22 02:29:46 +00:00
m.noteInput.Width = m.terminalWidth - stashViewHorizontalPadding*2 - len(setNotePromptText)
// Make sure the page stays in bounds
if m.paginator.Page >= m.paginator.TotalPages-1 {
m.paginator.Page = max(0, m.paginator.TotalPages-1)
}
}
2020-05-21 19:14:33 +00:00
// markdownIndex returns the index of the currently selected markdown item.
func (m stashModel) markdownIndex() int {
return m.paginator.Page*m.paginator.PerPage + m.index
}
2020-05-22 20:28:15 +00:00
// return the current selected markdown in the stash
func (m stashModel) selectedMarkdown() *markdown {
i := m.markdownIndex()
if i < 0 || len(m.markdowns) == 0 || len(m.markdowns) <= i {
return nil
}
return m.markdowns[i]
2020-05-22 20:28:15 +00:00
}
2020-08-13 19:37:53 +00:00
// adds markdown documents to the model
2020-05-22 20:01:23 +00:00
func (m *stashModel) addMarkdowns(mds ...*markdown) {
if len(mds) > 0 {
m.markdowns = append(m.markdowns, mds...)
sort.Sort(markdownsByLocalFirst(m.markdowns))
m.paginator.SetTotalPages(len(m.markdowns))
}
2020-05-22 20:01:23 +00:00
}
2020-08-13 19:37:53 +00:00
// return the number of markdown documents of a given type
func (m stashModel) countMarkdowns(t markdownType) (found int) {
if len(m.markdowns) == 0 {
return
}
for i := 0; i < len(m.markdowns); i++ {
if m.markdowns[i].markdownType == t {
found++
}
}
return
}
2020-08-21 17:39:59 +00:00
func (m *stashModel) hideStatusMessage() {
m.showStatusMessage = false
if m.statusMessageTimer != nil {
m.statusMessageTimer.Stop()
}
}
// INIT
func newStashModel() stashModel {
s := spinner.NewModel()
s.Frames = spinner.Line
s.ForegroundColor = common.SpinnerColor.String()
2020-05-15 00:52:25 +00:00
p := paginator.NewModel()
p.Type = paginator.Dots
p.InactiveDot = common.Subtle("•")
2020-05-22 02:29:46 +00:00
ni := textinput.NewModel()
ni.Prompt = te.String(setNotePromptText).Foreground(common.YellowGreen.Color()).String()
ni.CursorColor = common.Fuschia.String()
2020-05-22 22:42:18 +00:00
ni.CharLimit = noteCharacterLimit
2020-05-22 02:29:46 +00:00
ni.Focus()
m := stashModel{
spinner: s,
noteInput: ni,
page: 1,
paginator: p,
loadingFromNetwork: true,
}
return m
}
// UPDATE
func stashUpdate(msg tea.Msg, m stashModel) (stashModel, tea.Cmd) {
var cmds []tea.Cmd
2020-05-15 00:52:25 +00:00
switch msg := msg.(type) {
case errMsg:
m.err = msg
case stashLoadErrMsg:
m.err = msg.err
m.loaded |= loadedStash // still done, albeit unsuccessfully
m.stashFullyLoaded = true
m.loadingFromNetwork = false
case newsLoadErrMsg:
m.err = msg.err
m.loaded |= loadedNews // still done, albeit unsuccessfully
// We're finished searching for local files
case localFileSearchFinished:
m.loaded |= loadedLocalFiles
// Stash results have come in from the server
case gotStashMsg:
// This doesn't mean the whole stash listing is loaded, but some we've
// finished checking for the stash, at least, so mark the stash as
// loaded here.
m.loaded |= loadedStash
m.loadingFromNetwork = false
if len(msg) == 0 {
// If the server comes back with nothing then we've got everything
m.stashFullyLoaded = true
} else {
docs := wrapMarkdowns(stashedMarkdown, msg)
m.addMarkdowns(docs...)
}
// News has come in from the server
2020-05-21 19:14:33 +00:00
case gotNewsMsg:
m.loaded |= loadedNews
if len(msg) > 0 {
docs := wrapMarkdowns(newsMarkdown, msg)
2020-05-22 20:01:23 +00:00
m.addMarkdowns(docs...)
2020-05-21 19:14:33 +00:00
}
case spinner.TickMsg:
if !m.loaded.done() || m.loadingFromNetwork || m.state == stashStateLoadingDocument {
newSpinnerModel, cmd := spinner.Update(msg, m.spinner)
m.spinner = newSpinnerModel
2020-05-15 22:39:23 +00:00
cmds = append(cmds, cmd)
}
// A note was set on a document. This may have happened in the pager so
2020-05-22 02:29:46 +00:00
// we'll find the corresponding document here and update accordingly.
case noteSavedMsg:
2020-05-22 22:42:18 +00:00
for i := range m.markdowns {
if m.markdowns[i].ID == msg.ID {
m.markdowns[i].Note = msg.Note
}
}
2020-08-21 17:39:59 +00:00
// Something was stashed. Add it to the stash listing.
case stashSuccessMsg:
md := markdown(msg)
m.addMarkdowns(&md)
m.showStatusMessage = true
m.statusMessage = "Stashed!"
if m.statusMessageTimer != nil {
m.statusMessageTimer.Stop()
}
m.statusMessageTimer = time.NewTimer(time.Second * 3)
cmds = append(cmds, waitForStatusMessageTimeout(stashContext, m.statusMessageTimer))
case statusMessageTimeoutMsg:
if applicationContext(msg) == stashContext {
m.hideStatusMessage()
}
}
2020-05-22 02:29:46 +00:00
switch m.state {
case stashStateReady:
2020-07-16 19:37:48 +00:00
2020-08-21 17:39:59 +00:00
switch msg := msg.(type) {
2020-07-16 19:37:48 +00:00
// Handle keys
2020-08-21 17:39:59 +00:00
case tea.KeyMsg:
switch msg.String() {
case "k", "up":
m.index--
if m.index < 0 && m.paginator.Page == 0 {
// Stop
m.index = 0
} else if m.index < 0 {
// Go to previous page
m.paginator.PrevPage()
2020-05-22 22:42:18 +00:00
m.index = m.paginator.ItemsOnPage(len(m.markdowns)) - 1
}
case "j", "down":
2020-05-22 22:42:18 +00:00
itemsOnPage := m.paginator.ItemsOnPage(len(m.markdowns))
m.index++
if m.index >= itemsOnPage && m.paginator.OnLastPage() {
// Stop
m.index = itemsOnPage - 1
} else if m.index >= itemsOnPage {
// Go to next page
m.index = 0
m.paginator.NextPage()
}
// Open document
case "enter":
2020-08-21 17:39:59 +00:00
m.hideStatusMessage()
if len(m.markdowns) == 0 {
break
}
// Load the document from the server. We'll handle the message
// that comes back in the main update function.
m.state = stashStateLoadingDocument
2020-05-22 20:28:15 +00:00
md := m.selectedMarkdown()
2020-05-22 19:31:54 +00:00
if md.markdownType == localMarkdown {
cmds = append(cmds, loadLocalMarkdown(md))
} else {
cmds = append(cmds, loadRemoteMarkdown(m.cc, md.ID, md.markdownType))
}
cmds = append(cmds, spinner.Tick(m.spinner))
// Set note
case "m":
2020-08-21 17:39:59 +00:00
m.hideStatusMessage()
2020-05-22 20:28:15 +00:00
md := m.selectedMarkdown()
isUserMarkdown := md.markdownType == stashedMarkdown
2020-05-22 20:28:15 +00:00
isSettingNote := m.state == stashStateSettingNote
isPromptingDelete := m.state == stashStatePromptDelete
if isUserMarkdown && !isSettingNote && !isPromptingDelete {
m.state = stashStateSettingNote
2020-05-22 20:28:15 +00:00
m.noteInput.SetValue(md.Note)
m.noteInput.CursorEnd()
return m, textinput.Blink(m.noteInput)
}
2020-08-21 17:39:59 +00:00
// Stash
case "s":
md := m.selectedMarkdown()
if md != nil && md.markdownType == localMarkdown {
cmds = append(cmds, stashDocument(m.cc, *md))
}
// Prompt for deletion
case "x":
2020-08-21 17:39:59 +00:00
m.hideStatusMessage()
isUserMarkdown := m.selectedMarkdown().markdownType == stashedMarkdown
isValidState := m.state != stashStateSettingNote
2020-05-22 20:28:15 +00:00
if isUserMarkdown && isValidState {
m.state = stashStatePromptDelete
}
2020-08-13 19:37:53 +00:00
// Show errors
2020-07-16 20:51:44 +00:00
case "!":
if m.err != nil && m.state == stashStateReady {
m.state = stashStateShowingError
2020-07-16 19:37:48 +00:00
return m, nil
}
}
}
// Update paginator. Pagination key handling is done here, but it could
// also be moved up to this level, in which case we'd use model methods
// like model.PageUp().
newPaginatorModel, cmd := paginator.Update(msg, m.paginator)
m.paginator = newPaginatorModel
2020-05-15 00:52:25 +00:00
cmds = append(cmds, cmd)
// Extra paginator keystrokes
if key, ok := msg.(tea.KeyMsg); ok {
if key.Type == tea.KeyRune {
switch key.Rune {
case 'b', 'u':
m.paginator.PrevPage()
case 'f', 'd':
m.paginator.NextPage()
}
}
}
// Keep the index in bounds when paginating
2020-05-22 22:42:18 +00:00
itemsOnPage := m.paginator.ItemsOnPage(len(m.markdowns))
if m.index > itemsOnPage-1 {
m.index = max(0, itemsOnPage-1)
}
// If we're on the last page and we haven't loaded everything, get
// more stuff.
if m.paginator.OnLastPage() && !m.loadingFromNetwork && !m.stashFullyLoaded {
m.page++
m.loadingFromNetwork = true
cmds = append(cmds, loadStash(m))
}
case stashStatePromptDelete:
if msg, ok := msg.(tea.KeyMsg); ok {
switch msg.String() {
// Confirm deletion
case "y":
if m.state != stashStatePromptDelete {
break
}
i := m.markdownIndex()
2020-05-22 22:42:18 +00:00
id := m.markdowns[i].ID
// Delete optimistically and remove the stashed item
// before we've received a success response.
2020-05-22 22:42:18 +00:00
m.markdowns = append(m.markdowns[:i], m.markdowns[i+1:]...)
// Update pagination
2020-05-22 22:42:18 +00:00
m.paginator.SetTotalPages(len(m.markdowns))
m.paginator.Page = min(m.paginator.Page, m.paginator.TotalPages-1)
// Set state and delete
m.state = stashStateReady
return m, deleteStashedItem(m.cc, id)
default:
m.state = stashStateReady
}
}
2020-05-22 02:29:46 +00:00
case stashStateSettingNote:
if msg, ok := msg.(tea.KeyMsg); ok {
2020-05-22 02:29:46 +00:00
switch msg.String() {
case "esc":
// Cancel note
m.state = stashStateReady
m.noteInput.Reset()
case "enter":
// Set new note
2020-05-22 22:42:18 +00:00
md := m.selectedMarkdown()
2020-05-22 02:29:46 +00:00
newNote := m.noteInput.Value()
cmd := saveDocumentNote(m.cc, md.ID, newNote)
2020-05-22 22:42:18 +00:00
md.Note = newNote
2020-05-22 02:29:46 +00:00
m.noteInput.Reset()
m.state = stashStateReady
return m, cmd
}
}
// Update the text input component used to set notes
newNoteInputModel, cmd := textinput.Update(msg, m.noteInput)
m.noteInput = newNoteInputModel
2020-05-22 02:29:46 +00:00
cmds = append(cmds, cmd)
case stashStateShowingError:
// Any key exists the error view
if _, ok := msg.(tea.KeyMsg); ok {
m.state = stashStateReady
}
2020-05-15 00:52:25 +00:00
}
2020-05-15 22:34:42 +00:00
// If an item is being confirmed for delete, any key (other than the key
// used for confirmation above) cancels the deletion
return m, tea.Batch(cmds...)
}
// VIEW
func stashView(m stashModel) string {
2020-07-16 19:37:48 +00:00
var s string
2020-05-13 23:02:39 +00:00
switch m.state {
case stashStateShowingError:
return errorView(m.err, false)
2020-05-15 19:08:45 +00:00
case stashStateLoadingDocument:
s += " " + spinner.View(m.spinner) + " Loading document..."
case stashStateReady, stashStateSettingNote, stashStatePromptDelete:
loadingIndicator := ""
if !m.loaded.done() || m.loadingFromNetwork {
loadingIndicator = spinner.View(m.spinner)
}
2020-05-21 19:14:33 +00:00
// We need to fill any empty height with newlines so the footer reaches
// the bottom.
2020-06-02 23:44:26 +00:00
numBlankLines := max(0, (m.terminalHeight-stashViewTopPadding-stashViewBottomPadding)%stashViewItemHeight)
2020-05-15 00:23:11 +00:00
blankLines := ""
if numBlankLines > 0 {
blankLines = strings.Repeat("\n", numBlankLines)
}
2020-08-13 19:37:53 +00:00
var header string
2020-08-21 17:39:59 +00:00
if m.showStatusMessage {
header = greenFg(m.statusMessage)
} else {
switch m.state {
case stashStatePromptDelete:
header = redFg("Delete this item? ") + faintRedFg("(y/N)")
case stashStateSettingNote:
header = yellowFg("Set the memo for this item?")
}
2020-05-15 22:34:42 +00:00
}
// Only draw the normal header if we're not using the header area for
// something else (like a prompt)
if header == "" {
header = stashHeaderView(m)
}
var pagination string
if m.paginator.TotalPages > 1 {
pagination = paginator.View(m.paginator)
// If the dot pagination is wider than the width of the window
// switch to the arabic paginator.
if ansi.PrintableRuneWidth(pagination) > m.terminalWidth-stashViewHorizontalPadding {
m.paginator.Type = paginator.Arabic
pagination = common.Subtle(paginator.View(m.paginator))
}
// We could also look at m.stashFullyLoaded and add an indicator
// showing that we don't actually know how many more pages there
// are.
}
2020-05-15 00:52:25 +00:00
s += fmt.Sprintf(
" %s %s\n\n %s\n\n%s\n\n%s %s\n\n %s",
2020-05-15 01:12:13 +00:00
glowLogoView(" Glow "),
loadingIndicator,
2020-05-15 22:34:42 +00:00
header,
2020-06-02 23:44:26 +00:00
stashPopulatedView(m),
2020-05-15 01:12:13 +00:00
blankLines,
pagination,
2020-05-21 19:14:33 +00:00
stashHelpView(m),
2020-05-15 00:52:25 +00:00
)
2020-05-13 23:02:39 +00:00
}
return "\n" + indent(s, stashIndent)
2020-05-13 23:02:39 +00:00
}
func glowLogoView(text string) string {
return te.String(text).
Bold().
Foreground(glowLogoTextColor).
Background(common.Fuschia.Color()).
String()
}
func stashHeaderView(m stashModel) string {
loading := !m.loaded.done()
noMarkdowns := len(m.markdowns) == 0
// Still loading. We haven't found files, stashed items, or news yet.
if loading && noMarkdowns {
return common.Subtle("Looking for stuff...")
}
localItems := m.countMarkdowns(localMarkdown)
stashedItems := m.countMarkdowns(stashedMarkdown)
// Loading's finished and all we have is news.
if !loading && localItems == 0 && stashedItems == 0 {
return common.Subtle("No local or stashed markdown files found.")
}
// There are local and/or stashed files, so display counts.
var s string
if localItems > 0 {
s += fmt.Sprintf("%d Local", localItems)
}
if stashedItems > 0 {
var divider string
if localItems > 0 {
divider = " • "
}
s += fmt.Sprintf("%s%d Stashed", divider, stashedItems)
}
return common.Subtle(s)
2020-05-13 23:02:39 +00:00
}
func stashPopulatedView(m stashModel) string {
var b strings.Builder
2020-05-15 00:52:25 +00:00
2020-06-02 23:44:26 +00:00
if len(m.markdowns) > 0 {
start, end := m.paginator.GetSliceBounds(len(m.markdowns))
docs := m.markdowns[start:end]
2020-05-15 00:23:11 +00:00
2020-06-02 23:44:26 +00:00
for i, md := range docs {
stashItemView(&b, m, i, md)
if i != len(docs)-1 {
fmt.Fprintf(&b, "\n\n")
}
}
2020-05-13 23:02:39 +00:00
}
2020-05-15 00:52:25 +00:00
// If there aren't enough items to fill up this page (always the last page)
2020-06-02 23:44:26 +00:00
// then we need to add some newlines to fill up the space where stash items
// would have been.
2020-05-22 22:42:18 +00:00
itemsOnPage := m.paginator.ItemsOnPage(len(m.markdowns))
2020-05-15 00:52:25 +00:00
if itemsOnPage < m.paginator.PerPage {
n := (m.paginator.PerPage - itemsOnPage) * stashViewItemHeight
2020-06-02 23:44:26 +00:00
if len(m.markdowns) == 0 {
n -= stashViewItemHeight - 1
}
for i := 0; i < n; i++ {
fmt.Fprint(&b, "\n")
}
2020-05-15 00:52:25 +00:00
}
return b.String()
2020-05-15 00:23:11 +00:00
}
2020-05-21 19:14:33 +00:00
func stashHelpView(m stashModel) string {
var (
h []string
isStashed bool
2020-08-21 17:39:59 +00:00
isLocal bool
2020-05-21 19:14:33 +00:00
)
if len(m.markdowns) > 0 {
md := m.selectedMarkdown()
isStashed = md != nil && md.markdownType == stashedMarkdown
2020-08-21 17:39:59 +00:00
isLocal = md != nil && md.markdownType == localMarkdown
}
2020-05-22 02:29:46 +00:00
if m.state == stashStateSettingNote {
h = append(h, "enter: confirm", "esc: cancel")
} else if m.state == stashStatePromptDelete {
2020-05-15 22:34:42 +00:00
h = append(h, "y: delete", "n: cancel")
} else {
2020-05-22 22:42:18 +00:00
if len(m.markdowns) > 0 {
h = append(h, "enter: open")
}
if len(m.markdowns) > 1 {
2020-05-15 22:34:42 +00:00
h = append(h, "j/k, ↑/↓: choose")
}
if m.paginator.TotalPages > 1 {
h = append(h, "h/l, ←/→: page")
}
2020-08-21 17:39:59 +00:00
if isStashed {
h = append(h, []string{"x: delete", "m: set memo"}...)
2020-08-21 17:39:59 +00:00
} else if isLocal {
h = append(h, "s: stash")
2020-05-21 19:14:33 +00:00
}
2020-07-16 19:37:48 +00:00
if m.err != nil {
2020-08-21 17:39:59 +00:00
h = append(h, "!: errors")
2020-07-16 19:37:48 +00:00
}
2020-08-21 17:39:59 +00:00
h = append(h, "q: quit")
2020-05-15 00:23:11 +00:00
}
return stashHelpViewBuilder(m.terminalWidth, h...)
}
2020-08-13 19:37:53 +00:00
// builds the help view from various sections pieces, truncating it if the view
// would otherwise wrap to two lines.
func stashHelpViewBuilder(windowWidth int, sections ...string) string {
if len(sections) == 0 {
return ""
}
const truncationWidth = 1 // width of "…"
var (
s string
next string
maxWidth = windowWidth - stashViewHorizontalPadding - truncationWidth
)
for i := 0; i < len(sections); i++ {
// If we need this more often we'll formalize something rather than
// use an if clause/switch here.
switch sections[i] {
case "s: stash":
next = greenFg(sections[i])
default:
next = stashHelpItemStyle(sections[i])
}
if i < len(sections)-1 {
next += stashHelpDivider
}
// Only this (and the following) help text items if we have the
// horizontal space
if ansi.PrintableRuneWidth(s)+ansi.PrintableRuneWidth(next) >= maxWidth {
s += common.Subtle("…")
break
}
s += next
}
return s
2020-05-13 23:02:39 +00:00
}
// CMD
func loadRemoteMarkdown(cc *charm.Client, id int, t markdownType) tea.Cmd {
return func() tea.Msg {
2020-05-22 19:31:54 +00:00
var (
md *charm.Markdown
err error
)
if t == stashedMarkdown {
2020-05-22 19:31:54 +00:00
md, err = cc.GetStashMarkdown(id)
} else {
md, err = cc.GetNewsMarkdown(id)
}
2020-05-21 19:14:33 +00:00
if err != nil {
2020-08-18 19:41:57 +00:00
if debug {
log.Println("error loading remote markdown:", err)
}
return errMsg(err)
2020-05-21 19:14:33 +00:00
}
2020-05-22 19:31:54 +00:00
return fetchedMarkdownMsg(&markdown{
2020-05-22 20:28:15 +00:00
markdownType: t,
2020-08-21 00:21:52 +00:00
Markdown: *md,
2020-05-21 19:14:33 +00:00
})
2020-05-14 02:08:17 +00:00
}
}
2020-05-15 22:34:42 +00:00
func loadLocalMarkdown(md *markdown) tea.Cmd {
return func() tea.Msg {
if md.markdownType != localMarkdown {
return errMsg(errors.New("could not load local file: not a local file"))
}
if md.localPath == "" {
return errMsg(errors.New("could not load file: missing path"))
}
data, err := ioutil.ReadFile(md.localPath)
if err != nil {
2020-08-18 19:41:57 +00:00
if debug {
log.Println("error reading local markdown:", err)
}
return errMsg(err)
}
md.Body = string(data)
return fetchedMarkdownMsg(md)
}
}
func deleteStashedItem(cc *charm.Client, id int) tea.Cmd {
return func() tea.Msg {
2020-05-15 22:34:42 +00:00
err := cc.DeleteMarkdown(id)
if err != nil {
return errMsg(err)
2020-05-15 22:34:42 +00:00
}
return deletedStashedItemMsg(id)
}
}
2020-05-18 20:08:49 +00:00
// ETC
2020-05-22 02:29:46 +00:00
// wrapMarkdowns wraps a *charm.Markdown with a *markdown in order to add some
// extra metadata.
2020-05-21 19:14:33 +00:00
func wrapMarkdowns(t markdownType, md []*charm.Markdown) (m []*markdown) {
for _, v := range md {
m = append(m, &markdown{
markdownType: t,
2020-08-21 00:21:52 +00:00
Markdown: *v,
2020-05-21 19:14:33 +00:00
})
}
return m
}
2020-05-18 20:08:49 +00:00
func truncate(str string, num int) string {
return runewidth.Truncate(str, num, "…")
2020-05-18 20:08:49 +00:00
}
2020-05-19 00:45:13 +00:00
var magnitudes = []humanize.RelTimeMagnitude{
{D: time.Second, Format: "now", DivBy: time.Second},
{D: 2 * time.Second, Format: "1 second %s", DivBy: 1},
{D: time.Minute, Format: "%d seconds %s", DivBy: time.Second},
{D: 2 * time.Minute, Format: "1 minute %s", DivBy: 1},
{D: time.Hour, Format: "%d minutes %s", DivBy: time.Minute},
{D: 2 * time.Hour, Format: "1 hour %s", DivBy: 1},
{D: humanize.Day, Format: "%d hours %s", DivBy: time.Hour},
{D: 2 * humanize.Day, Format: "1 day %s", DivBy: 1},
{D: humanize.Week, Format: "%d days %s", DivBy: humanize.Day},
{D: 2 * humanize.Week, Format: "1 week %s", DivBy: 1},
{D: humanize.Month, Format: "%d weeks %s", DivBy: humanize.Week},
{D: 2 * humanize.Month, Format: "1 month %s", DivBy: 1},
{D: humanize.Year, Format: "%d months %s", DivBy: humanize.Month},
{D: 18 * humanize.Month, Format: "1 year %s", DivBy: 1},
{D: 2 * humanize.Year, Format: "2 years %s", DivBy: 1},
{D: humanize.LongTime, Format: "%d years %s", DivBy: humanize.Year},
{D: math.MaxInt64, Format: "a long while %s", DivBy: 1},
}
func relativeTime(then time.Time) string {
now := time.Now()
if now.Sub(then) < humanize.Week {
return humanize.CustomRelTime(then, now, "ago", "from now", magnitudes)
}
return then.Format("02 Jan 2006 15:04 MST")
}