diff options
| author | RblSb <msrblsb@gmail.com> | 2020-04-07 02:59:56 +0300 |
|---|---|---|
| committer | RblSb <msrblsb@gmail.com> | 2020-04-07 03:07:13 +0300 |
| commit | 9e358f7c4b9536dd9fadd3fee3a52305b9a98364 (patch) | |
| tree | 151e76cb69786cbe0eaa02ca988a3a197920bbac /src/client/InputWithHistory.hx | |
| parent | 4c955af4c4be0d3c1d002a867c89166811373a9f (diff) | |
Links history
Diffstat (limited to 'src/client/InputWithHistory.hx')
| -rw-r--r-- | src/client/InputWithHistory.hx | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/src/client/InputWithHistory.hx b/src/client/InputWithHistory.hx new file mode 100644 index 0000000..9c5b615 --- /dev/null +++ b/src/client/InputWithHistory.hx @@ -0,0 +1,54 @@ +package client; + +import js.html.KeyboardEvent; +import js.html.InputElement; + +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; + } + + function onKeyDown(e:KeyboardEvent) { + switch (e.keyCode) { + case 13: // Enter + if (element.value.length == 0) return; + final isAdd = onEnter(element.value); + if (isAdd) history.push(element.value); + if (history.length > maxItems) history.shift(); + historyId = -1; + element.value = ""; + case 38: // Up + historyId--; + if (historyId == -2) { + historyId = history.length - 1; + if (historyId == -1) return; + } else if (historyId == -1) historyId++; + element.value = history[historyId]; + case 40: // Down + if (historyId == -1) return; + historyId++; + if (historyId > history.length - 1) { + historyId = -1; + element.value = ""; + return; + } + element.value = history[historyId]; + } + } + +} |
