summaryrefslogtreecommitdiff
path: root/tui/context_menu.go
blob: e6d5bb9ec982802b1b76747630071d732e87a77d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package tui

import (
	"github.com/rivo/uniseg"
	"strings"
)

var menuStyle = Style {Fg: Black, Bg: Yellow}

var menuState struct {
	open bool
	x, y int
	width, height int
	boxId string
	menu []string
	selected string
}

func MenuOption(name string) bool {
	b := top()
	b.contextMenu = append(b.contextMenu, name)
	if menuState.boxId == top().id && menuState.selected == name {
		menuState.selected = ""
		return true
	}
	return false
}

func openContextMenu(x int, y int, b *Box) {
	menuState.open = true
	menuState.boxId = b.id
	menuState.menu = b.contextMenu

	menuState.height = len(menuState.menu)
	for _, option := range menuState.menu {
		menuState.width = max(menuState.width, uniseg.StringWidth(option))
	}
	size := Size()
	if x + menuState.width < size.Width {
		menuState.x = x + 1
	} else {
		menuState.x = x - menuState.width - 1
	}
	if y + menuState.height < size.Height {
		menuState.y = y
	} else {
		menuState.y = y - menuState.height
	}
}


func processContextMenu(ev MouseEvent) {
	for i, option := range menuState.menu {
		x, y := menuState.x, menuState.y + i
		if ev.Button <= 2 && (ev.Pressed || ev.Released) &&
				ev.X >= x && ev.X < x + menuState.width && ev.Y == y {
			menuState.selected = option
			menuState.open = false
		}
	}
	if ev.Button <= 2 && ev.Pressed {
		menuState.open = false
	}
}

func drawContextMenu() {
	if !menuState.open {
		return
	}
	for i, option := range menuState.menu {
		x, y := menuState.x, menuState.y + i
		WriteAt(x, y, strings.Repeat(" ", menuState.width), menuStyle)
		WriteAt(x, y, option, menuStyle)
	}
}