Snippet: input_history Index

Intuitive text input history saving

Console windows aren't complete without the ability to save an easily traversible input history.

The technique I describe below isn't only useful in console windows. Chat applications can also utilize it effectively.

Outline

Consoles are made up of 2 main GUI components:

When I use a console interface I expect the following intuitive behavior:

Code

Here's code I wrote in Dart that achieves all these effects by utilizing key listeners:

List<String> scrollback = [""];
int scrollbackIndex = 0;
InputElement inputField = new InputElement(type: "text");

inputField
    ..onKeyDown.listen((KeyboardEvent event) {
        if (event.keyCode == KeyCode.UP || event.keyCode == KeyCode.DOWN) {
            event.preventDefault();
            if (event.keyCode == KeyCode.UP) scrollbackIndex = min(scrollbackIndex + 1, scrollback.length - 1);
            if (event.keyCode == KeyCode.DOWN) scrollbackIndex = max(scrollbackIndex - 1, 0);
            inputField.value = scrollback[scrollbackIndex];
        }
    })
    ..onKeyUp.listen((KeyboardEvent event) {
        if (KeyCode.isCharacterKey(event.keyCode)) {
            if (scrollbackIndex != 0) scrollbackIndex = 0;
            if (scrollbackIndex == 0) scrollback[0] = inputField.value.trim();
        }
    })
    ..onKeyPress.listen((KeyboardEvent event) {
        String input = inputField.value.replaceAll(new RegExp("\\s+"), " ");
        if (event.keyCode == KeyCode.ENTER && input.length != 0) {
            scrollback[0] = input;
            int index = scrollback.lastIndexOf(input);
            if (index != 0) scrollback.removeAt(index);
            scrollback.insert(0, "");
            scrollbackIndex = 0;
            inputField.value = "";
            evaluateCommand(input);
        }
    });

Variable breakdown

Key listener breakdown

Demo

Click here to check out a demo featuring the Dart code above.

Document Changelog

Share: circlefacebook circletwitterbird circlegoogleplus circlereddit