-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlistbox.zsh
127 lines (115 loc) · 2.49 KB
/
listbox.zsh
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/bin/bash
listbox() {
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-h|--help)
echo "choose from list of options"
echo "Usage: listbox [options]"
echo "Example:"
echo " listbox -t title -o \"option 1|option 2|option 3\" -r resultVariable -a '>'"
echo "Options:"
echo " -h, --help help"
echo " -t, --title list title"
echo " -o, --options \"option 1|option 2\" listbox options"
echo " -r, --result <var> result variable"
echo " -a, --arrow <symbol> selected option symbol"
return 0
;;
-o|--options)
local OIFS=$IFS;
IFS="|";
# check if zsh/bash
if [ -n "$ZSH_VERSION" ]; then
IFS=$'\n' opts=($(echo "$2" | tr "|" "\n"))
else
IFS="|" read -a opts <<< "$2";
fi
IFS=$OIFS;
shift
;;
-t|--title)
local title="$2"
shift
;;
-r|--result)
local __result="$2"
shift
;;
-a|--arrow)
local arrow="$2"
shift
;;
*)
esac
shift
done
if [[ -z $arrow ]]; then
arrow=">"
fi
local len=${#opts[@]}
local choice=0
local titleLen=${#title}
if [[ -n "$title" ]]; then
echo -e "\n $title"
printf " "
printf %"$titleLen"s | tr " " "-"
echo ""
fi
draw() {
local idx=0
for it in "${opts[@]}"
do
local str="";
if [ $idx -eq $choice ]; then
str+="$arrow "
else
str+=" "
fi
echo "$str$it"
idx=$((idx+1))
done
}
move() {
for it in "${opts[@]}"
do
tput cuu1
done
tput el1
}
listen() {
while true
do
key=$(bash -c "read -n 1 -s key; echo \$key")
if [[ $key = q ]]; then
break
elif [[ $key = B ]]; then
if [ $choice -lt $((len-1)) ]; then
choice=$((choice+1))
move
draw
fi
elif [[ $key = A ]]; then
if [ $choice -gt 0 ]; then
choice=$((choice-1))
move
draw
fi
elif [[ $key = "" ]]; then
# check if zsh/bash
if [ -n "$ZSH_VERSION" ]; then
choice=$((choice+1))
fi
if [[ -n $__result ]]; then
eval "$__result=\"${opts[$choice]}\""
else
echo -e "\n${opts[$choice]}"
fi
break
fi
done
}
draw
listen
}