{"bugs":{"url":"https://github.com/rafgraph/detect-it/issues"},"dist":{"shasum":"b3f442019c4227f7733cdd67ad7ba22f2f42cb48","tarball":"https://registry.npmjs.org/detect-it/-/detect-it-4.0.0-next.0.tgz","fileCount":54,"integrity":"sha512-0/pWPu6XbZVPI2yGNssDh5ghi/Q2i3pnsINtArkVZk6/R41bPIWsrMXNwPpQV4y0urQpPS1MGnWsJ+koQlCVMQ==","signatures":[{"sig":"MEUCIDCO3zEWIjC7LozLLSug6zDlH7sDboZcvHAFLgPugb69AiEAw304jGstXyHDtGwFtNI8BLFvDEOJ1Al+e8KHToE46Bw=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":80803,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfkJqgCRA9TVsSAnZWagAA+5QQAIWsl5KPdmqyvdwWisKh\n3wgvEG7ObNRGKn4XFGRn2ijayfTcbW6bGdI2owQSigr7Heb6cJeQGBBNf+F9\nHh8z0EjheWKKcziTNTbQ9Bx/5KAaw/f3VuRHKYDbkC6UBq5sogKBBOQvPSyN\ng2q2rOt99NnlK/3TS9J3QxKC3pQc5fzbe7jkDhui5yWScakCN8HfH5RqFaoa\nLtx3uj0BncFdVJlYQCxrQNAaL8i/rQR0xV3XblbxuAQvqrf6PHMaeK8SB/QD\nWbTedtdzWNBil+KH0BbS50z3qXxyJR9+zocen+N9tJpEk9Q2bepbalaGQngS\nDtRcxwB8AfAaaMNs6k8PHQ9L4mQxSZp4Q5+LNFDLdIb2iDlF8sjniovO4j2B\niDPdmeoPYULeMun7WAak7sDwuUbIAuGpfCFyCS0QL69YCgrQEKJVNKc5q1ai\nKRtQHoGqe3jDRg6RE6RQGiPL2tWRZppHYpcq+Y46HFYMQQAwg2/qqK5bTM1W\n22SsbfIgE9ZZshojGUYca/3BthhoU5/gCL51sGjtUvGxwLLGvqyLEfCbleuX\nLRb1gldDM0Fpvrpjx23KazPoxw7sXL+s+gZqtE9luGUqfV3shApN46kv20hS\nY2xv3CFO9AZofysD8zg6OPGt+FxuxxYmGXIbFTnHUnC9fbOWUQuwLjuhD4N/\n5CuV\r\n=WWKS\r\n-----END PGP SIGNATURE-----\r\n"},"main":"dist/detect-it.js","name":"detect-it","husky":{"hooks":{"pre-commit":"lint-staged"}},"types":"dist/index.d.ts","author":{"name":"Rafael Pedicini","email":"rafael@rafgraph.dev"},"module":"dist/detect-it.esm.js","readme":"# Detect It\n\nDetect if a device is `mouseOnly`, `touchOnly`, or `hybrid`, and if the primary input is `mouse` or `touch`. Also detects if the browser supports the Pointer Events API, the Touch Events API, and passive event listeners. Detect It is tree-shakable and side-effect free.\n\nThis is useful for creating device responsive UX and responding to user interactions. When creating apps with device responsive UX it is important to know what the user can do. Can they hover? Can they swipe? Etc. Once it's known what the user can do, the next question is how does the app listen for user input. For example, it's not enough to know that the user is on a touch device, the app also needs to know how to listen for touch input, should the app set PointerEvent listeners or TouchEvent listeners? For more on this see the [Recommended usage](#recommended-usage) section.\n\n---\n\n[Live detection test](https://detect-it.rafgraph.dev) (code in the [demo repo](https://github.com/rafgraph/detect-it-demo))\n\n[![npm](https://img.shields.io/npm/dm/detect-it?label=npm)](https://www.npmjs.com/package/detect-it) [![npm bundle size (version)](https://img.shields.io/bundlephobia/minzip/detect-it@next?color=purple)](https://bundlephobia.com/result?p=detect-it@next) ![npm type definitions](https://img.shields.io/npm/types/detect-it?color=blue)\n\n---\n\n> `detect-it` v4 is currently in pre-release, use the `@next` tag to install it, [v3 is available here](https://github.com/rafgraph/detect-it/tree/v3.0.7)\n\n```\nnpm install --save detect-it@next\n```\n\n```js\nimport * as detectIt from 'detect-it';\n// OR\nimport {\n  deviceType,\n  primaryInput,\n  supportsPointerEvents,\n  supportsTouchEvents,\n  supportsPassiveEvents,\n} from 'detect-it';\n```\n\n```js\n// types\ndeviceType: 'mouseOnly' | 'touchOnly' | 'hybrid';\nprimaryInput: 'mouse' | 'touch';\nsupportsPointerEvents: boolean;\nsupportsTouchEvents: boolean;\nsupportsPassiveEvents: boolean;\n```\n\n---\n\n### `deviceType`\n\n**`mouseOnly` | `touchOnly` | `hybrid`**\n\nIndicates if the the device is `mouseOnly`, `touchOnly` or `hybrid`. For info on how the detection works and how specific devices are classified see [Notes on detecting `deviceType`](#notes-on-detecting-devicetype).\n\n```js\nimport { deviceType } from 'detect-it';\n\nif (deviceType === 'hybrid') {\n  // ensure the site is usable by both mouse and touch input\n}\n```\n\n---\n\n### `primaryInput`\n\n**`mouse` | `touch`**\n\nIndicates if the primary input for the device is `mouse` or `touch`. For more info on how to use `primaryInput` see the [Recommended usage](#recommended-usage) section.\n\n```js\nimport { primaryInput } from 'detect-it';\n\nif (primaryInput === 'touch') {\n  // tailor UX for touch input\n} else {\n  // tailor UX for mouse input\n}\n```\n\n---\n\n### `supportsPointerEvents`\n\n**`boolean`**\n\nIndicates if the browser supports the Pointer Events API. See [MDN's Pointer Events](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) and the [W3C Pointer Events specification](https://www.w3.org/TR/pointerevents/) for more information on Pointer Events. See [Can I use](https://caniuse.com/mdn-api_pointerevent) for current support.\n\n```js\nimport { supportsPointerEvents } from 'detect-it';\n\nif (supportsPointerEvents) {\n  element.addEventListener('pointerenter', handlePointerEnter, false);\n}\n```\n\n---\n\n### `supportsTouchEvents`\n\n**`boolean`**\n\nIndicates if the browser supports the Touch Events API. See [MDN's Touch Events](https://developer.mozilla.org/en-US/docs/Web/API/Touch_events) and the [W3C Touch Events specification](https://w3c.github.io/touch-events/) for more information on Touch Events.\n\n```js\nimport { supportsTouchEvents } from 'detect-it';\n\nif (supportsTouchEvents) {\n  element.addEventListener('touchstart', handleTouchStart, false);\n}\n```\n\n---\n\n### `supportsPassiveEvents`\n\n**`boolean`**\n\nIndicates if the browser supports passive event listeners. See this [Passive Events Explainer](https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md) for more information on passive events. See [Can I use](https://caniuse.com/passive-event-listener) for current support.\n\n```js\nimport { supportsPassiveEvents } from 'detect-it';\n\nif (supportsPassiveEvents) {\n  // passive events are supported by the browser\n  document.addEventListener('scroll', handleScroll, { capture: false, passive: true });\n} else {\n  // passive events are not supported by the browser\n  document.addEventListener('scroll', handleScroll, false);\n}\n```\n\n---\n\n## Pre-built option served from Unpkg CDN\n\nOptionally, instead of using `npm install` you can load Detect It directly in the browser. A minified UMD version is available from Unpkg for this purpose.\n\n```html\n<!-- in index.html -->\n<script src=\"https://unpkg.com/detect-it/dist/detect-it.umd.min.js\"></script>\n```\n\n```js\n// it will be available on the window as detectIt\nif (window.detectIt.primaryInput === 'touch') {\n  // tailor UX for touch input\n}\n```\n\n---\n\n## Recommended usage\n\nTL;DR:\n\n- Use `primaryInput` for creating device responsive UX that optimizes the user experience for either `mouse` or `touch` input (note that the app should still be usable by both inputs). Use this along with classic responsive design that adapts to screen/window size to create a fully device responsive app.\n- Listening for user interactions:\n  - If the browser `supportsPointerEvents` then only set PointerEvent listeners and use [`pointerType`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType) to determine if the interaction was from `mouse` or `touch`.\n  - Otherwise always set both MouseEvent and TouchEvent listeners and use [`event-from`](https://github.com/rafgraph/event-from) to ignore MouseEvents generated from touch input.\n\n### Device responsive UX\n\nDevice responsive UX is about creating web apps that feel native on every device. This goes beyond classic responsive design, which only responds to the screen/window size, and includes how the user can interact with the app (the capabilities of the device). Can the user hover, swipe, long press, etc?\n\nThere are 3 parts of device responsive UX: **Size** (size of screen/window), **Can** (what the user can do/capabilities of the device), and **Is** (is the user hovering, touching, etc). **Size** and **Can** need to be known at render time (when the UI is rendered), and **Is** needs to be known at interaction time (when the user is interacting with the app).\n\n- **Size**\n  - This can be determined using media queries, for example `(max-width: 600px)`, either applied via CSS or in JavaScript by using something like [`react-media`](https://github.com/ReactTraining/react-media).\n- **Can**\n  - This is what **Detect It** is built for - knowing at render time what the capabilities of the device are (what can the user do). There are a number of ways that you could use `deviceType` or `primaryInput` to optimize the UX for the capabilities of the device, however, in most cases I've found it makes sense to just use `primaryInput` and optimize the UX for `mouse` or `touch`, while ensuring that the app is still usable by both inputs.\n- Putting **Size** and **Can** together, my preferred approach is to optimize the UX for 4 scenarios:\n  - Wide screen with `primaryInput` `mouse`: desktop/laptop with a normal window\n  - Narrow screen and `primaryInput` `mouse`: desktop/laptop with a narrow window\n  - Wide screen with `primaryInput` `touch`: tablet\n  - Narrow screen with `primaryInput` `touch`: phone\n- **Is**\n  - Is the user hovering, touching, etc. To help with this I created [React Interactive]() which provides a callback for interactive state changes (`hover`, `mouseActive`, `touchActive`, `keyActive`) and allows you to style touch interactions in ways that are not possible with CSS pseudo selectors.\n\n### Setting event listeners\n\nSetting event listeners can be thought of as either setting PointerEvent listeners **_or_** setting MouseEvent and TouchEvent listeners. PointerEvents can do everything that MouseEvents and TouchEvents can do (and more), without having to worry about if a MouseEvent was caused by touch input and so should be ignored. It is recommended to use PointerEvents if they are supported.\n\n#### PointerEvent listeners\n\nIf the browser `supportsPointerEvents` then only set PointerEvent listeners and use [`pointerType`](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType) to determine if the interaction was from `mouse` or `touch`.\n\n```js\nimport { supportsPointerEvents } from 'detect-it';\n\nconst handlePointerEnter = (e) => {\n  if (e.pointerType === 'mouse') {\n    // event from mouse input\n  } else {\n    // event from touch input\n    // note that pointerType can be 'mouse', 'touch' or 'pen'\n    // but in most situations it makes it makes sense to treat 'touch' and 'pen' as the same\n  }\n};\n\nif (supportsPointerEvents) {\n  element.addEventListener('pointerenter', handlePointerEnter, false);\n} else {\n  // set mouse and touch event listeners\n}\n```\n\n#### MouseEvent and TouchEvent listeners\n\nIf the browser doesn't support PointerEvents, then there are a couple of ways to approach setting mouse and touch event listeners.\n\n> Note that a touch interaction will fire TouchEvents as the interaction is in progress (finger on the screen), and then will fire MouseEvents after the touch interaction has finished (after the finger is removed from the screen) to support sites that only listen for MouseEvents.\n\n**Option 1**: If the device is `mouseOnly` or `touchOnly` then only set mouse or touch listeners, and if the device is `hybrid` set both mouse and touch event listeners and ignore MouseEvents caused by touch input (you can use [`event-from`](https://github.com/rafgraph/event-from) for this).\n\n**Option 2**: Always set both mouse and touch event listeners and use [`event-from`](https://github.com/rafgraph/event-from) to ignore MouseEvents from touch input.\n\nI prefer option 2 as it's simpler to code and I haven't noticed any performance impact from setting extra listeners (note that setting TouchEvent listeners on a browser that doesn't support TouchEvents is fine, the browser will just ignore the event listeners).\n\n```js\nimport { supportsPointerEvents } from 'detect-it';\nimport { eventFrom } from 'event-from';\n\nconst handleMouseEnter = (e) => {\n  if (eventFrom(e) !== 'mouse') return;\n  // code for handling mouse enter event from mouse input\n};\n\nconst handleTouchStart = (e) => {\n  // code for handling touch start from touch input\n};\n\nif (supportsPointerEvents) {\n  // set pointer event listeners\n} else {\n  // PointerEvents are not supported so set both MouseEvent and TouchEvent listeners\n  element.addEventListener('mouseenter', handleMouseEnter, false);\n  element.addEventListener('touchstart', handleTouchStart, false);\n}\n```\n\n---\n\n## Notes on detecting `deviceType`\n\nTo determine the `deviceType` and `primaryInput` Detect It uses multiple API detections and media query results to triangulate what type of device is being used. The entire detection is done when the script is imported so the results are known at render time (Detect It doesn't set any event listeners).\n\nDetect It has a wide definition for what constitutes a `hybrid` device, or rather a strict definition for what are `mouseOnly` and `touchOnly` devices, because if a device strays from only a fine point and hover with a mouse, or a coarse touch with a finger, then it should be treated uniquely when considering how the user will interact with it. Below is the source code for determining `deviceType`:\n\n```js\n// a hybrid device is one that both hasTouch and\n// any input can hover or has a fine pointer, or the primary pointer is not coarse\n// if it's not a hybrid, then if it hasTouch it's touchOnly, otherwise it's mouseOnly\nexport const deviceType =\n  hasTouch && (hasAnyHoverOrAnyFinePointer || !hasCoarsePrimaryPointer)\n    ? 'hybrid'\n    : hasTouch\n    ? 'touchOnly'\n    : 'mouseOnly';\n```\n\n#### Some `hybrid` device examples\n\n- A touch capable Chromebook\n- A touch capable Windows computer (both when it's used as a regular computer, and when in tablet mode, e.g. Microsoft Surface without a keyboard)\n- A Samsung Galaxy Note with stylus\n- All iPads now that they support a mouse and keyboard (note that Apple makes it impossible to know if a mouse or keyboard is attached, so iPads are always treated as a `hybrid` with `primaryInput` `touch`)\n\n#### Detection limitations\n\nThese detections are limited by how the browser presents itself (the APIs it exposes and how it responds to media queries) so there is the potential for errors. As anyone who has done web development knows, browsers are quirky and they don't always behave in expected ways, so **Detect It uses real world browser behavior to triangulate the `deviceType` and `primaryInput`.** For more on this see the comments in the [source code](https://github.com/rafgraph/detect-it/blob/main/src/index.ts) for notes about detecting the device type. Also, [tests](https://github.com/rafgraph/detect-it/tree/main/src/__tests__) have been written to mock a number of different browser behaviors and edge cases. Cloning this repo and running `npm test` will provide insight into how `detect-it` will preform on different devices.\n","source":"src/index.ts","gitHead":"66266ea7a7ea2e4597971f1039737034350aafc7","license":"MIT","scripts":{"dev":"npm link && npm run watch && npm unlink","tsc":"tsc --watch","test":"jest","build":"rm -rf dist && microbundle build --format esm,cjs --no-compress --strict --tsconfig tsconfig.build.json && microbundle build --format umd --compress --strict --tsconfig tsconfig.build.json --external peerDependencies","watch":"rm -rf dist && trap 'exit 0' SIGINT; microbundle watch --format esm,cjs --no-compress --strict --tsconfig tsconfig.build.json & microbundle watch --format umd --compress --strict --tsconfig tsconfig.build.json --external peerDependencies","coverage":"npx live-server coverage/lcov-report","test:watch":"jest --watchAll","prepublishOnly":"npm run build"},"_npmUser":{"name":"rafgraph","email":"rafael@rafgraph.dev"},"homepage":"https://detect-it.rafgraph.dev","keywords":["detect","device","mouse","touch","hybrid","passive events"],"prettier":{"printWidth":100,"singleQuote":true,"trailingComma":"all"},"umd:main":"dist/detect-it.umd.min.js","repository":{"url":"git+https://github.com/rafgraph/detect-it.git","type":"git"},"_npmVersion":"6.14.8","description":"Detect if a device is mouse only, touch only, or hybrid","directories":{},"lint-staged":{"src/**/*":"prettier --write --ignore-unknown"},"maintainers":[{"name":"rafgraph","email":"rafael@rafgraph.dev"}],"sideEffects":false,"_nodeVersion":"12.18.3","eslintConfig":{"env":{"browser":true},"root":true,"rules":{"import/no-default-export":"error"},"parser":"@typescript-eslint/parser","extends":["eslint:recommended","plugin:import/errors","plugin:import/warnings","plugin:import/typescript","plugin:@typescript-eslint/recommended","plugin:@typescript-eslint/recommended-requiring-type-checking","prettier","prettier/@typescript-eslint"],"parserOptions":{"project":"./tsconfig.json","sourceType":"module","createDefaultProgram":true},"ignorePatterns":["dist","node_modules","jest.config.js"]},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"jest":"^26.5.3","husky":"^4.3.0","eslint":"^7.11.0","ts-jest":"^26.4.1","prettier":"^2.1.2","typescript":"^4.0.3","lint-staged":"^10.4.0","microbundle":"^0.12.4","eslint-plugin-import":"^2.22.1","eslint-config-prettier":"^6.13.0","@typescript-eslint/parser":"^4.4.1","@typescript-eslint/eslint-plugin":"^4.4.1"},"_npmOperationalInternal":{"tmp":"tmp/detect-it_4.0.0-next.0_1603312288207_0.6317040380286993","host":"s3://npm-registry-packages"},"_id":"detect-it@4.0.0-next.0","version":"4.0.0-next.0"}