mirror of
https://github.com/Maks1mS/bubbles.git
synced 2025-10-18 16:38:56 +03:00
Compare commits
41 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
1d489252fe | ||
|
06358c35f9 | ||
|
005233b529 | ||
|
18d25458da | ||
|
db97ac515d | ||
|
200f95759b | ||
|
7ecce3fb97 | ||
|
746834a7ce | ||
|
fd306528f9 | ||
|
a4dc540f3d | ||
|
151d1026dd | ||
|
daba232df4 | ||
|
7a6d306889 | ||
|
6c015a2aa8 | ||
|
764fd321f6 | ||
|
091c915462 | ||
|
505a16d057 | ||
|
465a66e963 | ||
|
7a728eae31 | ||
|
c426cb580b | ||
|
48e3f85baf | ||
|
5f256bf34f | ||
|
eef9098f37 | ||
|
b35f96cd2d | ||
|
9401ebbb83 | ||
|
add13c8028 | ||
|
4aed4e0a88 | ||
|
9c70b6a216 | ||
|
9d74635ea3 | ||
|
e01ee1d17e | ||
|
e83c113d06 | ||
|
94b84b6120 | ||
|
f09987549a | ||
|
7b20f4fe24 | ||
|
86e0c53e88 | ||
|
8d3cfdf380 | ||
|
0f500d5e59 | ||
|
0ac5ecdf81 | ||
|
8c03905dbe | ||
|
a7ea1bddbf | ||
|
7941c49504 |
12
.github/workflows/soft-serve.yml
vendored
Normal file
12
.github/workflows/soft-serve.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
name: soft-serve
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
soft-serve:
|
||||
uses: charmbracelet/meta/.github/workflows/soft-serve.yml@main
|
||||
secrets:
|
||||
ssh-key: "${{ secrets.CHARM_SOFT_SERVE_KEY }}"
|
37
README.md
37
README.md
@@ -71,7 +71,7 @@ logic and visualize pagination however you like.
|
||||
|
||||
## Viewport
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif" width="600" alt="Viewport Example">
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif?0" width="600" alt="Viewport Example">
|
||||
|
||||
A viewport for vertically scrolling content. Optionally includes standard
|
||||
pager keybindings and mouse wheel support. A high performance mode is available
|
||||
@@ -79,7 +79,7 @@ for applications which make use of the alternate screen buffer.
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/tea/tree/master/examples/pager/main.go)
|
||||
|
||||
This component is well complimented with [Reflow][reflow] for ANSI-aware
|
||||
This component is well complemented with [Reflow][reflow] for ANSI-aware
|
||||
indenting and text wrapping.
|
||||
|
||||
[reflow]: https://github.com/muesli/reflow
|
||||
@@ -99,6 +99,26 @@ Extrapolated from [Glow][glow].
|
||||
* [Example code, all features](https://github.com/charmbracelet/tea/tree/master/examples/list-fancy/main.go)
|
||||
|
||||
|
||||
## Timer
|
||||
|
||||
A simple, flexible component for counting down. The update frequency and output
|
||||
can be customized as you like.
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/timer.gif" width="400" alt="Timer example">
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/timer/main.go)
|
||||
|
||||
|
||||
## Stopwatch
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/stopwatch.gif" width="400" alt="Stopwatch example">
|
||||
|
||||
A simple, flexible component for counting up. The update frequency and output
|
||||
can be customized as you see fit.
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/stopwatch/main.go)
|
||||
|
||||
|
||||
## Help
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/help.gif" width="500" alt="Help Example">
|
||||
@@ -129,8 +149,8 @@ var DefaultKeyMap = KeyMap{
|
||||
key.WithHelp("↑/k", "move up"), // corresponding help text
|
||||
),
|
||||
Down: key.NewBinding(
|
||||
WithKeys("j", "down"),
|
||||
WithHelp("↓/j", "move down"),
|
||||
key.WithKeys("j", "down"),
|
||||
key.WithHelp("↓/j", "move down"),
|
||||
),
|
||||
}
|
||||
|
||||
@@ -158,6 +178,11 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
* [mritd/bubbles](https://github.com/mritd/bubbles): Some general-purpose
|
||||
bubbles. Inputs with validation, menu selection, a modified progressbar, and
|
||||
so on.
|
||||
* [bubblelister](https://github.com/treilik/bubblelister): An alternate list
|
||||
that is scrollable without pagination and has the ability to contain other
|
||||
bubbles as list items.
|
||||
* [bubbleboxer](https://github.com/treilik/bubbleboxer): Layout multiple bubbles
|
||||
side-by-side in a layout-tree.
|
||||
|
||||
If you’ve built a Bubble you think should be listed here,
|
||||
[let us know](mailto:vt100@charm.sh).
|
||||
@@ -172,6 +197,8 @@ If you’ve built a Bubble you think should be listed here,
|
||||
|
||||
Part of [Charm](https://charm.sh).
|
||||
|
||||
<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge-unrounded.jpg" width="400"></a>
|
||||
<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>
|
||||
|
||||
Charm热爱开源 • Charm loves open source
|
||||
|
||||
[charm]: https://charm.sh/
|
||||
|
6
go.mod
6
go.mod
@@ -3,10 +3,10 @@ module github.com/charmbracelet/bubbles
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/atotto/clipboard v0.1.2
|
||||
github.com/charmbracelet/bubbletea v0.14.1
|
||||
github.com/atotto/clipboard v0.1.4
|
||||
github.com/charmbracelet/bubbletea v0.19.3
|
||||
github.com/charmbracelet/harmonica v0.1.0
|
||||
github.com/charmbracelet/lipgloss v0.3.0
|
||||
github.com/charmbracelet/lipgloss v0.4.0
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0
|
||||
github.com/mattn/go-runewidth v0.0.13
|
||||
|
24
go.sum
24
go.sum
@@ -1,28 +1,28 @@
|
||||
github.com/atotto/clipboard v0.1.2 h1:YZCtFu5Ie8qX2VmVTBnrqLSiU9XOWwqNRmdT3gIQzbY=
|
||||
github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/charmbracelet/bubbletea v0.14.1 h1:pD/bM5LBEH/nDo7nKcgNUgi4uRHQhpWTIHZbG5vuSlc=
|
||||
github.com/charmbracelet/bubbletea v0.14.1/go.mod h1:b5lOf5mLjMg1tRn1HVla54guZB+jvsyV0yYAQja95zE=
|
||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/charmbracelet/bubbletea v0.19.3 h1:OKeO/Y13rQQqt4snX+lePB0QrnW80UdrMNolnCcmoAw=
|
||||
github.com/charmbracelet/bubbletea v0.19.3/go.mod h1:VuXF2pToRxDUHcBUcPmCRUHRvFATM4Ckb/ql1rBl3KA=
|
||||
github.com/charmbracelet/harmonica v0.1.0 h1:lFKeSd6OAckQ/CEzPVd2mqj+YMEubQ/3FM2IYY3xNm0=
|
||||
github.com/charmbracelet/harmonica v0.1.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
|
||||
github.com/charmbracelet/lipgloss v0.3.0 h1:5MysOD6sHr4RP4jkZNWGVIul5GKoOsP12NgbgXPvAlA=
|
||||
github.com/charmbracelet/lipgloss v0.3.0/go.mod h1:VkhdBS2eNAmRkTwRKLJCFhCOVkjntMusBDxv7TXahuk=
|
||||
github.com/containerd/console v1.0.1 h1:u7SFAJyRqWcG6ogaMAx3KjSTy1e3hT9QxqX7Jco7dRc=
|
||||
github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw=
|
||||
github.com/charmbracelet/lipgloss v0.4.0 h1:768h64EFkGUr8V5yAKV7/Ta0NiVceiPaV+PphaW1K9g=
|
||||
github.com/charmbracelet/lipgloss v0.4.0/go.mod h1:vmdkHvce7UzX6xkyf4cca8WlwdQ5RQr8fzta+xl7BOM=
|
||||
github.com/containerd/console v1.0.2 h1:Pi6D+aZXM+oUw1czuKgH5IJ+y0jhYcwBJfx5/Ghn9dE=
|
||||
github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA=
|
||||
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
|
||||
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
|
||||
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ=
|
||||
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
|
||||
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
|
||||
github.com/muesli/termenv v0.8.1/go.mod h1:kzt/D/4a88RoheZmwfqorY3A+tnsSMA9HJC/fQSFKo0=
|
||||
github.com/muesli/termenv v0.9.0 h1:wnbOaGz+LUR3jNT0zOzinPnyDaCZUQRZj9GxK8eRVl8=
|
||||
github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
@@ -36,9 +36,9 @@ github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ
|
||||
github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
|
||||
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200916030750-2334cc1a136f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4 h1:myAQVi0cGEoqQVR5POX+8RR2mrocKqNN1hmeMqhX27k=
|
||||
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed h1:Ei4bQjjpYUsS4efOUz+5Nz++IVkHk87n2zBA0NxBWc0=
|
||||
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
|
16
help/help.go
16
help/help.go
@@ -57,8 +57,8 @@ type Model struct {
|
||||
Styles Styles
|
||||
}
|
||||
|
||||
// NewModel creates a new help view with some useful defaults.
|
||||
func NewModel() Model {
|
||||
// New creates a new help view with some useful defaults.
|
||||
func New() Model {
|
||||
keyStyle := lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{
|
||||
Light: "#909090",
|
||||
Dark: "#626262",
|
||||
@@ -90,6 +90,11 @@ func NewModel() Model {
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel creates a new help view with some useful defaults.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// Update helps satisfy the Bubble Tea Model interface. It's a no-op.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
return m, nil
|
||||
@@ -160,7 +165,12 @@ func (m Model) FullHelpView(groups [][]key.Binding) string {
|
||||
}
|
||||
|
||||
var (
|
||||
out []string
|
||||
// Linter note: at this time we don't think it's worth the additional
|
||||
// code complexity involved in preallocating this slice.
|
||||
//
|
||||
//nolint:prealloc
|
||||
out []string
|
||||
|
||||
totalWidth int
|
||||
sep = m.Styles.FullSeparator.Render(m.FullSeparator)
|
||||
sepWidth = lipgloss.Width(sep)
|
||||
|
16
key/key.go
16
key/key.go
@@ -13,8 +13,8 @@
|
||||
// key.WithHelp("↑/k", "move up"), // corresponding help text
|
||||
// ),
|
||||
// Down: key.NewBinding(
|
||||
// WithKeys("j", "down"),
|
||||
// WithHelp("↓/j", "move down"),
|
||||
// key.WithKeys("j", "down"),
|
||||
// key.WithHelp("↓/j", "move down"),
|
||||
// ),
|
||||
// }
|
||||
//
|
||||
@@ -128,11 +128,13 @@ type Help struct {
|
||||
Desc string
|
||||
}
|
||||
|
||||
// Matches checks if the given KeyMsg matches a given binding.
|
||||
func Matches(k tea.KeyMsg, b Binding) bool {
|
||||
for _, v := range b.keys {
|
||||
if k.String() == v && b.Enabled() {
|
||||
return true
|
||||
// Matches checks if the given KeyMsg matches the given bindings.
|
||||
func Matches(k tea.KeyMsg, b ...Binding) bool {
|
||||
for _, binding := range b {
|
||||
for _, v := range binding.keys {
|
||||
if k.String() == v && binding.Enabled() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
41
list/list.go
41
list/list.go
@@ -67,15 +67,9 @@ func (f filteredItems) items() []Item {
|
||||
return agg
|
||||
}
|
||||
|
||||
func (f filteredItems) matches() [][]int {
|
||||
agg := make([][]int, len(f))
|
||||
for i, v := range f {
|
||||
agg[i] = v.matches
|
||||
}
|
||||
return agg
|
||||
}
|
||||
|
||||
type filterMatchesMsg []filteredItem
|
||||
// FilterMatchesMsg contains data about items matched during filtering. The
|
||||
// message should be routed to Update for processing.
|
||||
type FilterMatchesMsg []filteredItem
|
||||
|
||||
type statusMessageTimeoutMsg struct{}
|
||||
|
||||
@@ -113,6 +107,8 @@ type Model struct {
|
||||
// Key mappings for navigating the list.
|
||||
KeyMap KeyMap
|
||||
|
||||
disableQuitKeybindings bool
|
||||
|
||||
// Additional key mappings for the short and full help views. This allows
|
||||
// you to add additional key mappings to the help menu without
|
||||
// re-implementing the help component. Of course, you can also disable the
|
||||
@@ -149,8 +145,8 @@ type Model struct {
|
||||
delegate ItemDelegate
|
||||
}
|
||||
|
||||
// NewModel returns a new model with sensible defaults.
|
||||
func NewModel(items []Item, delegate ItemDelegate, width, height int) Model {
|
||||
// New returns a new model with sensible defaults.
|
||||
func New(items []Item, delegate ItemDelegate, width, height int) Model {
|
||||
styles := DefaultStyles()
|
||||
|
||||
sp := spinner.NewModel()
|
||||
@@ -196,6 +192,11 @@ func NewModel(items []Item, delegate ItemDelegate, width, height int) Model {
|
||||
return m
|
||||
}
|
||||
|
||||
// NewModel returns a new model with sensible defaults.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// SetFilteringEnabled enables or disables filtering. Note that this is different
|
||||
// from ShowFilter, which merely hides or shows the input view.
|
||||
func (m *Model) SetFilteringEnabled(v bool) {
|
||||
@@ -292,6 +293,7 @@ func (m *Model) SetItems(i []Item) tea.Cmd {
|
||||
}
|
||||
|
||||
m.updatePagination()
|
||||
m.updateKeybindings()
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -324,7 +326,8 @@ func (m *Model) SetItem(index int, item Item) tea.Cmd {
|
||||
return cmd
|
||||
}
|
||||
|
||||
// Insert an item at the given index. This returns a command.
|
||||
// Insert an item at the given index. If index is out of the upper bound, the
|
||||
// item will be appended. This returns a command.
|
||||
func (m *Model) InsertItem(index int, item Item) tea.Cmd {
|
||||
var cmd tea.Cmd
|
||||
m.items = insertItemIntoSlice(m.items, item, index)
|
||||
@@ -334,6 +337,7 @@ func (m *Model) InsertItem(index int, item Item) tea.Cmd {
|
||||
}
|
||||
|
||||
m.updatePagination()
|
||||
m.updateKeybindings()
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -519,6 +523,7 @@ func (m *Model) StopSpinner() {
|
||||
// Helper for disabling the keybindings used for quitting, incase you want to
|
||||
// handle this elsewhere in your application.
|
||||
func (m *Model) DisableQuitKeybindings() {
|
||||
m.disableQuitKeybindings = true
|
||||
m.KeyMap.Quit.SetEnabled(false)
|
||||
m.KeyMap.ForceQuit.SetEnabled(false)
|
||||
}
|
||||
@@ -601,12 +606,12 @@ func (m *Model) updateKeybindings() {
|
||||
m.KeyMap.ClearFilter.SetEnabled(false)
|
||||
m.KeyMap.CancelWhileFiltering.SetEnabled(true)
|
||||
m.KeyMap.AcceptWhileFiltering.SetEnabled(m.FilterInput.Value() != "")
|
||||
m.KeyMap.Quit.SetEnabled(true)
|
||||
m.KeyMap.Quit.SetEnabled(false)
|
||||
m.KeyMap.ShowFullHelp.SetEnabled(false)
|
||||
m.KeyMap.CloseFullHelp.SetEnabled(false)
|
||||
|
||||
default:
|
||||
hasItems := m.items != nil
|
||||
hasItems := len(m.items) != 0
|
||||
m.KeyMap.CursorUp.SetEnabled(hasItems)
|
||||
m.KeyMap.CursorDown.SetEnabled(hasItems)
|
||||
|
||||
@@ -621,7 +626,7 @@ func (m *Model) updateKeybindings() {
|
||||
m.KeyMap.ClearFilter.SetEnabled(m.filterState == FilterApplied)
|
||||
m.KeyMap.CancelWhileFiltering.SetEnabled(false)
|
||||
m.KeyMap.AcceptWhileFiltering.SetEnabled(false)
|
||||
m.KeyMap.Quit.SetEnabled(true)
|
||||
m.KeyMap.Quit.SetEnabled(!m.disableQuitKeybindings)
|
||||
|
||||
if m.Help.ShowAll {
|
||||
m.KeyMap.ShowFullHelp.SetEnabled(true)
|
||||
@@ -687,7 +692,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
return m, tea.Quit
|
||||
}
|
||||
|
||||
case filterMatchesMsg:
|
||||
case FilterMatchesMsg:
|
||||
m.filteredItems = filteredItems(msg)
|
||||
return m, nil
|
||||
|
||||
@@ -1118,7 +1123,7 @@ func (m Model) spinnerView() string {
|
||||
func filterItems(m Model) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
if m.FilterInput.Value() == "" || m.filterState == Unfiltered {
|
||||
return filterMatchesMsg(m.itemsAsFilterItems()) // return nothing
|
||||
return FilterMatchesMsg(m.itemsAsFilterItems()) // return nothing
|
||||
}
|
||||
|
||||
targets := []string{}
|
||||
@@ -1139,7 +1144,7 @@ func filterItems(m Model) tea.Cmd {
|
||||
})
|
||||
}
|
||||
|
||||
return filterMatchesMsg(filterMatches)
|
||||
return FilterMatchesMsg(filterMatches)
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -96,8 +96,8 @@ func (m Model) OnLastPage() bool {
|
||||
return m.Page == m.TotalPages-1
|
||||
}
|
||||
|
||||
// NewModel creates a new model with defaults.
|
||||
func NewModel() Model {
|
||||
// New creates a new model with defaults.
|
||||
func New() Model {
|
||||
return Model{
|
||||
Type: Arabic,
|
||||
Page: 0,
|
||||
@@ -114,6 +114,11 @@ func NewModel() Model {
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel creates a new model with defaults.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// Update is the Tea update function which binds keystrokes to pagination.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
|
@@ -98,6 +98,11 @@ func WithWidth(w int) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithSpringOptions sets the initial frequency and damping options for the
|
||||
// progressbar's built-in spring-based animation. Frequency corresponds to
|
||||
// speed, and damping to bounciness. For details see:
|
||||
//
|
||||
// https://github.com/charmbracelet/harmonica
|
||||
func WithSpringOptions(frequency, damping float64) Option {
|
||||
return func(m *Model) {
|
||||
m.SetSpringOptions(frequency, damping)
|
||||
@@ -154,8 +159,8 @@ type Model struct {
|
||||
scaleRamp bool
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
func NewModel(opts ...Option) Model {
|
||||
// New returns a model with default values.
|
||||
func New(opts ...Option) Model {
|
||||
m := Model{
|
||||
id: nextID(),
|
||||
Width: defaultWidth,
|
||||
@@ -176,6 +181,11 @@ func NewModel(opts ...Option) Model {
|
||||
return m
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// Init exists satisfy the tea.Model interface.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return nil
|
||||
@@ -208,7 +218,8 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
|
||||
// SetSpringOptions sets the frequency and damping for the current spring.
|
||||
// Frequency corresponds to speed, and damping to bounciness. For details see:
|
||||
// https://github.com/charmbracelet/harmonica.
|
||||
//
|
||||
// https://github.com/charmbracelet/harmonica
|
||||
func (m *Model) SetSpringOptions(frequency, damping float64) {
|
||||
m.spring = harmonica.NewSpring(harmonica.FPS(fps), frequency, damping)
|
||||
}
|
||||
|
@@ -2,6 +2,7 @@ package spinner
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
@@ -9,6 +10,21 @@ import (
|
||||
"github.com/muesli/reflow/ansi"
|
||||
)
|
||||
|
||||
// Internal ID management for text inputs. Necessary for blink integrity when
|
||||
// multiple text inputs are involved.
|
||||
var (
|
||||
lastID int
|
||||
idMtx sync.Mutex
|
||||
)
|
||||
|
||||
// Return the next ID we should use on the Model.
|
||||
func nextID() int {
|
||||
idMtx.Lock()
|
||||
defer idMtx.Unlock()
|
||||
lastID++
|
||||
return lastID
|
||||
}
|
||||
|
||||
// Spinner is a set of frames used in animating the spinner.
|
||||
type Spinner struct {
|
||||
Frames []string
|
||||
@@ -92,6 +108,7 @@ type Model struct {
|
||||
|
||||
frame int
|
||||
startTime time.Time
|
||||
id int
|
||||
tag int
|
||||
}
|
||||
|
||||
@@ -129,6 +146,11 @@ func (m *Model) Finish() {
|
||||
}
|
||||
}
|
||||
|
||||
// ID returns the spinner's unique ID.
|
||||
func (m Model) ID() int {
|
||||
return m.id
|
||||
}
|
||||
|
||||
// advancedMode returns whether or not the user is making use of HideFor and
|
||||
// MinimumLifetime properties.
|
||||
func (m Model) advancedMode() bool {
|
||||
@@ -171,15 +193,24 @@ func (m Model) Visible() bool {
|
||||
return !m.hidden() && !m.finished()
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
func NewModel() Model {
|
||||
return Model{Spinner: Line}
|
||||
// New returns a model with default values.
|
||||
func New() Model {
|
||||
return Model{
|
||||
Spinner: Line,
|
||||
id: nextID(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// TickMsg indicates that the timer has ticked and we should render a frame.
|
||||
type TickMsg struct {
|
||||
Time time.Time
|
||||
tag int
|
||||
ID int
|
||||
}
|
||||
|
||||
// Update is the Tea update function. This will advance the spinner one frame
|
||||
@@ -188,6 +219,12 @@ type TickMsg struct {
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case TickMsg:
|
||||
// If an ID is set, and the ID doesn't belong to this spinner, reject
|
||||
// the message.
|
||||
if msg.ID > 0 && msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// If a tag is set, and it's not the one we expect, reject the message.
|
||||
// This prevents the spinner from receiving too many messages and
|
||||
// thus spinning too fast.
|
||||
@@ -201,7 +238,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
}
|
||||
|
||||
m.tag++
|
||||
return m, m.tick(m.tag)
|
||||
return m, m.tick(m.id, m.tag)
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
@@ -227,15 +264,34 @@ func (m Model) View() string {
|
||||
|
||||
// Tick is the command used to advance the spinner one frame. Use this command
|
||||
// to effectively start the spinner.
|
||||
func Tick() tea.Msg {
|
||||
return TickMsg{Time: time.Now()}
|
||||
func (m Model) Tick() tea.Msg {
|
||||
return TickMsg{
|
||||
// The time at which the tick occurred.
|
||||
Time: time.Now(),
|
||||
|
||||
// The ID of the spinner that this message belongs to. This can be
|
||||
// helpful when routing messages, however bear in mind that spinners
|
||||
// will ignore messages that don't contain ID by default.
|
||||
ID: m.id,
|
||||
|
||||
tag: m.tag,
|
||||
}
|
||||
}
|
||||
|
||||
func (m Model) tick(tag int) tea.Cmd {
|
||||
func (m Model) tick(id, tag int) tea.Cmd {
|
||||
return tea.Tick(m.Spinner.FPS, func(t time.Time) tea.Msg {
|
||||
return TickMsg{
|
||||
Time: t,
|
||||
ID: id,
|
||||
tag: tag,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Tick is the command used to advance the spinner one frame. Use this command
|
||||
// to effectively start the spinner.
|
||||
//
|
||||
// This method is deprecated. Use Model.Tick instead.
|
||||
func Tick() tea.Msg {
|
||||
return TickMsg{Time: time.Now()}
|
||||
}
|
||||
|
152
stopwatch/stopwatch.go
Normal file
152
stopwatch/stopwatch.go
Normal file
@@ -0,0 +1,152 @@
|
||||
// Package stopwatch provides a simple stopwatch component.
|
||||
package stopwatch
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
var (
|
||||
lastID int
|
||||
idMtx sync.Mutex
|
||||
)
|
||||
|
||||
func nextID() int {
|
||||
idMtx.Lock()
|
||||
defer idMtx.Unlock()
|
||||
lastID++
|
||||
return lastID
|
||||
}
|
||||
|
||||
// TickMsg is a message that is sent on every timer tick.
|
||||
type TickMsg struct {
|
||||
// ID is the identifier of the stopwatch that send the message. This makes
|
||||
// it possible to determine which stopwatch a tick belongs to when there
|
||||
// are multiple stopwatches running.
|
||||
//
|
||||
// Note, however, that a stopwatch will reject ticks from other
|
||||
// stopwatches, so it's safe to flow all TickMsgs through all stopwatches
|
||||
// and have them still behave appropriately.
|
||||
ID int
|
||||
}
|
||||
|
||||
// StartStopMsg is sent when the stopwatch should start or stop.
|
||||
type StartStopMsg struct {
|
||||
ID int
|
||||
running bool
|
||||
}
|
||||
|
||||
// ResetMsg is sent when the stopwatch should reset.
|
||||
type ResetMsg struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
// Model for the stopwatch component.
|
||||
type Model struct {
|
||||
d time.Duration
|
||||
id int
|
||||
running bool
|
||||
|
||||
// How long to wait before every tick. Defaults to 1 second.
|
||||
Interval time.Duration
|
||||
}
|
||||
|
||||
// NewWithInterval creates a new stopwatch with the given timeout and tick
|
||||
// interval.
|
||||
func NewWithInterval(interval time.Duration) Model {
|
||||
return Model{
|
||||
Interval: interval,
|
||||
id: nextID(),
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a new stopwatch with 1s interval.
|
||||
func New() Model {
|
||||
return NewWithInterval(time.Second)
|
||||
}
|
||||
|
||||
// ID returns the unique ID of the model.
|
||||
func (m Model) ID() int {
|
||||
return m.id
|
||||
}
|
||||
|
||||
// Init starts the stopwatch.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return m.Start()
|
||||
}
|
||||
|
||||
// Start starts the stopwatch.
|
||||
func (m Model) Start() tea.Cmd {
|
||||
return tea.Batch(func() tea.Msg {
|
||||
return StartStopMsg{ID: m.id, running: true}
|
||||
}, tick(m.id, m.Interval))
|
||||
}
|
||||
|
||||
// Stop stops the stopwatch.
|
||||
func (m Model) Stop() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return StartStopMsg{ID: m.id, running: false}
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle stops the stopwatch if it is running and starts it if it is stopped.
|
||||
func (m Model) Toggle() tea.Cmd {
|
||||
if m.Running() {
|
||||
return m.Stop()
|
||||
}
|
||||
return m.Start()
|
||||
}
|
||||
|
||||
// Reset restes the stopwatch to 0.
|
||||
func (m Model) Reset() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return ResetMsg{ID: m.id}
|
||||
}
|
||||
}
|
||||
|
||||
// Running returns true if the stopwatch is running or false if it is stopped.
|
||||
func (m Model) Running() bool {
|
||||
return m.running
|
||||
}
|
||||
|
||||
// Update handles the timer tick.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case StartStopMsg:
|
||||
if msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
m.running = msg.running
|
||||
case ResetMsg:
|
||||
if msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
m.d = 0
|
||||
case TickMsg:
|
||||
if !m.running || msg.ID != m.id {
|
||||
break
|
||||
}
|
||||
m.d += m.Interval
|
||||
return m, tick(m.id, m.Interval)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Elapsed returns the time elapsed.
|
||||
func (m Model) Elapsed() time.Duration {
|
||||
return m.d
|
||||
}
|
||||
|
||||
// View of the timer component.
|
||||
func (m Model) View() string {
|
||||
return m.d.String()
|
||||
}
|
||||
|
||||
func tick(id int, d time.Duration) tea.Cmd {
|
||||
return tea.Tick(d, func(_ time.Time) tea.Msg {
|
||||
return TickMsg{ID: id}
|
||||
})
|
||||
}
|
@@ -62,7 +62,7 @@ const (
|
||||
// seen for password fields on the command line.
|
||||
EchoNone
|
||||
|
||||
// EchoOnEdit
|
||||
// EchoOnEdit.
|
||||
)
|
||||
|
||||
// blinkCtx manages cursor blinking.
|
||||
@@ -153,7 +153,7 @@ type Model struct {
|
||||
}
|
||||
|
||||
// NewModel creates a new model with default settings.
|
||||
func NewModel() Model {
|
||||
func New() Model {
|
||||
return Model{
|
||||
Prompt: "> ",
|
||||
BlinkSpeed: defaultBlinkSpeed,
|
||||
@@ -174,6 +174,11 @@ func NewModel() Model {
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel creates a new model with default settings.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// SetValue sets the value of the text input.
|
||||
func (m *Model) SetValue(s string) {
|
||||
runes := []rune(s)
|
||||
@@ -229,7 +234,7 @@ func (m *Model) cursorStart() bool {
|
||||
return m.setCursor(0)
|
||||
}
|
||||
|
||||
// CursorEnd moves the cursor to the end of the input field
|
||||
// CursorEnd moves the cursor to the end of the input field.
|
||||
func (m *Model) CursorEnd() {
|
||||
m.cursorEnd()
|
||||
}
|
||||
@@ -407,9 +412,16 @@ func (m *Model) deleteWordLeft() bool {
|
||||
return m.deleteBeforeCursor()
|
||||
}
|
||||
|
||||
i := m.pos
|
||||
// Linter note: it's critical that we acquire the initial cursor position
|
||||
// here prior to altering it via SetCursor() below. As such, moving this
|
||||
// call into the corresponding if clause does not apply here.
|
||||
oldPos := m.pos //nolint:ifshort
|
||||
|
||||
blink := m.setCursor(m.pos - 1)
|
||||
for unicode.IsSpace(m.value[m.pos]) {
|
||||
if m.pos <= 0 {
|
||||
break
|
||||
}
|
||||
// ignore series of whitespace before cursor
|
||||
blink = m.setCursor(m.pos - 1)
|
||||
}
|
||||
@@ -426,10 +438,10 @@ func (m *Model) deleteWordLeft() bool {
|
||||
}
|
||||
}
|
||||
|
||||
if i > len(m.value) {
|
||||
if oldPos > len(m.value) {
|
||||
m.value = m.value[:m.pos]
|
||||
} else {
|
||||
m.value = append(m.value[:m.pos], m.value[i:]...)
|
||||
m.value = append(m.value[:m.pos], m.value[oldPos:]...)
|
||||
}
|
||||
|
||||
return blink
|
||||
@@ -447,11 +459,15 @@ func (m *Model) deleteWordRight() bool {
|
||||
return m.deleteAfterCursor()
|
||||
}
|
||||
|
||||
i := m.pos
|
||||
oldPos := m.pos
|
||||
m.setCursor(m.pos + 1)
|
||||
for unicode.IsSpace(m.value[m.pos]) {
|
||||
// ignore series of whitespace after cursor
|
||||
m.setCursor(m.pos + 1)
|
||||
|
||||
if m.pos >= len(m.value) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for m.pos < len(m.value) {
|
||||
@@ -463,12 +479,12 @@ func (m *Model) deleteWordRight() bool {
|
||||
}
|
||||
|
||||
if m.pos > len(m.value) {
|
||||
m.value = m.value[:i]
|
||||
m.value = m.value[:oldPos]
|
||||
} else {
|
||||
m.value = append(m.value[:i], m.value[m.pos:]...)
|
||||
m.value = append(m.value[:oldPos], m.value[m.pos:]...)
|
||||
}
|
||||
|
||||
return m.setCursor(i)
|
||||
return m.setCursor(oldPos)
|
||||
}
|
||||
|
||||
// wordLeft moves the cursor one word to the left. Returns whether or not the
|
||||
@@ -784,6 +800,9 @@ func Paste() tea.Msg {
|
||||
}
|
||||
|
||||
func clamp(v, low, high int) int {
|
||||
if high < low {
|
||||
low, high = high, low
|
||||
}
|
||||
return min(high, max(low, v))
|
||||
}
|
||||
|
||||
|
194
timer/timer.go
Normal file
194
timer/timer.go
Normal file
@@ -0,0 +1,194 @@
|
||||
// Package timer provides a simple timeout component.
|
||||
package timer
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
var (
|
||||
lastID int
|
||||
idMtx sync.Mutex
|
||||
)
|
||||
|
||||
func nextID() int {
|
||||
idMtx.Lock()
|
||||
defer idMtx.Unlock()
|
||||
lastID++
|
||||
return lastID
|
||||
}
|
||||
|
||||
// Authors note with regard to start and stop commands:
|
||||
//
|
||||
// Technically speaking, sending commands to start and stop the timer in this
|
||||
// case is extraneous. To stop the timer we'd just need to set the 'running'
|
||||
// property on the model to false which cause logic in the update function to
|
||||
// stop responding to TickMsgs. To start the model we'd set 'running' to true
|
||||
// and fire off a TickMsg. Helper functions would look like:
|
||||
//
|
||||
// func (m *model) Start() tea.Cmd
|
||||
// func (m *model) Stop()
|
||||
//
|
||||
// The danger with this approach, however, is that order of operations becomes
|
||||
// important with helper functions like the above. Consider the following:
|
||||
//
|
||||
// // Would not work
|
||||
// return m, m.timer.Start()
|
||||
//
|
||||
// // Would work
|
||||
// cmd := m.timer.start()
|
||||
// return m, cmd
|
||||
//
|
||||
// Thus, because of potential pitfalls like the ones above, we've introduced
|
||||
// the extraneous StartStopMsg to simplify the mental model when using this
|
||||
// package. Bear in mind that the practice of sending commands to simply
|
||||
// communicate with other parts of your application, such as in this package,
|
||||
// is still not recommended.
|
||||
|
||||
// StartStopMsg is used to start and stop the timer.
|
||||
type StartStopMsg struct {
|
||||
ID int
|
||||
running bool
|
||||
}
|
||||
|
||||
// TickMsg is a message that is sent on every timer tick.
|
||||
type TickMsg struct {
|
||||
// ID is the identifier of the stopwatch that send the message. This makes
|
||||
// it possible to determine which timer a tick belongs to when there
|
||||
// are multiple timers running.
|
||||
//
|
||||
// Note, however, that a timer will reject ticks from other stopwatches, so
|
||||
// it's safe to flow all TickMsgs through all timers and have them still
|
||||
// behave appropriately.
|
||||
ID int
|
||||
|
||||
// Timeout returns whether or not this tick is a timeout tick. You can
|
||||
// alternatively listen for TimeoutMsg.
|
||||
Timeout bool
|
||||
}
|
||||
|
||||
// TimeoutMsg is a message that is sent once when the timer times out.
|
||||
//
|
||||
// It's a convenience message sent alongside a TickMsg with the Timeout value
|
||||
// set to true.
|
||||
type TimeoutMsg struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
// Model of the timer component.
|
||||
type Model struct {
|
||||
// How long until the timer expires.
|
||||
Timeout time.Duration
|
||||
|
||||
// How long to wait before every tick. Defaults to 1 second.
|
||||
Interval time.Duration
|
||||
|
||||
id int
|
||||
running bool
|
||||
}
|
||||
|
||||
// NewWithInterval creates a new timer with the given timeout and tick interval.
|
||||
func NewWithInterval(timeout, interval time.Duration) Model {
|
||||
return Model{
|
||||
Timeout: timeout,
|
||||
Interval: interval,
|
||||
running: true,
|
||||
id: nextID(),
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a new timer with the given timeout and default 1s interval.
|
||||
func New(timeout time.Duration) Model {
|
||||
return NewWithInterval(timeout, time.Second)
|
||||
}
|
||||
|
||||
// ID returns the model's identifier. This can be used to determine if messages
|
||||
// belong to this timer instance when there are multiple timers.
|
||||
func (m Model) ID() int {
|
||||
return m.id
|
||||
}
|
||||
|
||||
// Running returns whether or not the timer is running. If the timer has timed
|
||||
// out this will always return false.
|
||||
func (m Model) Running() bool {
|
||||
if m.Timedout() || !m.running {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Timedout returns whether or not the timer has timed out.
|
||||
func (m Model) Timedout() bool {
|
||||
return m.Timeout <= 0
|
||||
}
|
||||
|
||||
// Init starts the timer.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return m.tick()
|
||||
}
|
||||
|
||||
// Update handles the timer tick.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case StartStopMsg:
|
||||
if msg.ID != 0 && msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
m.running = msg.running
|
||||
return m, m.tick()
|
||||
case TickMsg:
|
||||
if !m.Running() || (msg.ID != 0 && msg.ID != m.id) {
|
||||
break
|
||||
}
|
||||
|
||||
m.Timeout -= m.Interval
|
||||
return m, tea.Batch(m.tick(), m.timedout())
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// View of the timer component.
|
||||
func (m Model) View() string {
|
||||
return m.Timeout.String()
|
||||
}
|
||||
|
||||
// Start resumes the timer. Has no effect if the timer has timed out.
|
||||
func (m *Model) Start() tea.Cmd {
|
||||
return m.startStop(true)
|
||||
}
|
||||
|
||||
// Stop pauses the timer. Has no effect if the timer has timed out.
|
||||
func (m *Model) Stop() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return m.startStop(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle stops the timer if it's running and starts it if it's stopped.
|
||||
func (m *Model) Toggle() tea.Cmd {
|
||||
return m.startStop(!m.Running())
|
||||
}
|
||||
|
||||
func (m Model) tick() tea.Cmd {
|
||||
return tea.Tick(m.Interval, func(_ time.Time) tea.Msg {
|
||||
return TickMsg{ID: m.id, Timeout: m.Timedout()}
|
||||
})
|
||||
}
|
||||
|
||||
func (m Model) timedout() tea.Cmd {
|
||||
if !m.Timedout() {
|
||||
return nil
|
||||
}
|
||||
return func() tea.Msg {
|
||||
return TimeoutMsg{ID: m.id}
|
||||
}
|
||||
}
|
||||
|
||||
func (m Model) startStop(v bool) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return StartStopMsg{ID: m.id, running: v}
|
||||
}
|
||||
}
|
42
viewport/keymap.go
Normal file
42
viewport/keymap.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package viewport
|
||||
|
||||
import "github.com/charmbracelet/bubbles/key"
|
||||
|
||||
const spacebar = " "
|
||||
|
||||
// KeyMap defines the keybindings for the viewport. Note that you don't
|
||||
// necessary need to use keybindings at all; the viewport can be controlled
|
||||
// programmatically with methods like Model.LineDown(1). See the GoDocs for
|
||||
// details.
|
||||
type KeyMap struct {
|
||||
PageDown key.Binding
|
||||
PageUp key.Binding
|
||||
HalfPageUp key.Binding
|
||||
HalfPageDown key.Binding
|
||||
Down key.Binding
|
||||
Up key.Binding
|
||||
}
|
||||
|
||||
// DefaultKeyMap returns a set of pager-like default keybindings.
|
||||
func DefaultKeyMap() KeyMap {
|
||||
return KeyMap{
|
||||
PageDown: key.NewBinding(
|
||||
key.WithKeys("pgdown", spacebar, "f"),
|
||||
),
|
||||
PageUp: key.NewBinding(
|
||||
key.WithKeys("pgup", "b"),
|
||||
),
|
||||
HalfPageUp: key.NewBinding(
|
||||
key.WithKeys("u", "ctrl+u"),
|
||||
),
|
||||
HalfPageDown: key.NewBinding(
|
||||
key.WithKeys("d", "ctrl+d"),
|
||||
),
|
||||
Up: key.NewBinding(
|
||||
key.WithKeys("up", "k"),
|
||||
),
|
||||
Down: key.NewBinding(
|
||||
key.WithKeys("down", "j"),
|
||||
),
|
||||
}
|
||||
}
|
@@ -4,26 +4,44 @@ import (
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/key"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
const (
|
||||
spacebar = " "
|
||||
mouseWheelDelta = 3
|
||||
)
|
||||
// New returns a new model with the given width and height as well as default
|
||||
// keymappings.
|
||||
func New(width, height int) (m Model) {
|
||||
m.Width = width
|
||||
m.Height = height
|
||||
m.setInitialValues()
|
||||
return m
|
||||
}
|
||||
|
||||
// Model is the Bubble Tea model for this viewport element.
|
||||
type Model struct {
|
||||
Width int
|
||||
Height int
|
||||
KeyMap KeyMap
|
||||
|
||||
// Whether or not to respond to the mouse. The mouse must be enabled in
|
||||
// Bubble Tea for this to work. For details, see the Bubble Tea docs.
|
||||
MouseWheelEnabled bool
|
||||
|
||||
// The number of lines the mouse wheel will scroll. By default, this is 3.
|
||||
MouseWheelDelta int
|
||||
|
||||
// YOffset is the vertical scroll position.
|
||||
YOffset int
|
||||
|
||||
// YPosition is the position of the viewport in relation to the terminal
|
||||
// window. It's used in high performance rendering.
|
||||
// window. It's used in high performance rendering only.
|
||||
YPosition int
|
||||
|
||||
// Style applies a lipgloss style to the viewport. Realistically, it's most
|
||||
// useful for setting borders, margins and padding.
|
||||
Style lipgloss.Style
|
||||
|
||||
// HighPerformanceRendering bypasses the normal Bubble Tea renderer to
|
||||
// provide higher performance rendering. Most of the time the normal Bubble
|
||||
// Tea rendering methods will suffice, but if you're passing content with
|
||||
@@ -34,7 +52,20 @@ type Model struct {
|
||||
// which is usually via the alternate screen buffer.
|
||||
HighPerformanceRendering bool
|
||||
|
||||
lines []string
|
||||
initialized bool
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (m *Model) setInitialValues() {
|
||||
m.KeyMap = DefaultKeyMap()
|
||||
m.MouseWheelEnabled = true
|
||||
m.MouseWheelDelta = 3
|
||||
m.initialized = true
|
||||
}
|
||||
|
||||
// Init exists to satisfy the tea.Model interface for composability purposes.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AtTop returns whether or not the viewport is in the very top position.
|
||||
@@ -45,13 +76,13 @@ func (m Model) AtTop() bool {
|
||||
// AtBottom returns whether or not the viewport is at or past the very bottom
|
||||
// position.
|
||||
func (m Model) AtBottom() bool {
|
||||
return m.YOffset >= len(m.lines)-1-m.Height
|
||||
return m.YOffset >= m.maxYOffset()
|
||||
}
|
||||
|
||||
// PastBottom returns whether or not the viewport is scrolled beyond the last
|
||||
// line. This can happen when adjusting the viewport height.
|
||||
func (m Model) PastBottom() bool {
|
||||
return m.YOffset > len(m.lines)-1-m.Height
|
||||
return m.YOffset > m.maxYOffset()
|
||||
}
|
||||
|
||||
// ScrollPercent returns the amount scrolled as a float between 0 and 1.
|
||||
@@ -69,7 +100,7 @@ func (m Model) ScrollPercent() float64 {
|
||||
// SetContent set the pager's text content. For high performance rendering the
|
||||
// Sync command should also be called.
|
||||
func (m *Model) SetContent(s string) {
|
||||
s = strings.Replace(s, "\r\n", "\n", -1) // normalize line endings
|
||||
s = strings.ReplaceAll(s, "\r\n", "\n") // normalize line endings
|
||||
m.lines = strings.Split(s, "\n")
|
||||
|
||||
if m.YOffset > len(m.lines)-1 {
|
||||
@@ -77,7 +108,14 @@ func (m *Model) SetContent(s string) {
|
||||
}
|
||||
}
|
||||
|
||||
// Return the lines that should currently be visible in the viewport.
|
||||
// maxYOffset returns the maximum possible value of the y-offset based on the
|
||||
// viewport's content and set height.
|
||||
func (m Model) maxYOffset() int {
|
||||
return max(0, len(m.lines)-m.Height)
|
||||
}
|
||||
|
||||
// visibleLines returns the lines that should currently be visible in the
|
||||
// viewport.
|
||||
func (m Model) visibleLines() (lines []string) {
|
||||
if len(m.lines) > 0 {
|
||||
top := max(0, m.YOffset)
|
||||
@@ -87,6 +125,21 @@ func (m Model) visibleLines() (lines []string) {
|
||||
return lines
|
||||
}
|
||||
|
||||
// scrollArea returns the scrollable boundaries for high performance rendering.
|
||||
func (m Model) scrollArea() (top, bottom int) {
|
||||
top = max(0, m.YPosition)
|
||||
bottom = max(top, top+m.Height)
|
||||
if top > 0 && bottom > top {
|
||||
bottom--
|
||||
}
|
||||
return top, bottom
|
||||
}
|
||||
|
||||
// SetYOffset sets the Y offset.
|
||||
func (m *Model) SetYOffset(n int) {
|
||||
m.YOffset = clamp(n, 0, m.maxYOffset())
|
||||
}
|
||||
|
||||
// ViewDown moves the view down by the number of lines in the viewport.
|
||||
// Basically, "page down".
|
||||
func (m *Model) ViewDown() []string {
|
||||
@@ -94,11 +147,7 @@ func (m *Model) ViewDown() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = min(
|
||||
m.YOffset+m.Height, // target
|
||||
len(m.lines)-1-m.Height, // fallback
|
||||
)
|
||||
|
||||
m.SetYOffset(m.YOffset + m.Height)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
@@ -108,11 +157,7 @@ func (m *Model) ViewUp() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = max(
|
||||
m.YOffset-m.Height, // target
|
||||
0, // fallback
|
||||
)
|
||||
|
||||
m.SetYOffset(m.YOffset - m.Height)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
@@ -122,18 +167,8 @@ func (m *Model) HalfViewDown() (lines []string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = min(
|
||||
m.YOffset+m.Height/2, // target
|
||||
len(m.lines)-1-m.Height, // fallback
|
||||
)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(m.YOffset+m.Height/2, 0)
|
||||
bottom := clamp(m.YOffset+m.Height, top, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset + m.Height/2)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// HalfViewUp moves the view up by half the height of the viewport.
|
||||
@@ -142,18 +177,8 @@ func (m *Model) HalfViewUp() (lines []string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = max(
|
||||
m.YOffset-m.Height/2, // target
|
||||
0, // fallback
|
||||
)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(m.YOffset, 0)
|
||||
bottom := clamp(m.YOffset+m.Height/2, top, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset - m.Height/2)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// LineDown moves the view down by the given number of lines.
|
||||
@@ -165,21 +190,8 @@ func (m *Model) LineDown(n int) (lines []string) {
|
||||
// Make sure the number of lines by which we're going to scroll isn't
|
||||
// greater than the number of lines we actually have left before we reach
|
||||
// the bottom.
|
||||
maxDelta := (len(m.lines) - 1) - (m.YOffset + m.Height) // number of lines - viewport bottom edge
|
||||
n = min(n, maxDelta)
|
||||
|
||||
m.YOffset = min(
|
||||
m.YOffset+n, // target
|
||||
len(m.lines)-1-m.Height, // fallback
|
||||
)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(m.YOffset+m.Height-n, 0)
|
||||
bottom := clamp(m.YOffset+m.Height, top, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset + n)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// LineUp moves the view down by the given number of lines. Returns the new
|
||||
@@ -191,17 +203,8 @@ func (m *Model) LineUp(n int) (lines []string) {
|
||||
|
||||
// Make sure the number of lines by which we're going to scroll isn't
|
||||
// greater than the number of lines we are from the top.
|
||||
n = min(n, m.YOffset)
|
||||
|
||||
m.YOffset = max(m.YOffset-n, 0)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(0, m.YOffset)
|
||||
bottom := clamp(m.YOffset+n, top, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset - n)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// GotoTop sets the viewport to the top position.
|
||||
@@ -210,32 +213,16 @@ func (m *Model) GotoTop() (lines []string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = 0
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := m.YOffset
|
||||
bottom := clamp(m.YOffset+m.Height, top, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(0)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// GotoBottom sets the viewport to the bottom position.
|
||||
func (m *Model) GotoBottom() (lines []string) {
|
||||
m.YOffset = max(len(m.lines)-1-m.Height, 0)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := m.YOffset
|
||||
bottom := max(len(m.lines)-1, 0)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.maxYOffset())
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// COMMANDS
|
||||
|
||||
// Sync tells the renderer where the viewport will be located and requests
|
||||
// a render of the current state of the viewport. It should be called for the
|
||||
// first render and after a window resize.
|
||||
@@ -245,17 +232,8 @@ func Sync(m Model) tea.Cmd {
|
||||
if len(m.lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO: we should probably use m.visibleLines() rather than these two
|
||||
// expressions.
|
||||
top := max(m.YOffset, 0)
|
||||
bottom := clamp(m.YOffset+m.Height, 0, len(m.lines)-1)
|
||||
|
||||
return tea.SyncScrollArea(
|
||||
m.lines[top:bottom],
|
||||
m.YPosition,
|
||||
m.YPosition+m.Height,
|
||||
)
|
||||
top, bottom := m.scrollArea()
|
||||
return tea.SyncScrollArea(m.visibleLines(), top, bottom)
|
||||
}
|
||||
|
||||
// ViewDown is a high performance command that moves the viewport up by a given
|
||||
@@ -269,7 +247,8 @@ func ViewDown(m Model, lines []string) tea.Cmd {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tea.ScrollDown(lines, m.YPosition, m.YPosition+m.Height)
|
||||
top, bottom := m.scrollArea()
|
||||
return tea.ScrollDown(lines, top, bottom)
|
||||
}
|
||||
|
||||
// ViewUp is a high performance command the moves the viewport down by a given
|
||||
@@ -279,57 +258,60 @@ func ViewUp(m Model, lines []string) tea.Cmd {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tea.ScrollUp(lines, m.YPosition, m.YPosition+m.Height)
|
||||
top, bottom := m.scrollArea()
|
||||
return tea.ScrollUp(lines, top, bottom)
|
||||
}
|
||||
|
||||
// UPDATE
|
||||
|
||||
// Update runs the update loop with default keybindings similar to popular
|
||||
// pagers. To define your own keybindings use the methods on Model (i.e.
|
||||
// Model.LineDown()) and define your own update function.
|
||||
// Update handles standard message-based viewport updates.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
var cmd tea.Cmd
|
||||
m, cmd = m.updateAsModel(msg)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// Author's note: this method has been broken out to make it easier to
|
||||
// potentially transition Update to satisfy tea.Model.
|
||||
func (m Model) updateAsModel(msg tea.Msg) (Model, tea.Cmd) {
|
||||
if !m.initialized {
|
||||
m.setInitialValues()
|
||||
}
|
||||
|
||||
var cmd tea.Cmd
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
// Down one page
|
||||
case "pgdown", spacebar, "f":
|
||||
switch {
|
||||
case key.Matches(msg, m.KeyMap.PageDown):
|
||||
lines := m.ViewDown()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
|
||||
// Up one page
|
||||
case "pgup", "b":
|
||||
case key.Matches(msg, m.KeyMap.PageUp):
|
||||
lines := m.ViewUp()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
}
|
||||
|
||||
// Down half page
|
||||
case "d", "ctrl+d":
|
||||
case key.Matches(msg, m.KeyMap.HalfPageDown):
|
||||
lines := m.HalfViewDown()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
|
||||
// Up half page
|
||||
case "u", "ctrl+u":
|
||||
case key.Matches(msg, m.KeyMap.HalfPageUp):
|
||||
lines := m.HalfViewUp()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
}
|
||||
|
||||
// Down one line
|
||||
case "down", "j":
|
||||
case key.Matches(msg, m.KeyMap.Down):
|
||||
lines := m.LineDown(1)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
|
||||
// Up one line
|
||||
case "up", "k":
|
||||
case key.Matches(msg, m.KeyMap.Up):
|
||||
lines := m.LineUp(1)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
@@ -337,15 +319,18 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
}
|
||||
|
||||
case tea.MouseMsg:
|
||||
if !m.MouseWheelEnabled {
|
||||
break
|
||||
}
|
||||
switch msg.Type {
|
||||
case tea.MouseWheelUp:
|
||||
lines := m.LineUp(mouseWheelDelta)
|
||||
lines := m.LineUp(m.MouseWheelDelta)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
}
|
||||
|
||||
case tea.MouseWheelDown:
|
||||
lines := m.LineDown(mouseWheelDelta)
|
||||
lines := m.LineDown(m.MouseWheelDelta)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
@@ -355,13 +340,11 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// VIEW
|
||||
|
||||
// View renders the viewport into a string.
|
||||
func (m Model) View() string {
|
||||
if m.HighPerformanceRendering {
|
||||
// Just send newlines since we're doing to be rendering the actual
|
||||
// content seprately. We still need send something that equals the
|
||||
// Just send newlines since we're going to be rendering the actual
|
||||
// content seprately. We still need to send something that equals the
|
||||
// height of this view so that the Bubble Tea standard renderer can
|
||||
// position anything below this view properly.
|
||||
return strings.Repeat("\n", m.Height-1)
|
||||
@@ -372,15 +355,19 @@ func (m Model) View() string {
|
||||
// Fill empty space with newlines
|
||||
extraLines := ""
|
||||
if len(lines) < m.Height {
|
||||
extraLines = strings.Repeat("\n", m.Height-len(lines))
|
||||
extraLines = strings.Repeat("\n", max(0, m.Height-len(lines)))
|
||||
}
|
||||
|
||||
return strings.Join(lines, "\n") + extraLines
|
||||
return m.Style.Copy().
|
||||
UnsetWidth().
|
||||
UnsetHeight().
|
||||
Render(strings.Join(lines, "\n") + extraLines)
|
||||
}
|
||||
|
||||
// ETC
|
||||
|
||||
func clamp(v, low, high int) int {
|
||||
if high < low {
|
||||
low, high = high, low
|
||||
}
|
||||
return min(high, max(low, v))
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user