-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcursorable.rb
79 lines (69 loc) · 1.36 KB
/
cursorable.rb
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
require "io/console"
module Cursorable
KEYMAP = {
" " => :space,
"h" => :left,
"j" => :down,
"k" => :up,
"l" => :right,
"w" => :up,
"a" => :left,
"s" => :down,
"d" => :right,
"\t" => :tab,
"\r" => :return,
"\n" => :newline,
"\e" => :escape,
"\e[A" => :up,
"\e[B" => :down,
"\e[C" => :right,
"\e[D" => :left,
"\177" => :backspace,
"\004" => :delete,
"\u0003" => :ctrl_c,
}
MOVES = {
left: [0, -1],
right: [0, 1],
up: [-1, 0],
down: [1, 0]
}
def get_input
key = KEYMAP[read_char]
handle_key(key)
end
def handle_key(key)
case key
when :ctrl_c
exit 0
when :return, :space
@cursor_pos
when :left, :right, :up, :down
update_pos(MOVES[key])
nil
else
puts key
end
end
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
def update_pos(diff)
new_pos = [@cursor_pos[0] + diff[0], @cursor_pos[1] + diff[1]]
@cursor_pos = new_pos if in_bounds?(new_pos)
end
def in_bounds?(pos)
return true if pos[0] <= 7 && pos[0] >= 0 && pos[1] <= 7 && pos[1] >= 0
false
end
end