Files
Robot-Clash/game/kit/kit-input.js

74 lines
3.1 KiB
JavaScript
Raw Permalink Normal View History

2026-11-13 00:41:54 +01:00
/* Kit input (v1) - keyboard + touch buttons mapped to actions. From _Tools\Library\web\kit.
const input = Kit.input({
keys: { ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left',
ArrowRight: 'right', d: 'right', ' ': 'action', p: 'pause', Escape: 'pause', m: 'mute' },
onPress(action, e) {}, // first press only (no key repeat)
onRelease(action) {},
});
input.down('left') is it held right now?
input.latest(['up','right','down','left']) most recently pressed of these that is still held
input.consume('action') true once per press (polling style inside update())
Touch buttons: any element with data-action="left" works like the key (pointer capture,
so sliding off the button releases it). Typing into <input>/<textarea> is ignored.
Keys are matched case-insensitively for letters. */
(function (root) {
'use strict';
const Kit = (root.Kit = root.Kit || {});
Kit.input = (opt = {}) => {
const map = {};
for (const [k, a] of Object.entries(opt.keys || {})) map[k.length === 1 ? k.toLowerCase() : k] = a;
const held = [], pressed = new Set();
const api = {};
function press(a, e) {
const i = held.indexOf(a);
if (i >= 0) return; // already held (key repeat)
held.push(a); pressed.add(a);
opt.onPress && opt.onPress(a, e);
}
function release(a) {
const i = held.indexOf(a);
if (i < 0) return;
held.splice(i, 1);
opt.onRelease && opt.onRelease(a);
}
const typing = e => e.target && /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName);
const keyOf = e => (e.key.length === 1 ? e.key.toLowerCase() : e.key);
addEventListener('keydown', e => {
if (typing(e)) return;
const a = map[keyOf(e)];
if (!a) return;
e.preventDefault();
if (!e.repeat) press(a, e);
});
addEventListener('keyup', e => { const a = map[keyOf(e)]; if (a) release(a); });
addEventListener('blur', () => { while (held.length) release(held[held.length - 1]); });
api.bindButtons = (scope = document) => {
scope.querySelectorAll('[data-action]').forEach(b => {
if (b._kitBound) return;
b._kitBound = true;
const a = b.dataset.action;
b.addEventListener('pointerdown', e => { e.preventDefault(); b.setPointerCapture(e.pointerId); press(a, e); });
b.addEventListener('pointerup', () => release(a));
b.addEventListener('pointercancel', () => release(a));
b.addEventListener('contextmenu', e => e.preventDefault());
});
};
if (typeof document !== 'undefined') {
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.bindButtons());
else api.bindButtons();
}
api.down = a => held.includes(a);
api.latest = list => { for (let i = held.length - 1; i >= 0; i--) if (list.includes(held[i])) return held[i]; return null; };
api.consume = a => pressed.delete(a);
api.clear = () => { held.length = 0; pressed.clear(); };
return api;
};
})(typeof window !== 'undefined' ? window : globalThis);