@primitiv/input 0.19.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.
package/LICENSE.txt ADDED
@@ -0,0 +1,190 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Thomas Piquet (THP Software)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # @primitiv/input
2
+
3
+ > **Internal package** - This is an internal module of the [Primitiv Engine](https://primitivengine.com/).
4
+
5
+ For documentation, examples, and guides, visit **[primitivengine.com](https://primitivengine.com/)**.
6
+
7
+ ## 📄 License
8
+
9
+ Apache-2.0 - See [LICENSE.txt](./LICENSE.txt).
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var G=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var V=(h,e)=>{for(var t in e)G(h,t,{get:e[t],enumerable:!0})},F=(h,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of J(e))!z.call(h,n)&&n!==t&&G(h,n,{get:()=>e[n],enumerable:!(s=W(e,n))||s.enumerable});return h};var U=h=>F(G({},"__esModule",{value:!0}),h);var N={};V(N,{BaseInputs:()=>f,GamepadInputs:()=>D,InputCollector:()=>O,InputRouter:()=>j,KeyboardInputs:()=>P,MobileVibration:()=>x,MotionInputs:()=>L,MouseInputs:()=>I,TouchInputs:()=>A,TouchZoneInputs:()=>B,VibrationPatterns:()=>y,getMobileVibration:()=>q});module.exports=U(N);var f=class{isActive=!1;targetElement;config;constructor(e=window,t={}){this.targetElement=e,this.config={enabled:!0,preventDefault:!1,stopPropagation:!1,debug:!1,...t}}isListening(){return this.isActive}destroy(){this.stop()}getTargetElement(){return this.targetElement}enable(){this.config.enabled=!0,this.isActive||this.start()}disable(){this.config.enabled=!1,this.isActive&&this.stop()}isEnabled(){return this.config.enabled??!0}};var r=require("@primitiv/types");var P=class extends f{keys={};textInputsThisFrame=[];keyboardCallbacks={};boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={keyDown:this.handleKeyDown.bind(this),keyUp:this.handleKeyUp.bind(this),blur:this.handleBlur.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.addEventListener("keyup",this.boundHandlers.keyUp),window.addEventListener("blur",this.boundHandlers.blur),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.removeEventListener("keyup",this.boundHandlers.keyUp),window.removeEventListener("blur",this.boundHandlers.blur),this.isActive=!1)}reset(){this.keys={},this.textInputsThisFrame=[]}resetDelta(){}poll(){for(let e in this.keys)this.keys[e].justPressed=!1,this.keys[e].justReleased=!1;this.textInputsThisFrame=[]}setCallbacks(e){this.keyboardCallbacks={...this.keyboardCallbacks,...e}}getTextInputs(){return this.textInputsThisFrame}isKeyPressed(e){return this.keys[e]?.pressed||!1}isKeyJustPressed(e){return this.keys[e]?.justPressed||!1}isKeyJustReleased(e){return this.keys[e]?.justReleased||!1}getKeysJustPressed(){let e=[];for(let t in this.keys)this.keys[t].justPressed&&e.push(t);return e}getKeysHeld(){let e=[];for(let t in this.keys)this.keys[t].pressed&&e.push(t);return e}shouldAllowDefault(e,t){let s=/^F([1-9]|1[0-2])$/.test(e),n=(t.ctrlKey||t.metaKey)&&(e==="KeyT"||e==="KeyW"||e==="KeyR"||e==="KeyN"||e==="Tab");return s||n}handleKeyDown(e){let t=e.code,s=this.shouldAllowDefault(t,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[t]||(this.keys[t]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[t].pressed||(this.keys[t].justPressed=!0,this.keyboardCallbacks.onKeyDown?.(t,e)),this.keys[t].pressed=!0,this.keys[t].justReleased=!1;let n=e.key;n.length===1&&!e.ctrlKey&&!e.metaKey&&this.textInputsThisFrame.push(n)}handleKeyUp(e){let t=e.code,s=this.shouldAllowDefault(t,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[t]||(this.keys[t]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[t].pressed&&(this.keys[t].justReleased=!0,this.keyboardCallbacks.onKeyUp?.(t,e)),this.keys[t].pressed=!1,this.keys[t].justPressed=!1}handleBlur(){this.reset()}};var T=require("@primitiv/types");var I=class h extends f{mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}};mousePosition=new T.Vector2(0,0);mouseDelta=new T.Vector2(0,0);wheelDelta=0;boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={mouseDown:this.handleMouseDown.bind(this),mouseUp:this.handleMouseUp.bind(this),mouseMove:this.handleMouseMove.bind(this),wheel:this.handleWheel.bind(this),contextMenu:this.handleContextMenu.bind(this),blur:this.handleBlur.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.addEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.addEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.addEventListener("wheel",this.boundHandlers.wheel),this.targetElement.addEventListener("contextmenu",this.boundHandlers.contextMenu),window.addEventListener("blur",this.boundHandlers.blur),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.removeEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.removeEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.removeEventListener("wheel",this.boundHandlers.wheel),this.targetElement.removeEventListener("contextmenu",this.boundHandlers.contextMenu),window.removeEventListener("blur",this.boundHandlers.blur),this.isActive=!1)}reset(){this.mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}},this.mousePosition=new T.Vector2(0,0),this.mouseDelta=new T.Vector2(0,0),this.wheelDelta=0}poll(){this.mouseButtons.left.justPressed=!1,this.mouseButtons.left.justReleased=!1,this.mouseButtons.middle.justPressed=!1,this.mouseButtons.middle.justReleased=!1,this.mouseButtons.right.justPressed=!1,this.mouseButtons.right.justReleased=!1,this.resetDelta()}resetDelta(){this.mouseDelta=new T.Vector2(0,0),this.wheelDelta=0}isLeftMousePressed(){return this.mouseButtons.left.pressed}isLeftMouseJustPressed(){return this.mouseButtons.left.justPressed}isLeftMouseJustReleased(){return this.mouseButtons.left.justReleased}isRightMousePressed(){return this.mouseButtons.right.pressed}isRightMouseJustPressed(){return this.mouseButtons.right.justPressed}isRightMouseJustReleased(){return this.mouseButtons.right.justReleased}isMiddleMousePressed(){return this.mouseButtons.middle.pressed}getMousePosition(){return this.mousePosition.clone()}getMouseDelta(){return this.mouseDelta.clone()}getWheelDelta(){return this.wheelDelta}static BUTTON_NAMES=["left","middle","right"];handleMouseDown(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault();let t=h.BUTTON_NAMES[e.button];if(t){let s=this.mouseButtons[t];s.pressed||(s.justPressed=!0),s.pressed=!0,s.justReleased=!1}}handleMouseUp(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault();let t=h.BUTTON_NAMES[e.button];if(t){let s=this.mouseButtons[t];s.pressed&&(s.justReleased=!0),s.pressed=!1,s.justPressed=!1}}handleMouseMove(e){let t=new T.Vector2(e.clientX,e.clientY);this.mouseDelta=t.subtract(this.mousePosition),this.mousePosition=t}handleWheel(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault(),this.wheelDelta=e.deltaY}handleContextMenu(e){this.isInteractiveSurfaceEvent(e)&&e.preventDefault()}handleBlur(){this.reset()}isInteractiveSurfaceEvent(e){let t=e.target;return t?(t.tagName||"").toLowerCase()==="canvas"||(t.getAttribute?.("data-primitiv-input-surface")??"").toLowerCase()==="true"?!0:!!t.closest?.('canvas, [data-primitiv-input-surface="true"]'):!1}};var D=class extends f{gamepads=new Map;previousGameState=new Map;rafId=null;boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={connected:this.handleGamepadConnected.bind(this),disconnected:this.handleGamepadDisconnected.bind(this)}}start(){this.isActive||(window.addEventListener("gamepadconnected",this.boundHandlers.connected),window.addEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.startPolling(),this.isActive=!0)}stop(){this.isActive&&(window.removeEventListener("gamepadconnected",this.boundHandlers.connected),window.removeEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.stopPolling(),this.isActive=!1)}startPolling(){let e=()=>{this.poll(),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopPolling(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}poll(){let e=navigator.getGamepads();for(let t=0;t<e.length;t++){let s=e[t];s&&this.updateGamepadState(s)}}reset(){this.gamepads.clear(),this.previousGameState.clear()}resetDelta(){this.previousGameState.clear();for(let[e,t]of this.gamepads)this.previousGameState.set(e,this.cloneState(t))}updateGamepadState(e){let t=this.gamepads.get(e.index),s=e.buttons.map((n,i)=>{let o=t?.buttons[i],a=n.pressed,l=o?.pressed??!1;return{pressed:a,justPressed:a&&!l,justReleased:!a&&l,value:n.value,touched:n.touched}});this.gamepads.set(e.index,{id:e.id,index:e.index,connected:e.connected,buttons:s,axes:[...e.axes],timestamp:e.timestamp,mapping:e.mapping})}isButtonPressed(e,t){return this.gamepads.get(e)?.buttons[t]?.pressed??!1}isButtonJustPressed(e,t){return this.gamepads.get(e)?.buttons[t]?.justPressed??!1}isButtonJustReleased(e,t){return this.gamepads.get(e)?.buttons[t]?.justReleased??!1}getAxis(e,t){let s=this.gamepads.get(e);return s?t===4?s.buttons[6]?.value??0:t===5?s.buttons[7]?.value??0:s.axes[t]??0:0}getButtonValue(e,t){return this.gamepads.get(e)?.buttons[t]?.value??0}vibrationPresets={tap:{duration:50,strongMagnitude:.3,weakMagnitude:.5},impact:{duration:100,strongMagnitude:.7,weakMagnitude:.3},heavy:{duration:200,strongMagnitude:1,weakMagnitude:.2},success:{duration:150,strongMagnitude:.4,weakMagnitude:.6},error:{duration:300,strongMagnitude:.8,weakMagnitude:.4},explosion:{duration:400,strongMagnitude:1,weakMagnitude:.8}};async vibrate(e,t){let s=navigator.getGamepads()[e];if(!s||!s.vibrationActuator)return!1;try{return await s.vibrationActuator.playEffect("dual-rumble",{startDelay:t.startDelay??0,duration:t.duration,strongMagnitude:t.strongMagnitude??1,weakMagnitude:t.weakMagnitude??1}),!0}catch{return!1}}async vibratePreset(e,t){return this.vibrate(e,this.vibrationPresets[t])}async vibrateAll(e){let t=Array.from(this.gamepads.keys()).map(s=>this.vibrate(s,e));await Promise.all(t)}async stopVibration(e){let t=navigator.getGamepads()[e];if(t&&t.vibrationActuator)try{await t.vibrationActuator.reset()}catch{}}handleGamepadConnected(e){this.updateGamepadState(e.gamepad)}handleGamepadDisconnected(e){this.gamepads.delete(e.gamepad.index),this.previousGameState.delete(e.gamepad.index)}cloneState(e){return{...e,buttons:e.buttons.map(t=>({...t})),axes:[...e.axes]}}};var A=class extends f{touches=new Map;nativeToInternal=new Map;maxTouches=10;boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={touchStart:this.handleTouchStart.bind(this),touchEnd:this.handleTouchEnd.bind(this),touchMove:this.handleTouchMove.bind(this),touchCancel:this.handleTouchCancel.bind(this),visibilityChange:this.handleVisibilityChange.bind(this)}}start(){if(this.isActive)return;let e={passive:!this.config.preventDefault};this.targetElement.addEventListener("touchstart",this.boundHandlers.touchStart,e),this.targetElement.addEventListener("touchend",this.boundHandlers.touchEnd,e),this.targetElement.addEventListener("touchmove",this.boundHandlers.touchMove,e),this.targetElement.addEventListener("touchcancel",this.boundHandlers.touchCancel,e),document.addEventListener("visibilitychange",this.boundHandlers.visibilityChange),this.isActive=!0}stop(){this.isActive&&(this.targetElement.removeEventListener("touchstart",this.boundHandlers.touchStart),this.targetElement.removeEventListener("touchend",this.boundHandlers.touchEnd),this.targetElement.removeEventListener("touchmove",this.boundHandlers.touchMove),this.targetElement.removeEventListener("touchcancel",this.boundHandlers.touchCancel),document.removeEventListener("visibilitychange",this.boundHandlers.visibilityChange),this.isActive=!1)}poll(){let e=[];for(let[t,s]of this.touches)s.justReleased?e.push(t):(s.justPressed=!1,s.justReleased=!1);for(let t of e){let s=this.touches.get(t);s&&(this.nativeToInternal.delete(s.nativeId),this.touches.delete(t))}}reset(){this.touches.clear(),this.nativeToInternal.clear()}resetDelta(){}isTouchActive(e){return this.touches.get(e)?.active??!1}isTouchJustPressed(e){return this.touches.get(e)?.justPressed??!1}isTouchJustReleased(e){return this.touches.get(e)?.justReleased??!1}getTouchPosition(e){let t=this.touches.get(e);return t?{x:t.x,y:t.y}:null}getAllTouches(){return Array.from(this.touches.values()).filter(e=>e.active)}updateTouches(e){let t=new Set;for(let s=0;s<e.touches.length;s++){let n=e.touches[s],i=n.identifier;t.add(i);let o=this.nativeToInternal.get(i),a;if(o===void 0){if(this.touches.size>=this.maxTouches)continue;for(let c=0;c<this.maxTouches;c++)if(!this.touches.has(c)){o=c;break}if(o===void 0)continue;this.nativeToInternal.set(i,o),a=void 0}else a=this.touches.get(o);let l=!0,d=a?.active??!1;this.touches.set(o,{id:o,nativeId:i,active:l,justPressed:l&&!d,justReleased:!1,x:n.clientX,y:n.clientY,startX:a?.startX??n.clientX,startY:a?.startY??n.clientY})}for(let[s,n]of this.nativeToInternal)if(!t.has(s)){let i=this.touches.get(n);i&&i.active&&(i.active=!1,i.justReleased=!0)}}handleTouchStart(e){this.config.preventDefault&&e.preventDefault(),this.updateTouches(e)}handleTouchEnd(e){this.config.preventDefault&&e.preventDefault(),this.updateTouches(e)}handleTouchMove(e){this.config.preventDefault&&e.preventDefault(),this.updateTouches(e)}handleTouchCancel(e){this.handleTouchEnd(e)}handleVisibilityChange(){document.visibilityState==="hidden"&&this.reset()}};var B=class extends f{constructor(t,s){super(s.targetElement,s);this.touch=t;this.gridWidth=s.gridWidth,this.gridHeight=s.gridHeight,this.rendererOffsets=s.rendererOffsets??{offsetX:0,offsetY:0},s.zones&&this.setZones(s.zones)}zones=[];zoneStates=new Map;gridWidth;gridHeight;rendererOffsets;start(){this.isActive=!0}stop(){this.isActive=!1}reset(){this.clearZones()}resetDelta(){}setTargetElement(t){this.targetElement=t}setLayout(t,s,n){this.gridWidth=t,this.gridHeight=s,n&&(this.rendererOffsets=n)}setZones(t){this.zones=t.filter(s=>s.id>=0&&s.id<=31),this.zoneStates.clear();for(let s of this.zones)this.zoneStates.set(s.id,{pressed:!1,justPressed:!1,justReleased:!1,lastX:s.x,lastY:s.y})}clearZones(){this.zones=[],this.zoneStates.clear()}updateFromTouches(){if(this.zones.length===0)return;let t=this.targetElement,s=t.getBoundingClientRect(),{renderWidth:n,renderHeight:i,offsetX:o,offsetY:a}=this.calculateRenderMetrics(t,s),l=n/this.gridWidth,d=i/this.gridHeight,c=this.touch.getAllTouches(),v=new Set,g=new Map;for(let M of c){let p=M.x-s.left-o,b=M.y-s.top-a,E=Math.floor(p/l),w=Math.floor(b/d);for(let m of this.zones)E>=m.x&&E<m.x+m.width&&w>=m.y&&w<m.y+m.height&&(v.add(m.id),g.set(m.id,{x:Math.max(m.x,Math.min(m.x+m.width-1,E)),y:Math.max(m.y,Math.min(m.y+m.height-1,w))}))}for(let M of this.zones){let p=this.zoneStates.get(M.id);if(!p)continue;let b=v.has(M.id);b&&!p.pressed&&(p.justPressed=!0),!b&&p.pressed&&(p.justReleased=!0),p.pressed=b;let E=g.get(M.id);E&&(p.lastX=E.x,p.lastY=E.y)}}poll(){for(let t of this.zoneStates.values())t.justPressed=!1,t.justReleased=!1}isZonePressed(t){return this.zoneStates.get(t)?.pressed??!1}isZoneJustPressed(t){return this.zoneStates.get(t)?.justPressed??!1}isZoneJustReleased(t){return this.zoneStates.get(t)?.justReleased??!1}getZoneAxis(t,s){let n=this.zoneStates.get(t);if(!n||!n.pressed)return 0;let i=this.zones.find(o=>o.id===t);if(!i)return 0;if(s==="x"){let o=(i.width-1)/2,a=i.x+o;return o>0?(n.lastX-a)/o:0}else{let o=(i.height-1)/2,a=i.y+o;return o>0?(n.lastY-a)/o:0}}getZonePosition(t){let s=this.zoneStates.get(t);return s?{x:s.lastX,y:s.lastY}:null}calculateRenderMetrics(t,s){let n=t.width,i=t.height;if(!n||!i)return{renderWidth:s.width,renderHeight:s.height,offsetX:this.rendererOffsets.offsetX,offsetY:this.rendererOffsets.offsetY};let o=n/i,a=s.width/s.height,l,d,c,v;o>a?(l=s.width,d=s.width/o,c=0,v=(s.height-d)/2):(l=s.height*o,d=s.height,c=(s.width-l)/2,v=0);let g=this.rendererOffsets;return c+=g.offsetX,v+=g.offsetY,l-=g.offsetX*2,d-=g.offsetY*2,{renderWidth:l,renderHeight:d,offsetX:c,offsetY:v}}};var Z=require("@primitiv/types");var L=class extends f{accelerometer={x:0,y:0,z:0,includesGravity:!1,timestamp:0};gyroscope={alpha:0,beta:0,gamma:0,timestamp:0};orientation={alpha:null,beta:null,gamma:null,absolute:!1,timestamp:0};smoothedAccel={x:0,y:0,z:0};smoothedGyro={alpha:0,beta:0,gamma:0};smoothedOrientation={alpha:0,beta:0,gamma:0};smoothedTiltX=0;smoothedTiltY=0;calibrationOffset={alpha:0,beta:0,gamma:0};isCalibrated=!1;motionCallbacks={};motionConfig;permissionGranted=!1;smoothingFactor=.85;hasReceivedMotion=!1;hasReceivedOrientation=!1;boundHandlers;constructor(e=window,t={}){super(e,t),this.motionConfig={targetElement:e,includeGravity:t.includeGravity??!0,threshold:t.threshold??.001,autoRequestPermission:t.autoRequestPermission??!1,enabled:t.enabled??!0,debug:t.debug??!1,preventDefault:t.preventDefault??!1,stopPropagation:t.stopPropagation??!1,smoothing:t.smoothing??.85,useAbsoluteOrientation:t.useAbsoluteOrientation??!0},this.smoothingFactor=this.motionConfig.smoothing,this.boundHandlers={devicemotion:this.handleDeviceMotion.bind(this),deviceorientation:this.handleDeviceOrientation.bind(this),deviceorientationabsolute:this.handleDeviceOrientationAbsolute.bind(this)}}async requestPermission(){let e=!0,t=!0;if(typeof DeviceMotionEvent.requestPermission=="function")try{e=await DeviceMotionEvent.requestPermission()==="granted"}catch{e=!1}if(typeof DeviceOrientationEvent.requestPermission=="function")try{t=await DeviceOrientationEvent.requestPermission()==="granted"}catch{t=!1}return this.permissionGranted=e&&t,this.permissionGranted}isPermissionGranted(){return this.permissionGranted}isReceivingMotion(){return this.hasReceivedMotion}isReceivingOrientation(){return this.hasReceivedOrientation}start(){this.isActive||(window.addEventListener("devicemotion",this.boundHandlers.devicemotion),this.motionConfig.useAbsoluteOrientation&&window.addEventListener("deviceorientationabsolute",this.boundHandlers.deviceorientationabsolute),window.addEventListener("deviceorientation",this.boundHandlers.deviceorientation),this.isActive=!0)}stop(){this.isActive&&(window.removeEventListener("devicemotion",this.boundHandlers.devicemotion),window.removeEventListener("deviceorientation",this.boundHandlers.deviceorientation),window.removeEventListener("deviceorientationabsolute",this.boundHandlers.deviceorientationabsolute),this.isActive=!1)}setCallbacks(e){this.motionCallbacks={...this.motionCallbacks,...e}}poll(){}reset(){this.accelerometer={x:0,y:0,z:0,includesGravity:!1,timestamp:0},this.gyroscope={alpha:0,beta:0,gamma:0,timestamp:0},this.orientation={alpha:null,beta:null,gamma:null,absolute:!1,timestamp:0},this.smoothedAccel={x:0,y:0,z:0},this.smoothedGyro={alpha:0,beta:0,gamma:0},this.smoothedOrientation={alpha:0,beta:0,gamma:0},this.smoothedTiltX=0,this.smoothedTiltY=0,this.hasReceivedMotion=!1,this.hasReceivedOrientation=!1}resetDelta(){}calibrate(){this.orientation.beta!==null&&this.orientation.gamma!==null&&(this.calibrationOffset={alpha:this.orientation.alpha??0,beta:this.orientation.beta,gamma:this.orientation.gamma},this.isCalibrated=!0)}clearCalibration(){this.calibrationOffset={alpha:0,beta:0,gamma:0},this.isCalibrated=!1}getIsCalibrated(){return this.isCalibrated}getAccelerometer(){return{...this.smoothedAccel,includesGravity:this.motionConfig.includeGravity,timestamp:this.accelerometer.timestamp}}getGyroscope(){return{...this.smoothedGyro,timestamp:this.gyroscope.timestamp}}getOrientation(){let e=this.smoothedOrientation.alpha,t=this.smoothedOrientation.beta-(this.isCalibrated?this.calibrationOffset.beta:0),s=this.smoothedOrientation.gamma-(this.isCalibrated?this.calibrationOffset.gamma:0);return{alpha:this.orientation.alpha!==null?e:null,beta:this.orientation.beta!==null?t:null,gamma:this.orientation.gamma!==null?s:null,absolute:this.orientation.absolute,timestamp:this.orientation.timestamp}}getRawAccelerometer(){return{...this.accelerometer}}getRawGyroscope(){return{...this.gyroscope}}getRawOrientation(){return{...this.orientation}}getNormalizedTilt(){let e=this.smoothedTiltX,t=this.smoothedTiltY;return this.isCalibrated&&(e-=this.calibrationOffset.gamma/90,t-=this.calibrationOffset.beta/90,e=Math.max(-1,Math.min(1,e)),t=Math.max(-1,Math.min(1,t))),new Z.Vector2(e,t)}getCompassHeading(){return this.orientation.alpha===null?null:this.smoothedOrientation.alpha}setSmoothing(e){this.smoothingFactor=Math.max(0,Math.min(.99,e))}lowPass(e,t){return e*this.smoothingFactor+t*(1-this.smoothingFactor)}lowPassAngle(e,t,s=360){let n=t-e;n>s/2&&(n-=s),n<-s/2&&(n+=s);let i=e+n*(1-this.smoothingFactor);for(;i<0;)i+=s;for(;i>=s;)i-=s;return i}handleDeviceMotion(e){let t=performance.now(),s=this.motionConfig.includeGravity?e.accelerationIncludingGravity:e.acceleration;if(s&&(s.x!==null||s.y!==null||s.z!==null)){this.hasReceivedMotion=!0;let i=s.x??0,o=s.y??0,a=s.z??0;this.accelerometer={x:i,y:o,z:a,includesGravity:this.motionConfig.includeGravity,timestamp:t},this.smoothedAccel={x:this.lowPass(this.smoothedAccel.x,i),y:this.lowPass(this.smoothedAccel.y,o),z:this.lowPass(this.smoothedAccel.z,a)},this.motionCallbacks.onAccelerometer?.(this.getAccelerometer())}let n=e.rotationRate;if(n&&(n.alpha!==null||n.beta!==null||n.gamma!==null)){let i=n.alpha??0,o=n.beta??0,a=n.gamma??0;this.gyroscope={alpha:i,beta:o,gamma:a,timestamp:t},this.smoothedGyro={alpha:this.lowPass(this.smoothedGyro.alpha,i),beta:this.lowPass(this.smoothedGyro.beta,o),gamma:this.lowPass(this.smoothedGyro.gamma,a)},this.motionCallbacks.onGyroscope?.(this.getGyroscope())}}handleDeviceOrientation(e){this.motionConfig.useAbsoluteOrientation&&this.orientation.absolute||this.processOrientationEvent(e,!1)}handleDeviceOrientationAbsolute(e){this.processOrientationEvent(e,!0)}processOrientationEvent(e,t){let s=performance.now();if(e.alpha===null&&e.beta===null&&e.gamma===null)return;this.hasReceivedOrientation=!0;let n=e.alpha??0,i=e.beta??0,o=e.gamma??0;this.orientation={alpha:e.alpha,beta:e.beta,gamma:e.gamma,absolute:t||e.absolute,timestamp:s},this.smoothedOrientation.alpha=this.lowPassAngle(this.smoothedOrientation.alpha,n,360),this.smoothedOrientation.beta=this.lowPass(this.smoothedOrientation.beta,i),this.smoothedOrientation.gamma=this.lowPass(this.smoothedOrientation.gamma,o),this.smoothedTiltX=this.lowPass(this.smoothedTiltX,Math.max(-1,Math.min(1,o/90))),this.smoothedTiltY=this.lowPass(this.smoothedTiltY,Math.max(-1,Math.min(1,Math.max(-90,Math.min(90,i))/90))),this.motionCallbacks.onOrientation?.(this.getOrientation())}};var y={tap:10,mediumTap:25,heavyTap:50,success:[30,50,30],error:[50,30,50,30,50],warning:[100],selection:5,impactLight:15,impactMedium:30,impactHeavy:50,notification:[100,100,100,100,100],sos:[100,30,100,30,100,30,200,30,200,30,200,30,100,30,100,30,100]},x=class{enabled;intensity;supported;userActivated=!1;constructor(e={}){this.enabled=e.enabled??!0,this.intensity=Math.max(0,Math.min(1,e.intensity??1)),this.supported=typeof navigator<"u"&&typeof navigator.vibrate=="function"}isSupported(){return this.supported}isEnabled(){return this.enabled&&this.supported}setEnabled(e){this.enabled=e}setIntensity(e){this.intensity=Math.max(0,Math.min(1,e))}getIntensity(){return this.intensity}hasUserActivation(){return this.userActivated}vibrate(e){if(!this.isEnabled())return!1;let t=this.scalePattern(e),s=navigator.vibrate(t);return s&&(this.userActivated=!0),s}cancel(){this.supported&&navigator.vibrate(0)}tap(){return this.vibrate(y.tap)}mediumTap(){return this.vibrate(y.mediumTap)}heavyTap(){return this.vibrate(y.heavyTap)}success(){return this.vibrate(y.success)}error(){return this.vibrate(y.error)}warning(){return this.vibrate(y.warning)}selection(){return this.vibrate(y.selection)}impactLight(){return this.vibrate(y.impactLight)}impactMedium(){return this.vibrate(y.impactMedium)}impactHeavy(){return this.vibrate(y.impactHeavy)}notification(){return this.vibrate(y.notification)}scalePattern(e){return this.intensity===1?e:typeof e=="number"?Math.round(e*this.intensity):e.map((t,s)=>s%2===0?Math.round(t*this.intensity):t)}},S=null;function q(h){return S||(S=new x(h)),S}var j=class{keyboard=null;mouse=null;gamepad=null;touch=null;touchZone=null;motion=null;vibration=null;config;constructor(e={}){this.config={enableKeyboardMouse:e.enableKeyboardMouse??!0,enableGamepad:e.enableGamepad??!0,enableTouch:e.enableTouch??!0,targetElement:e.targetElement??window,gridWidth:e.gridWidth??80,gridHeight:e.gridHeight??25,debug:e.debug??!1},this.initialize()}initialize(){let e=this.config.targetElement;if(this.config.enableKeyboardMouse&&(this.keyboard=new P(e),this.mouse=new I(e)),this.config.enableGamepad&&(this.gamepad=new D(e)),this.config.enableTouch){this.touch=new A(e);let t=e instanceof Window?document.body:e;this.touchZone=new B(this.touch,{targetElement:t,gridWidth:this.config.gridWidth,gridHeight:this.config.gridHeight}),this.motion=new L(e),this.vibration=new x}this.start()}getButton(e,t){switch(e){case r.InputDeviceType.Keyboard:return this.keyboard?.isKeyPressed(r.KeyboardInput[t])??!1;case r.InputDeviceType.Mouse:return this.getMouseButton(t);case r.InputDeviceType.Gamepad:return this.gamepad?.isButtonPressed(0,t)??!1;case r.InputDeviceType.Touch:return this.touch?.isTouchActive(t)??!1;case r.InputDeviceType.TouchZone:return this.touchZone?.isZonePressed(t)??!1;default:return!1}}getButtonJustPressed(e,t){switch(e){case r.InputDeviceType.Keyboard:return this.keyboard?.isKeyJustPressed(r.KeyboardInput[t])??!1;case r.InputDeviceType.Mouse:return this.getMouseButtonJustPressed(t);case r.InputDeviceType.Gamepad:return this.gamepad?.isButtonJustPressed(0,t)??!1;case r.InputDeviceType.Touch:return this.touch?.isTouchJustPressed?.(t)??!1;case r.InputDeviceType.TouchZone:return this.touchZone?.isZoneJustPressed(t)??!1;default:return!1}}getButtonJustReleased(e,t){switch(e){case r.InputDeviceType.Keyboard:return this.keyboard?.isKeyJustReleased(r.KeyboardInput[t])??!1;case r.InputDeviceType.Mouse:return this.getMouseButtonJustReleased(t);case r.InputDeviceType.Gamepad:return this.gamepad?.isButtonJustReleased(0,t)??!1;case r.InputDeviceType.Touch:return this.touch?.isTouchJustReleased?.(t)??!1;case r.InputDeviceType.TouchZone:return this.touchZone?.isZoneJustReleased(t)??!1;default:return!1}}getAxis(e,t){switch(e){case r.InputDeviceType.Mouse:return this.getMouseAxis(t);case r.InputDeviceType.Gamepad:return this.gamepad?.getAxis(0,t-100)??0;case r.InputDeviceType.Touch:return this.getTouchAxis(t);case r.InputDeviceType.TouchZone:return this.getTouchZoneAxis(t);case r.InputDeviceType.Motion:return this.getMotionAxis(t);default:return 0}}getButtonValue(e,t){return e===r.InputDeviceType.Gamepad?this.gamepad?.getButtonValue(0,t)??0:this.getButton(e,t)?1:0}isLeftMousePressed(){return this.mouse?.isLeftMousePressed()??!1}getTextInputs(){return this.keyboard?.getTextInputs()??[]}getMouseButton(e){return this.mouse?e===r.MouseInput.LeftButton?this.mouse.isLeftMousePressed():e===r.MouseInput.RightButton?this.mouse.isRightMousePressed():e===r.MouseInput.MiddleButton?this.mouse.isMiddleMousePressed():!1:!1}getMouseButtonJustPressed(e){return this.mouse?e===r.MouseInput.LeftButton?this.mouse.isLeftMouseJustPressed():e===r.MouseInput.RightButton?this.mouse.isRightMouseJustPressed():!1:!1}getMouseButtonJustReleased(e){return this.mouse?e===r.MouseInput.LeftButton?this.mouse.isLeftMouseJustReleased():e===r.MouseInput.RightButton?this.mouse.isRightMouseJustReleased():!1:!1}getMouseAxis(e){return this.mouse?e===r.MouseInput.PositionX?this.mouse.getMousePosition().x:e===r.MouseInput.PositionY?this.mouse.getMousePosition().y:e===r.MouseInput.DeltaX?this.mouse.getMouseDelta().x:e===r.MouseInput.DeltaY?this.mouse.getMouseDelta().y:e===r.MouseInput.WheelDeltaY?this.mouse.getWheelDelta():0:0}getTouchAxis(e){if(!this.touch)return 0;if(e>=100&&e<200){let t=Math.floor((e-100)/2),s=(e-100)%2===1,n=this.touch.getTouchPosition(t);return n?s?n.y:n.x:0}return 0}getTouchZoneAxis(e){if(!this.touchZone)return 0;if(e>=100&&e<200){let t=Math.floor((e-100)/2),s=(e-100)%2===1;return this.touchZone.getZoneAxis(t,s?"y":"x")}return 0}getMotionAxis(e){if(!this.motion)return 0;switch(e){case r.MotionInput.AccelerometerX:return this.motion.getAccelerometer().x;case r.MotionInput.AccelerometerY:return this.motion.getAccelerometer().y;case r.MotionInput.AccelerometerZ:return this.motion.getAccelerometer().z;case r.MotionInput.GyroscopeAlpha:return this.motion.getGyroscope().alpha;case r.MotionInput.GyroscopeBeta:return this.motion.getGyroscope().beta;case r.MotionInput.GyroscopeGamma:return this.motion.getGyroscope().gamma;case r.MotionInput.OrientationAlpha:return this.motion.getOrientation().alpha??0;case r.MotionInput.OrientationBeta:return this.motion.getOrientation().beta??0;case r.MotionInput.OrientationGamma:return this.motion.getOrientation().gamma??0;case r.MotionInput.TiltX:return this.motion.getNormalizedTilt().x;case r.MotionInput.TiltY:return this.motion.getNormalizedTilt().y;case r.MotionInput.CompassHeading:return this.motion.getCompassHeading()??0;default:return 0}}getMotion(){return this.motion}getVibration(){return this.vibration}getMouseGridX(){if(!this.mouse)return 0;let e=this.mouse.getMousePosition().x,t=this.config.targetElement,s,n;if(t instanceof Window)s=t.innerWidth,n=0;else{let i=t.getBoundingClientRect();s=i.width,n=i.left}return s===0?0:Math.floor((e-n)/s*this.config.gridWidth)}getMouseGridY(){if(!this.mouse)return 0;let e=this.mouse.getMousePosition().y,t=this.config.targetElement,s,n;if(t instanceof Window)s=t.innerHeight,n=0;else{let i=t.getBoundingClientRect();s=i.height,n=i.top}return s===0?0:Math.floor((e-n)/s*this.config.gridHeight)}isMouseButtonDown(e){return this.mouse?e===0?this.mouse.isLeftMousePressed():e===1?this.mouse.isMiddleMousePressed():e===2?this.mouse.isRightMousePressed():!1:!1}getKeysPressed(){return this.keyboard?.getKeysJustPressed()??[]}getKeysHeld(){return this.keyboard?.getKeysHeld()??[]}setTouchZones(e){this.touchZone&&this.touchZone.setZones(e.map(t=>({id:t.zoneId,x:t.x,y:t.y,width:t.width,height:t.height})))}setTouchLayout(e,t,s,n){this.touchZone&&(this.touchZone.setTargetElement(e),this.touchZone.setLayout(t,s,n))}start(){this.keyboard?.start(),this.mouse?.start(),this.gamepad?.start(),this.touch?.start(),this.touchZone?.start(),this.motion?.start()}stop(){this.keyboard?.stop(),this.mouse?.stop(),this.gamepad?.stop(),this.touch?.stop(),this.touchZone?.stop(),this.motion?.stop()}reset(){this.keyboard?.reset(),this.mouse?.reset(),this.gamepad?.reset(),this.touch?.reset(),this.touchZone?.reset(),this.motion?.reset()}poll(){this.keyboard?.poll(),this.mouse?.poll(),this.gamepad?.poll(),this.touchZone?.poll(),this.touch?.poll(),this.touchZone?.updateFromTouches(),this.motion?.poll()}resetDelta(){this.keyboard?.resetDelta(),this.mouse?.resetDelta(),this.gamepad?.resetDelta(),this.touch?.resetDelta(),this.touchZone?.resetDelta(),this.motion?.resetDelta()}destroy(){this.stop(),this.keyboard?.destroy(),this.mouse?.destroy(),this.gamepad?.destroy(),this.touch?.destroy(),this.touchZone?.destroy(),this.motion?.destroy()}};var u=require("@primitiv/types"),O=class h{static calculateRenderMetrics(e,t){let s=e.getBoundingClientRect(),n=e.width/e.height,i=s.width/s.height,o,a,l,d;n>i?(o=s.width,a=s.width/n,l=0,d=(s.height-a)/2):(o=s.height*n,a=s.height,l=(s.width-o)/2,d=0);let c=t?.offsetX||0,v=t?.offsetY||0;return l+=c,d+=v,o-=c*2,a-=v*2,{renderWidth:o,renderHeight:a,offsetX:l,offsetY:d,rect:s}}static collectAxisSources(e,t){let s=new Map;for(let n of e)for(let i of n.sources){if(s.has(i.sourceId))continue;let o=0,a=!1;if(i.type===u.InputDeviceType.Keyboard&&i.negativeKey!==void 0&&i.positiveKey!==void 0){let l=t.getButton(u.InputDeviceType.Keyboard,i.negativeKey);t.getButton(u.InputDeviceType.Keyboard,i.positiveKey)&&(o+=1),l&&(o-=1),a=!0}else if(i.type===u.InputDeviceType.Mouse&&i.mouseAxis!==void 0)o=t.getAxis(u.InputDeviceType.Mouse,i.mouseAxis),a=!0;else if(i.type===u.InputDeviceType.Gamepad&&i.axis!==void 0)o=t.getAxis(u.InputDeviceType.Gamepad,i.axis),a=!0;else if(i.type===u.InputDeviceType.Touch&&i.touchId!==void 0&&i.touchAxis!==void 0){let l=100+i.touchId*2,d=i.touchAxis==="x"?l:l+1;o=t.getAxis(u.InputDeviceType.Touch,d),a=!0}else if(i.type===u.InputDeviceType.TouchZone&&i.touchZoneId!==void 0&&i.touchZoneAxis!==void 0){let l=100+i.touchZoneId*2,d=i.touchZoneAxis==="x"?l:l+1;o=t.getAxis(u.InputDeviceType.TouchZone,d),a=!0}else i.type===u.InputDeviceType.Motion&&i.motionAxis!==void 0&&(o=t.getAxis(u.InputDeviceType.Motion,i.motionAxis),a=!0);a&&s.set(i.sourceId,o)}return s}static collectButtonSources(e,t){let s=new Map;for(let n of e)for(let i of n.sources){if(s.has(i.sourceId))continue;let o=!1,a=!1;i.type===u.InputDeviceType.Keyboard&&i.key!==void 0?(o=t.getButton(u.InputDeviceType.Keyboard,i.key),a=!0):i.type===u.InputDeviceType.Mouse&&i.mouseButton!==void 0?(o=t.getButton(u.InputDeviceType.Mouse,i.mouseButton),a=!0):i.type===u.InputDeviceType.Gamepad&&i.button!==void 0?(o=t.getButton(u.InputDeviceType.Gamepad,i.button),a=!0):i.type===u.InputDeviceType.Touch&&i.touchButton!==void 0?(o=t.getButton(u.InputDeviceType.Touch,i.touchButton),a=!0):i.type===u.InputDeviceType.TouchZone&&i.touchZoneId!==void 0&&(o=t.getButton(u.InputDeviceType.TouchZone,i.touchZoneId),a=!0),a&&s.set(i.sourceId,o)}return s}static collectButtonSourcesWithTransitions(e,t){let s=new Map;for(let n of e)for(let i of n.sources){if(s.has(i.sourceId))continue;let o=!1,a=!1,l=!1,d=!1;i.type===u.InputDeviceType.Keyboard&&i.key!==void 0?(o=t.getButton(u.InputDeviceType.Keyboard,i.key),a=t.getButtonJustPressed(u.InputDeviceType.Keyboard,i.key),l=t.getButtonJustReleased(u.InputDeviceType.Keyboard,i.key),d=!0):i.type===u.InputDeviceType.Mouse&&i.mouseButton!==void 0?(o=t.getButton(u.InputDeviceType.Mouse,i.mouseButton),a=t.getButtonJustPressed(u.InputDeviceType.Mouse,i.mouseButton),l=t.getButtonJustReleased(u.InputDeviceType.Mouse,i.mouseButton),d=!0):i.type===u.InputDeviceType.Gamepad&&i.button!==void 0?(o=t.getButton(u.InputDeviceType.Gamepad,i.button),a=t.getButtonJustPressed(u.InputDeviceType.Gamepad,i.button),l=t.getButtonJustReleased(u.InputDeviceType.Gamepad,i.button),d=!0):i.type===u.InputDeviceType.Touch&&i.touchButton!==void 0?(o=t.getButton(u.InputDeviceType.Touch,i.touchButton),a=t.getButtonJustPressed(u.InputDeviceType.Touch,i.touchButton),l=t.getButtonJustReleased(u.InputDeviceType.Touch,i.touchButton),d=!0):i.type===u.InputDeviceType.TouchZone&&i.touchZoneId!==void 0&&(o=t.getButton(u.InputDeviceType.TouchZone,i.touchZoneId),a=t.getButtonJustPressed(u.InputDeviceType.TouchZone,i.touchZoneId),l=t.getButtonJustReleased(u.InputDeviceType.TouchZone,i.touchZoneId),d=!0),d&&s.set(i.sourceId,{pressed:o,justPressed:a,justReleased:l})}return s}static collectMousePosition(e,t,s,n,i){let o=e.getAxis(u.InputDeviceType.Mouse,100),a=e.getAxis(u.InputDeviceType.Mouse,101),l=e.getButton(u.InputDeviceType.Mouse,0),{renderWidth:d,renderHeight:c,offsetX:v,offsetY:g,rect:M}=h.calculateRenderMetrics(t,i),p=o-M.left-v,b=a-M.top-g,E=d/s,w=c/n,m=Math.floor(p/E),R=Math.floor(b/w),H=p>=0&&p<d&&b>=0&&b<c;return{x:Math.max(0,Math.min(s-1,m)),y:Math.max(0,Math.min(n-1,R)),over:H,isLeftDown:l}}static collectTouchPositions(e,t,s,n,i=10,o){let a=[],{renderWidth:l,renderHeight:d,offsetX:c,offsetY:v,rect:g}=h.calculateRenderMetrics(t,o),M=l/s,p=d/n;for(let b=0;b<i;b++)if(e.getButton(u.InputDeviceType.Touch,b)){let w=100+b*2,m=100+b*2+1,R=e.getAxis(u.InputDeviceType.Touch,w),H=e.getAxis(u.InputDeviceType.Touch,m),C=R-g.left-c,k=H-g.top-v,K=Math.floor(C/M),Y=Math.floor(k/p),X=C>=0&&C<l&&k>=0&&k<d;a.push({id:b,x:Math.max(0,Math.min(s-1,K)),y:Math.max(0,Math.min(n-1,Y)),over:X})}return a}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};
@@ -0,0 +1,706 @@
1
+ import { Vector2, IInputSystem, InputDeviceType, AxisBinding, ButtonBinding } from '@primitiv/types';
2
+
3
+ /**
4
+ * Common button state interface
5
+ */
6
+ interface ButtonState {
7
+ pressed: boolean;
8
+ justPressed: boolean;
9
+ justReleased: boolean;
10
+ timestamp?: number;
11
+ }
12
+ /**
13
+ * Configuration options for input systems
14
+ */
15
+ interface InputConfig {
16
+ /**
17
+ * Target element to attach listeners to (default: window)
18
+ */
19
+ targetElement?: HTMLElement | Window;
20
+ /**
21
+ * Enable/disable specific input types
22
+ */
23
+ enabled?: boolean;
24
+ /**
25
+ * Prevent default browser behaviors
26
+ */
27
+ preventDefault?: boolean;
28
+ /**
29
+ * Stop event propagation
30
+ */
31
+ stopPropagation?: boolean;
32
+ /**
33
+ * Enable debug logging
34
+ */
35
+ debug?: boolean;
36
+ }
37
+ /**
38
+ * Abstract base class for input systems
39
+ */
40
+ declare abstract class BaseInputs {
41
+ protected isActive: boolean;
42
+ protected targetElement: HTMLElement | Window;
43
+ protected config: InputConfig;
44
+ constructor(targetElement?: HTMLElement | Window, config?: InputConfig);
45
+ abstract start(): void;
46
+ abstract stop(): void;
47
+ abstract reset(): void;
48
+ abstract resetDelta(): void;
49
+ isListening(): boolean;
50
+ destroy(): void;
51
+ getTargetElement(): HTMLElement | Window;
52
+ enable(): void;
53
+ disable(): void;
54
+ isEnabled(): boolean;
55
+ }
56
+
57
+ interface AccelerometerData {
58
+ x: number;
59
+ y: number;
60
+ z: number;
61
+ includesGravity: boolean;
62
+ timestamp: number;
63
+ }
64
+ interface GyroscopeData {
65
+ alpha: number;
66
+ beta: number;
67
+ gamma: number;
68
+ timestamp: number;
69
+ }
70
+ interface OrientationData {
71
+ /** Compass heading: 0-360° (0 = North, 90 = East). null if unavailable. */
72
+ alpha: number | null;
73
+ /** Front/back tilt: -180° to +180° (0 = flat, positive = tilted back). */
74
+ beta: number | null;
75
+ /** Left/right tilt: -90° to +90° (0 = flat, positive = tilted right). */
76
+ gamma: number | null;
77
+ /** True if alpha is relative to true north (compass), false if arbitrary. */
78
+ absolute: boolean;
79
+ timestamp: number;
80
+ }
81
+ interface MotionCallbacks {
82
+ onAccelerometer?: (data: AccelerometerData) => void;
83
+ onGyroscope?: (data: GyroscopeData) => void;
84
+ onOrientation?: (data: OrientationData) => void;
85
+ }
86
+ interface MotionInputsConfig extends InputConfig {
87
+ /** Include gravity in accelerometer readings. Default: true. */
88
+ includeGravity?: boolean;
89
+ /** Minimum change threshold to trigger callbacks. Default: 0.001. */
90
+ threshold?: number;
91
+ /** Automatically request permission on iOS. Default: false. */
92
+ autoRequestPermission?: boolean;
93
+ enabled?: boolean;
94
+ debug?: boolean;
95
+ preventDefault?: boolean;
96
+ stopPropagation?: boolean;
97
+ /** Low-pass filter smoothing (0 = raw, 0.95 = very smooth). Default: 0.85. */
98
+ smoothing?: number;
99
+ /** Use absolute orientation (true north compass) when available. Default: true. */
100
+ useAbsoluteOrientation?: boolean;
101
+ }
102
+ declare class MotionInputs extends BaseInputs {
103
+ private accelerometer;
104
+ private gyroscope;
105
+ private orientation;
106
+ private smoothedAccel;
107
+ private smoothedGyro;
108
+ private smoothedOrientation;
109
+ private smoothedTiltX;
110
+ private smoothedTiltY;
111
+ private calibrationOffset;
112
+ private isCalibrated;
113
+ private motionCallbacks;
114
+ private motionConfig;
115
+ private permissionGranted;
116
+ private smoothingFactor;
117
+ private hasReceivedMotion;
118
+ private hasReceivedOrientation;
119
+ private boundHandlers;
120
+ constructor(targetElement?: HTMLElement | Window, config?: MotionInputsConfig);
121
+ /**
122
+ * Request permission for motion sensors (required on iOS 13+).
123
+ * Must be called from a user gesture (tap, click).
124
+ */
125
+ requestPermission(): Promise<boolean>;
126
+ /** Check if permission has been granted. */
127
+ isPermissionGranted(): boolean;
128
+ /** Check if we're receiving motion data. */
129
+ isReceivingMotion(): boolean;
130
+ /** Check if we're receiving orientation data. */
131
+ isReceivingOrientation(): boolean;
132
+ start(): void;
133
+ stop(): void;
134
+ setCallbacks(callbacks: MotionCallbacks): void;
135
+ poll(): void;
136
+ reset(): void;
137
+ resetDelta(): void;
138
+ /**
139
+ * Calibrate sensors: set current orientation as the "zero" reference.
140
+ * Useful for games where the player holds the phone at an angle.
141
+ */
142
+ calibrate(): void;
143
+ /** Clear calibration and return to absolute values. */
144
+ clearCalibration(): void;
145
+ /** Check if sensors are calibrated. */
146
+ getIsCalibrated(): boolean;
147
+ /** Get smoothed accelerometer data (m/s²). */
148
+ getAccelerometer(): AccelerometerData;
149
+ /** Get smoothed gyroscope/rotation rate (°/s). */
150
+ getGyroscope(): GyroscopeData;
151
+ /** Get smoothed orientation with calibration applied. */
152
+ getOrientation(): OrientationData;
153
+ /** Get raw (unsmoothed) accelerometer data. */
154
+ getRawAccelerometer(): AccelerometerData;
155
+ /** Get raw (unsmoothed) gyroscope data. */
156
+ getRawGyroscope(): GyroscopeData;
157
+ /** Get raw (unsmoothed) orientation data. */
158
+ getRawOrientation(): OrientationData;
159
+ /**
160
+ * Get normalized tilt as a Vector2 (-1 to +1).
161
+ * Calibration is applied if set.
162
+ *
163
+ * - X: Left/right tilt (positive = tilted right)
164
+ * - Y: Forward/backward tilt (positive = tilted back)
165
+ */
166
+ getNormalizedTilt(): Vector2;
167
+ /**
168
+ * Get compass heading in degrees (0-360, 0 = North, 90 = East).
169
+ * Returns null if compass is unavailable.
170
+ */
171
+ getCompassHeading(): number | null;
172
+ /** Set the smoothing factor (0 = raw/noisy, 0.95 = very smooth). */
173
+ setSmoothing(factor: number): void;
174
+ /** Low-pass filter for regular values. */
175
+ private lowPass;
176
+ /** Low-pass filter for angles that wrap (0-360). */
177
+ private lowPassAngle;
178
+ private handleDeviceMotion;
179
+ private handleDeviceOrientation;
180
+ private handleDeviceOrientationAbsolute;
181
+ private processOrientationEvent;
182
+ }
183
+
184
+ /**
185
+ * MobileVibration - Named vibration presets with intensity scaling.
186
+ *
187
+ * Wraps navigator.vibrate() with convenience methods and
188
+ * a configurable intensity multiplier that scales vibration durations.
189
+ */
190
+ type VibrationPattern = number | readonly number[];
191
+ interface MobileVibrationConfig {
192
+ enabled?: boolean;
193
+ intensity?: number;
194
+ }
195
+ declare const VibrationPatterns: {
196
+ readonly tap: 10;
197
+ readonly mediumTap: 25;
198
+ readonly heavyTap: 50;
199
+ readonly success: readonly number[];
200
+ readonly error: readonly number[];
201
+ readonly warning: readonly number[];
202
+ readonly selection: 5;
203
+ readonly impactLight: 15;
204
+ readonly impactMedium: 30;
205
+ readonly impactHeavy: 50;
206
+ readonly notification: readonly number[];
207
+ readonly sos: readonly number[];
208
+ };
209
+ declare class MobileVibration {
210
+ private enabled;
211
+ private intensity;
212
+ private supported;
213
+ private userActivated;
214
+ constructor(config?: MobileVibrationConfig);
215
+ isSupported(): boolean;
216
+ isEnabled(): boolean;
217
+ setEnabled(enabled: boolean): void;
218
+ setIntensity(intensity: number): void;
219
+ getIntensity(): number;
220
+ hasUserActivation(): boolean;
221
+ vibrate(pattern: VibrationPattern): boolean;
222
+ cancel(): void;
223
+ tap(): boolean;
224
+ mediumTap(): boolean;
225
+ heavyTap(): boolean;
226
+ success(): boolean;
227
+ error(): boolean;
228
+ warning(): boolean;
229
+ selection(): boolean;
230
+ impactLight(): boolean;
231
+ impactMedium(): boolean;
232
+ impactHeavy(): boolean;
233
+ notification(): boolean;
234
+ /**
235
+ * Scale vibration durations by intensity.
236
+ * Only "on" segments (even indices in an array pattern) are scaled;
237
+ * pauses (odd indices) are kept as-is so rhythm is preserved.
238
+ */
239
+ private scalePattern;
240
+ }
241
+ declare function getMobileVibration(config?: MobileVibrationConfig): MobileVibration;
242
+
243
+ interface InputRouterConfig {
244
+ enableKeyboardMouse?: boolean;
245
+ enableGamepad?: boolean;
246
+ enableTouch?: boolean;
247
+ targetElement?: HTMLElement | Window;
248
+ gridWidth?: number;
249
+ gridHeight?: number;
250
+ debug?: boolean;
251
+ }
252
+ /**
253
+ * Unified input router - manages all input devices
254
+ */
255
+ declare class InputRouter implements IInputSystem {
256
+ private keyboard;
257
+ private mouse;
258
+ private gamepad;
259
+ private touch;
260
+ private touchZone;
261
+ private motion;
262
+ private vibration;
263
+ private config;
264
+ constructor(config?: InputRouterConfig);
265
+ private initialize;
266
+ getButton(device: InputDeviceType, input: number): boolean;
267
+ getButtonJustPressed(device: InputDeviceType, input: number): boolean;
268
+ getButtonJustReleased(device: InputDeviceType, input: number): boolean;
269
+ getAxis(device: InputDeviceType, input: number): number;
270
+ /**
271
+ * Get analog value (0.0 – 1.0) for a gamepad button.
272
+ * Primarily useful for L2/R2 triggers which have a linear pressure range.
273
+ */
274
+ getButtonValue(device: InputDeviceType, input: number): number;
275
+ isLeftMousePressed(): boolean;
276
+ getTextInputs(): string[];
277
+ private getMouseButton;
278
+ private getMouseButtonJustPressed;
279
+ private getMouseButtonJustReleased;
280
+ private getMouseAxis;
281
+ private getTouchAxis;
282
+ private getTouchZoneAxis;
283
+ private getMotionAxis;
284
+ /** Get the motion input device (accelerometer, gyroscope, orientation). */
285
+ getMotion(): MotionInputs | null;
286
+ /** Get the vibration controller. */
287
+ getVibration(): MobileVibration | null;
288
+ /** Mouse X position converted to grid column. */
289
+ getMouseGridX(): number;
290
+ /** Mouse Y position converted to grid row. */
291
+ getMouseGridY(): number;
292
+ /** Whether the given mouse button (0=left, 1=middle, 2=right) is down. */
293
+ isMouseButtonDown(button: number): boolean;
294
+ /** Key codes just pressed this frame. */
295
+ getKeysPressed(): string[];
296
+ /** Key codes currently held down. */
297
+ getKeysHeld(): string[];
298
+ /**
299
+ * Push touch-zone layout from the input binding registry to the TouchZoneInputs device.
300
+ *
301
+ * Must be called whenever the server (or standalone engine) sends updated
302
+ * input bindings so that hit-testing uses the current zone geometry.
303
+ *
304
+ * @param zones - Array of zone definitions from `InputBindingRegistry.getAllTouchZones()`.
305
+ */
306
+ setTouchZones(zones: {
307
+ zoneId: number;
308
+ x: number;
309
+ y: number;
310
+ width: number;
311
+ height: number;
312
+ }[]): void;
313
+ /**
314
+ * Configure the touch-zone coordinate system.
315
+ *
316
+ * This MUST be called whenever:
317
+ * - A new canvas is created (or the first render completes)
318
+ * - The display grid dimensions change
319
+ * - The renderer offsets (letterbox/pillarbox) change
320
+ *
321
+ * Without correct layout info, touch coordinates cannot be converted to
322
+ * grid cell coordinates and zone hit-testing will fail.
323
+ *
324
+ * @param canvas - The actual canvas element from the renderer
325
+ * @param gridWidth - Display width in cells
326
+ * @param gridHeight - Display height in cells
327
+ * @param rendererOffsets - Optional letterbox/pillarbox offsets from the renderer
328
+ */
329
+ setTouchLayout(canvas: HTMLCanvasElement, gridWidth: number, gridHeight: number, rendererOffsets?: {
330
+ offsetX: number;
331
+ offsetY: number;
332
+ }): void;
333
+ start(): void;
334
+ stop(): void;
335
+ reset(): void;
336
+ poll(): void;
337
+ resetDelta(): void;
338
+ destroy(): void;
339
+ }
340
+
341
+ /**
342
+ * Button state with transition detection
343
+ */
344
+ interface ButtonStateWithTransitions {
345
+ pressed: boolean;
346
+ justPressed: boolean;
347
+ justReleased: boolean;
348
+ }
349
+ /**
350
+ * InputCollector - Adapter between InputRouter and Binding evaluation
351
+ */
352
+ declare class InputCollector {
353
+ /**
354
+ * Calculate canvas render metrics for proper coordinate mapping
355
+ *
356
+ * Handles:
357
+ * - object-fit: contain (letterbox/pillarbox black bars)
358
+ * - Renderer centering offsets (Terminal2D may not fill its parent)
359
+ */
360
+ private static calculateRenderMetrics;
361
+ /**
362
+ * Collects raw source values for all axis bindings
363
+ */
364
+ static collectAxisSources(bindings: AxisBinding[], router: IInputSystem): Map<number, number>;
365
+ /**
366
+ * Collects raw source states for all button bindings
367
+ */
368
+ static collectButtonSources(bindings: ButtonBinding[], router: IInputSystem): Map<number, boolean>;
369
+ /**
370
+ * Collects raw source states with transition detection for all button bindings
371
+ */
372
+ static collectButtonSourcesWithTransitions(bindings: ButtonBinding[], router: IInputSystem): Map<number, ButtonStateWithTransitions>;
373
+ /**
374
+ * Calculate mouse position in grid coordinates
375
+ */
376
+ static collectMousePosition(router: IInputSystem, canvas: HTMLCanvasElement, gridWidth: number, gridHeight: number, rendererOffsets?: {
377
+ offsetX: number;
378
+ offsetY: number;
379
+ }): {
380
+ x: number;
381
+ y: number;
382
+ over: boolean;
383
+ isLeftDown: boolean;
384
+ };
385
+ /**
386
+ * Calculate touch positions in grid coordinates
387
+ */
388
+ static collectTouchPositions(router: IInputSystem, canvas: HTMLCanvasElement, gridWidth: number, gridHeight: number, maxTouches?: number, rendererOffsets?: {
389
+ offsetX: number;
390
+ offsetY: number;
391
+ }): Array<{
392
+ id: number;
393
+ x: number;
394
+ y: number;
395
+ over: boolean;
396
+ }>;
397
+ /**
398
+ * Collects text input events from keyboard
399
+ */
400
+ static collectTextInputs(router: IInputSystem): string[];
401
+ }
402
+
403
+ /**
404
+ * Keyboard button state with press/release detection
405
+ */
406
+ interface KeyButtonState {
407
+ pressed: boolean;
408
+ justPressed: boolean;
409
+ justReleased: boolean;
410
+ }
411
+ interface KeyState {
412
+ [key: string]: KeyButtonState;
413
+ }
414
+ interface KeyboardCallbacks {
415
+ onKeyDown?: (key: string, event: KeyboardEvent) => void;
416
+ onKeyUp?: (key: string, event: KeyboardEvent) => void;
417
+ }
418
+ declare class KeyboardInputs extends BaseInputs {
419
+ private keys;
420
+ private textInputsThisFrame;
421
+ private keyboardCallbacks;
422
+ private boundHandlers;
423
+ constructor(targetElement?: HTMLElement | Window, config?: InputConfig);
424
+ start(): void;
425
+ stop(): void;
426
+ reset(): void;
427
+ resetDelta(): void;
428
+ poll(): void;
429
+ setCallbacks(callbacks: KeyboardCallbacks): void;
430
+ getTextInputs(): string[];
431
+ isKeyPressed(key: string): boolean;
432
+ isKeyJustPressed(key: string): boolean;
433
+ isKeyJustReleased(key: string): boolean;
434
+ /** Returns all key codes that were just pressed this frame. */
435
+ getKeysJustPressed(): string[];
436
+ /** Returns all key codes currently held down. */
437
+ getKeysHeld(): string[];
438
+ private shouldAllowDefault;
439
+ private handleKeyDown;
440
+ private handleKeyUp;
441
+ private handleBlur;
442
+ }
443
+
444
+ interface MouseButtonState {
445
+ pressed: boolean;
446
+ justPressed: boolean;
447
+ justReleased: boolean;
448
+ }
449
+ interface MouseButtons {
450
+ left: MouseButtonState;
451
+ middle: MouseButtonState;
452
+ right: MouseButtonState;
453
+ }
454
+ declare class MouseInputs extends BaseInputs {
455
+ private mouseButtons;
456
+ private mousePosition;
457
+ private mouseDelta;
458
+ private wheelDelta;
459
+ private boundHandlers;
460
+ constructor(targetElement?: HTMLElement | Window, config?: InputConfig);
461
+ start(): void;
462
+ stop(): void;
463
+ reset(): void;
464
+ poll(): void;
465
+ resetDelta(): void;
466
+ isLeftMousePressed(): boolean;
467
+ isLeftMouseJustPressed(): boolean;
468
+ isLeftMouseJustReleased(): boolean;
469
+ isRightMousePressed(): boolean;
470
+ isRightMouseJustPressed(): boolean;
471
+ isRightMouseJustReleased(): boolean;
472
+ isMiddleMousePressed(): boolean;
473
+ getMousePosition(): Vector2;
474
+ getMouseDelta(): Vector2;
475
+ getWheelDelta(): number;
476
+ private static readonly BUTTON_NAMES;
477
+ private handleMouseDown;
478
+ private handleMouseUp;
479
+ private handleMouseMove;
480
+ private handleWheel;
481
+ private handleContextMenu;
482
+ private handleBlur;
483
+ /**
484
+ * Checks if the event target is the game canvas or a designated input surface.
485
+ * This logic helps isolate game inputs from standard web UI elements.
486
+ */
487
+ private isInteractiveSurfaceEvent;
488
+ }
489
+
490
+ /**
491
+ * Gamepad button state with press detection
492
+ */
493
+ interface GamepadButtonState {
494
+ pressed: boolean;
495
+ justPressed: boolean;
496
+ justReleased: boolean;
497
+ value: number;
498
+ touched: boolean;
499
+ }
500
+ /**
501
+ * Complete state of a single gamepad
502
+ */
503
+ interface GamepadState {
504
+ id: string;
505
+ index: number;
506
+ connected: boolean;
507
+ buttons: GamepadButtonState[];
508
+ axes: number[];
509
+ timestamp: number;
510
+ mapping: string;
511
+ }
512
+ interface GamepadVibrationOptions {
513
+ duration: number;
514
+ strongMagnitude?: number;
515
+ weakMagnitude?: number;
516
+ startDelay?: number;
517
+ }
518
+ declare class GamepadInputs extends BaseInputs {
519
+ private gamepads;
520
+ private previousGameState;
521
+ private rafId;
522
+ private boundHandlers;
523
+ constructor(targetElement?: HTMLElement | Window, config?: InputConfig);
524
+ start(): void;
525
+ stop(): void;
526
+ private startPolling;
527
+ private stopPolling;
528
+ poll(): void;
529
+ reset(): void;
530
+ resetDelta(): void;
531
+ private updateGamepadState;
532
+ isButtonPressed(gamepadIndex: number, buttonIndex: number): boolean;
533
+ isButtonJustPressed(gamepadIndex: number, buttonIndex: number): boolean;
534
+ isButtonJustReleased(gamepadIndex: number, buttonIndex: number): boolean;
535
+ getAxis(gamepadIndex: number, axisIndex: number): number;
536
+ /**
537
+ * Get the analog value (0.0 – 1.0) of a button.
538
+ * Useful for L2/R2 triggers which report a continuous pressure value.
539
+ */
540
+ getButtonValue(gamepadIndex: number, buttonIndex: number): number;
541
+ readonly vibrationPresets: {
542
+ tap: {
543
+ duration: number;
544
+ strongMagnitude: number;
545
+ weakMagnitude: number;
546
+ };
547
+ impact: {
548
+ duration: number;
549
+ strongMagnitude: number;
550
+ weakMagnitude: number;
551
+ };
552
+ heavy: {
553
+ duration: number;
554
+ strongMagnitude: number;
555
+ weakMagnitude: number;
556
+ };
557
+ success: {
558
+ duration: number;
559
+ strongMagnitude: number;
560
+ weakMagnitude: number;
561
+ };
562
+ error: {
563
+ duration: number;
564
+ strongMagnitude: number;
565
+ weakMagnitude: number;
566
+ };
567
+ explosion: {
568
+ duration: number;
569
+ strongMagnitude: number;
570
+ weakMagnitude: number;
571
+ };
572
+ };
573
+ vibrate(gamepadIndex: number, options: GamepadVibrationOptions): Promise<boolean>;
574
+ vibratePreset(gamepadIndex: number, preset: keyof typeof this.vibrationPresets): Promise<boolean>;
575
+ vibrateAll(options: GamepadVibrationOptions): Promise<void>;
576
+ stopVibration(gamepadIndex: number): Promise<void>;
577
+ private handleGamepadConnected;
578
+ private handleGamepadDisconnected;
579
+ private cloneState;
580
+ }
581
+
582
+ interface TouchPoint {
583
+ id: number;
584
+ nativeId: number;
585
+ active: boolean;
586
+ justPressed: boolean;
587
+ justReleased: boolean;
588
+ x: number;
589
+ y: number;
590
+ startX: number;
591
+ startY: number;
592
+ }
593
+ declare class TouchInputs extends BaseInputs {
594
+ private touches;
595
+ private nativeToInternal;
596
+ private maxTouches;
597
+ private boundHandlers;
598
+ constructor(targetElement?: HTMLElement | Window, config?: InputConfig);
599
+ start(): void;
600
+ stop(): void;
601
+ poll(): void;
602
+ reset(): void;
603
+ resetDelta(): void;
604
+ isTouchActive(id: number): boolean;
605
+ isTouchJustPressed(id: number): boolean;
606
+ isTouchJustReleased(id: number): boolean;
607
+ getTouchPosition(id: number): {
608
+ x: number;
609
+ y: number;
610
+ } | null;
611
+ getAllTouches(): TouchPoint[];
612
+ private updateTouches;
613
+ private handleTouchStart;
614
+ private handleTouchEnd;
615
+ private handleTouchMove;
616
+ private handleTouchCancel;
617
+ private handleVisibilityChange;
618
+ }
619
+
620
+ interface TouchZoneDefinition {
621
+ id: number;
622
+ x: number;
623
+ y: number;
624
+ width: number;
625
+ height: number;
626
+ }
627
+ interface TouchZoneState {
628
+ pressed: boolean;
629
+ justPressed: boolean;
630
+ justReleased: boolean;
631
+ lastX: number;
632
+ lastY: number;
633
+ }
634
+ interface TouchZoneConfig extends InputConfig {
635
+ targetElement: HTMLElement;
636
+ gridWidth: number;
637
+ gridHeight: number;
638
+ /** Optional renderer offsets (content centered inside canvas) */
639
+ rendererOffsets?: {
640
+ offsetX: number;
641
+ offsetY: number;
642
+ };
643
+ zones?: TouchZoneDefinition[];
644
+ }
645
+ declare class TouchZoneInputs extends BaseInputs {
646
+ private touch;
647
+ private zones;
648
+ private zoneStates;
649
+ private gridWidth;
650
+ private gridHeight;
651
+ private rendererOffsets;
652
+ constructor(touch: TouchInputs, config: TouchZoneConfig);
653
+ start(): void;
654
+ stop(): void;
655
+ reset(): void;
656
+ resetDelta(): void;
657
+ /**
658
+ * Update the target element used for coordinate calculations.
659
+ *
660
+ * By default this is `document.body`, but for accurate hit-testing it MUST
661
+ * be set to the actual canvas element rendered by the game's renderer.
662
+ * Otherwise touch coordinates cannot be mapped to grid cells correctly.
663
+ */
664
+ setTargetElement(element: HTMLElement): void;
665
+ /** Update layout info (grid size / offsets) when display changes */
666
+ setLayout(gridWidth: number, gridHeight: number, rendererOffsets?: {
667
+ offsetX: number;
668
+ offsetY: number;
669
+ }): void;
670
+ /** Define zones (replace all). Zone IDs must be 0-31. */
671
+ setZones(zones: TouchZoneDefinition[]): void;
672
+ /** Clear all zones and their state */
673
+ clearZones(): void;
674
+ /** Must be called before reads each frame to sync with current touches */
675
+ updateFromTouches(): void;
676
+ poll(): void;
677
+ isZonePressed(id: number): boolean;
678
+ isZoneJustPressed(id: number): boolean;
679
+ isZoneJustReleased(id: number): boolean;
680
+ /**
681
+ * Get zone axis value (normalized -1 to +1 relative to zone center)
682
+ *
683
+ * For joystick-like zones: returns position within zone as -1 to +1
684
+ * - Center of zone = 0
685
+ * - Left/Top edge = -1
686
+ * - Right/Bottom edge = +1
687
+ *
688
+ * Returns 0 if zone not found or not pressed.
689
+ */
690
+ getZoneAxis(zoneId: number, axis: 'x' | 'y'): number;
691
+ /**
692
+ * Get zone position in display cell coordinates (absolute)
693
+ */
694
+ getZonePosition(zoneId: number): {
695
+ x: number;
696
+ y: number;
697
+ } | null;
698
+ /**
699
+ * Calculate render metrics accounting for object-fit: contain
700
+ * (letterbox/pillarbox) and renderer content offsets.
701
+ */
702
+ private calculateRenderMetrics;
703
+ }
704
+
705
+ export { BaseInputs, GamepadInputs, InputCollector, InputRouter, KeyboardInputs, MobileVibration, MotionInputs, MouseInputs, TouchInputs, TouchZoneInputs, VibrationPatterns, getMobileVibration };
706
+ export type { AccelerometerData, ButtonState, ButtonStateWithTransitions, GamepadButtonState, GamepadState, GamepadVibrationOptions, GyroscopeData, InputConfig, InputRouterConfig, KeyButtonState, KeyState, KeyboardCallbacks, MobileVibrationConfig, MotionCallbacks, MotionInputsConfig, MouseButtonState, MouseButtons, OrientationData, TouchPoint, TouchZoneConfig, TouchZoneDefinition, TouchZoneState, VibrationPattern };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var v=class{isActive=!1;targetElement;config;constructor(e=window,t={}){this.targetElement=e,this.config={enabled:!0,preventDefault:!1,stopPropagation:!1,debug:!1,...t}}isListening(){return this.isActive}destroy(){this.stop()}getTargetElement(){return this.targetElement}enable(){this.config.enabled=!0,this.isActive||this.start()}disable(){this.config.enabled=!1,this.isActive&&this.stop()}isEnabled(){return this.config.enabled??!0}};import{InputDeviceType as d,KeyboardInput as O,MouseInput as y,MotionInput as M}from"@primitiv/types";var D=class extends v{keys={};textInputsThisFrame=[];keyboardCallbacks={};boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={keyDown:this.handleKeyDown.bind(this),keyUp:this.handleKeyUp.bind(this),blur:this.handleBlur.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.addEventListener("keyup",this.boundHandlers.keyUp),window.addEventListener("blur",this.boundHandlers.blur),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("keydown",this.boundHandlers.keyDown),this.targetElement.removeEventListener("keyup",this.boundHandlers.keyUp),window.removeEventListener("blur",this.boundHandlers.blur),this.isActive=!1)}reset(){this.keys={},this.textInputsThisFrame=[]}resetDelta(){}poll(){for(let e in this.keys)this.keys[e].justPressed=!1,this.keys[e].justReleased=!1;this.textInputsThisFrame=[]}setCallbacks(e){this.keyboardCallbacks={...this.keyboardCallbacks,...e}}getTextInputs(){return this.textInputsThisFrame}isKeyPressed(e){return this.keys[e]?.pressed||!1}isKeyJustPressed(e){return this.keys[e]?.justPressed||!1}isKeyJustReleased(e){return this.keys[e]?.justReleased||!1}getKeysJustPressed(){let e=[];for(let t in this.keys)this.keys[t].justPressed&&e.push(t);return e}getKeysHeld(){let e=[];for(let t in this.keys)this.keys[t].pressed&&e.push(t);return e}shouldAllowDefault(e,t){let s=/^F([1-9]|1[0-2])$/.test(e),n=(t.ctrlKey||t.metaKey)&&(e==="KeyT"||e==="KeyW"||e==="KeyR"||e==="KeyN"||e==="Tab");return s||n}handleKeyDown(e){let t=e.code,s=this.shouldAllowDefault(t,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[t]||(this.keys[t]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[t].pressed||(this.keys[t].justPressed=!0,this.keyboardCallbacks.onKeyDown?.(t,e)),this.keys[t].pressed=!0,this.keys[t].justReleased=!1;let n=e.key;n.length===1&&!e.ctrlKey&&!e.metaKey&&this.textInputsThisFrame.push(n)}handleKeyUp(e){let t=e.code,s=this.shouldAllowDefault(t,e);this.config.preventDefault&&!s&&e.preventDefault(),this.config.stopPropagation&&!s&&e.stopPropagation(),this.keys[t]||(this.keys[t]={pressed:!1,justPressed:!1,justReleased:!1}),this.keys[t].pressed&&(this.keys[t].justReleased=!0,this.keyboardCallbacks.onKeyUp?.(t,e)),this.keys[t].pressed=!1,this.keys[t].justPressed=!1}handleBlur(){this.reset()}};import{Vector2 as P}from"@primitiv/types";var A=class b extends v{mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}};mousePosition=new P(0,0);mouseDelta=new P(0,0);wheelDelta=0;boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={mouseDown:this.handleMouseDown.bind(this),mouseUp:this.handleMouseUp.bind(this),mouseMove:this.handleMouseMove.bind(this),wheel:this.handleWheel.bind(this),contextMenu:this.handleContextMenu.bind(this),blur:this.handleBlur.bind(this)}}start(){this.isActive||(this.targetElement.addEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.addEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.addEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.addEventListener("wheel",this.boundHandlers.wheel),this.targetElement.addEventListener("contextmenu",this.boundHandlers.contextMenu),window.addEventListener("blur",this.boundHandlers.blur),this.isActive=!0)}stop(){this.isActive&&(this.targetElement.removeEventListener("mousedown",this.boundHandlers.mouseDown),this.targetElement.removeEventListener("mouseup",this.boundHandlers.mouseUp),this.targetElement.removeEventListener("mousemove",this.boundHandlers.mouseMove),this.targetElement.removeEventListener("wheel",this.boundHandlers.wheel),this.targetElement.removeEventListener("contextmenu",this.boundHandlers.contextMenu),window.removeEventListener("blur",this.boundHandlers.blur),this.isActive=!1)}reset(){this.mouseButtons={left:{pressed:!1,justPressed:!1,justReleased:!1},middle:{pressed:!1,justPressed:!1,justReleased:!1},right:{pressed:!1,justPressed:!1,justReleased:!1}},this.mousePosition=new P(0,0),this.mouseDelta=new P(0,0),this.wheelDelta=0}poll(){this.mouseButtons.left.justPressed=!1,this.mouseButtons.left.justReleased=!1,this.mouseButtons.middle.justPressed=!1,this.mouseButtons.middle.justReleased=!1,this.mouseButtons.right.justPressed=!1,this.mouseButtons.right.justReleased=!1,this.resetDelta()}resetDelta(){this.mouseDelta=new P(0,0),this.wheelDelta=0}isLeftMousePressed(){return this.mouseButtons.left.pressed}isLeftMouseJustPressed(){return this.mouseButtons.left.justPressed}isLeftMouseJustReleased(){return this.mouseButtons.left.justReleased}isRightMousePressed(){return this.mouseButtons.right.pressed}isRightMouseJustPressed(){return this.mouseButtons.right.justPressed}isRightMouseJustReleased(){return this.mouseButtons.right.justReleased}isMiddleMousePressed(){return this.mouseButtons.middle.pressed}getMousePosition(){return this.mousePosition.clone()}getMouseDelta(){return this.mouseDelta.clone()}getWheelDelta(){return this.wheelDelta}static BUTTON_NAMES=["left","middle","right"];handleMouseDown(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault();let t=b.BUTTON_NAMES[e.button];if(t){let s=this.mouseButtons[t];s.pressed||(s.justPressed=!0),s.pressed=!0,s.justReleased=!1}}handleMouseUp(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault();let t=b.BUTTON_NAMES[e.button];if(t){let s=this.mouseButtons[t];s.pressed&&(s.justReleased=!0),s.pressed=!1,s.justPressed=!1}}handleMouseMove(e){let t=new P(e.clientX,e.clientY);this.mouseDelta=t.subtract(this.mousePosition),this.mousePosition=t}handleWheel(e){this.config.preventDefault&&this.isInteractiveSurfaceEvent(e)&&e.preventDefault(),this.wheelDelta=e.deltaY}handleContextMenu(e){this.isInteractiveSurfaceEvent(e)&&e.preventDefault()}handleBlur(){this.reset()}isInteractiveSurfaceEvent(e){let t=e.target;return t?(t.tagName||"").toLowerCase()==="canvas"||(t.getAttribute?.("data-primitiv-input-surface")??"").toLowerCase()==="true"?!0:!!t.closest?.('canvas, [data-primitiv-input-surface="true"]'):!1}};var B=class extends v{gamepads=new Map;previousGameState=new Map;rafId=null;boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={connected:this.handleGamepadConnected.bind(this),disconnected:this.handleGamepadDisconnected.bind(this)}}start(){this.isActive||(window.addEventListener("gamepadconnected",this.boundHandlers.connected),window.addEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.startPolling(),this.isActive=!0)}stop(){this.isActive&&(window.removeEventListener("gamepadconnected",this.boundHandlers.connected),window.removeEventListener("gamepaddisconnected",this.boundHandlers.disconnected),this.stopPolling(),this.isActive=!1)}startPolling(){let e=()=>{this.poll(),this.rafId=requestAnimationFrame(e)};this.rafId=requestAnimationFrame(e)}stopPolling(){this.rafId!==null&&(cancelAnimationFrame(this.rafId),this.rafId=null)}poll(){let e=navigator.getGamepads();for(let t=0;t<e.length;t++){let s=e[t];s&&this.updateGamepadState(s)}}reset(){this.gamepads.clear(),this.previousGameState.clear()}resetDelta(){this.previousGameState.clear();for(let[e,t]of this.gamepads)this.previousGameState.set(e,this.cloneState(t))}updateGamepadState(e){let t=this.gamepads.get(e.index),s=e.buttons.map((n,i)=>{let o=t?.buttons[i],a=n.pressed,u=o?.pressed??!1;return{pressed:a,justPressed:a&&!u,justReleased:!a&&u,value:n.value,touched:n.touched}});this.gamepads.set(e.index,{id:e.id,index:e.index,connected:e.connected,buttons:s,axes:[...e.axes],timestamp:e.timestamp,mapping:e.mapping})}isButtonPressed(e,t){return this.gamepads.get(e)?.buttons[t]?.pressed??!1}isButtonJustPressed(e,t){return this.gamepads.get(e)?.buttons[t]?.justPressed??!1}isButtonJustReleased(e,t){return this.gamepads.get(e)?.buttons[t]?.justReleased??!1}getAxis(e,t){let s=this.gamepads.get(e);return s?t===4?s.buttons[6]?.value??0:t===5?s.buttons[7]?.value??0:s.axes[t]??0:0}getButtonValue(e,t){return this.gamepads.get(e)?.buttons[t]?.value??0}vibrationPresets={tap:{duration:50,strongMagnitude:.3,weakMagnitude:.5},impact:{duration:100,strongMagnitude:.7,weakMagnitude:.3},heavy:{duration:200,strongMagnitude:1,weakMagnitude:.2},success:{duration:150,strongMagnitude:.4,weakMagnitude:.6},error:{duration:300,strongMagnitude:.8,weakMagnitude:.4},explosion:{duration:400,strongMagnitude:1,weakMagnitude:.8}};async vibrate(e,t){let s=navigator.getGamepads()[e];if(!s||!s.vibrationActuator)return!1;try{return await s.vibrationActuator.playEffect("dual-rumble",{startDelay:t.startDelay??0,duration:t.duration,strongMagnitude:t.strongMagnitude??1,weakMagnitude:t.weakMagnitude??1}),!0}catch{return!1}}async vibratePreset(e,t){return this.vibrate(e,this.vibrationPresets[t])}async vibrateAll(e){let t=Array.from(this.gamepads.keys()).map(s=>this.vibrate(s,e));await Promise.all(t)}async stopVibration(e){let t=navigator.getGamepads()[e];if(t&&t.vibrationActuator)try{await t.vibrationActuator.reset()}catch{}}handleGamepadConnected(e){this.updateGamepadState(e.gamepad)}handleGamepadDisconnected(e){this.gamepads.delete(e.gamepad.index),this.previousGameState.delete(e.gamepad.index)}cloneState(e){return{...e,buttons:e.buttons.map(t=>({...t})),axes:[...e.axes]}}};var L=class extends v{touches=new Map;nativeToInternal=new Map;maxTouches=10;boundHandlers;constructor(e=window,t={}){super(e,t),this.boundHandlers={touchStart:this.handleTouchStart.bind(this),touchEnd:this.handleTouchEnd.bind(this),touchMove:this.handleTouchMove.bind(this),touchCancel:this.handleTouchCancel.bind(this),visibilityChange:this.handleVisibilityChange.bind(this)}}start(){if(this.isActive)return;let e={passive:!this.config.preventDefault};this.targetElement.addEventListener("touchstart",this.boundHandlers.touchStart,e),this.targetElement.addEventListener("touchend",this.boundHandlers.touchEnd,e),this.targetElement.addEventListener("touchmove",this.boundHandlers.touchMove,e),this.targetElement.addEventListener("touchcancel",this.boundHandlers.touchCancel,e),document.addEventListener("visibilitychange",this.boundHandlers.visibilityChange),this.isActive=!0}stop(){this.isActive&&(this.targetElement.removeEventListener("touchstart",this.boundHandlers.touchStart),this.targetElement.removeEventListener("touchend",this.boundHandlers.touchEnd),this.targetElement.removeEventListener("touchmove",this.boundHandlers.touchMove),this.targetElement.removeEventListener("touchcancel",this.boundHandlers.touchCancel),document.removeEventListener("visibilitychange",this.boundHandlers.visibilityChange),this.isActive=!1)}poll(){let e=[];for(let[t,s]of this.touches)s.justReleased?e.push(t):(s.justPressed=!1,s.justReleased=!1);for(let t of e){let s=this.touches.get(t);s&&(this.nativeToInternal.delete(s.nativeId),this.touches.delete(t))}}reset(){this.touches.clear(),this.nativeToInternal.clear()}resetDelta(){}isTouchActive(e){return this.touches.get(e)?.active??!1}isTouchJustPressed(e){return this.touches.get(e)?.justPressed??!1}isTouchJustReleased(e){return this.touches.get(e)?.justReleased??!1}getTouchPosition(e){let t=this.touches.get(e);return t?{x:t.x,y:t.y}:null}getAllTouches(){return Array.from(this.touches.values()).filter(e=>e.active)}updateTouches(e){let t=new Set;for(let s=0;s<e.touches.length;s++){let n=e.touches[s],i=n.identifier;t.add(i);let o=this.nativeToInternal.get(i),a;if(o===void 0){if(this.touches.size>=this.maxTouches)continue;for(let h=0;h<this.maxTouches;h++)if(!this.touches.has(h)){o=h;break}if(o===void 0)continue;this.nativeToInternal.set(i,o),a=void 0}else a=this.touches.get(o);let u=!0,l=a?.active??!1;this.touches.set(o,{id:o,nativeId:i,active:u,justPressed:u&&!l,justReleased:!1,x:n.clientX,y:n.clientY,startX:a?.startX??n.clientX,startY:a?.startY??n.clientY})}for(let[s,n]of this.nativeToInternal)if(!t.has(s)){let i=this.touches.get(n);i&&i.active&&(i.active=!1,i.justReleased=!0)}}handleTouchStart(e){this.config.preventDefault&&e.preventDefault(),this.updateTouches(e)}handleTouchEnd(e){this.config.preventDefault&&e.preventDefault(),this.updateTouches(e)}handleTouchMove(e){this.config.preventDefault&&e.preventDefault(),this.updateTouches(e)}handleTouchCancel(e){this.handleTouchEnd(e)}handleVisibilityChange(){document.visibilityState==="hidden"&&this.reset()}};var R=class extends v{constructor(t,s){super(s.targetElement,s);this.touch=t;this.gridWidth=s.gridWidth,this.gridHeight=s.gridHeight,this.rendererOffsets=s.rendererOffsets??{offsetX:0,offsetY:0},s.zones&&this.setZones(s.zones)}zones=[];zoneStates=new Map;gridWidth;gridHeight;rendererOffsets;start(){this.isActive=!0}stop(){this.isActive=!1}reset(){this.clearZones()}resetDelta(){}setTargetElement(t){this.targetElement=t}setLayout(t,s,n){this.gridWidth=t,this.gridHeight=s,n&&(this.rendererOffsets=n)}setZones(t){this.zones=t.filter(s=>s.id>=0&&s.id<=31),this.zoneStates.clear();for(let s of this.zones)this.zoneStates.set(s.id,{pressed:!1,justPressed:!1,justReleased:!1,lastX:s.x,lastY:s.y})}clearZones(){this.zones=[],this.zoneStates.clear()}updateFromTouches(){if(this.zones.length===0)return;let t=this.targetElement,s=t.getBoundingClientRect(),{renderWidth:n,renderHeight:i,offsetX:o,offsetY:a}=this.calculateRenderMetrics(t,s),u=n/this.gridWidth,l=i/this.gridHeight,h=this.touch.getAllTouches(),f=new Set,g=new Map;for(let E of h){let m=E.x-s.left-o,p=E.y-s.top-a,T=Math.floor(m/u),x=Math.floor(p/l);for(let c of this.zones)T>=c.x&&T<c.x+c.width&&x>=c.y&&x<c.y+c.height&&(f.add(c.id),g.set(c.id,{x:Math.max(c.x,Math.min(c.x+c.width-1,T)),y:Math.max(c.y,Math.min(c.y+c.height-1,x))}))}for(let E of this.zones){let m=this.zoneStates.get(E.id);if(!m)continue;let p=f.has(E.id);p&&!m.pressed&&(m.justPressed=!0),!p&&m.pressed&&(m.justReleased=!0),m.pressed=p;let T=g.get(E.id);T&&(m.lastX=T.x,m.lastY=T.y)}}poll(){for(let t of this.zoneStates.values())t.justPressed=!1,t.justReleased=!1}isZonePressed(t){return this.zoneStates.get(t)?.pressed??!1}isZoneJustPressed(t){return this.zoneStates.get(t)?.justPressed??!1}isZoneJustReleased(t){return this.zoneStates.get(t)?.justReleased??!1}getZoneAxis(t,s){let n=this.zoneStates.get(t);if(!n||!n.pressed)return 0;let i=this.zones.find(o=>o.id===t);if(!i)return 0;if(s==="x"){let o=(i.width-1)/2,a=i.x+o;return o>0?(n.lastX-a)/o:0}else{let o=(i.height-1)/2,a=i.y+o;return o>0?(n.lastY-a)/o:0}}getZonePosition(t){let s=this.zoneStates.get(t);return s?{x:s.lastX,y:s.lastY}:null}calculateRenderMetrics(t,s){let n=t.width,i=t.height;if(!n||!i)return{renderWidth:s.width,renderHeight:s.height,offsetX:this.rendererOffsets.offsetX,offsetY:this.rendererOffsets.offsetY};let o=n/i,a=s.width/s.height,u,l,h,f;o>a?(u=s.width,l=s.width/o,h=0,f=(s.height-l)/2):(u=s.height*o,l=s.height,h=(s.width-u)/2,f=0);let g=this.rendererOffsets;return h+=g.offsetX,f+=g.offsetY,u-=g.offsetX*2,l-=g.offsetY*2,{renderWidth:u,renderHeight:l,offsetX:h,offsetY:f}}};import{Vector2 as J}from"@primitiv/types";var H=class extends v{accelerometer={x:0,y:0,z:0,includesGravity:!1,timestamp:0};gyroscope={alpha:0,beta:0,gamma:0,timestamp:0};orientation={alpha:null,beta:null,gamma:null,absolute:!1,timestamp:0};smoothedAccel={x:0,y:0,z:0};smoothedGyro={alpha:0,beta:0,gamma:0};smoothedOrientation={alpha:0,beta:0,gamma:0};smoothedTiltX=0;smoothedTiltY=0;calibrationOffset={alpha:0,beta:0,gamma:0};isCalibrated=!1;motionCallbacks={};motionConfig;permissionGranted=!1;smoothingFactor=.85;hasReceivedMotion=!1;hasReceivedOrientation=!1;boundHandlers;constructor(e=window,t={}){super(e,t),this.motionConfig={targetElement:e,includeGravity:t.includeGravity??!0,threshold:t.threshold??.001,autoRequestPermission:t.autoRequestPermission??!1,enabled:t.enabled??!0,debug:t.debug??!1,preventDefault:t.preventDefault??!1,stopPropagation:t.stopPropagation??!1,smoothing:t.smoothing??.85,useAbsoluteOrientation:t.useAbsoluteOrientation??!0},this.smoothingFactor=this.motionConfig.smoothing,this.boundHandlers={devicemotion:this.handleDeviceMotion.bind(this),deviceorientation:this.handleDeviceOrientation.bind(this),deviceorientationabsolute:this.handleDeviceOrientationAbsolute.bind(this)}}async requestPermission(){let e=!0,t=!0;if(typeof DeviceMotionEvent.requestPermission=="function")try{e=await DeviceMotionEvent.requestPermission()==="granted"}catch{e=!1}if(typeof DeviceOrientationEvent.requestPermission=="function")try{t=await DeviceOrientationEvent.requestPermission()==="granted"}catch{t=!1}return this.permissionGranted=e&&t,this.permissionGranted}isPermissionGranted(){return this.permissionGranted}isReceivingMotion(){return this.hasReceivedMotion}isReceivingOrientation(){return this.hasReceivedOrientation}start(){this.isActive||(window.addEventListener("devicemotion",this.boundHandlers.devicemotion),this.motionConfig.useAbsoluteOrientation&&window.addEventListener("deviceorientationabsolute",this.boundHandlers.deviceorientationabsolute),window.addEventListener("deviceorientation",this.boundHandlers.deviceorientation),this.isActive=!0)}stop(){this.isActive&&(window.removeEventListener("devicemotion",this.boundHandlers.devicemotion),window.removeEventListener("deviceorientation",this.boundHandlers.deviceorientation),window.removeEventListener("deviceorientationabsolute",this.boundHandlers.deviceorientationabsolute),this.isActive=!1)}setCallbacks(e){this.motionCallbacks={...this.motionCallbacks,...e}}poll(){}reset(){this.accelerometer={x:0,y:0,z:0,includesGravity:!1,timestamp:0},this.gyroscope={alpha:0,beta:0,gamma:0,timestamp:0},this.orientation={alpha:null,beta:null,gamma:null,absolute:!1,timestamp:0},this.smoothedAccel={x:0,y:0,z:0},this.smoothedGyro={alpha:0,beta:0,gamma:0},this.smoothedOrientation={alpha:0,beta:0,gamma:0},this.smoothedTiltX=0,this.smoothedTiltY=0,this.hasReceivedMotion=!1,this.hasReceivedOrientation=!1}resetDelta(){}calibrate(){this.orientation.beta!==null&&this.orientation.gamma!==null&&(this.calibrationOffset={alpha:this.orientation.alpha??0,beta:this.orientation.beta,gamma:this.orientation.gamma},this.isCalibrated=!0)}clearCalibration(){this.calibrationOffset={alpha:0,beta:0,gamma:0},this.isCalibrated=!1}getIsCalibrated(){return this.isCalibrated}getAccelerometer(){return{...this.smoothedAccel,includesGravity:this.motionConfig.includeGravity,timestamp:this.accelerometer.timestamp}}getGyroscope(){return{...this.smoothedGyro,timestamp:this.gyroscope.timestamp}}getOrientation(){let e=this.smoothedOrientation.alpha,t=this.smoothedOrientation.beta-(this.isCalibrated?this.calibrationOffset.beta:0),s=this.smoothedOrientation.gamma-(this.isCalibrated?this.calibrationOffset.gamma:0);return{alpha:this.orientation.alpha!==null?e:null,beta:this.orientation.beta!==null?t:null,gamma:this.orientation.gamma!==null?s:null,absolute:this.orientation.absolute,timestamp:this.orientation.timestamp}}getRawAccelerometer(){return{...this.accelerometer}}getRawGyroscope(){return{...this.gyroscope}}getRawOrientation(){return{...this.orientation}}getNormalizedTilt(){let e=this.smoothedTiltX,t=this.smoothedTiltY;return this.isCalibrated&&(e-=this.calibrationOffset.gamma/90,t-=this.calibrationOffset.beta/90,e=Math.max(-1,Math.min(1,e)),t=Math.max(-1,Math.min(1,t))),new J(e,t)}getCompassHeading(){return this.orientation.alpha===null?null:this.smoothedOrientation.alpha}setSmoothing(e){this.smoothingFactor=Math.max(0,Math.min(.99,e))}lowPass(e,t){return e*this.smoothingFactor+t*(1-this.smoothingFactor)}lowPassAngle(e,t,s=360){let n=t-e;n>s/2&&(n-=s),n<-s/2&&(n+=s);let i=e+n*(1-this.smoothingFactor);for(;i<0;)i+=s;for(;i>=s;)i-=s;return i}handleDeviceMotion(e){let t=performance.now(),s=this.motionConfig.includeGravity?e.accelerationIncludingGravity:e.acceleration;if(s&&(s.x!==null||s.y!==null||s.z!==null)){this.hasReceivedMotion=!0;let i=s.x??0,o=s.y??0,a=s.z??0;this.accelerometer={x:i,y:o,z:a,includesGravity:this.motionConfig.includeGravity,timestamp:t},this.smoothedAccel={x:this.lowPass(this.smoothedAccel.x,i),y:this.lowPass(this.smoothedAccel.y,o),z:this.lowPass(this.smoothedAccel.z,a)},this.motionCallbacks.onAccelerometer?.(this.getAccelerometer())}let n=e.rotationRate;if(n&&(n.alpha!==null||n.beta!==null||n.gamma!==null)){let i=n.alpha??0,o=n.beta??0,a=n.gamma??0;this.gyroscope={alpha:i,beta:o,gamma:a,timestamp:t},this.smoothedGyro={alpha:this.lowPass(this.smoothedGyro.alpha,i),beta:this.lowPass(this.smoothedGyro.beta,o),gamma:this.lowPass(this.smoothedGyro.gamma,a)},this.motionCallbacks.onGyroscope?.(this.getGyroscope())}}handleDeviceOrientation(e){this.motionConfig.useAbsoluteOrientation&&this.orientation.absolute||this.processOrientationEvent(e,!1)}handleDeviceOrientationAbsolute(e){this.processOrientationEvent(e,!0)}processOrientationEvent(e,t){let s=performance.now();if(e.alpha===null&&e.beta===null&&e.gamma===null)return;this.hasReceivedOrientation=!0;let n=e.alpha??0,i=e.beta??0,o=e.gamma??0;this.orientation={alpha:e.alpha,beta:e.beta,gamma:e.gamma,absolute:t||e.absolute,timestamp:s},this.smoothedOrientation.alpha=this.lowPassAngle(this.smoothedOrientation.alpha,n,360),this.smoothedOrientation.beta=this.lowPass(this.smoothedOrientation.beta,i),this.smoothedOrientation.gamma=this.lowPass(this.smoothedOrientation.gamma,o),this.smoothedTiltX=this.lowPass(this.smoothedTiltX,Math.max(-1,Math.min(1,o/90))),this.smoothedTiltY=this.lowPass(this.smoothedTiltY,Math.max(-1,Math.min(1,Math.max(-90,Math.min(90,i))/90))),this.motionCallbacks.onOrientation?.(this.getOrientation())}};var w={tap:10,mediumTap:25,heavyTap:50,success:[30,50,30],error:[50,30,50,30,50],warning:[100],selection:5,impactLight:15,impactMedium:30,impactHeavy:50,notification:[100,100,100,100,100],sos:[100,30,100,30,100,30,200,30,200,30,200,30,100,30,100,30,100]},I=class{enabled;intensity;supported;userActivated=!1;constructor(e={}){this.enabled=e.enabled??!0,this.intensity=Math.max(0,Math.min(1,e.intensity??1)),this.supported=typeof navigator<"u"&&typeof navigator.vibrate=="function"}isSupported(){return this.supported}isEnabled(){return this.enabled&&this.supported}setEnabled(e){this.enabled=e}setIntensity(e){this.intensity=Math.max(0,Math.min(1,e))}getIntensity(){return this.intensity}hasUserActivation(){return this.userActivated}vibrate(e){if(!this.isEnabled())return!1;let t=this.scalePattern(e),s=navigator.vibrate(t);return s&&(this.userActivated=!0),s}cancel(){this.supported&&navigator.vibrate(0)}tap(){return this.vibrate(w.tap)}mediumTap(){return this.vibrate(w.mediumTap)}heavyTap(){return this.vibrate(w.heavyTap)}success(){return this.vibrate(w.success)}error(){return this.vibrate(w.error)}warning(){return this.vibrate(w.warning)}selection(){return this.vibrate(w.selection)}impactLight(){return this.vibrate(w.impactLight)}impactMedium(){return this.vibrate(w.impactMedium)}impactHeavy(){return this.vibrate(w.impactHeavy)}notification(){return this.vibrate(w.notification)}scalePattern(e){return this.intensity===1?e:typeof e=="number"?Math.round(e*this.intensity):e.map((t,s)=>s%2===0?Math.round(t*this.intensity):t)}},j=null;function ae(b){return j||(j=new I(b)),j}var Z=class{keyboard=null;mouse=null;gamepad=null;touch=null;touchZone=null;motion=null;vibration=null;config;constructor(e={}){this.config={enableKeyboardMouse:e.enableKeyboardMouse??!0,enableGamepad:e.enableGamepad??!0,enableTouch:e.enableTouch??!0,targetElement:e.targetElement??window,gridWidth:e.gridWidth??80,gridHeight:e.gridHeight??25,debug:e.debug??!1},this.initialize()}initialize(){let e=this.config.targetElement;if(this.config.enableKeyboardMouse&&(this.keyboard=new D(e),this.mouse=new A(e)),this.config.enableGamepad&&(this.gamepad=new B(e)),this.config.enableTouch){this.touch=new L(e);let t=e instanceof Window?document.body:e;this.touchZone=new R(this.touch,{targetElement:t,gridWidth:this.config.gridWidth,gridHeight:this.config.gridHeight}),this.motion=new H(e),this.vibration=new I}this.start()}getButton(e,t){switch(e){case d.Keyboard:return this.keyboard?.isKeyPressed(O[t])??!1;case d.Mouse:return this.getMouseButton(t);case d.Gamepad:return this.gamepad?.isButtonPressed(0,t)??!1;case d.Touch:return this.touch?.isTouchActive(t)??!1;case d.TouchZone:return this.touchZone?.isZonePressed(t)??!1;default:return!1}}getButtonJustPressed(e,t){switch(e){case d.Keyboard:return this.keyboard?.isKeyJustPressed(O[t])??!1;case d.Mouse:return this.getMouseButtonJustPressed(t);case d.Gamepad:return this.gamepad?.isButtonJustPressed(0,t)??!1;case d.Touch:return this.touch?.isTouchJustPressed?.(t)??!1;case d.TouchZone:return this.touchZone?.isZoneJustPressed(t)??!1;default:return!1}}getButtonJustReleased(e,t){switch(e){case d.Keyboard:return this.keyboard?.isKeyJustReleased(O[t])??!1;case d.Mouse:return this.getMouseButtonJustReleased(t);case d.Gamepad:return this.gamepad?.isButtonJustReleased(0,t)??!1;case d.Touch:return this.touch?.isTouchJustReleased?.(t)??!1;case d.TouchZone:return this.touchZone?.isZoneJustReleased(t)??!1;default:return!1}}getAxis(e,t){switch(e){case d.Mouse:return this.getMouseAxis(t);case d.Gamepad:return this.gamepad?.getAxis(0,t-100)??0;case d.Touch:return this.getTouchAxis(t);case d.TouchZone:return this.getTouchZoneAxis(t);case d.Motion:return this.getMotionAxis(t);default:return 0}}getButtonValue(e,t){return e===d.Gamepad?this.gamepad?.getButtonValue(0,t)??0:this.getButton(e,t)?1:0}isLeftMousePressed(){return this.mouse?.isLeftMousePressed()??!1}getTextInputs(){return this.keyboard?.getTextInputs()??[]}getMouseButton(e){return this.mouse?e===y.LeftButton?this.mouse.isLeftMousePressed():e===y.RightButton?this.mouse.isRightMousePressed():e===y.MiddleButton?this.mouse.isMiddleMousePressed():!1:!1}getMouseButtonJustPressed(e){return this.mouse?e===y.LeftButton?this.mouse.isLeftMouseJustPressed():e===y.RightButton?this.mouse.isRightMouseJustPressed():!1:!1}getMouseButtonJustReleased(e){return this.mouse?e===y.LeftButton?this.mouse.isLeftMouseJustReleased():e===y.RightButton?this.mouse.isRightMouseJustReleased():!1:!1}getMouseAxis(e){return this.mouse?e===y.PositionX?this.mouse.getMousePosition().x:e===y.PositionY?this.mouse.getMousePosition().y:e===y.DeltaX?this.mouse.getMouseDelta().x:e===y.DeltaY?this.mouse.getMouseDelta().y:e===y.WheelDeltaY?this.mouse.getWheelDelta():0:0}getTouchAxis(e){if(!this.touch)return 0;if(e>=100&&e<200){let t=Math.floor((e-100)/2),s=(e-100)%2===1,n=this.touch.getTouchPosition(t);return n?s?n.y:n.x:0}return 0}getTouchZoneAxis(e){if(!this.touchZone)return 0;if(e>=100&&e<200){let t=Math.floor((e-100)/2),s=(e-100)%2===1;return this.touchZone.getZoneAxis(t,s?"y":"x")}return 0}getMotionAxis(e){if(!this.motion)return 0;switch(e){case M.AccelerometerX:return this.motion.getAccelerometer().x;case M.AccelerometerY:return this.motion.getAccelerometer().y;case M.AccelerometerZ:return this.motion.getAccelerometer().z;case M.GyroscopeAlpha:return this.motion.getGyroscope().alpha;case M.GyroscopeBeta:return this.motion.getGyroscope().beta;case M.GyroscopeGamma:return this.motion.getGyroscope().gamma;case M.OrientationAlpha:return this.motion.getOrientation().alpha??0;case M.OrientationBeta:return this.motion.getOrientation().beta??0;case M.OrientationGamma:return this.motion.getOrientation().gamma??0;case M.TiltX:return this.motion.getNormalizedTilt().x;case M.TiltY:return this.motion.getNormalizedTilt().y;case M.CompassHeading:return this.motion.getCompassHeading()??0;default:return 0}}getMotion(){return this.motion}getVibration(){return this.vibration}getMouseGridX(){if(!this.mouse)return 0;let e=this.mouse.getMousePosition().x,t=this.config.targetElement,s,n;if(t instanceof Window)s=t.innerWidth,n=0;else{let i=t.getBoundingClientRect();s=i.width,n=i.left}return s===0?0:Math.floor((e-n)/s*this.config.gridWidth)}getMouseGridY(){if(!this.mouse)return 0;let e=this.mouse.getMousePosition().y,t=this.config.targetElement,s,n;if(t instanceof Window)s=t.innerHeight,n=0;else{let i=t.getBoundingClientRect();s=i.height,n=i.top}return s===0?0:Math.floor((e-n)/s*this.config.gridHeight)}isMouseButtonDown(e){return this.mouse?e===0?this.mouse.isLeftMousePressed():e===1?this.mouse.isMiddleMousePressed():e===2?this.mouse.isRightMousePressed():!1:!1}getKeysPressed(){return this.keyboard?.getKeysJustPressed()??[]}getKeysHeld(){return this.keyboard?.getKeysHeld()??[]}setTouchZones(e){this.touchZone&&this.touchZone.setZones(e.map(t=>({id:t.zoneId,x:t.x,y:t.y,width:t.width,height:t.height})))}setTouchLayout(e,t,s,n){this.touchZone&&(this.touchZone.setTargetElement(e),this.touchZone.setLayout(t,s,n))}start(){this.keyboard?.start(),this.mouse?.start(),this.gamepad?.start(),this.touch?.start(),this.touchZone?.start(),this.motion?.start()}stop(){this.keyboard?.stop(),this.mouse?.stop(),this.gamepad?.stop(),this.touch?.stop(),this.touchZone?.stop(),this.motion?.stop()}reset(){this.keyboard?.reset(),this.mouse?.reset(),this.gamepad?.reset(),this.touch?.reset(),this.touchZone?.reset(),this.motion?.reset()}poll(){this.keyboard?.poll(),this.mouse?.poll(),this.gamepad?.poll(),this.touchZone?.poll(),this.touch?.poll(),this.touchZone?.updateFromTouches(),this.motion?.poll()}resetDelta(){this.keyboard?.resetDelta(),this.mouse?.resetDelta(),this.gamepad?.resetDelta(),this.touch?.resetDelta(),this.touchZone?.resetDelta(),this.motion?.resetDelta()}destroy(){this.stop(),this.keyboard?.destroy(),this.mouse?.destroy(),this.gamepad?.destroy(),this.touch?.destroy(),this.touchZone?.destroy(),this.motion?.destroy()}};import{InputDeviceType as r}from"@primitiv/types";var K=class b{static calculateRenderMetrics(e,t){let s=e.getBoundingClientRect(),n=e.width/e.height,i=s.width/s.height,o,a,u,l;n>i?(o=s.width,a=s.width/n,u=0,l=(s.height-a)/2):(o=s.height*n,a=s.height,u=(s.width-o)/2,l=0);let h=t?.offsetX||0,f=t?.offsetY||0;return u+=h,l+=f,o-=h*2,a-=f*2,{renderWidth:o,renderHeight:a,offsetX:u,offsetY:l,rect:s}}static collectAxisSources(e,t){let s=new Map;for(let n of e)for(let i of n.sources){if(s.has(i.sourceId))continue;let o=0,a=!1;if(i.type===r.Keyboard&&i.negativeKey!==void 0&&i.positiveKey!==void 0){let u=t.getButton(r.Keyboard,i.negativeKey);t.getButton(r.Keyboard,i.positiveKey)&&(o+=1),u&&(o-=1),a=!0}else if(i.type===r.Mouse&&i.mouseAxis!==void 0)o=t.getAxis(r.Mouse,i.mouseAxis),a=!0;else if(i.type===r.Gamepad&&i.axis!==void 0)o=t.getAxis(r.Gamepad,i.axis),a=!0;else if(i.type===r.Touch&&i.touchId!==void 0&&i.touchAxis!==void 0){let u=100+i.touchId*2,l=i.touchAxis==="x"?u:u+1;o=t.getAxis(r.Touch,l),a=!0}else if(i.type===r.TouchZone&&i.touchZoneId!==void 0&&i.touchZoneAxis!==void 0){let u=100+i.touchZoneId*2,l=i.touchZoneAxis==="x"?u:u+1;o=t.getAxis(r.TouchZone,l),a=!0}else i.type===r.Motion&&i.motionAxis!==void 0&&(o=t.getAxis(r.Motion,i.motionAxis),a=!0);a&&s.set(i.sourceId,o)}return s}static collectButtonSources(e,t){let s=new Map;for(let n of e)for(let i of n.sources){if(s.has(i.sourceId))continue;let o=!1,a=!1;i.type===r.Keyboard&&i.key!==void 0?(o=t.getButton(r.Keyboard,i.key),a=!0):i.type===r.Mouse&&i.mouseButton!==void 0?(o=t.getButton(r.Mouse,i.mouseButton),a=!0):i.type===r.Gamepad&&i.button!==void 0?(o=t.getButton(r.Gamepad,i.button),a=!0):i.type===r.Touch&&i.touchButton!==void 0?(o=t.getButton(r.Touch,i.touchButton),a=!0):i.type===r.TouchZone&&i.touchZoneId!==void 0&&(o=t.getButton(r.TouchZone,i.touchZoneId),a=!0),a&&s.set(i.sourceId,o)}return s}static collectButtonSourcesWithTransitions(e,t){let s=new Map;for(let n of e)for(let i of n.sources){if(s.has(i.sourceId))continue;let o=!1,a=!1,u=!1,l=!1;i.type===r.Keyboard&&i.key!==void 0?(o=t.getButton(r.Keyboard,i.key),a=t.getButtonJustPressed(r.Keyboard,i.key),u=t.getButtonJustReleased(r.Keyboard,i.key),l=!0):i.type===r.Mouse&&i.mouseButton!==void 0?(o=t.getButton(r.Mouse,i.mouseButton),a=t.getButtonJustPressed(r.Mouse,i.mouseButton),u=t.getButtonJustReleased(r.Mouse,i.mouseButton),l=!0):i.type===r.Gamepad&&i.button!==void 0?(o=t.getButton(r.Gamepad,i.button),a=t.getButtonJustPressed(r.Gamepad,i.button),u=t.getButtonJustReleased(r.Gamepad,i.button),l=!0):i.type===r.Touch&&i.touchButton!==void 0?(o=t.getButton(r.Touch,i.touchButton),a=t.getButtonJustPressed(r.Touch,i.touchButton),u=t.getButtonJustReleased(r.Touch,i.touchButton),l=!0):i.type===r.TouchZone&&i.touchZoneId!==void 0&&(o=t.getButton(r.TouchZone,i.touchZoneId),a=t.getButtonJustPressed(r.TouchZone,i.touchZoneId),u=t.getButtonJustReleased(r.TouchZone,i.touchZoneId),l=!0),l&&s.set(i.sourceId,{pressed:o,justPressed:a,justReleased:u})}return s}static collectMousePosition(e,t,s,n,i){let o=e.getAxis(r.Mouse,100),a=e.getAxis(r.Mouse,101),u=e.getButton(r.Mouse,0),{renderWidth:l,renderHeight:h,offsetX:f,offsetY:g,rect:E}=b.calculateRenderMetrics(t,i),m=o-E.left-f,p=a-E.top-g,T=l/s,x=h/n,c=Math.floor(m/T),C=Math.floor(p/x),k=m>=0&&m<l&&p>=0&&p<h;return{x:Math.max(0,Math.min(s-1,c)),y:Math.max(0,Math.min(n-1,C)),over:k,isLeftDown:u}}static collectTouchPositions(e,t,s,n,i=10,o){let a=[],{renderWidth:u,renderHeight:l,offsetX:h,offsetY:f,rect:g}=b.calculateRenderMetrics(t,o),E=u/s,m=l/n;for(let p=0;p<i;p++)if(e.getButton(r.Touch,p)){let x=100+p*2,c=100+p*2+1,C=e.getAxis(r.Touch,x),k=e.getAxis(r.Touch,c),G=C-g.left-h,S=k-g.top-f,Y=Math.floor(G/E),X=Math.floor(S/m),W=G>=0&&G<u&&S>=0&&S<l;a.push({id:p,x:Math.max(0,Math.min(s-1,Y)),y:Math.max(0,Math.min(n-1,X)),over:W})}return a}static collectTextInputs(e){return typeof e.getTextInputs=="function"?e.getTextInputs():[]}};export{v as BaseInputs,B as GamepadInputs,K as InputCollector,Z as InputRouter,D as KeyboardInputs,I as MobileVibration,H as MotionInputs,A as MouseInputs,L as TouchInputs,R as TouchZoneInputs,w as VibrationPatterns,ae as getMobileVibration};
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@primitiv/input",
3
+ "version": "0.19.0",
4
+ "description": "Primitiv input module",
5
+ "author": "THP Software",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/thp-software/primitiv",
9
+ "directory": "packages/input"
10
+ },
11
+ "homepage": "https://primitivengine.com",
12
+ "bugs": {
13
+ "url": "https://github.com/thp-software/primitiv/issues"
14
+ },
15
+ "license": "Apache-2.0",
16
+ "type": "module",
17
+ "main": "./dist/index.cjs",
18
+ "module": "./dist/index.mjs",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.mjs",
24
+ "require": "./dist/index.cjs"
25
+ }
26
+ },
27
+ "engines": {
28
+ "node": ">=18.0.0"
29
+ },
30
+ "sideEffects": false,
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE.txt"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "@primitiv/types": "0.19.0"
41
+ },
42
+ "devDependencies": {
43
+ "typescript": "^5.6.3"
44
+ },
45
+ "scripts": {
46
+ "build": "rimraf dist && node ../../scripts/build-package.mjs packages/input",
47
+ "dev": "tsc --watch",
48
+ "clean": "rimraf dist",
49
+ "lint": "eslint \"src/**/*.ts\" --max-warnings 0",
50
+ "typecheck": "tsc --noEmit",
51
+ "test": "node --test --import tsx src/**/*.test.ts"
52
+ }
53
+ }