Skip to content

Commit

Permalink
feat: emit timestamp on input
Browse files Browse the repository at this point in the history
Allows subscribers to calculate input lag
  • Loading branch information
pauldps committed Aug 8, 2022
1 parent 5742250 commit e035646
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 8 deletions.
10 changes: 8 additions & 2 deletions src/BaseInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ export class BaseInput extends EventEmitter {
this.removeAllListeners()
}

process (action, down) {
/**
* @param {string} action
* @param {boolean} down
* @param {number} [timestamp]
* @returns
*/
process (action, down, timestamp = undefined) {
if (!this.enabled) {
return
}
if (DIRECTIONS.indexOf(action) >= 0) {
action = this.diagonalize(action, down)
}
this.emit('input', action, this)
this.emit('input', action, this, timestamp)
}

diagonalize (action, down) {
Expand Down
9 changes: 5 additions & 4 deletions src/KeyboardInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export class KeyboardInput extends BaseInput {
}

onKeyDown (event) {
var timestamp = Date.now()
if (event.repeat === true) { // Supported by some browsers
return
}
Expand All @@ -40,20 +41,21 @@ export class KeyboardInput extends BaseInput {
return
}
this.actionsDown.set(action, true)
this.process(action, true)
this.process(action, true, timestamp)
}

onKeyUp (event) {
var timestamp = Date.now()
var action = this.capture(event, false)
if (!action) {
return
}
this.actionsDown.set(action.toUpperCase(), false)
this.process(action, false)
this.process(action, false, timestamp)
}

onWindowBlur (_event) {
this.process('5') // resets directional state
this.process('5', false, Date.now()) // resets directional state
this.actionsDown.clear()
}

Expand All @@ -64,7 +66,6 @@ export class KeyboardInput extends BaseInput {
* @param {boolean} down - `true` if key is being held down.
*/
capture (event, down) {
// console.log('Capture Start', Date.now())
var code = event.code
if (code) {
return this.captureCode(code, down, event)
Expand Down
4 changes: 2 additions & 2 deletions test/BaseInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,9 @@ describe('BaseInput', function () {
describe('button', function () {
it('emits buttons correctly', function () {
for (var button of BUTTONS) {
this.input.process(button)
this.input.process(button, true)
expect(events[0][1]).to.equal(button)
this.input.process(button.toLowerCase())
this.input.process(button.toLowerCase(), false)
expect(events[0][1]).to.equal(button.toLowerCase())
}
})
Expand Down

0 comments on commit e035646

Please sign in to comment.