aboutsummaryrefslogtreecommitdiffstats
path: root/src/client/InputWithHistory.hx
blob: e41ec16f124f1bbd530ac617ed6278de832c8415 (plain) (blame)
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
package client;

import js.html.InputElement;
import js.html.KeyboardEvent;

class InputWithHistory {
	final element:InputElement;
	final maxItems:Int;
	final history:Array<String>;
	final onEnter:(value:String) -> Bool;
	var historyId = -1;

	public function new(
		element:InputElement,
		?history:Array<String>,
		maxItems:Int,
		onEnter:(value:String) -> Bool
	) {
		this.element = element;
		if (history != null) this.history = history;
		else this.history = [];
		this.maxItems = maxItems;
		this.onEnter = onEnter;
		element.onkeydown = onKeyDown;
	}

	public static function pushIfNotLast(arr:Array<String>, item:String):Void {
		final len = arr.length;
		if (len == 0 || arr[len - 1] != item) arr.push(item);
	}

	function onKeyDown(e:KeyboardEvent) {
		final key:KeyCode = cast e.keyCode;
		switch (key) {
			case Return:
				final value = element.value.trim();
				if (value.length == 0) return;
				final isAdd = onEnter(value);
				if (isAdd) pushIfNotLast(history, value);
				if (history.length > maxItems) history.shift();
				historyId = -1;
				element.value = "";
				onInput();
			case Up:
				historyId--;
				if (historyId == -2) {
					historyId = history.length - 1;
					if (historyId == -1) return;
				} else if (historyId == -1) historyId++;
				element.value = history[historyId];
				onInput();
			case Down:
				if (historyId == -1) return;
				historyId++;
				if (historyId > history.length - 1) {
					historyId = -1;
					element.value = "";
				} else {
					element.value = history[historyId];
				}
				onInput();
			default:
		}
	}

	function onInput():Void {
		if (element.oninput != null) element.oninput();
	}
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage