aerc/lib/ui/stack.go
Jeffas f6216bb621 Add Mouseable
This adds the Mouseable interface. When this is implemented for a
component that item can accept and process mouseevents.

At the top level when a mouse event is received it is passed to the
grid's handler and then it trickles down until it reaches a component
that can actually handle it, such as the tablist, dirlist or msglist.

A mouse event is passed so that components can handle other things such
as scrolling with the mousewheel. The components themselves then perform
the necessary actions.

Clicking emails in the messagelist opens them in a new tab.

Textinputs can be clicked to position the cursor inside them.

Mouseevents are not forwarded to the terminal at the moment.

Elements which do not handle mouse events are not required to implement
the Mouseable interface.
2019-09-11 11:41:34 -04:00

81 lines
1.7 KiB
Go

package ui
import (
"fmt"
"github.com/gdamore/tcell"
)
type Stack struct {
children []Drawable
onInvalidate []func(d Drawable)
}
func NewStack() *Stack {
return &Stack{}
}
func (stack *Stack) Children() []Drawable {
return stack.children
}
func (stack *Stack) OnInvalidate(onInvalidate func(d Drawable)) {
stack.onInvalidate = append(stack.onInvalidate, onInvalidate)
}
func (stack *Stack) Invalidate() {
for _, fn := range stack.onInvalidate {
fn(stack)
}
}
func (stack *Stack) Draw(ctx *Context) {
if len(stack.children) > 0 {
stack.Peek().Draw(ctx)
} else {
ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', tcell.StyleDefault)
}
}
func (stack *Stack) MouseEvent(localX int, localY int, event tcell.Event) {
if len(stack.children) > 0 {
switch element := stack.Peek().(type) {
case Mouseable:
element.MouseEvent(localX, localY, event)
}
}
}
func (stack *Stack) Push(d Drawable) {
if len(stack.children) != 0 {
stack.Peek().OnInvalidate(nil)
}
stack.children = append(stack.children, d)
d.OnInvalidate(stack.invalidateFromChild)
stack.Invalidate()
}
func (stack *Stack) Pop() Drawable {
if len(stack.children) == 0 {
panic(fmt.Errorf("Tried to pop from an empty UI stack"))
}
d := stack.children[len(stack.children)-1]
stack.children = stack.children[:len(stack.children)-1]
stack.Invalidate()
d.OnInvalidate(nil)
if len(stack.children) != 0 {
stack.Peek().OnInvalidate(stack.invalidateFromChild)
}
return d
}
func (stack *Stack) Peek() Drawable {
if len(stack.children) == 0 {
panic(fmt.Errorf("Tried to peek from an empty stack"))
}
return stack.children[len(stack.children)-1]
}
func (stack *Stack) invalidateFromChild(d Drawable) {
stack.Invalidate()
}