mirror of
https://github.com/Maks1mS/bubbles.git
synced 2025-04-22 06:13:43 +03:00
Compare commits
No commits in common. "master" and "v0.1.0" have entirely different histories.
22
.github/dependabot.yml
vendored
22
.github/dependabot.yml
vendored
@ -1,22 +0,0 @@
|
|||||||
version: 2
|
|
||||||
updates:
|
|
||||||
- package-ecosystem: "gomod"
|
|
||||||
directory: "/"
|
|
||||||
schedule:
|
|
||||||
interval: "daily"
|
|
||||||
time: "08:00"
|
|
||||||
labels:
|
|
||||||
- "dependencies"
|
|
||||||
commit-message:
|
|
||||||
prefix: "feat"
|
|
||||||
include: "scope"
|
|
||||||
- package-ecosystem: "github-actions"
|
|
||||||
directory: "/"
|
|
||||||
schedule:
|
|
||||||
interval: "daily"
|
|
||||||
time: "08:00"
|
|
||||||
labels:
|
|
||||||
- "dependencies"
|
|
||||||
commit-message:
|
|
||||||
prefix: "chore"
|
|
||||||
include: "scope"
|
|
28
.github/workflows/build.yml
vendored
28
.github/workflows/build.yml
vendored
@ -1,28 +0,0 @@
|
|||||||
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@v3
|
|
||||||
with:
|
|
||||||
go-version: ${{ matrix.go-version }}
|
|
||||||
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- 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
28
.github/workflows/coverage.yml
vendored
@ -1,28 +0,0 @@
|
|||||||
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@v3
|
|
||||||
with:
|
|
||||||
go-version: ${{ matrix.go-version }}
|
|
||||||
|
|
||||||
- name: Checkout code
|
|
||||||
uses: actions/checkout@v3
|
|
||||||
|
|
||||||
- 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
|
|
28
.github/workflows/lint-soft.yml
vendored
28
.github/workflows/lint-soft.yml
vendored
@ -1,28 +0,0 @@
|
|||||||
name: lint-soft
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
# Optional: allow read access to pull request. Use with `only-new-issues` option.
|
|
||||||
pull-requests: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
golangci:
|
|
||||||
name: lint-soft
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Install Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: ^1
|
|
||||||
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- name: golangci-lint
|
|
||||||
uses: golangci/golangci-lint-action@v3
|
|
||||||
with:
|
|
||||||
# Optional: golangci-lint command line arguments.
|
|
||||||
args: --config .golangci-soft.yml --issues-exit-code=0
|
|
||||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
|
||||||
only-new-issues: true
|
|
28
.github/workflows/lint.yml
vendored
28
.github/workflows/lint.yml
vendored
@ -1,28 +0,0 @@
|
|||||||
name: lint
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
# Optional: allow read access to pull request. Use with `only-new-issues` option.
|
|
||||||
pull-requests: read
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
golangci:
|
|
||||||
name: lint
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Install Go
|
|
||||||
uses: actions/setup-go@v3
|
|
||||||
with:
|
|
||||||
go-version: ^1
|
|
||||||
|
|
||||||
- uses: actions/checkout@v3
|
|
||||||
- name: golangci-lint
|
|
||||||
uses: golangci/golangci-lint-action@v3
|
|
||||||
with:
|
|
||||||
# Optional: golangci-lint command line arguments.
|
|
||||||
#args:
|
|
||||||
# Optional: show only new issues if it's a pull request. The default value is `false`.
|
|
||||||
only-new-issues: true
|
|
12
.github/workflows/soft-serve.yml
vendored
12
.github/workflows/soft-serve.yml
vendored
@ -1,12 +0,0 @@
|
|||||||
name: soft-serve
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
soft-serve:
|
|
||||||
uses: charmbracelet/meta/.github/workflows/soft-serve.yml@main
|
|
||||||
secrets:
|
|
||||||
ssh-key: "${{ secrets.CHARM_SOFT_SERVE_KEY }}"
|
|
@ -1,47 +0,0 @@
|
|||||||
run:
|
|
||||||
tests: false
|
|
||||||
|
|
||||||
issues:
|
|
||||||
include:
|
|
||||||
- EXC0001
|
|
||||||
- EXC0005
|
|
||||||
- EXC0011
|
|
||||||
- EXC0012
|
|
||||||
- EXC0013
|
|
||||||
|
|
||||||
max-issues-per-linter: 0
|
|
||||||
max-same-issues: 0
|
|
||||||
|
|
||||||
linters:
|
|
||||||
enable:
|
|
||||||
# - dupl
|
|
||||||
- exhaustive
|
|
||||||
# - exhaustivestruct
|
|
||||||
- goconst
|
|
||||||
- godot
|
|
||||||
- godox
|
|
||||||
- gomnd
|
|
||||||
- gomoddirectives
|
|
||||||
- goprintffuncname
|
|
||||||
- ifshort
|
|
||||||
# - lll
|
|
||||||
- misspell
|
|
||||||
- nakedret
|
|
||||||
- nestif
|
|
||||||
- noctx
|
|
||||||
- nolintlint
|
|
||||||
- prealloc
|
|
||||||
- wrapcheck
|
|
||||||
|
|
||||||
# disable default linters, they are already enabled in .golangci.yml
|
|
||||||
disable:
|
|
||||||
- deadcode
|
|
||||||
- errcheck
|
|
||||||
- gosimple
|
|
||||||
- govet
|
|
||||||
- ineffassign
|
|
||||||
- staticcheck
|
|
||||||
- structcheck
|
|
||||||
- typecheck
|
|
||||||
- unused
|
|
||||||
- varcheck
|
|
@ -1,29 +0,0 @@
|
|||||||
run:
|
|
||||||
tests: false
|
|
||||||
|
|
||||||
issues:
|
|
||||||
include:
|
|
||||||
- EXC0001
|
|
||||||
- EXC0005
|
|
||||||
- EXC0011
|
|
||||||
- EXC0012
|
|
||||||
- EXC0013
|
|
||||||
|
|
||||||
max-issues-per-linter: 0
|
|
||||||
max-same-issues: 0
|
|
||||||
|
|
||||||
linters:
|
|
||||||
enable:
|
|
||||||
- bodyclose
|
|
||||||
- exportloopref
|
|
||||||
- goimports
|
|
||||||
- gosec
|
|
||||||
- nilerr
|
|
||||||
- predeclared
|
|
||||||
- revive
|
|
||||||
- rowserrcheck
|
|
||||||
- sqlclosecheck
|
|
||||||
- tparallel
|
|
||||||
- unconvert
|
|
||||||
- unparam
|
|
||||||
- whitespace
|
|
237
README.md
237
README.md
@ -1,238 +1,9 @@
|
|||||||
Bubbles
|
# Tea Party
|
||||||
=======
|
|
||||||
|
|
||||||
<p>
|
Components for [Tea](https://github.com/charmbraclet/tea)
|
||||||
<img src="https://stuff.charm.sh/bubbles/bubbles-github.png" width="233" alt="The Bubbles Logo">
|
|
||||||
</p>
|
|
||||||
|
|
||||||
[](https://github.com/charmbracelet/bubbles/releases)
|
⚠️ This project is a pre-release! Check back later.
|
||||||
[](https://pkg.go.dev/github.com/charmbracelet/bubbles)
|
|
||||||
[](https://github.com/charmbracelet/bubbles/actions)
|
|
||||||
[](https://goreportcard.com/report/charmbracelet/bubbles)
|
|
||||||
|
|
||||||
Some components for [Bubble Tea](https://github.com/charmbracelet/bubbletea)
|
|
||||||
applications. These components are used in production in [Glow][glow],
|
|
||||||
[Charm][charm] and [many other applications][otherstuff].
|
|
||||||
|
|
||||||
[glow]: https://github.com/charmbracelet/glow
|
|
||||||
[charm]: https://github.com/charmbracelet/charm
|
|
||||||
[otherstuff]: https://github.com/charmbracelet/bubbletea/#bubble-tea-in-the-wild
|
|
||||||
|
|
||||||
|
|
||||||
## Spinner
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/spinner.gif" width="400" alt="Spinner Example">
|
|
||||||
|
|
||||||
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, basic spinner](https://github.com/charmbracelet/bubbletea/tree/master/examples/spinner/main.go)
|
|
||||||
* [Example code, various spinners](https://github.com/charmbracelet/bubbletea/tree/master/examples/spinners/main.go)
|
|
||||||
|
|
||||||
|
|
||||||
## Text Input
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/textinput.gif" width="400" alt="Text Input Example">
|
|
||||||
|
|
||||||
A text input field, akin to an `<input type="text">` in HTML. Supports unicode,
|
|
||||||
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/bubbletea/tree/master/examples/textinput/main.go)
|
|
||||||
* [Example code, many fields](https://github.com/charmbracelet/bubbletea/tree/master/examples/textinputs/main.go)
|
|
||||||
|
|
||||||
## Text Area
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/textarea.gif" width="400" alt="Text Area Example">
|
|
||||||
|
|
||||||
A text area field, akin to an `<textarea />` in HTML. Allows for input that
|
|
||||||
spans multiple lines. Supports unicode, pasting, vertical scrolling when the
|
|
||||||
value exceeds the width and height of the element, and many customization
|
|
||||||
options.
|
|
||||||
|
|
||||||
* [Example code, chat input](https://github.com/charmbracelet/bubbletea/tree/master/examples/chat/main.go)
|
|
||||||
* [Example code, story time input](https://github.com/charmbracelet/bubbletea/tree/master/examples/textarea/main.go)
|
|
||||||
|
|
||||||
## Table
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/table.gif" width="400" alt="Table Example">
|
|
||||||
|
|
||||||
A component for displaying and navigating tabular data (columns and rows).
|
|
||||||
Supports vertical scrolling and many customization options.
|
|
||||||
|
|
||||||
* [Example code, countries and populations](https://github.com/charmbracelet/bubbletea/tree/master/examples/table/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
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/pagination.gif" width="200" alt="Paginator Example">
|
|
||||||
|
|
||||||
A component for handling pagination logic and optionally drawing pagination UI.
|
|
||||||
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.
|
|
||||||
|
|
||||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/paginator/main.go)
|
|
||||||
|
|
||||||
|
|
||||||
## Viewport
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/viewport.gif" 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 alternate screen buffer.
|
|
||||||
|
|
||||||
* [Example code](https://github.com/charmbracelet/bubbletea/tree/master/examples/pager/main.go)
|
|
||||||
|
|
||||||
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/bubbletea/tree/master/examples/list-default/main.go)
|
|
||||||
* [Example code, simple list](https://github.com/charmbracelet/bubbletea/tree/master/examples/list-simple/main.go)
|
|
||||||
* [Example code, all features](https://github.com/charmbracelet/bubbletea/tree/master/examples/list-fancy/main.go)
|
|
||||||
|
|
||||||
|
|
||||||
## Timer
|
|
||||||
|
|
||||||
A simple, flexible component for counting down. The update frequency and output
|
|
||||||
can be customized as you like.
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/timer.gif" width="400" alt="Timer example">
|
|
||||||
|
|
||||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/timer/main.go)
|
|
||||||
|
|
||||||
|
|
||||||
## Stopwatch
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/stopwatch.gif" width="400" alt="Stopwatch example">
|
|
||||||
|
|
||||||
A simple, flexible component for counting up. The update frequency and output
|
|
||||||
can be customized as you see fit.
|
|
||||||
|
|
||||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/stopwatch/main.go)
|
|
||||||
|
|
||||||
|
|
||||||
## Help
|
|
||||||
|
|
||||||
<img src="https://stuff.charm.sh/bubbles-examples/help.gif" width="500" alt="Help Example">
|
|
||||||
|
|
||||||
A customizable horizontal mini help view that automatically generates itself
|
|
||||||
from your keybindings. It features single and multi-line modes, which the user
|
|
||||||
can optionally toggle between. It will truncate gracefully if the terminal is
|
|
||||||
too wide for the content.
|
|
||||||
|
|
||||||
* [Example code](https://github.com/charmbracelet/bubbletea/blob/master/examples/help/main.go)
|
|
||||||
|
|
||||||
|
|
||||||
## Key
|
|
||||||
|
|
||||||
A non-visual component for managing keybindings. It’s useful for allowing users
|
|
||||||
to remap keybindings as well as generating help views corresponding to your
|
|
||||||
keybindings.
|
|
||||||
|
|
||||||
```go
|
|
||||||
type KeyMap struct {
|
|
||||||
Up key.Binding
|
|
||||||
Down key.Binding
|
|
||||||
}
|
|
||||||
|
|
||||||
var DefaultKeyMap = KeyMap{
|
|
||||||
Up: key.NewBinding(
|
|
||||||
key.WithKeys("k", "up"), // actual keybindings
|
|
||||||
key.WithHelp("↑/k", "move up"), // corresponding help text
|
|
||||||
),
|
|
||||||
Down: key.NewBinding(
|
|
||||||
key.WithKeys("j", "down"),
|
|
||||||
key.WithHelp("↓/j", "move down"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
||||||
switch msg := msg.(type) {
|
|
||||||
case tea.KeyMsg:
|
|
||||||
switch {
|
|
||||||
case key.Matches(msg, DefaultKeyMap.Up):
|
|
||||||
// The user pressed up
|
|
||||||
case key.Matches(msg, DefaultKeyMap.Down):
|
|
||||||
// The user pressed down
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Additional Bubbles
|
|
||||||
|
|
||||||
<!-- in alphabetical order by author -->
|
|
||||||
|
|
||||||
* [76creates/stickers](https://github.com/76creates/stickers): Responsive
|
|
||||||
flexbox and table components.
|
|
||||||
* [calyptia/go-bubble-table](https://github.com/calyptia/go-bubble-table): An
|
|
||||||
interactive, customizable, scrollable table component.
|
|
||||||
* [erikgeiser/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.
|
|
||||||
* [evertras/bubble-table](https://github.com/Evertras/bubble-table): Interactive,
|
|
||||||
customizable, paginated tables.
|
|
||||||
* [knipferrc/teacup](https://github.com/knipferrc/teacup): Various handy
|
|
||||||
bubbles and utilities for building Bubble Tea applications.
|
|
||||||
* [mritd/bubbles](https://github.com/mritd/bubbles): Some general-purpose
|
|
||||||
bubbles. Inputs with validation, menu selection, a modified progressbar, and
|
|
||||||
so on.
|
|
||||||
* [treilik/bubbleboxer](https://github.com/treilik/bubbleboxer): Layout
|
|
||||||
multiple bubbles side-by-side in a layout-tree.
|
|
||||||
* [treilik/bubblelister](https://github.com/treilik/bubblelister): An alternate
|
|
||||||
list that is scrollable without pagination and has the ability to contain
|
|
||||||
other bubbles as list items.
|
|
||||||
|
|
||||||
If you’ve built a Bubble you think should be listed here,
|
|
||||||
[let us know](mailto:vt100@charm.sh).
|
|
||||||
|
|
||||||
## Feedback
|
|
||||||
|
|
||||||
We’d love to hear your thoughts on this project. Feel free to drop us a note!
|
|
||||||
|
|
||||||
* [Twitter](https://twitter.com/charmcli)
|
|
||||||
* [The Fediverse](https://mastodon.social/@charmcli)
|
|
||||||
* [Discord](https://charm.sh/chat)
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
[MIT](https://github.com/charmbracelet/bubbletea/raw/master/LICENSE)
|
[MIT](https://github.com/charmbracelet/teaparty/raw/master/LICENSE)
|
||||||
|
|
||||||
***
|
|
||||||
|
|
||||||
Part of [Charm](https://charm.sh).
|
|
||||||
|
|
||||||
<a href="https://charm.sh/"><img alt="The Charm logo" src="https://stuff.charm.sh/charm-badge.jpg" width="400"></a>
|
|
||||||
|
|
||||||
Charm热爱开源 • Charm loves open source
|
|
||||||
|
207
cursor/cursor.go
207
cursor/cursor.go
@ -1,207 +0,0 @@
|
|||||||
package cursor
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
)
|
|
||||||
|
|
||||||
const defaultBlinkSpeed = time.Millisecond * 530
|
|
||||||
|
|
||||||
// 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{}
|
|
||||||
|
|
||||||
// blinkCtx manages cursor blinking.
|
|
||||||
type blinkCtx struct {
|
|
||||||
ctx context.Context
|
|
||||||
cancel context.CancelFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mode describes the behavior of the cursor.
|
|
||||||
type Mode int
|
|
||||||
|
|
||||||
// Available cursor modes.
|
|
||||||
const (
|
|
||||||
CursorBlink Mode = iota
|
|
||||||
CursorStatic
|
|
||||||
CursorHide
|
|
||||||
)
|
|
||||||
|
|
||||||
// String returns the cursor mode in a human-readable format. This method is
|
|
||||||
// provisional and for informational purposes only.
|
|
||||||
func (c Mode) String() string {
|
|
||||||
return [...]string{
|
|
||||||
"blink",
|
|
||||||
"static",
|
|
||||||
"hidden",
|
|
||||||
}[c]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Model is the Bubble Tea model for this cursor element.
|
|
||||||
type Model struct {
|
|
||||||
BlinkSpeed time.Duration
|
|
||||||
// Style for styling the cursor block.
|
|
||||||
Style lipgloss.Style
|
|
||||||
// TextStyle is the style used for the cursor when it is hidden (when blinking).
|
|
||||||
// I.e. displaying normal text.
|
|
||||||
TextStyle lipgloss.Style
|
|
||||||
|
|
||||||
// char is the character under the cursor
|
|
||||||
char string
|
|
||||||
// The ID of this Model as it relates to other cursors
|
|
||||||
id int
|
|
||||||
// focus indicates whether the containing input is focused
|
|
||||||
focus bool
|
|
||||||
// Cursor Blink state.
|
|
||||||
Blink bool
|
|
||||||
// Used to manage cursor blink
|
|
||||||
blinkCtx *blinkCtx
|
|
||||||
// The ID of the blink message we're expecting to receive.
|
|
||||||
blinkTag int
|
|
||||||
// mode determines the behavior of the cursor
|
|
||||||
mode Mode
|
|
||||||
}
|
|
||||||
|
|
||||||
// New creates a new model with default settings.
|
|
||||||
func New() Model {
|
|
||||||
return Model{
|
|
||||||
BlinkSpeed: defaultBlinkSpeed,
|
|
||||||
|
|
||||||
Blink: true,
|
|
||||||
mode: CursorBlink,
|
|
||||||
|
|
||||||
blinkCtx: &blinkCtx{
|
|
||||||
ctx: context.Background(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update updates the cursor.
|
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|
||||||
switch msg := msg.(type) {
|
|
||||||
case initialBlinkMsg:
|
|
||||||
// We accept all initialBlinkMsgs generated by the Blink command.
|
|
||||||
|
|
||||||
if m.mode != 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 blink-able?
|
|
||||||
if m.mode != 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.mode == CursorBlink {
|
|
||||||
m.Blink = !m.Blink
|
|
||||||
cmd = m.BlinkCmd()
|
|
||||||
}
|
|
||||||
return m, cmd
|
|
||||||
|
|
||||||
case blinkCanceled: // no-op
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mode returns the model's cursor mode. For available cursor modes, see
|
|
||||||
// type Mode.
|
|
||||||
func (m Model) Mode() Mode {
|
|
||||||
return m.mode
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetMode sets the model's cursor mode. This method returns a command.
|
|
||||||
//
|
|
||||||
// For available cursor modes, see type CursorMode.
|
|
||||||
func (m *Model) SetMode(mode Mode) tea.Cmd {
|
|
||||||
m.mode = mode
|
|
||||||
m.Blink = m.mode == CursorHide || !m.focus
|
|
||||||
if mode == CursorBlink {
|
|
||||||
return Blink
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// BlinkCmd is an command used to manage cursor blinking.
|
|
||||||
func (m *Model) BlinkCmd() tea.Cmd {
|
|
||||||
if m.mode != 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{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Focus focuses the cursor to allow it to blink if desired.
|
|
||||||
func (m *Model) Focus() tea.Cmd {
|
|
||||||
m.focus = true
|
|
||||||
m.Blink = m.mode == CursorHide // show the cursor unless we've explicitly hidden it
|
|
||||||
|
|
||||||
if m.mode == CursorBlink && m.focus {
|
|
||||||
return m.BlinkCmd()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blur blurs the cursor.
|
|
||||||
func (m *Model) Blur() {
|
|
||||||
m.focus = false
|
|
||||||
m.Blink = true
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetChar sets the character under the cursor.
|
|
||||||
func (m *Model) SetChar(char string) {
|
|
||||||
m.char = char
|
|
||||||
}
|
|
||||||
|
|
||||||
// View displays the cursor.
|
|
||||||
func (m Model) View() string {
|
|
||||||
if m.Blink {
|
|
||||||
return m.TextStyle.Inline(true).Render(m.char)
|
|
||||||
}
|
|
||||||
return m.Style.Inline(true).Reverse(true).Render(m.char)
|
|
||||||
}
|
|
14
go.mod
14
go.mod
@ -3,14 +3,8 @@ module github.com/charmbracelet/bubbles
|
|||||||
go 1.13
|
go 1.13
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/atotto/clipboard v0.1.4
|
github.com/charmbracelet/bubbletea v0.8.0
|
||||||
github.com/charmbracelet/bubbletea v0.22.1
|
github.com/muesli/termenv v0.5.3-0.20200526053627-d728968dcf83
|
||||||
github.com/charmbracelet/harmonica v0.2.0
|
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 // indirect
|
||||||
github.com/charmbracelet/lipgloss v0.6.0
|
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 // indirect
|
||||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0
|
|
||||||
github.com/mattn/go-runewidth v0.0.14
|
|
||||||
github.com/muesli/reflow v0.3.0
|
|
||||||
github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739
|
|
||||||
github.com/sahilm/fuzzy v0.1.0
|
|
||||||
)
|
)
|
||||||
|
76
go.sum
76
go.sum
@ -1,50 +1,26 @@
|
|||||||
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
|
github.com/charmbracelet/bubbletea v0.8.0 h1:ruZFaFF+2kgCI1IwNG40KTYDW5ZvE2+hPy4odlBdUko=
|
||||||
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
|
github.com/charmbracelet/bubbletea v0.8.0/go.mod h1:DzNhKkQQJI30eb+kBcaOs1+z86zTSqcMgSHoFY+uCsg=
|
||||||
github.com/charmbracelet/bubbletea v0.22.1 h1:z66q0LWdJNOWEH9zadiAIXp2GN1AWrwNXU8obVY9X24=
|
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=
|
||||||
github.com/charmbracelet/bubbletea v0.22.1/go.mod h1:8/7hVvbPN6ZZPkczLiB8YpLkLJ0n7DMho5Wvfd2X1C0=
|
github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=
|
||||||
github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG4pgaUBiQ=
|
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
|
||||||
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
|
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||||
github.com/charmbracelet/lipgloss v0.6.0 h1:1StyZB9vBSOyuZxQUcUwGr17JmojPNm87inij9N3wJY=
|
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||||
github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk=
|
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||||
github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw=
|
github.com/muesli/termenv v0.5.3-0.20200526053627-d728968dcf83 h1:AfshZBlqAwhCZ27NJ1aPlMcPBihF1squ1GpaollhLQk=
|
||||||
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
|
github.com/muesli/termenv v0.5.3-0.20200526053627-d728968dcf83/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=
|
||||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03 h1:pd4YKIqCB0U7O2I4gWHgEUA2mCEOENmco0l/bM957bU=
|
||||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
github.com/pkg/term v0.0.0-20200520122047-c3ffed290a03/go.mod h1:Z9+Ul5bCbBKnbCvdOWbLqTHhJiYV414CURZJba6L8qA=
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=
|
||||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ=
|
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM=
|
||||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||||
github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
golang.org/x/sys v0.0.0-20200523222454-059865788121 h1:rITEj+UZHYC927n8GT97eC3zrpzXdb/voyeOuVKS46o=
|
||||||
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
|
golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y=
|
||||||
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
|
golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
|
||||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
|
||||||
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.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs=
|
|
||||||
github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739 h1:QANkGiGr39l1EESqrE0gZw0/AJNYzIvoGLhIoVYtluI=
|
|
||||||
github.com/muesli/termenv v0.11.1-0.20220212125758-44cd13922739/go.mod h1:Bd5NYQ7pd+SrtBSrSNoBBmXlcY8+Xj4BMJgh8qcZrvs=
|
|
||||||
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/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-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU=
|
|
||||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
|
||||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
|
233
help/help.go
233
help/help.go
@ -1,233 +0,0 @@
|
|||||||
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 ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// Linter note: at this time we don't think it's worth the additional
|
|
||||||
// code complexity involved in preallocating this slice.
|
|
||||||
//nolint:prealloc
|
|
||||||
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 m.Width > 0 && totalWidth > m.Width {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
out = append(out, col)
|
|
||||||
|
|
||||||
// Separator
|
|
||||||
if i < len(group)-1 {
|
|
||||||
totalWidth += sepWidth
|
|
||||||
if m.Width > 0 && 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
|
|
||||||
}
|
|
142
key/key.go
142
key/key.go
@ -1,142 +0,0 @@
|
|||||||
// Package key provides some types and functions for generating user-definable
|
|
||||||
// keymappings useful in Bubble Tea components. There are a few different ways
|
|
||||||
// you can define a keymapping with this package. Here's one example:
|
|
||||||
//
|
|
||||||
// type KeyMap struct {
|
|
||||||
// Up key.Binding
|
|
||||||
// Down key.Binding
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// var DefaultKeyMap = KeyMap{
|
|
||||||
// Up: key.NewBinding(
|
|
||||||
// key.WithKeys("k", "up"), // actual keybindings
|
|
||||||
// key.WithHelp("↑/k", "move up"), // corresponding help text
|
|
||||||
// ),
|
|
||||||
// Down: key.NewBinding(
|
|
||||||
// key.WithKeys("j", "down"),
|
|
||||||
// key.WithHelp("↓/j", "move down"),
|
|
||||||
// ),
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|
||||||
// switch msg := msg.(type) {
|
|
||||||
// case tea.KeyMsg:
|
|
||||||
// switch {
|
|
||||||
// case key.Matches(msg, DefaultKeyMap.Up):
|
|
||||||
// // The user pressed up
|
|
||||||
// case key.Matches(msg, DefaultKeyMap.Down):
|
|
||||||
// // The user pressed down
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// // ...
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// The help information, which is not used in the example above, can be used
|
|
||||||
// to render help text for keystrokes in your views.
|
|
||||||
package key
|
|
||||||
|
|
||||||
import (
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Binding describes a set of keybindings and, optionally, their associated
|
|
||||||
// help text.
|
|
||||||
type Binding struct {
|
|
||||||
keys []string
|
|
||||||
help Help
|
|
||||||
disabled bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// BindingOpt is an initialization option for a keybinding. It's used as an
|
|
||||||
// argument to NewBinding.
|
|
||||||
type BindingOpt func(*Binding)
|
|
||||||
|
|
||||||
// NewBinding returns a new keybinding from a set of BindingOpt options.
|
|
||||||
func NewBinding(opts ...BindingOpt) Binding {
|
|
||||||
b := &Binding{}
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt(b)
|
|
||||||
}
|
|
||||||
return *b
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithKeys initializes a keybinding with the given keystrokes.
|
|
||||||
func WithKeys(keys ...string) BindingOpt {
|
|
||||||
return func(b *Binding) {
|
|
||||||
b.keys = keys
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithHelp initializes a keybinding with the given help text.
|
|
||||||
func WithHelp(key, desc string) BindingOpt {
|
|
||||||
return func(b *Binding) {
|
|
||||||
b.help = Help{Key: key, Desc: desc}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithDisabled initializes a disabled keybinding.
|
|
||||||
func WithDisabled() BindingOpt {
|
|
||||||
return func(b *Binding) {
|
|
||||||
b.disabled = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetKeys sets the keys for the keybinding.
|
|
||||||
func (b *Binding) SetKeys(keys ...string) {
|
|
||||||
b.keys = keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// Keys returns the keys for the keybinding.
|
|
||||||
func (b Binding) Keys() []string {
|
|
||||||
return b.keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHelp sets the help text for the keybinding.
|
|
||||||
func (b *Binding) SetHelp(key, desc string) {
|
|
||||||
b.help = Help{Key: key, Desc: desc}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Help returns the Help information for the keybinding.
|
|
||||||
func (b Binding) Help() Help {
|
|
||||||
return b.help
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enabled returns whether or not the keybinding is enabled. Disabled
|
|
||||||
// keybindings won't be activated and won't show up in help. Keybindings are
|
|
||||||
// enabled by default.
|
|
||||||
func (b Binding) Enabled() bool {
|
|
||||||
return !b.disabled && b.keys != nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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 {
|
|
||||||
keys := k.String()
|
|
||||||
for _, binding := range b {
|
|
||||||
for _, v := range binding.keys {
|
|
||||||
if keys == v && binding.Enabled() {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
package key
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestBinding_Enabled(t *testing.T) {
|
|
||||||
binding := NewBinding(
|
|
||||||
WithKeys("k", "up"),
|
|
||||||
WithHelp("↑/k", "move up"),
|
|
||||||
)
|
|
||||||
if !binding.Enabled() {
|
|
||||||
t.Errorf("expected key to be Enabled")
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.SetEnabled(false)
|
|
||||||
if binding.Enabled() {
|
|
||||||
t.Errorf("expected key not to be Enabled")
|
|
||||||
}
|
|
||||||
|
|
||||||
binding.SetEnabled(true)
|
|
||||||
binding.Unbind()
|
|
||||||
if binding.Enabled() {
|
|
||||||
t.Errorf("expected key not to be Enabled")
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,227 +0,0 @@
|
|||||||
package list
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"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
|
|
||||||
height int
|
|
||||||
spacing int
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewDefaultDelegate creates a new delegate with default styles.
|
|
||||||
func NewDefaultDelegate() DefaultDelegate {
|
|
||||||
return DefaultDelegate{
|
|
||||||
ShowDescription: true,
|
|
||||||
Styles: NewDefaultItemStyles(),
|
|
||||||
height: 2,
|
|
||||||
spacing: 1,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeight sets delegate's preferred height.
|
|
||||||
func (d *DefaultDelegate) SetHeight(i int) {
|
|
||||||
d.height = i
|
|
||||||
}
|
|
||||||
|
|
||||||
// Height returns the delegate's preferred height.
|
|
||||||
// This has effect only if ShowDescription is true,
|
|
||||||
// otherwise height is always 1.
|
|
||||||
func (d DefaultDelegate) Height() int {
|
|
||||||
if d.ShowDescription {
|
|
||||||
return d.height
|
|
||||||
}
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
if m.width <= 0 {
|
|
||||||
// short-circuit
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prevent text from exceeding list width
|
|
||||||
textwidth := uint(m.width - s.NormalTitle.GetPaddingLeft() - s.NormalTitle.GetPaddingRight())
|
|
||||||
title = truncate.StringWithTail(title, textwidth, ellipsis)
|
|
||||||
if d.ShowDescription {
|
|
||||||
var lines []string
|
|
||||||
for i, line := range strings.Split(desc, "\n") {
|
|
||||||
if i >= d.height-1 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
lines = append(lines, truncate.StringWithTail(line, textwidth, ellipsis))
|
|
||||||
}
|
|
||||||
desc = strings.Join(lines, "\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
97
list/keys.go
@ -1,97 +0,0 @@
|
|||||||
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")),
|
|
||||||
}
|
|
||||||
}
|
|
1263
list/list.go
1263
list/list.go
File diff suppressed because it is too large
Load Diff
@ -1,74 +0,0 @@
|
|||||||
package list
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
|
||||||
)
|
|
||||||
|
|
||||||
type item string
|
|
||||||
|
|
||||||
func (i item) FilterValue() string { return "" }
|
|
||||||
|
|
||||||
type itemDelegate struct{}
|
|
||||||
|
|
||||||
func (d itemDelegate) Height() int { return 1 }
|
|
||||||
func (d itemDelegate) Spacing() int { return 0 }
|
|
||||||
func (d itemDelegate) Update(msg tea.Msg, m *Model) tea.Cmd { return nil }
|
|
||||||
func (d itemDelegate) Render(w io.Writer, m Model, index int, listItem Item) {
|
|
||||||
i, ok := listItem.(item)
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
str := fmt.Sprintf("%d. %s", index+1, i)
|
|
||||||
fmt.Fprint(w, m.Styles.TitleBar.Render(str))
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStatusBarItemName(t *testing.T) {
|
|
||||||
list := New([]Item{item("foo"), item("bar")}, itemDelegate{}, 10, 10)
|
|
||||||
expected := "2 items"
|
|
||||||
if !strings.Contains(list.statusView(), expected) {
|
|
||||||
t.Fatalf("Error: expected view to contain %s", expected)
|
|
||||||
}
|
|
||||||
|
|
||||||
list.SetItems([]Item{item("foo")})
|
|
||||||
expected = "1 item"
|
|
||||||
if !strings.Contains(list.statusView(), expected) {
|
|
||||||
t.Fatalf("Error: expected view to contain %s", expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStatusBarWithoutItems(t *testing.T) {
|
|
||||||
list := New([]Item{}, itemDelegate{}, 10, 10)
|
|
||||||
|
|
||||||
expected := "No items"
|
|
||||||
if !strings.Contains(list.statusView(), expected) {
|
|
||||||
t.Fatalf("Error: expected view to contain %s", expected)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCustomStatusBarItemName(t *testing.T) {
|
|
||||||
list := New([]Item{item("foo"), item("bar")}, itemDelegate{}, 10, 10)
|
|
||||||
list.SetStatusBarItemName("connection", "connections")
|
|
||||||
|
|
||||||
expected := "2 connections"
|
|
||||||
if !strings.Contains(list.statusView(), expected) {
|
|
||||||
t.Fatalf("Error: expected view to contain %s", expected)
|
|
||||||
}
|
|
||||||
|
|
||||||
list.SetItems([]Item{item("foo")})
|
|
||||||
expected = "1 connection"
|
|
||||||
if !strings.Contains(list.statusView(), expected) {
|
|
||||||
t.Fatalf("Error: expected view to contain %s", expected)
|
|
||||||
}
|
|
||||||
|
|
||||||
list.SetItems([]Item{})
|
|
||||||
expected = "No connections"
|
|
||||||
if !strings.Contains(list.statusView(), expected) {
|
|
||||||
t.Fatalf("Error: expected view to contain %s", expected)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,99 +0,0 @@
|
|||||||
package list
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
bullet = "•"
|
|
||||||
ellipsis = "…"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Styles contains style definitions for this list component. By default, these
|
|
||||||
// values are generated by DefaultStyles.
|
|
||||||
type Styles struct {
|
|
||||||
TitleBar lipgloss.Style
|
|
||||||
Title lipgloss.Style
|
|
||||||
Spinner lipgloss.Style
|
|
||||||
FilterPrompt lipgloss.Style
|
|
||||||
FilterCursor lipgloss.Style
|
|
||||||
|
|
||||||
// Default styling for matched characters in a filter. This can be
|
|
||||||
// overridden by delegates.
|
|
||||||
DefaultFilterCharacterMatch lipgloss.Style
|
|
||||||
|
|
||||||
StatusBar lipgloss.Style
|
|
||||||
StatusEmpty lipgloss.Style
|
|
||||||
StatusBarActiveFilter lipgloss.Style
|
|
||||||
StatusBarFilterCount lipgloss.Style
|
|
||||||
|
|
||||||
NoItems lipgloss.Style
|
|
||||||
|
|
||||||
PaginationStyle lipgloss.Style
|
|
||||||
HelpStyle lipgloss.Style
|
|
||||||
|
|
||||||
// Styled characters.
|
|
||||||
ActivePaginationDot lipgloss.Style
|
|
||||||
InactivePaginationDot lipgloss.Style
|
|
||||||
ArabicPagination lipgloss.Style
|
|
||||||
DividerDot lipgloss.Style
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultStyles returns a set of default style definitions for this list
|
|
||||||
// component.
|
|
||||||
func DefaultStyles() (s Styles) {
|
|
||||||
verySubduedColor := lipgloss.AdaptiveColor{Light: "#DDDADA", Dark: "#3C3C3C"}
|
|
||||||
subduedColor := lipgloss.AdaptiveColor{Light: "#9B9B9B", Dark: "#5C5C5C"}
|
|
||||||
|
|
||||||
s.TitleBar = lipgloss.NewStyle().Padding(0, 0, 1, 2)
|
|
||||||
|
|
||||||
s.Title = lipgloss.NewStyle().
|
|
||||||
Background(lipgloss.Color("62")).
|
|
||||||
Foreground(lipgloss.Color("230")).
|
|
||||||
Padding(0, 1)
|
|
||||||
|
|
||||||
s.Spinner = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#8E8E8E", Dark: "#747373"})
|
|
||||||
|
|
||||||
s.FilterPrompt = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#04B575", Dark: "#ECFD65"})
|
|
||||||
|
|
||||||
s.FilterCursor = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#EE6FF8", Dark: "#EE6FF8"})
|
|
||||||
|
|
||||||
s.DefaultFilterCharacterMatch = lipgloss.NewStyle().Underline(true)
|
|
||||||
|
|
||||||
s.StatusBar = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#A49FA5", Dark: "#777777"}).
|
|
||||||
Padding(0, 0, 1, 2)
|
|
||||||
|
|
||||||
s.StatusEmpty = lipgloss.NewStyle().Foreground(subduedColor)
|
|
||||||
|
|
||||||
s.StatusBarActiveFilter = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#1a1a1a", Dark: "#dddddd"})
|
|
||||||
|
|
||||||
s.StatusBarFilterCount = lipgloss.NewStyle().Foreground(verySubduedColor)
|
|
||||||
|
|
||||||
s.NoItems = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#909090", Dark: "#626262"})
|
|
||||||
|
|
||||||
s.ArabicPagination = lipgloss.NewStyle().Foreground(subduedColor)
|
|
||||||
|
|
||||||
s.PaginationStyle = lipgloss.NewStyle().PaddingLeft(2) //nolint:gomnd
|
|
||||||
|
|
||||||
s.HelpStyle = lipgloss.NewStyle().Padding(1, 0, 0, 2)
|
|
||||||
|
|
||||||
s.ActivePaginationDot = lipgloss.NewStyle().
|
|
||||||
Foreground(lipgloss.AdaptiveColor{Light: "#847A85", Dark: "#979797"}).
|
|
||||||
SetString(bullet)
|
|
||||||
|
|
||||||
s.InactivePaginationDot = lipgloss.NewStyle().
|
|
||||||
Foreground(verySubduedColor).
|
|
||||||
SetString(bullet)
|
|
||||||
|
|
||||||
s.DividerDot = lipgloss.NewStyle().
|
|
||||||
Foreground(verySubduedColor).
|
|
||||||
SetString(" " + bullet + " ")
|
|
||||||
|
|
||||||
return s
|
|
||||||
}
|
|
@ -1,4 +1,4 @@
|
|||||||
// Package paginator provides a Bubble Tea package for calulating pagination
|
// package paginator provides a Bubble Tea package for calulating pagination
|
||||||
// and rendering pagination info. Note that this package does not render actual
|
// and rendering pagination info. Note that this package does not render actual
|
||||||
// pages: it's purely for handling keystrokes related to pagination, and
|
// pages: it's purely for handling keystrokes related to pagination, and
|
||||||
// rendering pagination status.
|
// rendering pagination status.
|
||||||
@ -7,71 +7,40 @@ package paginator
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/charmbracelet/bubbles/key"
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Type specifies the way we render pagination.
|
// Type specifies the way we render pagination.
|
||||||
type Type int
|
type Type int
|
||||||
|
|
||||||
// Pagination rendering options.
|
// Pagination rendering options
|
||||||
const (
|
const (
|
||||||
Arabic Type = iota
|
Arabic Type = iota
|
||||||
Dots
|
Dots
|
||||||
)
|
)
|
||||||
|
|
||||||
// KeyMap is the key bindings for different actions within the paginator.
|
// Model is the Tea model for this user interface.
|
||||||
type KeyMap struct {
|
|
||||||
PrevPage key.Binding
|
|
||||||
NextPage key.Binding
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultKeyMap is the default set of key bindings for navigating and acting
|
|
||||||
// upon the paginator.
|
|
||||||
var DefaultKeyMap = KeyMap{
|
|
||||||
PrevPage: key.NewBinding(key.WithKeys("pgup", "left", "h")),
|
|
||||||
NextPage: key.NewBinding(key.WithKeys("pgdown", "right", "l")),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Model is the Bubble Tea model for this user interface.
|
|
||||||
type Model struct {
|
type Model struct {
|
||||||
// Type configures how the pagination is rendered (Arabic, Dots).
|
|
||||||
Type Type
|
Type Type
|
||||||
// Page is the current page number.
|
|
||||||
Page int
|
Page int
|
||||||
// PerPage is the number of items per page.
|
|
||||||
PerPage int
|
PerPage int
|
||||||
// TotalPages is the total number of pages.
|
|
||||||
TotalPages int
|
TotalPages int
|
||||||
// ActiveDot is used to mark the current page under the Dots display type.
|
|
||||||
ActiveDot string
|
ActiveDot string
|
||||||
// InactiveDot is used to mark inactive pages under the Dots display type.
|
|
||||||
InactiveDot string
|
InactiveDot string
|
||||||
// ArabicFormat is the printf-style format to use for the Arabic display type.
|
|
||||||
ArabicFormat string
|
ArabicFormat string
|
||||||
|
|
||||||
// KeyMap encodes the keybindings recognized by the widget.
|
|
||||||
KeyMap KeyMap
|
|
||||||
|
|
||||||
// Deprecated: customize KeyMap instead.
|
|
||||||
UsePgUpPgDownKeys bool
|
|
||||||
// Deprecated: customize KeyMap instead.
|
|
||||||
UseLeftRightKeys bool
|
UseLeftRightKeys bool
|
||||||
// Deprecated: customize KeyMap instead.
|
|
||||||
UseUpDownKeys bool
|
UseUpDownKeys bool
|
||||||
// Deprecated: customize KeyMap instead.
|
|
||||||
UseHLKeys bool
|
UseHLKeys bool
|
||||||
// Deprecated: customize KeyMap instead.
|
|
||||||
UseJKKeys bool
|
UseJKKeys bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetTotalPages is a helper function for calculating the total number of pages
|
// SetTotalPages is a helper function for calculatng the total number of pages
|
||||||
// from a given number of items. It's use is optional since this pager can be
|
// from a given number of items. It's use is optional since this pager can be
|
||||||
// used for other things beyond navigating sets. Note that it both returns the
|
// used for other things beyond navigating sets. Note that it both returns the
|
||||||
// number of total pages and alters the model.
|
// number of total pages and alters the model.
|
||||||
func (m *Model) SetTotalPages(items int) int {
|
func (m *Model) SetTotalPages(items int) int {
|
||||||
if items < 1 {
|
if items == 0 {
|
||||||
return m.TotalPages
|
return 0
|
||||||
}
|
}
|
||||||
n := items / m.PerPage
|
n := items / m.PerPage
|
||||||
if items%m.PerPage > 0 {
|
if items%m.PerPage > 0 {
|
||||||
@ -98,6 +67,7 @@ func (m Model) ItemsOnPage(totalItems int) int {
|
|||||||
// bunchOfStuff := []stuff{...}
|
// bunchOfStuff := []stuff{...}
|
||||||
// start, end := model.GetSliceBounds(len(bunchOfStuff))
|
// start, end := model.GetSliceBounds(len(bunchOfStuff))
|
||||||
// sliceToRender := bunchOfStuff[start:end]
|
// sliceToRender := bunchOfStuff[start:end]
|
||||||
|
//
|
||||||
func (m *Model) GetSliceBounds(length int) (start int, end int) {
|
func (m *Model) GetSliceBounds(length int) (start int, end int) {
|
||||||
start = m.Page * m.PerPage
|
start = m.Page * m.PerPage
|
||||||
end = min(m.Page*m.PerPage+m.PerPage, length)
|
end = min(m.Page*m.PerPage+m.PerPage, length)
|
||||||
@ -120,39 +90,63 @@ func (m *Model) NextPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// OnLastPage returns whether or not we're on the last page.
|
// LastPage returns whether or not we're on the last page.
|
||||||
func (m Model) OnLastPage() bool {
|
func (m Model) OnLastPage() bool {
|
||||||
return m.Page == m.TotalPages-1
|
return m.Page == m.TotalPages-1
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new model with defaults.
|
// NewModel creates a new model with defaults.
|
||||||
func New() Model {
|
func NewModel() Model {
|
||||||
return Model{
|
return Model{
|
||||||
Type: Arabic,
|
Type: Arabic,
|
||||||
Page: 0,
|
Page: 0,
|
||||||
PerPage: 1,
|
PerPage: 1,
|
||||||
TotalPages: 1,
|
TotalPages: 1,
|
||||||
KeyMap: DefaultKeyMap,
|
|
||||||
ActiveDot: "•",
|
ActiveDot: "•",
|
||||||
InactiveDot: "○",
|
InactiveDot: "○",
|
||||||
ArabicFormat: "%d/%d",
|
ArabicFormat: "%d/%d",
|
||||||
|
UseLeftRightKeys: true,
|
||||||
|
UseUpDownKeys: false,
|
||||||
|
UseHLKeys: true,
|
||||||
|
UseJKKeys: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModel creates a new model with defaults.
|
|
||||||
//
|
|
||||||
// Deprecated. Use New instead.
|
|
||||||
var NewModel = New
|
|
||||||
|
|
||||||
// Update is the Tea update function which binds keystrokes to pagination.
|
// Update is the Tea update function which binds keystrokes to pagination.
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
switch {
|
if m.UseLeftRightKeys {
|
||||||
case key.Matches(msg, m.KeyMap.NextPage):
|
switch msg.String() {
|
||||||
m.NextPage()
|
case "left":
|
||||||
case key.Matches(msg, m.KeyMap.PrevPage):
|
|
||||||
m.PrevPage()
|
m.PrevPage()
|
||||||
|
case "right":
|
||||||
|
m.NextPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if m.UseUpDownKeys {
|
||||||
|
switch msg.String() {
|
||||||
|
case "up":
|
||||||
|
m.PrevPage()
|
||||||
|
case "down":
|
||||||
|
m.NextPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if m.UseHLKeys {
|
||||||
|
switch msg.String() {
|
||||||
|
case "h":
|
||||||
|
m.PrevPage()
|
||||||
|
case "l":
|
||||||
|
m.NextPage()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if m.UseJKKeys {
|
||||||
|
switch msg.String() {
|
||||||
|
case "j":
|
||||||
|
m.PrevPage()
|
||||||
|
case "k":
|
||||||
|
m.NextPage()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -160,16 +154,20 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// View renders the pagination to a string.
|
// View renders the pagination to a string.
|
||||||
func (m Model) View() string {
|
func View(model tea.Model) string {
|
||||||
|
m, ok := model.(Model)
|
||||||
|
if !ok {
|
||||||
|
return "could not perform assertion on model"
|
||||||
|
}
|
||||||
switch m.Type {
|
switch m.Type {
|
||||||
case Dots:
|
case Dots:
|
||||||
return m.dotsView()
|
return dotsView(m)
|
||||||
default:
|
default:
|
||||||
return m.arabicView()
|
return arabicView(m)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) dotsView() string {
|
func dotsView(m Model) string {
|
||||||
var s string
|
var s string
|
||||||
for i := 0; i < m.TotalPages; i++ {
|
for i := 0; i < m.TotalPages; i++ {
|
||||||
if i == m.Page {
|
if i == m.Page {
|
||||||
@ -181,7 +179,7 @@ func (m Model) dotsView() string {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) arabicView() string {
|
func arabicView(m Model) string {
|
||||||
return fmt.Sprintf(m.ArabicFormat, m.Page+1, m.TotalPages)
|
return fmt.Sprintf(m.ArabicFormat, m.Page+1, m.TotalPages)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,365 +0,0 @@
|
|||||||
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
|
|
||||||
)
|
|
||||||
|
|
||||||
// Option is used to set options in New. For example:
|
|
||||||
//
|
|
||||||
// progress := New(
|
|
||||||
// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithSpringOptions sets the initial frequency and damping options for the
|
|
||||||
// progressbar's built-in spring-based animation. Frequency corresponds to
|
|
||||||
// speed, and damping to bounciness. For details see:
|
|
||||||
//
|
|
||||||
// https://github.com/charmbracelet/harmonica
|
|
||||||
func WithSpringOptions(frequency, damping float64) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.SetSpringOptions(frequency, damping)
|
|
||||||
m.springCustomized = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithColorProfile sets the color profile to use for the progress bar.
|
|
||||||
func WithColorProfile(p termenv.Profile) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.colorProfile = p
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
|
||||||
percentShown float64 // percent currently displaying
|
|
||||||
targetPercent float64 // percent to which we're animating
|
|
||||||
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
|
|
||||||
|
|
||||||
// Color profile for the progress bar.
|
|
||||||
colorProfile termenv.Profile
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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%%",
|
|
||||||
colorProfile: termenv.ColorProfile(),
|
|
||||||
}
|
|
||||||
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.percentShown - m.targetPercent)
|
|
||||||
if dist < 0.001 && m.velocity < 0.01 {
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
m.percentShown, m.velocity = m.spring.Update(m.percentShown, 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 visible percentage on 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.percentShown)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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(m.color(c)).
|
|
||||||
String(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Solid fill
|
|
||||||
s := termenv.String(string(m.Full)).Foreground(m.color(m.FullColor)).String()
|
|
||||||
b.WriteString(strings.Repeat(s, fw))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Empty fill
|
|
||||||
e := termenv.String(string(m.Empty)).Foreground(m.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 (m Model) color(c string) termenv.Color {
|
|
||||||
return m.colorProfile.Color(c)
|
|
||||||
}
|
|
||||||
|
|
||||||
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,226 +1,118 @@
|
|||||||
package spinner
|
package spinner
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
"github.com/charmbracelet/lipgloss"
|
"github.com/muesli/termenv"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Internal ID management. Used during animating to ensure that frame messages
|
|
||||||
// are received only by spinner 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
|
|
||||||
}
|
|
||||||
|
|
||||||
// Spinner is a set of frames used in animating the spinner.
|
// Spinner is a set of frames used in animating the spinner.
|
||||||
type Spinner struct {
|
type Spinner = int
|
||||||
Frames []string
|
|
||||||
FPS time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// Some spinners to choose from. You could also make your own.
|
// Available types of spinners
|
||||||
var (
|
const (
|
||||||
Line = Spinner{
|
Line Spinner = iota
|
||||||
Frames: []string{"|", "/", "-", "\\"},
|
Dot
|
||||||
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
|
|
||||||
}
|
|
||||||
Meter = Spinner{
|
|
||||||
Frames: []string{
|
|
||||||
"▱▱▱",
|
|
||||||
"▰▱▱",
|
|
||||||
"▰▰▱",
|
|
||||||
"▰▰▰",
|
|
||||||
"▰▰▱",
|
|
||||||
"▰▱▱",
|
|
||||||
"▱▱▱",
|
|
||||||
},
|
|
||||||
FPS: time.Second / 7, //nolint:gomnd
|
|
||||||
}
|
|
||||||
Hamburger = Spinner{
|
|
||||||
Frames: []string{"☱", "☲", "☴", "☲"},
|
|
||||||
FPS: time.Second / 3, //nolint:gomnd
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Model contains the state for the spinner. Use New to create new models
|
const (
|
||||||
|
defaultFPS = 9
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// Spinner frames
|
||||||
|
spinners = map[Spinner][]string{
|
||||||
|
Line: {"|", "/", "-", "\\"},
|
||||||
|
Dot: {"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},
|
||||||
|
}
|
||||||
|
|
||||||
|
color = termenv.ColorProfile().Color
|
||||||
|
)
|
||||||
|
|
||||||
|
// Model contains the state for the spinner. Use NewModel to create new models
|
||||||
// rather than using Model as a struct literal.
|
// rather than using Model as a struct literal.
|
||||||
type Model struct {
|
type Model struct {
|
||||||
// Spinner settings to use. See type Spinner.
|
|
||||||
Spinner Spinner
|
|
||||||
|
|
||||||
// Style sets the styling for the spinner. Most of the time you'll just
|
// Type is the set of frames to use. See Spinner.
|
||||||
// want foreground and background coloring, and potentially some padding.
|
Type Spinner
|
||||||
//
|
|
||||||
// For an introduction to styling with Lip Gloss see:
|
// FPS is the speed at which the ticker should tick
|
||||||
// https://github.com/charmbracelet/lipgloss
|
FPS int
|
||||||
Style lipgloss.Style
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
// CustomMsgFunc can be used to a custom message on tick. This can be
|
||||||
|
// useful when you have spinners in different parts of your application and
|
||||||
|
// want to differentiate between the messages for clarity and simplicity.
|
||||||
|
// If nil, this setting is ignored.
|
||||||
|
CustomMsgFunc func() tea.Msg
|
||||||
|
|
||||||
frame int
|
frame int
|
||||||
id int
|
|
||||||
tag int
|
|
||||||
}
|
|
||||||
|
|
||||||
// ID returns the spinner's unique ID.
|
|
||||||
func (m Model) ID() int {
|
|
||||||
return m.id
|
|
||||||
}
|
|
||||||
|
|
||||||
// New returns a model with default values.
|
|
||||||
func New(opts ...Option) Model {
|
|
||||||
m := Model{
|
|
||||||
Spinner: Line,
|
|
||||||
id: nextID(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt(&m)
|
|
||||||
}
|
|
||||||
|
|
||||||
return m
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModel returns a model with default values.
|
// NewModel returns a model with default values.
|
||||||
//
|
func NewModel() Model {
|
||||||
// Deprecated. Use New instead.
|
return Model{
|
||||||
var NewModel = New
|
Type: Line,
|
||||||
|
FPS: defaultFPS,
|
||||||
// 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.
|
// TickMsg indicates that the timer has ticked and we should render a frame.
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
type TickMsg struct{}
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// 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) {
|
||||||
m.frame++
|
m.frame++
|
||||||
if m.frame >= len(m.Spinner.Frames) {
|
if m.frame >= len(spinners[m.Type]) {
|
||||||
m.frame = 0
|
m.frame = 0
|
||||||
}
|
}
|
||||||
|
if m.CustomMsgFunc != nil {
|
||||||
m.tag++
|
return m, Tick(m)
|
||||||
return m, m.tick(m.id, m.tag)
|
|
||||||
default:
|
|
||||||
return m, nil
|
|
||||||
}
|
}
|
||||||
|
return m, Tick(m)
|
||||||
}
|
}
|
||||||
|
|
||||||
// View renders the model's view.
|
// View renders the model's view.
|
||||||
func (m Model) View() string {
|
func View(model Model) string {
|
||||||
if m.frame >= len(m.Spinner.Frames) {
|
s := spinners[model.Type]
|
||||||
return "(error)"
|
if model.frame >= len(s) {
|
||||||
|
return "[error]"
|
||||||
}
|
}
|
||||||
|
|
||||||
return m.Style.Render(m.Spinner.Frames[m.frame])
|
str := s[model.frame]
|
||||||
|
|
||||||
|
if model.ForegroundColor != "" || model.BackgroundColor != "" {
|
||||||
|
return termenv.
|
||||||
|
String(str).
|
||||||
|
Foreground(color(model.ForegroundColor)).
|
||||||
|
Background(color(model.BackgroundColor)).
|
||||||
|
String()
|
||||||
|
}
|
||||||
|
|
||||||
|
return str
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tick is the command used to advance the spinner one frame. Use this command
|
// Tick is the command used to advance the spinner one frame.
|
||||||
// to effectively start the spinner.
|
func Tick(model Model) tea.Cmd {
|
||||||
func (m Model) Tick() tea.Msg {
|
return func() tea.Msg {
|
||||||
return TickMsg{
|
time.Sleep(time.Second / time.Duration(model.FPS))
|
||||||
// The time at which the tick occurred.
|
if model.CustomMsgFunc != nil {
|
||||||
Time: time.Now(),
|
return model.CustomMsgFunc()
|
||||||
|
}
|
||||||
// The ID of the spinner that this message belongs to. This can be
|
return TickMsg{}
|
||||||
// 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()}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Option is used to set options in New. For example:
|
|
||||||
//
|
|
||||||
// spinner := New(WithSpinner(Dot))
|
|
||||||
type Option func(*Model)
|
|
||||||
|
|
||||||
// WithSpinner is an option to set the spinner.
|
|
||||||
func WithSpinner(spinner Spinner) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.Spinner = spinner
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithStyle is an option to set the spinner style.
|
|
||||||
func WithStyle(style lipgloss.Style) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.Style = style
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,61 +0,0 @@
|
|||||||
package spinner_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/charmbracelet/bubbles/spinner"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestSpinnerNew(t *testing.T) {
|
|
||||||
assertEqualSpinner := func(t *testing.T, exp, got spinner.Spinner) {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
if exp.FPS != got.FPS {
|
|
||||||
t.Errorf("expecting %d FPS, got %d", exp.FPS, got.FPS)
|
|
||||||
}
|
|
||||||
|
|
||||||
if e, g := len(exp.Frames), len(got.Frames); e != g {
|
|
||||||
t.Fatalf("expecting %d frames, got %d", e, g)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, e := range exp.Frames {
|
|
||||||
if g := got.Frames[i]; e != g {
|
|
||||||
t.Errorf("expecting frame index %d with value %q, got %q", i, e, g)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
t.Run("default", func(t *testing.T) {
|
|
||||||
s := spinner.New()
|
|
||||||
|
|
||||||
assertEqualSpinner(t, spinner.Line, s.Spinner)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("WithSpinner", func(t *testing.T) {
|
|
||||||
customSpinner := spinner.Spinner{
|
|
||||||
Frames: []string{"a", "b", "c", "d"},
|
|
||||||
FPS: 16,
|
|
||||||
}
|
|
||||||
|
|
||||||
s := spinner.New(spinner.WithSpinner(customSpinner))
|
|
||||||
|
|
||||||
assertEqualSpinner(t, customSpinner, s.Spinner)
|
|
||||||
})
|
|
||||||
|
|
||||||
tests := map[string]spinner.Spinner{
|
|
||||||
"Line": spinner.Line,
|
|
||||||
"Dot": spinner.Dot,
|
|
||||||
"MiniDot": spinner.MiniDot,
|
|
||||||
"Jump": spinner.Jump,
|
|
||||||
"Pulse": spinner.Pulse,
|
|
||||||
"Points": spinner.Points,
|
|
||||||
"Globe": spinner.Globe,
|
|
||||||
"Moon": spinner.Moon,
|
|
||||||
"Monkey": spinner.Monkey,
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, s := range tests {
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
assertEqualSpinner(t, spinner.New(spinner.WithSpinner(s)).Spinner, s)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,152 +0,0 @@
|
|||||||
// 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}
|
|
||||||
})
|
|
||||||
}
|
|
392
table/table.go
392
table/table.go
@ -1,392 +0,0 @@
|
|||||||
package table
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/charmbracelet/bubbles/key"
|
|
||||||
"github.com/charmbracelet/bubbles/viewport"
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
"github.com/mattn/go-runewidth"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Model defines a state for the table widget.
|
|
||||||
type Model struct {
|
|
||||||
KeyMap KeyMap
|
|
||||||
|
|
||||||
cols []Column
|
|
||||||
rows []Row
|
|
||||||
cursor int
|
|
||||||
focus bool
|
|
||||||
styles Styles
|
|
||||||
|
|
||||||
viewport viewport.Model
|
|
||||||
}
|
|
||||||
|
|
||||||
// Row represents one line in the table.
|
|
||||||
type Row []string
|
|
||||||
|
|
||||||
// Column defines the table structure.
|
|
||||||
type Column struct {
|
|
||||||
Title string
|
|
||||||
Width int
|
|
||||||
}
|
|
||||||
|
|
||||||
// KeyMap defines keybindings. It satisfies to the help.KeyMap interface, which
|
|
||||||
// is used to render the menu menu.
|
|
||||||
type KeyMap struct {
|
|
||||||
LineUp key.Binding
|
|
||||||
LineDown key.Binding
|
|
||||||
PageUp key.Binding
|
|
||||||
PageDown key.Binding
|
|
||||||
HalfPageUp key.Binding
|
|
||||||
HalfPageDown key.Binding
|
|
||||||
GotoTop key.Binding
|
|
||||||
GotoBottom key.Binding
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultKeyMap returns a default set of keybindings.
|
|
||||||
func DefaultKeyMap() KeyMap {
|
|
||||||
const spacebar = " "
|
|
||||||
return KeyMap{
|
|
||||||
LineUp: key.NewBinding(
|
|
||||||
key.WithKeys("up", "k"),
|
|
||||||
key.WithHelp("↑/k", "up"),
|
|
||||||
),
|
|
||||||
LineDown: key.NewBinding(
|
|
||||||
key.WithKeys("down", "j"),
|
|
||||||
key.WithHelp("↓/j", "down"),
|
|
||||||
),
|
|
||||||
PageUp: key.NewBinding(
|
|
||||||
key.WithKeys("b", "pgup"),
|
|
||||||
key.WithHelp("b/pgup", "page up"),
|
|
||||||
),
|
|
||||||
PageDown: key.NewBinding(
|
|
||||||
key.WithKeys("f", "pgdown", spacebar),
|
|
||||||
key.WithHelp("f/pgdn", "page down"),
|
|
||||||
),
|
|
||||||
HalfPageUp: key.NewBinding(
|
|
||||||
key.WithKeys("u", "ctrl+u"),
|
|
||||||
key.WithHelp("u", "½ page up"),
|
|
||||||
),
|
|
||||||
HalfPageDown: key.NewBinding(
|
|
||||||
key.WithKeys("d", "ctrl+d"),
|
|
||||||
key.WithHelp("d", "½ page down"),
|
|
||||||
),
|
|
||||||
GotoTop: key.NewBinding(
|
|
||||||
key.WithKeys("home", "g"),
|
|
||||||
key.WithHelp("g/home", "go to start"),
|
|
||||||
),
|
|
||||||
GotoBottom: key.NewBinding(
|
|
||||||
key.WithKeys("end", "G"),
|
|
||||||
key.WithHelp("G/end", "go to end"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Styles contains style definitions for this list component. By default, these
|
|
||||||
// values are generated by DefaultStyles.
|
|
||||||
type Styles struct {
|
|
||||||
Header lipgloss.Style
|
|
||||||
Cell lipgloss.Style
|
|
||||||
Selected lipgloss.Style
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultStyles returns a set of default style definitions for this table.
|
|
||||||
func DefaultStyles() Styles {
|
|
||||||
return Styles{
|
|
||||||
Selected: lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("212")),
|
|
||||||
Header: lipgloss.NewStyle().Bold(true).Padding(0, 1),
|
|
||||||
Cell: lipgloss.NewStyle().Padding(0, 1),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetStyles sets the table styles.
|
|
||||||
func (m *Model) SetStyles(s Styles) {
|
|
||||||
m.styles = s
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Option is used to set options in New. For example:
|
|
||||||
//
|
|
||||||
// table := New(WithColumns([]Column{{Title: "ID", Width: 10}}))
|
|
||||||
type Option func(*Model)
|
|
||||||
|
|
||||||
// New creates a new model for the table widget.
|
|
||||||
func New(opts ...Option) Model {
|
|
||||||
m := Model{
|
|
||||||
cursor: 0,
|
|
||||||
viewport: viewport.New(0, 20),
|
|
||||||
|
|
||||||
KeyMap: DefaultKeyMap(),
|
|
||||||
styles: DefaultStyles(),
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt(&m)
|
|
||||||
}
|
|
||||||
|
|
||||||
m.UpdateViewport()
|
|
||||||
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithColumns sets the table columns (headers).
|
|
||||||
func WithColumns(cols []Column) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.cols = cols
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithRows sets the table rows (data).
|
|
||||||
func WithRows(rows []Row) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.rows = rows
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithHeight sets the height of the table.
|
|
||||||
func WithHeight(h int) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.viewport.Height = h
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithWidth sets the width of the table.
|
|
||||||
func WithWidth(w int) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.viewport.Width = w
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithFocused sets the focus state of the table.
|
|
||||||
func WithFocused(f bool) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.focus = f
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithStyles sets the table styles.
|
|
||||||
func WithStyles(s Styles) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.styles = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithKeyMap sets the key map.
|
|
||||||
func WithKeyMap(km KeyMap) Option {
|
|
||||||
return func(m *Model) {
|
|
||||||
m.KeyMap = km
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update is the Bubble Tea update loop.
|
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|
||||||
if !m.focus {
|
|
||||||
return m, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var cmds []tea.Cmd
|
|
||||||
|
|
||||||
switch msg := msg.(type) {
|
|
||||||
case tea.KeyMsg:
|
|
||||||
switch {
|
|
||||||
case key.Matches(msg, m.KeyMap.LineUp):
|
|
||||||
m.MoveUp(1)
|
|
||||||
case key.Matches(msg, m.KeyMap.LineDown):
|
|
||||||
m.MoveDown(1)
|
|
||||||
case key.Matches(msg, m.KeyMap.PageUp):
|
|
||||||
m.MoveUp(m.viewport.Height)
|
|
||||||
case key.Matches(msg, m.KeyMap.PageDown):
|
|
||||||
m.MoveDown(m.viewport.Height)
|
|
||||||
case key.Matches(msg, m.KeyMap.HalfPageUp):
|
|
||||||
m.MoveUp(m.viewport.Height / 2)
|
|
||||||
case key.Matches(msg, m.KeyMap.HalfPageDown):
|
|
||||||
m.MoveDown(m.viewport.Height / 2)
|
|
||||||
case key.Matches(msg, m.KeyMap.LineDown):
|
|
||||||
m.MoveDown(1)
|
|
||||||
case key.Matches(msg, m.KeyMap.GotoTop):
|
|
||||||
m.GotoTop()
|
|
||||||
case key.Matches(msg, m.KeyMap.GotoBottom):
|
|
||||||
m.GotoBottom()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return m, tea.Batch(cmds...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Focused returns the focus state of the table.
|
|
||||||
func (m Model) Focused() bool {
|
|
||||||
return m.focus
|
|
||||||
}
|
|
||||||
|
|
||||||
// Focus focusses the table, allowing the user to move around the rows and
|
|
||||||
// interact.
|
|
||||||
func (m *Model) Focus() {
|
|
||||||
m.focus = true
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Blur blurs the table, preventing selection or movement.
|
|
||||||
func (m *Model) Blur() {
|
|
||||||
m.focus = false
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// View renders the component.
|
|
||||||
func (m Model) View() string {
|
|
||||||
return m.headersView() + "\n" + m.viewport.View()
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateViewport updates the list content based on the previously defined
|
|
||||||
// columns and rows.
|
|
||||||
func (m *Model) UpdateViewport() {
|
|
||||||
renderedRows := make([]string, 0, len(m.rows))
|
|
||||||
for i := range m.rows {
|
|
||||||
renderedRows = append(renderedRows, m.renderRow(i))
|
|
||||||
}
|
|
||||||
|
|
||||||
m.viewport.SetContent(
|
|
||||||
lipgloss.JoinVertical(lipgloss.Left, renderedRows...),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SelectedRow returns the selected row.
|
|
||||||
// You can cast it to your own implementation.
|
|
||||||
func (m Model) SelectedRow() Row {
|
|
||||||
return m.rows[m.cursor]
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetRows set a new rows state.
|
|
||||||
func (m *Model) SetRows(r []Row) {
|
|
||||||
m.rows = r
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetWidth sets the width of the viewport of the table.
|
|
||||||
func (m *Model) SetWidth(w int) {
|
|
||||||
m.viewport.Width = w
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeight sets the height of the viewport of the table.
|
|
||||||
func (m *Model) SetHeight(h int) {
|
|
||||||
m.viewport.Height = h
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Height returns the viewport height of the table.
|
|
||||||
func (m Model) Height() int {
|
|
||||||
return m.viewport.Height
|
|
||||||
}
|
|
||||||
|
|
||||||
// Width returns the viewport width of the table.
|
|
||||||
func (m Model) Width() int {
|
|
||||||
return m.viewport.Width
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cursor returns the index of the selected row.
|
|
||||||
func (m Model) Cursor() int {
|
|
||||||
return m.cursor
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetCursor sets the cursor position in the table.
|
|
||||||
func (m *Model) SetCursor(n int) {
|
|
||||||
m.cursor = clamp(n, 0, len(m.rows)-1)
|
|
||||||
m.UpdateViewport()
|
|
||||||
}
|
|
||||||
|
|
||||||
// MoveUp moves the selection up by any number of row.
|
|
||||||
// It can not go above the first row.
|
|
||||||
func (m *Model) MoveUp(n int) {
|
|
||||||
m.cursor = clamp(m.cursor-n, 0, len(m.rows)-1)
|
|
||||||
m.UpdateViewport()
|
|
||||||
|
|
||||||
if m.cursor < m.viewport.YOffset {
|
|
||||||
m.viewport.SetYOffset(m.cursor)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MoveDown moves the selection down by any number of row.
|
|
||||||
// It can not go below the last row.
|
|
||||||
func (m *Model) MoveDown(n int) {
|
|
||||||
m.cursor = clamp(m.cursor+n, 0, len(m.rows)-1)
|
|
||||||
m.UpdateViewport()
|
|
||||||
|
|
||||||
if m.cursor > (m.viewport.YOffset + (m.viewport.Height - 1)) {
|
|
||||||
m.viewport.SetYOffset(m.cursor - (m.viewport.Height - 1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotoTop moves the selection to the first row.
|
|
||||||
func (m *Model) GotoTop() {
|
|
||||||
m.MoveUp(m.cursor)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotoBottom moves the selection to the last row.
|
|
||||||
func (m *Model) GotoBottom() {
|
|
||||||
m.MoveDown(len(m.rows))
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromValues create the table rows from a simple string. It uses `\n` by
|
|
||||||
// default for getting all the rows and the given separator for the fields on
|
|
||||||
// each row.
|
|
||||||
func (m *Model) FromValues(value, separator string) {
|
|
||||||
rows := []Row{}
|
|
||||||
for _, line := range strings.Split(value, "\n") {
|
|
||||||
r := Row{}
|
|
||||||
for _, field := range strings.Split(line, separator) {
|
|
||||||
r = append(r, field)
|
|
||||||
}
|
|
||||||
rows = append(rows, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetRows(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m Model) headersView() string {
|
|
||||||
var s = make([]string, 0, len(m.cols))
|
|
||||||
for _, col := range m.cols {
|
|
||||||
style := lipgloss.NewStyle().Width(col.Width).MaxWidth(col.Width).Inline(true)
|
|
||||||
renderedCell := style.Render(runewidth.Truncate(col.Title, col.Width, "…"))
|
|
||||||
s = append(s, m.styles.Header.Render(renderedCell))
|
|
||||||
}
|
|
||||||
return lipgloss.JoinHorizontal(lipgloss.Left, s...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Model) renderRow(rowID int) string {
|
|
||||||
var s = make([]string, 0, len(m.cols))
|
|
||||||
for i, value := range m.rows[rowID] {
|
|
||||||
style := lipgloss.NewStyle().Width(m.cols[i].Width).MaxWidth(m.cols[i].Width).Inline(true)
|
|
||||||
renderedCell := m.styles.Cell.Render(style.Render(runewidth.Truncate(value, m.cols[i].Width, "…")))
|
|
||||||
s = append(s, renderedCell)
|
|
||||||
}
|
|
||||||
|
|
||||||
row := lipgloss.JoinHorizontal(lipgloss.Left, s...)
|
|
||||||
|
|
||||||
if rowID == m.cursor {
|
|
||||||
return m.styles.Selected.Render(row)
|
|
||||||
}
|
|
||||||
|
|
||||||
return row
|
|
||||||
}
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
func clamp(v, low, high int) int {
|
|
||||||
return min(max(v, low), high)
|
|
||||||
}
|
|
@ -1,54 +0,0 @@
|
|||||||
package table
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestFromValues(t *testing.T) {
|
|
||||||
input := "foo1,bar1\nfoo2,bar2\nfoo3,bar3"
|
|
||||||
table := New(WithColumns([]Column{{Title: "Foo"}, {Title: "Bar"}}))
|
|
||||||
table.FromValues(input, ",")
|
|
||||||
|
|
||||||
if len(table.rows) != 3 {
|
|
||||||
t.Fatalf("expect table to have 3 rows but it has %d", len(table.rows))
|
|
||||||
}
|
|
||||||
|
|
||||||
expect := []Row{
|
|
||||||
{"foo1", "bar1"},
|
|
||||||
{"foo2", "bar2"},
|
|
||||||
{"foo3", "bar3"},
|
|
||||||
}
|
|
||||||
if !deepEqual(table.rows, expect) {
|
|
||||||
t.Fatal("table rows is not equals to the input")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFromValuesWithTabSeparator(t *testing.T) {
|
|
||||||
input := "foo1.\tbar1\nfoo,bar,baz\tbar,2"
|
|
||||||
table := New(WithColumns([]Column{{Title: "Foo"}, {Title: "Bar"}}))
|
|
||||||
table.FromValues(input, "\t")
|
|
||||||
|
|
||||||
if len(table.rows) != 2 {
|
|
||||||
t.Fatalf("expect table to have 2 rows but it has %d", len(table.rows))
|
|
||||||
}
|
|
||||||
|
|
||||||
expect := []Row{
|
|
||||||
{"foo1.", "bar1"},
|
|
||||||
{"foo,bar,baz", "bar,2"},
|
|
||||||
}
|
|
||||||
if !deepEqual(table.rows, expect) {
|
|
||||||
t.Fatal("table rows is not equals to the input")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func deepEqual(a, b []Row) bool {
|
|
||||||
if len(a) != len(b) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for i, r := range a {
|
|
||||||
for j, f := range r {
|
|
||||||
if f != b[i][j] {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
1292
textarea/textarea.go
1292
textarea/textarea.go
File diff suppressed because it is too large
Load Diff
@ -1,446 +0,0 @@
|
|||||||
package textarea
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestNew(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
view := textarea.View()
|
|
||||||
|
|
||||||
if !strings.Contains(view, ">") {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not render the prompt")
|
|
||||||
}
|
|
||||||
|
|
||||||
if !strings.Contains(view, "World!") {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not render the placeholder")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInput(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
|
|
||||||
input := "foo"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
}
|
|
||||||
|
|
||||||
view := textarea.View()
|
|
||||||
|
|
||||||
if !strings.Contains(view, input) {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not render the input")
|
|
||||||
}
|
|
||||||
|
|
||||||
if textarea.col != len(input) {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not move the cursor to the correct position")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSoftWrap(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.Prompt = ""
|
|
||||||
textarea.ShowLineNumbers = false
|
|
||||||
textarea.SetWidth(5)
|
|
||||||
textarea.SetHeight(5)
|
|
||||||
textarea.CharLimit = 60
|
|
||||||
|
|
||||||
textarea, _ = textarea.Update(nil)
|
|
||||||
|
|
||||||
input := "foo bar baz"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
}
|
|
||||||
|
|
||||||
view := textarea.View()
|
|
||||||
|
|
||||||
for _, word := range strings.Split(input, " ") {
|
|
||||||
if !strings.Contains(view, word) {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not render the input")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Due to the word wrapping, each word will be on a new line and the
|
|
||||||
// text area will look like this:
|
|
||||||
//
|
|
||||||
// > foo
|
|
||||||
// > bar
|
|
||||||
// > baz█
|
|
||||||
//
|
|
||||||
// However, due to soft-wrapping the column will still be at the end of the line.
|
|
||||||
if textarea.row != 0 || textarea.col != len(input) {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not move the cursor to the correct position")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCharLimit(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
|
|
||||||
// First input (foo bar) should be accepted as it will fall within the
|
|
||||||
// CharLimit. Second input (baz) should not appear in the input.
|
|
||||||
input := []string{"foo bar", "baz"}
|
|
||||||
textarea.CharLimit = len(input[0])
|
|
||||||
|
|
||||||
for _, k := range []rune(strings.Join(input, " ")) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
}
|
|
||||||
|
|
||||||
view := textarea.View()
|
|
||||||
if strings.Contains(view, input[1]) {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area should not include input past the character limit")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestVerticalScrolling(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.Prompt = ""
|
|
||||||
textarea.ShowLineNumbers = false
|
|
||||||
textarea.SetHeight(1)
|
|
||||||
textarea.SetWidth(20)
|
|
||||||
textarea.CharLimit = 100
|
|
||||||
|
|
||||||
textarea, _ = textarea.Update(nil)
|
|
||||||
|
|
||||||
input := "This is a really long line that should wrap around the text area."
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
}
|
|
||||||
|
|
||||||
view := textarea.View()
|
|
||||||
|
|
||||||
// The view should contain the first "line" of the input.
|
|
||||||
if !strings.Contains(view, "This is a really") {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not render the input")
|
|
||||||
}
|
|
||||||
|
|
||||||
// But we should be able to scroll to see the next line.
|
|
||||||
// Let's scroll down for each line to view the full input.
|
|
||||||
lines := []string{
|
|
||||||
"long line that",
|
|
||||||
"should wrap around",
|
|
||||||
"the text area.",
|
|
||||||
}
|
|
||||||
for _, line := range lines {
|
|
||||||
textarea.viewport.LineDown(1)
|
|
||||||
view = textarea.View()
|
|
||||||
if !strings.Contains(view, line) {
|
|
||||||
t.Log(view)
|
|
||||||
t.Error("Text area did not render the correct scrolled input")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestWordWrapOverflowing(t *testing.T) {
|
|
||||||
// An interesting edge case is when the user enters many words that fill up
|
|
||||||
// the text area and then goes back up and inserts a few words which causes
|
|
||||||
// a cascading wrap and causes an overflow of the last line.
|
|
||||||
//
|
|
||||||
// In this case, we should not let the user insert more words if, after the
|
|
||||||
// entire wrap is complete, the last line is overflowing.
|
|
||||||
textarea := newTextArea()
|
|
||||||
|
|
||||||
textarea.SetHeight(3)
|
|
||||||
textarea.SetWidth(20)
|
|
||||||
textarea.CharLimit = 500
|
|
||||||
|
|
||||||
textarea, _ = textarea.Update(nil)
|
|
||||||
|
|
||||||
input := "Testing Testing Testing Testing Testing Testing Testing Testing"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
textarea.View()
|
|
||||||
}
|
|
||||||
|
|
||||||
// We have essentially filled the text area with input.
|
|
||||||
// Let's see if we can cause wrapping to overflow the last line.
|
|
||||||
textarea.row = 0
|
|
||||||
textarea.col = 0
|
|
||||||
|
|
||||||
input = "Testing"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
textarea.View()
|
|
||||||
}
|
|
||||||
|
|
||||||
lastLineWidth := textarea.LineInfo().Width
|
|
||||||
if lastLineWidth > 20 {
|
|
||||||
t.Log(lastLineWidth)
|
|
||||||
t.Log(textarea.View())
|
|
||||||
t.Fail()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValueSoftWrap(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.SetWidth(16)
|
|
||||||
textarea.SetHeight(10)
|
|
||||||
textarea.CharLimit = 500
|
|
||||||
|
|
||||||
textarea, _ = textarea.Update(nil)
|
|
||||||
|
|
||||||
input := "Testing Testing Testing Testing Testing Testing Testing Testing"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
textarea.View()
|
|
||||||
}
|
|
||||||
|
|
||||||
value := textarea.Value()
|
|
||||||
if value != input {
|
|
||||||
t.Log(value)
|
|
||||||
t.Log(input)
|
|
||||||
t.Fatal("The text area does not have the correct value")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSetValue(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.SetValue(strings.Join([]string{"Foo", "Bar", "Baz"}, "\n"))
|
|
||||||
|
|
||||||
if textarea.row != 2 && textarea.col != 3 {
|
|
||||||
t.Log(textarea.row, textarea.col)
|
|
||||||
t.Fatal("Cursor Should be on row 2 column 3 after inserting 2 new lines")
|
|
||||||
}
|
|
||||||
|
|
||||||
value := textarea.Value()
|
|
||||||
if value != "Foo\nBar\nBaz" {
|
|
||||||
t.Fatal("Value should be Foo\nBar\nBaz")
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetValue should reset text area
|
|
||||||
textarea.SetValue("Test")
|
|
||||||
value = textarea.Value()
|
|
||||||
if value != "Test" {
|
|
||||||
t.Log(value)
|
|
||||||
t.Fatal("Text area was not reset when SetValue() was called")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInsertString(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
|
|
||||||
// Insert some text
|
|
||||||
input := "foo baz"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put cursor in the middle of the text
|
|
||||||
textarea.col = 4
|
|
||||||
|
|
||||||
textarea.InsertString("bar ")
|
|
||||||
|
|
||||||
value := textarea.Value()
|
|
||||||
if value != "foo bar baz" {
|
|
||||||
t.Log(value)
|
|
||||||
t.Fatal("Expected insert string to insert bar between foo and baz")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCanHandleEmoji(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
input := "🧋"
|
|
||||||
|
|
||||||
for _, k := range []rune(input) {
|
|
||||||
textarea, _ = textarea.Update(keyPress(k))
|
|
||||||
}
|
|
||||||
|
|
||||||
value := textarea.Value()
|
|
||||||
if value != input {
|
|
||||||
t.Log(value)
|
|
||||||
t.Fatal("Expected emoji to be inserted")
|
|
||||||
}
|
|
||||||
|
|
||||||
input = "🧋🧋🧋"
|
|
||||||
|
|
||||||
textarea.SetValue(input)
|
|
||||||
|
|
||||||
value = textarea.Value()
|
|
||||||
if value != input {
|
|
||||||
t.Log(value)
|
|
||||||
t.Fatal("Expected emoji to be inserted")
|
|
||||||
}
|
|
||||||
|
|
||||||
if textarea.col != 3 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the third character")
|
|
||||||
}
|
|
||||||
|
|
||||||
if charOffset := textarea.LineInfo().CharOffset; charOffset != 6 {
|
|
||||||
t.Log(charOffset)
|
|
||||||
t.Fatal("Expected cursor to be on the sixth character")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestVerticalNavigationKeepsCursorHorizontalPosition(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.SetWidth(20)
|
|
||||||
|
|
||||||
textarea.SetValue(strings.Join([]string{"你好你好", "Hello"}, "\n"))
|
|
||||||
|
|
||||||
textarea.row = 0
|
|
||||||
textarea.col = 2
|
|
||||||
|
|
||||||
// 你好|你好
|
|
||||||
// Hell|o
|
|
||||||
// 1234|
|
|
||||||
|
|
||||||
// Let's imagine our cursor is on the first line where the pipe is.
|
|
||||||
// We press the down arrow to get to the next line.
|
|
||||||
// The issue is that if we keep the cursor on the same column, the cursor will jump to after the `e`.
|
|
||||||
//
|
|
||||||
// 你好|你好
|
|
||||||
// He|llo
|
|
||||||
//
|
|
||||||
// But this is wrong because visually we were at the 4th character due to
|
|
||||||
// the first line containing double-width runes.
|
|
||||||
// We want to keep the cursor on the same visual column.
|
|
||||||
//
|
|
||||||
// 你好|你好
|
|
||||||
// Hell|o
|
|
||||||
//
|
|
||||||
// This test ensures that the cursor is kept on the same visual column by
|
|
||||||
// ensuring that the column offset goes from 2 -> 4.
|
|
||||||
|
|
||||||
lineInfo := textarea.LineInfo()
|
|
||||||
if lineInfo.CharOffset != 4 || lineInfo.ColumnOffset != 2 {
|
|
||||||
t.Log(lineInfo.CharOffset)
|
|
||||||
t.Log(lineInfo.ColumnOffset)
|
|
||||||
t.Fatal("Expected cursor to be on the fourth character because there two double width runes on the first line.")
|
|
||||||
}
|
|
||||||
|
|
||||||
downMsg := tea.KeyMsg{Type: tea.KeyDown, Alt: false, Runes: []rune{}}
|
|
||||||
textarea, _ = textarea.Update(downMsg)
|
|
||||||
|
|
||||||
lineInfo = textarea.LineInfo()
|
|
||||||
if lineInfo.CharOffset != 4 || lineInfo.ColumnOffset != 4 {
|
|
||||||
t.Log(lineInfo.CharOffset)
|
|
||||||
t.Log(lineInfo.ColumnOffset)
|
|
||||||
t.Fatal("Expected cursor to be on the fourth character because we came down from the first line.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestVerticalNavigationShouldRememberPositionWhileTraversing(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.SetWidth(40)
|
|
||||||
|
|
||||||
// Let's imagine we have a text area with the following content:
|
|
||||||
//
|
|
||||||
// Hello
|
|
||||||
// World
|
|
||||||
// This is a long line.
|
|
||||||
//
|
|
||||||
// If we are at the end of the last line and go up, we should be at the end
|
|
||||||
// of the second line.
|
|
||||||
// And, if we go up again we should be at the end of the first line.
|
|
||||||
// But, if we go back down twice, we should be at the end of the last line
|
|
||||||
// again and not the fifth (length of second line) character of the last line.
|
|
||||||
//
|
|
||||||
// In other words, we should remember the last horizontal position while
|
|
||||||
// traversing vertically.
|
|
||||||
|
|
||||||
textarea.SetValue(strings.Join([]string{"Hello", "World", "This is a long line."}, "\n"))
|
|
||||||
|
|
||||||
// We are at the end of the last line.
|
|
||||||
if textarea.col != 20 || textarea.row != 2 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the 20th character of the last line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Let's go up.
|
|
||||||
upMsg := tea.KeyMsg{Type: tea.KeyUp, Alt: false, Runes: []rune{}}
|
|
||||||
textarea, _ = textarea.Update(upMsg)
|
|
||||||
|
|
||||||
// We should be at the end of the second line.
|
|
||||||
if textarea.col != 5 || textarea.row != 1 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the 5th character of the second line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// And, again.
|
|
||||||
textarea, _ = textarea.Update(upMsg)
|
|
||||||
|
|
||||||
// We should be at the end of the first line.
|
|
||||||
if textarea.col != 5 || textarea.row != 0 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the 5th character of the first line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Let's go down, twice.
|
|
||||||
downMsg := tea.KeyMsg{Type: tea.KeyDown, Alt: false, Runes: []rune{}}
|
|
||||||
textarea, _ = textarea.Update(downMsg)
|
|
||||||
textarea, _ = textarea.Update(downMsg)
|
|
||||||
|
|
||||||
// We should be at the end of the last line.
|
|
||||||
if textarea.col != 20 || textarea.row != 2 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the 20th character of the last line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now, for correct behavior, if we move right or left, we should forget
|
|
||||||
// (reset) the saved horizontal position. Since we assume the user wants to
|
|
||||||
// keep the cursor where it is horizontally. This is how most text areas
|
|
||||||
// work.
|
|
||||||
|
|
||||||
textarea, _ = textarea.Update(upMsg)
|
|
||||||
leftMsg := tea.KeyMsg{Type: tea.KeyLeft, Alt: false, Runes: []rune{}}
|
|
||||||
textarea, _ = textarea.Update(leftMsg)
|
|
||||||
|
|
||||||
if textarea.col != 4 || textarea.row != 1 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the 5th character of the second line")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Going down now should keep us at the 4th column since we moved left and
|
|
||||||
// reset the horizontal position saved state.
|
|
||||||
textarea, _ = textarea.Update(downMsg)
|
|
||||||
if textarea.col != 4 || textarea.row != 2 {
|
|
||||||
t.Log(textarea.col)
|
|
||||||
t.Fatal("Expected cursor to be on the 4th character of the last line")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRendersEndOfLineBuffer(t *testing.T) {
|
|
||||||
textarea := newTextArea()
|
|
||||||
textarea.ShowLineNumbers = true
|
|
||||||
textarea.SetWidth(20)
|
|
||||||
|
|
||||||
view := textarea.View()
|
|
||||||
if !strings.Contains(view, "~") {
|
|
||||||
t.Log(view)
|
|
||||||
t.Fatal("Expected to see a tilde at the end of the line")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTextArea() Model {
|
|
||||||
textarea := New()
|
|
||||||
|
|
||||||
textarea.Prompt = "> "
|
|
||||||
textarea.Placeholder = "Hello, World!"
|
|
||||||
|
|
||||||
textarea.Focus()
|
|
||||||
|
|
||||||
textarea, _ = textarea.Update(nil)
|
|
||||||
|
|
||||||
return textarea
|
|
||||||
}
|
|
||||||
|
|
||||||
func keyPress(key rune) tea.Msg {
|
|
||||||
return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{key}, Alt: false}
|
|
||||||
}
|
|
@ -5,98 +5,35 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
|
|
||||||
"github.com/atotto/clipboard"
|
|
||||||
"github.com/charmbracelet/bubbles/cursor"
|
|
||||||
"github.com/charmbracelet/bubbles/key"
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
"github.com/charmbracelet/lipgloss"
|
"github.com/muesli/termenv"
|
||||||
rw "github.com/mattn/go-runewidth"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 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 (
|
const (
|
||||||
// EchoNormal displays text as is. This is the default behavior.
|
defaultBlinkSpeed = time.Millisecond * 600
|
||||||
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.
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ValidateFunc is a function that returns an error if the input is invalid.
|
var (
|
||||||
type ValidateFunc func(string) error
|
// color is a helper for returning colors
|
||||||
|
color func(s string) termenv.Color = termenv.ColorProfile().Color
|
||||||
|
)
|
||||||
|
|
||||||
// KeyMap is the key bindings for different actions within the textinput.
|
// ErrMsg indicates there's been an error. We don't handle errors in the this
|
||||||
type KeyMap struct {
|
// package; we're expecting errors to be handle in the program that implements
|
||||||
CharacterForward key.Binding
|
// this text input.
|
||||||
CharacterBackward key.Binding
|
type ErrMsg error
|
||||||
WordForward key.Binding
|
|
||||||
WordBackward key.Binding
|
|
||||||
DeleteWordBackward key.Binding
|
|
||||||
DeleteWordForward key.Binding
|
|
||||||
DeleteAfterCursor key.Binding
|
|
||||||
DeleteBeforeCursor key.Binding
|
|
||||||
DeleteCharacterBackward key.Binding
|
|
||||||
DeleteCharacterForward key.Binding
|
|
||||||
LineStart key.Binding
|
|
||||||
LineEnd key.Binding
|
|
||||||
Paste key.Binding
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultKeyMap is the default set of key bindings for navigating and acting
|
// Model is the Tea model for this text input element.
|
||||||
// upon the textinput.
|
|
||||||
var DefaultKeyMap = KeyMap{
|
|
||||||
CharacterForward: key.NewBinding(key.WithKeys("right", "ctrl+f")),
|
|
||||||
CharacterBackward: key.NewBinding(key.WithKeys("left", "ctrl+b")),
|
|
||||||
WordForward: key.NewBinding(key.WithKeys("alt+right", "alt+f")),
|
|
||||||
WordBackward: key.NewBinding(key.WithKeys("alt+left", "alt+b")),
|
|
||||||
DeleteWordBackward: key.NewBinding(key.WithKeys("alt+backspace", "ctrl+w")),
|
|
||||||
DeleteWordForward: key.NewBinding(key.WithKeys("alte+delete", "alt+d")),
|
|
||||||
DeleteAfterCursor: key.NewBinding(key.WithKeys("ctrl+k")),
|
|
||||||
DeleteBeforeCursor: key.NewBinding(key.WithKeys("ctrl+u")),
|
|
||||||
DeleteCharacterBackward: key.NewBinding(key.WithKeys("backspace", "ctrl+h")),
|
|
||||||
DeleteCharacterForward: key.NewBinding(key.WithKeys("delete", "ctrl+d")),
|
|
||||||
LineStart: key.NewBinding(key.WithKeys("home", "ctrl+a")),
|
|
||||||
LineEnd: key.NewBinding(key.WithKeys("end", "ctrl+e")),
|
|
||||||
Paste: key.NewBinding(key.WithKeys("ctrl+v")),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Model is the Bubble Tea model for this text input element.
|
|
||||||
type Model struct {
|
type Model struct {
|
||||||
Err error
|
Err error
|
||||||
|
|
||||||
// General settings.
|
|
||||||
Prompt string
|
Prompt string
|
||||||
Placeholder string
|
Cursor string
|
||||||
EchoMode EchoMode
|
|
||||||
EchoCharacter rune
|
|
||||||
Cursor cursor.Model
|
|
||||||
|
|
||||||
// Deprecated: use cursor.BlinkSpeed instead.
|
|
||||||
// This is unused and will be removed in the future.
|
|
||||||
BlinkSpeed time.Duration
|
BlinkSpeed time.Duration
|
||||||
|
Placeholder string
|
||||||
// Styles. These will be applied as inline styles.
|
TextColor string
|
||||||
//
|
BackgroundColor string
|
||||||
// For an introduction to styling with Lip Gloss see:
|
PlaceholderColor string
|
||||||
// https://github.com/charmbracelet/lipgloss
|
CursorColor string
|
||||||
PromptStyle lipgloss.Style
|
|
||||||
TextStyle lipgloss.Style
|
|
||||||
BackgroundStyle lipgloss.Style
|
|
||||||
PlaceholderStyle lipgloss.Style
|
|
||||||
CursorStyle lipgloss.Style
|
|
||||||
|
|
||||||
// CharLimit is the maximum amount of characters this input element will
|
// CharLimit is the maximum amount of characters this input element will
|
||||||
// accept. If 0 or less, there's no limit.
|
// accept. If 0 or less, there's no limit.
|
||||||
@ -107,101 +44,59 @@ type Model struct {
|
|||||||
// viewport. If 0 or less this setting is ignored.
|
// viewport. If 0 or less this setting is ignored.
|
||||||
Width int
|
Width int
|
||||||
|
|
||||||
// KeyMap encodes the keybindings recognized by the widget.
|
// Underlying text value
|
||||||
KeyMap KeyMap
|
value string
|
||||||
|
|
||||||
// Underlying text value.
|
// Focus indicates whether user input focus should be on this input
|
||||||
value []rune
|
// 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
|
focus bool
|
||||||
|
|
||||||
// Cursor position.
|
// Cursor blink state
|
||||||
|
blink bool
|
||||||
|
|
||||||
|
// Cursor position
|
||||||
pos int
|
pos int
|
||||||
|
|
||||||
// Used to emulate a viewport when width is set and the content is
|
// Used to emulate a viewport when width is set and the content is
|
||||||
// overflowing.
|
// overflowing
|
||||||
offset int
|
offset int
|
||||||
offsetRight int
|
|
||||||
|
|
||||||
// Validate is a function that checks whether or not the text within the
|
|
||||||
// input is valid. If it is not valid, the `Err` field will be set to the
|
|
||||||
// error returned by the function. If the function is not defined, all
|
|
||||||
// input is considered valid.
|
|
||||||
Validate ValidateFunc
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new model with default settings.
|
|
||||||
func New() Model {
|
|
||||||
return Model{
|
|
||||||
Prompt: "> ",
|
|
||||||
EchoCharacter: '*',
|
|
||||||
CharLimit: 0,
|
|
||||||
PlaceholderStyle: lipgloss.NewStyle().Foreground(lipgloss.Color("240")),
|
|
||||||
Cursor: cursor.New(),
|
|
||||||
KeyMap: DefaultKeyMap,
|
|
||||||
|
|
||||||
value: nil,
|
|
||||||
focus: false,
|
|
||||||
pos: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewModel creates a new model with default settings.
|
|
||||||
//
|
|
||||||
// Deprecated. Use New instead.
|
|
||||||
var NewModel = New
|
|
||||||
|
|
||||||
// SetValue sets the value of the text input.
|
// SetValue sets the value of the text input.
|
||||||
func (m *Model) SetValue(s string) {
|
func (m *Model) SetValue(s string) {
|
||||||
if m.Validate != nil {
|
if m.CharLimit > 0 && len(s) > m.CharLimit {
|
||||||
if err := m.Validate(s); err != nil {
|
m.value = s[:m.CharLimit]
|
||||||
m.Err = err
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
empty := len(m.value) == 0
|
|
||||||
m.Err = nil
|
|
||||||
|
|
||||||
runes := []rune(s)
|
|
||||||
if m.CharLimit > 0 && len(runes) > m.CharLimit {
|
|
||||||
m.value = runes[:m.CharLimit]
|
|
||||||
} else {
|
} else {
|
||||||
m.value = runes
|
m.value = s
|
||||||
}
|
}
|
||||||
if (m.pos == 0 && empty) || m.pos > len(m.value) {
|
if m.pos > len(m.value) {
|
||||||
m.SetCursor(len(m.value))
|
m.pos = len(m.value)
|
||||||
}
|
}
|
||||||
m.handleOverflow()
|
m.handleOverflow()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Value returns the value of the text input.
|
// Value returns the value of the text input.
|
||||||
func (m Model) Value() string {
|
func (m Model) Value() string {
|
||||||
return string(m.value)
|
return m.value
|
||||||
}
|
}
|
||||||
|
|
||||||
// Position returns the cursor position.
|
// Cursor start moves the cursor to the given position. If the position is out
|
||||||
func (m Model) Position() int {
|
// of bounds the cursor will be moved to the start or end accordingly.
|
||||||
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) {
|
func (m *Model) SetCursor(pos int) {
|
||||||
m.pos = clamp(pos, 0, len(m.value))
|
m.pos = max(0, min(len(m.value), pos))
|
||||||
m.handleOverflow()
|
m.handleOverflow()
|
||||||
}
|
}
|
||||||
|
|
||||||
// CursorStart moves the cursor to the start of the input field.
|
// CursorStart moves the cursor to the start of the field.
|
||||||
func (m *Model) CursorStart() {
|
func (m *Model) CursorStart() {
|
||||||
m.SetCursor(0)
|
m.pos = 0
|
||||||
|
m.handleOverflow()
|
||||||
}
|
}
|
||||||
|
|
||||||
// CursorEnd moves the cursor to the end of the input field.
|
// CursorEnd moves the cursor to the end of the field.
|
||||||
func (m *Model) CursorEnd() {
|
func (m *Model) CursorEnd() {
|
||||||
m.SetCursor(len(m.value))
|
m.pos = len(m.value)
|
||||||
|
m.handleOverflow()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Focused returns the focus state on the model.
|
// Focused returns the focus state on the model.
|
||||||
@ -209,238 +104,70 @@ func (m Model) Focused() bool {
|
|||||||
return m.focus
|
return m.focus
|
||||||
}
|
}
|
||||||
|
|
||||||
// Focus sets the focus state on the model. When the model is in focus it can
|
// Focus sets the focus state on the model.
|
||||||
// receive keyboard input and the cursor will be shown.
|
func (m *Model) Focus() {
|
||||||
func (m *Model) Focus() tea.Cmd {
|
|
||||||
m.focus = true
|
m.focus = true
|
||||||
return m.Cursor.Focus()
|
m.blink = false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Blur removes the focus state on the model. When the model is blurred it can
|
// Blur removes the focus state on the model.
|
||||||
// not receive keyboard input and the cursor will be hidden.
|
|
||||||
func (m *Model) Blur() {
|
func (m *Model) Blur() {
|
||||||
m.focus = false
|
m.focus = false
|
||||||
m.Cursor.Blur()
|
m.blink = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset sets the input to its default state with no input.
|
// Reset sets the input to its default state with no input.
|
||||||
func (m *Model) Reset() {
|
func (m *Model) Reset() {
|
||||||
m.value = nil
|
m.value = ""
|
||||||
m.SetCursor(0)
|
m.offset = 0
|
||||||
}
|
m.pos = 0
|
||||||
|
m.blink = false
|
||||||
// handle a clipboard paste event, if supported.
|
|
||||||
func (m *Model) handlePaste(v string) {
|
|
||||||
paste := []rune(v)
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// If there's not enough space to paste the whole thing cut the pasted
|
|
||||||
// runes down so they'll fit
|
|
||||||
if m.CharLimit > 0 && availSpace < len(paste) {
|
|
||||||
paste = paste[:len(paste)-availSpace]
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stuff before and after the cursor
|
|
||||||
head := m.value[:m.pos]
|
|
||||||
tailSrc := m.value[m.pos:]
|
|
||||||
tail := make([]rune, len(tailSrc))
|
|
||||||
copy(tail, tailSrc)
|
|
||||||
|
|
||||||
oldPos := m.pos
|
|
||||||
|
|
||||||
// Insert pasted runes
|
|
||||||
for _, r := range paste {
|
|
||||||
head = append(head, r)
|
|
||||||
m.pos++
|
|
||||||
if m.CharLimit > 0 {
|
|
||||||
availSpace--
|
|
||||||
if availSpace <= 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Put it all back together
|
|
||||||
value := append(head, tail...)
|
|
||||||
m.SetValue(string(value))
|
|
||||||
|
|
||||||
if m.Err != nil {
|
|
||||||
m.pos = oldPos
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetCursor(m.pos)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If a max width is defined, perform some logic to treat the visible area
|
// If a max width is defined, perform some logic to treat the visible area
|
||||||
// as a horizontally scrolling viewport.
|
// as a horizontally scrolling viewport.
|
||||||
func (m *Model) handleOverflow() {
|
func (m *Model) handleOverflow() {
|
||||||
if m.Width <= 0 || rw.StringWidth(string(m.value)) <= m.Width {
|
if m.Width > 0 {
|
||||||
m.offset = 0
|
overflow := max(0, len(m.value)-m.Width)
|
||||||
m.offsetRight = len(m.value)
|
|
||||||
return
|
if overflow > 0 && m.pos < m.offset {
|
||||||
|
m.offset = max(0, min(len(m.value), m.pos))
|
||||||
|
} else if overflow > 0 && m.pos >= m.offset+m.Width {
|
||||||
|
m.offset = max(0, m.pos-m.Width)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Correct right offset if we've deleted characters
|
|
||||||
m.offsetRight = min(m.offsetRight, len(m.value))
|
|
||||||
|
|
||||||
if m.pos < m.offset {
|
|
||||||
m.offset = m.pos
|
|
||||||
|
|
||||||
w := 0
|
|
||||||
i := 0
|
|
||||||
runes := m.value[m.offset:]
|
|
||||||
|
|
||||||
for i < len(runes) && w <= m.Width {
|
|
||||||
w += rw.RuneWidth(runes[i])
|
|
||||||
if w <= m.Width+1 {
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
m.offsetRight = m.offset + i
|
|
||||||
} else if m.pos >= m.offsetRight {
|
|
||||||
m.offsetRight = m.pos
|
|
||||||
|
|
||||||
w := 0
|
|
||||||
runes := m.value[:m.offsetRight]
|
|
||||||
i := len(runes) - 1
|
|
||||||
|
|
||||||
for i > 0 && w < m.Width {
|
|
||||||
w += rw.RuneWidth(runes[i])
|
|
||||||
if w <= m.Width {
|
|
||||||
i--
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
m.offset = m.offsetRight - (len(runes) - 1 - i)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteBeforeCursor deletes all text before the cursor.
|
// colorText colorizes a given string according to the TextColor value of the
|
||||||
func (m *Model) deleteBeforeCursor() {
|
// model.
|
||||||
m.value = m.value[m.pos:]
|
func (m *Model) colorText(s string) string {
|
||||||
m.offset = 0
|
return termenv.
|
||||||
m.SetCursor(0)
|
String(s).
|
||||||
|
Foreground(color(m.TextColor)).
|
||||||
|
Background(color(m.BackgroundColor)).
|
||||||
|
String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteAfterCursor deletes all text after the cursor. If input is masked
|
// colorPlaceholder colorizes a given string according to the TextColor value
|
||||||
// delete everything after the cursor so as not to reveal word breaks in the
|
// of the model.
|
||||||
// masked input.
|
func (m *Model) colorPlaceholder(s string) string {
|
||||||
func (m *Model) deleteAfterCursor() {
|
return termenv.
|
||||||
m.value = m.value[:m.pos]
|
String(s).
|
||||||
m.SetCursor(len(m.value))
|
Foreground(color(m.PlaceholderColor)).
|
||||||
|
Background(color(m.BackgroundColor)).
|
||||||
|
String()
|
||||||
}
|
}
|
||||||
|
|
||||||
// deleteWordBackward deletes the word left to the cursor.
|
func (m *Model) wordLeft() {
|
||||||
func (m *Model) deleteWordBackward() {
|
|
||||||
if m.pos == 0 || len(m.value) == 0 {
|
if m.pos == 0 || len(m.value) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.EchoMode != EchoNormal {
|
|
||||||
m.deleteBeforeCursor()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Linter note: it's critical that we acquire the initial cursor position
|
|
||||||
// here prior to altering it via SetCursor() below. As such, moving this
|
|
||||||
// call into the corresponding if clause does not apply here.
|
|
||||||
oldPos := m.pos //nolint:ifshort
|
|
||||||
|
|
||||||
m.SetCursor(m.pos - 1)
|
|
||||||
for unicode.IsSpace(m.value[m.pos]) {
|
|
||||||
if m.pos <= 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// ignore series of whitespace before cursor
|
|
||||||
m.SetCursor(m.pos - 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
for m.pos > 0 {
|
|
||||||
if !unicode.IsSpace(m.value[m.pos]) {
|
|
||||||
m.SetCursor(m.pos - 1)
|
|
||||||
} else {
|
|
||||||
if m.pos > 0 {
|
|
||||||
// keep the previous space
|
|
||||||
m.SetCursor(m.pos + 1)
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if oldPos > len(m.value) {
|
|
||||||
m.value = m.value[:m.pos]
|
|
||||||
} else {
|
|
||||||
m.value = append(m.value[:m.pos], m.value[oldPos:]...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// deleteWordForward deletes the word right to the cursor If input is masked
|
|
||||||
// delete everything after the cursor so as not to reveal word breaks in the
|
|
||||||
// masked input.
|
|
||||||
func (m *Model) deleteWordForward() {
|
|
||||||
if m.pos >= len(m.value) || len(m.value) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if m.EchoMode != EchoNormal {
|
|
||||||
m.deleteAfterCursor()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
oldPos := m.pos
|
|
||||||
m.SetCursor(m.pos + 1)
|
|
||||||
for unicode.IsSpace(m.value[m.pos]) {
|
|
||||||
// ignore series of whitespace after cursor
|
|
||||||
m.SetCursor(m.pos + 1)
|
|
||||||
|
|
||||||
if m.pos >= len(m.value) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for m.pos < len(m.value) {
|
|
||||||
if !unicode.IsSpace(m.value[m.pos]) {
|
|
||||||
m.SetCursor(m.pos + 1)
|
|
||||||
} else {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if m.pos > len(m.value) {
|
|
||||||
m.value = m.value[:oldPos]
|
|
||||||
} else {
|
|
||||||
m.value = append(m.value[:oldPos], m.value[m.pos:]...)
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetCursor(oldPos)
|
|
||||||
}
|
|
||||||
|
|
||||||
// wordBackward moves the cursor one word to the left. If input is masked, move
|
|
||||||
// input to the start so as not to reveal word breaks in the masked input.
|
|
||||||
func (m *Model) wordBackward() {
|
|
||||||
if m.pos == 0 || len(m.value) == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if m.EchoMode != EchoNormal {
|
|
||||||
m.CursorStart()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
i := m.pos - 1
|
i := m.pos - 1
|
||||||
|
|
||||||
for i >= 0 {
|
for i >= 0 {
|
||||||
if unicode.IsSpace(m.value[i]) {
|
if unicode.IsSpace(rune(m.value[i])) {
|
||||||
m.SetCursor(m.pos - 1)
|
m.pos--
|
||||||
i--
|
i--
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
@ -448,8 +175,8 @@ func (m *Model) wordBackward() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for i >= 0 {
|
for i >= 0 {
|
||||||
if !unicode.IsSpace(m.value[i]) {
|
if !unicode.IsSpace(rune(m.value[i])) {
|
||||||
m.SetCursor(m.pos - 1)
|
m.pos--
|
||||||
i--
|
i--
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
@ -457,22 +184,16 @@ func (m *Model) wordBackward() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// wordForward moves the cursor one word to the right. If the input is masked,
|
func (m *Model) wordRight() {
|
||||||
// move input to the end so as not to reveal word breaks in the masked input.
|
|
||||||
func (m *Model) wordForward() {
|
|
||||||
if m.pos >= len(m.value) || len(m.value) == 0 {
|
if m.pos >= len(m.value) || len(m.value) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.EchoMode != EchoNormal {
|
|
||||||
m.CursorEnd()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
i := m.pos
|
i := m.pos
|
||||||
|
|
||||||
for i < len(m.value) {
|
for i < len(m.value) {
|
||||||
if unicode.IsSpace(m.value[i]) {
|
if unicode.IsSpace(rune(m.value[i])) {
|
||||||
m.SetCursor(m.pos + 1)
|
m.pos++
|
||||||
i++
|
i++
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
@ -480,8 +201,8 @@ func (m *Model) wordForward() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for i < len(m.value) {
|
for i < len(m.value) {
|
||||||
if !unicode.IsSpace(m.value[i]) {
|
if !unicode.IsSpace(rune(m.value[i])) {
|
||||||
m.SetCursor(m.pos + 1)
|
m.pos++
|
||||||
i++
|
i++
|
||||||
} else {
|
} else {
|
||||||
break
|
break
|
||||||
@ -489,183 +210,206 @@ func (m *Model) wordForward() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) echoTransform(v string) string {
|
// BlinkMsg is sent when the cursor should alternate it's blinking state.
|
||||||
switch m.EchoMode {
|
type BlinkMsg struct{}
|
||||||
case EchoPassword:
|
|
||||||
return strings.Repeat(string(m.EchoCharacter), rw.StringWidth(v))
|
|
||||||
case EchoNone:
|
|
||||||
return ""
|
|
||||||
|
|
||||||
default:
|
// NewModel creates a new model with default settings.
|
||||||
return v
|
func NewModel() Model {
|
||||||
|
return Model{
|
||||||
|
Prompt: "> ",
|
||||||
|
BlinkSpeed: defaultBlinkSpeed,
|
||||||
|
Placeholder: "",
|
||||||
|
TextColor: "",
|
||||||
|
PlaceholderColor: "240",
|
||||||
|
CursorColor: "",
|
||||||
|
CharLimit: 0,
|
||||||
|
|
||||||
|
value: "",
|
||||||
|
focus: false,
|
||||||
|
blink: true,
|
||||||
|
pos: 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update is the Bubble Tea update loop.
|
// Update is the Tea update loop.
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||||
if !m.focus {
|
if !m.focus {
|
||||||
|
m.blink = true
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Let's remember where the position of the cursor currently is so that if
|
|
||||||
// the cursor position changes, we can reset the blink.
|
|
||||||
oldPos := m.pos //nolint
|
|
||||||
|
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
switch {
|
switch msg.Type {
|
||||||
case key.Matches(msg, m.KeyMap.DeleteWordBackward):
|
case tea.KeyBackspace:
|
||||||
m.Err = nil
|
fallthrough
|
||||||
m.deleteWordBackward()
|
case tea.KeyDelete:
|
||||||
case key.Matches(msg, m.KeyMap.DeleteCharacterBackward):
|
|
||||||
m.Err = nil
|
|
||||||
if len(m.value) > 0 {
|
if len(m.value) > 0 {
|
||||||
m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
|
m.value = m.value[:m.pos-1] + m.value[m.pos:]
|
||||||
|
m.pos--
|
||||||
|
}
|
||||||
|
case tea.KeyLeft:
|
||||||
|
if msg.Alt { // alt+left arrow, back one word
|
||||||
|
m.wordLeft()
|
||||||
|
break
|
||||||
|
}
|
||||||
if m.pos > 0 {
|
if m.pos > 0 {
|
||||||
m.SetCursor(m.pos - 1)
|
m.pos--
|
||||||
}
|
}
|
||||||
|
case tea.KeyRight:
|
||||||
|
if msg.Alt { // alt+right arrow, forward one word
|
||||||
|
m.wordRight()
|
||||||
|
break
|
||||||
}
|
}
|
||||||
case key.Matches(msg, m.KeyMap.WordBackward):
|
|
||||||
m.wordBackward()
|
|
||||||
case key.Matches(msg, m.KeyMap.CharacterBackward):
|
|
||||||
if m.pos > 0 {
|
|
||||||
m.SetCursor(m.pos - 1)
|
|
||||||
}
|
|
||||||
case key.Matches(msg, m.KeyMap.WordForward):
|
|
||||||
m.wordForward()
|
|
||||||
case key.Matches(msg, m.KeyMap.CharacterForward):
|
|
||||||
if m.pos < len(m.value) {
|
if m.pos < len(m.value) {
|
||||||
m.SetCursor(m.pos + 1)
|
m.pos++
|
||||||
}
|
}
|
||||||
case key.Matches(msg, m.KeyMap.DeleteWordBackward):
|
case tea.KeyCtrlF: // ^F, forward one character
|
||||||
m.deleteWordBackward()
|
fallthrough
|
||||||
case key.Matches(msg, m.KeyMap.LineStart):
|
case tea.KeyCtrlB: // ^B, back one charcter
|
||||||
|
fallthrough
|
||||||
|
case tea.KeyCtrlA: // ^A, go to beginning
|
||||||
m.CursorStart()
|
m.CursorStart()
|
||||||
case key.Matches(msg, m.KeyMap.DeleteCharacterForward):
|
case tea.KeyCtrlD: // ^D, delete char under cursor
|
||||||
if len(m.value) > 0 && m.pos < len(m.value) {
|
if len(m.value) > 0 && m.pos < len(m.value) {
|
||||||
m.value = append(m.value[:m.pos], m.value[m.pos+1:]...)
|
m.value = m.value[:m.pos] + m.value[m.pos+1:]
|
||||||
}
|
}
|
||||||
case key.Matches(msg, m.KeyMap.LineEnd):
|
case tea.KeyCtrlE: // ^E, go to end
|
||||||
m.CursorEnd()
|
m.CursorEnd()
|
||||||
case key.Matches(msg, m.KeyMap.DeleteAfterCursor):
|
case tea.KeyCtrlK: // ^K, kill text after cursor
|
||||||
m.deleteAfterCursor()
|
m.value = m.value[:m.pos]
|
||||||
case key.Matches(msg, m.KeyMap.DeleteBeforeCursor):
|
m.pos = len(m.value)
|
||||||
m.deleteBeforeCursor()
|
case tea.KeyCtrlU: // ^U, kill text before cursor
|
||||||
case key.Matches(msg, m.KeyMap.Paste):
|
m.value = m.value[m.pos:]
|
||||||
return m, Paste
|
m.pos = 0
|
||||||
case key.Matches(msg, m.KeyMap.DeleteWordForward):
|
m.offset = 0
|
||||||
m.deleteWordForward()
|
case tea.KeyRune: // input a regular character
|
||||||
default:
|
|
||||||
|
if msg.Alt {
|
||||||
|
if msg.Rune == 'b' { // alt+b, back one word
|
||||||
|
m.wordLeft()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if msg.Rune == 'f' { // alt+f, forward one word
|
||||||
|
m.wordRight()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Input a regular character
|
// Input a regular character
|
||||||
if m.CharLimit <= 0 || len(m.value) < m.CharLimit {
|
if m.CharLimit <= 0 || len(m.value) < m.CharLimit {
|
||||||
runes := msg.Runes
|
m.value = m.value[:m.pos] + string(msg.Rune) + m.value[m.pos:]
|
||||||
|
m.pos++
|
||||||
value := make([]rune, len(m.value))
|
|
||||||
copy(value, m.value)
|
|
||||||
value = append(value[:m.pos], append(runes, value[m.pos:]...)...)
|
|
||||||
m.SetValue(string(value))
|
|
||||||
if m.Err == nil {
|
|
||||||
m.SetCursor(m.pos + len(runes))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case pasteMsg:
|
case ErrMsg:
|
||||||
m.handlePaste(string(msg))
|
|
||||||
|
|
||||||
case pasteErrMsg:
|
|
||||||
m.Err = msg
|
m.Err = msg
|
||||||
}
|
|
||||||
|
|
||||||
var cmds []tea.Cmd
|
case BlinkMsg:
|
||||||
var cmd tea.Cmd
|
m.blink = !m.blink
|
||||||
|
return m, Blink(m)
|
||||||
m.Cursor, cmd = m.Cursor.Update(msg)
|
|
||||||
cmds = append(cmds, cmd)
|
|
||||||
|
|
||||||
if oldPos != m.pos {
|
|
||||||
m.Cursor.Blink = false
|
|
||||||
cmds = append(cmds, m.Cursor.BlinkCmd())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
m.handleOverflow()
|
m.handleOverflow()
|
||||||
return m, tea.Batch(cmds...)
|
|
||||||
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// View renders the textinput in its current state.
|
// View renders the textinput in its current state.
|
||||||
func (m Model) View() string {
|
func View(model tea.Model) string {
|
||||||
// Placeholder text
|
m, ok := model.(Model)
|
||||||
if len(m.value) == 0 && m.Placeholder != "" {
|
if !ok {
|
||||||
return m.placeholderView()
|
return "could not perform assertion on model"
|
||||||
}
|
}
|
||||||
|
|
||||||
styleText := m.TextStyle.Inline(true).Render
|
// Placeholder text
|
||||||
|
if m.value == "" && m.Placeholder != "" {
|
||||||
|
return placeholderView(m)
|
||||||
|
}
|
||||||
|
|
||||||
value := m.value[m.offset:m.offsetRight]
|
left := m.offset
|
||||||
pos := max(0, m.pos-m.offset)
|
right := 0
|
||||||
v := styleText(m.echoTransform(string(value[:pos])))
|
if m.Width > 0 {
|
||||||
|
right = min(len(m.value), m.offset+m.Width+1)
|
||||||
|
} else {
|
||||||
|
right = len(m.value)
|
||||||
|
}
|
||||||
|
value := m.value[left:right]
|
||||||
|
pos := m.pos - m.offset
|
||||||
|
|
||||||
|
v := m.colorText(value[:pos])
|
||||||
|
|
||||||
if pos < len(value) {
|
if pos < len(value) {
|
||||||
char := m.echoTransform(string(value[pos]))
|
v += cursorView(string(value[pos]), m) // cursor and text under it
|
||||||
m.Cursor.SetChar(char)
|
v += m.colorText(value[pos+1:]) // text after cursor
|
||||||
v += m.Cursor.View() // cursor and text under it
|
|
||||||
v += styleText(m.echoTransform(string(value[pos+1:]))) // text after cursor
|
|
||||||
} else {
|
} else {
|
||||||
m.Cursor.SetChar(" ")
|
v += cursorView(" ", m)
|
||||||
v += m.Cursor.View()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// If a max width and background color were set fill the empty spaces with
|
// If a max width and background color were set fill the empty spaces with
|
||||||
// the background color.
|
// the background color.
|
||||||
valWidth := rw.StringWidth(string(value))
|
if m.Width > 0 && len(m.BackgroundColor) > 0 && len(value) <= m.Width {
|
||||||
if m.Width > 0 && valWidth <= m.Width {
|
padding := m.Width - len(value)
|
||||||
padding := max(0, m.Width-valWidth)
|
if len(value)+padding <= m.Width && pos < len(value) {
|
||||||
if valWidth+padding <= m.Width && pos < len(value) {
|
|
||||||
padding++
|
padding++
|
||||||
}
|
}
|
||||||
v += styleText(strings.Repeat(" ", padding))
|
v += strings.Repeat(
|
||||||
|
termenv.String(" ").Background(color(m.BackgroundColor)).String(),
|
||||||
|
padding,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return m.PromptStyle.Render(m.Prompt) + v
|
return m.Prompt + v
|
||||||
}
|
}
|
||||||
|
|
||||||
// placeholderView returns the prompt and placeholder view, if any.
|
// placeholderView
|
||||||
func (m Model) placeholderView() string {
|
func placeholderView(m Model) string {
|
||||||
var (
|
var (
|
||||||
v string
|
v string
|
||||||
p = m.Placeholder
|
p = m.Placeholder
|
||||||
style = m.PlaceholderStyle.Inline(true).Render
|
|
||||||
)
|
)
|
||||||
|
|
||||||
m.Cursor.TextStyle = m.PlaceholderStyle
|
// Cursor
|
||||||
m.Cursor.SetChar(p[:1])
|
if m.blink && m.PlaceholderColor != "" {
|
||||||
v += m.Cursor.View()
|
v += cursorView(
|
||||||
|
m.colorPlaceholder(p[:1]),
|
||||||
|
m,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
v += cursorView(p[:1], m)
|
||||||
|
}
|
||||||
|
|
||||||
// The rest of the placeholder text
|
// The rest of the placeholder text
|
||||||
v += style(p[1:])
|
v += m.colorPlaceholder(p[1:])
|
||||||
|
|
||||||
return m.PromptStyle.Render(m.Prompt) + v
|
return m.Prompt + v
|
||||||
}
|
}
|
||||||
|
|
||||||
// Blink is a command used to initialize cursor blinking.
|
// cursorView styles the cursor.
|
||||||
func Blink() tea.Msg {
|
func cursorView(s string, m Model) string {
|
||||||
return cursor.Blink()
|
if m.blink {
|
||||||
}
|
if m.TextColor != "" || m.BackgroundColor != "" {
|
||||||
|
return termenv.String(s).
|
||||||
// Paste is a command for pasting from the clipboard into the text input.
|
Foreground(color(m.TextColor)).
|
||||||
func Paste() tea.Msg {
|
Background(color(m.BackgroundColor)).
|
||||||
str, err := clipboard.ReadAll()
|
String()
|
||||||
if err != nil {
|
|
||||||
return pasteErrMsg{err}
|
|
||||||
}
|
}
|
||||||
return pasteMsg(str)
|
return s
|
||||||
|
}
|
||||||
|
return termenv.String(s).
|
||||||
|
Foreground(color(m.CursorColor)).
|
||||||
|
Background(color(m.BackgroundColor)).
|
||||||
|
Reverse().
|
||||||
|
String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func clamp(v, low, high int) int {
|
// Blink is a command used to time the cursor blinking.
|
||||||
if high < low {
|
func Blink(model Model) tea.Cmd {
|
||||||
low, high = high, low
|
return func() tea.Msg {
|
||||||
|
time.Sleep(model.BlinkSpeed)
|
||||||
|
return BlinkMsg{}
|
||||||
}
|
}
|
||||||
return min(high, max(low, v))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func min(a, b int) int {
|
func min(a, b int) int {
|
||||||
@ -681,31 +425,3 @@ func max(a, b int) int {
|
|||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated.
|
|
||||||
|
|
||||||
// Deprecated: use cursor.Mode.
|
|
||||||
type CursorMode int
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Deprecated: use cursor.CursorBlink.
|
|
||||||
CursorBlink = CursorMode(cursor.CursorBlink)
|
|
||||||
// Deprecated: use cursor.CursorStatic.
|
|
||||||
CursorStatic = CursorMode(cursor.CursorStatic)
|
|
||||||
// Deprecated: use cursor.CursorHide.
|
|
||||||
CursorHide = CursorMode(cursor.CursorHide)
|
|
||||||
)
|
|
||||||
|
|
||||||
func (c CursorMode) String() string {
|
|
||||||
return cursor.Mode(c).String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use cursor.Mode().
|
|
||||||
func (m Model) CursorMode() CursorMode {
|
|
||||||
return CursorMode(m.Cursor.Mode())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use cursor.SetMode().
|
|
||||||
func (m *Model) SetCursorMode(mode CursorMode) tea.Cmd {
|
|
||||||
return m.Cursor.SetMode(cursor.Mode(mode))
|
|
||||||
}
|
|
||||||
|
192
timer/timer.go
192
timer/timer.go
@ -1,192 +0,0 @@
|
|||||||
// 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 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}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,48 +0,0 @@
|
|||||||
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"),
|
|
||||||
key.WithHelp("f/pgdn", "page down"),
|
|
||||||
),
|
|
||||||
PageUp: key.NewBinding(
|
|
||||||
key.WithKeys("pgup", "b"),
|
|
||||||
key.WithHelp("b/pgup", "page up"),
|
|
||||||
),
|
|
||||||
HalfPageUp: key.NewBinding(
|
|
||||||
key.WithKeys("u", "ctrl+u"),
|
|
||||||
key.WithHelp("u", "½ page up"),
|
|
||||||
),
|
|
||||||
HalfPageDown: key.NewBinding(
|
|
||||||
key.WithKeys("d", "ctrl+d"),
|
|
||||||
key.WithHelp("d", "½ page down"),
|
|
||||||
),
|
|
||||||
Up: key.NewBinding(
|
|
||||||
key.WithKeys("up", "k"),
|
|
||||||
key.WithHelp("↑/k", "up"),
|
|
||||||
),
|
|
||||||
Down: key.NewBinding(
|
|
||||||
key.WithKeys("down", "j"),
|
|
||||||
key.WithHelp("↓/j", "down"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,389 +1,158 @@
|
|||||||
package viewport
|
package viewport
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"math"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/charmbracelet/bubbles/key"
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// New returns a new model with the given width and height as well as default
|
// MODEL
|
||||||
// key mappings.
|
|
||||||
func New(width, height int) (m Model) {
|
|
||||||
m.Width = width
|
|
||||||
m.Height = height
|
|
||||||
m.setInitialValues()
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
// Model is the Bubble Tea model for this viewport element.
|
|
||||||
type Model struct {
|
type Model struct {
|
||||||
|
Err error
|
||||||
Width int
|
Width int
|
||||||
Height int
|
Height int
|
||||||
KeyMap KeyMap
|
Y int
|
||||||
|
|
||||||
// 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 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
|
|
||||||
// a lot of ANSI escape codes you may see improved rendering in certain
|
|
||||||
// terminals with this enabled.
|
|
||||||
//
|
|
||||||
// This should only be used in program occupying the entire terminal,
|
|
||||||
// which is usually via the alternate screen buffer.
|
|
||||||
HighPerformanceRendering bool
|
|
||||||
|
|
||||||
initialized bool
|
|
||||||
lines []string
|
lines []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) setInitialValues() {
|
// Scrollpercent returns the amount scrolled as a float between 0 and 1.
|
||||||
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.
|
|
||||||
func (m Model) AtTop() bool {
|
|
||||||
return m.YOffset <= 0
|
|
||||||
}
|
|
||||||
|
|
||||||
// AtBottom returns whether or not the viewport is at or past the very bottom
|
|
||||||
// position.
|
|
||||||
func (m Model) AtBottom() bool {
|
|
||||||
return m.YOffset >= m.maxYOffset()
|
|
||||||
}
|
|
||||||
|
|
||||||
// PastBottom returns whether or not the viewport is scrolled beyond the last
|
|
||||||
// line. This can happen when adjusting the viewport height.
|
|
||||||
func (m Model) PastBottom() bool {
|
|
||||||
return m.YOffset > m.maxYOffset()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ScrollPercent returns the amount scrolled as a float between 0 and 1.
|
|
||||||
func (m Model) ScrollPercent() float64 {
|
func (m Model) ScrollPercent() float64 {
|
||||||
if m.Height >= len(m.lines) {
|
if m.Height >= len(m.lines) {
|
||||||
return 1.0
|
return 1.0
|
||||||
}
|
}
|
||||||
y := float64(m.YOffset)
|
y := float64(m.Y)
|
||||||
h := float64(m.Height)
|
h := float64(m.Height)
|
||||||
t := float64(len(m.lines) - 1)
|
t := float64(len(m.lines))
|
||||||
v := y / (t - h)
|
return y / (t - h)
|
||||||
return math.Max(0.0, math.Min(1.0, v))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetContent set the pager's text content. For high performance rendering the
|
// SetContent set the pager's text content.
|
||||||
// Sync command should also be called.
|
|
||||||
func (m *Model) SetContent(s string) {
|
func (m *Model) SetContent(s string) {
|
||||||
s = strings.ReplaceAll(s, "\r\n", "\n") // normalize line endings
|
s = strings.Replace(s, "\r\n", "\n", -1) // normalize line endings
|
||||||
m.lines = strings.Split(s, "\n")
|
m.lines = strings.Split(s, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
if m.YOffset > len(m.lines)-1 {
|
// NewModel creates a new pager model. Pass the dimensions of the pager.
|
||||||
m.GotoBottom()
|
func NewModel(width, height int) Model {
|
||||||
|
return Model{
|
||||||
|
Width: width,
|
||||||
|
Height: height,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// maxYOffset returns the maximum possible value of the y-offset based on the
|
|
||||||
// viewport's content and set height.
|
|
||||||
func (m Model) maxYOffset() int {
|
|
||||||
return max(0, len(m.lines)-m.Height)
|
|
||||||
}
|
|
||||||
|
|
||||||
// visibleLines returns the lines that should currently be visible in the
|
|
||||||
// viewport.
|
|
||||||
func (m Model) visibleLines() (lines []string) {
|
|
||||||
if len(m.lines) > 0 {
|
|
||||||
top := max(0, m.YOffset)
|
|
||||||
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, m.maxYOffset())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ViewDown moves the view down by the number of lines in the viewport.
|
// ViewDown moves the view down by the number of lines in the viewport.
|
||||||
// Basically, "page down".
|
// Basically, "page down".
|
||||||
func (m *Model) ViewDown() []string {
|
func (m *Model) ViewDown() {
|
||||||
if m.AtBottom() {
|
m.Y = min(len(m.lines)-m.Height, m.Y+m.Height)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetYOffset(m.YOffset + m.Height)
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ViewUp moves the view up by one height of the viewport. Basically, "page up".
|
// ViewUp moves the view up by one height of the viewport. Basically, "page up".
|
||||||
func (m *Model) ViewUp() []string {
|
func (m *Model) ViewUp() {
|
||||||
if m.AtTop() {
|
m.Y = max(0, m.Y-m.Height)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetYOffset(m.YOffset - m.Height)
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
|
||||||
|
|
||||||
// HalfViewDown moves the view down by half the height of the viewport.
|
|
||||||
func (m *Model) HalfViewDown() (lines []string) {
|
|
||||||
if m.AtBottom() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetYOffset(m.YOffset + m.Height/2)
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// HalfViewUp moves the view up by half the height of the viewport.
|
// HalfViewUp moves the view up by half the height of the viewport.
|
||||||
func (m *Model) HalfViewUp() (lines []string) {
|
func (m *Model) HalfViewUp() {
|
||||||
if m.AtTop() {
|
m.Y = max(0, m.Y-m.Height/2)
|
||||||
return nil
|
}
|
||||||
}
|
|
||||||
|
|
||||||
m.SetYOffset(m.YOffset - m.Height/2)
|
// HalfViewDown moves the view down by half the height of the viewport.
|
||||||
return m.visibleLines()
|
func (m *Model) HalfViewDown() {
|
||||||
|
m.Y = min(len(m.lines)-m.Height, m.Y+m.Height/2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LineDown moves the view up by the given number of lines.
|
||||||
|
func (m *Model) LineDown(n int) {
|
||||||
|
m.Y = min(len(m.lines)-m.Height, m.Y+n)
|
||||||
}
|
}
|
||||||
|
|
||||||
// LineDown moves the view down by the given number of lines.
|
// LineDown moves the view down by the given number of lines.
|
||||||
func (m *Model) LineDown(n int) (lines []string) {
|
func (m *Model) LineUp(n int) {
|
||||||
if m.AtBottom() || n == 0 {
|
m.Y = max(0, m.Y-n)
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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.
|
|
||||||
m.SetYOffset(m.YOffset + n)
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// LineUp moves the view down by the given number of lines. Returns the new
|
// UPDATE
|
||||||
// lines to show.
|
|
||||||
func (m *Model) LineUp(n int) (lines []string) {
|
|
||||||
if m.AtTop() || n == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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.
|
|
||||||
m.SetYOffset(m.YOffset - n)
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TotalLineCount returns the total number of lines (both hidden and visible) within the viewport.
|
|
||||||
func (m Model) TotalLineCount() int {
|
|
||||||
return len(m.lines)
|
|
||||||
}
|
|
||||||
|
|
||||||
// VisibleLineCount returns the number of the visible lines within the viewport.
|
|
||||||
func (m Model) VisibleLineCount() int {
|
|
||||||
return len(m.visibleLines())
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotoTop sets the viewport to the top position.
|
|
||||||
func (m *Model) GotoTop() (lines []string) {
|
|
||||||
if m.AtTop() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
m.SetYOffset(0)
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotoBottom sets the viewport to the bottom position.
|
|
||||||
func (m *Model) GotoBottom() (lines []string) {
|
|
||||||
m.SetYOffset(m.maxYOffset())
|
|
||||||
return m.visibleLines()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sync tells the renderer where the viewport will be located and requests
|
|
||||||
// a render of the current state of the viewport. It should be called for the
|
|
||||||
// first render and after a window resize.
|
|
||||||
//
|
|
||||||
// For high performance rendering only.
|
|
||||||
func Sync(m Model) tea.Cmd {
|
|
||||||
if len(m.lines) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
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
|
|
||||||
// number of lines. Use Model.ViewDown to get the lines that should be rendered.
|
|
||||||
// For example:
|
|
||||||
//
|
|
||||||
// lines := model.ViewDown(1)
|
|
||||||
// cmd := ViewDown(m, lines)
|
|
||||||
func ViewDown(m Model, lines []string) tea.Cmd {
|
|
||||||
if len(lines) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
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.ViewUp to get the lines that should be
|
|
||||||
// rendered.
|
|
||||||
func ViewUp(m Model, lines []string) tea.Cmd {
|
|
||||||
if len(lines) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
top, bottom := m.scrollArea()
|
|
||||||
return tea.ScrollUp(lines, top, bottom)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update handles standard message-based viewport updates.
|
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|
||||||
var cmd tea.Cmd
|
|
||||||
m, cmd = m.updateAsModel(msg)
|
|
||||||
return m, cmd
|
|
||||||
}
|
|
||||||
|
|
||||||
// Author's note: this method has been broken out to make it easier to
|
|
||||||
// potentially transition Update to satisfy tea.Model.
|
|
||||||
func (m Model) updateAsModel(msg tea.Msg) (Model, tea.Cmd) {
|
|
||||||
if !m.initialized {
|
|
||||||
m.setInitialValues()
|
|
||||||
}
|
|
||||||
|
|
||||||
var cmd tea.Cmd
|
|
||||||
|
|
||||||
|
// Update runs the update loop with default keybindings. To define your own
|
||||||
|
// keybindings use the methods on Model.
|
||||||
|
func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
|
|
||||||
case tea.KeyMsg:
|
case tea.KeyMsg:
|
||||||
switch {
|
switch msg.String() {
|
||||||
case key.Matches(msg, m.KeyMap.PageDown):
|
// Down one page
|
||||||
lines := m.ViewDown()
|
case "pgdown":
|
||||||
if m.HighPerformanceRendering {
|
fallthrough
|
||||||
cmd = ViewDown(m, lines)
|
case " ": // spacebar
|
||||||
}
|
fallthrough
|
||||||
|
case "f":
|
||||||
|
m.ViewDown()
|
||||||
|
return m, nil
|
||||||
|
|
||||||
case key.Matches(msg, m.KeyMap.PageUp):
|
// Up one page
|
||||||
lines := m.ViewUp()
|
case "pgup":
|
||||||
if m.HighPerformanceRendering {
|
fallthrough
|
||||||
cmd = ViewUp(m, lines)
|
case "b":
|
||||||
}
|
m.ViewUp()
|
||||||
|
return m, nil
|
||||||
|
|
||||||
case key.Matches(msg, m.KeyMap.HalfPageDown):
|
// Down half page
|
||||||
lines := m.HalfViewDown()
|
case "d":
|
||||||
if m.HighPerformanceRendering {
|
m.HalfViewDown()
|
||||||
cmd = ViewDown(m, lines)
|
return m, nil
|
||||||
}
|
|
||||||
|
|
||||||
case key.Matches(msg, m.KeyMap.HalfPageUp):
|
// Up half page
|
||||||
lines := m.HalfViewUp()
|
case "u":
|
||||||
if m.HighPerformanceRendering {
|
m.HalfViewUp()
|
||||||
cmd = ViewUp(m, lines)
|
return m, nil
|
||||||
}
|
|
||||||
|
|
||||||
case key.Matches(msg, m.KeyMap.Down):
|
// Down one line
|
||||||
lines := m.LineDown(1)
|
case "down":
|
||||||
if m.HighPerformanceRendering {
|
fallthrough
|
||||||
cmd = ViewDown(m, lines)
|
case "j":
|
||||||
}
|
m.LineDown(1)
|
||||||
|
return m, nil
|
||||||
|
|
||||||
case key.Matches(msg, m.KeyMap.Up):
|
// Up one line
|
||||||
lines := m.LineUp(1)
|
case "up":
|
||||||
if m.HighPerformanceRendering {
|
fallthrough
|
||||||
cmd = ViewUp(m, lines)
|
case "k":
|
||||||
|
m.LineUp(1)
|
||||||
|
return m, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case tea.MouseMsg:
|
return m, nil
|
||||||
if !m.MouseWheelEnabled {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
switch msg.Type {
|
|
||||||
case tea.MouseWheelUp:
|
|
||||||
lines := m.LineUp(m.MouseWheelDelta)
|
|
||||||
if m.HighPerformanceRendering {
|
|
||||||
cmd = ViewUp(m, lines)
|
|
||||||
}
|
|
||||||
|
|
||||||
case tea.MouseWheelDown:
|
|
||||||
lines := m.LineDown(m.MouseWheelDelta)
|
|
||||||
if m.HighPerformanceRendering {
|
|
||||||
cmd = ViewDown(m, lines)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return m, cmd
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// VIEW
|
||||||
|
|
||||||
// View renders the viewport into a string.
|
// View renders the viewport into a string.
|
||||||
func (m Model) View() string {
|
func View(m Model) string {
|
||||||
if m.HighPerformanceRendering {
|
if m.Err != nil {
|
||||||
// Just send newlines since we're going to be rendering the actual
|
return m.Err.Error()
|
||||||
// content separately. 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", max(0, m.Height-1))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
w, h := m.Width, m.Height
|
var lines []string
|
||||||
if sw := m.Style.GetWidth(); sw != 0 {
|
|
||||||
w = min(w, sw)
|
if len(m.lines) > 0 {
|
||||||
|
top := max(0, m.Y)
|
||||||
|
bottom := min(len(m.lines), m.Y+m.Height)
|
||||||
|
lines = m.lines[top:bottom]
|
||||||
}
|
}
|
||||||
if sh := m.Style.GetHeight(); sh != 0 {
|
|
||||||
h = min(h, sh)
|
// Fill empty space with newlines
|
||||||
|
extraLines := ""
|
||||||
|
if len(lines) < m.Height {
|
||||||
|
extraLines = strings.Repeat("\n", m.Height-len(lines))
|
||||||
}
|
}
|
||||||
contentWidth := w - m.Style.GetHorizontalFrameSize()
|
|
||||||
contentHeight := h - m.Style.GetVerticalFrameSize()
|
return strings.Join(lines, "\n") + extraLines
|
||||||
contents := lipgloss.NewStyle().
|
|
||||||
Height(contentHeight). // pad to height.
|
|
||||||
MaxHeight(contentHeight). // truncate height if taller.
|
|
||||||
MaxWidth(contentWidth). // truncate width.
|
|
||||||
Render(strings.Join(m.visibleLines(), "\n"))
|
|
||||||
return m.Style.Copy().
|
|
||||||
UnsetWidth().UnsetHeight(). // Style size already applied in contents.
|
|
||||||
Render(contents)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func clamp(v, low, high int) int {
|
// ETC
|
||||||
if high < low {
|
|
||||||
low, high = high, low
|
|
||||||
}
|
|
||||||
return min(high, max(low, v))
|
|
||||||
}
|
|
||||||
|
|
||||||
func min(a, b int) int {
|
func min(a, b int) int {
|
||||||
if a < b {
|
if a < b {
|
||||||
|
Loading…
Reference in New Issue
Block a user