mirror of
https://github.com/Maks1mS/bubbles.git
synced 2025-10-17 16:15:58 +03:00
Compare commits
137 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
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 | ||
|
c8f4855d20 | ||
|
43d43d14ae | ||
|
de359c53bb | ||
|
c7d69b61f0 | ||
|
11f56f9b6b | ||
|
3be2d0585b | ||
|
37a85afcd1 | ||
|
f9c79eef64 | ||
|
c303de1e85 | ||
|
7e5ef42924 | ||
|
79ca4d09d1 | ||
|
f48e53556a | ||
|
5d6d8cb0fb | ||
|
47b8d9c6a8 | ||
|
b78277e7ec | ||
|
6a768905a6 | ||
|
0f06d78b92 | ||
|
1e16eca939 | ||
|
d81e5713d4 | ||
|
b10dbcb4dd | ||
|
a2e0a2e72e | ||
|
3dea7d036e | ||
|
68e87e08c5 | ||
|
65a17d039e | ||
|
38d59517fb | ||
|
06109f45ce | ||
|
9cb8e8d90a | ||
|
e6219572e5 | ||
|
81feaacf5b | ||
|
9a25d8b8b9 | ||
|
e8e052c64b | ||
|
3d7cd43046 | ||
|
9c38e101d2 | ||
|
84f7b047bb | ||
|
9e1e435bba | ||
|
0fd072ddcc | ||
|
a07ab1d6af | ||
|
8e49ee609e | ||
|
d02641f6b5 | ||
|
9b47f26bdd | ||
|
9c780011ff | ||
|
8148e61443 | ||
|
ce7d8da084 | ||
|
d14fdf585c | ||
|
bf7719e6c1 | ||
|
1b530b293c | ||
|
7d1c04164e | ||
|
97020cd0d2 | ||
|
5dbcf95877 | ||
|
f58fead10d | ||
|
703de11da4 | ||
|
03461d6804 | ||
|
4445acbace | ||
|
bd161e8ded | ||
|
d9716a97f6 | ||
|
a0fe547fdb | ||
|
1cb36774ed | ||
|
bdd909a5d7 | ||
|
b08b3efa02 | ||
|
83b6a2205f | ||
|
c06af8962d | ||
|
3a65be950a | ||
|
2dd6e0c80b | ||
|
1e50e6d291 | ||
|
573f90a876 | ||
|
a498b857d6 | ||
|
82097a1c79 | ||
|
a8ec421800 | ||
|
9c10cd0586 | ||
|
154f3763f7 | ||
|
eff931bdea | ||
|
0d7b3ed8e8 | ||
|
cbafae84f9 |
28
.github/workflows/build.yml
vendored
Normal file
28
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
name: build
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
test:
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [~1.13, ^1]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
GO111MODULE: "on"
|
||||
steps:
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Download Go modules
|
||||
run: go mod download
|
||||
|
||||
- name: Build
|
||||
run: go build -v ./...
|
||||
|
||||
- name: Test
|
||||
run: go test ./...
|
28
.github/workflows/coverage.yml
vendored
Normal file
28
.github/workflows/coverage.yml
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
name: coverage
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
coverage:
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [^1]
|
||||
os: [ubuntu-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
GO111MODULE: "on"
|
||||
steps:
|
||||
- name: Install Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Coverage
|
||||
env:
|
||||
COVERALLS_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
go test -race -covermode atomic -coverprofile=profile.cov ./...
|
||||
GO111MODULE=off go get github.com/mattn/goveralls
|
||||
$(go env GOPATH)/bin/goveralls -coverprofile=profile.cov -service=github
|
18
.github/workflows/lint.yml
vendored
Normal file
18
.github/workflows/lint.yml
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
name: lint
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
golangci:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v2
|
||||
with:
|
||||
# Optional: golangci-lint command line arguments.
|
||||
args: --issues-exit-code=0
|
||||
# Optional: working directory, useful for monorepos
|
||||
# working-directory: somedir
|
||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
||||
only-new-issues: true
|
34
.golangci.yml
Normal file
34
.golangci.yml
Normal file
@@ -0,0 +1,34 @@
|
||||
run:
|
||||
tests: false
|
||||
|
||||
issues:
|
||||
include:
|
||||
- EXC0001
|
||||
- EXC0005
|
||||
- EXC0011
|
||||
- EXC0012
|
||||
- EXC0013
|
||||
|
||||
max-issues-per-linter: 0
|
||||
max-same-issues: 0
|
||||
|
||||
linters:
|
||||
enable:
|
||||
- bodyclose
|
||||
- dupl
|
||||
- exportloopref
|
||||
- goconst
|
||||
- godot
|
||||
- godox
|
||||
- goimports
|
||||
- goprintffuncname
|
||||
- gosec
|
||||
- ifshort
|
||||
- misspell
|
||||
- prealloc
|
||||
- revive
|
||||
- rowserrcheck
|
||||
- sqlclosecheck
|
||||
- unconvert
|
||||
- unparam
|
||||
- whitespace
|
152
README.md
152
README.md
@@ -2,16 +2,21 @@ Bubbles
|
||||
=======
|
||||
|
||||
<p>
|
||||
<a href="https://pkg.go.dev/github.com/charmbracelet/bubbles?tab=doc"><img src="https://godoc.org/github.com/golang/gddo?status.svg" alt="GoDoc"></a>
|
||||
<a href="https://github.com/charmbracelet/bubbles/actions"><img src="https://github.com/charmbracelet/glow/workflows/build/badge.svg" alt="Build Status"></a>
|
||||
<img src="https://stuff.charm.sh/bubbles/bubbles-github.png" width="233" alt="The Bubbles Logo">
|
||||
</p>
|
||||
|
||||
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea) applications.
|
||||
[](https://github.com/charmbracelet/bubbles/releases)
|
||||
[](https://pkg.go.dev/github.com/charmbracelet/bubbles)
|
||||
[](https://github.com/charmbracelet/bubbles/actions)
|
||||
[](https://goreportcard.com/report/charmbracelet/bubbles)
|
||||
|
||||
These components are used in production in [Glow][glow] and [Charm][charm].
|
||||
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea)
|
||||
applications. These components are used in production in [Glow][glow],
|
||||
[Charm][charm] and [many other applications][otherstuff].
|
||||
|
||||
[glow]: https://github.com/charmbraclet/glow
|
||||
[charm]: https://github.com/charmbraclet/charm
|
||||
[glow]: https://github.com/charmbracelet/glow
|
||||
[charm]: https://github.com/charmbracelet/charm
|
||||
[otherstuff]: https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild
|
||||
|
||||
|
||||
## Spinner
|
||||
@@ -21,7 +26,8 @@ These components are used in production in [Glow][glow] and [Charm][charm].
|
||||
A spinner, useful for indicating that some kind an operation is happening.
|
||||
There are a couple default ones, but you can also pass your own ”frames.”
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/tea/tree/master/examples/spinner/main.go)
|
||||
* [Example code, basic spinner](https://github.com/charmbracelet/tea/tree/master/examples/spinner/main.go)
|
||||
* [Example code, various spinners](https://github.com/charmbracelet/tea/tree/master/examples/spinners/main.go)
|
||||
|
||||
|
||||
## Text Input
|
||||
@@ -33,7 +39,22 @@ pasting, in-place scrolling when the value exceeds the width of the element and
|
||||
the common, and many customization options.
|
||||
|
||||
* [Example code, one field](https://github.com/charmbracelet/tea/tree/master/examples/textinput/main.go)
|
||||
* [Example code, many fields](https://github.com/charmbracelet/tea/tree/master/examples/textinput/main.go)
|
||||
* [Example code, many fields](https://github.com/charmbracelet/tea/tree/master/examples/textinputs/main.go)
|
||||
|
||||
|
||||
## Progress
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/progress.gif" width="800" alt="Progressbar Example">
|
||||
|
||||
A simple, customizable progress meter, with optional animation via
|
||||
[Harmonica][harmonica]. Supports solid and gradient fills. The empty and filled
|
||||
runes can be set to whatever you'd like. The percentage readout is customizable
|
||||
and can also be omitted entirely.
|
||||
|
||||
* [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
|
||||
@@ -45,26 +66,123 @@ Supports "dot-style" pagination (similar to what you might see on iOS) and
|
||||
numeric page numbering, but you could also just use this component for the
|
||||
logic and visualize pagination however you like.
|
||||
|
||||
This component is used in [Glow][glow] to browse documents and [Charm][charm] to
|
||||
browse SSH keys.
|
||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/pager/main.go)
|
||||
|
||||
|
||||
## Viewport
|
||||
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif" width="600" alt="Viewport Example">
|
||||
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif?0" width="600" alt="Viewport Example">
|
||||
|
||||
A viewport for vertically scrolling content. Optionally includes standard
|
||||
pager keybindings and mouse wheel support. A high performance mode is available
|
||||
for applications which make use of the alterate screen buffer.
|
||||
for applications which make use of the alternate screen buffer.
|
||||
|
||||
* [Example code](https://github.com/charmbracelet/tea/tree/master/examples/pager/main.go)
|
||||
|
||||
This compoent is well complimented with [Reflow][reflow] for ANSI-aware
|
||||
This component is well complemented with [Reflow][reflow] for ANSI-aware
|
||||
indenting and text wrapping.
|
||||
|
||||
[reflow]: https://github.com/muesli/reflow
|
||||
|
||||
|
||||
## 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(
|
||||
WithKeys("j", "down"),
|
||||
WithHelp("↓/j", "move down"),
|
||||
),
|
||||
}
|
||||
|
||||
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch {
|
||||
case key.Matches(msg, DefaultKeyMap.Up):
|
||||
// The user pressed up
|
||||
case key.Matches(msg, DefaultKeyMap.Down):
|
||||
// The user pressed down
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Additional Bubbles
|
||||
|
||||
* [promptkit](https://github.com/erikgeiser/promptkit): A collection of common
|
||||
prompts for cases like selection, text input, and confirmation. Each prompt
|
||||
comes with sensible defaults, remappable keybindings, any many customization
|
||||
options.
|
||||
* [mritd/bubbles](https://github.com/mritd/bubbles): Some general-purpose
|
||||
bubbles. Inputs with validation, menu selection, a modified progressbar, and
|
||||
so on.
|
||||
|
||||
If you’ve built a Bubble you think should be listed here,
|
||||
[let us know](mailto:vt100@charm.sh).
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
|
||||
@@ -72,8 +190,10 @@ indenting and text wrapping.
|
||||
|
||||
***
|
||||
|
||||
A [Charm](https://charm.sh) project.
|
||||
Part of [Charm](https://charm.sh).
|
||||
|
||||
<img alt="the Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400">
|
||||
<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>
|
||||
|
||||
Charm热爱开源!
|
||||
Charm热爱开源 • Charm loves open source
|
||||
|
||||
[charm]: https://charm.sh/
|
||||
|
15
go.mod
15
go.mod
@@ -4,10 +4,13 @@ go 1.13
|
||||
|
||||
require (
|
||||
github.com/atotto/clipboard v0.1.2
|
||||
github.com/charmbracelet/bubbletea v0.10.3
|
||||
github.com/mattn/go-runewidth v0.0.9
|
||||
github.com/muesli/termenv v0.7.2
|
||||
golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de // indirect
|
||||
github.com/charmbracelet/bubbletea v0.19.3
|
||||
github.com/charmbracelet/harmonica v0.1.0
|
||||
github.com/charmbracelet/lipgloss v0.3.0
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0
|
||||
github.com/mattn/go-runewidth v0.0.13
|
||||
github.com/muesli/reflow v0.3.0
|
||||
github.com/muesli/termenv v0.9.0
|
||||
github.com/sahilm/fuzzy v0.1.0
|
||||
)
|
||||
|
||||
replace github.com/charmbracelet/bubbletea => ../bubbletea
|
||||
|
72
go.sum
72
go.sum
@@ -1,34 +1,46 @@
|
||||
github.com/atotto/clipboard v0.1.2 h1:YZCtFu5Ie8qX2VmVTBnrqLSiU9XOWwqNRmdT3gIQzbY=
|
||||
github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
||||
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=
|
||||
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=
|
||||
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
|
||||
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/charmbracelet/bubbletea v0.19.3 h1:OKeO/Y13rQQqt4snX+lePB0QrnW80UdrMNolnCcmoAw=
|
||||
github.com/charmbracelet/bubbletea v0.19.3/go.mod h1:VuXF2pToRxDUHcBUcPmCRUHRvFATM4Ckb/ql1rBl3KA=
|
||||
github.com/charmbracelet/harmonica v0.1.0 h1:lFKeSd6OAckQ/CEzPVd2mqj+YMEubQ/3FM2IYY3xNm0=
|
||||
github.com/charmbracelet/harmonica v0.1.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
|
||||
github.com/charmbracelet/lipgloss v0.3.0 h1:5MysOD6sHr4RP4jkZNWGVIul5GKoOsP12NgbgXPvAlA=
|
||||
github.com/charmbracelet/lipgloss v0.3.0/go.mod h1:VkhdBS2eNAmRkTwRKLJCFhCOVkjntMusBDxv7TXahuk=
|
||||
github.com/containerd/console v1.0.2 h1:Pi6D+aZXM+oUw1czuKgH5IJ+y0jhYcwBJfx5/Ghn9dE=
|
||||
github.com/containerd/console v1.0.2/go.mod h1:ytZPjGgY2oeTkAONYafi2kSj0aYggsf8acV1PGKCbzQ=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/muesli/termenv v0.5.3-0.20200625163851-04b5c30e4c04 h1:Wr876oXlAk6avTWi0daXAriOr+r5fqIuyDmtNc/KwY0=
|
||||
github.com/muesli/termenv v0.5.3-0.20200625163851-04b5c30e4c04/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=
|
||||
github.com/muesli/termenv v0.7.0 h1:KcLfgg/KICGxOxNr+P9gmkrJ5azxOm3WzkfXMePGTq4=
|
||||
github.com/muesli/termenv v0.7.0/go.mod h1:SohX91w6swWA4AYU+QmPx+aSgXhWO0juiyID9UZmbpA=
|
||||
github.com/muesli/termenv v0.7.2 h1:r1raklL3uKE7rOvWgSenmEm2px+dnc33OTisZ8YR1fw=
|
||||
github.com/muesli/termenv v0.7.2/go.mod h1:ct2L5N2lmix82RaY3bMWwVu/jUFc9Ule0KGDCiKYPh8=
|
||||
github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03 h1:pd4YKIqCB0U7O2I4gWHgEUA2mCEOENmco0l/bM957bU=
|
||||
github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03/go.mod h1:Z9+Ul5bCbBKnbCvdOWbLqTHhJiYV414CURZJba6L8qA=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 h1:DZhuSZLsGlFL4CmhA8BcRA0mnthyA/nZ00AqCUo7vHg=
|
||||
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de h1:ikNHVSjEfnvz6sxdSPCaPt572qowuyMDMJLLm3Db3ig=
|
||||
golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
github.com/mattn/go-isatty v0.0.13 h1:qdl+GuBjcsKKDco5BsxPJlId98mSWNKqYA+Co0SC1yA=
|
||||
github.com/mattn/go-isatty v0.0.13/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
|
||||
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
|
||||
github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68/go.mod h1:Xk+z4oIWdQqJzsxyjgl3P22oYZnHdZ8FFTHAQQt5BMQ=
|
||||
github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
|
||||
github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
|
||||
github.com/muesli/termenv v0.8.1/go.mod h1:kzt/D/4a88RoheZmwfqorY3A+tnsSMA9HJC/fQSFKo0=
|
||||
github.com/muesli/termenv v0.9.0 h1:wnbOaGz+LUR3jNT0zOzinPnyDaCZUQRZj9GxK8eRVl8=
|
||||
github.com/muesli/termenv v0.9.0/go.mod h1:R/LzAKf+suGs4IsO95y7+7DpFHO0KABgnZqtlyx2mBw=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
|
||||
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae h1:Ih9Yo4hSPImZOpfGuA4bR/ORKTAbhZo2AbWNRCnevdo=
|
||||
golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200819171115-d785dc25833f h1:KJuwZVtZBVzDmEDtB2zro9CXkD9O0dpCv4o2LHbQIAw=
|
||||
golang.org/x/sys v0.0.0-20200819171115-d785dc25833f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200821140526-fda516888d29 h1:mNuhGagCf3lDDm5C0376C/sxh6V7fy9WbdEu/YDNA04=
|
||||
golang.org/x/sys v0.0.0-20200821140526-fda516888d29/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk=
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed h1:Ei4bQjjpYUsS4efOUz+5Nz++IVkHk87n2zBA0NxBWc0=
|
||||
golang.org/x/term v0.0.0-20210422114643-f5beecf764ed/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
|
229
help/help.go
Normal file
229
help/help.go
Normal file
@@ -0,0 +1,229 @@
|
||||
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 (
|
||||
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(
|
||||
// WithKeys("j", "down"),
|
||||
// WithHelp("↓/j", "move down"),
|
||||
// ),
|
||||
// }
|
||||
//
|
||||
// func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
// switch msg := msg.(type) {
|
||||
// case tea.KeyMsg:
|
||||
// switch {
|
||||
// case key.Matches(msg, DefaultKeyMap.Up):
|
||||
// // The user pressed up
|
||||
// case key.Matches(msg, DefaultKeyMap.Down):
|
||||
// // The user pressed down
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // ...
|
||||
// }
|
||||
//
|
||||
// The help information, which is not used in the example above, can be used
|
||||
// to render help text for keystrokes in your views.
|
||||
package key
|
||||
|
||||
import (
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
// Binding describes a set of keybindings and, optionally, their associated
|
||||
// help text.
|
||||
type Binding struct {
|
||||
keys []string
|
||||
help Help
|
||||
disabled bool
|
||||
}
|
||||
|
||||
// BindingOpt is an initialization option for a keybinding. It's used as an
|
||||
// argument to NewBinding.
|
||||
type BindingOpt func(*Binding)
|
||||
|
||||
// NewBinding returns a new keybinding from a set of BindingOpt options.
|
||||
func NewBinding(opts ...BindingOpt) Binding {
|
||||
b := &Binding{}
|
||||
for _, opt := range opts {
|
||||
opt(b)
|
||||
}
|
||||
return *b
|
||||
}
|
||||
|
||||
// WithKeys initializes a keybinding with the given keystrokes.
|
||||
func WithKeys(keys ...string) BindingOpt {
|
||||
return func(b *Binding) {
|
||||
b.keys = keys
|
||||
}
|
||||
}
|
||||
|
||||
// WithHelp initializes a keybinding with the given help text.
|
||||
func WithHelp(key, desc string) BindingOpt {
|
||||
return func(b *Binding) {
|
||||
b.help = Help{Key: key, Desc: desc}
|
||||
}
|
||||
}
|
||||
|
||||
// WithDisabled initializes a disabled keybinding.
|
||||
func WithDisabled() BindingOpt {
|
||||
return func(b *Binding) {
|
||||
b.disabled = true
|
||||
}
|
||||
}
|
||||
|
||||
// SetKeys sets the keys for the keybinding.
|
||||
func (b *Binding) SetKeys(keys ...string) {
|
||||
b.keys = keys
|
||||
}
|
||||
|
||||
// Keys returns the keys for the keybinding.
|
||||
func (b Binding) Keys() []string {
|
||||
return b.keys
|
||||
}
|
||||
|
||||
// SetHelp sets the help text for the keybinding.
|
||||
func (b *Binding) SetHelp(key, desc string) {
|
||||
b.help = Help{Key: key, Desc: desc}
|
||||
}
|
||||
|
||||
// Help returns the Help information for the keybinding.
|
||||
func (b Binding) Help() Help {
|
||||
return b.help
|
||||
}
|
||||
|
||||
// Enabled returns whether or not the keybinding is enabled. Disabled
|
||||
// keybindings won't be activated and won't show up in help. Keybindings are
|
||||
// enabled by default.
|
||||
func (b Binding) Enabled() bool {
|
||||
return !b.disabled
|
||||
}
|
||||
|
||||
// SetEnabled enables or disables the keybinding.
|
||||
func (b *Binding) SetEnabled(v bool) {
|
||||
b.disabled = !v
|
||||
}
|
||||
|
||||
// Unbind removes the keys and help from this binding, effectively nullifying
|
||||
// it. This is a step beyond disabling it, since applications can enable
|
||||
// or disable key bindings based on application state.
|
||||
func (b *Binding) Unbind() {
|
||||
b.keys = nil
|
||||
b.help = Help{}
|
||||
}
|
||||
|
||||
// Help is help information for a given keybinding.
|
||||
type Help struct {
|
||||
Key string
|
||||
Desc string
|
||||
}
|
||||
|
||||
// Matches checks if the given KeyMsg matches 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")),
|
||||
}
|
||||
}
|
1204
list/list.go
Normal file
1204
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
|
||||
// pages: it's purely for handling keystrokes related to pagination, and
|
||||
// rendering pagination status.
|
||||
@@ -19,7 +19,7 @@ const (
|
||||
Dots
|
||||
)
|
||||
|
||||
// Model is the Tea model for this user interface.
|
||||
// Model is the Bubble Tea model for this user interface.
|
||||
type Model struct {
|
||||
Type Type
|
||||
Page int
|
||||
@@ -35,13 +35,13 @@ type Model struct {
|
||||
UseJKKeys bool
|
||||
}
|
||||
|
||||
// SetTotalPages is a helper function for calculatng the total number of pages
|
||||
// SetTotalPages is a helper function for calculating the total number of pages
|
||||
// from a given number of items. It's use is optional since this pager can be
|
||||
// used for other things beyond navigating sets. Note that it both returns the
|
||||
// number of total pages and alters the model.
|
||||
func (m *Model) SetTotalPages(items int) int {
|
||||
if items == 0 {
|
||||
return 0
|
||||
if items < 1 {
|
||||
return m.TotalPages
|
||||
}
|
||||
n := items / m.PerPage
|
||||
if items%m.PerPage > 0 {
|
||||
@@ -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 {
|
||||
return m.Page == m.TotalPages-1
|
||||
}
|
||||
|
||||
// NewModel creates a new model with defaults.
|
||||
func NewModel() Model {
|
||||
// New creates a new model with defaults.
|
||||
func New() Model {
|
||||
return Model{
|
||||
Type: Arabic,
|
||||
Page: 0,
|
||||
@@ -114,8 +114,13 @@ func NewModel() Model {
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel creates a new model with defaults.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// Update is the Tea update function which binds keystrokes to pagination.
|
||||
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
if m.UsePgUpPgDownKeys {
|
||||
@@ -164,20 +169,16 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
}
|
||||
|
||||
// View renders the pagination to a string.
|
||||
func View(model tea.Model) string {
|
||||
m, ok := model.(Model)
|
||||
if !ok {
|
||||
return "could not perform assertion on model"
|
||||
}
|
||||
func (m Model) View() string {
|
||||
switch m.Type {
|
||||
case Dots:
|
||||
return dotsView(m)
|
||||
return m.dotsView()
|
||||
default:
|
||||
return arabicView(m)
|
||||
return m.arabicView()
|
||||
}
|
||||
}
|
||||
|
||||
func dotsView(m Model) string {
|
||||
func (m Model) dotsView() string {
|
||||
var s string
|
||||
for i := 0; i < m.TotalPages; i++ {
|
||||
if i == m.Page {
|
||||
@@ -189,7 +190,7 @@ func dotsView(m Model) string {
|
||||
return s
|
||||
}
|
||||
|
||||
func arabicView(m Model) string {
|
||||
func (m Model) arabicView() string {
|
||||
return fmt.Sprintf(m.ArabicFormat, m.Page+1, m.TotalPages)
|
||||
}
|
||||
|
||||
|
347
progress/progress.go
Normal file
347
progress/progress.go
Normal file
@@ -0,0 +1,347 @@
|
||||
package progress
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/harmonica"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/lucasb-eyer/go-colorful"
|
||||
"github.com/muesli/reflow/ansi"
|
||||
"github.com/muesli/termenv"
|
||||
)
|
||||
|
||||
// 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
|
||||
|
||||
// Option is used to set options in NewModel. For example:
|
||||
//
|
||||
// progress := NewModel(
|
||||
// WithRamp("#ff0000", "#0000ff"),
|
||||
// WithoutPercentage(),
|
||||
// )
|
||||
//
|
||||
type Option func(*Model)
|
||||
|
||||
// WithDefaultGradient sets a gradient fill with default colors.
|
||||
func WithDefaultGradient() Option {
|
||||
return WithGradient("#5A56E0", "#EE6FF8")
|
||||
}
|
||||
|
||||
// WithGradient sets a gradient fill blending between two colors.
|
||||
func WithGradient(colorA, colorB string) Option {
|
||||
return func(m *Model) {
|
||||
m.setRamp(colorA, colorB, false)
|
||||
}
|
||||
}
|
||||
|
||||
// WithDefaultScaledGradient sets a gradient with default colors, and scales the
|
||||
// gradient to fit the filled portion of the ramp.
|
||||
func WithDefaultScaledGradient() Option {
|
||||
return WithScaledGradient("#5A56E0", "#EE6FF8")
|
||||
}
|
||||
|
||||
// WithScaledGradient scales the gradient to fit the width of the filled portion of
|
||||
// the progress bar.
|
||||
func WithScaledGradient(colorA, colorB string) Option {
|
||||
return func(m *Model) {
|
||||
m.setRamp(colorA, colorB, true)
|
||||
}
|
||||
}
|
||||
|
||||
// WithSolidFill sets the progress to use a solid fill with the given color.
|
||||
func WithSolidFill(color string) Option {
|
||||
return func(m *Model) {
|
||||
m.FullColor = color
|
||||
m.useRamp = false
|
||||
}
|
||||
}
|
||||
|
||||
// WithoutPercentage hides the numeric percentage.
|
||||
func WithoutPercentage() Option {
|
||||
return func(m *Model) {
|
||||
m.ShowPercentage = false
|
||||
}
|
||||
}
|
||||
|
||||
// WithWidth sets the initial width of the progress bar. Note that you can also
|
||||
// set the width via the Width property, which can come in handy if you're
|
||||
// waiting for a tea.WindowSizeMsg.
|
||||
func WithWidth(w int) Option {
|
||||
return func(m *Model) {
|
||||
m.Width = w
|
||||
}
|
||||
}
|
||||
|
||||
func WithSpringOptions(frequency, damping float64) Option {
|
||||
return func(m *Model) {
|
||||
m.SetSpringOptions(frequency, damping)
|
||||
m.springCustomized = true
|
||||
}
|
||||
}
|
||||
|
||||
// FrameMsg indicates that an animation step should occur.
|
||||
type FrameMsg struct {
|
||||
id int
|
||||
tag int
|
||||
}
|
||||
|
||||
// Model stores values we'll use when rendering the progress bar.
|
||||
type Model struct {
|
||||
// An identifier to keep us from receiving messages intended for other
|
||||
// progress bars.
|
||||
id int
|
||||
|
||||
// An identifier to keep us from receiving frame messages too quickly.
|
||||
tag int
|
||||
|
||||
// Total width of the progress bar, including percentage, if set.
|
||||
Width int
|
||||
|
||||
// "Filled" sections of the progress bar.
|
||||
Full rune
|
||||
FullColor string
|
||||
|
||||
// "Empty" sections of progress bar.
|
||||
Empty rune
|
||||
EmptyColor string
|
||||
|
||||
// Settings for rendering the numeric percentage.
|
||||
ShowPercentage bool
|
||||
PercentFormat string // a fmt string for a float
|
||||
PercentageStyle lipgloss.Style
|
||||
|
||||
// Members for animated transitions.
|
||||
spring harmonica.Spring
|
||||
springCustomized bool
|
||||
percent float64
|
||||
targetPercent float64
|
||||
velocity float64
|
||||
|
||||
// Gradient settings
|
||||
useRamp bool
|
||||
rampColorA colorful.Color
|
||||
rampColorB colorful.Color
|
||||
|
||||
// When true, we scale the gradient to fit the width of the filled section
|
||||
// of the progress bar. When false, the width of the gradient will be set
|
||||
// to the full width of the progress bar.
|
||||
scaleRamp bool
|
||||
}
|
||||
|
||||
// New returns a model with default values.
|
||||
func New(opts ...Option) Model {
|
||||
m := Model{
|
||||
id: nextID(),
|
||||
Width: defaultWidth,
|
||||
Full: '█',
|
||||
FullColor: "#7571F9",
|
||||
Empty: '░',
|
||||
EmptyColor: "#606060",
|
||||
ShowPercentage: true,
|
||||
PercentFormat: " %3.0f%%",
|
||||
}
|
||||
if !m.springCustomized {
|
||||
m.SetSpringOptions(defaultFrequency, defaultDamping)
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(&m)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// Init exists satisfy the tea.Model interface.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// If we've more or less reached equilibrium, stop updating.
|
||||
dist := math.Abs(m.percent - m.targetPercent)
|
||||
if dist < 0.001 && m.velocity < 0.01 {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
m.percent, m.velocity = m.spring.Update(m.percent, m.velocity, m.targetPercent)
|
||||
return m, m.nextFrame()
|
||||
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
}
|
||||
|
||||
// SetSpringOptions sets the frequency and damping for the current spring.
|
||||
// Frequency corresponds to speed, and damping to bounciness. For details see:
|
||||
// https://github.com/charmbracelet/harmonica.
|
||||
func (m *Model) SetSpringOptions(frequency, damping float64) {
|
||||
m.spring = harmonica.NewSpring(harmonica.FPS(fps), frequency, damping)
|
||||
}
|
||||
|
||||
// Percent returns the current percentage state of the model. This is only
|
||||
// relevant when you're animating the progress bar.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m Model) Percent() float64 {
|
||||
return m.targetPercent
|
||||
}
|
||||
|
||||
// SetPercent sets the percentage state of the model as well as a command
|
||||
// necessary for animating the progress bar to this new percentage.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m *Model) SetPercent(p float64) tea.Cmd {
|
||||
m.targetPercent = math.Max(0, math.Min(1, p))
|
||||
m.tag++
|
||||
return m.nextFrame()
|
||||
}
|
||||
|
||||
// IncrPercent increments the percentage by a given amount, returning a command
|
||||
// necessary to animate the progress bar to the new percentage.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m *Model) IncrPercent(v float64) tea.Cmd {
|
||||
return m.SetPercent(m.Percent() + v)
|
||||
}
|
||||
|
||||
// DecrPercent decrements the percentage by a given amount, returning a command
|
||||
// necessary to animate the progress bar to the new percentage.
|
||||
//
|
||||
// If you're rendering with ViewAs you won't need this.
|
||||
func (m *Model) DecrPercent(v float64) tea.Cmd {
|
||||
return m.SetPercent(m.Percent() - v)
|
||||
}
|
||||
|
||||
// View renders the an animated progress bar in its current state. To render
|
||||
// a static progress bar based on your own calculations use ViewAs instead.
|
||||
func (m Model) View() string {
|
||||
return m.ViewAs(m.percent)
|
||||
}
|
||||
|
||||
// ViewAs renders the progress bar with a given percentage.
|
||||
func (m Model) ViewAs(percent float64) string {
|
||||
b := strings.Builder{}
|
||||
percentView := m.percentageView(percent)
|
||||
m.barView(&b, percent, ansi.PrintableRuneWidth(percentView))
|
||||
b.WriteString(percentView)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *Model) nextFrame() tea.Cmd {
|
||||
return tea.Tick(time.Second/time.Duration(fps), func(time.Time) tea.Msg {
|
||||
return FrameMsg{id: m.id, tag: m.tag}
|
||||
})
|
||||
}
|
||||
|
||||
func (m Model) barView(b *strings.Builder, percent float64, textWidth int) {
|
||||
var (
|
||||
tw = max(0, m.Width-textWidth) // total width
|
||||
fw = int(math.Round((float64(tw) * percent))) // filled width
|
||||
p float64
|
||||
)
|
||||
|
||||
fw = max(0, min(tw, fw))
|
||||
|
||||
if m.useRamp {
|
||||
// Gradient fill
|
||||
for i := 0; i < fw; i++ {
|
||||
if m.scaleRamp {
|
||||
p = float64(i) / float64(fw)
|
||||
} else {
|
||||
p = float64(i) / float64(tw)
|
||||
}
|
||||
c := m.rampColorA.BlendLuv(m.rampColorB, p).Hex()
|
||||
b.WriteString(termenv.
|
||||
String(string(m.Full)).
|
||||
Foreground(color(c)).
|
||||
String(),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
// Solid fill
|
||||
s := termenv.String(string(m.Full)).Foreground(color(m.FullColor)).String()
|
||||
b.WriteString(strings.Repeat(s, fw))
|
||||
}
|
||||
|
||||
// Empty fill
|
||||
e := termenv.String(string(m.Empty)).Foreground(color(m.EmptyColor)).String()
|
||||
n := max(0, tw-fw)
|
||||
b.WriteString(strings.Repeat(e, n))
|
||||
}
|
||||
|
||||
func (m Model) percentageView(percent float64) string {
|
||||
if !m.ShowPercentage {
|
||||
return ""
|
||||
}
|
||||
percent = math.Max(0, math.Min(1, percent))
|
||||
percentage := fmt.Sprintf(m.PercentFormat, percent*100) //nolint:gomnd
|
||||
percentage = m.PercentageStyle.Inline(true).Render(percentage)
|
||||
return percentage
|
||||
}
|
||||
|
||||
func (m *Model) setRamp(colorA, colorB string, scaled bool) {
|
||||
// In the event of an error colors here will default to black. For
|
||||
// usability's sake, and because such an error is only cosmetic, we're
|
||||
// ignoring the error for sake of usability.
|
||||
a, _ := colorful.Hex(colorA)
|
||||
b, _ := colorful.Hex(colorB)
|
||||
|
||||
m.useRamp = true
|
||||
m.scaleRamp = scaled
|
||||
m.rampColorA = a
|
||||
m.rampColorB = b
|
||||
}
|
||||
|
||||
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
|
||||
}
|
@@ -1,48 +1,89 @@
|
||||
package spinner
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/muesli/termenv"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/muesli/reflow/ansi"
|
||||
)
|
||||
|
||||
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.
|
||||
type Spinner = []string
|
||||
type Spinner struct {
|
||||
Frames []string
|
||||
FPS time.Duration
|
||||
}
|
||||
|
||||
// Some spinners to choose from. You could also make your own.
|
||||
var (
|
||||
// Some spinners to choose from. You could also make your own.
|
||||
Line = Spinner([]string{"|", "/", "-", "\\"})
|
||||
Dot = Spinner([]string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "})
|
||||
|
||||
color = termenv.ColorProfile().Color
|
||||
Line = Spinner{
|
||||
Frames: []string{"|", "/", "-", "\\"},
|
||||
FPS: time.Second / 10, //nolint:gomnd
|
||||
}
|
||||
Dot = Spinner{
|
||||
Frames: []string{"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},
|
||||
FPS: time.Second / 10, //nolint:gomnd
|
||||
}
|
||||
MiniDot = Spinner{
|
||||
Frames: []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
|
||||
FPS: time.Second / 12, //nolint:gomnd
|
||||
}
|
||||
Jump = Spinner{
|
||||
Frames: []string{"⢄", "⢂", "⢁", "⡁", "⡈", "⡐", "⡠"},
|
||||
FPS: time.Second / 10, //nolint:gomnd
|
||||
}
|
||||
Pulse = Spinner{
|
||||
Frames: []string{"█", "▓", "▒", "░"},
|
||||
FPS: time.Second / 8, //nolint:gomnd
|
||||
}
|
||||
Points = Spinner{
|
||||
Frames: []string{"∙∙∙", "●∙∙", "∙●∙", "∙∙●"},
|
||||
FPS: time.Second / 7, //nolint:gomnd
|
||||
}
|
||||
Globe = Spinner{
|
||||
Frames: []string{"🌍", "🌎", "🌏"},
|
||||
FPS: time.Second / 4, //nolint:gomnd
|
||||
}
|
||||
Moon = Spinner{
|
||||
Frames: []string{"🌑", "🌒", "🌓", "🌔", "🌕", "🌖", "🌗", "🌘"},
|
||||
FPS: time.Second / 8, //nolint:gomnd
|
||||
}
|
||||
Monkey = Spinner{
|
||||
Frames: []string{"🙈", "🙉", "🙊"},
|
||||
FPS: time.Second / 3, //nolint:gomnd
|
||||
}
|
||||
)
|
||||
|
||||
// Model contains the state for the spinner. Use NewModel to create new models
|
||||
// rather than using Model as a struct literal.
|
||||
type Model struct {
|
||||
|
||||
// Type is the set of frames to use. See Spinner.
|
||||
Frames Spinner
|
||||
// Spinner settings to use. See type Spinner.
|
||||
Spinner Spinner
|
||||
|
||||
// FPS is the speed at which the ticker should tick.
|
||||
FPS time.Duration
|
||||
|
||||
// ForegroundColor 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
|
||||
// doesn't support the color specified it will automatically degrade
|
||||
// (per github.com/muesli/termenv).
|
||||
ForegroundColor string
|
||||
|
||||
// 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
|
||||
// doesn't support the color specified it will automatically degrade
|
||||
// (per github.com/muesli/termenv).
|
||||
BackgroundColor string
|
||||
// Style sets the styling for the spinner. Most of the time you'll just
|
||||
// want foreground and background coloring, and potentially some padding.
|
||||
//
|
||||
// For an introduction to styling with Lip Gloss see:
|
||||
// https://github.com/charmbracelet/lipgloss
|
||||
Style lipgloss.Style
|
||||
|
||||
// MinimumLifetime is the minimum amount of time the spinner can run. Any
|
||||
// logic around this can be implemented in view that implements this
|
||||
@@ -67,17 +108,55 @@ type Model struct {
|
||||
|
||||
frame int
|
||||
startTime time.Time
|
||||
id int
|
||||
tag int
|
||||
}
|
||||
|
||||
// Start resets resets the spinner start time. For use with MinimumLifetime and
|
||||
// MinimumStartTime. Optional.
|
||||
//
|
||||
// This function is optional and generally considered for advanced use only.
|
||||
// Most of the time your application logic will obviate the need for this
|
||||
// method.
|
||||
//
|
||||
// This is considered experimental and may not appear in future versions of
|
||||
// this library.
|
||||
func (m *Model) Start() {
|
||||
m.startTime = time.Now()
|
||||
}
|
||||
|
||||
// Finish sets the internal timer to a completed state so long as the spinner
|
||||
// isn't flagged to be showing. If it is showing, finish has no effect. The
|
||||
// idea here is that you call Finish if your operation has completed and, if
|
||||
// the spinner isn't showing yet (by virtue of HideFor) then Visible() doesn't
|
||||
// show the spinner at all.
|
||||
//
|
||||
// This is intended to work in conjunction with MinimumLifetime and
|
||||
// MinimumStartTime, is completely optional.
|
||||
//
|
||||
// This function is optional and generally considered for advanced use only.
|
||||
// Most of the time your application logic will obviate the need for this
|
||||
// method.
|
||||
//
|
||||
// This is considered experimental and may not appear in future versions of
|
||||
// this library.
|
||||
func (m *Model) Finish() {
|
||||
if m.hidden() {
|
||||
m.startTime = time.Time{}
|
||||
}
|
||||
}
|
||||
|
||||
// ID returns the spinner's unique ID.
|
||||
func (m Model) ID() int {
|
||||
return m.id
|
||||
}
|
||||
|
||||
// advancedMode returns whether or not the user is making use of HideFor and
|
||||
// MinimumLifetime properties.
|
||||
func (m Model) advancedMode() bool {
|
||||
return m.HideFor > 0 && m.MinimumLifetime > 0
|
||||
}
|
||||
|
||||
// hidden returns whether or not Model.HideFor is in effect.
|
||||
func (m Model) hidden() bool {
|
||||
if m.startTime.IsZero() {
|
||||
@@ -89,12 +168,10 @@ func (m Model) hidden() bool {
|
||||
return m.startTime.Add(m.HideFor).After(time.Now())
|
||||
}
|
||||
|
||||
// finished returns whether Model.MinimumLifetimeReached has been met.
|
||||
// finished returns whether the minimum lifetime of this spinner has been
|
||||
// exceeded.
|
||||
func (m Model) finished() bool {
|
||||
if m.startTime.IsZero() {
|
||||
return true
|
||||
}
|
||||
if m.MinimumLifetime == 0 {
|
||||
if m.startTime.IsZero() || m.MinimumLifetime == 0 {
|
||||
return true
|
||||
}
|
||||
return m.startTime.Add(m.HideFor).Add(m.MinimumLifetime).Before(time.Now())
|
||||
@@ -102,13 +179,13 @@ func (m Model) finished() bool {
|
||||
|
||||
// Visible returns whether or not the view should be rendered. Works in
|
||||
// conjunction with Model.HideFor and Model.MinimumLifetimeReached. You should
|
||||
// use this message directly to determine whether or not to render this view in
|
||||
// use this method directly to determine whether or not to render this view in
|
||||
// the parent view and whether to continue sending spin messaging in the
|
||||
// parent update function.
|
||||
//
|
||||
// Also note that using this function is optional and generally considered for
|
||||
// advanced use only. Most of the time your application logic will determine
|
||||
// whether or not this view should be used.
|
||||
// This function is optional and generally considered for advanced use only.
|
||||
// Most of the time your application logic will obviate the need for this
|
||||
// method.
|
||||
//
|
||||
// This is considered experimental and may not appear in future versions of
|
||||
// this library.
|
||||
@@ -116,57 +193,105 @@ func (m Model) Visible() bool {
|
||||
return !m.hidden() && !m.finished()
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
func NewModel() Model {
|
||||
// New returns a model with default values.
|
||||
func New() Model {
|
||||
return Model{
|
||||
Frames: Line,
|
||||
FPS: defaultFPS,
|
||||
Spinner: Line,
|
||||
id: nextID(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel returns a model with default values.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// TickMsg indicates that the timer has ticked and we should render a frame.
|
||||
type TickMsg struct {
|
||||
Time time.Time
|
||||
tag int
|
||||
ID int
|
||||
}
|
||||
|
||||
// Update is the Tea update function. This will advance the spinner one frame
|
||||
// every time it's called, regardless the message passed, so be sure the logic
|
||||
// is setup so as not to call this Update needlessly.
|
||||
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
if _, ok := msg.(TickMsg); ok {
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case TickMsg:
|
||||
// If an ID is set, and the ID doesn't belong to this spinner, reject
|
||||
// the message.
|
||||
if msg.ID > 0 && msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// If a tag is set, and it's not the one we expect, reject the message.
|
||||
// This prevents the spinner from receiving too many messages and
|
||||
// thus spinning too fast.
|
||||
if msg.tag > 0 && msg.tag != m.tag {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
m.frame++
|
||||
if m.frame >= len(m.Frames) {
|
||||
if m.frame >= len(m.Spinner.Frames) {
|
||||
m.frame = 0
|
||||
}
|
||||
return m, Tick(m)
|
||||
|
||||
m.tag++
|
||||
return m, m.tick(m.id, m.tag)
|
||||
default:
|
||||
return m, nil
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// View renders the model's view.
|
||||
func View(model Model) string {
|
||||
if model.frame >= len(model.Frames) {
|
||||
return "error"
|
||||
func (m Model) View() string {
|
||||
if m.frame >= len(m.Spinner.Frames) {
|
||||
return "(error)"
|
||||
}
|
||||
|
||||
frame := model.Frames[model.frame]
|
||||
frame := m.Spinner.Frames[m.frame]
|
||||
|
||||
if model.ForegroundColor != "" || model.BackgroundColor != "" {
|
||||
return termenv.
|
||||
String(frame).
|
||||
Foreground(color(model.ForegroundColor)).
|
||||
Background(color(model.BackgroundColor)).
|
||||
String()
|
||||
// If we're using the fine-grained hide/show spinner rules and those rules
|
||||
// deem that the spinner should be hidden, draw an empty space in place of
|
||||
// the spinner.
|
||||
if m.advancedMode() && !m.Visible() {
|
||||
frame = strings.Repeat(" ", ansi.PrintableRuneWidth(frame))
|
||||
}
|
||||
|
||||
return frame
|
||||
return m.Style.Render(frame)
|
||||
}
|
||||
|
||||
// Tick is the command used to advance the spinner one frame.
|
||||
func Tick(m Model) tea.Cmd {
|
||||
return tea.Tick(m.FPS, func(t time.Time) tea.Msg {
|
||||
// Tick is the command used to advance the spinner one frame. Use this command
|
||||
// to effectively start the spinner.
|
||||
func (m Model) Tick() tea.Msg {
|
||||
return TickMsg{
|
||||
// The time at which the tick occurred.
|
||||
Time: time.Now(),
|
||||
|
||||
// The ID of the spinner that this message belongs to. This can be
|
||||
// helpful when routing messages, however bear in mind that spinners
|
||||
// will ignore messages that don't contain ID by default.
|
||||
ID: m.id,
|
||||
|
||||
tag: m.tag,
|
||||
}
|
||||
}
|
||||
|
||||
func (m Model) tick(id, tag int) tea.Cmd {
|
||||
return tea.Tick(m.Spinner.FPS, func(t time.Time) tea.Msg {
|
||||
return TickMsg{
|
||||
Time: t,
|
||||
ID: id,
|
||||
tag: tag,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Tick is the command used to advance the spinner one frame. Use this command
|
||||
// to effectively start the spinner.
|
||||
//
|
||||
// This method is deprecated. Use Model.Tick instead.
|
||||
func Tick() tea.Msg {
|
||||
return TickMsg{Time: time.Now()}
|
||||
}
|
||||
|
152
stopwatch/stopwatch.go
Normal file
152
stopwatch/stopwatch.go
Normal file
@@ -0,0 +1,152 @@
|
||||
// Package stopwatch provides a simple stopwatch component.
|
||||
package stopwatch
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
var (
|
||||
lastID int
|
||||
idMtx sync.Mutex
|
||||
)
|
||||
|
||||
func nextID() int {
|
||||
idMtx.Lock()
|
||||
defer idMtx.Unlock()
|
||||
lastID++
|
||||
return lastID
|
||||
}
|
||||
|
||||
// TickMsg is a message that is sent on every timer tick.
|
||||
type TickMsg struct {
|
||||
// ID is the identifier of the stopwatch that send the message. This makes
|
||||
// it possible to determine which stopwatch a tick belongs to when there
|
||||
// are multiple stopwatches running.
|
||||
//
|
||||
// Note, however, that a stopwatch will reject ticks from other
|
||||
// stopwatches, so it's safe to flow all TickMsgs through all stopwatches
|
||||
// and have them still behave appropriately.
|
||||
ID int
|
||||
}
|
||||
|
||||
// StartStopMsg is sent when the stopwatch should start or stop.
|
||||
type StartStopMsg struct {
|
||||
ID int
|
||||
running bool
|
||||
}
|
||||
|
||||
// ResetMsg is sent when the stopwatch should reset.
|
||||
type ResetMsg struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
// Model for the stopwatch component.
|
||||
type Model struct {
|
||||
d time.Duration
|
||||
id int
|
||||
running bool
|
||||
|
||||
// How long to wait before every tick. Defaults to 1 second.
|
||||
Interval time.Duration
|
||||
}
|
||||
|
||||
// NewWithInterval creates a new stopwatch with the given timeout and tick
|
||||
// interval.
|
||||
func NewWithInterval(interval time.Duration) Model {
|
||||
return Model{
|
||||
Interval: interval,
|
||||
id: nextID(),
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a new stopwatch with 1s interval.
|
||||
func New() Model {
|
||||
return NewWithInterval(time.Second)
|
||||
}
|
||||
|
||||
// ID returns the unique ID of the model.
|
||||
func (m Model) ID() int {
|
||||
return m.id
|
||||
}
|
||||
|
||||
// Init starts the stopwatch.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return m.Start()
|
||||
}
|
||||
|
||||
// Start starts the stopwatch.
|
||||
func (m Model) Start() tea.Cmd {
|
||||
return tea.Batch(func() tea.Msg {
|
||||
return StartStopMsg{ID: m.id, running: true}
|
||||
}, tick(m.id, m.Interval))
|
||||
}
|
||||
|
||||
// Stop stops the stopwatch.
|
||||
func (m Model) Stop() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return StartStopMsg{ID: m.id, running: false}
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle stops the stopwatch if it is running and starts it if it is stopped.
|
||||
func (m Model) Toggle() tea.Cmd {
|
||||
if m.Running() {
|
||||
return m.Stop()
|
||||
}
|
||||
return m.Start()
|
||||
}
|
||||
|
||||
// Reset restes the stopwatch to 0.
|
||||
func (m Model) Reset() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return ResetMsg{ID: m.id}
|
||||
}
|
||||
}
|
||||
|
||||
// Running returns true if the stopwatch is running or false if it is stopped.
|
||||
func (m Model) Running() bool {
|
||||
return m.running
|
||||
}
|
||||
|
||||
// Update handles the timer tick.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case StartStopMsg:
|
||||
if msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
m.running = msg.running
|
||||
case ResetMsg:
|
||||
if msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
m.d = 0
|
||||
case TickMsg:
|
||||
if !m.running || msg.ID != m.id {
|
||||
break
|
||||
}
|
||||
m.d += m.Interval
|
||||
return m, tick(m.id, m.Interval)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Elapsed returns the time elapsed.
|
||||
func (m Model) Elapsed() time.Duration {
|
||||
return m.d
|
||||
}
|
||||
|
||||
// View of the timer component.
|
||||
func (m Model) View() string {
|
||||
return m.d.String()
|
||||
}
|
||||
|
||||
func tick(id int, d time.Duration) tea.Cmd {
|
||||
return tea.Tick(d, func(_ time.Time) tea.Msg {
|
||||
return TickMsg{ID: id}
|
||||
})
|
||||
}
|
@@ -1,41 +1,116 @@
|
||||
package textinput
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/atotto/clipboard"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
rw "github.com/mattn/go-runewidth"
|
||||
"github.com/muesli/termenv"
|
||||
)
|
||||
|
||||
const defaultBlinkSpeed = time.Millisecond * 530
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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{}
|
||||
|
||||
// Internal messages for clipboard operations.
|
||||
type pasteMsg string
|
||||
type pasteErrMsg struct{ error }
|
||||
|
||||
// EchoMode sets the input behavior of the text input field.
|
||||
type EchoMode int
|
||||
|
||||
const (
|
||||
defaultBlinkSpeed = time.Millisecond * 600
|
||||
// EchoNormal displays text as is. This is the default behavior.
|
||||
EchoNormal EchoMode = iota
|
||||
|
||||
// EchoPassword displays the EchoCharacter mask instead of actual
|
||||
// characters. This is commonly used for password fields.
|
||||
EchoPassword
|
||||
|
||||
// EchoNone displays nothing as characters are entered. This is commonly
|
||||
// seen for password fields on the command line.
|
||||
EchoNone
|
||||
|
||||
// EchoOnEdit
|
||||
)
|
||||
|
||||
var (
|
||||
// color is a helper for returning colors.
|
||||
color func(s string) termenv.Color = termenv.ColorProfile().Color
|
||||
// blinkCtx manages cursor blinking.
|
||||
type blinkCtx struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
// CursorMode describes the behavior of the cursor.
|
||||
type CursorMode int
|
||||
|
||||
// Available cursor modes.
|
||||
const (
|
||||
CursorBlink CursorMode = iota
|
||||
CursorStatic
|
||||
CursorHide
|
||||
)
|
||||
|
||||
// ErrMsg indicates there's been an error. We don't handle errors in the this
|
||||
// package; we're expecting errors to be handle in the program that implements
|
||||
// this text input.
|
||||
type ErrMsg error
|
||||
// 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 Tea model for this text input element.
|
||||
// Model is the Bubble Tea model for this text input element.
|
||||
type Model struct {
|
||||
Err error
|
||||
Prompt string
|
||||
Cursor string
|
||||
BlinkSpeed time.Duration
|
||||
Placeholder string
|
||||
TextColor string
|
||||
BackgroundColor string
|
||||
PlaceholderColor string
|
||||
CursorColor string
|
||||
Err error
|
||||
|
||||
// General settings.
|
||||
Prompt string
|
||||
Placeholder string
|
||||
BlinkSpeed time.Duration
|
||||
EchoMode EchoMode
|
||||
EchoCharacter rune
|
||||
|
||||
// Styles. These will be applied as inline styles.
|
||||
//
|
||||
// For an introduction to styling with Lip Gloss see:
|
||||
// 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
|
||||
// accept. If 0 or less, there's no limit.
|
||||
@@ -46,25 +121,64 @@ type Model struct {
|
||||
// viewport. If 0 or less this setting is ignored.
|
||||
Width int
|
||||
|
||||
// Underlying text value
|
||||
// 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.
|
||||
value []rune
|
||||
|
||||
// Focus indicates whether user input focus should be on this input
|
||||
// component. When false, don't blink and ignore keyboard input.
|
||||
// focus indicates whether user input focus should be on this input
|
||||
// component. When false, ignore keyboard input and hide the cursor.
|
||||
focus bool
|
||||
|
||||
// Cursor blink state
|
||||
// Cursor blink state.
|
||||
blink bool
|
||||
|
||||
// Cursor position
|
||||
// Cursor position.
|
||||
pos int
|
||||
|
||||
// Used to emulate a viewport when width is set and the content is
|
||||
// overflowing
|
||||
// overflowing.
|
||||
offset int
|
||||
offsetRight int
|
||||
|
||||
// Used to manage cursor blink
|
||||
blinkCtx *blinkCtx
|
||||
|
||||
// cursorMode determines the behavior of the cursor
|
||||
cursorMode CursorMode
|
||||
}
|
||||
|
||||
// NewModel creates a new model with default settings.
|
||||
func New() Model {
|
||||
return Model{
|
||||
Prompt: "> ",
|
||||
BlinkSpeed: defaultBlinkSpeed,
|
||||
EchoCharacter: '*',
|
||||
CharLimit: 0,
|
||||
PlaceholderStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
|
||||
|
||||
id: nextID(),
|
||||
value: nil,
|
||||
focus: false,
|
||||
blink: true,
|
||||
pos: 0,
|
||||
cursorMode: CursorBlink,
|
||||
|
||||
blinkCtx: &blinkCtx{
|
||||
ctx: context.Background(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// NewModel creates a new model with default settings.
|
||||
//
|
||||
// Deprecated. Use New instead.
|
||||
var NewModel = New
|
||||
|
||||
// SetValue sets the value of the text input.
|
||||
func (m *Model) SetValue(s string) {
|
||||
runes := []rune(s)
|
||||
@@ -73,8 +187,8 @@ func (m *Model) SetValue(s string) {
|
||||
} else {
|
||||
m.value = runes
|
||||
}
|
||||
if m.pos > len(m.value) {
|
||||
m.pos = len(m.value)
|
||||
if m.pos == 0 || m.pos > len(m.value) {
|
||||
m.setCursor(len(m.value))
|
||||
}
|
||||
m.handleOverflow()
|
||||
}
|
||||
@@ -84,23 +198,69 @@ func (m Model) Value() string {
|
||||
return string(m.value)
|
||||
}
|
||||
|
||||
// Cursor start 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.
|
||||
// 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.
|
||||
func (m *Model) SetCursor(pos int) {
|
||||
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.handleOverflow()
|
||||
|
||||
// Show the cursor unless it's been explicitly hidden
|
||||
m.blink = m.cursorMode == CursorHide
|
||||
|
||||
// Reset cursor blink if necessary
|
||||
return m.cursorMode == CursorBlink
|
||||
}
|
||||
|
||||
// CursorStart moves the cursor to the start of the field.
|
||||
// CursorStart moves the cursor to the start of the input field.
|
||||
func (m *Model) CursorStart() {
|
||||
m.pos = 0
|
||||
m.handleOverflow()
|
||||
m.cursorStart()
|
||||
}
|
||||
|
||||
// CursorEnd moves the cursor to the end of the field.
|
||||
// cursorStart moves the cursor to the start of the input field and returns
|
||||
// whether or not the curosr blink should be reset.
|
||||
func (m *Model) cursorStart() bool {
|
||||
return m.setCursor(0)
|
||||
}
|
||||
|
||||
// CursorEnd moves the cursor to the end of the input field
|
||||
func (m *Model) CursorEnd() {
|
||||
m.pos = len(m.value)
|
||||
m.handleOverflow()
|
||||
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.
|
||||
@@ -108,43 +268,50 @@ func (m Model) Focused() bool {
|
||||
return m.focus
|
||||
}
|
||||
|
||||
// Focus sets the focus state on the model.
|
||||
func (m *Model) Focus() {
|
||||
// Focus sets the focus state on the model. When the model is in focus it can
|
||||
// receive keyboard input and the cursor will be hidden.
|
||||
func (m *Model) Focus() tea.Cmd {
|
||||
m.focus = true
|
||||
m.blink = false
|
||||
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() {
|
||||
m.focus = false
|
||||
m.blink = true
|
||||
}
|
||||
|
||||
// Reset sets the input to its default state with no input.
|
||||
func (m *Model) Reset() {
|
||||
// Reset sets the input to its default state with no input. Returns whether
|
||||
// or not the cursor blink should reset.
|
||||
func (m *Model) Reset() bool {
|
||||
m.value = nil
|
||||
m.pos = 0
|
||||
m.blink = false
|
||||
return m.setCursor(0)
|
||||
}
|
||||
|
||||
// Paste pastes the contents of the clipboard into the text area (if supported).
|
||||
func (m *Model) Paste() {
|
||||
pasteString, err := clipboard.ReadAll()
|
||||
if err != nil {
|
||||
m.Err = err
|
||||
}
|
||||
paste := []rune(pasteString)
|
||||
// handle a clipboard paste event, if supported. Returns whether or not the
|
||||
// cursor blink should reset.
|
||||
func (m *Model) handlePaste(v string) bool {
|
||||
paste := []rune(v)
|
||||
|
||||
availSpace := m.CharLimit - len(m.value)
|
||||
var availSpace int
|
||||
if m.CharLimit > 0 {
|
||||
availSpace = m.CharLimit - len(m.value)
|
||||
}
|
||||
|
||||
// If the char limit's been reached cancel
|
||||
if m.CharLimit > 0 && availSpace <= 0 {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
// If there's not enough space to paste the whole thing cut the pasted
|
||||
// runes down so they'll fit
|
||||
if availSpace < len(paste) {
|
||||
if m.CharLimit > 0 && availSpace < len(paste) {
|
||||
paste = paste[:len(paste)-availSpace]
|
||||
}
|
||||
|
||||
@@ -157,15 +324,20 @@ func (m *Model) Paste() {
|
||||
// Insert pasted runes
|
||||
for _, r := range paste {
|
||||
head = append(head, r)
|
||||
availSpace--
|
||||
m.pos++
|
||||
if m.CharLimit > 0 && availSpace <= 0 {
|
||||
break
|
||||
if m.CharLimit > 0 {
|
||||
availSpace--
|
||||
if availSpace <= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Put it all back together
|
||||
m.value = append(head, tail...)
|
||||
|
||||
// Reset blink state if necessary and run overflow checks
|
||||
return m.setCursor(m.pos)
|
||||
}
|
||||
|
||||
// If a max width is defined, perform some logic to treat the visible area
|
||||
@@ -213,62 +385,156 @@ func (m *Model) handleOverflow() {
|
||||
}
|
||||
}
|
||||
|
||||
// colorText colorizes a given string according to the TextColor value of the
|
||||
// model.
|
||||
func (m *Model) colorText(s string) string {
|
||||
return termenv.
|
||||
String(s).
|
||||
Foreground(color(m.TextColor)).
|
||||
Background(color(m.BackgroundColor)).
|
||||
String()
|
||||
// deleteBeforeCursor deletes all text before the cursor. Returns whether or
|
||||
// not the cursor blink should be reset.
|
||||
func (m *Model) deleteBeforeCursor() bool {
|
||||
m.value = m.value[m.pos:]
|
||||
m.offset = 0
|
||||
return m.setCursor(0)
|
||||
}
|
||||
|
||||
// colorPlaceholder colorizes a given string according to the TextColor value
|
||||
// of the model.
|
||||
func (m *Model) colorPlaceholder(s string) string {
|
||||
return termenv.
|
||||
String(s).
|
||||
Foreground(color(m.PlaceholderColor)).
|
||||
Background(color(m.BackgroundColor)).
|
||||
String()
|
||||
// deleteAfterCursor deletes all text after the cursor. Returns whether or not
|
||||
// the cursor blink should be reset. If input is masked delete everything after
|
||||
// the cursor so as not to reveal word breaks in the masked input.
|
||||
func (m *Model) deleteAfterCursor() bool {
|
||||
m.value = m.value[:m.pos]
|
||||
return m.setCursor(len(m.value))
|
||||
}
|
||||
|
||||
func (m *Model) wordLeft() {
|
||||
// deleteWordLeft deletes the word left to the cursor. Returns whether or not
|
||||
// the cursor blink should be reset.
|
||||
func (m *Model) deleteWordLeft() bool {
|
||||
if m.pos == 0 || len(m.value) == 0 {
|
||||
return
|
||||
return false
|
||||
}
|
||||
|
||||
i := m.pos - 1
|
||||
|
||||
for i >= 0 {
|
||||
if unicode.IsSpace(m.value[i]) {
|
||||
m.pos--
|
||||
i--
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for i >= 0 {
|
||||
if !unicode.IsSpace(m.value[i]) {
|
||||
m.pos--
|
||||
i--
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) wordRight() {
|
||||
if m.pos >= len(m.value) || len(m.value) == 0 {
|
||||
return
|
||||
if m.EchoMode != EchoNormal {
|
||||
return m.deleteBeforeCursor()
|
||||
}
|
||||
|
||||
i := m.pos
|
||||
blink := m.setCursor(m.pos - 1)
|
||||
for unicode.IsSpace(m.value[m.pos]) {
|
||||
if m.pos <= 0 {
|
||||
break
|
||||
}
|
||||
// ignore series of whitespace before cursor
|
||||
blink = m.setCursor(m.pos - 1)
|
||||
}
|
||||
|
||||
for m.pos > 0 {
|
||||
if !unicode.IsSpace(m.value[m.pos]) {
|
||||
blink = m.setCursor(m.pos - 1)
|
||||
} else {
|
||||
if m.pos > 0 {
|
||||
// keep the previous space
|
||||
blink = m.setCursor(m.pos + 1)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if i > len(m.value) {
|
||||
m.value = m.value[:m.pos]
|
||||
} else {
|
||||
m.value = append(m.value[:m.pos], m.value[i:]...)
|
||||
}
|
||||
|
||||
return blink
|
||||
}
|
||||
|
||||
// deleteWordRight deletes the word right to the cursor. Returns whether or not
|
||||
// the cursor blink should be reset. If input is masked delete everything after
|
||||
// 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 {
|
||||
return false
|
||||
}
|
||||
|
||||
if m.EchoMode != EchoNormal {
|
||||
return m.deleteAfterCursor()
|
||||
}
|
||||
|
||||
i := m.pos
|
||||
m.setCursor(m.pos + 1)
|
||||
for unicode.IsSpace(m.value[m.pos]) {
|
||||
// ignore series of whitespace after cursor
|
||||
m.setCursor(m.pos + 1)
|
||||
|
||||
if m.pos >= len(m.value) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for m.pos < len(m.value) {
|
||||
if !unicode.IsSpace(m.value[m.pos]) {
|
||||
m.setCursor(m.pos + 1)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if m.pos > len(m.value) {
|
||||
m.value = m.value[:i]
|
||||
} else {
|
||||
m.value = append(m.value[:i], m.value[m.pos:]...)
|
||||
}
|
||||
|
||||
return m.setCursor(i)
|
||||
}
|
||||
|
||||
// wordLeft moves the cursor one word to the left. Returns whether or not the
|
||||
// cursor blink should be reset. If input is masked, move input to the start
|
||||
// so as not to reveal word breaks in the masked input.
|
||||
func (m *Model) wordLeft() bool {
|
||||
if m.pos == 0 || len(m.value) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if m.EchoMode != EchoNormal {
|
||||
return m.cursorStart()
|
||||
}
|
||||
|
||||
blink := false
|
||||
i := m.pos - 1
|
||||
for i >= 0 {
|
||||
if unicode.IsSpace(m.value[i]) {
|
||||
blink = m.setCursor(m.pos - 1)
|
||||
i--
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for i >= 0 {
|
||||
if !unicode.IsSpace(m.value[i]) {
|
||||
blink = m.setCursor(m.pos - 1)
|
||||
i--
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return blink
|
||||
}
|
||||
|
||||
// wordRight moves the cursor one word to the right. Returns whether or not the
|
||||
// cursor blink should be reset. If the input is masked, move input to the end
|
||||
// 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 {
|
||||
return false
|
||||
}
|
||||
|
||||
if m.EchoMode != EchoNormal {
|
||||
return m.cursorEnd()
|
||||
}
|
||||
|
||||
blink := false
|
||||
i := m.pos
|
||||
for i < len(m.value) {
|
||||
if unicode.IsSpace(m.value[i]) {
|
||||
m.pos++
|
||||
blink = m.setCursor(m.pos + 1)
|
||||
i++
|
||||
} else {
|
||||
break
|
||||
@@ -277,212 +543,256 @@ func (m *Model) wordRight() {
|
||||
|
||||
for i < len(m.value) {
|
||||
if !unicode.IsSpace(m.value[i]) {
|
||||
m.pos++
|
||||
blink = m.setCursor(m.pos + 1)
|
||||
i++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return blink
|
||||
}
|
||||
|
||||
// BlinkMsg is sent when the cursor should alternate it's blinking state.
|
||||
type BlinkMsg struct{}
|
||||
func (m Model) echoTransform(v string) string {
|
||||
switch m.EchoMode {
|
||||
case EchoPassword:
|
||||
return strings.Repeat(string(m.EchoCharacter), rw.StringWidth(v))
|
||||
case EchoNone:
|
||||
return ""
|
||||
|
||||
// NewModel creates a new model with default settings.
|
||||
func NewModel() Model {
|
||||
return Model{
|
||||
Prompt: "> ",
|
||||
BlinkSpeed: defaultBlinkSpeed,
|
||||
Placeholder: "",
|
||||
TextColor: "",
|
||||
PlaceholderColor: "240",
|
||||
CursorColor: "",
|
||||
CharLimit: 0,
|
||||
|
||||
value: nil,
|
||||
focus: false,
|
||||
blink: true,
|
||||
pos: 0,
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// Update is the Tea update loop.
|
||||
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
// Update is the Bubble Tea update loop.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
if !m.focus {
|
||||
m.blink = true
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var resetBlink bool
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.Type {
|
||||
case tea.KeyBackspace:
|
||||
fallthrough
|
||||
case tea.KeyDelete:
|
||||
if len(m.value) > 0 {
|
||||
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
|
||||
if m.pos > 0 {
|
||||
m.pos--
|
||||
case tea.KeyBackspace: // delete character before cursor
|
||||
if msg.Alt {
|
||||
resetBlink = m.deleteWordLeft()
|
||||
} else {
|
||||
if len(m.value) > 0 {
|
||||
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
|
||||
if m.pos > 0 {
|
||||
resetBlink = m.setCursor(m.pos - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
case tea.KeyLeft:
|
||||
case tea.KeyLeft, tea.KeyCtrlB:
|
||||
if msg.Alt { // alt+left arrow, back one word
|
||||
m.wordLeft()
|
||||
resetBlink = m.wordLeft()
|
||||
break
|
||||
}
|
||||
if m.pos > 0 {
|
||||
m.pos--
|
||||
if m.pos > 0 { // left arrow, ^F, back one character
|
||||
resetBlink = m.setCursor(m.pos - 1)
|
||||
}
|
||||
case tea.KeyRight:
|
||||
case tea.KeyRight, tea.KeyCtrlF:
|
||||
if msg.Alt { // alt+right arrow, forward one word
|
||||
m.wordRight()
|
||||
resetBlink = m.wordRight()
|
||||
break
|
||||
}
|
||||
if m.pos < len(m.value) {
|
||||
m.pos++
|
||||
if m.pos < len(m.value) { // right arrow, ^F, forward one character
|
||||
resetBlink = m.setCursor(m.pos + 1)
|
||||
}
|
||||
case tea.KeyCtrlF: // ^F, forward one character
|
||||
fallthrough
|
||||
case tea.KeyCtrlB: // ^B, back one charcter
|
||||
fallthrough
|
||||
case tea.KeyCtrlA: // ^A, go to beginning
|
||||
m.CursorStart()
|
||||
case tea.KeyCtrlD: // ^D, delete char under cursor
|
||||
case tea.KeyCtrlW: // ^W, delete word left of cursor
|
||||
resetBlink = m.deleteWordLeft()
|
||||
case tea.KeyHome, tea.KeyCtrlA: // ^A, go to beginning
|
||||
resetBlink = m.cursorStart()
|
||||
case tea.KeyDelete, tea.KeyCtrlD: // ^D, delete char under cursor
|
||||
if len(m.value) > 0 && m.pos < len(m.value) {
|
||||
m.value = append(m.value[:m.pos], m.value[m.pos+1:]...)
|
||||
}
|
||||
case tea.KeyCtrlE: // ^E, go to end
|
||||
m.CursorEnd()
|
||||
case tea.KeyCtrlE, tea.KeyEnd: // ^E, go to end
|
||||
resetBlink = m.cursorEnd()
|
||||
case tea.KeyCtrlK: // ^K, kill text after cursor
|
||||
m.value = m.value[:m.pos]
|
||||
m.pos = len(m.value)
|
||||
resetBlink = m.deleteAfterCursor()
|
||||
case tea.KeyCtrlU: // ^U, kill text before cursor
|
||||
m.value = m.value[m.pos:]
|
||||
m.pos = 0
|
||||
m.offset = 0
|
||||
resetBlink = m.deleteBeforeCursor()
|
||||
case tea.KeyCtrlV: // ^V paste
|
||||
m.Paste()
|
||||
case tea.KeyRune: // input a regular character
|
||||
|
||||
if msg.Alt {
|
||||
if msg.Rune == 'b' { // alt+b, back one word
|
||||
m.wordLeft()
|
||||
return m, Paste
|
||||
case tea.KeyRunes: // input regular characters
|
||||
if msg.Alt && len(msg.Runes) == 1 {
|
||||
if msg.Runes[0] == 'd' { // alt+d, delete word right of cursor
|
||||
resetBlink = m.deleteWordRight()
|
||||
break
|
||||
}
|
||||
if msg.Rune == 'f' { // alt+f, forward one word
|
||||
m.wordRight()
|
||||
if msg.Runes[0] == 'b' { // alt+b, back one word
|
||||
resetBlink = m.wordLeft()
|
||||
break
|
||||
}
|
||||
if msg.Runes[0] == 'f' { // alt+f, forward one word
|
||||
resetBlink = m.wordRight()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Input a regular character
|
||||
if m.CharLimit <= 0 || len(m.value) < m.CharLimit {
|
||||
m.value = append(m.value[:m.pos], append([]rune{msg.Rune}, m.value[m.pos:]...)...)
|
||||
m.pos++
|
||||
m.value = append(m.value[:m.pos], append(msg.Runes, m.value[m.pos:]...)...)
|
||||
resetBlink = m.setCursor(m.pos + len(msg.Runes))
|
||||
}
|
||||
}
|
||||
|
||||
case ErrMsg:
|
||||
m.Err = msg
|
||||
case initialBlinkMsg:
|
||||
// We accept all initialBlinkMsgs genrated by the Blink command.
|
||||
|
||||
case BlinkMsg:
|
||||
m.blink = !m.blink
|
||||
return m, Blink(m)
|
||||
if m.cursorMode != CursorBlink || !m.focus {
|
||||
return m, nil
|
||||
}
|
||||
|
||||
cmd := m.blinkCmd()
|
||||
return m, cmd
|
||||
|
||||
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
|
||||
if m.cursorMode == CursorBlink {
|
||||
m.blink = !m.blink
|
||||
cmd = m.blinkCmd()
|
||||
}
|
||||
return m, cmd
|
||||
|
||||
case blinkCanceled: // no-op
|
||||
return m, nil
|
||||
|
||||
case pasteMsg:
|
||||
resetBlink = m.handlePaste(string(msg))
|
||||
|
||||
case pasteErrMsg:
|
||||
m.Err = msg
|
||||
}
|
||||
|
||||
var cmd tea.Cmd
|
||||
if resetBlink {
|
||||
cmd = m.blinkCmd()
|
||||
}
|
||||
|
||||
m.handleOverflow()
|
||||
|
||||
return m, nil
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// View renders the textinput in its current state.
|
||||
func View(model tea.Model) string {
|
||||
m, ok := model.(Model)
|
||||
if !ok {
|
||||
return "could not perform assertion on model"
|
||||
}
|
||||
|
||||
func (m Model) View() string {
|
||||
// Placeholder text
|
||||
if len(m.value) == 0 && m.Placeholder != "" {
|
||||
return placeholderView(m)
|
||||
return m.placeholderView()
|
||||
}
|
||||
|
||||
styleText := m.TextStyle.Inline(true).Render
|
||||
|
||||
value := m.value[m.offset:m.offsetRight]
|
||||
pos := max(0, m.pos-m.offset)
|
||||
|
||||
v := m.colorText(string(value[:pos]))
|
||||
v := styleText(m.echoTransform(string(value[:pos])))
|
||||
|
||||
if pos < len(value) {
|
||||
v += cursorView(string(value[pos]), m) // cursor and text under it
|
||||
v += m.colorText(string(value[pos+1:])) // text after cursor
|
||||
v += m.cursorView(m.echoTransform(string(value[pos]))) // cursor and text under it
|
||||
v += styleText(m.echoTransform(string(value[pos+1:]))) // text after cursor
|
||||
} else {
|
||||
v += cursorView(" ", m)
|
||||
v += m.cursorView(" ")
|
||||
}
|
||||
|
||||
// If a max width and background color were set fill the empty spaces with
|
||||
// the background color.
|
||||
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)
|
||||
if valWidth+padding <= m.Width && pos < len(value) {
|
||||
padding++
|
||||
}
|
||||
v += strings.Repeat(
|
||||
termenv.String(" ").Background(color(m.BackgroundColor)).String(),
|
||||
padding,
|
||||
)
|
||||
v += styleText(strings.Repeat(" ", padding))
|
||||
}
|
||||
|
||||
return m.Prompt + v
|
||||
return m.PromptStyle.Render(m.Prompt) + v
|
||||
}
|
||||
|
||||
// placeholderView.
|
||||
func placeholderView(m Model) string {
|
||||
// placeholderView returns the prompt and placeholder view, if any.
|
||||
func (m Model) placeholderView() string {
|
||||
var (
|
||||
v string
|
||||
p = m.Placeholder
|
||||
v string
|
||||
p = m.Placeholder
|
||||
style = m.PlaceholderStyle.Inline(true).Render
|
||||
)
|
||||
|
||||
// Cursor
|
||||
if m.blink && m.PlaceholderColor != "" {
|
||||
v += cursorView(
|
||||
m.colorPlaceholder(p[:1]),
|
||||
m,
|
||||
)
|
||||
if m.blink {
|
||||
v += m.cursorView(style(p[:1]))
|
||||
} else {
|
||||
v += cursorView(p[:1], m)
|
||||
v += m.cursorView(p[:1])
|
||||
}
|
||||
|
||||
// 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.
|
||||
func cursorView(s string, m Model) string {
|
||||
func (m Model) cursorView(v string) string {
|
||||
if m.blink {
|
||||
if m.TextColor != "" || m.BackgroundColor != "" {
|
||||
return termenv.String(s).
|
||||
Foreground(color(m.TextColor)).
|
||||
Background(color(m.BackgroundColor)).
|
||||
String()
|
||||
}
|
||||
return s
|
||||
return m.TextStyle.Render(v)
|
||||
}
|
||||
return termenv.String(s).
|
||||
Foreground(color(m.CursorColor)).
|
||||
Background(color(m.BackgroundColor)).
|
||||
Reverse().
|
||||
String()
|
||||
return m.CursorStyle.Inline(true).Reverse(true).Render(v)
|
||||
}
|
||||
|
||||
// Blink is a command used to time the cursor blinking.
|
||||
func Blink(model Model) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
time.Sleep(model.BlinkSpeed)
|
||||
return BlinkMsg{}
|
||||
// blinkCmd is an internal command used to manage cursor blinking.
|
||||
func (m *Model) blinkCmd() tea.Cmd {
|
||||
if m.cursorMode != CursorBlink {
|
||||
return nil
|
||||
}
|
||||
|
||||
if m.blinkCtx != nil && m.blinkCtx.cancel != nil {
|
||||
m.blinkCtx.cancel()
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(m.blinkCtx.ctx, m.BlinkSpeed)
|
||||
m.blinkCtx.cancel = cancel
|
||||
|
||||
m.blinkTag++
|
||||
|
||||
return func() tea.Msg {
|
||||
defer cancel()
|
||||
<-ctx.Done()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return blinkMsg{id: m.id, tag: m.blinkTag}
|
||||
}
|
||||
return blinkCanceled{}
|
||||
}
|
||||
}
|
||||
|
||||
// Blink is a command used to initialize cursor blinking.
|
||||
func Blink() tea.Msg {
|
||||
return initialBlinkMsg{}
|
||||
}
|
||||
|
||||
// Paste is a command for pasting from the clipboard into the text input.
|
||||
func Paste() tea.Msg {
|
||||
str, err := clipboard.ReadAll()
|
||||
if err != nil {
|
||||
return pasteErrMsg{err}
|
||||
}
|
||||
return pasteMsg(str)
|
||||
}
|
||||
|
||||
func clamp(v, low, high int) int {
|
||||
|
194
timer/timer.go
Normal file
194
timer/timer.go
Normal file
@@ -0,0 +1,194 @@
|
||||
// Package timer provides a simple timeout component.
|
||||
package timer
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
)
|
||||
|
||||
var (
|
||||
lastID int
|
||||
idMtx sync.Mutex
|
||||
)
|
||||
|
||||
func nextID() int {
|
||||
idMtx.Lock()
|
||||
defer idMtx.Unlock()
|
||||
lastID++
|
||||
return lastID
|
||||
}
|
||||
|
||||
// Authors note with regard to start and stop commands:
|
||||
//
|
||||
// Technically speaking, sending commands to start and stop the timer in this
|
||||
// case is extraneous. To stop the timer we'd just need to set the 'running'
|
||||
// property on the model to false which cause logic in the update function to
|
||||
// stop responding to TickMsgs. To start the model we'd set 'running' to true
|
||||
// and fire off a TickMsg. Helper functions would look like:
|
||||
//
|
||||
// func (m *model) Start() tea.Cmd
|
||||
// func (m *model) Stop()
|
||||
//
|
||||
// The danger with this approach, however, is that order of operations becomes
|
||||
// important with helper functions like the above. Consider the following:
|
||||
//
|
||||
// // Would not work
|
||||
// return m, m.timer.Start()
|
||||
//
|
||||
// // Would work
|
||||
// cmd := m.timer.start()
|
||||
// return m, cmd
|
||||
//
|
||||
// Thus, because of potential pitfalls like the ones above, we've introduced
|
||||
// the extraneous StartStopMsg to simplify the mental model when using this
|
||||
// package. Bear in mind that the practice of sending commands to simply
|
||||
// communicate with other parts of your application, such as in this package,
|
||||
// is still not recommended.
|
||||
|
||||
// StartStopMsg is used to start and stop the timer.
|
||||
type StartStopMsg struct {
|
||||
ID int
|
||||
running bool
|
||||
}
|
||||
|
||||
// TickMsg is a message that is sent on every timer tick.
|
||||
type TickMsg struct {
|
||||
// ID is the identifier of the stopwatch that send the message. This makes
|
||||
// it possible to determine which timer a tick belongs to when there
|
||||
// are multiple timers running.
|
||||
//
|
||||
// Note, however, that a timer will reject ticks from other stopwatches, so
|
||||
// it's safe to flow all TickMsgs through all timers and have them still
|
||||
// behave appropriately.
|
||||
ID int
|
||||
|
||||
// Timeout returns whether or not this tick is a timeout tick. You can
|
||||
// alternatively listen for TimeoutMsg.
|
||||
Timeout bool
|
||||
}
|
||||
|
||||
// TimeoutMsg is a message that is sent once when the timer times out.
|
||||
//
|
||||
// It's a convenience message sent alongside a TickMsg with the Timeout value
|
||||
// set to true.
|
||||
type TimeoutMsg struct {
|
||||
ID int
|
||||
}
|
||||
|
||||
// Model of the timer component.
|
||||
type Model struct {
|
||||
// How long until the timer expires.
|
||||
Timeout time.Duration
|
||||
|
||||
// How long to wait before every tick. Defaults to 1 second.
|
||||
Interval time.Duration
|
||||
|
||||
id int
|
||||
running bool
|
||||
}
|
||||
|
||||
// NewWithInterval creates a new timer with the given timeout and tick interval.
|
||||
func NewWithInterval(timeout, interval time.Duration) Model {
|
||||
return Model{
|
||||
Timeout: timeout,
|
||||
Interval: interval,
|
||||
running: true,
|
||||
id: nextID(),
|
||||
}
|
||||
}
|
||||
|
||||
// New creates a new timer with the given timeout and default 1s interval.
|
||||
func New(timeout time.Duration) Model {
|
||||
return NewWithInterval(timeout, time.Second)
|
||||
}
|
||||
|
||||
// ID returns the model's identifier. This can be used to determine if messages
|
||||
// belong to this timer instance when there are multiple timers.
|
||||
func (m Model) ID() int {
|
||||
return m.id
|
||||
}
|
||||
|
||||
// Running returns whether or not the timer is running. If the timer has timed
|
||||
// out this will always return false.
|
||||
func (m Model) Running() bool {
|
||||
if m.Timedout() || !m.running {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Timedout returns whether or not the timer has timed out.
|
||||
func (m Model) Timedout() bool {
|
||||
return m.Timeout <= 0
|
||||
}
|
||||
|
||||
// Init starts the timer.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return m.tick()
|
||||
}
|
||||
|
||||
// Update handles the timer tick.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case StartStopMsg:
|
||||
if msg.ID != 0 && msg.ID != m.id {
|
||||
return m, nil
|
||||
}
|
||||
m.running = msg.running
|
||||
return m, m.tick()
|
||||
case TickMsg:
|
||||
if !m.Running() || (msg.ID != 0 && msg.ID != m.id) {
|
||||
break
|
||||
}
|
||||
|
||||
m.Timeout -= m.Interval
|
||||
return m, tea.Batch(m.tick(), m.timedout())
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// View of the timer component.
|
||||
func (m Model) View() string {
|
||||
return m.Timeout.String()
|
||||
}
|
||||
|
||||
// Start resumes the timer. Has no effect if the timer has timed out.
|
||||
func (m *Model) Start() tea.Cmd {
|
||||
return m.startStop(true)
|
||||
}
|
||||
|
||||
// Stop pauses the timer. Has no effect if the timer has timed out.
|
||||
func (m *Model) Stop() tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return m.startStop(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle stops the timer if it's running and starts it if it's stopped.
|
||||
func (m *Model) Toggle() tea.Cmd {
|
||||
return m.startStop(!m.Running())
|
||||
}
|
||||
|
||||
func (m Model) tick() tea.Cmd {
|
||||
return tea.Tick(m.Interval, func(_ time.Time) tea.Msg {
|
||||
return TickMsg{ID: m.id, Timeout: m.Timedout()}
|
||||
})
|
||||
}
|
||||
|
||||
func (m Model) timedout() tea.Cmd {
|
||||
if !m.Timedout() {
|
||||
return nil
|
||||
}
|
||||
return func() tea.Msg {
|
||||
return TimeoutMsg{ID: m.id}
|
||||
}
|
||||
}
|
||||
|
||||
func (m Model) startStop(v bool) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
return StartStopMsg{ID: m.id, running: v}
|
||||
}
|
||||
}
|
42
viewport/keymap.go
Normal file
42
viewport/keymap.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package viewport
|
||||
|
||||
import "github.com/charmbracelet/bubbles/key"
|
||||
|
||||
const spacebar = " "
|
||||
|
||||
// KeyMap defines the keybindings for the viewport. Note that you don't
|
||||
// necessary need to use keybindings at all; the viewport can be controlled
|
||||
// programmatically with methods like Model.LineDown(1). See the GoDocs for
|
||||
// details.
|
||||
type KeyMap struct {
|
||||
PageDown key.Binding
|
||||
PageUp key.Binding
|
||||
HalfPageUp key.Binding
|
||||
HalfPageDown key.Binding
|
||||
Down key.Binding
|
||||
Up key.Binding
|
||||
}
|
||||
|
||||
// DefaultKeyMap returns a set of pager-like default keybindings.
|
||||
func DefaultKeyMap() KeyMap {
|
||||
return KeyMap{
|
||||
PageDown: key.NewBinding(
|
||||
key.WithKeys("pgdown", spacebar, "f"),
|
||||
),
|
||||
PageUp: key.NewBinding(
|
||||
key.WithKeys("pgup", "b"),
|
||||
),
|
||||
HalfPageUp: key.NewBinding(
|
||||
key.WithKeys("u", "ctrl+u"),
|
||||
),
|
||||
HalfPageDown: key.NewBinding(
|
||||
key.WithKeys("d", "ctrl+d"),
|
||||
),
|
||||
Up: key.NewBinding(
|
||||
key.WithKeys("up", "k"),
|
||||
),
|
||||
Down: key.NewBinding(
|
||||
key.WithKeys("down", "j"),
|
||||
),
|
||||
}
|
||||
}
|
@@ -4,26 +4,44 @@ import (
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/bubbles/key"
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
const (
|
||||
spacebar = " "
|
||||
)
|
||||
|
||||
// MODEL
|
||||
// New returns a new model with the given width and height as well as default
|
||||
// keymappings.
|
||||
func New(width, height int) (m Model) {
|
||||
m.Width = width
|
||||
m.Height = height
|
||||
m.setInitialValues()
|
||||
return m
|
||||
}
|
||||
|
||||
// Model is the Bubble Tea model for this viewport element.
|
||||
type Model struct {
|
||||
Width int
|
||||
Height int
|
||||
KeyMap KeyMap
|
||||
|
||||
// Whether or not to respond to the mouse. The mouse must be enabled in
|
||||
// Bubble Tea for this to work. For details, see the Bubble Tea docs.
|
||||
MouseWheelEnabled bool
|
||||
|
||||
// The number of lines the mouse wheel will scroll. By default, this is 3.
|
||||
MouseWheelDelta int
|
||||
|
||||
// YOffset is the vertical scroll position.
|
||||
YOffset int
|
||||
|
||||
// YPosition is the position of the viewport in relation to the terminal
|
||||
// window. It's used in high performance rendering.
|
||||
// window. It's used in high performance rendering only.
|
||||
YPosition int
|
||||
|
||||
// Style applies a lipgloss style to the viewport. Realistically, it's most
|
||||
// useful for setting borders, margins and padding.
|
||||
Style lipgloss.Style
|
||||
|
||||
// HighPerformanceRendering bypasses the normal Bubble Tea renderer to
|
||||
// provide higher performance rendering. Most of the time the normal Bubble
|
||||
// Tea rendering methods will suffice, but if you're passing content with
|
||||
@@ -34,7 +52,20 @@ type Model struct {
|
||||
// which is usually via the alternate screen buffer.
|
||||
HighPerformanceRendering bool
|
||||
|
||||
lines []string
|
||||
initialized bool
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (m *Model) setInitialValues() {
|
||||
m.KeyMap = DefaultKeyMap()
|
||||
m.MouseWheelEnabled = true
|
||||
m.MouseWheelDelta = 3
|
||||
m.initialized = true
|
||||
}
|
||||
|
||||
// Init exists to satisfy the tea.Model interface for composability purposes.
|
||||
func (m Model) Init() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
// AtTop returns whether or not the viewport is in the very top position.
|
||||
@@ -45,16 +76,16 @@ func (m Model) AtTop() bool {
|
||||
// AtBottom returns whether or not the viewport is at or past the very bottom
|
||||
// position.
|
||||
func (m Model) AtBottom() bool {
|
||||
return m.YOffset >= len(m.lines)-1-m.Height
|
||||
return m.YOffset >= len(m.lines)-m.Height
|
||||
}
|
||||
|
||||
// PastBottom returns whether or not the viewport is scrolled beyond the last
|
||||
// line. This can happen when adjusting the viewport height.
|
||||
func (m Model) PastBottom() bool {
|
||||
return m.YOffset > len(m.lines)-1-m.Height
|
||||
return m.YOffset > len(m.lines)-m.Height
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if m.Height >= len(m.lines) {
|
||||
return 1.0
|
||||
@@ -69,20 +100,40 @@ func (m Model) ScrollPercent() float64 {
|
||||
// SetContent set the pager's text content. For high performance rendering the
|
||||
// Sync command should also be called.
|
||||
func (m *Model) SetContent(s string) {
|
||||
s = strings.Replace(s, "\r\n", "\n", -1) // normalize line endings
|
||||
s = strings.ReplaceAll(s, "\r\n", "\n") // normalize line endings
|
||||
m.lines = strings.Split(s, "\n")
|
||||
|
||||
if m.YOffset > len(m.lines)-1 {
|
||||
m.GotoBottom()
|
||||
}
|
||||
}
|
||||
|
||||
// Return the lines that should currently be visible in the viewport.
|
||||
// visibleLines returns the lines that should currently be visible in the
|
||||
// viewport.
|
||||
func (m Model) visibleLines() (lines []string) {
|
||||
if len(m.lines) > 0 {
|
||||
top := max(0, m.YOffset)
|
||||
bottom := min(len(m.lines), m.YOffset+m.Height)
|
||||
bottom := clamp(m.YOffset+m.Height, top, len(m.lines))
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
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, len(m.lines)-m.Height)
|
||||
}
|
||||
|
||||
// ViewDown moves the view down by the number of lines in the viewport.
|
||||
// Basically, "page down".
|
||||
func (m *Model) ViewDown() []string {
|
||||
@@ -90,11 +141,7 @@ func (m *Model) ViewDown() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = min(
|
||||
m.YOffset+m.Height, // target
|
||||
len(m.lines)-1-m.Height, // fallback
|
||||
)
|
||||
|
||||
m.SetYOffset(m.YOffset + m.Height)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
@@ -104,11 +151,7 @@ func (m *Model) ViewUp() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = max(
|
||||
m.YOffset-m.Height, // target
|
||||
0, // fallback
|
||||
)
|
||||
|
||||
m.SetYOffset(m.YOffset - m.Height)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
@@ -118,18 +161,8 @@ func (m *Model) HalfViewDown() (lines []string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = min(
|
||||
m.YOffset+m.Height/2, // target
|
||||
len(m.lines)-1-m.Height, // fallback
|
||||
)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(m.YOffset+m.Height/2, 0)
|
||||
bottom := min(m.YOffset+m.Height, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset + m.Height/2)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// HalfViewUp moves the view up by half the height of the viewport.
|
||||
@@ -138,18 +171,8 @@ func (m *Model) HalfViewUp() (lines []string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = max(
|
||||
m.YOffset-m.Height/2, // target
|
||||
0, // fallback
|
||||
)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(m.YOffset, 0)
|
||||
bottom := min(m.YOffset+m.Height/2, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset - m.Height/2)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// LineDown moves the view down by the given number of lines.
|
||||
@@ -161,21 +184,8 @@ func (m *Model) LineDown(n int) (lines []string) {
|
||||
// Make sure the number of lines by which we're going to scroll isn't
|
||||
// greater than the number of lines we actually have left before we reach
|
||||
// the bottom.
|
||||
maxDelta := (len(m.lines) - 1) - (m.YOffset + m.Height) // number of lines - viewport bottom edge
|
||||
n = min(n, maxDelta)
|
||||
|
||||
m.YOffset = min(
|
||||
m.YOffset+n, // target
|
||||
len(m.lines)-1-m.Height, // fallback
|
||||
)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(m.YOffset+m.Height-n, 0)
|
||||
bottom := min(m.YOffset+m.Height, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset + n)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// LineUp moves the view down by the given number of lines. Returns the new
|
||||
@@ -187,17 +197,8 @@ func (m *Model) LineUp(n int) (lines []string) {
|
||||
|
||||
// Make sure the number of lines by which we're going to scroll isn't
|
||||
// greater than the number of lines we are from the top.
|
||||
n = min(n, m.YOffset)
|
||||
|
||||
m.YOffset = max(m.YOffset-n, 0)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := max(0, m.YOffset)
|
||||
bottom := min(m.YOffset+n, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(m.YOffset - n)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// GotoTop sets the viewport to the top position.
|
||||
@@ -206,28 +207,14 @@ func (m *Model) GotoTop() (lines []string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.YOffset = 0
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := m.YOffset
|
||||
bottom := min(m.YOffset+m.Height, len(m.lines)-1)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(0)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// GotoTop sets the viewport to the bottom position.
|
||||
// GotoBottom sets the viewport to the bottom position.
|
||||
func (m *Model) GotoBottom() (lines []string) {
|
||||
m.YOffset = max(len(m.lines)-1-m.Height, 0)
|
||||
|
||||
if len(m.lines) > 0 {
|
||||
top := m.YOffset
|
||||
bottom := max(len(m.lines)-1, 0)
|
||||
lines = m.lines[top:bottom]
|
||||
}
|
||||
|
||||
return lines
|
||||
m.SetYOffset(len(m.lines) - 1 - m.Height)
|
||||
return m.visibleLines()
|
||||
}
|
||||
|
||||
// COMMANDS
|
||||
@@ -241,17 +228,8 @@ func Sync(m Model) tea.Cmd {
|
||||
if len(m.lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO: we should probably use m.visibleLines() rather than these two
|
||||
// expressions.
|
||||
top := max(m.YOffset, 0)
|
||||
bottom := min(m.YOffset+m.Height, len(m.lines)-1)
|
||||
|
||||
return tea.SyncScrollArea(
|
||||
m.lines[top:bottom],
|
||||
m.YPosition,
|
||||
m.YPosition+m.Height,
|
||||
)
|
||||
top, bottom := m.scrollArea()
|
||||
return tea.SyncScrollArea(m.visibleLines(), top, bottom)
|
||||
}
|
||||
|
||||
// ViewDown is a high performance command that moves the viewport up by a given
|
||||
@@ -265,67 +243,71 @@ func ViewDown(m Model, lines []string) tea.Cmd {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tea.ScrollDown(lines, m.YPosition, m.YPosition+m.Height)
|
||||
top, bottom := m.scrollArea()
|
||||
return tea.ScrollDown(lines, top, bottom)
|
||||
}
|
||||
|
||||
// ViewUp is a high performance command the moves the viewport down by a given
|
||||
// number of lines height. Use Model.ViewDown to get the lines that should be
|
||||
// number of lines height. Use Model.ViewUp to get the lines that should be
|
||||
// rendered.
|
||||
func ViewUp(m Model, lines []string) tea.Cmd {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tea.ScrollUp(lines, m.YPosition, m.YPosition+m.Height)
|
||||
top, bottom := m.scrollArea()
|
||||
return tea.ScrollUp(lines, top, bottom)
|
||||
}
|
||||
|
||||
// UPDATE
|
||||
// Update handles standard message-based viewport updates.
|
||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
||||
var cmd tea.Cmd
|
||||
m, cmd = m.updateAsModel(msg)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// Author's note: this method has been broken out to make it easier to
|
||||
// potentially transition Update to satisfy tea.Model.
|
||||
func (m Model) updateAsModel(msg tea.Msg) (Model, tea.Cmd) {
|
||||
if !m.initialized {
|
||||
m.setInitialValues()
|
||||
}
|
||||
|
||||
// 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 Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
var cmd tea.Cmd
|
||||
|
||||
switch msg := msg.(type) {
|
||||
case tea.KeyMsg:
|
||||
switch msg.String() {
|
||||
// Down one page
|
||||
case "pgdown", spacebar, "f":
|
||||
switch {
|
||||
case key.Matches(msg, m.KeyMap.PageDown):
|
||||
lines := m.ViewDown()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
|
||||
// Up one page
|
||||
case "pgup", "b":
|
||||
case key.Matches(msg, m.KeyMap.PageUp):
|
||||
lines := m.ViewUp()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
}
|
||||
|
||||
// Down half page
|
||||
case "d":
|
||||
case key.Matches(msg, m.KeyMap.HalfPageDown):
|
||||
lines := m.HalfViewDown()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
|
||||
// Up half page
|
||||
case "u":
|
||||
case key.Matches(msg, m.KeyMap.HalfPageUp):
|
||||
lines := m.HalfViewUp()
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
}
|
||||
|
||||
// Down one line
|
||||
case "down", "j":
|
||||
case key.Matches(msg, m.KeyMap.Down):
|
||||
lines := m.LineDown(1)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
|
||||
// Up one line
|
||||
case "up", "k":
|
||||
case key.Matches(msg, m.KeyMap.Up):
|
||||
lines := m.LineUp(1)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
@@ -333,15 +315,18 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
}
|
||||
|
||||
case tea.MouseMsg:
|
||||
switch msg.Button {
|
||||
if !m.MouseWheelEnabled {
|
||||
break
|
||||
}
|
||||
switch msg.Type {
|
||||
case tea.MouseWheelUp:
|
||||
lines := m.LineUp(3)
|
||||
lines := m.LineUp(m.MouseWheelDelta)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewUp(m, lines)
|
||||
}
|
||||
|
||||
case tea.MouseWheelDown:
|
||||
lines := m.LineDown(3)
|
||||
lines := m.LineDown(m.MouseWheelDelta)
|
||||
if m.HighPerformanceRendering {
|
||||
cmd = ViewDown(m, lines)
|
||||
}
|
||||
@@ -351,13 +336,11 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
// VIEW
|
||||
|
||||
// View renders the viewport into a string.
|
||||
func View(m Model) string {
|
||||
func (m Model) View() string {
|
||||
if m.HighPerformanceRendering {
|
||||
// Just send newlines since we're doing to be rendering the actual
|
||||
// content seprately. We still need send something that equals the
|
||||
// Just send newlines since we're going to be rendering the actual
|
||||
// content seprately. We still need to send something that equals the
|
||||
// height of this view so that the Bubble Tea standard renderer can
|
||||
// position anything below this view properly.
|
||||
return strings.Repeat("\n", m.Height-1)
|
||||
@@ -368,14 +351,18 @@ func View(m Model) string {
|
||||
// Fill empty space with newlines
|
||||
extraLines := ""
|
||||
if len(lines) < m.Height {
|
||||
extraLines = strings.Repeat("\n", m.Height-len(lines))
|
||||
extraLines = strings.Repeat("\n", max(0, m.Height-len(lines)))
|
||||
}
|
||||
|
||||
return strings.Join(lines, "\n") + extraLines
|
||||
return m.Style.Render(strings.Join(lines, "\n") + extraLines)
|
||||
}
|
||||
|
||||
// ETC
|
||||
|
||||
func clamp(v, low, high int) int {
|
||||
return min(high, max(low, v))
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
@@ -389,7 +376,3 @@ func max(a, b int) int {
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func clamp(val, low, high int) int {
|
||||
return max(low, min(high, val))
|
||||
}
|
||||
|
Reference in New Issue
Block a user