refactor: ui owns key input

This commit is contained in:
cha0s 2024-05-26 12:33:52 -05:00
parent 243574ff79
commit 872a001877
3 changed files with 32 additions and 25 deletions

View File

@ -1,6 +1,6 @@
// Handle lame OS key input event behavior. See: https://mzl.la/2Ob0WQE // Handle lame OS key input event behavior. See: https://mzl.la/2Ob0WQE
// Also "up" all keys on blur. // Also "up" all keys on blur.
export default function addKeyInputListener(target, listener) { export default function addKeyListener(target, listener) {
let keysDown = {}; let keysDown = {};
let keyUpDelays = {}; let keyUpDelays = {};
function setAllKeysUp() { function setAllKeysUp() {

View File

@ -1,11 +1,42 @@
import {useContext, useEffect} from 'react';
import addKeyListener from '../add-key-listener.js';
import {RESOLUTION} from '../constants'; import {RESOLUTION} from '../constants';
import ServerContext from '../context/server';
import Dom from './dom'; import Dom from './dom';
import Pixi from './pixi'; import Pixi from './pixi';
import styles from './ui.module.css'; import styles from './ui.module.css';
const ratio = RESOLUTION[0] / RESOLUTION[1]; const ratio = RESOLUTION[0] / RESOLUTION[1];
// Handle input.
const ACTION_MAP = {
w: 'moveUp',
d: 'moveRight',
s: 'moveDown',
a: 'moveLeft',
};
const KEY_MAP = {
keyDown: 1,
keyUp: 0,
};
export default function Ui() { export default function Ui() {
// Key input.
const server = useContext(ServerContext);
useEffect(() => {
return addKeyListener(document.body, ({type, payload}) => {
if (type in KEY_MAP && payload in ACTION_MAP) {
server.send({
type: 'action',
payload: {
type: ACTION_MAP[payload],
value: KEY_MAP[type],
},
});
}
});
});
return ( return (
<div className={styles.ui}> <div className={styles.ui}>
<style> <style>

View File

@ -1,7 +1,6 @@
import {createElement} from 'react'; import {createElement} from 'react';
import {createRoot} from 'react-dom/client'; import {createRoot} from 'react-dom/client';
import addKeyInputListener from './add-key-input-listener.js';
import Silphius from './components/silphius.jsx'; import Silphius from './components/silphius.jsx';
import ServerContext from './context/server.js'; import ServerContext from './context/server.js';
@ -13,29 +12,6 @@ const server = new Server();
await server.connect(); await server.connect();
server.send({type: 'connect'}); server.send({type: 'connect'});
// Handle input.
const ACTION_MAP = {
w: 'moveUp',
d: 'moveRight',
s: 'moveDown',
a: 'moveLeft',
};
const KEY_MAP = {
keyDown: 1,
keyUp: 0,
};
addKeyInputListener(document.body, ({type, payload}) => {
if (type in KEY_MAP && payload in ACTION_MAP) {
server.send({
type: 'action',
payload: {
type: ACTION_MAP[payload],
value: KEY_MAP[type],
},
});
}
});
// Setup DOM. // Setup DOM.
createRoot(document.querySelector('.silphius')) createRoot(document.querySelector('.silphius'))
.render( .render(