Repository: vaneenige/unswitch
Branch: master
Commit: 88e073bce1e3
Files: 10
Total size: 11.9 KB
Directory structure:
gitextract_gn2ydkn5/
├── .editorconfig
├── .gitignore
├── LICENSE
├── README.md
├── demo/
│ ├── index.html
│ └── src/
│ ├── index.js
│ └── style.css
├── package.json
├── rollup.config.js
└── src/
└── index.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
indent_size = 2
indent_style = space
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
================================================
FILE: .gitignore
================================================
dist
node_modules
.DS_Store
package-lock.json
.vscode/
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018 Colin van Eenige
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# Unswitch
[](https://www.npmjs.com/package/unswitch)
[](https://unpkg.com/unswitch)
[](https://github.com/vaneenige/unswitch/blob/master/LICENSE)
[](https://github.com/vaneenige/unswitch/blob/master/package.json)
Unswitch is a tiny event handler for Switch controllers on the web based on the Gamepad API. Attach callbacks to button presses (up & down) and the joystick!
## Install
```
$ npm install --save unswitch
```
> Use script tags or modules? Check out the version on [unpkg](https://unpkg.com/unswitch)!
## Setup
Connecting a Switch controller is easy: pair it with bluetooth and you're ready to go! This library doesn't listen to `connected` or `disconnected` events but in some cases it might be useful. Here's how you can listen to these events:
```js
window.addEventListener("gamepadconnected", ({ gamepad }) => {});
```
```js
window.addEventListener("gamepaddisconnected", ({ gamepad }) => {});
```
## Usage
```js
// Import the library
import Unswitch from 'unswitch';
// Observe a controller
const unswitch = new Unswitch({
side: 'L', // or R
buttons: (button, pressed, side) => console.log(`Catch-all - button: ${button} was ${pressed ? 'pressed' : 'released'} on the ${side} side`),
b: p => {},
a: p => {},
y: p => {},
x: p => {},
sl: p => {},
sr: p => {},
minus: p => {},
plus: p => {},
lstick: p => {},
rstick: p => {},
home: p => {},
screenshot: p => {},
bumper: p => {}, // L or R
trigger: p => {}, // ZL or ZR
axes: p => {},
});
function render() {
// Call the update function manually
unswitch.update();
requestAnimationFrame(render);
}
render();
```
Please note that it's not required to pass all button-functions to Unswitch and will only be executed when you provide them.
You are able to use the `buttons` function to catch all button presses and implement your own logic using the provided data. The `buttons` function will always be executed when provided, even when the button is also passed as property.
It's possible to connect up to two controllers at the same time. To make this work `side` is to be passed with either `L` (left) or `R` (right) for the controllers respectively. Calling `unswitch.update()` will check every button for a change in state. If a callback is provided the new state is passed along. The axis works in the same way, but instead of a `boolean` it will return a `number` from 0 to 8. Number 0 to 7 are for the joystick positions going clockwise, number 8 is used as default (center).
> Have a look at the demo on [Codepen](https://codepen.io/cvaneenige/pen/gjdJrP)!
## Contribute
Are you excited about this library and have interesting ideas on how to improve it? Please tell me or contribute directly! 🙌
```
npm install > npm run demo > http://localhost:8080
```
## License
MIT © Colin van Eenige
================================================
FILE: demo/index.html
================================================
Demo
Event history:
================================================
FILE: demo/src/index.js
================================================
import Unswitch from '../../src/index';
const ul = document.querySelector('ul');
function lb(side, control, state) {
ul.innerHTML = `${side} ${control} was ${state ? 'pressed' : 'released'} ${ul.innerHTML}`;
}
function la(controller, position) {
ul.innerHTML = `${controller} ~ Axes position ${position} ${ul.innerHTML}`;
}
function catchAll(button, pressed, side) {
const enableCatchAll = false;
if (enableCatchAll) ul.innerHTML = `Catch-all - button: ${button} was ${pressed ? 'pressed' : 'released'} on the ${side} side ${ul.innerHTML}`;
}
function createController(s) {
const controller = new Unswitch({
side: s,
buttons: catchAll,
b: p => lb(s, ' ~ B', p),
a: p => lb(s, ' ~ A', p),
y: p => lb(s, ' ~ Y', p),
x: p => lb(s, ' ~ X', p),
sl: p => lb(s, ' ~ SL', p),
sr: p => lb(s, ' ~ SR', p),
minus: p => lb(s, ' ~ Minus ', p),
plus: p => lb(s, ' ~ Plus', p),
lstick: p => lb(s, ' ~ Lstick', p),
rstick: p => lb(s, ' ~ Rstick', p),
home: p => lb(s, ' ~ Home', p),
screenshot: p => lb(s, ' ~ Screenshot', p),
bumper: p => lb(s, ' ~ Bumper', p), // L or R
trigger: p => lb(s, ' ~ Trigger', p), // ZL or ZR
axes: p => la(s, p),
});
return controller;
}
const controllerLeft = createController('L');
const controllerRight = createController('R');
function render() {
controllerLeft.update();
controllerRight.update();
requestAnimationFrame(render);
}
render();
================================================
FILE: demo/src/style.css
================================================
html,
body {
margin: 0;
padding: 20px;
width: 100%;
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
letter-spacing: 0;
font-style: normal;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
h1 {
font-weight: 500;
color: #00BBDD;
}
ul {
list-style: none;
padding: 0;
max-height: 220px;
overflow: auto;
}
li {
line-height: 24px;
}
================================================
FILE: package.json
================================================
{
"name": "unswitch",
"version": "1.4.0",
"description": "A tiny event handler for switch controllers on the web.",
"main": "dist/unswitch.es.js",
"unpkg": "dist/unswitch.iife.js",
"scripts": {
"demo": "cross-env DEBUG=true rollup -c -w",
"build": "npm run es && npm run iife",
"es": "rollup -c -f es -o $npm_package_main && gzip-size $npm_package_main",
"iife": "rollup -c -f iife -o $npm_package_unpkg && gzip-size $npm_package_unpkg",
"prepare": "npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vaneenige/unswitch.git"
},
"license": "MIT",
"author": {
"name": "Colin van Eenige",
"email": "cvaneenige@gmail.com",
"url": "https://use-the-platform.com"
},
"files": [
"src",
"dist"
],
"keywords": [
"controller",
"input"
],
"devDependencies": {
"babel-core": "^6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.7.0",
"cross-env": "^5.2.0",
"eslint": "^4.19.1",
"eslint-config-airbnb-base": "^13.0.0",
"eslint-plugin-import": "^2.13.0",
"gzip-size-cli": "^3.0.0",
"rollup": "^0.62.0",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-eslint": "^4.0.0",
"rollup-plugin-serve": "^0.4.2",
"rollup-plugin-uglify": "^3.0.0"
},
"eslintConfig": {
"extends": "airbnb-base",
"env": {
"browser": true
}
}
}
================================================
FILE: rollup.config.js
================================================
import babel from 'rollup-plugin-babel';
import uglify from 'rollup-plugin-uglify';
import serve from 'rollup-plugin-serve';
import eslint from 'rollup-plugin-eslint';
const { DEBUG } = process.env;
const uglifySettings = {
compress: {
negate_iife: false,
unsafe_comps: true,
properties: true,
keep_fargs: false,
pure_getters: true,
collapse_vars: true,
unsafe: true,
warnings: false,
sequences: true,
dead_code: true,
drop_debugger: true,
comparisons: true,
conditionals: true,
evaluate: true,
booleans: true,
loops: true,
unused: true,
hoist_funs: true,
if_return: true,
join_vars: true,
drop_console: true,
pure_funcs: ['classCallCheck', 'invariant', 'warning'],
},
output: {
comments: false,
},
mangle: {
toplevel: true,
reserved: ['Unswitch'],
},
};
const input = DEBUG ? './demo/src/index.js' : './src/index.js';
const output = {
file: DEBUG ? './demo/dist/bundle.js' : './dist/unswitch.es.js',
format: 'es',
name: 'Unswitch',
sourcemap: false,
};
const plugins = [
/**
* Verify entry point and all imported files with ESLint.
* @see https://github.com/TrySound/rollup-plugin-eslint
*/
eslint({ throwOnError: true }),
/**
* Convert ES2015 with babel.
* @see https://github.com/rollup/rollup-plugin-babel
*/
babel({
babelrc: false,
presets: [['env', { loose: true, modules: false }]],
plugins: ['external-helpers'],
}),
];
if (DEBUG) {
plugins.push(
/**
* Serve the bundle for local debugging.
* @see https://github.com/thgh/rollup-plugin-serve
*/
serve({
port: 8080,
contentBase: 'demo',
}),
);
} else {
plugins.push(
/**
* Rollup plugin to minify generated bundle.
* @see https://github.com/TrySound/rollup-plugin-uglify
*/
uglify(uglifySettings),
);
}
export default { input, output, plugins };
================================================
FILE: src/index.js
================================================
const buttonMappings = ['a', 'x', 'b', 'y', 'sl', 'sr', '-', '-', 'minus', 'plus', 'lstick', 'rstick', 'home', 'screenshot', 'bumper', 'trigger'];
/**
* Get the axes position based based on browser.
* @param {array} axes
* @param {array} buttons
*/
function getAxesPosition(axes, buttons) {
if (axes.length === 10) {
return Math.round(axes[9] / (2 / 7) + 3.5);
}
const [right, left, down, up] = [...buttons].reverse();
const buttonValues = [up, right, down, left]
.map((pressed, i) => (pressed.value ? i * 2 : false))
.filter(val => val !== false);
if (buttonValues.length === 0) return 8;
if (buttonValues.length === 2 && buttonValues[0] === 0 && buttonValues[1] === 6) return 7;
return buttonValues.reduce((prev, curr) => prev + curr, 0) / buttonValues.length;
}
/**
* Create an instance of Unswitch.
* @param {object} settings
*/
function Unswitch(settings) {
const buttonState = {};
let axesPosition = 8;
for (let i = buttonMappings.length - 1; i >= 0; i -= 1) {
buttonState[buttonMappings[i]] = { pressed: false };
}
this.update = () => {
const gamepads = navigator.getGamepads();
for (let i = Object.keys(gamepads).length - 1; i >= 0; i -= 1) {
if (gamepads[i] && gamepads[i].id && gamepads[i].id.indexOf(settings.side) !== -1) {
this.observe(gamepads[i]);
break;
}
}
};
this.observe = (pad) => {
const { buttons, axes } = pad;
for (let j = buttonMappings.length - 1; j >= 0; j -= 1) {
const button = buttonMappings[j];
if (buttonState[button].pressed !== buttons[j].pressed) {
buttonState[button].pressed = buttons[j].pressed;
if (settings[button]) {
settings[button](buttonState[button].pressed);
}
if (settings.buttons) {
settings.buttons(button, buttonState[button].pressed, settings.side);
}
}
}
if (settings.axes) {
const position = getAxesPosition(axes, buttons);
if (position !== axesPosition) {
settings.axes(position);
axesPosition = position;
}
}
};
}
export default Unswitch;