mirror of
https://github.com/Maks1mS/bubbles.git
synced 2025-10-17 16:15:58 +03:00
Compare commits
19 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
da9248f877 | ||
|
b691d7f07e | ||
|
8ad268837a | ||
|
0f290114f5 | ||
|
500d7989e1 | ||
|
d987ef84f2 | ||
|
cb52746b97 | ||
|
985ffcb319 | ||
|
4e18245481 | ||
|
0be588365e | ||
|
4c32a64d65 | ||
|
e723cfd15e | ||
|
90d8eaffeb | ||
|
202d5a9f9d | ||
|
446433d680 | ||
|
2cd3b16343 | ||
|
5ae3b7b822 | ||
|
20ead8fb7d | ||
|
09a4cf419d |
2
.github/workflows/lint.yml
vendored
2
.github/workflows/lint.yml
vendored
@@ -10,8 +10,6 @@ jobs:
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
with:
|
||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||
version: v1.30
|
||||
# Optional: golangci-lint command line arguments.
|
||||
args: --issues-exit-code=0
|
||||
# Optional: working directory, useful for monorepos
|
||||
|
@@ -2,6 +2,13 @@ run:
|
||||
tests: false
|
||||
|
||||
issues:
|
||||
include:
|
||||
- EXC0001
|
||||
- EXC0005
|
||||
- EXC0011
|
||||
- EXC0012
|
||||
- EXC0013
|
||||
|
||||
max-issues-per-linter: 0
|
||||
max-same-issues: 0
|
||||
|
||||
@@ -14,12 +21,12 @@ linters:
|
||||
- godot
|
||||
- godox
|
||||
- goimports
|
||||
- golint
|
||||
- gomnd
|
||||
- goprintffuncname
|
||||
- gosec
|
||||
- ifshort
|
||||
- misspell
|
||||
- prealloc
|
||||
- revive
|
||||
- rowserrcheck
|
||||
- sqlclosecheck
|
||||
- unconvert
|
||||
|
103
README.md
103
README.md
@@ -10,12 +10,13 @@ Bubbles
|
||||
[](https://github.com/charmbracelet/bubbles/actions)
|
||||
[](https://goreportcard.com/report/charmbracelet/bubbles)
|
||||
|
||||
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea) applications.
|
||||
|
||||
These components are used in production in [Glow][glow] and [Charm][charm].
|
||||
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea)
|
||||
applications. These components are used in production in [Glow][glow],
|
||||
[Charm][charm] and [many other applications][otherstuff].
|
||||
|
||||
[glow]: https://github.com/charmbracelet/glow
|
||||
[charm]: https://github.com/charmbracelet/charm
|
||||
[otherstuff]: https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild
|
||||
|
||||
|
||||
## Spinner
|
||||
@@ -25,7 +26,8 @@ These components are used in production in [Glow][glow] and [Charm][charm].
|
||||
A spinner, useful for indicating that some kind an operation is happening.
|
||||
There are a couple default ones, but you can also pass your own ”frames.”
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/tea/tree/master/examples/spinner/main.go)
|
||||
* [Example code, basic spinner](https://github.com/charmbracelet/tea/tree/master/examples/spinner/main.go)
|
||||
* [Example code, various spinners](https://github.com/charmbracelet/tea/tree/master/examples/spinners/main.go)
|
||||
|
||||
|
||||
## Text Input
|
||||
@@ -44,11 +46,15 @@ the common, and many customization options.
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/progress.gif" width="800" alt="Progressbar Example">
|
||||
|
||||
A simple, customizable progress meter. Supports solid and gradient fills. The
|
||||
empty and filled runes can be set to whatever you'd like. The percentage readout
|
||||
is customizable and can also be omitted entirely.
|
||||
A simple, customizable progress meter, with optional animation via
|
||||
[Harmonica][harmonica]. Supports solid and gradient fills. The empty and filled
|
||||
runes can be set to whatever you'd like. The percentage readout is customizable
|
||||
and can also be omitted entirely.
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/progress/main.go)
|
||||
* [Animated example](https://github.com/charmbracelet/bubbletea/blob/master/examples/progress-animated/main.go)
|
||||
* [Static example](https://github.com/charmbracelet/bubbletea/blob/master/examples/progress-static/main.go)
|
||||
|
||||
[harmonica]: https://github.com/charmbracelet/harmonica
|
||||
|
||||
|
||||
## Paginator
|
||||
@@ -60,8 +66,7 @@ Supports "dot-style" pagination (similar to what you might see on iOS) and
|
||||
numeric page numbering, but you could also just use this component for the
|
||||
logic and visualize pagination however you like.
|
||||
|
||||
This component is used in [Glow][glow] to browse documents and [Charm][charm] to
|
||||
browse SSH keys.
|
||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/pager/main.go)
|
||||
|
||||
|
||||
## Viewport
|
||||
@@ -80,6 +85,84 @@ indenting and text wrapping.
|
||||
[reflow]: https://github.com/muesli/reflow
|
||||
|
||||
|
||||
## List
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/list.gif" width="600" alt="List Example">
|
||||
|
||||
A customizable, batteries-included component for browsing a set of items.
|
||||
Features pagination, fuzzy filtering, auto-generated help, an activity spinner,
|
||||
and status messages, all of which can be enabled and disabled as needed.
|
||||
Extrapolated from [Glow][glow].
|
||||
|
||||
* [Example code, default list](https://github.com/charmbracelet/tea/tree/master/examples/list-default/main.go)
|
||||
* [Example code, simple list](https://github.com/charmbracelet/tea/tree/master/examples/list-simple/main.go)
|
||||
* [Example code, all features](https://github.com/charmbracelet/tea/tree/master/examples/list-fancy/main.go)
|
||||
|
||||
|
||||
## Help
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/help.gif" width="500" alt="Help Example">
|
||||
|
||||
A customizable horizontal mini help view that automatically generates itself
|
||||
from your keybindings. It features single and multi-line modes, which the user
|
||||
can optionally toggle between. It will truncate gracefully if the terminal is
|
||||
too wide for the content.
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/help/main.go)
|
||||
|
||||
|
||||
## Key
|
||||
|
||||
A non-visual component for managing keybindings. It’s useful for allowing users
|
||||
to remap keybindings as well as generating help views corresponding to your
|
||||
keybindings.
|
||||
|
||||
```go
|
||||
type KeyMap struct {
|
||||
Up key.Binding
|
||||
Down key.Binding
|
||||
}
|
||||
|
||||
var DefaultKeyMap = KeyMap{
|
||||
Up: key.NewBinding(
|
||||
key.WithKeys("k", "up"), // actual keybindings
|
||||
key.WithHelp("↑/k", "move up"), // corresponding help text
|
||||
),
|
||||
Down: key.NewBinding(
|
||||
WithKeys("j", "down"),
|
||||
WithHelp("↓/j", "move down"),
|
||||
),
|
||||
}
|
||||
|
||||
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch {
|
||||
case key.Matches(msg, DefaultKeyMap.Up):
|
||||
// The user pressed up
|
||||
case key.Matches(msg, DefaultKeyMap.Down):
|
||||
// The user pressed down
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Additional Bubbles
|
||||
|
||||
* [promptkit](https://github.com/erikgeiser/promptkit): A collection of common
|
||||
prompts for cases like selection, text input, and confirmation. Each prompt
|
||||
comes with sensible defaults, remappable keybindings, any many customization
|
||||
options.
|
||||
* [mritd/bubbles](https://github.com/mritd/bubbles): Some general-purpose
|
||||
bubbles. Inputs with validation, menu selection, a modified progressbar, and
|
||||
so on.
|
||||
|
||||
If you’ve built a Bubble you think should be listed here,
|
||||
[let us know](mailto:vt100@charm.sh).
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
|
||||
|
14
go.mod
14
go.mod
@@ -4,11 +4,13 @@ go 1.13
|
||||
|
||||
require (
|
||||
github.com/atotto/clipboard v0.1.2
|
||||
github.com/charmbracelet/bubbletea v0.13.1
|
||||
github.com/charmbracelet/lipgloss v0.1.2
|
||||
github.com/charmbracelet/bubbletea v0.14.1
|
||||
github.com/charmbracelet/harmonica v0.1.0
|
||||
github.com/charmbracelet/lipgloss v0.3.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.12
|
||||
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68
|
||||
github.com/muesli/termenv v0.8.1
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.13
|
||||
github.com/muesli/reflow v0.3.0
|
||||
github.com/muesli/termenv v0.9.0
|
||||
github.com/sahilm/fuzzy v0.1.0
|
||||
)
|
||||
|
45
go.sum
45
go.sum
@@ -1,41 +1,44 @@
|
||||
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.13.1 h1:huvX8mPaeMZ8DLulT50iEWRF+iitY5FNEDqDVLu69nM=
|
||||
github.com/charmbracelet/bubbletea v0.13.1/go.mod h1:tp9tr9Dadh0PLhgiwchE5zZJXm5543JYjHG9oY+5qSg=
|
||||
github.com/charmbracelet/lipgloss v0.1.2 h1:D+LUMg34W7n2pkuMrevKVxT7HXqnoRHm7IoomkX3/ZU=
|
||||
github.com/charmbracelet/lipgloss v0.1.2/go.mod h1:5D8zradw52m7QmxRF6QgwbwJi9je84g8MkWiGN07uKg=
|
||||
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/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/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=
|
||||
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
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 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
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 h1:Y41i/hVW3Pgwr8gV+J23B9YEY0zxjptBuCWEaxmAOow=
|
||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68 h1:y1p/ycavWjGT9FnmSjdbWUlLGvcxrY0Rw3ATltrxOhk=
|
||||
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/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ=
|
||||
github.com/muesli/termenv v0.7.2/go.mod h1:ct2L5N2lmix82RaY3bMWwVu/jUFc9Ule0KGDCiKYPh8=
|
||||
github.com/muesli/termenv v0.8.1 h1:9q230czSP3DHVpkaPDXGp0TOfAwyjyYwXlUCQxQSaBk=
|
||||
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=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E=
|
||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
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-20201009025420-dfb3f7c4e634/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/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
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=
|
||||
|
224
help/help.go
Normal file
224
help/help.go
Normal file
@@ -0,0 +1,224 @@
|
||||
package help
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/key"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
// KeyMap is a map of keybindings used to generate help. Since it's an
|
||||
// interface it can be any type, though struct or a map[string][]key.Binding
|
||||
// are likely candidates.
|
||||
//
|
||||
// Note that if a key is disabled (via key.Binding.SetEnabled) it will not be
|
||||
// rendered in the help view, so in theory generated help should self-manage.
|
||||
type KeyMap interface {
|
||||
|
||||
// ShortHelp returns a slice of bindings to be displayed in the short
|
||||
// version of the help. The help bubble will render help in the order in
|
||||
// which the help items are returned here.
|
||||
ShortHelp() []key.Binding
|
||||
|
||||
// MoreHelp returns an extended group of help items, grouped by columns.
|
||||
// The help bubble will render the help in the order in which the help
|
||||
// items are returned here.
|
||||
FullHelp() [][]key.Binding
|
||||
}
|
||||
|
||||
// Styles is a set of available style definitions for the Help bubble.
|
||||
type Styles struct {
|
||||
Ellipsis lipgloss.Style
|
||||
|
||||
// Styling for the short help
|
||||
ShortKey lipgloss.Style
|
||||
ShortDesc lipgloss.Style
|
||||
ShortSeparator lipgloss.Style
|
||||
|
||||
// Styling for the full help
|
||||
FullKey lipgloss.Style
|
||||
FullDesc lipgloss.Style
|
||||
FullSeparator lipgloss.Style
|
||||
}
|
||||
|
||||
// Model contains the state of the help view.
|
||||
type Model struct {
|
||||
Width int
|
||||
ShowAll bool // if true, render the "full" help menu
|
||||
|
||||
ShortSeparator string
|
||||
FullSeparator string
|
||||
|
||||
// The symbol we use in the short help when help items have been truncated
|
||||
// due to width. Periods of ellipsis by default.
|
||||
Ellipsis string
|
||||
|
||||
Styles Styles
|
||||
}
|
||||
|
||||
// NewModel creates a new help view with some useful defaults.
|
||||
func NewModel() Model {
|
||||
keyStyle := lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{
|
||||
Light: "#909090",
|
||||
Dark: "#626262",
|
||||
})
|
||||
|
||||
descStyle := lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{
|
||||
Light: "#B2B2B2",
|
||||
Dark: "#4A4A4A",
|
||||
})
|
||||
|
||||
sepStyle := lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{
|
||||
Light: "#DDDADA",
|
||||
Dark: "#3C3C3C",
|
||||
})
|
||||
|
||||
return Model{
|
||||
ShortSeparator: " • ",
|
||||
FullSeparator: " ",
|
||||
Ellipsis: "…",
|
||||
Styles: Styles{
|
||||
ShortKey: keyStyle,
|
||||
ShortDesc: descStyle,
|
||||
ShortSeparator: sepStyle,
|
||||
Ellipsis: sepStyle.Copy(),
|
||||
FullKey: keyStyle.Copy(),
|
||||
FullDesc: descStyle.Copy(),
|
||||
FullSeparator: sepStyle.Copy(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// View renders the help view's current state.
|
||||
func (m Model) View(k KeyMap) string {
|
||||
if m.ShowAll {
|
||||
return m.FullHelpView(k.FullHelp())
|
||||
}
|
||||
return m.ShortHelpView(k.ShortHelp())
|
||||
}
|
||||
|
||||
// ShortHelpView renders a single line help view from a slice of keybindings.
|
||||
// If the line is longer than the maximum width it will be gracefully
|
||||
// truncated, showing only as many help items as possible.
|
||||
func (m Model) ShortHelpView(bindings []key.Binding) string {
|
||||
if len(bindings) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
var totalWidth int
|
||||
var separator = m.Styles.ShortSeparator.Inline(true).Render(m.ShortSeparator)
|
||||
|
||||
for i, kb := range bindings {
|
||||
if !kb.Enabled() {
|
||||
continue
|
||||
}
|
||||
|
||||
var sep string
|
||||
if totalWidth > 0 && i < len(bindings) {
|
||||
sep = separator
|
||||
}
|
||||
|
||||
str := sep +
|
||||
m.Styles.ShortKey.Inline(true).Render(kb.Help().Key) + " " +
|
||||
m.Styles.ShortDesc.Inline(true).Render(kb.Help().Desc)
|
||||
|
||||
w := lipgloss.Width(str)
|
||||
|
||||
// If adding this help item would go over the available width, stop
|
||||
// drawing.
|
||||
if m.Width > 0 && totalWidth+w > m.Width {
|
||||
// Although if there's room for an ellipsis, print that.
|
||||
tail := " " + m.Styles.Ellipsis.Inline(true).Render(m.Ellipsis)
|
||||
tailWidth := lipgloss.Width(tail)
|
||||
|
||||
if totalWidth+tailWidth < m.Width {
|
||||
b.WriteString(tail)
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
totalWidth += w
|
||||
b.WriteString(str)
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// FullHelpView renders help columns from a slice of key binding slices. Each
|
||||
// top level slice entry renders into a column.
|
||||
func (m Model) FullHelpView(groups [][]key.Binding) string {
|
||||
if len(groups) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
var (
|
||||
out []string
|
||||
totalWidth int
|
||||
sep = m.Styles.FullSeparator.Render(m.FullSeparator)
|
||||
sepWidth = lipgloss.Width(sep)
|
||||
)
|
||||
|
||||
// Iterate over groups to build columns
|
||||
for i, group := range groups {
|
||||
if group == nil || !shouldRenderColumn(group) {
|
||||
continue
|
||||
}
|
||||
|
||||
var (
|
||||
keys []string
|
||||
descriptions []string
|
||||
)
|
||||
|
||||
// Separate keys and descriptions into different slices
|
||||
for _, kb := range group {
|
||||
if !kb.Enabled() {
|
||||
continue
|
||||
}
|
||||
keys = append(keys, kb.Help().Key)
|
||||
descriptions = append(descriptions, kb.Help().Desc)
|
||||
}
|
||||
|
||||
col := lipgloss.JoinHorizontal(lipgloss.Top,
|
||||
m.Styles.FullKey.Render(strings.Join(keys, "\n")),
|
||||
m.Styles.FullKey.Render(" "),
|
||||
m.Styles.FullDesc.Render(strings.Join(descriptions, "\n")),
|
||||
)
|
||||
|
||||
// Column
|
||||
totalWidth += lipgloss.Width(col)
|
||||
if totalWidth > m.Width {
|
||||
break
|
||||
}
|
||||
|
||||
out = append(out, col)
|
||||
|
||||
// Separator
|
||||
if i < len(group)-1 {
|
||||
totalWidth += sepWidth
|
||||
if totalWidth > m.Width {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
out = append(out, sep)
|
||||
}
|
||||
|
||||
return lipgloss.JoinHorizontal(lipgloss.Top, out...)
|
||||
}
|
||||
|
||||
func shouldRenderColumn(b []key.Binding) (ok bool) {
|
||||
for _, v := range b {
|
||||
if v.Enabled() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
139
key/key.go
Normal file
139
key/key.go
Normal file
@@ -0,0 +1,139 @@
|
||||
// Package key provides some types and functions for generating user-definable
|
||||
// keymappings useful in Bubble Tea components. There are a few different ways
|
||||
// you can define a keymapping with this package. Here's one example:
|
||||
//
|
||||
// type KeyMap struct {
|
||||
// Up key.Binding
|
||||
// Down key.Binding
|
||||
// }
|
||||
//
|
||||
// var DefaultKeyMap = KeyMap{
|
||||
// Up: key.NewBinding(
|
||||
// key.WithKeys("k", "up"), // actual keybindings
|
||||
// key.WithHelp("↑/k", "move up"), // corresponding help text
|
||||
// ),
|
||||
// Down: key.NewBinding(
|
||||
// WithKeys("j", "down"),
|
||||
// WithHelp("↓/j", "move down"),
|
||||
// ),
|
||||
// }
|
||||
//
|
||||
// func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
// switch msg := msg.(type) {
|
||||
// case tea.KeyMsg:
|
||||
// switch {
|
||||
// case key.Matches(msg, DefaultKeyMap.Up):
|
||||
// // The user pressed up
|
||||
// case key.Matches(msg, DefaultKeyMap.Down):
|
||||
// // The user pressed down
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // ...
|
||||
// }
|
||||
//
|
||||
// The help information, which is not used in the example above, can be used
|
||||
// to render help text for keystrokes in your views.
|
||||
package key
|
||||
|
||||
import (
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
// Binding describes a set of keybindings and, optionally, their associated
|
||||
// help text.
|
||||
type Binding struct {
|
||||
keys []string
|
||||
help Help
|
||||
disabled bool
|
||||
}
|
||||
|
||||
// BindingOpt is an initialization option for a keybinding. It's used as an
|
||||
// argument to NewBinding.
|
||||
type BindingOpt func(*Binding)
|
||||
|
||||
// NewBinding returns a new keybinding from a set of BindingOpt options.
|
||||
func NewBinding(opts ...BindingOpt) Binding {
|
||||
b := &Binding{}
|
||||
for _, opt := range opts {
|
||||
opt(b)
|
||||
}
|
||||
return *b
|
||||
}
|
||||
|
||||
// WithKeys initializes a keybinding with the given keystrokes.
|
||||
func WithKeys(keys ...string) BindingOpt {
|
||||
return func(b *Binding) {
|
||||
b.keys = keys
|
||||
}
|
||||
}
|
||||
|
||||
// WithHelp initializes a keybinding with the given help text.
|
||||
func WithHelp(key, desc string) BindingOpt {
|
||||
return func(b *Binding) {
|
||||
b.help = Help{Key: key, Desc: desc}
|
||||
}
|
||||
}
|
||||
|
||||
// WithDisabled initializes a disabled keybinding.
|
||||
func WithDisabled() BindingOpt {
|
||||
return func(b *Binding) {
|
||||
b.disabled = true
|
||||
}
|
||||
}
|
||||
|
||||
// SetKeys sets the keys for the keybinding.
|
||||
func (b *Binding) SetKeys(keys ...string) {
|
||||
b.keys = keys
|
||||
}
|
||||
|
||||
// Keys returns the keys for the keybinding.
|
||||
func (b Binding) Keys() []string {
|
||||
return b.keys
|
||||
}
|
||||
|
||||
// SetHelp sets the help text for the keybinding.
|
||||
func (b *Binding) SetHelp(key, desc string) {
|
||||
b.help = Help{Key: key, Desc: desc}
|
||||
}
|
||||
|
||||
// Help returns the Help information for the keybinding.
|
||||
func (b Binding) Help() Help {
|
||||
return b.help
|
||||
}
|
||||
|
||||
// Enabled returns whether or not the keybinding is enabled. Disabled
|
||||
// keybindings won't be activated and won't show up in help. Keybindings are
|
||||
// enabled by default.
|
||||
func (b Binding) Enabled() bool {
|
||||
return !b.disabled
|
||||
}
|
||||
|
||||
// SetEnabled enables or disables the keybinding.
|
||||
func (b *Binding) SetEnabled(v bool) {
|
||||
b.disabled = !v
|
||||
}
|
||||
|
||||
// Unbind removes the keys and help from this binding, effectively nullifying
|
||||
// it. This is a step beyond disabling it, since applications can enable
|
||||
// or disable key bindings based on application state.
|
||||
func (b *Binding) Unbind() {
|
||||
b.keys = nil
|
||||
b.help = Help{}
|
||||
}
|
||||
|
||||
// Help is help information for a given keybinding.
|
||||
type Help struct {
|
||||
Key string
|
||||
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
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
205
list/defaultitem.go
Normal file
205
list/defaultitem.go
Normal file
@@ -0,0 +1,205 @@
|
||||
package list
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/charmbracelet/bubbles/key"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/muesli/reflow/truncate"
|
||||
)
|
||||
|
||||
// DefaultItemStyles defines styling for a default list item.
|
||||
// See DefaultItemView for when these come into play.
|
||||
type DefaultItemStyles struct {
|
||||
// The Normal state.
|
||||
NormalTitle lipgloss.Style
|
||||
NormalDesc lipgloss.Style
|
||||
|
||||
// The selected item state.
|
||||
SelectedTitle lipgloss.Style
|
||||
SelectedDesc lipgloss.Style
|
||||
|
||||
// The dimmed state, for when the filter input is initially activated.
|
||||
DimmedTitle lipgloss.Style
|
||||
DimmedDesc lipgloss.Style
|
||||
|
||||
// Charcters matching the current filter, if any.
|
||||
FilterMatch lipgloss.Style
|
||||
}
|
||||
|
||||
// NewDefaultItemStyles returns style definitions for a default item. See
|
||||
// DefaultItemView for when these come into play.
|
||||
func NewDefaultItemStyles() (s DefaultItemStyles) {
|
||||
s.NormalTitle = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#1a1a1a", Dark: "#dddddd"}).
|
||||
Padding(0, 0, 0, 2)
|
||||
|
||||
s.NormalDesc = s.NormalTitle.Copy().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#A49FA5", Dark: "#777777"})
|
||||
|
||||
s.SelectedTitle = lipgloss.NewStyle().
|
||||
Border(lipgloss.NormalBorder(), false, false, false, true).
|
||||
BorderForeground(lipgloss.AdaptiveColor{Light: "#F793FF", Dark: "#AD58B4"}).
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#EE6FF8", Dark: "#EE6FF8"}).
|
||||
Padding(0, 0, 0, 1)
|
||||
|
||||
s.SelectedDesc = s.SelectedTitle.Copy().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#F793FF", Dark: "#AD58B4"})
|
||||
|
||||
s.DimmedTitle = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#A49FA5", Dark: "#777777"}).
|
||||
Padding(0, 0, 0, 2)
|
||||
|
||||
s.DimmedDesc = s.DimmedTitle.Copy().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#C2B8C2", Dark: "#4D4D4D"})
|
||||
|
||||
s.FilterMatch = lipgloss.NewStyle().Underline(true)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
// DefaultItem describes an items designed to work with DefaultDelegate.
|
||||
type DefaultItem interface {
|
||||
Item
|
||||
Title() string
|
||||
Description() string
|
||||
}
|
||||
|
||||
// DefaultDelegate is a standard delegate designed to work in lists. It's
|
||||
// styled by DefaultItemStyles, which can be customized as you like.
|
||||
//
|
||||
// The description line can be hidden by setting Description to false, which
|
||||
// renders the list as single-line-items. The spacing between items can be set
|
||||
// with the SetSpacing method.
|
||||
//
|
||||
// Setting UpdateFunc is optional. If it's set it will be called when the
|
||||
// ItemDelegate called, which is called when the list's Update function is
|
||||
// invoked.
|
||||
//
|
||||
// Settings ShortHelpFunc and FullHelpFunc is optional. They can can be set to
|
||||
// include items in the list's default short and full help menus.
|
||||
type DefaultDelegate struct {
|
||||
ShowDescription bool
|
||||
Styles DefaultItemStyles
|
||||
UpdateFunc func(tea.Msg, *Model) tea.Cmd
|
||||
ShortHelpFunc func() []key.Binding
|
||||
FullHelpFunc func() [][]key.Binding
|
||||
spacing int
|
||||
}
|
||||
|
||||
// NewDefaultDelegate creates a new delegate with default styles.
|
||||
func NewDefaultDelegate() DefaultDelegate {
|
||||
return DefaultDelegate{
|
||||
ShowDescription: true,
|
||||
Styles: NewDefaultItemStyles(),
|
||||
spacing: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// Height returns the delegate's preferred height.
|
||||
func (d DefaultDelegate) Height() int {
|
||||
if d.ShowDescription {
|
||||
return 2 //nolint:gomnd
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// SetSpacing set the delegate's spacing.
|
||||
func (d *DefaultDelegate) SetSpacing(i int) {
|
||||
d.spacing = i
|
||||
}
|
||||
|
||||
// Spacing returns the delegate's spacing.
|
||||
func (d DefaultDelegate) Spacing() int {
|
||||
return d.spacing
|
||||
}
|
||||
|
||||
// Update checks whether the delegate's UpdateFunc is set and calls it.
|
||||
func (d DefaultDelegate) Update(msg tea.Msg, m *Model) tea.Cmd {
|
||||
if d.UpdateFunc == nil {
|
||||
return nil
|
||||
}
|
||||
return d.UpdateFunc(msg, m)
|
||||
}
|
||||
|
||||
// Render prints an item.
|
||||
func (d DefaultDelegate) Render(w io.Writer, m Model, index int, item Item) {
|
||||
var (
|
||||
title, desc string
|
||||
matchedRunes []int
|
||||
s = &d.Styles
|
||||
)
|
||||
|
||||
if i, ok := item.(DefaultItem); ok {
|
||||
title = i.Title()
|
||||
desc = i.Description()
|
||||
} else {
|
||||
return
|
||||
}
|
||||
|
||||
// Prevent text from exceeding list width
|
||||
if m.width > 0 {
|
||||
textwidth := uint(m.width - s.NormalTitle.GetPaddingLeft() - s.NormalTitle.GetPaddingRight())
|
||||
title = truncate.StringWithTail(title, textwidth, ellipsis)
|
||||
desc = truncate.StringWithTail(desc, textwidth, ellipsis)
|
||||
}
|
||||
|
||||
// Conditions
|
||||
var (
|
||||
isSelected = index == m.Index()
|
||||
emptyFilter = m.FilterState() == Filtering && m.FilterValue() == ""
|
||||
isFiltered = m.FilterState() == Filtering || m.FilterState() == FilterApplied
|
||||
)
|
||||
|
||||
if isFiltered && index < len(m.filteredItems) {
|
||||
// Get indices of matched characters
|
||||
matchedRunes = m.MatchesForItem(index)
|
||||
}
|
||||
|
||||
if emptyFilter {
|
||||
title = s.DimmedTitle.Render(title)
|
||||
desc = s.DimmedDesc.Render(desc)
|
||||
} else if isSelected && m.FilterState() != Filtering {
|
||||
if isFiltered {
|
||||
// Highlight matches
|
||||
unmatched := s.SelectedTitle.Inline(true)
|
||||
matched := unmatched.Copy().Inherit(s.FilterMatch)
|
||||
title = lipgloss.StyleRunes(title, matchedRunes, matched, unmatched)
|
||||
}
|
||||
title = s.SelectedTitle.Render(title)
|
||||
desc = s.SelectedDesc.Render(desc)
|
||||
} else {
|
||||
if isFiltered {
|
||||
// Highlight matches
|
||||
unmatched := s.NormalTitle.Inline(true)
|
||||
matched := unmatched.Copy().Inherit(s.FilterMatch)
|
||||
title = lipgloss.StyleRunes(title, matchedRunes, matched, unmatched)
|
||||
}
|
||||
title = s.NormalTitle.Render(title)
|
||||
desc = s.NormalDesc.Render(desc)
|
||||
}
|
||||
|
||||
if d.ShowDescription {
|
||||
fmt.Fprintf(w, "%s\n%s", title, desc)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, "%s", title)
|
||||
}
|
||||
|
||||
// ShortHelp returns the delegate's short help.
|
||||
func (d DefaultDelegate) ShortHelp() []key.Binding {
|
||||
if d.ShortHelpFunc != nil {
|
||||
return d.ShortHelpFunc()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FullHelp returns the delegate's full help.
|
||||
func (d DefaultDelegate) FullHelp() [][]key.Binding {
|
||||
if d.FullHelpFunc != nil {
|
||||
return d.FullHelpFunc()
|
||||
}
|
||||
return nil
|
||||
}
|
97
list/keys.go
Normal file
97
list/keys.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package list
|
||||
|
||||
import "github.com/charmbracelet/bubbles/key"
|
||||
|
||||
// KeyMap defines keybindings. It satisfies to the help.KeyMap interface, which
|
||||
// is used to render the menu menu.
|
||||
type KeyMap struct {
|
||||
// Keybindings used when browsing the list.
|
||||
CursorUp key.Binding
|
||||
CursorDown key.Binding
|
||||
NextPage key.Binding
|
||||
PrevPage key.Binding
|
||||
GoToStart key.Binding
|
||||
GoToEnd key.Binding
|
||||
Filter key.Binding
|
||||
ClearFilter key.Binding
|
||||
|
||||
// Keybindings used when setting a filter.
|
||||
CancelWhileFiltering key.Binding
|
||||
AcceptWhileFiltering key.Binding
|
||||
|
||||
// Help toggle keybindings.
|
||||
ShowFullHelp key.Binding
|
||||
CloseFullHelp key.Binding
|
||||
|
||||
// The quit keybinding. This won't be caught when filtering.
|
||||
Quit key.Binding
|
||||
|
||||
// The quit-no-matter-what keybinding. This will be caught when filtering.
|
||||
ForceQuit key.Binding
|
||||
}
|
||||
|
||||
// DefaultKeyMap returns a default set of keybindings.
|
||||
func DefaultKeyMap() KeyMap {
|
||||
return KeyMap{
|
||||
// Browsing.
|
||||
CursorUp: key.NewBinding(
|
||||
key.WithKeys("up", "k"),
|
||||
key.WithHelp("↑/k", "up"),
|
||||
),
|
||||
CursorDown: key.NewBinding(
|
||||
key.WithKeys("down", "j"),
|
||||
key.WithHelp("↓/j", "down"),
|
||||
),
|
||||
PrevPage: key.NewBinding(
|
||||
key.WithKeys("left", "h", "pgup", "b", "u"),
|
||||
key.WithHelp("←/h/pgup", "prev page"),
|
||||
),
|
||||
NextPage: key.NewBinding(
|
||||
key.WithKeys("right", "l", "pgdown", "f", "d"),
|
||||
key.WithHelp("→/l/pgdn", "next page"),
|
||||
),
|
||||
GoToStart: key.NewBinding(
|
||||
key.WithKeys("home", "g"),
|
||||
key.WithHelp("g/home", "go to start"),
|
||||
),
|
||||
GoToEnd: key.NewBinding(
|
||||
key.WithKeys("end", "G"),
|
||||
key.WithHelp("G/end", "go to end"),
|
||||
),
|
||||
Filter: key.NewBinding(
|
||||
key.WithKeys("/"),
|
||||
key.WithHelp("/", "filter"),
|
||||
),
|
||||
ClearFilter: key.NewBinding(
|
||||
key.WithKeys("esc"),
|
||||
key.WithHelp("esc", "clear filter"),
|
||||
),
|
||||
|
||||
// Filtering.
|
||||
CancelWhileFiltering: key.NewBinding(
|
||||
key.WithKeys("esc"),
|
||||
key.WithHelp("esc", "cancel"),
|
||||
),
|
||||
AcceptWhileFiltering: key.NewBinding(
|
||||
key.WithKeys("enter", "tab", "shift+tab", "ctrl+k", "up", "ctrl+j", "down"),
|
||||
key.WithHelp("enter", "apply filter"),
|
||||
),
|
||||
|
||||
// Toggle help.
|
||||
ShowFullHelp: key.NewBinding(
|
||||
key.WithKeys("?"),
|
||||
key.WithHelp("?", "more"),
|
||||
),
|
||||
CloseFullHelp: key.NewBinding(
|
||||
key.WithKeys("?"),
|
||||
key.WithHelp("?", "close help"),
|
||||
),
|
||||
|
||||
// Quitting.
|
||||
Quit: key.NewBinding(
|
||||
key.WithKeys("q", "esc"),
|
||||
key.WithHelp("q", "quit"),
|
||||
),
|
||||
ForceQuit: key.NewBinding(key.WithKeys("ctrl+c")),
|
||||
}
|
||||
}
|
1197
list/list.go
Normal file
1197
list/list.go
Normal file
File diff suppressed because it is too large
Load Diff
99
list/style.go
Normal file
99
list/style.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package list
|
||||
|
||||
import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
const (
|
||||
bullet = "•"
|
||||
ellipsis = "…"
|
||||
)
|
||||
|
||||
// Styles contains style definitions for this list component. By default, these
|
||||
// values are generated by DefaultStyles.
|
||||
type Styles struct {
|
||||
TitleBar lipgloss.Style
|
||||
Title lipgloss.Style
|
||||
Spinner lipgloss.Style
|
||||
FilterPrompt lipgloss.Style
|
||||
FilterCursor lipgloss.Style
|
||||
|
||||
// Default styling for matched characters in a filter. This can be
|
||||
// overridden by delegates.
|
||||
DefaultFilterCharacterMatch lipgloss.Style
|
||||
|
||||
StatusBar lipgloss.Style
|
||||
StatusEmpty lipgloss.Style
|
||||
StatusBarActiveFilter lipgloss.Style
|
||||
StatusBarFilterCount lipgloss.Style
|
||||
|
||||
NoItems lipgloss.Style
|
||||
|
||||
PaginationStyle lipgloss.Style
|
||||
HelpStyle lipgloss.Style
|
||||
|
||||
// Styled characters.
|
||||
ActivePaginationDot lipgloss.Style
|
||||
InactivePaginationDot lipgloss.Style
|
||||
ArabicPagination lipgloss.Style
|
||||
DividerDot lipgloss.Style
|
||||
}
|
||||
|
||||
// DefaultStyles returns a set of default style definitions for this list
|
||||
// component.
|
||||
func DefaultStyles() (s Styles) {
|
||||
verySubduedColor := lipgloss.AdaptiveColor{Light: "#DDDADA", Dark: "#3C3C3C"}
|
||||
subduedColor := lipgloss.AdaptiveColor{Light: "#9B9B9B", Dark: "#5C5C5C"}
|
||||
|
||||
s.TitleBar = lipgloss.NewStyle().Padding(0, 0, 1, 2)
|
||||
|
||||
s.Title = lipgloss.NewStyle().
|
||||
Background(lipgloss.Color("62")).
|
||||
Foreground(lipgloss.Color("230")).
|
||||
Padding(0, 1)
|
||||
|
||||
s.Spinner = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#8E8E8E", Dark: "#747373"})
|
||||
|
||||
s.FilterPrompt = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#04B575", Dark: "#ECFD65"})
|
||||
|
||||
s.FilterCursor = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#EE6FF8", Dark: "#EE6FF8"})
|
||||
|
||||
s.DefaultFilterCharacterMatch = lipgloss.NewStyle().Underline(true)
|
||||
|
||||
s.StatusBar = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#A49FA5", Dark: "#777777"}).
|
||||
Padding(0, 0, 1, 2)
|
||||
|
||||
s.StatusEmpty = lipgloss.NewStyle().Foreground(subduedColor)
|
||||
|
||||
s.StatusBarActiveFilter = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#1a1a1a", Dark: "#dddddd"})
|
||||
|
||||
s.StatusBarFilterCount = lipgloss.NewStyle().Foreground(verySubduedColor)
|
||||
|
||||
s.NoItems = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#909090", Dark: "#626262"})
|
||||
|
||||
s.ArabicPagination = lipgloss.NewStyle().Foreground(subduedColor)
|
||||
|
||||
s.PaginationStyle = lipgloss.NewStyle().PaddingLeft(2) //nolint:gomnd
|
||||
|
||||
s.HelpStyle = lipgloss.NewStyle().Padding(1, 0, 0, 2)
|
||||
|
||||
s.ActivePaginationDot = lipgloss.NewStyle().
|
||||
Foreground(lipgloss.AdaptiveColor{Light: "#847A85", Dark: "#979797"}).
|
||||
SetString(bullet)
|
||||
|
||||
s.InactivePaginationDot = lipgloss.NewStyle().
|
||||
Foreground(verySubduedColor).
|
||||
SetString(bullet)
|
||||
|
||||
s.DividerDot = lipgloss.NewStyle().
|
||||
Foreground(verySubduedColor).
|
||||
SetString(" " + bullet + " ")
|
||||
|
||||
return s
|
||||
}
|
@@ -35,7 +35,7 @@ type Model struct {
|
||||
UseJKKeys bool
|
||||
}
|
||||
|
||||
// SetTotalPages is a helper function for calculatng the total number of pages
|
||||
// SetTotalPages is a helper function for calculating the total number of pages
|
||||
// from a given number of items. It's use is optional since this pager can be
|
||||
// used for other things beyond navigating sets. Note that it both returns the
|
||||
// number of total pages and alters the model.
|
||||
|
@@ -2,14 +2,40 @@ package progress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/harmonica"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/lucasb-eyer/go-colorful"
|
||||
"github.com/muesli/reflow/ansi"
|
||||
"github.com/muesli/termenv"
|
||||
)
|
||||
|
||||
const defaultWidth = 40
|
||||
// Internal ID management. Used during animating to assure that frame messages
|
||||
// can only be received by progress components that sent them.
|
||||
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
|
||||
}
|
||||
|
||||
const (
|
||||
fps = 60
|
||||
defaultWidth = 40
|
||||
defaultFrequency = 18.0
|
||||
defaultDamping = 1.0
|
||||
)
|
||||
|
||||
var color func(string) termenv.Color = termenv.ColorProfile().Color
|
||||
|
||||
@@ -19,7 +45,8 @@ var color func(string) termenv.Color = termenv.ColorProfile().Color
|
||||
// WithRamp("#ff0000", "#0000ff"),
|
||||
// WithoutPercentage(),
|
||||
// )
|
||||
type Option func(*Model) error
|
||||
//
|
||||
type Option func(*Model)
|
||||
|
||||
// WithDefaultGradient sets a gradient fill with default colors.
|
||||
func WithDefaultGradient() Option {
|
||||
@@ -28,8 +55,8 @@ func WithDefaultGradient() Option {
|
||||
|
||||
// WithGradient sets a gradient fill blending between two colors.
|
||||
func WithGradient(colorA, colorB string) Option {
|
||||
return func(m *Model) error {
|
||||
return m.setRamp(colorA, colorB, false)
|
||||
return func(m *Model) {
|
||||
m.setRamp(colorA, colorB, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,25 +69,23 @@ func WithDefaultScaledGradient() Option {
|
||||
// WithScaledGradient scales the gradient to fit the width of the filled portion of
|
||||
// the progress bar.
|
||||
func WithScaledGradient(colorA, colorB string) Option {
|
||||
return func(m *Model) error {
|
||||
return m.setRamp(colorA, colorB, true)
|
||||
return func(m *Model) {
|
||||
m.setRamp(colorA, colorB, true)
|
||||
}
|
||||
}
|
||||
|
||||
// WithSolidFill sets the progress to use a solid fill with the given color.
|
||||
func WithSolidFill(color string) Option {
|
||||
return func(m *Model) error {
|
||||
return func(m *Model) {
|
||||
m.FullColor = color
|
||||
m.useRamp = false
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// WithoutPercentage hides the numeric percentage.
|
||||
func WithoutPercentage() Option {
|
||||
return func(m *Model) error {
|
||||
return func(m *Model) {
|
||||
m.ShowPercentage = false
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,31 +93,57 @@ func WithoutPercentage() Option {
|
||||
// set the width via the Width property, which can come in handy if you're
|
||||
// waiting for a tea.WindowSizeMsg.
|
||||
func WithWidth(w int) Option {
|
||||
return func(m *Model) error {
|
||||
return func(m *Model) {
|
||||
m.Width = w
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func WithSpringOptions(frequency, damping float64) Option {
|
||||
return func(m *Model) {
|
||||
m.SetSpringOptions(frequency, damping)
|
||||
m.springCustomized = true
|
||||
}
|
||||
}
|
||||
|
||||
// FrameMsg indicates that an animation step should occur.
|
||||
type FrameMsg struct {
|
||||
id int
|
||||
tag int
|
||||
}
|
||||
|
||||
// Model stores values we'll use when rendering the progress bar.
|
||||
type Model struct {
|
||||
// An identifier to keep us from receiving messages intended for other
|
||||
// progress bars.
|
||||
id int
|
||||
|
||||
// An identifier to keep us from receiving frame messages too quickly.
|
||||
tag int
|
||||
|
||||
// Total width of the progress bar, including percentage, if set.
|
||||
Width int
|
||||
|
||||
// "Filled" sections of the progress bar
|
||||
// "Filled" sections of the progress bar.
|
||||
Full rune
|
||||
FullColor string
|
||||
|
||||
// "Empty" sections of progress bar
|
||||
// "Empty" sections of progress bar.
|
||||
Empty rune
|
||||
EmptyColor string
|
||||
|
||||
// Settings for rendering the numeric percentage
|
||||
// Settings for rendering the numeric percentage.
|
||||
ShowPercentage bool
|
||||
PercentFormat string // a fmt string for a float
|
||||
PercentageStyle *termenv.Style
|
||||
PercentageStyle lipgloss.Style
|
||||
|
||||
// Members for animated transitions.
|
||||
spring harmonica.Spring
|
||||
springCustomized bool
|
||||
percent float64
|
||||
targetPercent float64
|
||||
velocity float64
|
||||
|
||||
// Gradient settings
|
||||
useRamp bool
|
||||
rampColorA colorful.Color
|
||||
rampColorB colorful.Color
|
||||
@@ -104,8 +155,9 @@ type Model struct {
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
func NewModel(opts ...Option) (*Model, error) {
|
||||
m := &Model{
|
||||
func NewModel(opts ...Option) Model {
|
||||
m := Model{
|
||||
id: nextID(),
|
||||
Width: defaultWidth,
|
||||
Full: '█',
|
||||
FullColor: "#7571F9",
|
||||
@@ -114,39 +166,117 @@ func NewModel(opts ...Option) (*Model, error) {
|
||||
ShowPercentage: true,
|
||||
PercentFormat: " %3.0f%%",
|
||||
}
|
||||
if !m.springCustomized {
|
||||
m.SetSpringOptions(defaultFrequency, defaultDamping)
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
if err := opt(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opt(&m)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
return m
|
||||
}
|
||||
|
||||
// View renders the progress bar as a given percentage.
|
||||
func (m Model) View(percent float64) string {
|
||||
b := strings.Builder{}
|
||||
if m.ShowPercentage {
|
||||
percentage := fmt.Sprintf(m.PercentFormat, percent*100) //nolint:gomnd
|
||||
if m.PercentageStyle != nil {
|
||||
percentage = m.PercentageStyle.Styled(percentage)
|
||||
// Init exists satisfy the tea.Model interface.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update is used to animation the progress bar during transitions. Use
|
||||
// SetPercent to create the command you'll need to trigger the animation.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case FrameMsg:
|
||||
if msg.id != m.id || msg.tag != m.tag {
|
||||
return m, nil
|
||||
}
|
||||
m.bar(&b, percent, ansi.PrintableRuneWidth(percentage))
|
||||
b.WriteString(percentage)
|
||||
} else {
|
||||
m.bar(&b, percent, 0)
|
||||
|
||||
// If we've more or less reached equilibrium, stop updating.
|
||||
dist := math.Abs(m.percent - m.targetPercent)
|
||||
if dist < 0.001 && m.velocity < 0.01 {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
m.percent, m.velocity = m.spring.Update(m.percent, m.velocity, m.targetPercent)
|
||||
return m, m.nextFrame()
|
||||
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (m *Model) SetSpringOptions(frequency, damping float64) {
|
||||
m.spring = harmonica.NewSpring(harmonica.FPS(fps), frequency, damping)
|
||||
}
|
||||
|
||||
// Percent returns the current percentage state of the model. This is only
|
||||
// relevant when you're animating the progress bar.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m Model) Percent() float64 {
|
||||
return m.targetPercent
|
||||
}
|
||||
|
||||
// SetPercent sets the percentage state of the model as well as a command
|
||||
// necessary for animating the progress bar to this new percentage.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m *Model) SetPercent(p float64) tea.Cmd {
|
||||
m.targetPercent = math.Max(0, math.Min(1, p))
|
||||
m.tag++
|
||||
return m.nextFrame()
|
||||
}
|
||||
|
||||
// IncrPercent increments the percentage by a given amount, returning a command
|
||||
// necessary to animate the progress bar to the new percentage.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m *Model) IncrPercent(v float64) tea.Cmd {
|
||||
return m.SetPercent(m.Percent() + v)
|
||||
}
|
||||
|
||||
// DecrPercent decrements the percentage by a given amount, returning a command
|
||||
// necessary to animate the progress bar to the new percentage.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m *Model) DecrPercent(v float64) tea.Cmd {
|
||||
return m.SetPercent(m.Percent() - v)
|
||||
}
|
||||
|
||||
// View renders the an animated progress bar in its current state. To render
|
||||
// a static progress bar based on your own calculations use ViewAs instead.
|
||||
func (m Model) View() string {
|
||||
return m.ViewAs(m.percent)
|
||||
}
|
||||
|
||||
// ViewAs renders the progress bar with a given percentage.
|
||||
func (m Model) ViewAs(percent float64) string {
|
||||
b := strings.Builder{}
|
||||
percentView := m.percentageView(percent)
|
||||
m.barView(&b, percent, ansi.PrintableRuneWidth(percentView))
|
||||
b.WriteString(percentView)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m Model) bar(b *strings.Builder, percent float64, textWidth int) {
|
||||
func (m *Model) nextFrame() tea.Cmd {
|
||||
return tea.Tick(time.Second/time.Duration(fps), func(time.Time) tea.Msg {
|
||||
return FrameMsg{id: m.id, tag: m.tag}
|
||||
})
|
||||
}
|
||||
|
||||
func (m Model) barView(b *strings.Builder, percent float64, textWidth int) {
|
||||
var (
|
||||
tw = m.Width - textWidth // total width
|
||||
fw = int(float64(tw) * percent) // filled width
|
||||
tw = max(0, m.Width-textWidth) // total width
|
||||
fw = int(math.Round((float64(tw) * percent))) // filled width
|
||||
p float64
|
||||
)
|
||||
|
||||
fw = max(0, min(tw, fw))
|
||||
|
||||
if m.useRamp {
|
||||
// Gradient fill
|
||||
for i := 0; i < fw; i++ {
|
||||
@@ -170,23 +300,43 @@ func (m Model) bar(b *strings.Builder, percent float64, textWidth int) {
|
||||
|
||||
// Empty fill
|
||||
e := termenv.String(string(m.Empty)).Foreground(color(m.EmptyColor)).String()
|
||||
b.WriteString(strings.Repeat(e, tw-fw))
|
||||
n := max(0, tw-fw)
|
||||
b.WriteString(strings.Repeat(e, n))
|
||||
}
|
||||
|
||||
func (m *Model) setRamp(colorA, colorB string, scaled bool) error {
|
||||
a, err := colorful.Hex(colorA)
|
||||
if err != nil {
|
||||
return err
|
||||
func (m Model) percentageView(percent float64) string {
|
||||
if !m.ShowPercentage {
|
||||
return ""
|
||||
}
|
||||
percent = math.Max(0, math.Min(1, percent))
|
||||
percentage := fmt.Sprintf(m.PercentFormat, percent*100) //nolint:gomnd
|
||||
percentage = m.PercentageStyle.Inline(true).Render(percentage)
|
||||
return percentage
|
||||
}
|
||||
|
||||
b, err := colorful.Hex(colorB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
func (m *Model) setRamp(colorA, colorB string, scaled bool) {
|
||||
// In the event of an error colors here will default to black. For
|
||||
// usability's sake, and because such an error is only cosmetic, we're
|
||||
// ignoring the error for sake of usability.
|
||||
a, _ := colorful.Hex(colorA)
|
||||
b, _ := colorful.Hex(colorB)
|
||||
|
||||
m.useRamp = true
|
||||
m.scaleRamp = scaled
|
||||
m.rampColorA = a
|
||||
m.rampColorB = b
|
||||
return nil
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
Reference in New Issue
Block a user