@margoengine/input 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ import type { Binding, InputFeed } from './index.js';
2
+ /**
3
+ * A recording, safe to `JSON.stringify` into a file. Only changes are stored, so a held key costs nothing per tick.
4
+ * Written by {@link InputRecorder.clip}; {@link InputReplay} checks all of it, so a clip may come from anywhere.
5
+ */
6
+ export interface InputClip {
7
+ version: 1;
8
+ /** What each channel holds: action name and binding index. */
9
+ channels: [action: string, binding: number][];
10
+ /** Milliseconds since the first tick, one number per tick. */
11
+ times: number[];
12
+ /** Flat triples of tick, channel and new value, in tick order. */
13
+ events: number[];
14
+ }
15
+ /** What {@link InputRecorder} reads: an `Input`, or anything with the same two members. */
16
+ export interface RecordSource {
17
+ readonly actions: Readonly<Record<string, readonly Binding[]>>;
18
+ bindingValue(action: string, binding: number): number;
19
+ }
20
+ /** What {@link InputReplay} plays into: an `Input`, or anything with the same two members. */
21
+ export interface ReplayTarget {
22
+ readonly actions: Readonly<Record<string, readonly Binding[]>>;
23
+ setFeed(feed: InputFeed | null): void;
24
+ }
25
+ /** Options for {@link InputReplay}. */
26
+ export interface ReplayOptions {
27
+ /** Start again at the end, for an attract mode. `finished` then waits for `stop`. Default false. */
28
+ loop?: boolean;
29
+ /** Stops the replay; `finished` rejects with the reason. */
30
+ signal?: AbortSignal;
31
+ }
32
+ /**
33
+ * Records what every binding of an `Input` gave, tick by tick.
34
+ *
35
+ * ```ts
36
+ * const recorder = new InputRecorder(input);
37
+ * input.update();
38
+ * recorder.capture(); // once per tick, after input.update()
39
+ * localStorage.setItem('demo', JSON.stringify(recorder.clip()));
40
+ * ```
41
+ */
42
+ export declare class InputRecorder {
43
+ private readonly source;
44
+ private readonly now;
45
+ private readonly channels;
46
+ private readonly ids;
47
+ private readonly last;
48
+ private readonly times;
49
+ private readonly events;
50
+ private start;
51
+ /** @param options.now Clock in milliseconds. Default `performance.now`. */
52
+ constructor(input: RecordSource, { now }?: {
53
+ now?: () => number;
54
+ });
55
+ /** Ticks captured so far. */
56
+ get frames(): number;
57
+ /** Note this tick. Call once per tick, after `input.update()`. */
58
+ capture(): void;
59
+ /** Copy of what was recorded so far. Recording can go on. */
60
+ clip(): InputClip;
61
+ }
62
+ /**
63
+ * Plays a clip into an `Input`: each `input.update()` takes one recorded tick in place of the devices, and everything
64
+ * reading that Input (the game, `Interactions`) runs as it did live. At the end the Input goes back to its devices.
65
+ *
66
+ * ```ts
67
+ * const replay = new InputReplay(input, localStorage.getItem('demo')!);
68
+ * await replay.finished;
69
+ * ```
70
+ */
71
+ export declare class InputReplay implements InputFeed {
72
+ /** Resolves when the clip has played or {@link InputReplay.stop} was called; rejects when `signal` aborts. */
73
+ readonly finished: Promise<void>;
74
+ private readonly input;
75
+ private readonly clip;
76
+ private readonly loop;
77
+ private readonly signal;
78
+ private readonly table;
79
+ private readonly values;
80
+ private tick;
81
+ private cursor;
82
+ private offset;
83
+ private done;
84
+ private resolve;
85
+ private reject;
86
+ private readonly abort;
87
+ /**
88
+ * @param clip What {@link InputRecorder.clip} gave, or its JSON text.
89
+ * @throws TypeError for a clip that fails its checks, or one with an action this Input does not have.
90
+ */
91
+ constructor(input: ReplayTarget, clip: InputClip | string, { loop, signal }?: ReplayOptions);
92
+ /** The tick playing, from 0, or -1 before the first update. */
93
+ get frame(): number;
94
+ /** Ticks in the clip. */
95
+ get frames(): number;
96
+ /**
97
+ * Recorded time of this tick in milliseconds, growing across loops. Give it to whatever reads a clock, so timing
98
+ * rules replay exactly: `new Interactions(input, rules, { now: () => replay.time })`.
99
+ */
100
+ get time(): number;
101
+ /** Stop now and hand the Input back to its devices. `finished` resolves. Idempotent. */
102
+ stop(): void;
103
+ [Symbol.dispose]: () => void;
104
+ /** @internal Called by `Input.update`. */
105
+ begin(): void;
106
+ /** @internal Called by `Input.update`. */
107
+ read(action: string, binding: number): number;
108
+ private finish;
109
+ }
package/dist/replay.js ADDED
@@ -0,0 +1,99 @@
1
+ //#region src/replay.ts
2
+ var e = class {
3
+ constructor(e, { now: t = () => performance.now() } = {}) {
4
+ if (this.channels = [], this.ids = /* @__PURE__ */ new Map(), this.last = [], this.times = [], this.events = [], this.start = 0, typeof e?.bindingValue != "function" || !e.actions) throw TypeError("InputRecorder reads an Input; pass one as the first argument");
5
+ this.source = e, this.now = t;
6
+ }
7
+ get frames() {
8
+ return this.times.length;
9
+ }
10
+ capture() {
11
+ let e = this.times.length, t = this.now();
12
+ e || (this.start = t), this.times.push(t - this.start);
13
+ let n = this.source.actions;
14
+ for (let t of Object.keys(n)) {
15
+ let r = this.ids.get(t) ?? [], i = n[t].length;
16
+ this.ids.set(t, r);
17
+ for (let n = 0; n < i; n++) {
18
+ let i = r[n] ??= this.channels.push([t, n]) - 1, a = this.source.bindingValue(t, n);
19
+ a !== (this.last[i] ?? 0) && (this.last[i] = a, this.events.push(e, i, a));
20
+ }
21
+ }
22
+ }
23
+ clip() {
24
+ return {
25
+ version: 1,
26
+ channels: this.channels.map(([e, t]) => [e, t]),
27
+ times: [...this.times],
28
+ events: [...this.events]
29
+ };
30
+ }
31
+ };
32
+ function t(e) {
33
+ return /* @__PURE__ */ TypeError(`Invalid input clip: ${e}; use what InputRecorder.clip() wrote`);
34
+ }
35
+ function n(e) {
36
+ let n;
37
+ try {
38
+ n = typeof e == "string" ? JSON.parse(e) : e;
39
+ } catch {
40
+ throw t("not JSON");
41
+ }
42
+ if (!n || n.version !== 1) throw t("unknown version");
43
+ let { channels: r, times: i, events: a } = n;
44
+ if (!Array.isArray(r) || !Array.isArray(i) || !Array.isArray(a) || a.length % 3) throw t("missing lists");
45
+ for (let e of r) if (!Array.isArray(e) || typeof e[0] != "string" || !Number.isInteger(e[1]) || e[1] < 0) throw t("bad channel");
46
+ for (let e = 0; e < i.length; e++) if (!Number.isFinite(i[e]) || e > 0 && i[e] < i[e - 1]) throw t("times out of order");
47
+ for (let e = 0, n = 0; e < a.length; e += 3) {
48
+ let o = a[e], s = a[e + 1];
49
+ if (!Number.isInteger(o) || o < n || o >= i.length) throw t("tick out of order");
50
+ if (!Number.isInteger(s) || s < 0 || s >= r.length) throw t("unknown channel");
51
+ if (!Number.isFinite(a[e + 2])) throw t("value not finite");
52
+ n = o;
53
+ }
54
+ return n;
55
+ }
56
+ var r = class {
57
+ constructor(e, t, { loop: r = !1, signal: i } = {}) {
58
+ if (this.table = /* @__PURE__ */ new Map(), this.tick = -1, this.cursor = 0, this.offset = 0, this.done = !1, this.abort = () => this.finish(this.signal.reason ?? new DOMException("Aborted", "AbortError")), typeof e?.setFeed != "function" || !e.actions) throw TypeError("InputReplay plays into an Input; pass one as the first argument");
59
+ this.input = e, this.clip = n(t), this.loop = r, this.signal = i, this.values = new Float64Array(this.clip.channels.length), this.clip.channels.forEach(([t, n], r) => {
60
+ if (!Object.hasOwn(e.actions, t)) throw TypeError(`Input clip has an action this Input lacks, ${t}; add it to the actions`);
61
+ (this.table.get(t) ?? this.table.set(t, []).get(t))[n] = r;
62
+ }), this.finished = new Promise((e, t) => {
63
+ this.resolve = e, this.reject = t;
64
+ }), this.finished.catch(() => {}), i?.aborted ? this.abort() : (i?.addEventListener("abort", this.abort, { once: !0 }), e.setFeed(this));
65
+ }
66
+ get frame() {
67
+ return this.tick;
68
+ }
69
+ get frames() {
70
+ return this.clip.times.length;
71
+ }
72
+ get time() {
73
+ return this.offset + (this.clip.times[Math.max(this.tick, 0)] ?? 0);
74
+ }
75
+ stop() {
76
+ this.finish();
77
+ }
78
+ [Symbol.dispose ?? Symbol()]() {
79
+ this.stop();
80
+ }
81
+ begin() {
82
+ let { times: e, events: t } = this.clip;
83
+ if (this.tick + 1 >= e.length) {
84
+ if (!this.loop || !e.length) return this.finish();
85
+ let t = e[e.length - 1];
86
+ this.offset += t + (e.length > 1 ? t - e[e.length - 2] : 0), this.tick = -1, this.cursor = 0, this.values.fill(0);
87
+ }
88
+ for (this.tick++; this.cursor < t.length && t[this.cursor] === this.tick;) this.values[t[this.cursor + 1]] = t[this.cursor + 2], this.cursor += 3;
89
+ }
90
+ read(e, t) {
91
+ let n = this.table.get(e)?.[t];
92
+ return n === void 0 ? 0 : this.values[n];
93
+ }
94
+ finish(e) {
95
+ this.done || (this.done = !0, this.signal?.removeEventListener("abort", this.abort), this.input.setFeed(null), e === void 0 ? this.resolve() : this.reject(e));
96
+ }
97
+ };
98
+ //#endregion
99
+ export { e as InputRecorder, r as InputReplay };
@@ -0,0 +1,459 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/gestures.ts
3
+ var t = class {
4
+ constructor(e, t = {}) {
5
+ this.element = e, this.pointers = /* @__PURE__ */ new Map(), this.handlers = /* @__PURE__ */ new Map(), this.cleanups = [], this.lastTap = null, this.moved = !1, this.multi = !1, this.disposed = !1, this.o = {
6
+ swipeDistance: 40,
7
+ swipeVelocity: 300,
8
+ tapTime: 250,
9
+ tapSlop: 10,
10
+ doubleTapTime: 300,
11
+ now: () => performance.now(),
12
+ ...t
13
+ };
14
+ for (let [e, t] of Object.entries(this.o)) if (e === "now" ? typeof t != "function" : !(Number.isFinite(t) && t > 0)) throw RangeError(`Invalid gesture option ${e}; thresholds must be positive numbers and now a function`);
15
+ this.listen("pointerdown", (e) => this.down(e)), this.listen("pointermove", (e) => this.move(e)), this.listen("pointerup", (e) => this.up(e)), this.listen("pointercancel", (e) => {
16
+ this.pointers.delete(e.pointerId);
17
+ });
18
+ }
19
+ listen(e, t) {
20
+ this.element.addEventListener(e, t), this.cleanups.push(() => this.element.removeEventListener(e, t));
21
+ }
22
+ on(t, n) {
23
+ if (this.disposed) throw new e("disposed", "Gestures is disposed; create a new Gestures");
24
+ let r = this.handlers.get(t) ?? this.handlers.set(t, /* @__PURE__ */ new Set()).get(t);
25
+ return r.add(n), () => r.delete(n);
26
+ }
27
+ emit(e) {
28
+ for (let t of this.handlers.get(e.type) ?? []) t(e);
29
+ }
30
+ down(e) {
31
+ if (e.pointerType === "mouse") return;
32
+ let t = this.o.now();
33
+ this.pointers.size === 0 && (this.moved = this.multi = !1), this.pointers.set(e.pointerId, {
34
+ x: e.clientX,
35
+ y: e.clientY,
36
+ startX: e.clientX,
37
+ startY: e.clientY,
38
+ startTime: t
39
+ }), this.pointers.size > 1 && (this.multi = !0);
40
+ }
41
+ move(e) {
42
+ let t = this.pointers.get(e.pointerId);
43
+ if (t) {
44
+ if (Math.hypot(e.clientX - t.startX, e.clientY - t.startY) > this.o.tapSlop && (this.moved = !0), this.pointers.size === 2) {
45
+ let [n, r] = [...this.pointers.values()], i = {
46
+ dx: r.x - n.x,
47
+ dy: r.y - n.y
48
+ };
49
+ t.x = e.clientX, t.y = e.clientY;
50
+ let a = {
51
+ dx: r.x - n.x,
52
+ dy: r.y - n.y
53
+ }, o = Math.hypot(i.dx, i.dy), s = Math.hypot(a.dx, a.dy), c = (n.x + r.x) / 2, l = (n.y + r.y) / 2;
54
+ o > 0 && s > 0 && o !== s && this.emit({
55
+ type: "pinch",
56
+ x: c,
57
+ y: l,
58
+ scale: s / o
59
+ });
60
+ let u = Math.atan2(a.dy, a.dx) - Math.atan2(i.dy, i.dx);
61
+ u = Math.atan2(Math.sin(u), Math.cos(u)), o > 0 && s > 0 && u !== 0 && this.emit({
62
+ type: "rotate",
63
+ x: c,
64
+ y: l,
65
+ rotation: u
66
+ });
67
+ } else t.x = e.clientX, t.y = e.clientY;
68
+ }
69
+ }
70
+ up(e) {
71
+ let t = this.pointers.get(e.pointerId);
72
+ if (!t) return;
73
+ let n = this.pointers.size === 1;
74
+ if (this.pointers.delete(e.pointerId), !n || this.multi) return;
75
+ let r = this.o.now(), i = Math.max(1, r - t.startTime), a = e.clientX - t.startX, o = e.clientY - t.startY, s = Math.hypot(a, o);
76
+ if (!this.moved && i <= this.o.tapTime) {
77
+ let t = this.lastTap;
78
+ t && r - t.time <= this.o.doubleTapTime && Math.hypot(e.clientX - t.x, e.clientY - t.y) <= this.o.tapSlop * 3 ? (this.lastTap = null, this.emit({
79
+ type: "doubletap",
80
+ x: e.clientX,
81
+ y: e.clientY
82
+ })) : (this.lastTap = {
83
+ x: e.clientX,
84
+ y: e.clientY,
85
+ time: r
86
+ }, this.emit({
87
+ type: "tap",
88
+ x: e.clientX,
89
+ y: e.clientY
90
+ }));
91
+ return;
92
+ }
93
+ let c = s / i * 1e3;
94
+ this.moved && s >= this.o.swipeDistance && c >= this.o.swipeVelocity && this.emit({
95
+ type: "swipe",
96
+ x: e.clientX,
97
+ y: e.clientY,
98
+ velocity: c,
99
+ direction: Math.abs(a) > Math.abs(o) ? a > 0 ? "right" : "left" : o > 0 ? "down" : "up"
100
+ });
101
+ }
102
+ dispose() {
103
+ if (!this.disposed) {
104
+ this.disposed = !0;
105
+ for (let e of this.cleanups) e();
106
+ this.cleanups.length = 0, this.handlers.clear(), this.pointers.clear();
107
+ }
108
+ }
109
+ [Symbol.dispose ?? Symbol()]() {
110
+ this.dispose();
111
+ }
112
+ }, n = {
113
+ shift: ["ShiftLeft", "ShiftRight"],
114
+ ctrl: ["ControlLeft", "ControlRight"],
115
+ alt: ["AltLeft", "AltRight"],
116
+ meta: ["MetaLeft", "MetaRight"]
117
+ }, r = [
118
+ 1,
119
+ 4,
120
+ 2,
121
+ 8,
122
+ 16
123
+ ];
124
+ function i(e) {
125
+ let t = 0;
126
+ for (let n = 0; n < r.length; n++) e & r[n] && (t |= 1 << n);
127
+ return t;
128
+ }
129
+ var a = [
130
+ "key",
131
+ "mouse",
132
+ "pointer",
133
+ "gamepad-axis",
134
+ "gamepad-button",
135
+ "touch",
136
+ "control"
137
+ ];
138
+ function o(e) {
139
+ if (!e || typeof e != "object" || !Number.isFinite(e.scale ?? 1) || !a.includes(e.type) || e.type === "key" && (!e.code || e.modifiers !== void 0 && (!Array.isArray(e.modifiers) || e.modifiers.some((e) => !(e in n)))) || e.type === "mouse" && (!Number.isInteger(e.button) || e.button < 0 || e.button > 4) || (e.type === "gamepad-axis" || e.type === "gamepad-button") && (!Number.isInteger(e.index) || e.index < 0 || !Number.isInteger(e.gamepad ?? 0) || (e.gamepad ?? 0) < 0) || e.type === "pointer" && ![
140
+ "x",
141
+ "y",
142
+ "wheel"
143
+ ].includes(e.axis) || e.type === "touch" && (!e.id || e.axis !== void 0 && e.axis !== "x" && e.axis !== "y") || e.type === "control" && (!e.id || typeof e.id != "string" || e.axis !== void 0 && !e.axis)) throw TypeError("Invalid action binding; bind an action to key, mouse, gamepad or touch codes (see InputOptions)");
144
+ }
145
+ var s = class {
146
+ get actions() {
147
+ return this.bindingsByAction;
148
+ }
149
+ constructor(e, { target: t = window, gamepads: n = () => navigator.getGamepads?.() ?? [], deadzone: r = .15, contexts: i = {} } = {}) {
150
+ if (this.states = /* @__PURE__ */ new Map(), this.samples = [], this.keys = /* @__PURE__ */ new Set(), this.buttons = 0, this.tapped = /* @__PURE__ */ new Set(), this.tappedButtons = 0, this.motion = {
151
+ x: 0,
152
+ y: 0,
153
+ wheel: 0
154
+ }, this.touch = /* @__PURE__ */ new Map(), this.controls = /* @__PURE__ */ new Map(), this.feed = null, this.cleanups = [], this.disposed = !1, this.owners = /* @__PURE__ */ new Map(), this.enabled = /* @__PURE__ */ new Set(), this.target = t, this.bindingsByAction = { ...e }, this.initial = { ...e }, !Number.isFinite(r) || r < 0 || r >= 1 || typeof n != "function") throw RangeError("Invalid input options; pass the documented option types");
155
+ this.gamepads = n, this.deadzone = r;
156
+ for (let [t, n] of Object.entries(e)) {
157
+ if (!t || !n.length) throw TypeError("Actions need names and bindings; give every action at least one binding");
158
+ for (let e of n) o(e);
159
+ this.states.set(t, {
160
+ value: 0,
161
+ down: !1,
162
+ pressed: !1,
163
+ released: !1
164
+ }), this.samples.push({
165
+ name: t,
166
+ state: this.states.get(t),
167
+ values: []
168
+ });
169
+ }
170
+ for (let [e, t] of Object.entries(i)) {
171
+ if (!e || !Array.isArray(t)) throw TypeError("Invalid input context; map each context name to an array of action names");
172
+ for (let n of t) {
173
+ if (!this.states.has(n)) throw TypeError("Unknown input action in context; list only actions defined in the first argument");
174
+ (this.owners.get(n) ?? this.owners.set(n, /* @__PURE__ */ new Set()).get(n)).add(e);
175
+ }
176
+ this.enabled.add(e);
177
+ }
178
+ try {
179
+ this.listen(t, "keydown", (e) => {
180
+ let t = e, n = t.composedPath()[0];
181
+ !t.repeat && !n?.closest?.("input,textarea,select,[contenteditable=true]") && (this.keys.add(t.code), this.tapped.add(t.code));
182
+ }), this.listen(t, "keyup", (e) => this.keys.delete(e.code)), this.listen(t, "pointerdown", (e) => this.pointerButtons(e)), this.listen(t, "pointerup", (e) => this.pointerButtons(e)), this.listen(t, "pointermove", (e) => {
183
+ let t = e;
184
+ t.pointerType !== "touch" && (this.motion.x += t.movementX || 0, this.motion.y += t.movementY || 0, this.pointerButtons(t));
185
+ }), this.listen(t, "wheel", (e) => {
186
+ let t = e;
187
+ this.motion.wheel += t.deltaY * (t.deltaMode === 1 ? 16 : t.deltaMode === 2 ? 800 : 1);
188
+ }), this.listen(t, "blur", () => this.reset()), this.listen(t, "pointercancel", () => this.reset());
189
+ } catch (e) {
190
+ throw this.dispose(), e;
191
+ }
192
+ }
193
+ pointerButtons(e) {
194
+ if (e.pointerType === "touch") return;
195
+ let t = e.button >= 0 ? 1 << e.button : 0, n = typeof e.buttons == "number", r = n ? i(e.buttons) : this.buttons;
196
+ if (e.type === "pointerdown") r |= t;
197
+ else if (e.type === "pointerup") r &= ~t;
198
+ else if (!t || !n) return;
199
+ this.tappedButtons |= r & ~this.buttons, this.buttons = r;
200
+ }
201
+ listen(e, t, n) {
202
+ e.addEventListener(t, n), this.cleanups.push(() => e.removeEventListener(t, n));
203
+ }
204
+ state(e) {
205
+ let t = this.states.get(e);
206
+ if (!t) throw TypeError("Unknown input action; add it to the actions option first");
207
+ return t;
208
+ }
209
+ bindingValue(e, t) {
210
+ if (!this.states.has(e)) throw TypeError("Unknown input action; add it to the actions option first");
211
+ return this.samples.find((t) => t.name === e).values[t] ?? 0;
212
+ }
213
+ setFeed(e) {
214
+ this.feed = e;
215
+ }
216
+ update() {
217
+ if (this.disposed) throw new e("disposed", "Input is disposed; create a new Input");
218
+ this.feed?.begin();
219
+ let t = this.gamepads(), r = this.feed;
220
+ for (let e = 0; e < this.samples.length; e++) {
221
+ let i = this.samples[e], a = i.name, o = i.state, s = i.values, c = 0, l = this.bindingsByAction[a], u = this.owners.get(a), d = !0;
222
+ if (u) {
223
+ d = !1;
224
+ for (let e of u) if (this.enabled.has(e)) {
225
+ d = !0;
226
+ break;
227
+ }
228
+ }
229
+ s.length = l.length, s.fill(0);
230
+ for (let e = 0; d && e < l.length; e++) {
231
+ if (r) {
232
+ c += s[e] = r.read(a, e);
233
+ continue;
234
+ }
235
+ let i = l[e], o = 0;
236
+ switch (i.type) {
237
+ case "key":
238
+ if (o = +this.held(i.code), o && i.modifiers) for (let e of i.modifiers) n[e].some((e) => this.held(e)) || (o = 0);
239
+ break;
240
+ case "mouse":
241
+ o = +!!((this.buttons | this.tappedButtons) & 1 << i.button);
242
+ break;
243
+ case "pointer":
244
+ o = this.motion[i.axis];
245
+ break;
246
+ case "touch": {
247
+ let e = this.touch.get(i.id);
248
+ o = i.axis ? e?.[i.axis] ?? 0 : +!!(e?.down || e?.tapped);
249
+ break;
250
+ }
251
+ case "control":
252
+ o = this.controls.get(i.id)?.[i.axis ?? "value"] ?? 0;
253
+ break;
254
+ case "gamepad-button":
255
+ o = t[i.gamepad ?? 0]?.buttons[i.index]?.value ?? 0;
256
+ break;
257
+ case "gamepad-axis": {
258
+ let e = t[i.gamepad ?? 0]?.axes[i.index] ?? 0;
259
+ o = Math.abs(e) <= this.deadzone ? 0 : Math.sign(e) * (Math.abs(e) - this.deadzone) / (1 - this.deadzone);
260
+ break;
261
+ }
262
+ }
263
+ Number.isFinite(o) && (c += s[e] = o * (i.scale ?? 1));
264
+ }
265
+ c = Math.max(-1, Math.min(1, c));
266
+ let f = Math.abs(c) > 1e-6;
267
+ o.pressed = f && !o.down, o.released = !f && o.down, o.down = f, o.value = c;
268
+ }
269
+ this.motion.x = this.motion.y = this.motion.wheel = 0, this.clearTapped();
270
+ }
271
+ held(e) {
272
+ return this.keys.has(e) || this.tapped.has(e);
273
+ }
274
+ clearTapped() {
275
+ this.tapped.clear(), this.tappedButtons = 0;
276
+ for (let e of this.touch.values()) e.tapped = !1;
277
+ }
278
+ control(t) {
279
+ if (this.disposed) throw new e("disposed", "Input is disposed; create a new Input");
280
+ if (!t || typeof t != "string") throw TypeError("Control ids must be non-empty strings");
281
+ let n = this.controls.get(t);
282
+ return n || this.controls.set(t, n = Object.create(null)), n;
283
+ }
284
+ removeControl(e) {
285
+ this.controls.delete(e);
286
+ }
287
+ createStick(e, t) {
288
+ if (this.disposed || !t || this.touch.has(t)) throw TypeError("Invalid or duplicate touch control; give each touch control a unique name and a finite radius");
289
+ let n = e.ownerDocument, r = n.createElement("div"), i = n.createElement("div"), a = {
290
+ x: 0,
291
+ y: 0,
292
+ down: !1,
293
+ tapped: !1
294
+ }, o = null;
295
+ r.setAttribute("role", "group"), r.setAttribute("aria-label", `${t} touch stick`), r.style.cssText = "position:relative;width:120px;height:120px;border:2px solid #747c86;border-radius:50%;touch-action:none;background:#20222644", i.style.cssText = "position:absolute;left:40px;top:40px;width:36px;height:36px;border:2px solid white;border-radius:50%;background:#167f68;pointer-events:none", r.append(i), e.append(r), this.touch.set(t, a);
296
+ let s = (e) => {
297
+ let t = e;
298
+ if (t.pointerId !== o) return;
299
+ let n = r.getBoundingClientRect(), s = Math.min(n.width, n.height) / 2;
300
+ if (!s) return;
301
+ let c = (t.clientX - n.left - n.width / 2) / s, l = (t.clientY - n.top - n.height / 2) / s, u = Math.max(1, Math.hypot(c, l));
302
+ a.x = c / u, a.y = l / u, i.style.transform = `translate(${a.x * 40}px,${a.y * 40}px)`;
303
+ };
304
+ this.listen(r, "pointerdown", (e) => {
305
+ o === null && (o = e.pointerId, a.down = a.tapped = !0, r.setPointerCapture?.(o), s(e));
306
+ }), this.listen(r, "pointermove", s);
307
+ let c = () => {
308
+ o = null, a.down = !1, a.x = a.y = 0, i.style.transform = "";
309
+ };
310
+ a.reset = c;
311
+ let l = (e) => {
312
+ e.pointerId === o && c();
313
+ };
314
+ return this.listen(r, "pointerup", l), this.listen(r, "pointercancel", l), this.listen(r, "lostpointercapture", l), this.cleanups.push(() => {
315
+ this.touch.delete(t), r.remove();
316
+ }), r;
317
+ }
318
+ bindTouchButton(e, t) {
319
+ if (this.disposed || !t || this.touch.has(t)) throw TypeError("Invalid or duplicate touch control; give each touch control a unique name and a finite radius");
320
+ let n = {
321
+ x: 0,
322
+ y: 0,
323
+ down: !1,
324
+ tapped: !1
325
+ };
326
+ this.touch.set(t, n);
327
+ let r = null, i = !1, a = () => {
328
+ r = null, i = !1, n.down = !1;
329
+ };
330
+ n.reset = a, this.listen(e, "pointerdown", (t) => {
331
+ r === null && (r = t.pointerId, n.down = n.tapped = !0, e.setPointerCapture?.(r));
332
+ });
333
+ let o = (e) => {
334
+ e.pointerId === r && (r = null, n.down = i);
335
+ };
336
+ this.listen(e, "pointerup", o), this.listen(e, "pointercancel", o), this.listen(e, "lostpointercapture", o), this.listen(e, "keydown", (e) => {
337
+ (e.key === " " || e.key === "Enter") && (e.preventDefault(), i = !0, n.down = n.tapped = !0);
338
+ }), this.listen(e, "keyup", (e) => {
339
+ (e.key === " " || e.key === "Enter") && (i = !1, n.down = r !== null);
340
+ }), this.listen(e, "blur", a), this.cleanups.push(() => this.touch.delete(t));
341
+ }
342
+ async rumble(t, n = 1, r = 0) {
343
+ if (this.disposed) throw new e("disposed", "Input is disposed; create a new Input");
344
+ if (!Number.isFinite(t) || t < 0 || t > 1e4 || !Number.isFinite(n) || n < 0 || n > 1 || !Number.isInteger(r) || r < 0) throw RangeError("Invalid haptics; pass finite durations and magnitudes from 0 to 1");
345
+ let i = this.gamepads()[r]?.vibrationActuator;
346
+ return i ? (await i.playEffect("dual-rumble", {
347
+ duration: t,
348
+ strongMagnitude: n,
349
+ weakMagnitude: n
350
+ }), !0) : !1;
351
+ }
352
+ setContext(e, t) {
353
+ if (![...this.owners.values()].some((t) => t.has(e))) throw TypeError("Unknown input context; use a name from the contexts option");
354
+ t ? this.enabled.add(e) : this.enabled.delete(e);
355
+ }
356
+ hasContext(e) {
357
+ return this.enabled.has(e);
358
+ }
359
+ rebind(e, t) {
360
+ if (!this.states.has(e)) throw TypeError("Unknown input action; use a name from the actions given to the constructor");
361
+ if (!t.length) throw TypeError("Actions need names and bindings; give every action at least one binding");
362
+ for (let e of t) o(e);
363
+ this.bindingsByAction = {
364
+ ...this.bindingsByAction,
365
+ [e]: t.map((e) => ({ ...e }))
366
+ };
367
+ }
368
+ exportBindings() {
369
+ return JSON.parse(JSON.stringify(this.bindingsByAction));
370
+ }
371
+ importBindings(e) {
372
+ let t;
373
+ try {
374
+ t = typeof e == "string" ? JSON.parse(e) : e;
375
+ } catch {
376
+ throw TypeError("Saved bindings are not valid JSON; pass the text from JSON.stringify(input.exportBindings())");
377
+ }
378
+ if (!t || typeof t != "object" || Array.isArray(t)) throw TypeError("Saved bindings must be an object");
379
+ let n = { ...this.bindingsByAction };
380
+ for (let [e, r] of Object.entries(t)) if (this.states.has(e)) {
381
+ if (!Array.isArray(r) || !r.length) throw TypeError("Invalid saved bindings; give each action a non-empty array of bindings");
382
+ for (let e of r) o(e);
383
+ n[e] = r.map((e) => ({ ...e }));
384
+ }
385
+ this.bindingsByAction = n;
386
+ }
387
+ resetBindings() {
388
+ this.bindingsByAction = { ...this.initial };
389
+ }
390
+ captureBinding({ signal: t } = {}) {
391
+ return new Promise((r, i) => {
392
+ if (this.disposed) return i(new e("disposed", "Input is disposed; create a new Input"));
393
+ let a = 0, o = (e) => {
394
+ this.target.removeEventListener("keydown", u), this.target.removeEventListener("keyup", d), this.target.removeEventListener("pointerdown", f), t?.removeEventListener("abort", s), a && cancelAnimationFrame(a), e();
395
+ }, s = () => o(() => i(t?.reason ?? new DOMException("Aborted", "AbortError"))), c = "", l = (e) => {
396
+ let t = {
397
+ shift: e.shiftKey,
398
+ ctrl: e.ctrlKey,
399
+ alt: e.altKey,
400
+ meta: e.metaKey
401
+ }, i = Object.keys(t).filter((r) => t[r] && !n[r].includes(e.code));
402
+ o(() => r(i.length ? {
403
+ type: "key",
404
+ code: e.code,
405
+ modifiers: i
406
+ } : {
407
+ type: "key",
408
+ code: e.code
409
+ }));
410
+ }, u = (e) => {
411
+ let t = e;
412
+ if (t.code === "Escape") return o(() => i(new DOMException("Cancelled", "AbortError")));
413
+ t.preventDefault?.(), !t.repeat && (Object.values(n).some((e) => e.includes(t.code)) ? c = t.code : l(t));
414
+ }, d = (e) => {
415
+ e.code === c && l(e);
416
+ }, f = (e) => {
417
+ let t = e;
418
+ t.pointerType !== "touch" && t.button >= 0 && t.button <= 4 && o(() => r({
419
+ type: "mouse",
420
+ button: t.button
421
+ }));
422
+ };
423
+ if (t?.aborted) return s();
424
+ t?.addEventListener("abort", s), this.target.addEventListener("keydown", u), this.target.addEventListener("keyup", d), this.target.addEventListener("pointerdown", f);
425
+ let p = /* @__PURE__ */ new Set();
426
+ for (let e of this.gamepads()) e?.buttons.forEach((t, n) => t.pressed && p.add(`${e.index}:${n}`));
427
+ let m = () => {
428
+ for (let e of this.gamepads()) if (e) for (let t = 0; t < e.buttons.length; t++) {
429
+ let n = `${e.index}:${t}`;
430
+ if (!e.buttons[t].pressed) p.delete(n);
431
+ else if (!p.has(n)) return o(() => r({
432
+ type: "gamepad-button",
433
+ index: t,
434
+ gamepad: e.index
435
+ }));
436
+ }
437
+ a = requestAnimationFrame(m);
438
+ };
439
+ typeof requestAnimationFrame == "function" && (a = requestAnimationFrame(m));
440
+ });
441
+ }
442
+ reset() {
443
+ this.keys.clear(), this.buttons = 0, this.motion.x = this.motion.y = this.motion.wheel = 0, this.clearTapped();
444
+ for (let e of this.controls.values()) for (let t in e) e[t] = 0;
445
+ for (let e of this.touch.values()) e.reset?.(), e.down = !1, e.x = e.y = 0;
446
+ }
447
+ dispose() {
448
+ if (!this.disposed) {
449
+ this.disposed = !0;
450
+ for (let e = this.cleanups.length - 1; e >= 0; e--) this.cleanups[e]();
451
+ this.cleanups.length = 0, this.reset();
452
+ }
453
+ }
454
+ [Symbol.dispose ?? Symbol()]() {
455
+ this.dispose();
456
+ }
457
+ };
458
+ //#endregion
459
+ export { t as n, s as t };