diff --git a/internal/ui/input.go b/internal/ui/input.go index a4c951849..5c6f5422f 100644 --- a/internal/ui/input.go +++ b/internal/ui/input.go @@ -33,25 +33,6 @@ func CursorPosition() (x, y int) { return current.input.cursorPosition() } -type input struct { - keyPressed [KeyMax]bool - mouseButtonPressed [MouseButtonMax]bool - cursorX int - cursorY int -} - -func (i *input) isKeyPressed(key Key) bool { - return i.keyPressed[key] -} - -func (i *input) isMouseButtonPressed(button MouseButton) bool { - return i.mouseButtonPressed[button] -} - -func (i *input) cursorPosition() (x, y int) { - return i.cursorX, i.cursorY -} - var glfwKeyCodeToKey = map[glfw.Key]Key{ glfw.KeySpace: KeySpace, glfw.KeyLeft: KeyLeft, diff --git a/internal/ui/input_js.go b/internal/ui/input_js.go index af81cca86..7acce39ae 100644 --- a/internal/ui/input_js.go +++ b/internal/ui/input_js.go @@ -16,17 +16,34 @@ package ui +var keyCodeToKey = map[int]Key{ + 32: KeySpace, + 37: KeyLeft, + 39: KeyRight, + 38: KeyUp, + 40: KeyDown, +} + +var currentInput input + func IsKeyPressed(key Key) bool { - // TODO: Implement this. - return false + return currentInput.isKeyPressed(key) } func IsMouseButtonPressed(button MouseButton) bool { - // TODO: Implement this. - return false + return currentInput.isMouseButtonPressed(button) } func CursorPosition() (x, y int) { - // TODO: Implement this. - return 0, 0 + return currentInput.cursorPosition() +} + +func (i *input) keyDown(key int) { + k := keyCodeToKey[key] + i.keyPressed[k] = true +} + +func (i *input) keyUp(key int) { + k := keyCodeToKey[key] + i.keyPressed[k] = false } diff --git a/internal/ui/keys.go b/internal/ui/keys.go index d7eb93bf7..ad157cade 100644 --- a/internal/ui/keys.go +++ b/internal/ui/keys.go @@ -33,3 +33,22 @@ const ( MouseButtonMiddle MouseButtonMax ) + +type input struct { + keyPressed [KeyMax]bool + mouseButtonPressed [MouseButtonMax]bool + cursorX int + cursorY int +} + +func (i *input) isKeyPressed(key Key) bool { + return i.keyPressed[key] +} + +func (i *input) isMouseButtonPressed(button MouseButton) bool { + return i.mouseButtonPressed[button] +} + +func (i *input) cursorPosition() (x, y int) { + return i.cursorX, i.cursorY +} diff --git a/internal/ui/ui_js.go b/internal/ui/ui_js.go index bfe894d46..ad64f4b33 100644 --- a/internal/ui/ui_js.go +++ b/internal/ui/ui_js.go @@ -66,6 +66,21 @@ func init() { panic(err) } context = opengl.NewContext(webglContext) + + // Make the canvas focusable. + canvas.Call("setAttribute", "tabindex", 1) + canvas.Get("style").Set("outline", "none") + + canvas.Set("onkeydown", func(e js.Object) { + defer e.Call("preventDefault") + code := e.Get("keyCode").Int() + currentInput.keyDown(code) + }) + canvas.Set("onkeyup", func(e js.Object) { + defer e.Call("preventDefault") + code := e.Get("keyCode").Int() + currentInput.keyUp(code) + }) } func Start(width, height, scale int, title string) (actualScale int, err error) {