summary refs log tree commit diff
path: root/wip-v2.ts
blob: 0f701a0e896db99e800844523aa66a51fbfc104d (plain)
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import readline, { Key } from 'node:readline';
import chalk from "chalk";

readline.emitKeypressEvents(process.stdin);

const logs: string[] = [];

function onexit() {
    console.clear()
    console.log("\nQuitting meower CL")
    for (const log of logs) {
        console.log(log)
    }
}

abstract class Element {
    focusable: boolean = false;
    focused: boolean = false;
    screen: Screen;
    abstract render(): void;
    onkeypres(key: Key): void {};
}

class Text extends Element {
    text: string;
    constructor(text: string) {
        super();
        this.text = text;
    }
    render() {
        process.stdout.write(this.text)
    }
}

class Input extends Element {
    focusable: boolean = true;
    value: string = "";

    isPassword: boolean = false;

    render(): void {
        let text = this.value
        if (this.isPassword) text = text.replace(/[^]/g, '*');
        if (this.focused) text += "_"
        console.log(text)
    }

    onkeypres(key: Key): void {
        //@ts-ignore
        if (key.meta || key.code || ["return", "backspace"].includes(key.name)) {
            switch (key.name) {
                case "return":
                    this.focused = false;
                    const focusableIDs = Object.keys(this.screen.getFocusable());
                    const focusedIndex = focusableIDs.indexOf(this.screen.focusedElementId);
                    this.screen.focus(focusableIDs[(focusedIndex - 1) % focusableIDs.length]);
                    break;
                
                case "backspace":
                    const prevValue = '' + this.value
                    // logs.push(`doing backspace : before ${prevValue}, after ${prevValue.substring(0, prevValue.length - 1)} : 0-${prevValue.length - 1}`)
                    this.value = prevValue.substring(0, prevValue.length - 1)
                    break;
            }
            return;
        }
        if (!key.sequence || key.sequence.length > 1 || key.name != key.sequence?.toLowerCase()) return;
        this.value += key.sequence;
    }

    constructor(isPassword: boolean, ) {
        super()
        this.isPassword = isPassword
    }
}

class Button extends Text {
    focusable: boolean = true;
    constructor (text: string) {
        super(text)
    }
    render(): void {
        console.log(`(${(this.focused ? chalk.bgWhite : a=>a)(this.text)})`)
    }
}

class Screen {
    elements: Map<string, Element> = new Map<string, Element>();
    name: string;
    focusedElementId: string = '';
    constructor(name: string) {
        this.name = name
    }
    addElement(name: string, element: Element) {
        if(this.elements.has(name)) throw new Error();
        element.screen = this;
        this.elements.set(name, element);
    }
    render() {
        console.clear()
        this.elements.forEach(element => {
            element.render()
        });
    }

    getFocusable() {
        return Object.fromEntries([...this.elements.entries()].filter(([k, v]) => v.focusable))
    }

    getElements() {
        return Object.fromEntries([...this.elements.entries()])
    }

    focus(id: string) {
        this.elements.forEach(e => e.focused = false);
        const focusElem = this.elements.get(id) as Element
        focusElem.focused = true;
        this.focusedElementId = id
    }

    getFocusedElement(): Element|undefined {
        return this.focusedElementId ? this.elements.get(this.focusedElementId) as Element : undefined
    }
}

// TODO: add focus change with arrows

const screen = new Screen("login");
screen.addElement('username-label', new Text("Username: \n"));
screen.addElement('username-input', new Input(false))
screen.addElement('password-label', new Text("Password: \n"));
screen.addElement('password-input', new Input(true))
screen.addElement('done-btn', new Button("Done"))

screen.focus('username-input')

if (process.stdin.isTTY) process.stdin.setRawMode(true); // makes the terminal send stdin without the user pressing enter

process.stdin.on('keypress', (chunk, key) => {
    const focusableIDs = Object.keys(screen.getFocusable());
    const focusedIndex = focusableIDs.indexOf(screen.focusedElementId);
    if (key && key.name == 'escape') {
        onexit();
        process.exit();
    }
    
    if (['up', 'left'].includes(key.name)) {
        // logs.push(`Got up key, moving focus upward ${focusedIndex} ${(focusedIndex - 1) % focusableIDs.length}`)
        screen.focus(focusableIDs[(focusedIndex - 1) % focusableIDs.length]);
        return screen.render()
    }
    if (['down', 'right'].includes(key.name)) {
        // logs.push(`Got down key, moving focus downward ${focusedIndex} ${(focusedIndex + 1) % focusableIDs.length}`)
        screen.focus(focusableIDs[(focusedIndex + 1) % focusableIDs.length]);
        return screen.render()
    }

    // logs.push("pressed key, data: " + JSON.stringify(key))
    if (!screen.focusedElementId) return;
    const focusedElement = screen.getFocusedElement();
    focusedElement?.onkeypres(key)
    screen.render()
});
screen.render()