json-joy
Version:
Collection of libraries for building collaborative editing apps.
71 lines • 2.49 kB
JavaScript
import { ValueSyncStore } from '../../../util/events/sync-store';
class KeyPress {
key;
ts;
constructor(key, ts) {
this.key = key;
this.ts = ts;
}
}
/**
* Keeps track of all pressed down keys.
*/
export class KeyController {
dom;
/**
* All currently pressed keys.
*/
pressed = new Set();
/**
* History of last 5 pressed keys.
*/
history = new ValueSyncStore([]);
constructor(dom) {
this.dom = dom;
}
/** ----------------------------------------------------- {@link Printable} */
start() {
const onKeyDown = (event) => {
const key = event.key;
if (event.isComposing || key === 'Dead')
return;
const { pressed, history } = this;
pressed.add(key);
const press = new KeyPress(key, Date.now());
const historyList = history.value;
historyList.push(press);
if (historyList.length > 5)
historyList.shift();
history.next(historyList, true);
};
const onKeyUp = (event) => {
const key = event.key;
if (event.isComposing || key === 'Dead')
return;
this.pressed.delete(key);
};
const onReset = () => {
this.pressed.clear();
};
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
document.addEventListener('focus', onReset);
document.addEventListener('compositionstart', onReset);
document.addEventListener('compositionend', onReset);
const el = this.dom.el;
el.addEventListener('blur', onReset);
return () => {
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('keyup', onKeyUp);
document.removeEventListener('focus', onReset);
document.removeEventListener('compositionstart', onReset);
document.removeEventListener('compositionend', onReset);
el.removeEventListener('blur', onReset);
};
}
/** ----------------------------------------------------- {@link Printable} */
toString(tab) {
return `keys { hold: [ ${[...this.pressed].map((key) => JSON.stringify(key)).join(', ')}, hist: [ ${this.history.value.map((press) => JSON.stringify(press.key)).join(', ')} ] ] }`;
}
}
//# sourceMappingURL=KeyController.js.map