whispervis/widgets/loader.go

88 lines
1.6 KiB
Go
Raw Normal View History

2018-09-06 11:45:13 +03:00
package widgets
import (
"fmt"
"sync"
2018-09-06 11:45:13 +03:00
"github.com/gopherjs/vecty"
"github.com/gopherjs/vecty/elem"
)
2018-09-17 22:11:04 +03:00
// Loader implements prograss-bar style loader widget.
2018-09-06 11:45:13 +03:00
type Loader struct {
vecty.Core
mx sync.RWMutex
2018-09-06 11:45:13 +03:00
steps int
current int
}
2018-09-17 22:11:04 +03:00
// Render implements Component interface for Loader.
2018-09-06 11:45:13 +03:00
func (l *Loader) Render() vecty.ComponentOrHTML {
2018-09-06 15:15:55 +03:00
text := l.text()
2018-09-06 11:45:13 +03:00
return elem.Div(
2018-09-06 15:15:55 +03:00
vecty.Markup(
2018-10-20 19:39:16 +02:00
vecty.Class("is-size-1"),
2018-09-06 15:15:55 +03:00
vecty.Style("position", "relative"),
vecty.Style("top", "50%"),
),
elem.Heading1(
vecty.Text(text),
),
2018-09-06 11:45:13 +03:00
)
}
2018-09-17 22:11:04 +03:00
// NewLoader creates new Loader.
func NewLoader() *Loader {
return &Loader{}
2018-09-06 11:45:13 +03:00
}
2018-09-17 22:11:04 +03:00
// Inc increases current value of loader by one.
2018-09-06 11:45:13 +03:00
func (l *Loader) Inc() {
l.mx.Lock()
2018-09-17 22:11:04 +03:00
if l.current < l.steps {
l.current++
}
l.mx.Unlock()
2018-09-06 11:45:13 +03:00
}
2018-09-17 22:11:04 +03:00
// Steps returns the total number of steps.
2018-09-06 18:37:46 +03:00
func (l *Loader) Steps() int {
l.mx.RLock()
defer l.mx.RUnlock()
2018-09-06 18:37:46 +03:00
return l.steps
}
2018-09-17 22:11:04 +03:00
// Reset resets the current state of Loader.
func (l *Loader) Reset() {
l.mx.Lock()
l.current = 0
l.mx.Unlock()
}
2018-09-17 22:11:04 +03:00
// SetSteps updates the number of steps for loader.
func (l *Loader) SetSteps(steps int) {
l.mx.Lock()
l.steps = steps
l.mx.Unlock()
}
// Progress reports Loader's progress in percentage.
2018-09-06 11:45:13 +03:00
func (l *Loader) Progress() float64 {
l.mx.RLock()
defer l.mx.RUnlock()
2018-09-06 11:45:13 +03:00
return 100 * float64(l.current) / float64(l.steps)
}
2018-09-06 15:15:55 +03:00
2018-09-17 22:11:04 +03:00
// text returns formatted string to display.
2018-09-06 15:15:55 +03:00
func (l *Loader) text() string {
var text string
progress := l.Progress()
if progress > 99.9 {
text = "Completed"
} else {
text = fmt.Sprintf("Loading %.0f%%...", progress)
}
return text
}