1
0
mirror of https://github.com/mum4k/termdash.git synced 2025-04-27 13:48:49 +08:00

Merge pull request #127 from mum4k/write-atomic-reset

Adding Text Write option that atomically replaces the text content.
This commit is contained in:
Jakub Sobon 2019-02-15 00:54:38 -05:00 committed by GitHub
commit 2dd5a0c33d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 39 additions and 1 deletions

View File

@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- The LineChart widget can display X axis labels in vertical orientation.
- The LineChart widget allows the user to specify a custom scale for the Y
axis.
- The Text widget now has a Write option that atomically replaces the entire
text content.
### Changed

View File

@ -85,7 +85,11 @@ func New(opts ...Option) (*Text, error) {
func (t *Text) Reset() {
t.mu.Lock()
defer t.mu.Unlock()
t.reset()
}
// reset implements Reset, caller must hold t.mu.
func (t *Text) reset() {
t.buff.Reset()
t.givenWOpts = nil
t.wOptsTracker = attrrange.NewTracker()
@ -109,8 +113,13 @@ func (t *Text) Write(text string, wOpts ...WriteOption) error {
return err
}
opts := newWriteOptions(wOpts...)
if opts.replace {
t.reset()
}
pos := t.buff.Len()
t.givenWOpts = append(t.givenWOpts, newWriteOptions(wOpts...))
t.givenWOpts = append(t.givenWOpts, opts)
wOptsIdx := len(t.givenWOpts) - 1
if err := t.wOptsTracker.Add(pos, pos+len(text), wOptsIdx); err != nil {
return err

View File

@ -133,6 +133,24 @@ func TestTextDraws(t *testing.T) {
return ft
},
},
{
desc: "multiple writes replace when requested",
canvas: image.Rect(0, 0, 12, 1),
writes: func(widget *Text) error {
if err := widget.Write("hello", WriteReplace()); err != nil {
return err
}
return widget.Write("world", WriteReplace())
},
want: func(size image.Point) *faketerm.Terminal {
ft := faketerm.MustNew(size)
c := testcanvas.MustNew(ft.Area())
testdraw.MustText(c, "world", image.Point{0, 0})
testcanvas.MustApply(c, ft)
return ft
},
},
{
desc: "reset clears the content",
canvas: image.Rect(0, 0, 12, 1),

View File

@ -29,6 +29,7 @@ type WriteOption interface {
// writeOptions stores the provided options.
type writeOptions struct {
cellOpts *cell.Options
replace bool
}
// newWriteOptions returns new writeOptions instance.
@ -56,3 +57,11 @@ func WriteCellOpts(opts ...cell.Option) WriteOption {
wOpts.cellOpts = cell.NewOptions(opts...)
})
}
// WriteReplace instructs the text widget to replace the entire text content on
// this write instead of appending.
func WriteReplace() WriteOption {
return writeOption(func(wOpts *writeOptions) {
wOpts.replace = true
})
}