summaryrefslogtreecommitdiff
path: root/src/jsMain/kotlin/moe/nea89/website/KConsole.kt
blob: c5850fcbdb2353882c8417920e35840ebf6487ae (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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package moe.nea89.website

import kotlinx.browser.window
import kotlinx.browser.document
import kotlinx.dom.addClass
import kotlinx.html.InputType
import kotlinx.html.dom.append
import kotlinx.html.dom.create
import kotlinx.html.js.input
import kotlinx.html.js.p
import kotlinx.html.js.pre
import kotlinx.html.js.span
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.HTMLParagraphElement
import org.w3c.dom.HTMLPreElement
import org.w3c.dom.events.EventType
import org.w3c.dom.events.KeyboardEvent
import org.w3c.dom.events.addEventHandler
import styled.injectGlobal
import kotlin.collections.set


class KConsole(
    val root: HTMLElement,
    val text: HTMLPreElement,
    val prompt: HTMLElement,
    fileSystem: KFileSystem?,
) {


    private lateinit var uninjectKeyHandler: () -> Unit
    val fileAccessor = fileSystem?.let { FileAccessor(it) }
    var wholecommand = ""
    var currenthistory = 0
    var commandHistory : Array<String> = emptyArray()
    var PS1: KConsole.() -> String = { "$" }
    private lateinit var mobileInput: HTMLInputElement

    companion object {

        init {
            injectGlobal(Styles.global)
        }

        val shlexRegex =
            """"([^"\\]+|\\.)+"|([^ "'\\]+|\\.)+|'([^'\\]+|\\.)+'""".toRegex()

        fun createFor(element: HTMLElement, fileSystem: KFileSystem? = null): KConsole {
            val text = element.append.pre()
            val prompt = text.append.p()
            prompt.addClass(Styles.promptClass)
            element.classList.add(Styles.consoleClass)
            val console = KConsole(element, text, prompt, fileSystem)
            console.uninjectKeyHandler =
                document.body!!.addEventHandler(EventType("keydown"), console::keydown)
            console.rerender()
            return console
        }
    }

    enum class ConsoleState {
        SHELLPROMPT,
        IN_PROGRAM
    }

    var state = ConsoleState.SHELLPROMPT

    var input: String = ""
    var justHandledInput = false
    fun openMobileKeyboardOnTap() {
        uninjectKeyHandler()
        mobileInput = this.root.append.input(InputType.text)
        mobileInput.classList.add(Styles.mobileFocusInput)
        mobileInput.onkeyup = this::keydown
        mobileInput.oninput = {
            input += it.data
            mobileInput.value = ""
            justHandledInput = true
            rerender()
            scrollDown()
        }
        root.onclick = {
            mobileInput.focus()
        }
    }

    fun addLines(newLines: List<String>) {
        newLines.forEach { addLine(it) }
    }

    fun addMultilineText(text: String) {
        addLines(text.split("\n"))
    }

    fun addLine(vararg elements: Any) {
        addLine(document.create.p().apply {
            elements.forEach {
                when (it) {
                    is HTMLElement -> append(it)
                    is ColoredElement -> append(document.create.span().also { el ->
                        el.style.color = it.color.color.toString()
                        el.append(it.text)
                    })

                    is String -> append(it)
                    else -> throw RuntimeException("Unknown element")
                }
            }
        })
    }

    private fun addLine(element: HTMLParagraphElement) {
        text.insertBefore(element, prompt)
    }

    fun rerender() {
        if (state == KConsole.ConsoleState.SHELLPROMPT) {
            prompt.innerText = "${PS1.invoke(this)} $input"
        } else {
            prompt.innerText = ""
        }
    }

    fun scrollDown() {
        text.lastElementChild?.scrollIntoView()
    }

    fun registerCommand(command: Command) {
        command.aliases.forEach {
            commands[it] = command
        }
        commands[command.name] = command
    }

    val commands = mutableMapOf<String, Command>()

    fun executeCommand(commandLine: String) {
        val parts = shlex(commandLine)
        if (parts == null) {
            addLine("Syntax Error")
            return
        }
        if (parts.isEmpty()) {
            return
        }
        val command = parts[0]
        wholecommand = ""
        println("whole command:")
        for (element in parts){
            wholecommand += element + " "
        }
        println(wholecommand)
        commandHistory += wholecommand

        val arguments = parts.drop(1)
        val commandThing = commands[command]
        if (commandThing == null) {
            addLine("Unknown command")
            return
        }
        ShellExecutionContext.run(this, commandThing, command, arguments)
        scrollDown()
    }

    fun shlex(command: String): List<String>? {
        var i = 0
        val parts = mutableListOf<String>()
        while (i < command.length) {
            val match = shlexRegex.matchAt(command, i)
            if (match == null) {
                println("Could not shlex: $command")
                return null
            }
            // TODO: Proper string unescaping
            parts.add(match.groupValues.drop(1).firstOrNull { it != "" } ?: "")
            i += match.value.length
            while (command[i] == ' ' && i < command.length)
                i++
        }
        return parts
    }

    fun handleSubmit() {
        currenthistory = 0
        val toExecute = input
        addLine("${PS1.invoke(this)} $toExecute")
        input = ""
        executeCommand(toExecute)
    }

    fun keydown(event: KeyboardEvent) {
        if (event.altKey || event.metaKey) return
        if (event.ctrlKey) {
            handleControlDown(event)
            return
        }
        if (event.keyCode == 38 || event.keyCode == 40) {
            handleArrowKeys(event)
        }
        if (event.isComposing) return
        if (state != ConsoleState.SHELLPROMPT) return
        if (justHandledInput) {
            justHandledInput = false
            return
        }
        val toHandle = if (event.keyCode == 229) {
            val x = (mobileInput.selectionStart ?: 1) - 1
            val v = mobileInput.value
            addLine("X: $x, V: $v")
            if (x < 0 || x >= v.length)
                return
            mobileInput.value = ""
            v[x]
        } else event.key
        when (toHandle) {
            "Enter" -> {
                handleSubmit()
            }

            "Backspace" -> input = input.substring(0, input.length - 1)
            else ->
                if (event.key.length == 1 || event.key.any { it !in 'a'..'z' && it !in 'A'..'Z' })
                    input += event.key
        }
        event.preventDefault()
        rerender()
        scrollDown()
    }


    fun handleControlDown(event: KeyboardEvent){
        if (event.key == "v"){
            event.preventDefault()
            window.navigator.clipboard.readText().then {
                input += it
                rerender()
                scrollDown()
            }
        }
    }
    fun handleArrowKeys(event: KeyboardEvent){
        if (event.keyCode == 40) {
            if (commandHistory.isEmpty() || currenthistory > commandHistory.size || currenthistory == 0){
                return
            }
            input = commandHistory[commandHistory.size-currenthistory]
            currenthistory -= 1
        }
        if (event.keyCode == 38) {
            if (commandHistory.isEmpty() || currenthistory == commandHistory.size){
                return
            }
            input = commandHistory[commandHistory.size-1-currenthistory]
            currenthistory += 1
        }
    }
}