| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | export const cageWheelEncoding = -57345; |
| 9 | export const cageWheelCapability = 'cage-wheel-v1'; |
| 10 | export const cageWheelMessage = 180; |
| 11 | export const cageWheelLimit = 2048; |
| 12 | |
| 13 | |
| 14 | export function cageWheelPacket(x, y, dx, dy) { |
| 15 | const packet = new Uint8Array(14), view = new DataView(packet.buffer); |
| 16 | packet[0] = cageWheelMessage; |
| 17 | view.setUint16(2, x); |
| 18 | view.setUint16(4, y); |
| 19 | view.setInt32(6, dx); |
| 20 | view.setInt32(10, dy); |
| 21 | return packet; |
| 22 | } |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | export default class CageWheel { |
| 28 | constructor(send, schedule = callback => requestAnimationFrame(callback), |
| 29 | cancel = handle => cancelAnimationFrame(handle)) { |
| 30 | this._send = send; |
| 31 | this._schedule = schedule; |
| 32 | this._cancel = cancel; |
| 33 | this._x = this._y = this._dx = this._dy = 0; |
| 34 | this._frame = null; |
| 35 | } |
| 36 | |
| 37 | add(x, y, dx, dy) { |
| 38 | this._x = x; |
| 39 | this._y = y; |
| 40 | this._dx += dx; |
| 41 | this._dy += dy; |
| 42 | if (this._frame === null) this._flush(); |
| 43 | } |
| 44 | |
| 45 | _flush() { |
| 46 | this._frame = null; |
| 47 | const dx = Math.max(-cageWheelLimit, Math.min(cageWheelLimit, Math.round(this._dx))); |
| 48 | const dy = Math.max(-cageWheelLimit, Math.min(cageWheelLimit, Math.round(this._dy))); |
| 49 | |
| 50 | if (!dx && !dy) return; |
| 51 | this._dx -= dx; |
| 52 | this._dy -= dy; |
| 53 | this._send(this._x, this._y, dx, dy); |
| 54 | this._frame = this._schedule(() => this._flush()); |
| 55 | } |
| 56 | |
| 57 | stop() { |
| 58 | if (this._frame !== null) this._cancel(this._frame); |
| 59 | this._frame = null; |
| 60 | this._dx = this._dy = 0; |
| 61 | } |
| 62 | } |