mirror of
https://github.com/Maks1mS/bubbles.git
synced 2025-10-17 16:15:58 +03:00
Compare commits
81 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 | ||
|
da9248f877 | ||
|
b691d7f07e | ||
|
8ad268837a | ||
|
0f290114f5 | ||
|
500d7989e1 | ||
|
d987ef84f2 | ||
|
cb52746b97 | ||
|
985ffcb319 | ||
|
4e18245481 | ||
|
0be588365e | ||
|
4c32a64d65 | ||
|
e723cfd15e | ||
|
90d8eaffeb | ||
|
202d5a9f9d | ||
|
446433d680 | ||
|
2cd3b16343 | ||
|
5ae3b7b822 | ||
|
20ead8fb7d | ||
|
09a4cf419d | ||
|
d06aa4aa48 | ||
|
10962af2f2 | ||
|
5082ae6f31 | ||
|
4365990396 | ||
|
1405b09ec8 | ||
|
f53c742d6c | ||
|
9449cc7e41 | ||
|
58a177394e | ||
|
f016c31d83 | ||
|
74436326b9 | ||
|
158097df66 | ||
|
0d5d7e5acd | ||
|
ddd48d9ab7 | ||
|
7242bbe8dc | ||
|
9e324205c2 | ||
|
b2f42066a2 | ||
|
a0d7cb77a1 | ||
|
046b9ca129 | ||
|
da9a4049de | ||
|
490a599c05 | ||
|
f719cc8cb1 |
2
.github/workflows/lint.yml
vendored
2
.github/workflows/lint.yml
vendored
@@ -10,8 +10,6 @@ jobs:
|
|||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v2
|
||||||
with:
|
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.
|
# Optional: golangci-lint command line arguments.
|
||||||
args: --issues-exit-code=0
|
args: --issues-exit-code=0
|
||||||
# Optional: working directory, useful for monorepos
|
# Optional: working directory, useful for monorepos
|
||||||
|
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 }}"
|
@@ -2,6 +2,13 @@ run:
|
|||||||
tests: false
|
tests: false
|
||||||
|
|
||||||
issues:
|
issues:
|
||||||
|
include:
|
||||||
|
- EXC0001
|
||||||
|
- EXC0005
|
||||||
|
- EXC0011
|
||||||
|
- EXC0012
|
||||||
|
- EXC0013
|
||||||
|
|
||||||
max-issues-per-linter: 0
|
max-issues-per-linter: 0
|
||||||
max-same-issues: 0
|
max-same-issues: 0
|
||||||
|
|
||||||
@@ -14,11 +21,12 @@ linters:
|
|||||||
- godot
|
- godot
|
||||||
- godox
|
- godox
|
||||||
- goimports
|
- goimports
|
||||||
- gomnd
|
|
||||||
- goprintffuncname
|
- goprintffuncname
|
||||||
- gosec
|
- gosec
|
||||||
|
- ifshort
|
||||||
- misspell
|
- misspell
|
||||||
- prealloc
|
- prealloc
|
||||||
|
- revive
|
||||||
- rowserrcheck
|
- rowserrcheck
|
||||||
- sqlclosecheck
|
- sqlclosecheck
|
||||||
- unconvert
|
- unconvert
|
||||||
|
140
README.md
140
README.md
@@ -8,14 +8,15 @@ Bubbles
|
|||||||
[](https://github.com/charmbracelet/bubbles/releases)
|
[](https://github.com/charmbracelet/bubbles/releases)
|
||||||
[](https://pkg.go.dev/github.com/charmbracelet/bubbles)
|
[](https://pkg.go.dev/github.com/charmbracelet/bubbles)
|
||||||
[](https://github.com/charmbracelet/bubbles/actions)
|
[](https://github.com/charmbracelet/bubbles/actions)
|
||||||
[](http://goreportcard.com/report/charmbracelet/bubbles)
|
[](https://goreportcard.com/report/charmbracelet/bubbles)
|
||||||
|
|
||||||
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea) applications.
|
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea)
|
||||||
|
applications. These components are used in production in [Glow][glow],
|
||||||
These components are used in production in [Glow][glow] and [Charm][charm].
|
[Charm][charm] and [many other applications][otherstuff].
|
||||||
|
|
||||||
[glow]: https://github.com/charmbracelet/glow
|
[glow]: https://github.com/charmbracelet/glow
|
||||||
[charm]: https://github.com/charmbracelet/charm
|
[charm]: https://github.com/charmbracelet/charm
|
||||||
|
[otherstuff]: https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild
|
||||||
|
|
||||||
|
|
||||||
## Spinner
|
## 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.
|
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.”
|
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
|
## 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">
|
<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
|
A simple, customizable progress meter, with optional animation via
|
||||||
empty and filled runes can be set to whatever you'd like. The percentage readout
|
[Harmonica][harmonica]. Supports solid and gradient fills. The empty and filled
|
||||||
is customizable and can also be omitted entirely.
|
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
|
## Paginator
|
||||||
@@ -60,13 +66,12 @@ 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
|
numeric page numbering, but you could also just use this component for the
|
||||||
logic and visualize pagination however you like.
|
logic and visualize pagination however you like.
|
||||||
|
|
||||||
This component is used in [Glow][glow] to browse documents and [Charm][charm] to
|
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/pager/main.go)
|
||||||
browse SSH keys.
|
|
||||||
|
|
||||||
|
|
||||||
## Viewport
|
## 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
|
A viewport for vertically scrolling content. Optionally includes standard
|
||||||
pager keybindings and mouse wheel support. A high performance mode is available
|
pager keybindings and mouse wheel support. A high performance mode is available
|
||||||
@@ -74,12 +79,115 @@ for applications which make use of the alternate screen buffer.
|
|||||||
|
|
||||||
* [Example code](https://github.com/charmbracelet/tea/tree/master/examples/pager/main.go)
|
* [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.
|
indenting and text wrapping.
|
||||||
|
|
||||||
[reflow]: https://github.com/muesli/reflow
|
[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)
|
||||||
|
|
||||||
|
|
||||||
|
## 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">
|
||||||
|
|
||||||
|
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(
|
||||||
|
key.WithKeys("j", "down"),
|
||||||
|
key.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.
|
||||||
|
* [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).
|
||||||
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
[MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
|
[MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
|
||||||
@@ -89,6 +197,8 @@ indenting and text wrapping.
|
|||||||
|
|
||||||
Part of [Charm](https://charm.sh).
|
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热爱开源 • Charm loves open source
|
||||||
|
|
||||||
|
[charm]: https://charm.sh/
|
||||||
|
18
go.mod
18
go.mod
@@ -3,12 +3,14 @@ module github.com/charmbracelet/bubbles
|
|||||||
go 1.13
|
go 1.13
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/atotto/clipboard v0.1.2
|
github.com/atotto/clipboard v0.1.4
|
||||||
github.com/charmbracelet/bubbletea v0.12.2
|
github.com/charmbracelet/bubbletea v0.19.3
|
||||||
github.com/lucasb-eyer/go-colorful v1.0.3
|
github.com/charmbracelet/harmonica v0.1.0
|
||||||
github.com/mattn/go-runewidth v0.0.9
|
github.com/charmbracelet/lipgloss v0.4.0
|
||||||
github.com/muesli/reflow v0.2.0
|
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||||
github.com/muesli/termenv v0.7.4
|
github.com/lucasb-eyer/go-colorful v1.2.0
|
||||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 // indirect
|
github.com/mattn/go-runewidth v0.0.13
|
||||||
golang.org/x/sys v0.0.0-20201020230747-6e5568b54d1a // indirect
|
github.com/muesli/reflow v0.3.0
|
||||||
|
github.com/muesli/termenv v0.9.0
|
||||||
|
github.com/sahilm/fuzzy v0.1.0
|
||||||
)
|
)
|
||||||
|
75
go.sum
75
go.sum
@@ -1,37 +1,44 @@
|
|||||||
github.com/atotto/clipboard v0.1.2 h1:YZCtFu5Ie8qX2VmVTBnrqLSiU9XOWwqNRmdT3gIQzbY=
|
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
||||||
github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||||
github.com/charmbracelet/bubbletea v0.12.2 h1:y9Yo2Pv8tcm3mAJsWONGsmHhzrbNxJVxpVtemikxE9A=
|
github.com/charmbracelet/bubbletea v0.19.3 h1:OKeO/Y13rQQqt4snX+lePB0QrnW80UdrMNolnCcmoAw=
|
||||||
github.com/charmbracelet/bubbletea v0.12.2/go.mod h1:3gZkYELUOiEUOp0bTInkxguucy/xRbGSOcbMs1geLxg=
|
github.com/charmbracelet/bubbletea v0.19.3/go.mod h1:VuXF2pToRxDUHcBUcPmCRUHRvFATM4Ckb/ql1rBl3KA=
|
||||||
github.com/containerd/console v1.0.1 h1:u7SFAJyRqWcG6ogaMAx3KjSTy1e3hT9QxqX7Jco7dRc=
|
github.com/charmbracelet/harmonica v0.1.0 h1:lFKeSd6OAckQ/CEzPVd2mqj+YMEubQ/3FM2IYY3xNm0=
|
||||||
github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw=
|
github.com/charmbracelet/harmonica v0.1.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
|
||||||
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=
|
github.com/charmbracelet/lipgloss v0.4.0 h1:768h64EFkGUr8V5yAKV7/Ta0NiVceiPaV+PphaW1K9g=
|
||||||
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=
|
github.com/charmbracelet/lipgloss v0.4.0/go.mod h1:vmdkHvce7UzX6xkyf4cca8WlwdQ5RQr8fzta+xl7BOM=
|
||||||
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
|
github.com/containerd/console v1.0.2 h1:Pi6D+aZXM+oUw1czuKgH5IJ+y0jhYcwBJfx5/Ghn9dE=
|
||||||
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ=
|
||||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||||
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
|
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||||
github.com/muesli/reflow v0.2.0 h1:2o0UBJPHHH4fa2GCXU4Rg4DwOtWPMekCeyc5EWbAQp0=
|
github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA=
|
||||||
github.com/muesli/reflow v0.2.0/go.mod h1:qT22vjVmM9MIUeLgsVYe/Ye7eZlbv9dZjL3dVhUqLX8=
|
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
github.com/muesli/termenv v0.7.2 h1:r1raklL3uKE7rOvWgSenmEm2px+dnc33OTisZ8YR1fw=
|
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||||
github.com/muesli/termenv v0.7.2/go.mod h1:ct2L5N2lmix82RaY3bMWwVu/jUFc9Ule0KGDCiKYPh8=
|
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||||
github.com/muesli/termenv v0.7.4 h1:/pBqvU5CpkY53tU0vVn+xgs2ZTX63aH5nY+SSps5Xa8=
|
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
|
||||||
github.com/muesli/termenv v0.7.4/go.mod h1:pZ7qY9l3F7e5xsAOS0zCew2tME+p7bWeBkotCEcIIcc=
|
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.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 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee h1:4yd7jl+vXjalO5ztz6Vc1VADv+S/80LGJmyl1ROJ2AI=
|
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E=
|
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||||
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
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-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-20201009025420-dfb3f7c4e634 h1:bNEHhJCnrwMKNMmOx3yAynp5vs5/gRy+XWFtZFu7NBM=
|
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
|
||||||
golang.org/x/sys v0.0.0-20201020230747-6e5568b54d1a h1:e3IU37lwO4aq3uoRKINC7JikojFmE5gO7xhfxs8VC34=
|
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201020230747-6e5568b54d1a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed h1:Ei4bQjjpYUsS4efOUz+5Nz++IVkHk87n2zBA0NxBWc0=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
234
help/help.go
Normal file
234
help/help.go
Normal file
@@ -0,0 +1,234 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a new help view with some useful defaults.
|
||||||
|
func New() 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(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 (
|
||||||
|
// 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)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
141
key/key.go
Normal file
141
key/key.go
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
// 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(
|
||||||
|
// key.WithKeys("j", "down"),
|
||||||
|
// key.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 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
|
||||||
|
}
|
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")),
|
||||||
|
}
|
||||||
|
}
|
1202
list/list.go
Normal file
1202
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
|
||||||
|
}
|
@@ -1,4 +1,4 @@
|
|||||||
// package paginator provides a Bubble Tea package for calulating pagination
|
// Package paginator provides a Bubble Tea package for calulating pagination
|
||||||
// and rendering pagination info. Note that this package does not render actual
|
// and rendering pagination info. Note that this package does not render actual
|
||||||
// pages: it's purely for handling keystrokes related to pagination, and
|
// pages: it's purely for handling keystrokes related to pagination, and
|
||||||
// rendering pagination status.
|
// rendering pagination status.
|
||||||
@@ -35,7 +35,7 @@ type Model struct {
|
|||||||
UseJKKeys bool
|
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
|
// 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
|
// used for other things beyond navigating sets. Note that it both returns the
|
||||||
// number of total pages and alters the model.
|
// number of total pages and alters the model.
|
||||||
@@ -91,13 +91,13 @@ func (m *Model) NextPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// LastPage returns whether or not we're on the last page.
|
// OnLastPage returns whether or not we're on the last page.
|
||||||
func (m Model) OnLastPage() bool {
|
func (m Model) OnLastPage() bool {
|
||||||
return m.Page == m.TotalPages-1
|
return m.Page == m.TotalPages-1
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModel creates a new model with defaults.
|
// New creates a new model with defaults.
|
||||||
func NewModel() Model {
|
func New() Model {
|
||||||
return Model{
|
return Model{
|
||||||
Type: Arabic,
|
Type: Arabic,
|
||||||
Page: 0,
|
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.
|
// Update is the Tea update function which binds keystrokes to pagination.
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
|
@@ -2,14 +2,40 @@ package progress
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/harmonica"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
"github.com/lucasb-eyer/go-colorful"
|
"github.com/lucasb-eyer/go-colorful"
|
||||||
"github.com/muesli/reflow/ansi"
|
"github.com/muesli/reflow/ansi"
|
||||||
"github.com/muesli/termenv"
|
"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
|
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"),
|
// WithRamp("#ff0000", "#0000ff"),
|
||||||
// WithoutPercentage(),
|
// WithoutPercentage(),
|
||||||
// )
|
// )
|
||||||
type Option func(*Model) error
|
//
|
||||||
|
type Option func(*Model)
|
||||||
|
|
||||||
// WithDefaultGradient sets a gradient fill with default colors.
|
// WithDefaultGradient sets a gradient fill with default colors.
|
||||||
func WithDefaultGradient() Option {
|
func WithDefaultGradient() Option {
|
||||||
@@ -28,8 +55,8 @@ func WithDefaultGradient() Option {
|
|||||||
|
|
||||||
// WithGradient sets a gradient fill blending between two colors.
|
// WithGradient sets a gradient fill blending between two colors.
|
||||||
func WithGradient(colorA, colorB string) Option {
|
func WithGradient(colorA, colorB string) Option {
|
||||||
return func(m *Model) error {
|
return func(m *Model) {
|
||||||
return m.setRamp(colorA, colorB, false)
|
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
|
// WithScaledGradient scales the gradient to fit the width of the filled portion of
|
||||||
// the progress bar.
|
// the progress bar.
|
||||||
func WithScaledGradient(colorA, colorB string) Option {
|
func WithScaledGradient(colorA, colorB string) Option {
|
||||||
return func(m *Model) error {
|
return func(m *Model) {
|
||||||
return m.setRamp(colorA, colorB, true)
|
m.setRamp(colorA, colorB, true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// WithSolidFill sets the progress to use a solid fill with the given color.
|
// WithSolidFill sets the progress to use a solid fill with the given color.
|
||||||
func WithSolidFill(color string) Option {
|
func WithSolidFill(color string) Option {
|
||||||
return func(m *Model) error {
|
return func(m *Model) {
|
||||||
m.FullColor = color
|
m.FullColor = color
|
||||||
m.useRamp = false
|
m.useRamp = false
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// WithoutPercentage hides the numeric percentage.
|
// WithoutPercentage hides the numeric percentage.
|
||||||
func WithoutPercentage() Option {
|
func WithoutPercentage() Option {
|
||||||
return func(m *Model) error {
|
return func(m *Model) {
|
||||||
m.ShowPercentage = false
|
m.ShowPercentage = false
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,31 +93,62 @@ func WithoutPercentage() Option {
|
|||||||
// set the width via the Width property, which can come in handy if you're
|
// set the width via the Width property, which can come in handy if you're
|
||||||
// waiting for a tea.WindowSizeMsg.
|
// waiting for a tea.WindowSizeMsg.
|
||||||
func WithWidth(w int) Option {
|
func WithWidth(w int) Option {
|
||||||
return func(m *Model) error {
|
return func(m *Model) {
|
||||||
m.Width = w
|
m.Width = w
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
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.
|
// Model stores values we'll use when rendering the progress bar.
|
||||||
type Model struct {
|
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.
|
// Total width of the progress bar, including percentage, if set.
|
||||||
Width int
|
Width int
|
||||||
|
|
||||||
// "Filled" sections of the progress bar
|
// "Filled" sections of the progress bar.
|
||||||
Full rune
|
Full rune
|
||||||
FullColor string
|
FullColor string
|
||||||
|
|
||||||
// "Empty" sections of progress bar
|
// "Empty" sections of progress bar.
|
||||||
Empty rune
|
Empty rune
|
||||||
EmptyColor string
|
EmptyColor string
|
||||||
|
|
||||||
// Settings for rendering the numeric percentage
|
// Settings for rendering the numeric percentage.
|
||||||
ShowPercentage bool
|
ShowPercentage bool
|
||||||
PercentFormat string // a fmt string for a float
|
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
|
useRamp bool
|
||||||
rampColorA colorful.Color
|
rampColorA colorful.Color
|
||||||
rampColorB colorful.Color
|
rampColorB colorful.Color
|
||||||
@@ -103,9 +159,10 @@ type Model struct {
|
|||||||
scaleRamp bool
|
scaleRamp bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModel returns a model with default values.
|
// New returns a model with default values.
|
||||||
func NewModel(opts ...Option) (*Model, error) {
|
func New(opts ...Option) Model {
|
||||||
m := &Model{
|
m := Model{
|
||||||
|
id: nextID(),
|
||||||
Width: defaultWidth,
|
Width: defaultWidth,
|
||||||
Full: '█',
|
Full: '█',
|
||||||
FullColor: "#7571F9",
|
FullColor: "#7571F9",
|
||||||
@@ -114,39 +171,123 @@ func NewModel(opts ...Option) (*Model, error) {
|
|||||||
ShowPercentage: true,
|
ShowPercentage: true,
|
||||||
PercentFormat: " %3.0f%%",
|
PercentFormat: " %3.0f%%",
|
||||||
}
|
}
|
||||||
|
if !m.springCustomized {
|
||||||
|
m.SetSpringOptions(defaultFrequency, defaultDamping)
|
||||||
|
}
|
||||||
|
|
||||||
for _, opt := range opts {
|
for _, opt := range opts {
|
||||||
if err := opt(m); err != nil {
|
opt(&m)
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
return m
|
||||||
return m, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// View renders the progress bar as a given percentage.
|
// NewModel returns a model with default values.
|
||||||
func (m Model) View(percent float64) string {
|
//
|
||||||
b := strings.Builder{}
|
// Deprecated. Use New instead.
|
||||||
if m.ShowPercentage {
|
var NewModel = New
|
||||||
percentage := fmt.Sprintf(m.PercentFormat, percent*100)
|
|
||||||
if m.PercentageStyle != nil {
|
// Init exists satisfy the tea.Model interface.
|
||||||
percentage = m.PercentageStyle.Styled(percentage)
|
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)
|
// If we've more or less reached equilibrium, stop updating.
|
||||||
} else {
|
dist := math.Abs(m.percent - m.targetPercent)
|
||||||
m.bar(&b, percent, 0)
|
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()
|
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 (
|
var (
|
||||||
tw = m.Width - textWidth // total width
|
tw = max(0, m.Width-textWidth) // total width
|
||||||
fw = int(float64(tw) * percent) // filled width
|
fw = int(math.Round((float64(tw) * percent))) // filled width
|
||||||
p float64
|
p float64
|
||||||
)
|
)
|
||||||
|
|
||||||
|
fw = max(0, min(tw, fw))
|
||||||
|
|
||||||
if m.useRamp {
|
if m.useRamp {
|
||||||
// Gradient fill
|
// Gradient fill
|
||||||
for i := 0; i < fw; i++ {
|
for i := 0; i < fw; i++ {
|
||||||
@@ -170,23 +311,43 @@ func (m Model) bar(b *strings.Builder, percent float64, textWidth int) {
|
|||||||
|
|
||||||
// Empty fill
|
// Empty fill
|
||||||
e := termenv.String(string(m.Empty)).Foreground(color(m.EmptyColor)).String()
|
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 {
|
func (m Model) percentageView(percent float64) string {
|
||||||
a, err := colorful.Hex(colorA)
|
if !m.ShowPercentage {
|
||||||
if err != nil {
|
return ""
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
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)
|
func (m *Model) setRamp(colorA, colorB string, scaled bool) {
|
||||||
if err != nil {
|
// In the event of an error colors here will default to black. For
|
||||||
return err
|
// 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.useRamp = true
|
||||||
m.scaleRamp = scaled
|
m.scaleRamp = scaled
|
||||||
m.rampColorA = a
|
m.rampColorA = a
|
||||||
m.rampColorB = b
|
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
|
||||||
}
|
}
|
||||||
|
@@ -2,14 +2,28 @@ package spinner
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
"github.com/muesli/reflow/ansi"
|
"github.com/muesli/reflow/ansi"
|
||||||
"github.com/muesli/termenv"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultFPS = time.Second / 10
|
// 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.
|
// Spinner is a set of frames used in animating the spinner.
|
||||||
type Spinner struct {
|
type Spinner struct {
|
||||||
@@ -17,46 +31,44 @@ type Spinner struct {
|
|||||||
FPS time.Duration
|
FPS time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Some spinners to choose from. You could also make your own.
|
||||||
var (
|
var (
|
||||||
// Some spinners to choose from. You could also make your own.
|
|
||||||
Line = Spinner{
|
Line = Spinner{
|
||||||
Frames: []string{"|", "/", "-", "\\"},
|
Frames: []string{"|", "/", "-", "\\"},
|
||||||
FPS: time.Second / 10,
|
FPS: time.Second / 10, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Dot = Spinner{
|
Dot = Spinner{
|
||||||
Frames: []string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},
|
Frames: []string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},
|
||||||
FPS: time.Second / 10,
|
FPS: time.Second / 10, //nolint:gomnd
|
||||||
}
|
}
|
||||||
MiniDot = Spinner{
|
MiniDot = Spinner{
|
||||||
Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
|
Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
|
||||||
FPS: time.Second / 12,
|
FPS: time.Second / 12, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Jump = Spinner{
|
Jump = Spinner{
|
||||||
Frames: []string{"⢄", "⢂", "⢁", "⡁", "⡈", "⡐", "⡠"},
|
Frames: []string{"⢄", "⢂", "⢁", "⡁", "⡈", "⡐", "⡠"},
|
||||||
FPS: time.Second / 10,
|
FPS: time.Second / 10, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Pulse = Spinner{
|
Pulse = Spinner{
|
||||||
Frames: []string{"█", "▓", "▒", "░"},
|
Frames: []string{"█", "▓", "▒", "░"},
|
||||||
FPS: time.Second / 8,
|
FPS: time.Second / 8, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Points = Spinner{
|
Points = Spinner{
|
||||||
Frames: []string{"∙∙∙", "●∙∙", "∙●∙", "∙∙●"},
|
Frames: []string{"∙∙∙", "●∙∙", "∙●∙", "∙∙●"},
|
||||||
FPS: time.Second / 7,
|
FPS: time.Second / 7, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Globe = Spinner{
|
Globe = Spinner{
|
||||||
Frames: []string{"🌍", "🌎", "🌏"},
|
Frames: []string{"🌍", "🌎", "🌏"},
|
||||||
FPS: time.Second / 4,
|
FPS: time.Second / 4, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Moon = Spinner{
|
Moon = Spinner{
|
||||||
Frames: []string{"🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"},
|
Frames: []string{"🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"},
|
||||||
FPS: time.Second / 8,
|
FPS: time.Second / 8, //nolint:gomnd
|
||||||
}
|
}
|
||||||
Monkey = Spinner{
|
Monkey = Spinner{
|
||||||
Frames: []string{"🙈", "🙉", "🙊"},
|
Frames: []string{"🙈", "🙉", "🙊"},
|
||||||
FPS: time.Second / 3,
|
FPS: time.Second / 3, //nolint:gomnd
|
||||||
}
|
}
|
||||||
|
|
||||||
color = termenv.ColorProfile().Color
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Model contains the state for the spinner. Use NewModel to create new models
|
// Model contains the state for the spinner. Use NewModel to create new models
|
||||||
@@ -66,17 +78,12 @@ type Model struct {
|
|||||||
// Spinner settings to use. See type Spinner.
|
// Spinner settings to use. See type Spinner.
|
||||||
Spinner Spinner
|
Spinner Spinner
|
||||||
|
|
||||||
// ForegroundColor sets the background color of the spinner. It can be
|
// Style sets the styling for the spinner. Most of the time you'll just
|
||||||
// a hex code or one of the 256 ANSI colors. If the terminal emulator can't
|
// want foreground and background coloring, and potentially some padding.
|
||||||
// support the color specified it will automatically degrade (per
|
//
|
||||||
// github.com/muesli/termenv).
|
// For an introduction to styling with Lip Gloss see:
|
||||||
ForegroundColor string
|
// https://github.com/charmbracelet/lipgloss
|
||||||
|
Style lipgloss.Style
|
||||||
// BackgroundColor sets the background color of the spinner. It can be
|
|
||||||
// a hex code or one of the 256 ANSI colors. If the terminal emulator can't
|
|
||||||
// support the color specified it will automatically degrade (per
|
|
||||||
// github.com/muesli/termenv).
|
|
||||||
BackgroundColor string
|
|
||||||
|
|
||||||
// MinimumLifetime is the minimum amount of time the spinner can run. Any
|
// MinimumLifetime is the minimum amount of time the spinner can run. Any
|
||||||
// logic around this can be implemented in view that implements this
|
// logic around this can be implemented in view that implements this
|
||||||
@@ -101,6 +108,7 @@ type Model struct {
|
|||||||
|
|
||||||
frame int
|
frame int
|
||||||
startTime time.Time
|
startTime time.Time
|
||||||
|
id int
|
||||||
tag int
|
tag int
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,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
|
// advancedMode returns whether or not the user is making use of HideFor and
|
||||||
// MinimumLifetime properties.
|
// MinimumLifetime properties.
|
||||||
func (m Model) advancedMode() bool {
|
func (m Model) advancedMode() bool {
|
||||||
@@ -180,15 +193,24 @@ func (m Model) Visible() bool {
|
|||||||
return !m.hidden() && !m.finished()
|
return !m.hidden() && !m.finished()
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModel returns a model with default values.
|
// New returns a model with default values.
|
||||||
func NewModel() Model {
|
func New() Model {
|
||||||
return Model{Spinner: Line}
|
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.
|
// TickMsg indicates that the timer has ticked and we should render a frame.
|
||||||
type TickMsg struct {
|
type TickMsg struct {
|
||||||
Time time.Time
|
Time time.Time
|
||||||
tag int
|
tag int
|
||||||
|
ID int
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update is the Tea update function. This will advance the spinner one frame
|
// Update is the Tea update function. This will advance the spinner one frame
|
||||||
@@ -197,10 +219,15 @@ type TickMsg struct {
|
|||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case TickMsg:
|
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.
|
// 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
|
// This prevents the spinner from receiving too many messages and
|
||||||
// this spinning too fast.
|
// thus spinning too fast.
|
||||||
if msg.tag > 0 && msg.tag != m.tag {
|
if msg.tag > 0 && msg.tag != m.tag {
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
@@ -211,7 +238,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m.tag++
|
m.tag++
|
||||||
return m, m.tick(m.tag)
|
return m, m.tick(m.id, m.tag)
|
||||||
default:
|
default:
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
@@ -232,28 +259,39 @@ func (m Model) View() string {
|
|||||||
frame = strings.Repeat(" ", ansi.PrintableRuneWidth(frame))
|
frame = strings.Repeat(" ", ansi.PrintableRuneWidth(frame))
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.ForegroundColor != "" || m.BackgroundColor != "" {
|
return m.Style.Render(frame)
|
||||||
return termenv.
|
|
||||||
String(frame).
|
|
||||||
Foreground(color(m.ForegroundColor)).
|
|
||||||
Background(color(m.BackgroundColor)).
|
|
||||||
String()
|
|
||||||
}
|
|
||||||
|
|
||||||
return frame
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tick is the command used to advance the spinner one frame. Use this command
|
// Tick is the command used to advance the spinner one frame. Use this command
|
||||||
// to effectively start the spinner.
|
// to effectively start the spinner.
|
||||||
func Tick() tea.Msg {
|
func (m Model) Tick() tea.Msg {
|
||||||
return TickMsg{Time: time.Now()}
|
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 tea.Tick(m.Spinner.FPS, func(t time.Time) tea.Msg {
|
||||||
return TickMsg{
|
return TickMsg{
|
||||||
Time: t,
|
Time: t,
|
||||||
|
ID: id,
|
||||||
tag: tag,
|
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}
|
||||||
|
})
|
||||||
|
}
|
@@ -3,25 +3,47 @@ package textinput
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
"github.com/atotto/clipboard"
|
"github.com/atotto/clipboard"
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
rw "github.com/mattn/go-runewidth"
|
rw "github.com/mattn/go-runewidth"
|
||||||
"github.com/muesli/termenv"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultBlinkSpeed = time.Millisecond * 530
|
const defaultBlinkSpeed = time.Millisecond * 530
|
||||||
|
|
||||||
// color is a helper for returning colors.
|
// Internal ID management for text inputs. Necessary for blink integrity when
|
||||||
var color func(s string) termenv.Color = termenv.ColorProfile().Color
|
// multiple text inputs are involved.
|
||||||
|
var (
|
||||||
|
lastID int
|
||||||
|
idMtx sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
// blinkMsg and blinkCanceled are used to manage cursor blinking.
|
// Return the next ID we should use on the Model.
|
||||||
type blinkMsg struct{}
|
func nextID() int {
|
||||||
|
idMtx.Lock()
|
||||||
|
defer idMtx.Unlock()
|
||||||
|
lastID++
|
||||||
|
return lastID
|
||||||
|
}
|
||||||
|
|
||||||
|
// initialBlinkMsg initializes cursor blinking.
|
||||||
|
type initialBlinkMsg struct{}
|
||||||
|
|
||||||
|
// blinkMsg signals that the cursor should blink. It contains metadata that
|
||||||
|
// allows us to tell if the blink message is the one we're expecting.
|
||||||
|
type blinkMsg struct {
|
||||||
|
id int
|
||||||
|
tag int
|
||||||
|
}
|
||||||
|
|
||||||
|
// blinkCanceled is sent when a blink operation is canceled.
|
||||||
type blinkCanceled struct{}
|
type blinkCanceled struct{}
|
||||||
|
|
||||||
// Messages for clipboard events.
|
// Internal messages for clipboard operations.
|
||||||
type pasteMsg string
|
type pasteMsg string
|
||||||
type pasteErrMsg struct{ error }
|
type pasteErrMsg struct{ error }
|
||||||
|
|
||||||
@@ -40,7 +62,7 @@ const (
|
|||||||
// seen for password fields on the command line.
|
// seen for password fields on the command line.
|
||||||
EchoNone
|
EchoNone
|
||||||
|
|
||||||
// EchoOnEdit
|
// EchoOnEdit.
|
||||||
)
|
)
|
||||||
|
|
||||||
// blinkCtx manages cursor blinking.
|
// blinkCtx manages cursor blinking.
|
||||||
@@ -49,29 +71,46 @@ type blinkCtx struct {
|
|||||||
cancel context.CancelFunc
|
cancel context.CancelFunc
|
||||||
}
|
}
|
||||||
|
|
||||||
type cursorMode int
|
// CursorMode describes the behavior of the cursor.
|
||||||
|
type CursorMode int
|
||||||
|
|
||||||
|
// Available cursor modes.
|
||||||
const (
|
const (
|
||||||
cursorBlink = iota
|
CursorBlink CursorMode = iota
|
||||||
cursorStatic
|
CursorStatic
|
||||||
cursorHide
|
CursorHide
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// String returns a the cursor mode in a human-readable format. This method is
|
||||||
|
// provisional and for informational purposes only.
|
||||||
|
func (c CursorMode) String() string {
|
||||||
|
return [...]string{
|
||||||
|
"blink",
|
||||||
|
"static",
|
||||||
|
"hidden",
|
||||||
|
}[c]
|
||||||
|
}
|
||||||
|
|
||||||
// Model is the Bubble Tea model for this text input element.
|
// Model is the Bubble Tea model for this text input element.
|
||||||
type Model struct {
|
type Model struct {
|
||||||
Err error
|
Err error
|
||||||
|
|
||||||
// General settings
|
// General settings.
|
||||||
Prompt string
|
Prompt string
|
||||||
Placeholder string
|
Placeholder string
|
||||||
Cursor string
|
BlinkSpeed time.Duration
|
||||||
BlinkSpeed time.Duration
|
EchoMode EchoMode
|
||||||
TextColor string
|
EchoCharacter rune
|
||||||
BackgroundColor string
|
|
||||||
PlaceholderColor string
|
// Styles. These will be applied as inline styles.
|
||||||
CursorColor string
|
//
|
||||||
EchoMode EchoMode
|
// For an introduction to styling with Lip Gloss see:
|
||||||
EchoCharacter rune
|
// https://github.com/charmbracelet/lipgloss
|
||||||
|
PromptStyle lipgloss.Style
|
||||||
|
TextStyle lipgloss.Style
|
||||||
|
BackgroundStyle lipgloss.Style
|
||||||
|
PlaceholderStyle lipgloss.Style
|
||||||
|
CursorStyle lipgloss.Style
|
||||||
|
|
||||||
// CharLimit is the maximum amount of characters this input element will
|
// CharLimit is the maximum amount of characters this input element will
|
||||||
// accept. If 0 or less, there's no limit.
|
// accept. If 0 or less, there's no limit.
|
||||||
@@ -82,11 +121,17 @@ type Model struct {
|
|||||||
// viewport. If 0 or less this setting is ignored.
|
// viewport. If 0 or less this setting is ignored.
|
||||||
Width int
|
Width int
|
||||||
|
|
||||||
|
// The ID of this Model as it relates to other textinput Models.
|
||||||
|
id int
|
||||||
|
|
||||||
|
// The ID of the blink message we're expecting to receive.
|
||||||
|
blinkTag int
|
||||||
|
|
||||||
// Underlying text value.
|
// Underlying text value.
|
||||||
value []rune
|
value []rune
|
||||||
|
|
||||||
// Focus indicates whether user input focus should be on this input
|
// focus indicates whether user input focus should be on this input
|
||||||
// component. When false, don't blink and ignore keyboard input.
|
// component. When false, ignore keyboard input and hide the cursor.
|
||||||
focus bool
|
focus bool
|
||||||
|
|
||||||
// Cursor blink state.
|
// Cursor blink state.
|
||||||
@@ -104,26 +149,24 @@ type Model struct {
|
|||||||
blinkCtx *blinkCtx
|
blinkCtx *blinkCtx
|
||||||
|
|
||||||
// cursorMode determines the behavior of the cursor
|
// cursorMode determines the behavior of the cursor
|
||||||
cursorMode cursorMode
|
cursorMode CursorMode
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModel creates a new model with default settings.
|
// NewModel creates a new model with default settings.
|
||||||
func NewModel() Model {
|
func New() Model {
|
||||||
return Model{
|
return Model{
|
||||||
Prompt: "> ",
|
Prompt: "> ",
|
||||||
Placeholder: "",
|
|
||||||
BlinkSpeed: defaultBlinkSpeed,
|
BlinkSpeed: defaultBlinkSpeed,
|
||||||
TextColor: "",
|
|
||||||
PlaceholderColor: "240",
|
|
||||||
CursorColor: "",
|
|
||||||
EchoCharacter: '*',
|
EchoCharacter: '*',
|
||||||
CharLimit: 0,
|
CharLimit: 0,
|
||||||
|
PlaceholderStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
|
||||||
|
|
||||||
|
id: nextID(),
|
||||||
value: nil,
|
value: nil,
|
||||||
focus: false,
|
focus: false,
|
||||||
blink: true,
|
blink: true,
|
||||||
pos: 0,
|
pos: 0,
|
||||||
cursorMode: cursorBlink,
|
cursorMode: CursorBlink,
|
||||||
|
|
||||||
blinkCtx: &blinkCtx{
|
blinkCtx: &blinkCtx{
|
||||||
ctx: context.Background(),
|
ctx: context.Background(),
|
||||||
@@ -131,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.
|
// SetValue sets the value of the text input.
|
||||||
func (m *Model) SetValue(s string) {
|
func (m *Model) SetValue(s string) {
|
||||||
runes := []rune(s)
|
runes := []rune(s)
|
||||||
@@ -139,8 +187,8 @@ func (m *Model) SetValue(s string) {
|
|||||||
} else {
|
} else {
|
||||||
m.value = runes
|
m.value = runes
|
||||||
}
|
}
|
||||||
if m.pos > len(m.value) {
|
if m.pos == 0 || m.pos > len(m.value) {
|
||||||
m.SetCursor(len(m.value))
|
m.setCursor(len(m.value))
|
||||||
}
|
}
|
||||||
m.handleOverflow()
|
m.handleOverflow()
|
||||||
}
|
}
|
||||||
@@ -150,30 +198,69 @@ func (m Model) Value() string {
|
|||||||
return string(m.value)
|
return string(m.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetCursor start moves the cursor to the given position. If the position is
|
// Cursor returns the cursor position.
|
||||||
|
func (m Model) Cursor() int {
|
||||||
|
return m.pos
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetCursor moves the cursor to the given position. If the position is
|
||||||
// out of bounds the cursor will be moved to the start or end accordingly.
|
// out of bounds the cursor will be moved to the start or end accordingly.
|
||||||
// Returns whether or nor the cursor timer should be reset.
|
func (m *Model) SetCursor(pos int) {
|
||||||
func (m *Model) SetCursor(pos int) bool {
|
m.setCursor(pos)
|
||||||
|
}
|
||||||
|
|
||||||
|
// setCursor moves the cursor to the given position and returns whether or not
|
||||||
|
// the cursor blink should be reset. If the position is out of bounds the
|
||||||
|
// cursor will be moved to the start or end accordingly.
|
||||||
|
func (m *Model) setCursor(pos int) bool {
|
||||||
m.pos = clamp(pos, 0, len(m.value))
|
m.pos = clamp(pos, 0, len(m.value))
|
||||||
m.handleOverflow()
|
m.handleOverflow()
|
||||||
|
|
||||||
// Show the cursor unless it's been explicitly hidden
|
// Show the cursor unless it's been explicitly hidden
|
||||||
m.blink = m.cursorMode == cursorHide
|
m.blink = m.cursorMode == CursorHide
|
||||||
|
|
||||||
// Reset cursor blink if necessary
|
// Reset cursor blink if necessary
|
||||||
return m.cursorMode == cursorBlink
|
return m.cursorMode == CursorBlink
|
||||||
}
|
}
|
||||||
|
|
||||||
// CursorStart moves the cursor to the start of the field. Returns whether or
|
// CursorStart moves the cursor to the start of the input field.
|
||||||
// not the curosr blink should be reset.
|
func (m *Model) CursorStart() {
|
||||||
func (m *Model) CursorStart() bool {
|
m.cursorStart()
|
||||||
return m.SetCursor(0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// CursorEnd moves the cursor to the end of the field. Returns whether or not
|
// cursorStart moves the cursor to the start of the input field and returns
|
||||||
// the cursor blink should be reset.
|
// whether or not the curosr blink should be reset.
|
||||||
func (m *Model) CursorEnd() bool {
|
func (m *Model) cursorStart() bool {
|
||||||
return m.SetCursor(len(m.value))
|
return m.setCursor(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CursorEnd moves the cursor to the end of the input field.
|
||||||
|
func (m *Model) CursorEnd() {
|
||||||
|
m.cursorEnd()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CursorMode returns the model's cursor mode. For available cursor modes, see
|
||||||
|
// type CursorMode.
|
||||||
|
func (m Model) CursorMode() CursorMode {
|
||||||
|
return m.cursorMode
|
||||||
|
}
|
||||||
|
|
||||||
|
// CursorMode sets the model's cursor mode. This method returns a command.
|
||||||
|
//
|
||||||
|
// For available cursor modes, see type CursorMode.
|
||||||
|
func (m *Model) SetCursorMode(mode CursorMode) tea.Cmd {
|
||||||
|
m.cursorMode = mode
|
||||||
|
m.blink = m.cursorMode == CursorHide || !m.focus
|
||||||
|
if mode == CursorBlink {
|
||||||
|
return Blink
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cursorEnd moves the cursor to the end of the input field and returns whether
|
||||||
|
// the cursor should blink should reset.
|
||||||
|
func (m *Model) cursorEnd() bool {
|
||||||
|
return m.setCursor(len(m.value))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Focused returns the focus state on the model.
|
// Focused returns the focus state on the model.
|
||||||
@@ -181,13 +268,20 @@ func (m Model) Focused() bool {
|
|||||||
return m.focus
|
return m.focus
|
||||||
}
|
}
|
||||||
|
|
||||||
// Focus sets the focus state on the model.
|
// Focus sets the focus state on the model. When the model is in focus it can
|
||||||
func (m *Model) Focus() {
|
// receive keyboard input and the cursor will be hidden.
|
||||||
|
func (m *Model) Focus() tea.Cmd {
|
||||||
m.focus = true
|
m.focus = true
|
||||||
m.blink = m.cursorMode == cursorHide // show the cursor unless we've explicitly hidden it
|
m.blink = m.cursorMode == CursorHide // show the cursor unless we've explicitly hidden it
|
||||||
|
|
||||||
|
if m.cursorMode == CursorBlink && m.focus {
|
||||||
|
return m.blinkCmd()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Blur removes the focus state on the model.
|
// Blur removes the focus state on the model. When the model is blurred it can
|
||||||
|
// not receive keyboard input and the cursor will be hidden.
|
||||||
func (m *Model) Blur() {
|
func (m *Model) Blur() {
|
||||||
m.focus = false
|
m.focus = false
|
||||||
m.blink = true
|
m.blink = true
|
||||||
@@ -197,12 +291,12 @@ func (m *Model) Blur() {
|
|||||||
// or not the cursor blink should reset.
|
// or not the cursor blink should reset.
|
||||||
func (m *Model) Reset() bool {
|
func (m *Model) Reset() bool {
|
||||||
m.value = nil
|
m.value = nil
|
||||||
return m.SetCursor(0)
|
return m.setCursor(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
// handle a clipboard paste event, if supported. Returns whether or not the
|
// handle a clipboard paste event, if supported. Returns whether or not the
|
||||||
// cursor blink should be reset.
|
// cursor blink should reset.
|
||||||
func (m *Model) handlePaste(v string) (blink bool) {
|
func (m *Model) handlePaste(v string) bool {
|
||||||
paste := []rune(v)
|
paste := []rune(v)
|
||||||
|
|
||||||
var availSpace int
|
var availSpace int
|
||||||
@@ -212,7 +306,7 @@ func (m *Model) handlePaste(v string) (blink bool) {
|
|||||||
|
|
||||||
// If the char limit's been reached cancel
|
// If the char limit's been reached cancel
|
||||||
if m.CharLimit > 0 && availSpace <= 0 {
|
if m.CharLimit > 0 && availSpace <= 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// If there's not enough space to paste the whole thing cut the pasted
|
// If there's not enough space to paste the whole thing cut the pasted
|
||||||
@@ -243,7 +337,7 @@ func (m *Model) handlePaste(v string) (blink bool) {
|
|||||||
m.value = append(head, tail...)
|
m.value = append(head, tail...)
|
||||||
|
|
||||||
// Reset blink state if necessary and run overflow checks
|
// Reset blink state if necessary and run overflow checks
|
||||||
return m.SetCursor(m.pos)
|
return m.setCursor(m.pos)
|
||||||
}
|
}
|
||||||
|
|
||||||
// If a max width is defined, perform some logic to treat the visible area
|
// If a max width is defined, perform some logic to treat the visible area
|
||||||
@@ -291,105 +385,125 @@ func (m *Model) handleOverflow() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// colorText colorizes a given string according to the TextColor value of the
|
// deleteBeforeCursor deletes all text before the cursor. Returns whether or
|
||||||
// model.
|
// not the cursor blink should be reset.
|
||||||
func (m *Model) colorText(s string) string {
|
func (m *Model) deleteBeforeCursor() bool {
|
||||||
return termenv.
|
m.value = m.value[m.pos:]
|
||||||
String(s).
|
m.offset = 0
|
||||||
Foreground(color(m.TextColor)).
|
return m.setCursor(0)
|
||||||
Background(color(m.BackgroundColor)).
|
|
||||||
String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// colorPlaceholder colorizes a given string according to the TextColor value
|
// deleteAfterCursor deletes all text after the cursor. Returns whether or not
|
||||||
// of the model.
|
// the cursor blink should be reset. If input is masked delete everything after
|
||||||
func (m *Model) colorPlaceholder(s string) string {
|
// the cursor so as not to reveal word breaks in the masked input.
|
||||||
return termenv.
|
func (m *Model) deleteAfterCursor() bool {
|
||||||
String(s).
|
m.value = m.value[:m.pos]
|
||||||
Foreground(color(m.PlaceholderColor)).
|
return m.setCursor(len(m.value))
|
||||||
Background(color(m.BackgroundColor)).
|
|
||||||
String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteWordLeft deletes the word left to the cursor. Returns whether or not
|
// deleteWordLeft deletes the word left to the cursor. Returns whether or not
|
||||||
// the cursor blink should be reset.
|
// the cursor blink should be reset.
|
||||||
func (m *Model) deleteWordLeft() (blink bool) {
|
func (m *Model) deleteWordLeft() bool {
|
||||||
if m.pos == 0 || len(m.value) == 0 {
|
if m.pos == 0 || len(m.value) == 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
i := m.pos
|
if m.EchoMode != EchoNormal {
|
||||||
blink = m.SetCursor(m.pos - 1)
|
return m.deleteBeforeCursor()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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]) {
|
for unicode.IsSpace(m.value[m.pos]) {
|
||||||
|
if m.pos <= 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
// ignore series of whitespace before cursor
|
// ignore series of whitespace before cursor
|
||||||
blink = m.SetCursor(m.pos - 1)
|
blink = m.setCursor(m.pos - 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
for m.pos > 0 {
|
for m.pos > 0 {
|
||||||
if !unicode.IsSpace(m.value[m.pos]) {
|
if !unicode.IsSpace(m.value[m.pos]) {
|
||||||
blink = m.SetCursor(m.pos - 1)
|
blink = m.setCursor(m.pos - 1)
|
||||||
} else {
|
} else {
|
||||||
if m.pos > 0 {
|
if m.pos > 0 {
|
||||||
// keep the previous space
|
// keep the previous space
|
||||||
blink = m.SetCursor(m.pos + 1)
|
blink = m.setCursor(m.pos + 1)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if i > len(m.value) {
|
if oldPos > len(m.value) {
|
||||||
m.value = m.value[:m.pos]
|
m.value = m.value[:m.pos]
|
||||||
} else {
|
} else {
|
||||||
m.value = append(m.value[:m.pos], m.value[i:]...)
|
m.value = append(m.value[:m.pos], m.value[oldPos:]...)
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return blink
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteWordRight deletes the word right to the cursor. Returns whether or not
|
// deleteWordRight deletes the word right to the cursor. Returns whether or not
|
||||||
// the cursor blink should be reset.
|
// the cursor blink should be reset. If input is masked delete everything after
|
||||||
func (m *Model) deleteWordRight() (blink bool) {
|
// the cursor so as not to reveal word breaks in the masked input.
|
||||||
|
func (m *Model) deleteWordRight() bool {
|
||||||
if m.pos >= len(m.value) || len(m.value) == 0 {
|
if m.pos >= len(m.value) || len(m.value) == 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
i := m.pos
|
if m.EchoMode != EchoNormal {
|
||||||
blink = m.SetCursor(m.pos + 1)
|
return m.deleteAfterCursor()
|
||||||
|
}
|
||||||
|
|
||||||
|
oldPos := m.pos
|
||||||
|
m.setCursor(m.pos + 1)
|
||||||
for unicode.IsSpace(m.value[m.pos]) {
|
for unicode.IsSpace(m.value[m.pos]) {
|
||||||
// ignore series of whitespace after cursor
|
// ignore series of whitespace after cursor
|
||||||
blink = m.SetCursor(m.pos + 1)
|
m.setCursor(m.pos + 1)
|
||||||
|
|
||||||
|
if m.pos >= len(m.value) {
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for m.pos < len(m.value) {
|
for m.pos < len(m.value) {
|
||||||
if !unicode.IsSpace(m.value[m.pos]) {
|
if !unicode.IsSpace(m.value[m.pos]) {
|
||||||
blink = m.SetCursor(m.pos + 1)
|
m.setCursor(m.pos + 1)
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.pos > len(m.value) {
|
if m.pos > len(m.value) {
|
||||||
m.value = m.value[:i]
|
m.value = m.value[:oldPos]
|
||||||
} else {
|
} else {
|
||||||
m.value = append(m.value[:i], m.value[m.pos:]...)
|
m.value = append(m.value[:oldPos], m.value[m.pos:]...)
|
||||||
}
|
}
|
||||||
blink = m.SetCursor(i)
|
|
||||||
|
|
||||||
return
|
return m.setCursor(oldPos)
|
||||||
}
|
}
|
||||||
|
|
||||||
// wordLeft moves the cursor one word to the left. Returns whether or not the
|
// wordLeft moves the cursor one word to the left. Returns whether or not the
|
||||||
// cursor blink should be reset.
|
// cursor blink should be reset. If input is masked, move input to the start
|
||||||
func (m *Model) wordLeft() (blink bool) {
|
// so as not to reveal word breaks in the masked input.
|
||||||
|
func (m *Model) wordLeft() bool {
|
||||||
if m.pos == 0 || len(m.value) == 0 {
|
if m.pos == 0 || len(m.value) == 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
i := m.pos - 1
|
if m.EchoMode != EchoNormal {
|
||||||
|
return m.cursorStart()
|
||||||
|
}
|
||||||
|
|
||||||
|
blink := false
|
||||||
|
i := m.pos - 1
|
||||||
for i >= 0 {
|
for i >= 0 {
|
||||||
if unicode.IsSpace(m.value[i]) {
|
if unicode.IsSpace(m.value[i]) {
|
||||||
blink = m.SetCursor(m.pos - 1)
|
blink = m.setCursor(m.pos - 1)
|
||||||
i--
|
i--
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
@@ -398,28 +512,33 @@ func (m *Model) wordLeft() (blink bool) {
|
|||||||
|
|
||||||
for i >= 0 {
|
for i >= 0 {
|
||||||
if !unicode.IsSpace(m.value[i]) {
|
if !unicode.IsSpace(m.value[i]) {
|
||||||
blink = m.SetCursor(m.pos - 1)
|
blink = m.setCursor(m.pos - 1)
|
||||||
i--
|
i--
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return blink
|
||||||
}
|
}
|
||||||
|
|
||||||
// wordRight moves the cursor one word to the right. Returns whether or not the
|
// wordRight moves the cursor one word to the right. Returns whether or not the
|
||||||
// cursor blink should be reset.
|
// cursor blink should be reset. If the input is masked, move input to the end
|
||||||
func (m *Model) wordRight() (blink bool) {
|
// so as not to reveal word breaks in the masked input.
|
||||||
|
func (m *Model) wordRight() bool {
|
||||||
if m.pos >= len(m.value) || len(m.value) == 0 {
|
if m.pos >= len(m.value) || len(m.value) == 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
i := m.pos
|
if m.EchoMode != EchoNormal {
|
||||||
|
return m.cursorEnd()
|
||||||
|
}
|
||||||
|
|
||||||
|
blink := false
|
||||||
|
i := m.pos
|
||||||
for i < len(m.value) {
|
for i < len(m.value) {
|
||||||
if unicode.IsSpace(m.value[i]) {
|
if unicode.IsSpace(m.value[i]) {
|
||||||
blink = m.SetCursor(m.pos + 1)
|
blink = m.setCursor(m.pos + 1)
|
||||||
i++
|
i++
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
@@ -428,14 +547,14 @@ func (m *Model) wordRight() (blink bool) {
|
|||||||
|
|
||||||
for i < len(m.value) {
|
for i < len(m.value) {
|
||||||
if !unicode.IsSpace(m.value[i]) {
|
if !unicode.IsSpace(m.value[i]) {
|
||||||
blink = m.SetCursor(m.pos + 1)
|
blink = m.setCursor(m.pos + 1)
|
||||||
i++
|
i++
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return blink
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) echoTransform(v string) string {
|
func (m Model) echoTransform(v string) string {
|
||||||
@@ -469,7 +588,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
if len(m.value) > 0 {
|
if len(m.value) > 0 {
|
||||||
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
|
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
|
||||||
if m.pos > 0 {
|
if m.pos > 0 {
|
||||||
resetBlink = m.SetCursor(m.pos - 1)
|
resetBlink = m.setCursor(m.pos - 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -479,33 +598,30 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
break
|
break
|
||||||
}
|
}
|
||||||
if m.pos > 0 { // left arrow, ^F, back one character
|
if m.pos > 0 { // left arrow, ^F, back one character
|
||||||
resetBlink = m.SetCursor(m.pos - 1)
|
resetBlink = m.setCursor(m.pos - 1)
|
||||||
}
|
}
|
||||||
case tea.KeyRight, tea.KeyCtrlF:
|
case tea.KeyRight, tea.KeyCtrlF:
|
||||||
if msg.Alt { // alt+right arrow, forward one word
|
if msg.Alt { // alt+right arrow, forward one word
|
||||||
resetBlink = m.wordRight()
|
resetBlink = m.wordRight()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if m.pos < len(m.value) { // right arrow, ^F, forward one word
|
if m.pos < len(m.value) { // right arrow, ^F, forward one character
|
||||||
resetBlink = m.SetCursor(m.pos + 1)
|
resetBlink = m.setCursor(m.pos + 1)
|
||||||
}
|
}
|
||||||
case tea.KeyCtrlW: // ^W, delete word left of cursor
|
case tea.KeyCtrlW: // ^W, delete word left of cursor
|
||||||
resetBlink = m.deleteWordLeft()
|
resetBlink = m.deleteWordLeft()
|
||||||
case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning
|
case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning
|
||||||
resetBlink = m.CursorStart()
|
resetBlink = m.cursorStart()
|
||||||
case tea.KeyDelete, tea.KeyCtrlD: // ^D, delete char under cursor
|
case tea.KeyDelete, tea.KeyCtrlD: // ^D, delete char under cursor
|
||||||
if len(m.value) > 0 && m.pos < len(m.value) {
|
if len(m.value) > 0 && m.pos < len(m.value) {
|
||||||
m.value = append(m.value[:m.pos], m.value[m.pos+1:]...)
|
m.value = append(m.value[:m.pos], m.value[m.pos+1:]...)
|
||||||
}
|
}
|
||||||
case tea.KeyCtrlE, tea.KeyEnd: // ^E, go to end
|
case tea.KeyCtrlE, tea.KeyEnd: // ^E, go to end
|
||||||
resetBlink = m.CursorEnd()
|
resetBlink = m.cursorEnd()
|
||||||
case tea.KeyCtrlK: // ^K, kill text after cursor
|
case tea.KeyCtrlK: // ^K, kill text after cursor
|
||||||
m.value = m.value[:m.pos]
|
resetBlink = m.deleteAfterCursor()
|
||||||
resetBlink = m.SetCursor(len(m.value))
|
|
||||||
case tea.KeyCtrlU: // ^U, kill text before cursor
|
case tea.KeyCtrlU: // ^U, kill text before cursor
|
||||||
m.value = m.value[m.pos:]
|
resetBlink = m.deleteBeforeCursor()
|
||||||
resetBlink = m.SetCursor(0)
|
|
||||||
m.offset = 0
|
|
||||||
case tea.KeyCtrlV: // ^V paste
|
case tea.KeyCtrlV: // ^V paste
|
||||||
return m, Paste
|
return m, Paste
|
||||||
case tea.KeyRunes: // input regular characters
|
case tea.KeyRunes: // input regular characters
|
||||||
@@ -527,13 +643,36 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
// Input a regular character
|
// Input a regular character
|
||||||
if m.CharLimit <= 0 || len(m.value) < m.CharLimit {
|
if m.CharLimit <= 0 || len(m.value) < m.CharLimit {
|
||||||
m.value = append(m.value[:m.pos], append(msg.Runes, m.value[m.pos:]...)...)
|
m.value = append(m.value[:m.pos], append(msg.Runes, m.value[m.pos:]...)...)
|
||||||
resetBlink = m.SetCursor(m.pos + len(msg.Runes))
|
resetBlink = m.setCursor(m.pos + len(msg.Runes))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case initialBlinkMsg:
|
||||||
|
// We accept all initialBlinkMsgs genrated by the Blink command.
|
||||||
|
|
||||||
|
if m.cursorMode != CursorBlink || !m.focus {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := m.blinkCmd()
|
||||||
|
return m, cmd
|
||||||
|
|
||||||
case blinkMsg:
|
case blinkMsg:
|
||||||
|
// We're choosy about whether to accept blinkMsgs so that our cursor
|
||||||
|
// only exactly when it should.
|
||||||
|
|
||||||
|
// Is this model blinkable?
|
||||||
|
if m.cursorMode != CursorBlink || !m.focus {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Were we expecting this blink message?
|
||||||
|
if msg.id != m.id || msg.tag != m.blinkTag {
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
if m.cursorMode == cursorBlink {
|
if m.cursorMode == CursorBlink {
|
||||||
m.blink = !m.blink
|
m.blink = !m.blink
|
||||||
cmd = m.blinkCmd()
|
cmd = m.blinkCmd()
|
||||||
}
|
}
|
||||||
@@ -565,13 +704,15 @@ func (m Model) View() string {
|
|||||||
return m.placeholderView()
|
return m.placeholderView()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
styleText := m.TextStyle.Inline(true).Render
|
||||||
|
|
||||||
value := m.value[m.offset:m.offsetRight]
|
value := m.value[m.offset:m.offsetRight]
|
||||||
pos := max(0, m.pos-m.offset)
|
pos := max(0, m.pos-m.offset)
|
||||||
v := m.colorText(m.echoTransform(string(value[:pos])))
|
v := styleText(m.echoTransform(string(value[:pos])))
|
||||||
|
|
||||||
if pos < len(value) {
|
if pos < len(value) {
|
||||||
v += m.cursorView(m.echoTransform(string(value[pos]))) // cursor and text under it
|
v += m.cursorView(m.echoTransform(string(value[pos]))) // cursor and text under it
|
||||||
v += m.colorText(m.echoTransform(string(value[pos+1:]))) // text after cursor
|
v += styleText(m.echoTransform(string(value[pos+1:]))) // text after cursor
|
||||||
} else {
|
} else {
|
||||||
v += m.cursorView(" ")
|
v += m.cursorView(" ")
|
||||||
}
|
}
|
||||||
@@ -579,60 +720,52 @@ func (m Model) View() string {
|
|||||||
// If a max width and background color were set fill the empty spaces with
|
// If a max width and background color were set fill the empty spaces with
|
||||||
// the background color.
|
// the background color.
|
||||||
valWidth := rw.StringWidth(string(value))
|
valWidth := rw.StringWidth(string(value))
|
||||||
if m.Width > 0 && len(m.BackgroundColor) > 0 && valWidth <= m.Width {
|
if m.Width > 0 && valWidth <= m.Width {
|
||||||
padding := max(0, m.Width-valWidth)
|
padding := max(0, m.Width-valWidth)
|
||||||
if valWidth+padding <= m.Width && pos < len(value) {
|
if valWidth+padding <= m.Width && pos < len(value) {
|
||||||
padding++
|
padding++
|
||||||
}
|
}
|
||||||
v += strings.Repeat(
|
v += styleText(strings.Repeat(" ", padding))
|
||||||
termenv.String(" ").Background(color(m.BackgroundColor)).String(),
|
|
||||||
padding,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return m.Prompt + v
|
return m.PromptStyle.Render(m.Prompt) + v
|
||||||
}
|
}
|
||||||
|
|
||||||
// placeholderView returns the prompt and placeholder view, if any.
|
// placeholderView returns the prompt and placeholder view, if any.
|
||||||
func (m Model) placeholderView() string {
|
func (m Model) placeholderView() string {
|
||||||
var (
|
var (
|
||||||
v string
|
v string
|
||||||
p = m.Placeholder
|
p = m.Placeholder
|
||||||
|
style = m.PlaceholderStyle.Inline(true).Render
|
||||||
)
|
)
|
||||||
|
|
||||||
// Cursor
|
// Cursor
|
||||||
if m.blink && m.PlaceholderColor != "" {
|
if m.blink {
|
||||||
v += m.cursorView(m.colorPlaceholder(p[:1]))
|
v += m.cursorView(style(p[:1]))
|
||||||
} else {
|
} else {
|
||||||
v += m.cursorView(p[:1])
|
v += m.cursorView(p[:1])
|
||||||
}
|
}
|
||||||
|
|
||||||
// The rest of the placeholder text
|
// The rest of the placeholder text
|
||||||
v += m.colorPlaceholder(p[1:])
|
v += style(p[1:])
|
||||||
|
|
||||||
return m.Prompt + v
|
return m.PromptStyle.Render(m.Prompt) + v
|
||||||
}
|
}
|
||||||
|
|
||||||
// cursorView styles the cursor.
|
// cursorView styles the cursor.
|
||||||
func (m Model) cursorView(v string) string {
|
func (m Model) cursorView(v string) string {
|
||||||
if m.blink {
|
if m.blink {
|
||||||
if m.TextColor != "" || m.BackgroundColor != "" {
|
return m.TextStyle.Render(v)
|
||||||
return termenv.String(v).
|
|
||||||
Foreground(color(m.TextColor)).
|
|
||||||
Background(color(m.BackgroundColor)).
|
|
||||||
String()
|
|
||||||
}
|
|
||||||
return v
|
|
||||||
}
|
}
|
||||||
return termenv.String(v).
|
return m.CursorStyle.Inline(true).Reverse(true).Render(v)
|
||||||
Foreground(color(m.CursorColor)).
|
|
||||||
Background(color(m.BackgroundColor)).
|
|
||||||
Reverse().
|
|
||||||
String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// blinkCmd is an internal command used to manage cursor blinking.
|
// blinkCmd is an internal command used to manage cursor blinking.
|
||||||
func (m Model) blinkCmd() tea.Cmd {
|
func (m *Model) blinkCmd() tea.Cmd {
|
||||||
|
if m.cursorMode != CursorBlink {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
if m.blinkCtx != nil && m.blinkCtx.cancel != nil {
|
if m.blinkCtx != nil && m.blinkCtx.cancel != nil {
|
||||||
m.blinkCtx.cancel()
|
m.blinkCtx.cancel()
|
||||||
}
|
}
|
||||||
@@ -640,11 +773,13 @@ func (m Model) blinkCmd() tea.Cmd {
|
|||||||
ctx, cancel := context.WithTimeout(m.blinkCtx.ctx, m.BlinkSpeed)
|
ctx, cancel := context.WithTimeout(m.blinkCtx.ctx, m.BlinkSpeed)
|
||||||
m.blinkCtx.cancel = cancel
|
m.blinkCtx.cancel = cancel
|
||||||
|
|
||||||
|
m.blinkTag++
|
||||||
|
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
defer cancel()
|
defer cancel()
|
||||||
<-ctx.Done()
|
<-ctx.Done()
|
||||||
if ctx.Err() == context.DeadlineExceeded {
|
if ctx.Err() == context.DeadlineExceeded {
|
||||||
return blinkMsg{}
|
return blinkMsg{id: m.id, tag: m.blinkTag}
|
||||||
}
|
}
|
||||||
return blinkCanceled{}
|
return blinkCanceled{}
|
||||||
}
|
}
|
||||||
@@ -652,7 +787,7 @@ func (m Model) blinkCmd() tea.Cmd {
|
|||||||
|
|
||||||
// Blink is a command used to initialize cursor blinking.
|
// Blink is a command used to initialize cursor blinking.
|
||||||
func Blink() tea.Msg {
|
func Blink() tea.Msg {
|
||||||
return blinkMsg{}
|
return initialBlinkMsg{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Paste is a command for pasting from the clipboard into the text input.
|
// Paste is a command for pasting from the clipboard into the text input.
|
||||||
@@ -665,6 +800,9 @@ func Paste() tea.Msg {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func clamp(v, low, high int) int {
|
func clamp(v, low, high int) int {
|
||||||
|
if high < low {
|
||||||
|
low, high = high, low
|
||||||
|
}
|
||||||
return min(high, max(low, v))
|
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,24 +4,44 @@ import (
|
|||||||
"math"
|
"math"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/charmbracelet/bubbles/key"
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
)
|
)
|
||||||
|
|
||||||
const spacebar = " "
|
// New returns a new model with the given width and height as well as default
|
||||||
|
// keymappings.
|
||||||
// MODEL
|
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 {
|
type Model struct {
|
||||||
Width int
|
Width int
|
||||||
Height 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 is the vertical scroll position.
|
||||||
YOffset int
|
YOffset int
|
||||||
|
|
||||||
// YPosition is the position of the viewport in relation to the terminal
|
// 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
|
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
|
// HighPerformanceRendering bypasses the normal Bubble Tea renderer to
|
||||||
// provide higher performance rendering. Most of the time the normal Bubble
|
// provide higher performance rendering. Most of the time the normal Bubble
|
||||||
// Tea rendering methods will suffice, but if you're passing content with
|
// Tea rendering methods will suffice, but if you're passing content with
|
||||||
@@ -32,7 +52,20 @@ type Model struct {
|
|||||||
// which is usually via the alternate screen buffer.
|
// which is usually via the alternate screen buffer.
|
||||||
HighPerformanceRendering bool
|
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.
|
// AtTop returns whether or not the viewport is in the very top position.
|
||||||
@@ -43,16 +76,16 @@ func (m Model) AtTop() bool {
|
|||||||
// AtBottom returns whether or not the viewport is at or past the very bottom
|
// AtBottom returns whether or not the viewport is at or past the very bottom
|
||||||
// position.
|
// position.
|
||||||
func (m Model) AtBottom() bool {
|
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
|
// PastBottom returns whether or not the viewport is scrolled beyond the last
|
||||||
// line. This can happen when adjusting the viewport height.
|
// line. This can happen when adjusting the viewport height.
|
||||||
func (m Model) PastBottom() bool {
|
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.
|
// ScrollPercent returns the amount scrolled as a float between 0 and 1.
|
||||||
func (m Model) ScrollPercent() float64 {
|
func (m Model) ScrollPercent() float64 {
|
||||||
if m.Height >= len(m.lines) {
|
if m.Height >= len(m.lines) {
|
||||||
return 1.0
|
return 1.0
|
||||||
@@ -67,11 +100,22 @@ func (m Model) ScrollPercent() float64 {
|
|||||||
// SetContent set the pager's text content. For high performance rendering the
|
// SetContent set the pager's text content. For high performance rendering the
|
||||||
// Sync command should also be called.
|
// Sync command should also be called.
|
||||||
func (m *Model) SetContent(s string) {
|
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")
|
m.lines = strings.Split(s, "\n")
|
||||||
|
|
||||||
|
if m.YOffset > len(m.lines)-1 {
|
||||||
|
m.GotoBottom()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
func (m Model) visibleLines() (lines []string) {
|
||||||
if len(m.lines) > 0 {
|
if len(m.lines) > 0 {
|
||||||
top := max(0, m.YOffset)
|
top := max(0, m.YOffset)
|
||||||
@@ -81,6 +125,21 @@ func (m Model) visibleLines() (lines []string) {
|
|||||||
return lines
|
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.
|
// ViewDown moves the view down by the number of lines in the viewport.
|
||||||
// Basically, "page down".
|
// Basically, "page down".
|
||||||
func (m *Model) ViewDown() []string {
|
func (m *Model) ViewDown() []string {
|
||||||
@@ -88,11 +147,7 @@ func (m *Model) ViewDown() []string {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
m.YOffset = min(
|
m.SetYOffset(m.YOffset + m.Height)
|
||||||
m.YOffset+m.Height, // target
|
|
||||||
len(m.lines)-1-m.Height, // fallback
|
|
||||||
)
|
|
||||||
|
|
||||||
return m.visibleLines()
|
return m.visibleLines()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,11 +157,7 @@ func (m *Model) ViewUp() []string {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
m.YOffset = max(
|
m.SetYOffset(m.YOffset - m.Height)
|
||||||
m.YOffset-m.Height, // target
|
|
||||||
0, // fallback
|
|
||||||
)
|
|
||||||
|
|
||||||
return m.visibleLines()
|
return m.visibleLines()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,18 +167,8 @@ func (m *Model) HalfViewDown() (lines []string) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
m.YOffset = min(
|
m.SetYOffset(m.YOffset + m.Height/2)
|
||||||
m.YOffset+m.Height/2, // target
|
return m.visibleLines()
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// HalfViewUp moves the view up by half the height of the viewport.
|
// HalfViewUp moves the view up by half the height of the viewport.
|
||||||
@@ -136,18 +177,8 @@ func (m *Model) HalfViewUp() (lines []string) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
m.YOffset = max(
|
m.SetYOffset(m.YOffset - m.Height/2)
|
||||||
m.YOffset-m.Height/2, // target
|
return m.visibleLines()
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LineDown moves the view down by the given number of lines.
|
// LineDown moves the view down by the given number of lines.
|
||||||
@@ -159,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
|
// 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
|
// greater than the number of lines we actually have left before we reach
|
||||||
// the bottom.
|
// the bottom.
|
||||||
maxDelta := (len(m.lines) - 1) - (m.YOffset + m.Height) // number of lines - viewport bottom edge
|
m.SetYOffset(m.YOffset + n)
|
||||||
n = min(n, maxDelta)
|
return m.visibleLines()
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LineUp moves the view down by the given number of lines. Returns the new
|
// LineUp moves the view down by the given number of lines. Returns the new
|
||||||
@@ -185,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
|
// 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.
|
// greater than the number of lines we are from the top.
|
||||||
n = min(n, m.YOffset)
|
m.SetYOffset(m.YOffset - n)
|
||||||
|
return m.visibleLines()
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GotoTop sets the viewport to the top position.
|
// GotoTop sets the viewport to the top position.
|
||||||
@@ -204,32 +213,16 @@ func (m *Model) GotoTop() (lines []string) {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
m.YOffset = 0
|
m.SetYOffset(0)
|
||||||
|
return m.visibleLines()
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GotoTop sets the viewport to the bottom position.
|
// GotoBottom sets the viewport to the bottom position.
|
||||||
func (m *Model) GotoBottom() (lines []string) {
|
func (m *Model) GotoBottom() (lines []string) {
|
||||||
m.YOffset = max(len(m.lines)-1-m.Height, 0)
|
m.SetYOffset(m.maxYOffset())
|
||||||
|
return m.visibleLines()
|
||||||
if len(m.lines) > 0 {
|
|
||||||
top := m.YOffset
|
|
||||||
bottom := max(len(m.lines)-1, 0)
|
|
||||||
lines = m.lines[top:bottom]
|
|
||||||
}
|
|
||||||
|
|
||||||
return lines
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// COMMANDS
|
|
||||||
|
|
||||||
// Sync tells the renderer where the viewport will be located and requests
|
// 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
|
// a render of the current state of the viewport. It should be called for the
|
||||||
// first render and after a window resize.
|
// first render and after a window resize.
|
||||||
@@ -239,17 +232,8 @@ func Sync(m Model) tea.Cmd {
|
|||||||
if len(m.lines) == 0 {
|
if len(m.lines) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
top, bottom := m.scrollArea()
|
||||||
// TODO: we should probably use m.visibleLines() rather than these two
|
return tea.SyncScrollArea(m.visibleLines(), top, bottom)
|
||||||
// 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,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ViewDown is a high performance command that moves the viewport up by a given
|
// ViewDown is a high performance command that moves the viewport up by a given
|
||||||
@@ -263,7 +247,8 @@ func ViewDown(m Model, lines []string) tea.Cmd {
|
|||||||
if len(lines) == 0 {
|
if len(lines) == 0 {
|
||||||
return nil
|
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
|
// ViewUp is a high performance command the moves the viewport down by a given
|
||||||
@@ -273,57 +258,60 @@ func ViewUp(m Model, lines []string) tea.Cmd {
|
|||||||
if len(lines) == 0 {
|
if len(lines) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return tea.ScrollUp(lines, m.YPosition, m.YPosition+m.Height)
|
top, bottom := m.scrollArea()
|
||||||
|
return tea.ScrollUp(lines, top, bottom)
|
||||||
}
|
}
|
||||||
|
|
||||||
// UPDATE
|
// Update handles standard message-based viewport updates.
|
||||||
|
|
||||||
// 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.
|
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
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
|
var cmd tea.Cmd
|
||||||
|
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
switch msg.String() {
|
switch {
|
||||||
// Down one page
|
case key.Matches(msg, m.KeyMap.PageDown):
|
||||||
case "pgdown", spacebar, "f":
|
|
||||||
lines := m.ViewDown()
|
lines := m.ViewDown()
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewDown(m, lines)
|
cmd = ViewDown(m, lines)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Up one page
|
case key.Matches(msg, m.KeyMap.PageUp):
|
||||||
case "pgup", "b":
|
|
||||||
lines := m.ViewUp()
|
lines := m.ViewUp()
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewUp(m, lines)
|
cmd = ViewUp(m, lines)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Down half page
|
case key.Matches(msg, m.KeyMap.HalfPageDown):
|
||||||
case "d", "ctrl+d":
|
|
||||||
lines := m.HalfViewDown()
|
lines := m.HalfViewDown()
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewDown(m, lines)
|
cmd = ViewDown(m, lines)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Up half page
|
case key.Matches(msg, m.KeyMap.HalfPageUp):
|
||||||
case "u", "ctrl+u":
|
|
||||||
lines := m.HalfViewUp()
|
lines := m.HalfViewUp()
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewUp(m, lines)
|
cmd = ViewUp(m, lines)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Down one line
|
case key.Matches(msg, m.KeyMap.Down):
|
||||||
case "down", "j":
|
|
||||||
lines := m.LineDown(1)
|
lines := m.LineDown(1)
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewDown(m, lines)
|
cmd = ViewDown(m, lines)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Up one line
|
case key.Matches(msg, m.KeyMap.Up):
|
||||||
case "up", "k":
|
|
||||||
lines := m.LineUp(1)
|
lines := m.LineUp(1)
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewUp(m, lines)
|
cmd = ViewUp(m, lines)
|
||||||
@@ -331,15 +319,18 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case tea.MouseMsg:
|
case tea.MouseMsg:
|
||||||
|
if !m.MouseWheelEnabled {
|
||||||
|
break
|
||||||
|
}
|
||||||
switch msg.Type {
|
switch msg.Type {
|
||||||
case tea.MouseWheelUp:
|
case tea.MouseWheelUp:
|
||||||
lines := m.LineUp(3)
|
lines := m.LineUp(m.MouseWheelDelta)
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewUp(m, lines)
|
cmd = ViewUp(m, lines)
|
||||||
}
|
}
|
||||||
|
|
||||||
case tea.MouseWheelDown:
|
case tea.MouseWheelDown:
|
||||||
lines := m.LineDown(3)
|
lines := m.LineDown(m.MouseWheelDelta)
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
cmd = ViewDown(m, lines)
|
cmd = ViewDown(m, lines)
|
||||||
}
|
}
|
||||||
@@ -349,13 +340,11 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
return m, cmd
|
return m, cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
// VIEW
|
|
||||||
|
|
||||||
// View renders the viewport into a string.
|
// View renders the viewport into a string.
|
||||||
func (m Model) View() string {
|
func (m Model) View() string {
|
||||||
if m.HighPerformanceRendering {
|
if m.HighPerformanceRendering {
|
||||||
// Just send newlines since we're doing to be rendering the actual
|
// Just send newlines since we're going to be rendering the actual
|
||||||
// content seprately. We still need send something that equals the
|
// content seprately. We still need to send something that equals the
|
||||||
// height of this view so that the Bubble Tea standard renderer can
|
// height of this view so that the Bubble Tea standard renderer can
|
||||||
// position anything below this view properly.
|
// position anything below this view properly.
|
||||||
return strings.Repeat("\n", m.Height-1)
|
return strings.Repeat("\n", m.Height-1)
|
||||||
@@ -366,15 +355,19 @@ func (m Model) View() string {
|
|||||||
// Fill empty space with newlines
|
// Fill empty space with newlines
|
||||||
extraLines := ""
|
extraLines := ""
|
||||||
if len(lines) < m.Height {
|
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 {
|
func clamp(v, low, high int) int {
|
||||||
|
if high < low {
|
||||||
|
low, high = high, low
|
||||||
|
}
|
||||||
return min(high, max(low, v))
|
return min(high, max(low, v))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user