├── .docz ├── .cache │ ├── match-paths.json │ ├── pages.json │ ├── redirects.json │ ├── react-lifecycles-compat.js │ ├── __tests__ │ │ ├── .babelrc │ │ ├── __snapshots__ │ │ │ ├── dev-loader.js.snap │ │ │ ├── loader.js.snap │ │ │ └── static-entry.js.snap │ │ ├── minimal-config.js │ │ ├── strip-prefix.js │ │ ├── error-overlay-handler.js │ │ └── find-path.js │ ├── commonjs │ │ ├── react-lifecycles-compat.js │ │ ├── create-react-context.js │ │ ├── emitter.js │ │ ├── public-page-renderer.js │ │ ├── normalize-page-path.js │ │ ├── api-runner-browser-plugins.js │ │ ├── strip-prefix.js │ │ ├── public-page-renderer-prod.js │ │ ├── public-page-renderer-dev.js │ │ ├── dev-loader.js │ │ ├── api-runner-ssr.js │ │ ├── default-html.js │ │ ├── page-renderer.js │ │ ├── api-runner-browser.js │ │ ├── error-overlay-handler.js │ │ ├── prefetch.js │ │ ├── app.js │ │ ├── ensure-resources.js │ │ ├── register-service-worker.js │ │ ├── find-path.js │ │ ├── gatsby-browser-entry.js │ │ ├── develop-static-entry.js │ │ ├── socketIo.js │ │ ├── query-result-store.js │ │ ├── root.js │ │ └── production-app.js │ ├── create-react-context.js │ ├── emitter.js │ ├── redux.state │ ├── caches │ │ └── gatsby-plugin-mdx │ │ │ └── mdx-scopes-dir │ │ │ ├── 1970366a8c100bb8e42caab4bfa24659.js │ │ │ └── 265130ed43978149dbd190a4d099f77c.js │ ├── .eslintrc.json │ ├── normalize-page-path.js │ ├── public-page-renderer.js │ ├── strip-prefix.js │ ├── public-page-renderer-dev.js │ ├── public-page-renderer-prod.js │ ├── async-requires.js │ ├── sync-requires.js │ ├── test-require-error.js │ ├── default-html.js │ ├── dev-loader.js │ ├── page-renderer.js │ ├── error-overlay-handler.js │ ├── api-runner-ssr.js │ ├── api-runner-browser.js │ ├── prefetch.js │ ├── app.js │ ├── ensure-resources.js │ ├── find-path.js │ ├── api-runner-browser-plugins.js │ ├── register-service-worker.js │ ├── gatsby-browser-entry.js │ ├── develop-static-entry.js │ ├── query-result-store.js │ ├── socketIo.js │ ├── babelState.json │ ├── root.js │ ├── production-app.js │ └── navigation.js ├── public │ ├── 404 │ │ └── index.html │ ├── page-data │ │ ├── 404 │ │ │ └── page-data.json │ │ ├── app-data.json │ │ ├── 404.html │ │ │ └── page-data.json │ │ ├── dev-404-page │ │ │ └── page-data.json │ │ ├── demo │ │ │ └── page-data.json │ │ ├── props │ │ │ └── page-data.json │ │ └── index │ │ │ └── page-data.json │ ├── public │ │ └── images │ │ │ └── favicon.png │ ├── styles-fca67d4a49d8b7427c9b.js.map │ ├── styles-fca67d4a49d8b7427c9b.js │ ├── chunk-map.json │ ├── component---src-pages-404-js-2a38f26ee55704d6d07d.js │ ├── component---src-pages-404-js-2a38f26ee55704d6d07d.js.map │ ├── styles.617b70be7bd88a8d962f.css │ ├── webpack.stats.json │ ├── webpack-runtime-357cce2467b02eb17283.js │ ├── static │ │ └── d │ │ │ └── 1803957048.json │ ├── 404.html │ ├── component---docs-index-mdx-3927419ecd2651d24dd3.js │ ├── component---docs-pages-demo-mdx-da562a47741883850a15.js │ ├── component---docs-pages-demo-mdx-da562a47741883850a15.js.map │ ├── component---docs-index-mdx-3927419ecd2651d24dd3.js.map │ └── component---docs-pages-props-mdx-592d10813f233ead71ef.js ├── static │ └── public │ │ └── images │ │ └── favicon.png ├── doczrc.js ├── package.json ├── src │ └── pages │ │ └── 404.js ├── gatsby-config.js └── app │ └── db.json ├── .gitignore ├── src ├── index.js ├── __tests__ │ ├── utils │ │ ├── testUtils.js │ │ └── TestComponent.js │ ├── props.test.js │ └── target.test.js └── useKeyCapture │ ├── index.js │ ├── useKeyCaptureReducer.js │ └── useKeyCaptureUtils.js ├── .DS_Store ├── .npmignore ├── public └── images │ └── favicon.png ├── doczrc.js ├── .babelrc ├── .github └── workflows │ └── main.yml ├── jest.config.js ├── docs ├── Components │ ├── TargetEventComponent.js │ ├── GlobalEventComponent.js │ └── styles.css ├── index.mdx └── pages │ ├── props.mdx │ └── demo.mdx ├── LICENSE ├── package.json └── README.md /.docz/.cache/match-paths.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /.docz/.cache/pages.json: -------------------------------------------------------------------------------- 1 | [] 2 | -------------------------------------------------------------------------------- /.docz/.cache/redirects.json: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | coverage 4 | .gitconfig -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | export { default } from './useKeyCapture'; 2 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/use-key-capture/HEAD/.DS_Store -------------------------------------------------------------------------------- /.docz/.cache/react-lifecycles-compat.js: -------------------------------------------------------------------------------- 1 | exports.polyfill = Component => Component 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src 2 | node_modules 3 | __test__ 4 | .docz 5 | coverage 6 | docs 7 | public -------------------------------------------------------------------------------- /.docz/public/page-data/app-data.json: -------------------------------------------------------------------------------- 1 | {"webpackCompilationHash":"ed6d9096a76dc5eb66f0"} 2 | -------------------------------------------------------------------------------- /.docz/.cache/__tests__/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | ["babel-preset-gatsby"] 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/react-lifecycles-compat.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | exports.polyfill = Component => Component; -------------------------------------------------------------------------------- /.docz/.cache/create-react-context.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | 3 | export default React.createContext 4 | -------------------------------------------------------------------------------- /.docz/.cache/emitter.js: -------------------------------------------------------------------------------- 1 | import mitt from "mitt" 2 | 3 | const emitter = mitt() 4 | export default emitter 5 | -------------------------------------------------------------------------------- /.docz/.cache/redux.state: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/use-key-capture/HEAD/.docz/.cache/redux.state -------------------------------------------------------------------------------- /public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/use-key-capture/HEAD/public/images/favicon.png -------------------------------------------------------------------------------- /.docz/public/page-data/404/page-data.json: -------------------------------------------------------------------------------- 1 | {"componentChunkName":"component---src-pages-404-js","path":"/404/","result":{"pageContext":{}}} -------------------------------------------------------------------------------- /.docz/public/public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/use-key-capture/HEAD/.docz/public/public/images/favicon.png -------------------------------------------------------------------------------- /.docz/static/public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pranesh239/use-key-capture/HEAD/.docz/static/public/images/favicon.png -------------------------------------------------------------------------------- /.docz/public/page-data/404.html/page-data.json: -------------------------------------------------------------------------------- 1 | {"componentChunkName":"component---src-pages-404-js","path":"/404.html","result":{"pageContext":{}}} -------------------------------------------------------------------------------- /.docz/.cache/caches/gatsby-plugin-mdx/mdx-scopes-dir/1970366a8c100bb8e42caab4bfa24659.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | export default { 3 | React 4 | }; -------------------------------------------------------------------------------- /.docz/public/styles-fca67d4a49d8b7427c9b.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":[],"names":[],"mappings":"","file":"styles-fca67d4a49d8b7427c9b.js","sourceRoot":""} -------------------------------------------------------------------------------- /.docz/.cache/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true 4 | }, 5 | "globals": { 6 | "__PATH_PREFIX__": false, 7 | "___emitter": false 8 | } 9 | } -------------------------------------------------------------------------------- /doczrc.js: -------------------------------------------------------------------------------- 1 | export default { 2 | ignore: ['README.md'], 3 | public: './public', 4 | htmlContext: { 5 | favicon: '/public/public/images/favicon.png' 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /.docz/doczrc.js: -------------------------------------------------------------------------------- 1 | export default { 2 | ignore: ['README.md'], 3 | public: './public', 4 | htmlContext: { 5 | favicon: '/public/public/images/favicon.png' 6 | } 7 | }; 8 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/preset-env", "@babel/preset-react"], 3 | "ignore": ["*/__tests__.js", "*.test.js", "/__tests__/"], 4 | "plugins": ["@babel/transform-runtime"] 5 | } 6 | -------------------------------------------------------------------------------- /.docz/public/styles-fca67d4a49d8b7427c9b.js: -------------------------------------------------------------------------------- 1 | (window.webpackJsonp=window.webpackJsonp||[]).push([[6],{kV37:function(n,o,w){},oKgo:function(n,o,w){}}]); 2 | //# sourceMappingURL=styles-fca67d4a49d8b7427c9b.js.map -------------------------------------------------------------------------------- /.docz/.cache/normalize-page-path.js: -------------------------------------------------------------------------------- 1 | export default path => { 2 | if (path === undefined) { 3 | return path 4 | } 5 | if (path === `/`) { 6 | return `/` 7 | } 8 | if (path.charAt(path.length - 1) === `/`) { 9 | return path.slice(0, -1) 10 | } 11 | return path 12 | } 13 | -------------------------------------------------------------------------------- /.docz/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "docz-app", 3 | "license": "MIT", 4 | "dependencies": { 5 | "gatsby": "just-to-fool-cli-never-installed" 6 | }, 7 | "scripts": { 8 | "dev": "gatsby develop", 9 | "build": "gatsby build", 10 | "serve": "gatsby serve" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: ziishaned/jest-reporter-action@v0.0.1 12 | with: 13 | github-token: ${{ secrets.token }} 14 | test-command: "yarn jest --coverage" 15 | 16 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/create-react-context.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | var _default = _react.default.createContext; 11 | exports.default = _default; -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | const ignores = [ 2 | '/node_modules/', 3 | '/__fixtures__/', 4 | '/fixtures/', 5 | '/__tests__/helpers/', 6 | '/__tests__/utils/', 7 | '__mocks__', 8 | 'docz', 9 | '.docz', 10 | 'dist' 11 | ]; 12 | 13 | module.exports = { 14 | testMatch: ['**/__tests__/**/*.+(js|jsx|ts|tsx)'], 15 | testPathIgnorePatterns: [...ignores] 16 | }; 17 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/emitter.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _mitt = _interopRequireDefault(require("mitt")); 9 | 10 | const emitter = (0, _mitt.default)(); 11 | var _default = emitter; 12 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/public/page-data/dev-404-page/page-data.json: -------------------------------------------------------------------------------- 1 | {"componentChunkName":"component---cache-dev-404-page-js","path":"/dev-404-page/","result":{"data":{"allSitePage":{"nodes":[{"id":"SitePage /","path":"/"},{"id":"SitePage /demo","path":"/demo"},{"id":"SitePage /props","path":"/props"},{"id":"SitePage /404/","path":"/404/"},{"id":"SitePage /404.html","path":"/404.html"}]}},"pageContext":{}}} -------------------------------------------------------------------------------- /.docz/src/pages/404.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react' 2 | 3 | const NotFound = () => { 4 | const style = { 5 | display: 'flex', 6 | alignItems: 'center', 7 | justifyContent: 'center', 8 | height: '100vh', 9 | width: '100vw', 10 | fontSize: 32, 11 | } 12 | 13 | return
Not Found
14 | } 15 | 16 | export default NotFound 17 | -------------------------------------------------------------------------------- /src/__tests__/utils/testUtils.js: -------------------------------------------------------------------------------- 1 | import { renderHook } from '@testing-library/react-hooks'; 2 | import useKeyCapture from '../../index'; 3 | import { initialState } from '../../useKeyCapture/useKeyCaptureUtils'; 4 | 5 | const setUpHook = () => renderHook(() => useKeyCapture()); 6 | 7 | const initialStateValues = initialState; 8 | 9 | export { setUpHook, initialStateValues }; 10 | -------------------------------------------------------------------------------- /.docz/.cache/public-page-renderer.js: -------------------------------------------------------------------------------- 1 | const preferDefault = m => (m && m.default) || m 2 | 3 | if (process.env.BUILD_STAGE === `develop`) { 4 | module.exports = preferDefault(require(`./public-page-renderer-dev`)) 5 | } else if (process.env.BUILD_STAGE === `build-javascript`) { 6 | module.exports = preferDefault(require(`./public-page-renderer-prod`)) 7 | } else { 8 | module.exports = () => null 9 | } 10 | -------------------------------------------------------------------------------- /.docz/.cache/strip-prefix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Remove a prefix from a string. Return the input string if the given prefix 3 | * isn't found. 4 | */ 5 | 6 | export default (str, prefix = ``) => { 7 | if (!prefix) { 8 | return str 9 | } 10 | 11 | prefix += `/` 12 | 13 | if (str.substr(0, prefix.length) === prefix) { 14 | return str.slice(prefix.length - 1) 15 | } 16 | 17 | return str 18 | } 19 | -------------------------------------------------------------------------------- /.docz/public/chunk-map.json: -------------------------------------------------------------------------------- 1 | {"app":["/app-d181e0c33b178d7f5bfb.js"],"component---docs-index-mdx":["/component---docs-index-mdx-3927419ecd2651d24dd3.js"],"component---docs-pages-props-mdx":["/component---docs-pages-props-mdx-592d10813f233ead71ef.js"],"component---docs-pages-demo-mdx":["/component---docs-pages-demo-mdx-da562a47741883850a15.js"],"component---src-pages-404-js":["/component---src-pages-404-js-2a38f26ee55704d6d07d.js"]} -------------------------------------------------------------------------------- /.docz/public/component---src-pages-404-js-2a38f26ee55704d6d07d.js: -------------------------------------------------------------------------------- 1 | (window.webpackJsonp=window.webpackJsonp||[]).push([[5],{w2l6:function(t,e,n){"use strict";n.r(e);n("mXGw");var i=n("aD51");e.default=function(){return Object(i.c)("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100vh",width:"100vw",fontSize:32}},"Not Found")}}}]); 2 | //# sourceMappingURL=component---src-pages-404-js-2a38f26ee55704d6d07d.js.map -------------------------------------------------------------------------------- /.docz/.cache/caches/gatsby-plugin-mdx/mdx-scopes-dir/265130ed43978149dbd190a4d099f77c.js: -------------------------------------------------------------------------------- 1 | import { Playground } from 'docz'; 2 | import GlobalComponent from "../../../../../docs/Components/GlobalEventComponent.js"; 3 | import TargetEventComponent from "../../../../../docs/Components/TargetEventComponent.js"; 4 | import React from 'react'; 5 | export default { 6 | Playground, 7 | GlobalComponent, 8 | TargetEventComponent, 9 | React 10 | }; -------------------------------------------------------------------------------- /.docz/.cache/commonjs/public-page-renderer.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const preferDefault = m => m && m.default || m; 4 | 5 | if (process.env.BUILD_STAGE === `develop`) { 6 | module.exports = preferDefault(require(`./public-page-renderer-dev`)); 7 | } else if (process.env.BUILD_STAGE === `build-javascript`) { 8 | module.exports = preferDefault(require(`./public-page-renderer-prod`)); 9 | } else { 10 | module.exports = () => null; 11 | } -------------------------------------------------------------------------------- /.docz/.cache/commonjs/normalize-page-path.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | exports.__esModule = true; 4 | exports.default = void 0; 5 | 6 | var _default = path => { 7 | if (path === undefined) { 8 | return path; 9 | } 10 | 11 | if (path === `/`) { 12 | return `/`; 13 | } 14 | 15 | if (path.charAt(path.length - 1) === `/`) { 16 | return path.slice(0, -1); 17 | } 18 | 19 | return path; 20 | }; 21 | 22 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/commonjs/api-runner-browser-plugins.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | // During bootstrap, we write requires at top of this file which looks 4 | // basically like: 5 | // module.exports = [ 6 | // { 7 | // plugin: require("/path/to/plugin1/gatsby-browser.js"), 8 | // options: { ... }, 9 | // }, 10 | // { 11 | // plugin: require("/path/to/plugin2/gatsby-browser.js"), 12 | // options: { ... }, 13 | // }, 14 | // ] 15 | module.exports = []; -------------------------------------------------------------------------------- /.docz/.cache/__tests__/__snapshots__/dev-loader.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Dev loader loadPage should be successful when component can be loaded 1`] = ` 4 | Object { 5 | "component": "instance", 6 | "json": Object { 7 | "pageContext": "something something", 8 | }, 9 | "page": Object { 10 | "componentChunkName": "chunk", 11 | "matchPath": undefined, 12 | "path": "/mypage/", 13 | "webpackCompilationHash": "123", 14 | }, 15 | } 16 | `; 17 | -------------------------------------------------------------------------------- /.docz/.cache/__tests__/__snapshots__/loader.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Production loader loadPage should be successful when component can be loaded 1`] = ` 4 | Object { 5 | "component": "instance", 6 | "json": Object { 7 | "pageContext": "something something", 8 | }, 9 | "page": Object { 10 | "componentChunkName": "chunk", 11 | "matchPath": undefined, 12 | "path": "/mypage/", 13 | "webpackCompilationHash": "123", 14 | }, 15 | } 16 | `; 17 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/strip-prefix.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | exports.__esModule = true; 4 | exports.default = void 0; 5 | 6 | /** 7 | * Remove a prefix from a string. Return the input string if the given prefix 8 | * isn't found. 9 | */ 10 | var _default = (str, prefix = ``) => { 11 | if (!prefix) { 12 | return str; 13 | } 14 | 15 | prefix += `/`; 16 | 17 | if (str.substr(0, prefix.length) === prefix) { 18 | return str.slice(prefix.length - 1); 19 | } 20 | 21 | return str; 22 | }; 23 | 24 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/public/page-data/demo/page-data.json: -------------------------------------------------------------------------------- 1 | {"componentChunkName":"component---docs-pages-demo-mdx","path":"/demo","result":{"pageContext":{"frontmatter":{"name":"Demo","route":"/demo","order":2},"entry":{"id":"87411c77fdcfbb7f6278f322040c1731","filepath":"docs/pages/demo.mdx","fullpath":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/demo.mdx","route":"/demo","slug":"docs-pages-demo","name":"Demo","menu":"","headings":[{"slug":"target-listener","depth":2,"value":"Target Listener"},{"slug":"global-listener","depth":2,"value":"Global Listener"}]}}}} -------------------------------------------------------------------------------- /.docz/.cache/public-page-renderer-dev.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import PropTypes from "prop-types" 3 | 4 | import loader from "./loader" 5 | import { PageQueryStore } from "./query-result-store" 6 | 7 | const DevPageRenderer = ({ location }) => { 8 | const pageResources = loader.loadPageSync(location.pathname) 9 | return React.createElement(PageQueryStore, { 10 | location, 11 | pageResources, 12 | }) 13 | } 14 | 15 | DevPageRenderer.propTypes = { 16 | location: PropTypes.shape({ 17 | pathname: PropTypes.string.isRequired, 18 | }).isRequired, 19 | } 20 | 21 | export default DevPageRenderer 22 | -------------------------------------------------------------------------------- /.docz/.cache/public-page-renderer-prod.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import PropTypes from "prop-types" 3 | 4 | import InternalPageRenderer from "./page-renderer" 5 | 6 | const ProdPageRenderer = ({ location, pageResources }) => { 7 | if (!pageResources) { 8 | return null 9 | } 10 | return React.createElement(InternalPageRenderer, { 11 | location, 12 | pageResources, 13 | ...pageResources.json, 14 | }) 15 | } 16 | 17 | ProdPageRenderer.propTypes = { 18 | location: PropTypes.shape({ 19 | pathname: PropTypes.string.isRequired, 20 | }).isRequired, 21 | } 22 | 23 | export default ProdPageRenderer 24 | -------------------------------------------------------------------------------- /.docz/public/page-data/props/page-data.json: -------------------------------------------------------------------------------- 1 | {"componentChunkName":"component---docs-pages-props-mdx","path":"/props","result":{"pageContext":{"frontmatter":{"name":"Props","route":"/props","order":2},"entry":{"id":"b5cb4d959720d31e411c9b125e451a6a","filepath":"docs/pages/props.mdx","fullpath":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/props.mdx","route":"/props","slug":"docs-pages-props","name":"Props","menu":"","headings":[{"slug":"props","depth":2,"value":"Props"},{"slug":"keydata","depth":3,"value":"keyData"},{"slug":"gettargetprops","depth":3,"value":"getTargetProps"},{"slug":"resetkeydata","depth":3,"value":"resetKeyData"}]}}}} -------------------------------------------------------------------------------- /.docz/public/page-data/index/page-data.json: -------------------------------------------------------------------------------- 1 | {"componentChunkName":"component---docs-index-mdx","path":"/","result":{"pageContext":{"frontmatter":{"name":"Docs","route":"/","order":1},"entry":{"id":"73498ad0e1e62a714b08085d318f9de1","filepath":"docs/index.mdx","fullpath":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/index.mdx","route":"/","slug":"docs-index","name":"Docs","menu":"","headings":[{"slug":"use-key-capture","depth":1,"value":"use-key-capture"},{"slug":"installation","depth":2,"value":"Installation"},{"slug":"how-it-is-used","depth":2,"value":"How it is used"},{"slug":"properties","depth":2,"value":"Properties"},{"slug":"target-prop-getter","depth":2,"value":"Target Prop getter"}]}}}} -------------------------------------------------------------------------------- /.docz/.cache/async-requires.js: -------------------------------------------------------------------------------- 1 | // prefer default export if available 2 | const preferDefault = m => m && m.default || m 3 | 4 | exports.components = { 5 | "component---docs-index-mdx": () => import("./../../docs/index.mdx" /* webpackChunkName: "component---docs-index-mdx" */), 6 | "component---docs-pages-props-mdx": () => import("./../../docs/pages/props.mdx" /* webpackChunkName: "component---docs-pages-props-mdx" */), 7 | "component---docs-pages-demo-mdx": () => import("./../../docs/pages/demo.mdx" /* webpackChunkName: "component---docs-pages-demo-mdx" */), 8 | "component---src-pages-404-js": () => import("./../src/pages/404.js" /* webpackChunkName: "component---src-pages-404-js" */) 9 | } 10 | 11 | -------------------------------------------------------------------------------- /.docz/public/component---src-pages-404-js-2a38f26ee55704d6d07d.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["webpack:///./src/pages/404.js"],"names":["style","display","alignItems","justifyContent","height","width","fontSize"],"mappings":"2FAAA,iCAeA,UAbiB,WAUf,OAAO,mBAAKA,MATE,CACZC,QADY,OAEZC,WAFY,SAGZC,eAHY,SAIZC,OAJY,QAKZC,MALY,QAMZC,SAAU,KAGZ","file":"component---src-pages-404-js-2a38f26ee55704d6d07d.js","sourcesContent":["import * as React from 'react'\n\nconst NotFound = () => {\n const style = {\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: '100vh',\n width: '100vw',\n fontSize: 32,\n }\n\n return
Not Found
\n}\n\nexport default NotFound\n"],"sourceRoot":""} -------------------------------------------------------------------------------- /src/__tests__/utils/TestComponent.js: -------------------------------------------------------------------------------- 1 | import React, { useRef, useEffect } from 'react'; 2 | import useKey from '../../useKeyCapture'; 3 | 4 | const TestComponent = () => { 5 | const { keyData, getTargetProps } = useKey(); 6 | 7 | const inputRef = useRef(null); 8 | 9 | useEffect(() => { 10 | // console.log(inputRef.current); 11 | }, []); 12 | 13 | return ( 14 |
15 | 21 | 22 | {keyData.key && {keyData.key}} 23 |
24 | ); 25 | }; 26 | 27 | export default TestComponent; 28 | -------------------------------------------------------------------------------- /.docz/.cache/sync-requires.js: -------------------------------------------------------------------------------- 1 | const { hot } = require("react-hot-loader/root") 2 | 3 | // prefer default export if available 4 | const preferDefault = m => m && m.default || m 5 | 6 | 7 | exports.components = { 8 | "component---docs-index-mdx": hot(preferDefault(require("/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/index.mdx"))), 9 | "component---docs-pages-props-mdx": hot(preferDefault(require("/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/props.mdx"))), 10 | "component---docs-pages-demo-mdx": hot(preferDefault(require("/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/demo.mdx"))), 11 | "component---src-pages-404-js": hot(preferDefault(require("/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/src/pages/404.js"))) 12 | } 13 | 14 | -------------------------------------------------------------------------------- /.docz/.cache/__tests__/minimal-config.js: -------------------------------------------------------------------------------- 1 | const path = require(`path`) 2 | const child = require(`child_process`) 3 | 4 | it(`Builds cache-dir with minimal config`, done => { 5 | const args = [ 6 | require.resolve(`@babel/cli/bin/babel.js`), 7 | path.join(__dirname, `..`), 8 | `--config-file`, 9 | path.join(__dirname, `.babelrc`), 10 | `--ignore`, 11 | `**/__tests__`, 12 | ] 13 | 14 | const spawn = child.spawn(process.execPath, args) 15 | 16 | let stderr = `` 17 | let stdout = `` 18 | 19 | spawn.stderr.on(`data`, function(chunk) { 20 | stderr += chunk 21 | }) 22 | 23 | spawn.stdout.on(`data`, function(chunk) { 24 | stdout += chunk 25 | }) 26 | 27 | spawn.on(`close`, function() { 28 | expect(stderr).toEqual(``) 29 | expect(stdout).not.toEqual(``) 30 | done() 31 | }) 32 | }, 30000) 33 | -------------------------------------------------------------------------------- /.docz/.cache/test-require-error.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | exports.__esModule = true; 4 | exports.default = void 0; 5 | 6 | // This module is also copied into the .cache directory some modules copied there 7 | // from cache-dir can also use this module. 8 | var _default = (moduleName, err) => { 9 | // PnP will return the following code when a require is allowed per the 10 | // dependency tree rules but the requested file doesn't exist 11 | if (err.code === `QUALIFIED_PATH_RESOLUTION_FAILED` || err.pnpCode === `QUALIFIED_PATH_RESOLUTION_FAILED`) { 12 | return true; 13 | } 14 | 15 | const regex = new RegExp(`Error:\\s(\\S+\\s)?[Cc]annot find module\\s.${moduleName.replace(/[-/\\^$*+?.()|[\]{}]/g, `\\$&`)}`); 16 | const firstLine = err.toString().split(`\n`)[0]; 17 | return regex.test(firstLine); 18 | }; 19 | 20 | exports.default = _default; 21 | //# sourceMappingURL=test-require-error.js.map -------------------------------------------------------------------------------- /.docz/.cache/__tests__/strip-prefix.js: -------------------------------------------------------------------------------- 1 | const stripPrefix = require(`../strip-prefix`).default 2 | 3 | describe(`strip-prefix`, () => { 4 | it(`strips a prefix`, () => { 5 | expect(stripPrefix(`/foo/bar/`, `/foo`)).toBe(`/bar/`) 6 | }) 7 | 8 | it(`strips first instance only`, () => { 9 | expect(stripPrefix(`/foo/foo/bar/`, `/foo`)).toBe(`/foo/bar/`) 10 | }) 11 | 12 | it(`strips full instance only`, () => { 13 | expect(stripPrefix(`/footest/`, `/foo`)).toBe(`/footest/`) 14 | }) 15 | 16 | it(`ignores prefix appearing elsewhere in the string`, () => { 17 | expect(stripPrefix(`/foo/bar/`, `bar`)).toBe(`/foo/bar/`) 18 | }) 19 | 20 | it(`ignores a non-existent prefix`, () => { 21 | expect(stripPrefix(`/bar`, `/foo`)).toBe(`/bar`) 22 | }) 23 | 24 | it(`returns input str if no prefix is provided`, () => { 25 | expect(stripPrefix(`/bar`)).toBe(`/bar`) 26 | }) 27 | }) 28 | -------------------------------------------------------------------------------- /docs/Components/TargetEventComponent.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import useKey from '../../src/useKeyCapture'; 3 | import './styles.css'; 4 | 5 | const displayKeys = ['Q', 'W', 'E', 'R', 'T', 'Y', 'Backspace']; 6 | 7 | const TargetEventComponent = () => { 8 | const { keyData, getTargetProps } = useKey(); 9 | 10 | const getIsActive = key => (keyData.key === key ? 'active' : ''); 11 | 12 | return ( 13 |
14 |
15 | Type QWERTY in the input element below. If the focus outside the target, 16 | we won't see any change. 17 |
18 | 19 |
20 | {displayKeys.map(key => { 21 | return
{key}
; 22 | })} 23 |
24 |
25 | ); 26 | }; 27 | 28 | export default TargetEventComponent; 29 | -------------------------------------------------------------------------------- /.docz/public/styles.617b70be7bd88a8d962f.css: -------------------------------------------------------------------------------- 1 | @import url(https://fonts.googleapis.com/css?family=Inconsolata&display=swap);@import url(https://fonts.googleapis.com/css?family=Source+Sans+Pro&display=swap);.box{height:100px;width:100px;margin:4px;border:4px solid #b8e994;border-radius:4px;-webkit-transition:all .3s ease-in-out;transition:all .3s ease-in-out;background:#fff}.box,.container{display:flex;align-items:center;justify-content:center}.container{min-height:200px;border:1px solid #ccc;border-radius:8px;background:#5f3ccf}.container-target .container{border:none}.container-target .message{color:#fff;margin:48px}.container-target input{width:500px;height:50px;background:#977af7;border:none;outline:none;font-size:48px;line-height:50px;color:#fff;text-align:center;padding:8px;border-radius:8px}.container-target{background:#5f3ccf;display:flex;flex-flow:column;justify-content:center;align-items:center;border-radius:8px}.box.active{background:#78e08f;color:#fff}.message{text-align:center} -------------------------------------------------------------------------------- /docs/Components/GlobalEventComponent.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import useKey from '../../src/useKeyCapture'; 3 | import './styles.css'; 4 | 5 | const displayKeys = ['Enter', 'Escape', 'Tab', 'ArrowUp']; 6 | 7 | const GlobalComponent = () => { 8 | const { keyData } = useKey(); 9 | 10 | const getIsActive = key => (keyData.key === key ? 'active' : ''); 11 | 12 | const getCombinedActiveClass = () => 13 | keyData.key === 'A' && keyData.isWithShift ? 'active' : ''; 14 | 15 | return ( 16 | <> 17 |
18 | Press below mentioned keys to see the hook in action 19 |
20 |
21 | {displayKeys.map(key => { 22 | return
{key}
; 23 | })} 24 |
Shift + A
25 |
26 | 27 | ); 28 | }; 29 | 30 | export default GlobalComponent; 31 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/public-page-renderer-prod.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | var _propTypes = _interopRequireDefault(require("prop-types")); 11 | 12 | var _pageRenderer = _interopRequireDefault(require("./page-renderer")); 13 | 14 | const ProdPageRenderer = ({ 15 | location, 16 | pageResources 17 | }) => { 18 | if (!pageResources) { 19 | return null; 20 | } 21 | 22 | return _react.default.createElement(_pageRenderer.default, Object.assign({ 23 | location, 24 | pageResources 25 | }, pageResources.json)); 26 | }; 27 | 28 | ProdPageRenderer.propTypes = { 29 | location: _propTypes.default.shape({ 30 | pathname: _propTypes.default.string.isRequired 31 | }).isRequired 32 | }; 33 | var _default = ProdPageRenderer; 34 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/commonjs/public-page-renderer-dev.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | var _propTypes = _interopRequireDefault(require("prop-types")); 11 | 12 | var _loader = _interopRequireDefault(require("./loader")); 13 | 14 | var _queryResultStore = require("./query-result-store"); 15 | 16 | const DevPageRenderer = ({ 17 | location 18 | }) => { 19 | const pageResources = _loader.default.loadPageSync(location.pathname); 20 | 21 | return _react.default.createElement(_queryResultStore.PageQueryStore, { 22 | location, 23 | pageResources 24 | }); 25 | }; 26 | 27 | DevPageRenderer.propTypes = { 28 | location: _propTypes.default.shape({ 29 | pathname: _propTypes.default.string.isRequired 30 | }).isRequired 31 | }; 32 | var _default = DevPageRenderer; 33 | exports.default = _default; -------------------------------------------------------------------------------- /src/__tests__/props.test.js: -------------------------------------------------------------------------------- 1 | import { cleanup } from '@testing-library/react'; 2 | import { setUpHook, initialStateValues } from './utils/testUtils'; 3 | 4 | describe('useKeyCapture', () => { 5 | afterEach(() => cleanup()); 6 | 7 | describe('props', () => { 8 | it('are present', () => { 9 | const { result } = setUpHook(); 10 | expect(result.current.keyData).toBeTruthy(); 11 | expect(result.current.resetKeyData).toBeTruthy(); 12 | expect(result.current.getTargetProps).toBeTruthy(); 13 | }); 14 | }); 15 | 16 | describe('prop getters', () => { 17 | it('are returned as functions', () => { 18 | const { result } = setUpHook(); 19 | expect(result.current.getTargetProps).toBeInstanceOf(Function); 20 | expect(result.current.resetKeyData).toBeInstanceOf(Function); 21 | }); 22 | }); 23 | 24 | it('should have have correct initial state', () => { 25 | const { result } = setUpHook(); 26 | 27 | expect(result.current.keyData).toEqual(initialStateValues); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /.docz/.cache/default-html.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import PropTypes from "prop-types" 3 | 4 | export default function HTML(props) { 5 | return ( 6 | 7 | 8 | 9 | 10 | 14 | {props.headComponents} 15 | 16 | 17 | {props.preBodyComponents} 18 |
23 | {props.postBodyComponents} 24 | 25 | 26 | ) 27 | } 28 | 29 | HTML.propTypes = { 30 | htmlAttributes: PropTypes.object, 31 | headComponents: PropTypes.array, 32 | bodyAttributes: PropTypes.object, 33 | preBodyComponents: PropTypes.array, 34 | body: PropTypes.string, 35 | postBodyComponents: PropTypes.array, 36 | } 37 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Pranesh 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /docs/index.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | name: Docs 3 | route: / 4 | order: 1 5 | --- 6 | 7 | # use-key-capture 8 | 9 | use-key-capture is a custom hook which will let us not to worry about the key-press event. Just plugin in use-key-capture hook to the **target** we want to listen for key press event or by default it can listen for key-press event **globally**. 10 | 11 | ## Installation 12 | 13 | **npm** 14 | 15 | ```bash 16 | npm i use-key-capture 17 | ``` 18 | 19 | **yarn** 20 | 21 | ```bash 22 | yarn add use-key-capture 23 | ``` 24 | 25 | ## How it is used 26 | 27 | ```jsx 28 | import useKey from 'use-key-capture'; 29 | ... 30 | const { keyData, resetKeyData, getTargetProps } = useKey(); 31 | ``` 32 | 33 | ## Properties 34 | 35 | | Property name | Description | 36 | | ------------- | ------------------------------ | 37 | | keyData | gives pressed key details | 38 | | resetKeyData | resets the pressed key details | 39 | 40 | ## Target Prop getter 41 | 42 | | Property name | Description | 43 | | -------------- | ------------------------------------------ | 44 | | getTargetProps | gives the required props to target element | 45 | -------------------------------------------------------------------------------- /.docz/.cache/dev-loader.js: -------------------------------------------------------------------------------- 1 | import { BaseLoader } from "./loader" 2 | import { findPath } from "./find-path" 3 | 4 | class DevLoader extends BaseLoader { 5 | constructor(syncRequires, matchPaths) { 6 | const loadComponent = chunkName => 7 | Promise.resolve(syncRequires.components[chunkName]) 8 | super(loadComponent, matchPaths) 9 | } 10 | 11 | loadPage(pagePath) { 12 | const realPath = findPath(pagePath) 13 | return super.loadPage(realPath).then(result => 14 | require(`./socketIo`) 15 | .getPageData(realPath) 16 | .then(() => result) 17 | ) 18 | } 19 | 20 | loadPageDataJson(rawPath) { 21 | return super.loadPageDataJson(rawPath).then(data => { 22 | // when we can't find a proper 404.html we fallback to dev-404-page 23 | // we need to make sure to mark it as not found. 24 | if (data.status === `failure`) { 25 | return this.loadPageDataJson(`/dev-404-page/`).then(result => 26 | Object.assign({}, data, result) 27 | ) 28 | } 29 | 30 | return data 31 | }) 32 | } 33 | 34 | doPrefetch(pagePath) { 35 | return Promise.resolve(require(`./socketIo`).getPageData(pagePath)) 36 | } 37 | } 38 | 39 | export default DevLoader 40 | -------------------------------------------------------------------------------- /docs/Components/styles.css: -------------------------------------------------------------------------------- 1 | .box { 2 | height: 100px; 3 | width: 100px; 4 | margin: 4px; 5 | display: flex; 6 | align-items: center; 7 | justify-content: center; 8 | border: 4px solid #b8e994; 9 | border-radius: 4px; 10 | transition: 0.3s all ease-in-out; 11 | background: #ffffff; 12 | } 13 | 14 | .container { 15 | display: flex; 16 | align-items: center; 17 | justify-content: center; 18 | min-height: 200px; 19 | border: 1px solid #ccc; 20 | border-radius: 8px; 21 | background: #5f3ccf; 22 | } 23 | 24 | .container-target .container { 25 | border: none; 26 | } 27 | .container-target .message { 28 | color: #fff; 29 | margin: 48px; 30 | } 31 | 32 | .container-target input { 33 | width: 500px; 34 | height: 50px; 35 | background: #977af7; 36 | border: none; 37 | outline: none; 38 | font-size: 48px; 39 | line-height: 50px; 40 | color: #fff; 41 | text-align: center; 42 | padding: 8px; 43 | border-radius: 8px; 44 | } 45 | 46 | .container-target { 47 | background: #5f3ccf; 48 | display: flex; 49 | flex-flow: column; 50 | justify-content: center; 51 | align-items: center; 52 | border-radius: 8px; 53 | } 54 | 55 | .box.active { 56 | background: #78e08f; 57 | color: #ffffff; 58 | } 59 | 60 | .message { 61 | text-align: center; 62 | } 63 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/dev-loader.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | exports.__esModule = true; 4 | exports.default = void 0; 5 | 6 | var _loader = require("./loader"); 7 | 8 | var _findPath = require("./find-path"); 9 | 10 | class DevLoader extends _loader.BaseLoader { 11 | constructor(syncRequires, matchPaths) { 12 | const loadComponent = chunkName => Promise.resolve(syncRequires.components[chunkName]); 13 | 14 | super(loadComponent, matchPaths); 15 | } 16 | 17 | loadPage(pagePath) { 18 | const realPath = (0, _findPath.findPath)(pagePath); 19 | return super.loadPage(realPath).then(result => require(`./socketIo`).getPageData(realPath).then(() => result)); 20 | } 21 | 22 | loadPageDataJson(rawPath) { 23 | return super.loadPageDataJson(rawPath).then(data => { 24 | // when we can't find a proper 404.html we fallback to dev-404-page 25 | // we need to make sure to mark it as not found. 26 | if (data.status === `failure`) { 27 | return this.loadPageDataJson(`/dev-404-page/`).then(result => Object.assign({}, data, result)); 28 | } 29 | 30 | return data; 31 | }); 32 | } 33 | 34 | doPrefetch(pagePath) { 35 | return Promise.resolve(require(`./socketIo`).getPageData(pagePath)); 36 | } 37 | 38 | } 39 | 40 | var _default = DevLoader; 41 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/page-renderer.js: -------------------------------------------------------------------------------- 1 | import React, { createElement } from "react" 2 | import PropTypes from "prop-types" 3 | import { publicLoader } from "./loader" 4 | import { apiRunner } from "./api-runner-browser" 5 | 6 | // Renders page 7 | class PageRenderer extends React.Component { 8 | render() { 9 | const props = { 10 | ...this.props, 11 | pathContext: this.props.pageContext, 12 | } 13 | 14 | const [replacementElement] = apiRunner(`replaceComponentRenderer`, { 15 | props: this.props, 16 | loader: publicLoader, 17 | }) 18 | 19 | const pageElement = 20 | replacementElement || 21 | createElement(this.props.pageResources.component, { 22 | ...props, 23 | key: this.props.path || this.props.pageResources.page.path, 24 | }) 25 | 26 | const wrappedPage = apiRunner( 27 | `wrapPageElement`, 28 | { element: pageElement, props }, 29 | pageElement, 30 | ({ result }) => { 31 | return { element: result, props } 32 | } 33 | ).pop() 34 | 35 | return wrappedPage 36 | } 37 | } 38 | 39 | PageRenderer.propTypes = { 40 | location: PropTypes.object.isRequired, 41 | pageResources: PropTypes.object.isRequired, 42 | data: PropTypes.object, 43 | pageContext: PropTypes.object.isRequired, 44 | } 45 | 46 | export default PageRenderer 47 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/api-runner-ssr.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | // During bootstrap, we write requires at top of this file which looks like: 4 | // var plugins = [ 5 | // { 6 | // plugin: require("/path/to/plugin1/gatsby-ssr.js"), 7 | // options: { ... }, 8 | // }, 9 | // { 10 | // plugin: require("/path/to/plugin2/gatsby-ssr.js"), 11 | // options: { ... }, 12 | // }, 13 | // ] 14 | const apis = require(`./api-ssr-docs`); // Run the specified API in any plugins that have implemented it 15 | 16 | 17 | module.exports = (api, args, defaultReturn, argTransform) => { 18 | if (!apis[api]) { 19 | console.log(`This API doesn't exist`, api); 20 | } // Run each plugin in series. 21 | // eslint-disable-next-line no-undef 22 | 23 | 24 | let results = plugins.map(plugin => { 25 | if (!plugin.plugin[api]) { 26 | return undefined; 27 | } 28 | 29 | const result = plugin.plugin[api](args, plugin.options); 30 | 31 | if (result && argTransform) { 32 | args = argTransform({ 33 | args, 34 | result 35 | }); 36 | } 37 | 38 | return result; 39 | }); // Filter out undefined results. 40 | 41 | results = results.filter(result => typeof result !== `undefined`); 42 | 43 | if (results.length > 0) { 44 | return results; 45 | } else { 46 | return [defaultReturn]; 47 | } 48 | }; -------------------------------------------------------------------------------- /docs/pages/props.mdx: -------------------------------------------------------------------------------- 1 | --- 2 | name: Props 3 | route: /props 4 | order: 2 5 | --- 6 | 7 | ## Props 8 | 9 | ### keyData 10 | 11 | It will be the most used props from `useKeyCapture`. It gives the key/key varient/key combinations pressed. 12 | 13 | | Property | Type | 14 | | ------------------ | ------- | 15 | | key | String | 16 | | isEnter | Boolean | 17 | | isBackspace | Boolean | 18 | | isEscape | Boolean | 19 | | isCapsLock | Boolean | 20 | | isTab | Boolean | 21 | | isSpace | Boolean | 22 | | isArrow | Boolean | 23 | | isArrowRight | Boolean | 24 | | isArrowLeft | Boolean | 25 | | isArrowUp | Boolean | 26 | | isArrowDown | Boolean | 27 | | isWithShift | Boolean | 28 | | isWithCtrl | Boolean | 29 | | isWithMeta | Boolean | 30 | | isWithAlt | Boolean | 31 | | isCaps | Boolean | 32 | | isSmall | Boolean | 33 | | isNumber | Boolean | 34 | | isSpecialCharacter | Boolean | 35 | 36 | ### getTargetProps 37 | 38 | `type: function({})` 39 | 40 | A prop getter to be given if a target (input, textarea) have to be listened for key-press. 41 | 42 | ### resetKeyData 43 | 44 | `type: function({})` 45 | 46 | It will reset all the values in `keyData` props to the initial values. 47 | -------------------------------------------------------------------------------- /src/__tests__/target.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render, cleanup, fireEvent } from '@testing-library/react'; 3 | import TestComponent from './utils/TestComponent'; 4 | 5 | describe('component with target', () => { 6 | afterEach(() => cleanup()); 7 | 8 | it('updated when keydown event is in the target', async () => { 9 | const { findByTestId, queryByTestId, container } = render( 10 | 11 | ); 12 | 13 | const targetInput = await findByTestId('input'); 14 | let displayDOM = queryByTestId('displayDOM'); 15 | 16 | expect(displayDOM).toBeNull(); 17 | 18 | fireEvent.keyDown(targetInput, { 19 | key: 'Shift' 20 | }); 21 | 22 | displayDOM = queryByTestId('displayDOM'); 23 | 24 | expect(displayDOM.textContent).not.toBeNull(); 25 | expect(displayDOM.textContent).toBe('Shift'); 26 | }); 27 | 28 | it('should not update, when the event is made on the non-target element', async () => { 29 | const { findByTestId, queryByTestId } = render(); 30 | 31 | const targetInput = await findByTestId('secondary_input'); 32 | let displayDOM = queryByTestId('displayDOM'); 33 | 34 | expect(displayDOM).toBeNull(); 35 | 36 | fireEvent.keyDown(targetInput, { 37 | key: 'Shift' 38 | }); 39 | 40 | displayDOM = queryByTestId('displayDOM'); 41 | expect(displayDOM).toBeNull(); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/default-html.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = HTML; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | var _propTypes = _interopRequireDefault(require("prop-types")); 11 | 12 | function HTML(props) { 13 | return _react.default.createElement("html", props.htmlAttributes, _react.default.createElement("head", null, _react.default.createElement("meta", { 14 | charSet: "utf-8" 15 | }), _react.default.createElement("meta", { 16 | httpEquiv: "x-ua-compatible", 17 | content: "ie=edge" 18 | }), _react.default.createElement("meta", { 19 | name: "viewport", 20 | content: "width=device-width, initial-scale=1, shrink-to-fit=no" 21 | }), props.headComponents), _react.default.createElement("body", props.bodyAttributes, props.preBodyComponents, _react.default.createElement("div", { 22 | key: `body`, 23 | id: "___gatsby", 24 | dangerouslySetInnerHTML: { 25 | __html: props.body 26 | } 27 | }), props.postBodyComponents)); 28 | } 29 | 30 | HTML.propTypes = { 31 | htmlAttributes: _propTypes.default.object, 32 | headComponents: _propTypes.default.array, 33 | bodyAttributes: _propTypes.default.object, 34 | preBodyComponents: _propTypes.default.array, 35 | body: _propTypes.default.string, 36 | postBodyComponents: _propTypes.default.array 37 | }; -------------------------------------------------------------------------------- /src/useKeyCapture/index.js: -------------------------------------------------------------------------------- 1 | import { useEffect, useReducer, useRef } from 'react'; 2 | import reducer from './useKeyCaptureReducer'; 3 | 4 | import { 5 | initialState, 6 | getAction, 7 | useKeyActionTypes, 8 | useEnhancedReducer, 9 | targetItemPropsDefaultValue, 10 | handleRefAssignment 11 | } from './useKeyCaptureUtils'; 12 | 13 | function useKeys() { 14 | const [keyData, dispatch] = useReducer( 15 | useEnhancedReducer(reducer), 16 | initialState 17 | ); 18 | 19 | const targetItemRef = useRef(null); 20 | 21 | const dispatchWithActionDetails = event => { 22 | dispatch(getAction(event)); 23 | }; 24 | 25 | /** 26 | * It resets all state values to initial values 27 | */ 28 | const resetKeyData = () => { 29 | dispatch({ 30 | type: useKeyActionTypes.RESET_CAPTURES 31 | }); 32 | }; 33 | 34 | useEffect(() => { 35 | // example for IS_TRUSTED as false 36 | // setTimeout(() => { 37 | // document.dispatchEvent(new KeyboardEvent('keydown'), { key: 'Escape' }); 38 | // }, 2000); 39 | }, [keyData]); 40 | 41 | useEffect(() => { 42 | const listenerItem = targetItemRef.current || document; 43 | listenerItem.addEventListener('keydown', dispatchWithActionDetails); 44 | 45 | return () => { 46 | listenerItem.removeEventListener('keydown', dispatchWithActionDetails); 47 | }; 48 | }, []); 49 | 50 | const getTargetProps = ({ ref, type } = {}) => { 51 | return { 52 | type: type || targetItemPropsDefaultValue.type, 53 | ref: handleRefAssignment(ref, targetItemNode => { 54 | targetItemRef.current = targetItemNode; 55 | }) 56 | }; 57 | }; 58 | 59 | return { keyData, resetKeyData, getTargetProps }; 60 | } 61 | 62 | export default useKeys; 63 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/page-renderer.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); 6 | 7 | exports.__esModule = true; 8 | exports.default = void 0; 9 | 10 | var _react = _interopRequireWildcard(require("react")); 11 | 12 | var _propTypes = _interopRequireDefault(require("prop-types")); 13 | 14 | var _loader = require("./loader"); 15 | 16 | var _apiRunnerBrowser = require("./api-runner-browser"); 17 | 18 | class PageRenderer extends _react.default.Component { 19 | render() { 20 | const props = Object.assign({}, this.props, { 21 | pathContext: this.props.pageContext 22 | }); 23 | const [replacementElement] = (0, _apiRunnerBrowser.apiRunner)(`replaceComponentRenderer`, { 24 | props: this.props, 25 | loader: _loader.publicLoader 26 | }); 27 | const pageElement = replacementElement || (0, _react.createElement)(this.props.pageResources.component, Object.assign({}, props, { 28 | key: this.props.path || this.props.pageResources.page.path 29 | })); 30 | const wrappedPage = (0, _apiRunnerBrowser.apiRunner)(`wrapPageElement`, { 31 | element: pageElement, 32 | props 33 | }, pageElement, ({ 34 | result 35 | }) => { 36 | return { 37 | element: result, 38 | props 39 | }; 40 | }).pop(); 41 | return wrappedPage; 42 | } 43 | 44 | } 45 | 46 | PageRenderer.propTypes = { 47 | location: _propTypes.default.object.isRequired, 48 | pageResources: _propTypes.default.object.isRequired, 49 | data: _propTypes.default.object, 50 | pageContext: _propTypes.default.object.isRequired 51 | }; 52 | var _default = PageRenderer; 53 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/error-overlay-handler.js: -------------------------------------------------------------------------------- 1 | import * as ErrorOverlay from "react-error-overlay" 2 | 3 | // Report runtime errors 4 | ErrorOverlay.startReportingRuntimeErrors({ 5 | onError: () => {}, 6 | filename: `/commons.js`, 7 | }) 8 | ErrorOverlay.setEditorHandler(errorLocation => 9 | window.fetch( 10 | `/__open-stack-frame-in-editor?fileName=` + 11 | window.encodeURIComponent(errorLocation.fileName) + 12 | `&lineNumber=` + 13 | window.encodeURIComponent(errorLocation.lineNumber || 1) 14 | ) 15 | ) 16 | 17 | const errorMap = {} 18 | 19 | function flat(arr) { 20 | return Array.prototype.flat ? arr.flat() : [].concat(...arr) 21 | } 22 | 23 | const handleErrorOverlay = () => { 24 | const errors = Object.values(errorMap) 25 | let errorStringsToDisplay = [] 26 | if (errors.length > 0) { 27 | errorStringsToDisplay = flat(errors) 28 | .map(error => { 29 | if (typeof error === `string`) { 30 | return error 31 | } else if (typeof error === `object`) { 32 | const errorStrBuilder = [error.text] 33 | 34 | if (error.filePath) { 35 | errorStrBuilder.push(`File: ${error.filePath}`) 36 | } 37 | 38 | return errorStrBuilder.join(`\n\n`) 39 | } 40 | 41 | return null 42 | }) 43 | .filter(Boolean) 44 | } 45 | 46 | if (errorStringsToDisplay.length > 0) { 47 | ErrorOverlay.reportBuildError(errorStringsToDisplay.join(`\n\n`)) 48 | } else { 49 | ErrorOverlay.dismissBuildError() 50 | } 51 | } 52 | 53 | export const clearError = errorID => { 54 | delete errorMap[errorID] 55 | handleErrorOverlay() 56 | } 57 | 58 | export const reportError = (errorID, error) => { 59 | if (error) { 60 | errorMap[errorID] = error 61 | } 62 | handleErrorOverlay() 63 | } 64 | 65 | export { errorMap } 66 | -------------------------------------------------------------------------------- /.docz/.cache/api-runner-ssr.js: -------------------------------------------------------------------------------- 1 | var plugins = [{ 2 | plugin: require('/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/gatsby-plugin-mdx/gatsby-ssr'), 3 | options: {"plugins":[],"extensions":[".md",".mdx"],"remarkPlugins":[[null,{"type":"yaml","marker":"-"}],null],"rehypePlugins":[null,null],"gatsbyRemarkPlugins":[],"defaultLayouts":{"default":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/gatsby-theme-docz/src/base/Layout.js"}}, 4 | },{ 5 | plugin: require('/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/gatsby-plugin-react-helmet-async/gatsby-ssr'), 6 | options: {"plugins":[]}, 7 | }] 8 | // During bootstrap, we write requires at top of this file which looks like: 9 | // var plugins = [ 10 | // { 11 | // plugin: require("/path/to/plugin1/gatsby-ssr.js"), 12 | // options: { ... }, 13 | // }, 14 | // { 15 | // plugin: require("/path/to/plugin2/gatsby-ssr.js"), 16 | // options: { ... }, 17 | // }, 18 | // ] 19 | 20 | const apis = require(`./api-ssr-docs`) 21 | 22 | // Run the specified API in any plugins that have implemented it 23 | module.exports = (api, args, defaultReturn, argTransform) => { 24 | if (!apis[api]) { 25 | console.log(`This API doesn't exist`, api) 26 | } 27 | 28 | // Run each plugin in series. 29 | // eslint-disable-next-line no-undef 30 | let results = plugins.map(plugin => { 31 | if (!plugin.plugin[api]) { 32 | return undefined 33 | } 34 | const result = plugin.plugin[api](args, plugin.options) 35 | if (result && argTransform) { 36 | args = argTransform({ args, result }) 37 | } 38 | return result 39 | }) 40 | 41 | // Filter out undefined results. 42 | results = results.filter(result => typeof result !== `undefined`) 43 | 44 | if (results.length > 0) { 45 | return results 46 | } else { 47 | return [defaultReturn] 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "use-key-capture", 3 | "version": "1.0.1-beta.1", 4 | "main": "dist", 5 | "license": "MIT", 6 | "scripts": { 7 | "build": "rimraf dist && babel src --ignore */__tests__ --out-dir dist", 8 | "prepare": "yarn test && yarn build", 9 | "postpublish": "git push --tags", 10 | "test": "jest --config=jest.config.js", 11 | "test:watch": "jest --config=jest.config.js --watch", 12 | "test:coverage": "jest --config=jest.config.js --coverage && open coverage/Icov-report/index.html", 13 | "docz:dev": "docz dev", 14 | "docz:build": "docz build", 15 | "docz:serve": "docz build && docz serve", 16 | "predeploy": "yarn test && yarn docz:build", 17 | "deploy": "gh-pages -d .docz/dist" 18 | }, 19 | "keywords": [ 20 | "keyboard event", 21 | "key press", 22 | "enhanced key press event", 23 | "key press listener", 24 | "react" 25 | ], 26 | "devDependencies": { 27 | "@babel/cli": "^7.7.7", 28 | "@babel/core": "^7.7.7", 29 | "@babel/plugin-transform-runtime": "^7.8.3", 30 | "@babel/preset-env": "^7.7.7", 31 | "@babel/preset-react": "^7.7.4", 32 | "@testing-library/jest-dom": "^5.0.0", 33 | "@testing-library/react": "^9.4.0", 34 | "@testing-library/react-hooks": "^3.2.1", 35 | "docz": "^2.2.0", 36 | "gh-pages": "^2.2.0", 37 | "husky": "^4.2.1", 38 | "jest": "^24.9.0", 39 | "react-test-renderer": "^16.12.0", 40 | "rimraf": "^3.0.0" 41 | }, 42 | "husky": { 43 | "hooks": { 44 | "pre-commit": "yarn test" 45 | } 46 | }, 47 | "peerDependencies": { 48 | "@babel/runtime": "^7.8.4", 49 | "react": "^16.12.0", 50 | "react-dom": "^16.12.0" 51 | }, 52 | "browserslist": "> 0.25%, not dead", 53 | "author": "Pranesh T G", 54 | "homepage": "http://pranesh239.github.io/use-key-capture", 55 | "bugs": { 56 | "url": "https://github.com/pranesh239/use-key-capture/issues" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /.docz/.cache/api-runner-browser.js: -------------------------------------------------------------------------------- 1 | const plugins = require(`./api-runner-browser-plugins`) 2 | const { 3 | getResourcesForPathname, 4 | getResourcesForPathnameSync, 5 | getResourceURLsForPathname, 6 | loadPage, 7 | loadPageSync, 8 | } = require(`./loader`).publicLoader 9 | 10 | exports.apiRunner = (api, args = {}, defaultReturn, argTransform) => { 11 | // Hooks for gatsby-cypress's API handler 12 | if (process.env.CYPRESS_SUPPORT) { 13 | if (window.___apiHandler) { 14 | window.___apiHandler(api) 15 | } else if (window.___resolvedAPIs) { 16 | window.___resolvedAPIs.push(api) 17 | } else { 18 | window.___resolvedAPIs = [api] 19 | } 20 | } 21 | 22 | let results = plugins.map(plugin => { 23 | if (!plugin.plugin[api]) { 24 | return undefined 25 | } 26 | 27 | // Deprecated April 2019. Use `loadPageSync` instead 28 | args.getResourcesForPathnameSync = getResourcesForPathnameSync 29 | // Deprecated April 2019. Use `loadPage` instead 30 | args.getResourcesForPathname = getResourcesForPathname 31 | args.getResourceURLsForPathname = getResourceURLsForPathname 32 | args.loadPage = loadPage 33 | args.loadPageSync = loadPageSync 34 | 35 | const result = plugin.plugin[api](args, plugin.options) 36 | if (result && argTransform) { 37 | args = argTransform({ args, result, plugin }) 38 | } 39 | return result 40 | }) 41 | 42 | // Filter out undefined results. 43 | results = results.filter(result => typeof result !== `undefined`) 44 | 45 | if (results.length > 0) { 46 | return results 47 | } else if (defaultReturn) { 48 | return [defaultReturn] 49 | } else { 50 | return [] 51 | } 52 | } 53 | 54 | exports.apiRunnerAsync = (api, args, defaultReturn) => 55 | plugins.reduce( 56 | (previous, next) => 57 | next.plugin[api] 58 | ? previous.then(() => next.plugin[api](args, next.options)) 59 | : previous, 60 | Promise.resolve() 61 | ) 62 | -------------------------------------------------------------------------------- /.docz/.cache/__tests__/error-overlay-handler.js: -------------------------------------------------------------------------------- 1 | import "@babel/polyfill" 2 | const { 3 | reportError, 4 | clearError, 5 | errorMap, 6 | } = require(`../error-overlay-handler`) 7 | 8 | import * as ErrorOverlay from "react-error-overlay" 9 | 10 | jest.mock(`react-error-overlay`, () => { 11 | return { 12 | reportBuildError: jest.fn(), 13 | dismissBuildError: jest.fn(), 14 | startReportingRuntimeErrors: jest.fn(), 15 | setEditorHandler: jest.fn(), 16 | } 17 | }) 18 | 19 | beforeEach(() => { 20 | ErrorOverlay.reportBuildError.mockClear() 21 | ErrorOverlay.dismissBuildError.mockClear() 22 | }) 23 | 24 | describe(`errorOverlayHandler`, () => { 25 | describe(`clearError()`, () => { 26 | beforeEach(() => { 27 | reportError(`foo`, `error`) 28 | reportError(`bar`, `error`) 29 | }) 30 | afterAll(() => { 31 | clearError(`foo`) 32 | clearError(`bar`) 33 | }) 34 | it(`should clear specific error type`, () => { 35 | expect(Object.keys(errorMap)).toHaveLength(2) 36 | clearError(`foo`) 37 | expect(Object.keys(errorMap)).toHaveLength(1) 38 | expect(ErrorOverlay.dismissBuildError).not.toHaveBeenCalled() 39 | }) 40 | 41 | it(`should call ErrorOverlay to dismiss build errors`, () => { 42 | clearError(`foo`) 43 | clearError(`bar`) 44 | expect(ErrorOverlay.dismissBuildError).toHaveBeenCalled() 45 | }) 46 | }) 47 | describe(`reportErrorOverlay()`, () => { 48 | it(`should not add error if it's empty and not call ErrorOverlay`, () => { 49 | reportError(`foo`, null) 50 | expect(Object.keys(errorMap)).toHaveLength(0) 51 | expect(ErrorOverlay.reportBuildError).not.toHaveBeenCalled() 52 | }) 53 | it(`should add error if it has a truthy value and call ErrorOverlay`, () => { 54 | reportError(`foo`, `bar`) 55 | expect(Object.keys(errorMap)).toHaveLength(1) 56 | expect(ErrorOverlay.reportBuildError).toHaveBeenCalled() 57 | }) 58 | }) 59 | }) 60 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/api-runner-browser.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | const plugins = require(`./api-runner-browser-plugins`); 4 | 5 | const { 6 | getResourcesForPathname, 7 | getResourcesForPathnameSync, 8 | getResourceURLsForPathname, 9 | loadPage, 10 | loadPageSync 11 | } = require(`./loader`).publicLoader; 12 | 13 | exports.apiRunner = (api, args = {}, defaultReturn, argTransform) => { 14 | // Hooks for gatsby-cypress's API handler 15 | if (process.env.CYPRESS_SUPPORT) { 16 | if (window.___apiHandler) { 17 | window.___apiHandler(api); 18 | } else if (window.___resolvedAPIs) { 19 | window.___resolvedAPIs.push(api); 20 | } else { 21 | window.___resolvedAPIs = [api]; 22 | } 23 | } 24 | 25 | let results = plugins.map(plugin => { 26 | if (!plugin.plugin[api]) { 27 | return undefined; 28 | } // Deprecated April 2019. Use `loadPageSync` instead 29 | 30 | 31 | args.getResourcesForPathnameSync = getResourcesForPathnameSync; // Deprecated April 2019. Use `loadPage` instead 32 | 33 | args.getResourcesForPathname = getResourcesForPathname; 34 | args.getResourceURLsForPathname = getResourceURLsForPathname; 35 | args.loadPage = loadPage; 36 | args.loadPageSync = loadPageSync; 37 | const result = plugin.plugin[api](args, plugin.options); 38 | 39 | if (result && argTransform) { 40 | args = argTransform({ 41 | args, 42 | result, 43 | plugin 44 | }); 45 | } 46 | 47 | return result; 48 | }); // Filter out undefined results. 49 | 50 | results = results.filter(result => typeof result !== `undefined`); 51 | 52 | if (results.length > 0) { 53 | return results; 54 | } else if (defaultReturn) { 55 | return [defaultReturn]; 56 | } else { 57 | return []; 58 | } 59 | }; 60 | 61 | exports.apiRunnerAsync = (api, args, defaultReturn) => plugins.reduce((previous, next) => next.plugin[api] ? previous.then(() => next.plugin[api](args, next.options)) : previous, Promise.resolve()); -------------------------------------------------------------------------------- /.docz/.cache/commonjs/error-overlay-handler.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); 4 | 5 | exports.__esModule = true; 6 | exports.errorMap = exports.reportError = exports.clearError = void 0; 7 | 8 | var ErrorOverlay = _interopRequireWildcard(require("react-error-overlay")); 9 | 10 | // Report runtime errors 11 | ErrorOverlay.startReportingRuntimeErrors({ 12 | onError: () => {}, 13 | filename: `/commons.js` 14 | }); 15 | ErrorOverlay.setEditorHandler(errorLocation => window.fetch(`/__open-stack-frame-in-editor?fileName=` + window.encodeURIComponent(errorLocation.fileName) + `&lineNumber=` + window.encodeURIComponent(errorLocation.lineNumber || 1))); 16 | const errorMap = {}; 17 | exports.errorMap = errorMap; 18 | 19 | function flat(arr) { 20 | return Array.prototype.flat ? arr.flat() : [].concat(...arr); 21 | } 22 | 23 | const handleErrorOverlay = () => { 24 | const errors = Object.values(errorMap); 25 | let errorStringsToDisplay = []; 26 | 27 | if (errors.length > 0) { 28 | errorStringsToDisplay = flat(errors).map(error => { 29 | if (typeof error === `string`) { 30 | return error; 31 | } else if (typeof error === `object`) { 32 | const errorStrBuilder = [error.text]; 33 | 34 | if (error.filePath) { 35 | errorStrBuilder.push(`File: ${error.filePath}`); 36 | } 37 | 38 | return errorStrBuilder.join(`\n\n`); 39 | } 40 | 41 | return null; 42 | }).filter(Boolean); 43 | } 44 | 45 | if (errorStringsToDisplay.length > 0) { 46 | ErrorOverlay.reportBuildError(errorStringsToDisplay.join(`\n\n`)); 47 | } else { 48 | ErrorOverlay.dismissBuildError(); 49 | } 50 | }; 51 | 52 | const clearError = errorID => { 53 | delete errorMap[errorID]; 54 | handleErrorOverlay(); 55 | }; 56 | 57 | exports.clearError = clearError; 58 | 59 | const reportError = (errorID, error) => { 60 | if (error) { 61 | errorMap[errorID] = error; 62 | } 63 | 64 | handleErrorOverlay(); 65 | }; 66 | 67 | exports.reportError = reportError; -------------------------------------------------------------------------------- /.docz/.cache/prefetch.js: -------------------------------------------------------------------------------- 1 | const support = function(feature) { 2 | if (typeof document === `undefined`) { 3 | return false 4 | } 5 | const fakeLink = document.createElement(`link`) 6 | try { 7 | if (fakeLink.relList && typeof fakeLink.relList.supports === `function`) { 8 | return fakeLink.relList.supports(feature) 9 | } 10 | } catch (err) { 11 | return false 12 | } 13 | return false 14 | } 15 | 16 | const linkPrefetchStrategy = function(url, options) { 17 | return new Promise((resolve, reject) => { 18 | if (typeof document === `undefined`) { 19 | reject() 20 | return 21 | } 22 | 23 | const link = document.createElement(`link`) 24 | link.setAttribute(`rel`, `prefetch`) 25 | link.setAttribute(`href`, url) 26 | 27 | Object.keys(options).forEach(key => { 28 | link.setAttribute(key, options[key]) 29 | }) 30 | 31 | link.onload = resolve 32 | link.onerror = reject 33 | 34 | const parentElement = 35 | document.getElementsByTagName(`head`)[0] || 36 | document.getElementsByName(`script`)[0].parentNode 37 | parentElement.appendChild(link) 38 | }) 39 | } 40 | 41 | const xhrPrefetchStrategy = function(url) { 42 | return new Promise((resolve, reject) => { 43 | const req = new XMLHttpRequest() 44 | req.open(`GET`, url, true) 45 | 46 | req.onload = () => { 47 | if (req.status === 200) { 48 | resolve() 49 | } else { 50 | reject() 51 | } 52 | } 53 | 54 | req.send(null) 55 | }) 56 | } 57 | 58 | const supportedPrefetchStrategy = support(`prefetch`) 59 | ? linkPrefetchStrategy 60 | : xhrPrefetchStrategy 61 | 62 | const preFetched = {} 63 | 64 | const prefetch = function(url, options) { 65 | return new Promise(resolve => { 66 | if (preFetched[url]) { 67 | resolve() 68 | return 69 | } 70 | 71 | supportedPrefetchStrategy(url, options) 72 | .then(() => { 73 | resolve() 74 | preFetched[url] = true 75 | }) 76 | .catch(() => {}) // 404s are logged to the console anyway 77 | }) 78 | } 79 | 80 | export default prefetch 81 | -------------------------------------------------------------------------------- /.docz/public/webpack.stats.json: -------------------------------------------------------------------------------- 1 | {"errors":[],"warnings":[],"namedChunkGroups":{"app":{"chunks":[7,6,0,1],"assets":["webpack-runtime-357cce2467b02eb17283.js","webpack-runtime-357cce2467b02eb17283.js.map","styles.617b70be7bd88a8d962f.css","styles-fca67d4a49d8b7427c9b.js","styles-fca67d4a49d8b7427c9b.js.map","commons-2c28349e80f1eab29f39.js","commons-2c28349e80f1eab29f39.js.map","app-d181e0c33b178d7f5bfb.js","app-d181e0c33b178d7f5bfb.js.map"],"children":{},"childAssets":{}},"component---docs-index-mdx":{"chunks":[0,2],"assets":["commons-2c28349e80f1eab29f39.js","commons-2c28349e80f1eab29f39.js.map","component---docs-index-mdx-3927419ecd2651d24dd3.js","component---docs-index-mdx-3927419ecd2651d24dd3.js.map"],"children":{},"childAssets":{}},"component---docs-pages-props-mdx":{"chunks":[0,4],"assets":["commons-2c28349e80f1eab29f39.js","commons-2c28349e80f1eab29f39.js.map","component---docs-pages-props-mdx-592d10813f233ead71ef.js","component---docs-pages-props-mdx-592d10813f233ead71ef.js.map"],"children":{},"childAssets":{}},"component---docs-pages-demo-mdx":{"chunks":[0,3],"assets":["commons-2c28349e80f1eab29f39.js","commons-2c28349e80f1eab29f39.js.map","component---docs-pages-demo-mdx-da562a47741883850a15.js","component---docs-pages-demo-mdx-da562a47741883850a15.js.map"],"children":{},"childAssets":{}},"component---src-pages-404-js":{"chunks":[5],"assets":["component---src-pages-404-js-2a38f26ee55704d6d07d.js","component---src-pages-404-js-2a38f26ee55704d6d07d.js.map"],"children":{},"childAssets":{}}},"assetsByChunkName":{"app":["webpack-runtime-357cce2467b02eb17283.js","styles.617b70be7bd88a8d962f.css","styles-fca67d4a49d8b7427c9b.js","commons-2c28349e80f1eab29f39.js","app-d181e0c33b178d7f5bfb.js"],"component---docs-index-mdx":["commons-2c28349e80f1eab29f39.js","component---docs-index-mdx-3927419ecd2651d24dd3.js"],"component---docs-pages-props-mdx":["commons-2c28349e80f1eab29f39.js","component---docs-pages-props-mdx-592d10813f233ead71ef.js"],"component---docs-pages-demo-mdx":["commons-2c28349e80f1eab29f39.js","component---docs-pages-demo-mdx-da562a47741883850a15.js"],"component---src-pages-404-js":["component---src-pages-404-js-2a38f26ee55704d6d07d.js"]}} -------------------------------------------------------------------------------- /.docz/.cache/commonjs/prefetch.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | exports.__esModule = true; 4 | exports.default = void 0; 5 | 6 | const support = function (feature) { 7 | if (typeof document === `undefined`) { 8 | return false; 9 | } 10 | 11 | const fakeLink = document.createElement(`link`); 12 | 13 | try { 14 | if (fakeLink.relList && typeof fakeLink.relList.supports === `function`) { 15 | return fakeLink.relList.supports(feature); 16 | } 17 | } catch (err) { 18 | return false; 19 | } 20 | 21 | return false; 22 | }; 23 | 24 | const linkPrefetchStrategy = function (url, options) { 25 | return new Promise((resolve, reject) => { 26 | if (typeof document === `undefined`) { 27 | reject(); 28 | return; 29 | } 30 | 31 | const link = document.createElement(`link`); 32 | link.setAttribute(`rel`, `prefetch`); 33 | link.setAttribute(`href`, url); 34 | Object.keys(options).forEach(key => { 35 | link.setAttribute(key, options[key]); 36 | }); 37 | link.onload = resolve; 38 | link.onerror = reject; 39 | const parentElement = document.getElementsByTagName(`head`)[0] || document.getElementsByName(`script`)[0].parentNode; 40 | parentElement.appendChild(link); 41 | }); 42 | }; 43 | 44 | const xhrPrefetchStrategy = function (url) { 45 | return new Promise((resolve, reject) => { 46 | const req = new XMLHttpRequest(); 47 | req.open(`GET`, url, true); 48 | 49 | req.onload = () => { 50 | if (req.status === 200) { 51 | resolve(); 52 | } else { 53 | reject(); 54 | } 55 | }; 56 | 57 | req.send(null); 58 | }); 59 | }; 60 | 61 | const supportedPrefetchStrategy = support(`prefetch`) ? linkPrefetchStrategy : xhrPrefetchStrategy; 62 | const preFetched = {}; 63 | 64 | const prefetch = function (url, options) { 65 | return new Promise(resolve => { 66 | if (preFetched[url]) { 67 | resolve(); 68 | return; 69 | } 70 | 71 | supportedPrefetchStrategy(url, options).then(() => { 72 | resolve(); 73 | preFetched[url] = true; 74 | }).catch(() => {}); // 404s are logged to the console anyway 75 | }); 76 | }; 77 | 78 | var _default = prefetch; 79 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/app.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import ReactDOM from "react-dom" 3 | import domReady from "@mikaelkristiansson/domready" 4 | 5 | import socketIo from "./socketIo" 6 | import emitter from "./emitter" 7 | import { apiRunner, apiRunnerAsync } from "./api-runner-browser" 8 | import { setLoader, publicLoader } from "./loader" 9 | import DevLoader from "./dev-loader" 10 | import syncRequires from "./sync-requires" 11 | // Generated during bootstrap 12 | import matchPaths from "./match-paths.json" 13 | 14 | window.___emitter = emitter 15 | 16 | const loader = new DevLoader(syncRequires, matchPaths) 17 | setLoader(loader) 18 | loader.setApiRunner(apiRunner) 19 | 20 | window.___loader = publicLoader 21 | 22 | // Let the site/plugins run code very early. 23 | apiRunnerAsync(`onClientEntry`).then(() => { 24 | // Hook up the client to socket.io on server 25 | const socket = socketIo() 26 | if (socket) { 27 | socket.on(`reload`, () => { 28 | window.location.reload() 29 | }) 30 | } 31 | 32 | /** 33 | * Service Workers are persistent by nature. They stick around, 34 | * serving a cached version of the site if they aren't removed. 35 | * This is especially frustrating when you need to test the 36 | * production build on your local machine. 37 | * 38 | * Let's warn if we find service workers in development. 39 | */ 40 | if (`serviceWorker` in navigator) { 41 | navigator.serviceWorker.getRegistrations().then(registrations => { 42 | if (registrations.length > 0) 43 | console.warn( 44 | `Warning: found one or more service workers present.`, 45 | `If your site isn't behaving as expected, you might want to remove these.`, 46 | registrations 47 | ) 48 | }) 49 | } 50 | 51 | const rootElement = document.getElementById(`___gatsby`) 52 | 53 | const renderer = apiRunner( 54 | `replaceHydrateFunction`, 55 | undefined, 56 | ReactDOM.render 57 | )[0] 58 | 59 | Promise.all([ 60 | loader.loadPage(`/dev-404-page/`), 61 | loader.loadPage(`/404.html`), 62 | loader.loadPage(window.location.pathname), 63 | ]).then(() => { 64 | const preferDefault = m => (m && m.default) || m 65 | let Root = preferDefault(require(`./root`)) 66 | domReady(() => { 67 | renderer(, rootElement, () => { 68 | apiRunner(`onInitialClientRender`) 69 | }) 70 | }) 71 | }) 72 | }) 73 | -------------------------------------------------------------------------------- /.docz/.cache/ensure-resources.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import loader from "./loader" 3 | import shallowCompare from "shallow-compare" 4 | 5 | class EnsureResources extends React.Component { 6 | constructor(props) { 7 | super() 8 | const { location, pageResources } = props 9 | this.state = { 10 | location: { ...location }, 11 | pageResources: pageResources || loader.loadPageSync(location.pathname), 12 | } 13 | } 14 | 15 | static getDerivedStateFromProps({ location }, prevState) { 16 | if (prevState.location.href !== location.href) { 17 | const pageResources = loader.loadPageSync(location.pathname) 18 | return { 19 | pageResources, 20 | location: { ...location }, 21 | } 22 | } 23 | 24 | return { 25 | location: { ...location }, 26 | } 27 | } 28 | 29 | loadResources(rawPath) { 30 | loader.loadPage(rawPath).then(pageResources => { 31 | if (pageResources && pageResources.status !== `error`) { 32 | this.setState({ 33 | location: { ...window.location }, 34 | pageResources, 35 | }) 36 | } else { 37 | window.history.replaceState({}, ``, location.href) 38 | window.location = rawPath 39 | } 40 | }) 41 | } 42 | 43 | shouldComponentUpdate(nextProps, nextState) { 44 | // Always return false if we're missing resources. 45 | if (!nextState.pageResources) { 46 | this.loadResources(nextProps.location.pathname) 47 | return false 48 | } 49 | 50 | // Check if the component or json have changed. 51 | if (this.state.pageResources !== nextState.pageResources) { 52 | return true 53 | } 54 | if ( 55 | this.state.pageResources.component !== nextState.pageResources.component 56 | ) { 57 | return true 58 | } 59 | 60 | if (this.state.pageResources.json !== nextState.pageResources.json) { 61 | return true 62 | } 63 | // Check if location has changed on a page using internal routing 64 | // via matchPath configuration. 65 | if ( 66 | this.state.location.key !== nextState.location.key && 67 | nextState.pageResources.page && 68 | (nextState.pageResources.page.matchPath || 69 | nextState.pageResources.page.path) 70 | ) { 71 | return true 72 | } 73 | return shallowCompare(this, nextProps, nextState) 74 | } 75 | 76 | render() { 77 | return this.props.children(this.state) 78 | } 79 | } 80 | 81 | export default EnsureResources 82 | -------------------------------------------------------------------------------- /src/useKeyCapture/useKeyCaptureReducer.js: -------------------------------------------------------------------------------- 1 | import { initialState, useKeyActionTypes } from './useKeyCaptureUtils'; 2 | 3 | export default function keyReducer(state, action) { 4 | switch (action.type) { 5 | case useKeyActionTypes.ESCAPE_KEY: { 6 | return { 7 | ...initialState, 8 | isEscape: true, 9 | ...action.payload 10 | }; 11 | } 12 | 13 | case useKeyActionTypes.ENTER_KEY: { 14 | return { 15 | ...initialState, 16 | isEnter: true, 17 | ...action.payload 18 | }; 19 | } 20 | 21 | case useKeyActionTypes.CAPSLOCK: { 22 | return { 23 | ...initialState, 24 | isCapsLock: true, 25 | ...action.payload 26 | }; 27 | } 28 | 29 | case useKeyActionTypes.BACKSPACE: { 30 | return { 31 | ...initialState, 32 | isBackspace: true, 33 | ...action.payload 34 | }; 35 | } 36 | 37 | case useKeyActionTypes.SHIFT: { 38 | return { 39 | ...initialState, 40 | isShift: true, 41 | ...action.payload 42 | }; 43 | } 44 | 45 | case useKeyActionTypes.CAPS_ALPHABET: { 46 | return { 47 | ...initialState, 48 | isCaps: true, 49 | ...action.payload 50 | }; 51 | } 52 | 53 | case useKeyActionTypes.SMALL_ALPHABET: { 54 | return { 55 | ...initialState, 56 | isSmall: true, 57 | ...action.payload 58 | }; 59 | } 60 | 61 | case useKeyActionTypes.NUMBER: { 62 | return { 63 | ...initialState, 64 | isNumber: true, 65 | ...action.payload 66 | }; 67 | } 68 | 69 | case useKeyActionTypes.SPACE: { 70 | return { 71 | ...initialState, 72 | isSpace: true, 73 | ...action.payload 74 | }; 75 | } 76 | 77 | case useKeyActionTypes.TAB: { 78 | return { 79 | ...initialState, 80 | isTab: true, 81 | ...action.payload 82 | }; 83 | } 84 | 85 | case useKeyActionTypes.SPECIAL: { 86 | return { 87 | ...initialState, 88 | isSpecialCharacter: true, 89 | ...action.payload 90 | }; 91 | } 92 | 93 | case useKeyActionTypes.ARROWS: { 94 | return { 95 | ...initialState, 96 | isArrow: true, 97 | ...action.payload 98 | }; 99 | } 100 | default: 101 | return { ...initialState }; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /.docz/public/webpack-runtime-357cce2467b02eb17283.js: -------------------------------------------------------------------------------- 1 | !function(e){function r(r){for(var n,u,c=r[0],i=r[1],p=r[2],f=0,l=[];f 19 | ``` 20 | 21 | 22 | 23 | ```jsx 24 | import React from 'react'; 25 | import useKey from 'use-key-capture'; 26 | import './styles.css'; 27 | 28 | const displayKeys = ['Q', 'W', 'E', 'R', 'T', 'Y', 'Backspace']; 29 | 30 | const TargetEventComponent = () => { 31 | const { keyData, getTargetProps } = useKey(); 32 | 33 | const getIsActive = key => (keyData.key === key ? 'active' : ''); 34 | 35 | return ( 36 |
37 |
38 | Type QWERTY in the input element below. If the focus is outside the 39 | target, we won't see any change. 40 |
41 | 42 |
43 | {displayKeys.map(key => { 44 | return
{key}
; 45 | })} 46 |
47 |
48 | ); 49 | }; 50 | 51 | export default TargetEventComponent; 52 | ``` 53 | 54 | ## Global Listener 55 | 56 | If no target is specified, it will listen for global event. 57 | 58 | 59 | 60 | ```jsx 61 | import React from 'react'; 62 | import useKey from 'use-key-capture'; 63 | import './styles.css'; 64 | 65 | const displayKeys = ['Enter', 'Escape', 'Tab', 'ArrowUp']; 66 | 67 | const GlobalComponent = () => { 68 | const { keyData } = useKey(); 69 | 70 | const getIsActive = key => (keyData.key === key ? 'active' : ''); 71 | 72 | const getCombinedActiveClass = () => 73 | keyData.key === 'A' && keyData.isWithShift ? 'active' : ''; 74 | 75 | return ( 76 | <> 77 |
78 | Press below mentioned keys to see the hook in action 79 |
80 |
81 | {displayKeys.map(key => { 82 | return
{key}
; 83 | })} 84 |
Shift + A
85 |
86 | 87 | ); 88 | }; 89 | 90 | export default GlobalComponent; 91 | ``` 92 | -------------------------------------------------------------------------------- /.docz/public/static/d/1803957048.json: -------------------------------------------------------------------------------- 1 | {"data":{"doczDb":{"id":"ace00e2b-9c46-5e24-a19a-5ed242ca9c64","db":"{\"config\":{\"title\":\"Use Key Capture\",\"description\":\"My awesome app using docz\",\"menu\":[],\"version\":\"1.0.0\",\"repository\":null,\"native\":false,\"themeConfig\":{},\"separator\":\"-\",\"ignore\":[\"README.md\"],\"public\":\"./public\",\"htmlContext\":{\"favicon\":\"/public/public/images/favicon.png\"}},\"entries\":[{\"key\":\"docs/index.mdx\",\"value\":{\"name\":\"Docs\",\"route\":\"/\",\"order\":1,\"id\":\"73498ad0e1e62a714b08085d318f9de1\",\"filepath\":\"docs/index.mdx\",\"fullpath\":\"/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/index.mdx\",\"link\":\"\",\"slug\":\"docs-index\",\"menu\":\"\",\"headings\":[{\"slug\":\"use-key-capture\",\"depth\":1,\"value\":\"use-key-capture\"},{\"slug\":\"installation\",\"depth\":2,\"value\":\"Installation\"},{\"slug\":\"how-it-is-used\",\"depth\":2,\"value\":\"How it is used\"},{\"slug\":\"properties\",\"depth\":2,\"value\":\"Properties\"},{\"slug\":\"target-prop-getter\",\"depth\":2,\"value\":\"Target Prop getter\"}]}},{\"key\":\"docs/pages/demo.mdx\",\"value\":{\"name\":\"Demo\",\"route\":\"/demo\",\"order\":2,\"id\":\"87411c77fdcfbb7f6278f322040c1731\",\"filepath\":\"docs/pages/demo.mdx\",\"fullpath\":\"/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/demo.mdx\",\"link\":\"\",\"slug\":\"docs-pages-demo\",\"menu\":\"\",\"headings\":[{\"slug\":\"target-listener\",\"depth\":2,\"value\":\"Target Listener\"},{\"slug\":\"global-listener\",\"depth\":2,\"value\":\"Global Listener\"}]}},{\"key\":\"docs/pages/props.mdx\",\"value\":{\"name\":\"Props\",\"route\":\"/props\",\"order\":2,\"id\":\"b5cb4d959720d31e411c9b125e451a6a\",\"filepath\":\"docs/pages/props.mdx\",\"fullpath\":\"/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/props.mdx\",\"link\":\"\",\"slug\":\"docs-pages-props\",\"menu\":\"\",\"headings\":[{\"slug\":\"props\",\"depth\":2,\"value\":\"Props\"},{\"slug\":\"keydata\",\"depth\":3,\"value\":\"keyData\"},{\"slug\":\"gettargetprops\",\"depth\":3,\"value\":\"getTargetProps\"},{\"slug\":\"resetkeydata\",\"depth\":3,\"value\":\"resetKeyData\"}]}}],\"props\":[{\"key\":\"docs/Components/GlobalEventComponent.js\",\"value\":[{\"description\":\"\",\"displayName\":\"GlobalComponent\",\"methods\":[],\"actualName\":\"GlobalComponent\"}]},{\"key\":\"docs/Components/TargetEventComponent.js\",\"value\":[{\"description\":\"\",\"displayName\":\"TargetEventComponent\",\"methods\":[],\"actualName\":\"TargetEventComponent\"}]},{\"key\":\"src/__tests__/utils/TestComponent.js\",\"value\":[{\"description\":\"\",\"displayName\":\"TestComponent\",\"methods\":[],\"actualName\":\"TestComponent\"}]}]}"}}} -------------------------------------------------------------------------------- /.docz/.cache/find-path.js: -------------------------------------------------------------------------------- 1 | import { match } from "@reach/router/lib/utils" 2 | import stripPrefix from "./strip-prefix" 3 | import normalizePagePath from "./normalize-page-path" 4 | 5 | const pathCache = new Map() 6 | let matchPaths = [] 7 | 8 | const trimPathname = rawPathname => { 9 | const pathname = decodeURIComponent(rawPathname) 10 | // Remove the pathPrefix from the pathname. 11 | const trimmedPathname = stripPrefix(pathname, __BASE_PATH__) 12 | // Remove any hashfragment 13 | .split(`#`)[0] 14 | // Remove search query 15 | .split(`?`)[0] 16 | 17 | return trimmedPathname 18 | } 19 | 20 | /** 21 | * Set list of matchPaths 22 | * 23 | * @param {Array<{path: string, matchPath: string}>} value collection of matchPaths 24 | */ 25 | export const setMatchPaths = value => { 26 | matchPaths = value 27 | } 28 | 29 | /** 30 | * Return a matchpath url 31 | * if `match-paths.json` contains `{ "/foo*": "/page1", ...}`, then 32 | * `/foo?bar=far` => `/page1` 33 | * 34 | * @param {string} rawPathname A raw pathname 35 | * @return {string|null} 36 | */ 37 | export const findMatchPath = rawPathname => { 38 | const trimmedPathname = cleanPath(rawPathname) 39 | 40 | for (const { matchPath, path } of matchPaths) { 41 | if (match(matchPath, trimmedPathname)) { 42 | return normalizePagePath(path) 43 | } 44 | } 45 | 46 | return null 47 | } 48 | 49 | // Given a raw URL path, returns the cleaned version of it (trim off 50 | // `#` and query params), or if it matches an entry in 51 | // `match-paths.json`, its matched path is returned 52 | // 53 | // E.g. `/foo?bar=far` => `/foo` 54 | // 55 | // Or if `match-paths.json` contains `{ "/foo*": "/page1", ...}`, then 56 | // `/foo?bar=far` => `/page1` 57 | export const findPath = rawPathname => { 58 | const trimmedPathname = trimPathname(rawPathname) 59 | 60 | if (pathCache.has(trimmedPathname)) { 61 | return pathCache.get(trimmedPathname) 62 | } 63 | 64 | let foundPath = findMatchPath(trimmedPathname) 65 | 66 | if (!foundPath) { 67 | foundPath = cleanPath(rawPathname) 68 | } 69 | 70 | pathCache.set(trimmedPathname, foundPath) 71 | 72 | return foundPath 73 | } 74 | 75 | /** 76 | * Clean a url and converts /index.html => / 77 | * E.g. `/foo?bar=far` => `/foo` 78 | * 79 | * @param {string} rawPathname A raw pathname 80 | * @return {string} 81 | */ 82 | export const cleanPath = rawPathname => { 83 | const trimmedPathname = trimPathname(rawPathname) 84 | 85 | let foundPath = trimmedPathname 86 | if (foundPath === `/index.html`) { 87 | foundPath = `/` 88 | } 89 | 90 | foundPath = normalizePagePath(foundPath) 91 | 92 | return foundPath 93 | } 94 | -------------------------------------------------------------------------------- /.docz/.cache/api-runner-browser-plugins.js: -------------------------------------------------------------------------------- 1 | module.exports = [{ 2 | plugin: require('../../node_modules/gatsby-plugin-mdx/gatsby-browser.js'), 3 | options: {"plugins":[],"extensions":[".md",".mdx"],"remarkPlugins":[[null,{"type":"yaml","marker":"-"}],null],"rehypePlugins":[null,null],"gatsbyRemarkPlugins":[],"defaultLayouts":{"default":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/gatsby-theme-docz/src/base/Layout.js"}}, 4 | },{ 5 | plugin: require('../../node_modules/gatsby-plugin-react-helmet-async/gatsby-browser.js'), 6 | options: {"plugins":[]}, 7 | },{ 8 | plugin: require('../../node_modules/gatsby-theme-docz/gatsby-browser.js'), 9 | options: {"plugins":[],"themeConfig":{},"themesDir":"src","mdxExtensions":[".md",".mdx"],"docgenConfig":{},"menu":[],"mdPlugins":[],"hastPlugins":[],"ignore":["README.md"],"typescript":false,"ts":false,"propsParser":true,"props-parser":true,"debug":false,"native":false,"openBrowser":false,"o":false,"open":false,"open-browser":false,"root":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz","base":"/","source":"./","src":"./","files":"**/*.{md,markdown,mdx}","public":"./public","dest":".docz/dist","d":".docz/dist","editBranch":"master","eb":"master","edit-branch":"master","config":"","title":"Use Key Capture","description":"My awesome app using docz","host":"localhost","port":3000,"p":3000,"separator":"-","paths":{"root":"/Users/pranesh.g/Documents/opensource/use-key-capture-2","templates":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/docz-core/dist/templates","docz":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz","cache":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/.cache","app":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/app","appPackageJson":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/package.json","gatsbyConfig":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/gatsby-config.js","gatsbyBrowser":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/gatsby-browser.js","gatsbyNode":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/gatsby-node.js","gatsbySSR":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/gatsby-ssr.js","importsJs":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/app/imports.js","rootJs":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/app/root.jsx","indexJs":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/app/index.jsx","indexHtml":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/app/index.html","db":"/Users/pranesh.g/Documents/opensource/use-key-capture-2/.docz/app/db.json"},"htmlContext":{"favicon":"/public/public/images/favicon.png"}}, 10 | }] 11 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/app.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | var _react = _interopRequireDefault(require("react")); 6 | 7 | var _reactDom = _interopRequireDefault(require("react-dom")); 8 | 9 | var _domready = _interopRequireDefault(require("@mikaelkristiansson/domready")); 10 | 11 | var _socketIo = _interopRequireDefault(require("./socketIo")); 12 | 13 | var _emitter = _interopRequireDefault(require("./emitter")); 14 | 15 | var _apiRunnerBrowser = require("./api-runner-browser"); 16 | 17 | var _loader = require("./loader"); 18 | 19 | var _devLoader = _interopRequireDefault(require("./dev-loader")); 20 | 21 | var _syncRequires = _interopRequireDefault(require("./sync-requires")); 22 | 23 | var _matchPaths = _interopRequireDefault(require("./match-paths.json")); 24 | 25 | // Generated during bootstrap 26 | window.___emitter = _emitter.default; 27 | const loader = new _devLoader.default(_syncRequires.default, _matchPaths.default); 28 | (0, _loader.setLoader)(loader); 29 | loader.setApiRunner(_apiRunnerBrowser.apiRunner); 30 | window.___loader = _loader.publicLoader; // Let the site/plugins run code very early. 31 | 32 | (0, _apiRunnerBrowser.apiRunnerAsync)(`onClientEntry`).then(() => { 33 | // Hook up the client to socket.io on server 34 | const socket = (0, _socketIo.default)(); 35 | 36 | if (socket) { 37 | socket.on(`reload`, () => { 38 | window.location.reload(); 39 | }); 40 | } 41 | /** 42 | * Service Workers are persistent by nature. They stick around, 43 | * serving a cached version of the site if they aren't removed. 44 | * This is especially frustrating when you need to test the 45 | * production build on your local machine. 46 | * 47 | * Let's warn if we find service workers in development. 48 | */ 49 | 50 | 51 | if (`serviceWorker` in navigator) { 52 | navigator.serviceWorker.getRegistrations().then(registrations => { 53 | if (registrations.length > 0) console.warn(`Warning: found one or more service workers present.`, `If your site isn't behaving as expected, you might want to remove these.`, registrations); 54 | }); 55 | } 56 | 57 | const rootElement = document.getElementById(`___gatsby`); 58 | const renderer = (0, _apiRunnerBrowser.apiRunner)(`replaceHydrateFunction`, undefined, _reactDom.default.render)[0]; 59 | Promise.all([loader.loadPage(`/dev-404-page/`), loader.loadPage(`/404.html`), loader.loadPage(window.location.pathname)]).then(() => { 60 | const preferDefault = m => m && m.default || m; 61 | 62 | let Root = preferDefault(require(`./root`)); 63 | (0, _domready.default)(() => { 64 | renderer(_react.default.createElement(Root, null), rootElement, () => { 65 | (0, _apiRunnerBrowser.apiRunner)(`onInitialClientRender`); 66 | }); 67 | }); 68 | }); 69 | }); -------------------------------------------------------------------------------- /.docz/public/404/index.html: -------------------------------------------------------------------------------- 1 |
Not Found
-------------------------------------------------------------------------------- /.docz/public/404.html: -------------------------------------------------------------------------------- 1 |
Not Found
-------------------------------------------------------------------------------- /.docz/.cache/commonjs/ensure-resources.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | var _loader = _interopRequireDefault(require("./loader")); 11 | 12 | var _shallowCompare = _interopRequireDefault(require("shallow-compare")); 13 | 14 | class EnsureResources extends _react.default.Component { 15 | constructor(props) { 16 | super(); 17 | const { 18 | location, 19 | pageResources 20 | } = props; 21 | this.state = { 22 | location: Object.assign({}, location), 23 | pageResources: pageResources || _loader.default.loadPageSync(location.pathname) 24 | }; 25 | } 26 | 27 | static getDerivedStateFromProps({ 28 | location 29 | }, prevState) { 30 | if (prevState.location.href !== location.href) { 31 | const pageResources = _loader.default.loadPageSync(location.pathname); 32 | 33 | return { 34 | pageResources, 35 | location: Object.assign({}, location) 36 | }; 37 | } 38 | 39 | return { 40 | location: Object.assign({}, location) 41 | }; 42 | } 43 | 44 | loadResources(rawPath) { 45 | _loader.default.loadPage(rawPath).then(pageResources => { 46 | if (pageResources && pageResources.status !== `error`) { 47 | this.setState({ 48 | location: Object.assign({}, window.location), 49 | pageResources 50 | }); 51 | } else { 52 | window.history.replaceState({}, ``, location.href); 53 | window.location = rawPath; 54 | } 55 | }); 56 | } 57 | 58 | shouldComponentUpdate(nextProps, nextState) { 59 | // Always return false if we're missing resources. 60 | if (!nextState.pageResources) { 61 | this.loadResources(nextProps.location.pathname); 62 | return false; 63 | } // Check if the component or json have changed. 64 | 65 | 66 | if (this.state.pageResources !== nextState.pageResources) { 67 | return true; 68 | } 69 | 70 | if (this.state.pageResources.component !== nextState.pageResources.component) { 71 | return true; 72 | } 73 | 74 | if (this.state.pageResources.json !== nextState.pageResources.json) { 75 | return true; 76 | } // Check if location has changed on a page using internal routing 77 | // via matchPath configuration. 78 | 79 | 80 | if (this.state.location.key !== nextState.location.key && nextState.pageResources.page && (nextState.pageResources.page.matchPath || nextState.pageResources.page.path)) { 81 | return true; 82 | } 83 | 84 | return (0, _shallowCompare.default)(this, nextProps, nextState); 85 | } 86 | 87 | render() { 88 | return this.props.children(this.state); 89 | } 90 | 91 | } 92 | 93 | var _default = EnsureResources; 94 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/register-service-worker.js: -------------------------------------------------------------------------------- 1 | import { apiRunner } from "./api-runner-browser" 2 | 3 | if ( 4 | window.location.protocol !== `https:` && 5 | window.location.hostname !== `localhost` 6 | ) { 7 | console.error( 8 | `Service workers can only be used over HTTPS, or on localhost for development` 9 | ) 10 | } else if (`serviceWorker` in navigator) { 11 | navigator.serviceWorker 12 | .register(`${__BASE_PATH__}/sw.js`) 13 | .then(function(reg) { 14 | reg.addEventListener(`updatefound`, () => { 15 | apiRunner(`onServiceWorkerUpdateFound`, { serviceWorker: reg }) 16 | // The updatefound event implies that reg.installing is set; see 17 | // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event 18 | const installingWorker = reg.installing 19 | console.log(`installingWorker`, installingWorker) 20 | installingWorker.addEventListener(`statechange`, () => { 21 | switch (installingWorker.state) { 22 | case `installed`: 23 | if (navigator.serviceWorker.controller) { 24 | // At this point, the old content will have been purged and the fresh content will 25 | // have been added to the cache. 26 | 27 | // We set a flag so Gatsby Link knows to refresh the page on next navigation attempt 28 | window.___swUpdated = true 29 | // We call the onServiceWorkerUpdateReady API so users can show update prompts. 30 | apiRunner(`onServiceWorkerUpdateReady`, { serviceWorker: reg }) 31 | 32 | // If resources failed for the current page, reload. 33 | if (window.___failedResources) { 34 | console.log(`resources failed, SW updated - reloading`) 35 | window.location.reload() 36 | } 37 | } else { 38 | // At this point, everything has been precached. 39 | // It's the perfect time to display a "Content is cached for offline use." message. 40 | console.log(`Content is now available offline!`) 41 | 42 | // Post to service worker that install is complete. 43 | // Delay to allow time for the event listener to be added -- 44 | // otherwise fetch is called too soon and resources aren't cached. 45 | apiRunner(`onServiceWorkerInstalled`, { serviceWorker: reg }) 46 | } 47 | break 48 | 49 | case `redundant`: 50 | console.error(`The installing service worker became redundant.`) 51 | apiRunner(`onServiceWorkerRedundant`, { serviceWorker: reg }) 52 | break 53 | 54 | case `activated`: 55 | apiRunner(`onServiceWorkerActive`, { serviceWorker: reg }) 56 | break 57 | } 58 | }) 59 | }) 60 | }) 61 | .catch(function(e) { 62 | console.error(`Error during service worker registration:`, e) 63 | }) 64 | } 65 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/register-service-worker.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _apiRunnerBrowser = require("./api-runner-browser"); 4 | 5 | if (window.location.protocol !== `https:` && window.location.hostname !== `localhost`) { 6 | console.error(`Service workers can only be used over HTTPS, or on localhost for development`); 7 | } else if (`serviceWorker` in navigator) { 8 | navigator.serviceWorker.register(`${__BASE_PATH__}/sw.js`).then(function (reg) { 9 | reg.addEventListener(`updatefound`, () => { 10 | (0, _apiRunnerBrowser.apiRunner)(`onServiceWorkerUpdateFound`, { 11 | serviceWorker: reg 12 | }); // The updatefound event implies that reg.installing is set; see 13 | // https://w3c.github.io/ServiceWorker/#service-worker-registration-updatefound-event 14 | 15 | const installingWorker = reg.installing; 16 | console.log(`installingWorker`, installingWorker); 17 | installingWorker.addEventListener(`statechange`, () => { 18 | switch (installingWorker.state) { 19 | case `installed`: 20 | if (navigator.serviceWorker.controller) { 21 | // At this point, the old content will have been purged and the fresh content will 22 | // have been added to the cache. 23 | // We set a flag so Gatsby Link knows to refresh the page on next navigation attempt 24 | window.___swUpdated = true; // We call the onServiceWorkerUpdateReady API so users can show update prompts. 25 | 26 | (0, _apiRunnerBrowser.apiRunner)(`onServiceWorkerUpdateReady`, { 27 | serviceWorker: reg 28 | }); // If resources failed for the current page, reload. 29 | 30 | if (window.___failedResources) { 31 | console.log(`resources failed, SW updated - reloading`); 32 | window.location.reload(); 33 | } 34 | } else { 35 | // At this point, everything has been precached. 36 | // It's the perfect time to display a "Content is cached for offline use." message. 37 | console.log(`Content is now available offline!`); // Post to service worker that install is complete. 38 | // Delay to allow time for the event listener to be added -- 39 | // otherwise fetch is called too soon and resources aren't cached. 40 | 41 | (0, _apiRunnerBrowser.apiRunner)(`onServiceWorkerInstalled`, { 42 | serviceWorker: reg 43 | }); 44 | } 45 | 46 | break; 47 | 48 | case `redundant`: 49 | console.error(`The installing service worker became redundant.`); 50 | (0, _apiRunnerBrowser.apiRunner)(`onServiceWorkerRedundant`, { 51 | serviceWorker: reg 52 | }); 53 | break; 54 | 55 | case `activated`: 56 | (0, _apiRunnerBrowser.apiRunner)(`onServiceWorkerActive`, { 57 | serviceWorker: reg 58 | }); 59 | break; 60 | } 61 | }); 62 | }); 63 | }).catch(function (e) { 64 | console.error(`Error during service worker registration:`, e); 65 | }); 66 | } -------------------------------------------------------------------------------- /.docz/.cache/gatsby-browser-entry.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import PropTypes from "prop-types" 3 | import Link, { 4 | withPrefix, 5 | withAssetPrefix, 6 | navigate, 7 | push, 8 | replace, 9 | navigateTo, 10 | parsePath, 11 | } from "gatsby-link" 12 | import PageRenderer from "./public-page-renderer" 13 | import loader from "./loader" 14 | 15 | const prefetchPathname = loader.enqueue 16 | 17 | const StaticQueryContext = React.createContext({}) 18 | 19 | function StaticQueryDataRenderer({ staticQueryData, data, query, render }) { 20 | const finalData = data 21 | ? data.data 22 | : staticQueryData[query] && staticQueryData[query].data 23 | 24 | return ( 25 | 26 | {finalData && render(finalData)} 27 | {!finalData &&
Loading (StaticQuery)
} 28 |
29 | ) 30 | } 31 | 32 | const StaticQuery = props => { 33 | const { data, query, render, children } = props 34 | 35 | return ( 36 | 37 | {staticQueryData => ( 38 | 44 | )} 45 | 46 | ) 47 | } 48 | 49 | const useStaticQuery = query => { 50 | if ( 51 | typeof React.useContext !== `function` && 52 | process.env.NODE_ENV === `development` 53 | ) { 54 | throw new Error( 55 | `You're likely using a version of React that doesn't support Hooks\n` + 56 | `Please update React and ReactDOM to 16.8.0 or later to use the useStaticQuery hook.` 57 | ) 58 | } 59 | const context = React.useContext(StaticQueryContext) 60 | if (context[query] && context[query].data) { 61 | return context[query].data 62 | } else { 63 | throw new Error( 64 | `The result of this StaticQuery could not be fetched.\n\n` + 65 | `This is likely a bug in Gatsby and if refreshing the page does not fix it, ` + 66 | `please open an issue in https://github.com/gatsbyjs/gatsby/issues` 67 | ) 68 | } 69 | } 70 | 71 | StaticQuery.propTypes = { 72 | data: PropTypes.object, 73 | query: PropTypes.string.isRequired, 74 | render: PropTypes.func, 75 | children: PropTypes.func, 76 | } 77 | 78 | function graphql() { 79 | throw new Error( 80 | `It appears like Gatsby is misconfigured. Gatsby related \`graphql\` calls ` + 81 | `are supposed to only be evaluated at compile time, and then compiled away. ` + 82 | `Unfortunately, something went wrong and the query was left in the compiled code.\n\n` + 83 | `Unless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.` 84 | ) 85 | } 86 | 87 | export { 88 | Link, 89 | withAssetPrefix, 90 | withPrefix, 91 | graphql, 92 | parsePath, 93 | navigate, 94 | push, // TODO replace for v3 95 | replace, // TODO remove replace for v3 96 | navigateTo, // TODO: remove navigateTo for v3 97 | StaticQueryContext, 98 | StaticQuery, 99 | PageRenderer, 100 | useStaticQuery, 101 | prefetchPathname, 102 | } 103 | -------------------------------------------------------------------------------- /.docz/.cache/__tests__/find-path.js: -------------------------------------------------------------------------------- 1 | import { cleanPath, setMatchPaths, findMatchPath, findPath } from "../find-path" 2 | 3 | describe(`find-path`, () => { 4 | describe(`cleanPath`, () => { 5 | beforeEach(() => { 6 | global.__BASE_PATH__ = `` 7 | }) 8 | 9 | it(`should strip out ? & # from a pathname`, () => { 10 | expect(cleanPath(`/mypath#anchor?gatsby=cool`)).toBe(`/mypath`) 11 | }) 12 | 13 | it(`should convert a /index.html to root dir`, () => { 14 | expect(cleanPath(`/index.html`)).toBe(`/`) 15 | }) 16 | 17 | it(`strip out a basePrefix`, () => { 18 | global.__BASE_PATH__ = `/blog` 19 | expect(cleanPath(`/blog/mypath`)).toBe(`/mypath`) 20 | }) 21 | }) 22 | 23 | describe(`findMatchPath`, () => { 24 | beforeEach(() => { 25 | // reset matchPaths 26 | setMatchPaths([]) 27 | global.__BASE_PATH__ = `` 28 | }) 29 | 30 | it(`should find a path when matchPath found`, () => { 31 | setMatchPaths([ 32 | { 33 | matchPath: `/app/*`, 34 | path: `/app`, 35 | }, 36 | ]) 37 | 38 | expect(findMatchPath(`/app/dynamic-page#anchor?gatsby=cool`)).toBe(`/app`) 39 | }) 40 | 41 | it(`should return null when no matchPathFound`, () => { 42 | setMatchPaths([ 43 | { 44 | matchPath: `/app/*`, 45 | path: `/app`, 46 | }, 47 | ]) 48 | 49 | expect(findMatchPath(`/notanapp/dynamic-page`)).toBeNull() 50 | }) 51 | }) 52 | 53 | describe(`findPath`, () => { 54 | beforeEach(() => { 55 | // reset matchPaths 56 | setMatchPaths([]) 57 | global.__BASE_PATH__ = `` 58 | }) 59 | 60 | it(`should use matchPath if found`, () => { 61 | setMatchPaths([ 62 | { 63 | matchPath: `/app/*`, 64 | path: `/app`, 65 | }, 66 | ]) 67 | 68 | expect(findPath(`/app/dynamic-page#anchor?gatsby=cool`)).toBe(`/app`) 69 | }) 70 | 71 | it(`should return the cleaned up path when no matchPathFound`, () => { 72 | setMatchPaths([ 73 | { 74 | matchPath: `/app/*`, 75 | path: `/app`, 76 | }, 77 | ]) 78 | 79 | expect(findPath(`/notanapp/my-page#anchor?gatsby=cool`)).toBe( 80 | `/notanapp/my-page` 81 | ) 82 | }) 83 | 84 | it(`should only process a request once`, () => { 85 | jest.resetModules() 86 | jest.mock(`@reach/router/lib/utils`) 87 | const findPath = require(`../find-path`).findPath 88 | const setMatchPaths = require(`../find-path`).setMatchPaths 89 | const match = require(`@reach/router/lib/utils`).match 90 | 91 | setMatchPaths([ 92 | { 93 | matchPath: `/app/*`, 94 | path: `/app`, 95 | }, 96 | ]) 97 | 98 | expect(findPath(`/notanapp/my-page#anchor?gatsby=cool`)).toBe( 99 | `/notanapp/my-page` 100 | ) 101 | expect(findPath(`/notanapp/my-page#anchor?gatsby=cool`)).toBe( 102 | `/notanapp/my-page` 103 | ) 104 | expect(findPath(`/notanapp/my-page`)).toBe(`/notanapp/my-page`) 105 | 106 | expect(match).toHaveBeenCalledTimes(1) 107 | }) 108 | }) 109 | }) 110 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/find-path.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.cleanPath = exports.findPath = exports.findMatchPath = exports.setMatchPaths = void 0; 7 | 8 | var _utils = require("@reach/router/lib/utils"); 9 | 10 | var _stripPrefix = _interopRequireDefault(require("./strip-prefix")); 11 | 12 | var _normalizePagePath = _interopRequireDefault(require("./normalize-page-path")); 13 | 14 | const pathCache = new Map(); 15 | let matchPaths = []; 16 | 17 | const trimPathname = rawPathname => { 18 | const pathname = decodeURIComponent(rawPathname); // Remove the pathPrefix from the pathname. 19 | 20 | const trimmedPathname = (0, _stripPrefix.default)(pathname, __BASE_PATH__) // Remove any hashfragment 21 | .split(`#`)[0] // Remove search query 22 | .split(`?`)[0]; 23 | return trimmedPathname; 24 | }; 25 | /** 26 | * Set list of matchPaths 27 | * 28 | * @param {Array<{path: string, matchPath: string}>} value collection of matchPaths 29 | */ 30 | 31 | 32 | const setMatchPaths = value => { 33 | matchPaths = value; 34 | }; 35 | /** 36 | * Return a matchpath url 37 | * if `match-paths.json` contains `{ "/foo*": "/page1", ...}`, then 38 | * `/foo?bar=far` => `/page1` 39 | * 40 | * @param {string} rawPathname A raw pathname 41 | * @return {string|null} 42 | */ 43 | 44 | 45 | exports.setMatchPaths = setMatchPaths; 46 | 47 | const findMatchPath = rawPathname => { 48 | const trimmedPathname = cleanPath(rawPathname); 49 | 50 | for (const { 51 | matchPath, 52 | path 53 | } of matchPaths) { 54 | if ((0, _utils.match)(matchPath, trimmedPathname)) { 55 | return (0, _normalizePagePath.default)(path); 56 | } 57 | } 58 | 59 | return null; 60 | }; // Given a raw URL path, returns the cleaned version of it (trim off 61 | // `#` and query params), or if it matches an entry in 62 | // `match-paths.json`, its matched path is returned 63 | // 64 | // E.g. `/foo?bar=far` => `/foo` 65 | // 66 | // Or if `match-paths.json` contains `{ "/foo*": "/page1", ...}`, then 67 | // `/foo?bar=far` => `/page1` 68 | 69 | 70 | exports.findMatchPath = findMatchPath; 71 | 72 | const findPath = rawPathname => { 73 | const trimmedPathname = trimPathname(rawPathname); 74 | 75 | if (pathCache.has(trimmedPathname)) { 76 | return pathCache.get(trimmedPathname); 77 | } 78 | 79 | let foundPath = findMatchPath(trimmedPathname); 80 | 81 | if (!foundPath) { 82 | foundPath = cleanPath(rawPathname); 83 | } 84 | 85 | pathCache.set(trimmedPathname, foundPath); 86 | return foundPath; 87 | }; 88 | /** 89 | * Clean a url and converts /index.html => / 90 | * E.g. `/foo?bar=far` => `/foo` 91 | * 92 | * @param {string} rawPathname A raw pathname 93 | * @return {string} 94 | */ 95 | 96 | 97 | exports.findPath = findPath; 98 | 99 | const cleanPath = rawPathname => { 100 | const trimmedPathname = trimPathname(rawPathname); 101 | let foundPath = trimmedPathname; 102 | 103 | if (foundPath === `/index.html`) { 104 | foundPath = `/`; 105 | } 106 | 107 | foundPath = (0, _normalizePagePath.default)(foundPath); 108 | return foundPath; 109 | }; 110 | 111 | exports.cleanPath = cleanPath; -------------------------------------------------------------------------------- /.docz/public/component---docs-index-mdx-3927419ecd2651d24dd3.js: -------------------------------------------------------------------------------- 1 | (window.webpackJsonp=window.webpackJsonp||[]).push([[2],{IXnM:function(e,t,a){"use strict";a.r(t),a.d(t,"_frontmatter",(function(){return l})),a.d(t,"default",(function(){return o}));a("5hJT"),a("W1QL"),a("K/PF"),a("t91x"),a("75LO"),a("PJhk"),a("mXGw");var n=a("/FXl"),r=a("TjRS");a("aD51");function b(){return(b=Object.assign||function(e){for(var t=1;t=0||(r[a]=e[a]);return r}(e,["components"]);return Object(n.b)(c,b({},p,a,{components:t,mdxType:"MDXLayout"}),Object(n.b)("h1",{id:"use-key-capture"},"use-key-capture"),Object(n.b)("p",null,"use-key-capture is a custom hook which will let us not to worry about the key-press event. Just plugin in use-key-capture hook to the ",Object(n.b)("strong",{parentName:"p"},"target")," we want to listen for key press event or by default it can listen for key-press event ",Object(n.b)("strong",{parentName:"p"},"globally"),"."),Object(n.b)("h2",{id:"installation"},"Installation"),Object(n.b)("p",null,Object(n.b)("strong",{parentName:"p"},"npm")),Object(n.b)("pre",null,Object(n.b)("code",b({parentName:"pre"},{className:"language-bash"}),"npm i use-key-capture\n")),Object(n.b)("p",null,Object(n.b)("strong",{parentName:"p"},"yarn")),Object(n.b)("pre",null,Object(n.b)("code",b({parentName:"pre"},{className:"language-bash"}),"yarn add use-key-capture\n")),Object(n.b)("h2",{id:"how-it-is-used"},"How it is used"),Object(n.b)("pre",null,Object(n.b)("code",b({parentName:"pre"},{className:"language-jsx"}),"import useKey from 'use-key-capture';\n...\nconst { keyData, resetKeyData, getTargetProps } = useKey();\n")),Object(n.b)("h2",{id:"properties"},"Properties"),Object(n.b)("table",null,Object(n.b)("thead",{parentName:"table"},Object(n.b)("tr",{parentName:"thead"},Object(n.b)("th",b({parentName:"tr"},{align:null}),"Property name"),Object(n.b)("th",b({parentName:"tr"},{align:null}),"Description"))),Object(n.b)("tbody",{parentName:"table"},Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"keyData"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"gives pressed key details")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"resetKeyData"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"resets the pressed key details")))),Object(n.b)("h2",{id:"target-prop-getter"},"Target Prop getter"),Object(n.b)("table",null,Object(n.b)("thead",{parentName:"table"},Object(n.b)("tr",{parentName:"thead"},Object(n.b)("th",b({parentName:"tr"},{align:null}),"Property name"),Object(n.b)("th",b({parentName:"tr"},{align:null}),"Description"))),Object(n.b)("tbody",{parentName:"table"},Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"getTargetProps"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"gives the required props to target element")))))}o&&o===Object(o)&&Object.isExtensible(o)&&!o.hasOwnProperty("__filemeta")&&Object.defineProperty(o,"__filemeta",{configurable:!0,value:{name:"MDXContent",filename:"docs/index.mdx"}}),o.isMDXComponent=!0}}]); 2 | //# sourceMappingURL=component---docs-index-mdx-3927419ecd2651d24dd3.js.map -------------------------------------------------------------------------------- /.docz/.cache/commonjs/gatsby-browser-entry.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); 4 | 5 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 6 | 7 | exports.__esModule = true; 8 | exports.graphql = graphql; 9 | exports.prefetchPathname = exports.useStaticQuery = exports.StaticQuery = exports.StaticQueryContext = void 0; 10 | 11 | var _react = _interopRequireDefault(require("react")); 12 | 13 | var _propTypes = _interopRequireDefault(require("prop-types")); 14 | 15 | var _gatsbyLink = _interopRequireWildcard(require("gatsby-link")); 16 | 17 | exports.Link = _gatsbyLink.default; 18 | exports.withPrefix = _gatsbyLink.withPrefix; 19 | exports.withAssetPrefix = _gatsbyLink.withAssetPrefix; 20 | exports.navigate = _gatsbyLink.navigate; 21 | exports.push = _gatsbyLink.push; 22 | exports.replace = _gatsbyLink.replace; 23 | exports.navigateTo = _gatsbyLink.navigateTo; 24 | exports.parsePath = _gatsbyLink.parsePath; 25 | 26 | var _publicPageRenderer = _interopRequireDefault(require("./public-page-renderer")); 27 | 28 | exports.PageRenderer = _publicPageRenderer.default; 29 | 30 | var _loader = _interopRequireDefault(require("./loader")); 31 | 32 | const prefetchPathname = _loader.default.enqueue; 33 | exports.prefetchPathname = prefetchPathname; 34 | 35 | const StaticQueryContext = _react.default.createContext({}); 36 | 37 | exports.StaticQueryContext = StaticQueryContext; 38 | 39 | function StaticQueryDataRenderer({ 40 | staticQueryData, 41 | data, 42 | query, 43 | render 44 | }) { 45 | const finalData = data ? data.data : staticQueryData[query] && staticQueryData[query].data; 46 | return _react.default.createElement(_react.default.Fragment, null, finalData && render(finalData), !finalData && _react.default.createElement("div", null, "Loading (StaticQuery)")); 47 | } 48 | 49 | const StaticQuery = props => { 50 | const { 51 | data, 52 | query, 53 | render, 54 | children 55 | } = props; 56 | return _react.default.createElement(StaticQueryContext.Consumer, null, staticQueryData => _react.default.createElement(StaticQueryDataRenderer, { 57 | data: data, 58 | query: query, 59 | render: render || children, 60 | staticQueryData: staticQueryData 61 | })); 62 | }; 63 | 64 | exports.StaticQuery = StaticQuery; 65 | 66 | const useStaticQuery = query => { 67 | if (typeof _react.default.useContext !== `function` && process.env.NODE_ENV === `development`) { 68 | throw new Error(`You're likely using a version of React that doesn't support Hooks\n` + `Please update React and ReactDOM to 16.8.0 or later to use the useStaticQuery hook.`); 69 | } 70 | 71 | const context = _react.default.useContext(StaticQueryContext); 72 | 73 | if (context[query] && context[query].data) { 74 | return context[query].data; 75 | } else { 76 | throw new Error(`The result of this StaticQuery could not be fetched.\n\n` + `This is likely a bug in Gatsby and if refreshing the page does not fix it, ` + `please open an issue in https://github.com/gatsbyjs/gatsby/issues`); 77 | } 78 | }; 79 | 80 | exports.useStaticQuery = useStaticQuery; 81 | StaticQuery.propTypes = { 82 | data: _propTypes.default.object, 83 | query: _propTypes.default.string.isRequired, 84 | render: _propTypes.default.func, 85 | children: _propTypes.default.func 86 | }; 87 | 88 | function graphql() { 89 | throw new Error(`It appears like Gatsby is misconfigured. Gatsby related \`graphql\` calls ` + `are supposed to only be evaluated at compile time, and then compiled away. ` + `Unfortunately, something went wrong and the query was left in the compiled code.\n\n` + `Unless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.`); 90 | } -------------------------------------------------------------------------------- /.docz/.cache/develop-static-entry.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import { renderToStaticMarkup } from "react-dom/server" 3 | import { merge } from "lodash" 4 | import apiRunner from "./api-runner-ssr" 5 | // import testRequireError from "./test-require-error" 6 | // For some extremely mysterious reason, webpack adds the above module *after* 7 | // this module so that when this code runs, testRequireError is undefined. 8 | // So in the meantime, we'll just inline it. 9 | const testRequireError = (moduleName, err) => { 10 | const regex = new RegExp(`Error: Cannot find module\\s.${moduleName}`) 11 | const firstLine = err.toString().split(`\n`)[0] 12 | return regex.test(firstLine) 13 | } 14 | 15 | let Html 16 | try { 17 | Html = require(`../src/html`) 18 | } catch (err) { 19 | if (testRequireError(`../src/html`, err)) { 20 | Html = require(`./default-html`) 21 | } else { 22 | console.log(`There was an error requiring "src/html.js"\n\n`, err, `\n\n`) 23 | process.exit() 24 | } 25 | } 26 | 27 | Html = Html && Html.__esModule ? Html.default : Html 28 | 29 | export default (pagePath, callback) => { 30 | let headComponents = [ 31 | , 32 | ] 33 | let htmlAttributes = {} 34 | let bodyAttributes = {} 35 | let preBodyComponents = [] 36 | let postBodyComponents = [] 37 | let bodyProps = {} 38 | let htmlStr 39 | 40 | const setHeadComponents = components => { 41 | headComponents = headComponents.concat(components) 42 | } 43 | 44 | const setHtmlAttributes = attributes => { 45 | htmlAttributes = merge(htmlAttributes, attributes) 46 | } 47 | 48 | const setBodyAttributes = attributes => { 49 | bodyAttributes = merge(bodyAttributes, attributes) 50 | } 51 | 52 | const setPreBodyComponents = components => { 53 | preBodyComponents = preBodyComponents.concat(components) 54 | } 55 | 56 | const setPostBodyComponents = components => { 57 | postBodyComponents = postBodyComponents.concat(components) 58 | } 59 | 60 | const setBodyProps = props => { 61 | bodyProps = merge({}, bodyProps, props) 62 | } 63 | 64 | const getHeadComponents = () => headComponents 65 | 66 | const replaceHeadComponents = components => { 67 | headComponents = components 68 | } 69 | 70 | const getPreBodyComponents = () => preBodyComponents 71 | 72 | const replacePreBodyComponents = components => { 73 | preBodyComponents = components 74 | } 75 | 76 | const getPostBodyComponents = () => postBodyComponents 77 | 78 | const replacePostBodyComponents = components => { 79 | postBodyComponents = components 80 | } 81 | 82 | apiRunner(`onRenderBody`, { 83 | setHeadComponents, 84 | setHtmlAttributes, 85 | setBodyAttributes, 86 | setPreBodyComponents, 87 | setPostBodyComponents, 88 | setBodyProps, 89 | pathname: pagePath, 90 | }) 91 | 92 | apiRunner(`onPreRenderHTML`, { 93 | getHeadComponents, 94 | replaceHeadComponents, 95 | getPreBodyComponents, 96 | replacePreBodyComponents, 97 | getPostBodyComponents, 98 | replacePostBodyComponents, 99 | pathname: pagePath, 100 | }) 101 | 102 | const htmlElement = React.createElement(Html, { 103 | ...bodyProps, 104 | body: ``, 105 | headComponents: headComponents.concat([ 106 |
"`; 4 | 5 | exports[`develop-static-entry onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; 6 | 7 | exports[`develop-static-entry onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; 8 | 9 | exports[`static-entry onPreRenderHTML can be used to replace headComponents 1`] = `"
"`; 10 | 11 | exports[`static-entry onPreRenderHTML can be used to replace postBodyComponents 1`] = `"
div3
div2
div1
"`; 12 | 13 | exports[`static-entry onPreRenderHTML can be used to replace preBodyComponents 1`] = `"
div3
div2
div1
"`; 14 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/develop-static-entry.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _react = _interopRequireDefault(require("react")); 9 | 10 | var _server = require("react-dom/server"); 11 | 12 | var _lodash = require("lodash"); 13 | 14 | var _apiRunnerSsr = _interopRequireDefault(require("./api-runner-ssr")); 15 | 16 | // import testRequireError from "./test-require-error" 17 | // For some extremely mysterious reason, webpack adds the above module *after* 18 | // this module so that when this code runs, testRequireError is undefined. 19 | // So in the meantime, we'll just inline it. 20 | const testRequireError = (moduleName, err) => { 21 | const regex = new RegExp(`Error: Cannot find module\\s.${moduleName}`); 22 | const firstLine = err.toString().split(`\n`)[0]; 23 | return regex.test(firstLine); 24 | }; 25 | 26 | let Html; 27 | 28 | try { 29 | Html = require(`../src/html`); 30 | } catch (err) { 31 | if (testRequireError(`../src/html`, err)) { 32 | Html = require(`./default-html`); 33 | } else { 34 | console.log(`There was an error requiring "src/html.js"\n\n`, err, `\n\n`); 35 | process.exit(); 36 | } 37 | } 38 | 39 | Html = Html && Html.__esModule ? Html.default : Html; 40 | 41 | var _default = (pagePath, callback) => { 42 | let headComponents = [_react.default.createElement("meta", { 43 | key: "environment", 44 | name: "note", 45 | content: "environment=development" 46 | })]; 47 | let htmlAttributes = {}; 48 | let bodyAttributes = {}; 49 | let preBodyComponents = []; 50 | let postBodyComponents = []; 51 | let bodyProps = {}; 52 | let htmlStr; 53 | 54 | const setHeadComponents = components => { 55 | headComponents = headComponents.concat(components); 56 | }; 57 | 58 | const setHtmlAttributes = attributes => { 59 | htmlAttributes = (0, _lodash.merge)(htmlAttributes, attributes); 60 | }; 61 | 62 | const setBodyAttributes = attributes => { 63 | bodyAttributes = (0, _lodash.merge)(bodyAttributes, attributes); 64 | }; 65 | 66 | const setPreBodyComponents = components => { 67 | preBodyComponents = preBodyComponents.concat(components); 68 | }; 69 | 70 | const setPostBodyComponents = components => { 71 | postBodyComponents = postBodyComponents.concat(components); 72 | }; 73 | 74 | const setBodyProps = props => { 75 | bodyProps = (0, _lodash.merge)({}, bodyProps, props); 76 | }; 77 | 78 | const getHeadComponents = () => headComponents; 79 | 80 | const replaceHeadComponents = components => { 81 | headComponents = components; 82 | }; 83 | 84 | const getPreBodyComponents = () => preBodyComponents; 85 | 86 | const replacePreBodyComponents = components => { 87 | preBodyComponents = components; 88 | }; 89 | 90 | const getPostBodyComponents = () => postBodyComponents; 91 | 92 | const replacePostBodyComponents = components => { 93 | postBodyComponents = components; 94 | }; 95 | 96 | (0, _apiRunnerSsr.default)(`onRenderBody`, { 97 | setHeadComponents, 98 | setHtmlAttributes, 99 | setBodyAttributes, 100 | setPreBodyComponents, 101 | setPostBodyComponents, 102 | setBodyProps, 103 | pathname: pagePath 104 | }); 105 | (0, _apiRunnerSsr.default)(`onPreRenderHTML`, { 106 | getHeadComponents, 107 | replaceHeadComponents, 108 | getPreBodyComponents, 109 | replacePreBodyComponents, 110 | getPostBodyComponents, 111 | replacePostBodyComponents, 112 | pathname: pagePath 113 | }); 114 | 115 | const htmlElement = _react.default.createElement(Html, Object.assign({}, bodyProps, { 116 | body: ``, 117 | headComponents: headComponents.concat([_react.default.createElement("script", { 118 | key: `io`, 119 | src: "/socket.io/socket.io.js" 120 | })]), 121 | htmlAttributes, 122 | bodyAttributes, 123 | preBodyComponents, 124 | postBodyComponents: postBodyComponents.concat([_react.default.createElement("script", { 125 | key: `commons`, 126 | src: "/commons.js" 127 | })]) 128 | })); 129 | 130 | htmlStr = (0, _server.renderToStaticMarkup)(htmlElement); 131 | htmlStr = `${htmlStr}`; 132 | callback(null, htmlStr); 133 | }; 134 | 135 | exports.default = _default; -------------------------------------------------------------------------------- /.docz/.cache/commonjs/socketIo.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = socketIo; 7 | exports.getPageData = getPageData; 8 | exports.registerPath = registerPath; 9 | exports.unregisterPath = unregisterPath; 10 | exports.getIsInitialized = exports.getPageQueryData = exports.getStaticQueryData = void 0; 11 | 12 | var _errorOverlayHandler = require("./error-overlay-handler"); 13 | 14 | var _normalizePagePath = _interopRequireDefault(require("./normalize-page-path")); 15 | 16 | let socket = null; 17 | let staticQueryData = {}; 18 | let pageQueryData = {}; 19 | let isInitialized = false; 20 | 21 | const getStaticQueryData = () => staticQueryData; 22 | 23 | exports.getStaticQueryData = getStaticQueryData; 24 | 25 | const getPageQueryData = () => pageQueryData; 26 | 27 | exports.getPageQueryData = getPageQueryData; 28 | 29 | const getIsInitialized = () => isInitialized; 30 | 31 | exports.getIsInitialized = getIsInitialized; 32 | 33 | function socketIo() { 34 | if (process.env.NODE_ENV !== `production`) { 35 | if (!socket) { 36 | // Try to initialize web socket if we didn't do it already 37 | try { 38 | // eslint-disable-next-line no-undef 39 | socket = io(); 40 | 41 | const didDataChange = (msg, queryData) => { 42 | const id = msg.type === `staticQueryResult` ? msg.payload.id : (0, _normalizePagePath.default)(msg.payload.id); 43 | return !(id in queryData) || JSON.stringify(msg.payload.result) !== JSON.stringify(queryData[id]); 44 | }; 45 | 46 | socket.on(`message`, msg => { 47 | if (msg.type === `staticQueryResult`) { 48 | if (didDataChange(msg, staticQueryData)) { 49 | staticQueryData = Object.assign({}, staticQueryData, { 50 | [msg.payload.id]: msg.payload.result 51 | }); 52 | } 53 | } else if (msg.type === `pageQueryResult`) { 54 | if (didDataChange(msg, pageQueryData)) { 55 | pageQueryData = Object.assign({}, pageQueryData, { 56 | [(0, _normalizePagePath.default)(msg.payload.id)]: msg.payload.result 57 | }); 58 | } 59 | } else if (msg.type === `overlayError`) { 60 | if (msg.payload.message) { 61 | (0, _errorOverlayHandler.reportError)(msg.payload.id, msg.payload.message); 62 | } else { 63 | (0, _errorOverlayHandler.clearError)(msg.payload.id); 64 | } 65 | } 66 | 67 | if (msg.type && msg.payload) { 68 | ___emitter.emit(msg.type, msg.payload); 69 | } 70 | }); 71 | } catch (err) { 72 | console.error(`Could not connect to socket.io on dev server.`); 73 | } 74 | } 75 | 76 | return socket; 77 | } else { 78 | return null; 79 | } 80 | } 81 | 82 | const inFlightGetPageDataPromiseCache = {}; 83 | 84 | function getPageData(pathname) { 85 | pathname = (0, _normalizePagePath.default)(pathname); 86 | 87 | if (inFlightGetPageDataPromiseCache[pathname]) { 88 | return inFlightGetPageDataPromiseCache[pathname]; 89 | } else { 90 | inFlightGetPageDataPromiseCache[pathname] = new Promise(resolve => { 91 | if (pageQueryData[pathname]) { 92 | delete inFlightGetPageDataPromiseCache[pathname]; 93 | resolve(pageQueryData[pathname]); 94 | } else { 95 | const onPageDataCallback = msg => { 96 | if (msg.type === `pageQueryResult` && (0, _normalizePagePath.default)(msg.payload.id) === pathname) { 97 | socket.off(`message`, onPageDataCallback); 98 | delete inFlightGetPageDataPromiseCache[pathname]; 99 | resolve(pageQueryData[pathname]); 100 | } 101 | }; 102 | 103 | socket.on(`message`, onPageDataCallback); 104 | socket.emit(`getDataForPath`, pathname); 105 | } 106 | }); 107 | } 108 | 109 | return inFlightGetPageDataPromiseCache[pathname]; 110 | } // Tell websocket-manager.js the new path we're on. 111 | // This will help the backend prioritize queries for this 112 | // path. 113 | 114 | 115 | function registerPath(path) { 116 | socket.emit(`registerPath`, path); 117 | } // Unregister the former path 118 | 119 | 120 | function unregisterPath(path) { 121 | socket.emit(`unregisterPath`, path); 122 | } -------------------------------------------------------------------------------- /.docz/public/component---docs-pages-demo-mdx-da562a47741883850a15.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["webpack:///../docs/pages/demo.mdx"],"names":["_frontmatter","layoutProps","MDXLayout","DefaultLayout","MDXContent","components","props","mdxType","parentName","isMDXComponent"],"mappings":"whBASO,IAAMA,EAAe,Q,qMAE5B,IAKMC,EAAc,CAClBD,gBAEIE,EAAYC,IACH,SAASC,EAAT,GAGZ,IAFDC,EAEC,EAFDA,WACGC,E,oIACF,mBACD,OAAO,YAACJ,EAAD,KAAeD,EAAiBK,EAAhC,CAAuCD,WAAYA,EAAYE,QAAQ,cAI5E,iBAAQ,CACN,GAAM,mBADR,mBAGA,qFACA,0CAAyB,0BAAYC,WAAW,KAAvB,kBAAzB,qBAAyG,0BAAYA,WAAW,KAAvB,kBAAzG,oFACA,uBAAK,sBAAMA,WAAW,OAAU,CAC5B,UAAa,iBADZ,sCAIL,YAAC,IAAD,CAAsBD,QAAQ,yBAC9B,uBAAK,sBAAMC,WAAW,OAAU,CAC5B,UAAa,iBADZ,szBA+BL,iBAAQ,CACN,GAAM,mBADR,mBAGA,oFACA,YAAC,IAAD,CAAiBD,QAAQ,oBACzB,uBAAK,sBAAMC,WAAW,OAAU,CAC5B,UAAa,iBADZ,y0B,4LAqCTJ,EAAWK,gBAAiB","file":"component---docs-pages-demo-mdx-da562a47741883850a15.js","sourcesContent":["import React from 'react'\n /* @jsx mdx */\nimport { mdx } from '@mdx-js/react';\n/* @jsx mdx */\n\nimport DefaultLayout from \"/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/gatsby-theme-docz/src/base/Layout.js\";\nimport { Playground } from 'docz';\nimport GlobalComponent from '../Components/GlobalEventComponent.js';\nimport TargetEventComponent from '../Components/TargetEventComponent.js';\nexport const _frontmatter = {};\n\nconst makeShortcode = name => function MDXDefaultShortcode(props) {\n console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n return
;\n};\n\nconst layoutProps = {\n _frontmatter\n};\nconst MDXLayout = DefaultLayout;\nexport default function MDXContent({\n components,\n ...props\n}) {\n return \n\n\n\n

{`Target Listener`}

\n

{`Listen only for the key-press event for a particular target.`}

\n

{`It is provided by `}{`getTargetProps`}{` props getter. If `}{`getTargetProps`}{` props getter is not provided, then it will listen for key-press event globally.`}

\n
{`\n`}
\n \n
{`import React from 'react';\nimport useKey from 'use-key-capture';\nimport './styles.css';\n\nconst displayKeys = ['Q', 'W', 'E', 'R', 'T', 'Y', 'Backspace'];\n\nconst TargetEventComponent = () => {\n  const { keyData, getTargetProps } = useKey();\n\n  const getIsActive = key => (keyData.key === key ? 'active' : '');\n\n  return (\n    
\n
\n Type QWERTY in the input element below. If the focus is outside the\n target, we won't see any change.\n
\n \n
\n {displayKeys.map(key => {\n return
{key}
;\n })}\n
\n
\n );\n};\n\nexport default TargetEventComponent;\n`}
\n

{`Global Listener`}

\n

{`If no target is specified, it will listen for global event.`}

\n \n
{`import React from 'react';\nimport useKey from 'use-key-capture';\nimport './styles.css';\n\nconst displayKeys = ['Enter', 'Escape', 'Tab', 'ArrowUp'];\n\nconst GlobalComponent = () => {\n  const { keyData } = useKey();\n\n  const getIsActive = key => (keyData.key === key ? 'active' : '');\n\n  const getCombinedActiveClass = () =>\n    keyData.key === 'A' && keyData.isWithShift ? 'active' : '';\n\n  return (\n    <>\n      
\n Press below mentioned keys to see the hook in action\n
\n
\n {displayKeys.map(key => {\n return
{key}
;\n })}\n
Shift + A
\n
\n \n );\n};\n\nexport default GlobalComponent;\n`}
\n\n
;\n}\n;\nMDXContent.isMDXComponent = true;\n "],"sourceRoot":""} -------------------------------------------------------------------------------- /.docz/.cache/commonjs/query-result-store.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.StaticQueryStore = exports.PageQueryStore = void 0; 7 | 8 | var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); 9 | 10 | var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); 11 | 12 | var _react = _interopRequireDefault(require("react")); 13 | 14 | var _gatsby = require("gatsby"); 15 | 16 | var _socketIo = require("./socketIo"); 17 | 18 | var _pageRenderer = _interopRequireDefault(require("./page-renderer")); 19 | 20 | var _normalizePagePath = _interopRequireDefault(require("./normalize-page-path")); 21 | 22 | if (process.env.NODE_ENV === `production`) { 23 | throw new Error(`It appears like Gatsby is misconfigured. JSONStore is Gatsby internal ` + `development-only component and should never be used in production.\n\n` + `Unless your site has a complex or custom webpack/Gatsby ` + `configuration this is likely a bug in Gatsby. ` + `Please report this at https://github.com/gatsbyjs/gatsby/issues ` + `with steps to reproduce this error.`); 24 | } 25 | 26 | const getPathFromProps = props => props.pageResources && props.pageResources.page ? (0, _normalizePagePath.default)(props.pageResources.page.path) : undefined; 27 | 28 | class PageQueryStore extends _react.default.Component { 29 | constructor(props) { 30 | super(props); 31 | (0, _defineProperty2.default)(this, "handleMittEvent", () => { 32 | this.setState({ 33 | pageQueryData: (0, _socketIo.getPageQueryData)() 34 | }); 35 | }); 36 | this.state = { 37 | pageQueryData: (0, _socketIo.getPageQueryData)(), 38 | path: null 39 | }; 40 | } 41 | 42 | componentDidMount() { 43 | (0, _socketIo.registerPath)(getPathFromProps(this.props)); 44 | 45 | ___emitter.on(`*`, this.handleMittEvent); 46 | } 47 | 48 | componentWillUnmount() { 49 | (0, _socketIo.unregisterPath)(this.state.path); 50 | 51 | ___emitter.off(`*`, this.handleMittEvent); 52 | } 53 | 54 | static getDerivedStateFromProps(props, state) { 55 | const newPath = getPathFromProps(props); 56 | 57 | if (newPath !== state.path) { 58 | (0, _socketIo.unregisterPath)(state.path); 59 | (0, _socketIo.registerPath)(newPath); 60 | return { 61 | path: newPath 62 | }; 63 | } 64 | 65 | return null; 66 | } 67 | 68 | shouldComponentUpdate(nextProps, nextState) { 69 | // We want to update this component when: 70 | // - location changed 71 | // - page data for path changed 72 | return this.props.location !== nextProps.location || this.state.path !== nextState.path || this.state.pageQueryData[(0, _normalizePagePath.default)(nextState.path)] !== nextState.pageQueryData[(0, _normalizePagePath.default)(nextState.path)]; 73 | } 74 | 75 | render() { 76 | const data = this.state.pageQueryData[getPathFromProps(this.props)]; // eslint-disable-next-line 77 | 78 | if (!data) { 79 | return _react.default.createElement("div", null); 80 | } 81 | 82 | return _react.default.createElement(_pageRenderer.default, (0, _extends2.default)({}, this.props, data)); 83 | } 84 | 85 | } 86 | 87 | exports.PageQueryStore = PageQueryStore; 88 | 89 | class StaticQueryStore extends _react.default.Component { 90 | constructor(props) { 91 | super(props); 92 | (0, _defineProperty2.default)(this, "handleMittEvent", () => { 93 | this.setState({ 94 | staticQueryData: (0, _socketIo.getStaticQueryData)() 95 | }); 96 | }); 97 | this.state = { 98 | staticQueryData: (0, _socketIo.getStaticQueryData)() 99 | }; 100 | } 101 | 102 | componentDidMount() { 103 | ___emitter.on(`*`, this.handleMittEvent); 104 | } 105 | 106 | componentWillUnmount() { 107 | ___emitter.off(`*`, this.handleMittEvent); 108 | } 109 | 110 | shouldComponentUpdate(nextProps, nextState) { 111 | // We want to update this component when: 112 | // - static query results changed 113 | return this.state.staticQueryData !== nextState.staticQueryData; 114 | } 115 | 116 | render() { 117 | return _react.default.createElement(_gatsby.StaticQueryContext.Provider, { 118 | value: this.state.staticQueryData 119 | }, this.props.children); 120 | } 121 | 122 | } 123 | 124 | exports.StaticQueryStore = StaticQueryStore; -------------------------------------------------------------------------------- /.docz/app/db.json: -------------------------------------------------------------------------------- 1 | { 2 | "config": { 3 | "title": "Use Key Capture", 4 | "description": "My awesome app using docz", 5 | "menu": [], 6 | "version": "1.0.0", 7 | "repository": null, 8 | "native": false, 9 | "themeConfig": {}, 10 | "separator": "-", 11 | "ignore": [ 12 | "README.md" 13 | ], 14 | "public": "./public", 15 | "htmlContext": { 16 | "favicon": "/public/public/images/favicon.png" 17 | } 18 | }, 19 | "entries": [ 20 | { 21 | "key": "docs/index.mdx", 22 | "value": { 23 | "name": "Docs", 24 | "route": "/", 25 | "order": 1, 26 | "id": "73498ad0e1e62a714b08085d318f9de1", 27 | "filepath": "docs/index.mdx", 28 | "fullpath": "/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/index.mdx", 29 | "link": "", 30 | "slug": "docs-index", 31 | "menu": "", 32 | "headings": [ 33 | { 34 | "slug": "use-key-capture", 35 | "depth": 1, 36 | "value": "use-key-capture" 37 | }, 38 | { 39 | "slug": "installation", 40 | "depth": 2, 41 | "value": "Installation" 42 | }, 43 | { 44 | "slug": "how-it-is-used", 45 | "depth": 2, 46 | "value": "How it is used" 47 | }, 48 | { 49 | "slug": "properties", 50 | "depth": 2, 51 | "value": "Properties" 52 | }, 53 | { 54 | "slug": "target-prop-getter", 55 | "depth": 2, 56 | "value": "Target Prop getter" 57 | } 58 | ] 59 | } 60 | }, 61 | { 62 | "key": "docs/pages/demo.mdx", 63 | "value": { 64 | "name": "Demo", 65 | "route": "/demo", 66 | "order": 2, 67 | "id": "87411c77fdcfbb7f6278f322040c1731", 68 | "filepath": "docs/pages/demo.mdx", 69 | "fullpath": "/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/demo.mdx", 70 | "link": "", 71 | "slug": "docs-pages-demo", 72 | "menu": "", 73 | "headings": [ 74 | { 75 | "slug": "target-listener", 76 | "depth": 2, 77 | "value": "Target Listener" 78 | }, 79 | { 80 | "slug": "global-listener", 81 | "depth": 2, 82 | "value": "Global Listener" 83 | } 84 | ] 85 | } 86 | }, 87 | { 88 | "key": "docs/pages/props.mdx", 89 | "value": { 90 | "name": "Props", 91 | "route": "/props", 92 | "order": 2, 93 | "id": "b5cb4d959720d31e411c9b125e451a6a", 94 | "filepath": "docs/pages/props.mdx", 95 | "fullpath": "/Users/pranesh.g/Documents/opensource/use-key-capture-2/docs/pages/props.mdx", 96 | "link": "", 97 | "slug": "docs-pages-props", 98 | "menu": "", 99 | "headings": [ 100 | { 101 | "slug": "props", 102 | "depth": 2, 103 | "value": "Props" 104 | }, 105 | { 106 | "slug": "keydata", 107 | "depth": 3, 108 | "value": "keyData" 109 | }, 110 | { 111 | "slug": "gettargetprops", 112 | "depth": 3, 113 | "value": "getTargetProps" 114 | }, 115 | { 116 | "slug": "resetkeydata", 117 | "depth": 3, 118 | "value": "resetKeyData" 119 | } 120 | ] 121 | } 122 | } 123 | ], 124 | "props": [ 125 | { 126 | "key": "docs/Components/GlobalEventComponent.js", 127 | "value": [ 128 | { 129 | "description": "", 130 | "displayName": "GlobalComponent", 131 | "methods": [], 132 | "actualName": "GlobalComponent" 133 | } 134 | ] 135 | }, 136 | { 137 | "key": "docs/Components/TargetEventComponent.js", 138 | "value": [ 139 | { 140 | "description": "", 141 | "displayName": "TargetEventComponent", 142 | "methods": [], 143 | "actualName": "TargetEventComponent" 144 | } 145 | ] 146 | }, 147 | { 148 | "key": "src/__tests__/utils/TestComponent.js", 149 | "value": [ 150 | { 151 | "description": "", 152 | "displayName": "TestComponent", 153 | "methods": [], 154 | "actualName": "TestComponent" 155 | } 156 | ] 157 | } 158 | ] 159 | } 160 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/root.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | exports.__esModule = true; 6 | exports.default = void 0; 7 | 8 | var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); 9 | 10 | var _react = _interopRequireDefault(require("react")); 11 | 12 | var _router = require("@reach/router"); 13 | 14 | var _gatsbyReactRouterScroll = require("gatsby-react-router-scroll"); 15 | 16 | var _navigation = require("./navigation"); 17 | 18 | var _apiRunnerBrowser = require("./api-runner-browser"); 19 | 20 | var _loader = _interopRequireDefault(require("./loader")); 21 | 22 | var _queryResultStore = require("./query-result-store"); 23 | 24 | var _ensureResources = _interopRequireDefault(require("./ensure-resources")); 25 | 26 | var _errorOverlayHandler = require("./error-overlay-handler"); 27 | 28 | if (window.__webpack_hot_middleware_reporter__ !== undefined) { 29 | const overlayErrorID = `webpack`; // Report build errors 30 | 31 | window.__webpack_hot_middleware_reporter__.useCustomOverlay({ 32 | showProblems(type, obj) { 33 | if (type !== `errors`) { 34 | (0, _errorOverlayHandler.clearError)(overlayErrorID); 35 | return; 36 | } 37 | 38 | (0, _errorOverlayHandler.reportError)(overlayErrorID, obj[0]); 39 | }, 40 | 41 | clear() { 42 | (0, _errorOverlayHandler.clearError)(overlayErrorID); 43 | } 44 | 45 | }); 46 | } 47 | 48 | (0, _navigation.init)(); // In gatsby v2 if Router is used in page using matchPaths 49 | // paths need to contain full path. 50 | // For example: 51 | // - page have `/app/*` matchPath 52 | // - inside template user needs to use `/app/xyz` as path 53 | // Resetting `basepath`/`baseuri` keeps current behaviour 54 | // to not introduce breaking change. 55 | // Remove this in v3 56 | 57 | const RouteHandler = props => _react.default.createElement(_router.BaseContext.Provider, { 58 | value: { 59 | baseuri: `/`, 60 | basepath: `/` 61 | } 62 | }, _react.default.createElement(_queryResultStore.PageQueryStore, props)); 63 | 64 | class LocationHandler extends _react.default.Component { 65 | render() { 66 | const { 67 | location 68 | } = this.props; 69 | 70 | if (!_loader.default.isPageNotFound(location.pathname)) { 71 | return _react.default.createElement(_ensureResources.default, { 72 | location: location 73 | }, locationAndPageResources => _react.default.createElement(_navigation.RouteUpdates, { 74 | location: location 75 | }, _react.default.createElement(_gatsbyReactRouterScroll.ScrollContext, { 76 | location: location, 77 | shouldUpdateScroll: _navigation.shouldUpdateScroll 78 | }, _react.default.createElement(_router.Router, { 79 | basepath: __BASE_PATH__, 80 | location: location, 81 | id: "gatsby-focus-wrapper" 82 | }, _react.default.createElement(RouteHandler, (0, _extends2.default)({ 83 | path: encodeURI(locationAndPageResources.pageResources.page.matchPath || locationAndPageResources.pageResources.page.path) 84 | }, this.props, locationAndPageResources)))))); 85 | } 86 | 87 | const dev404PageResources = _loader.default.loadPageSync(`/dev-404-page`); 88 | 89 | const real404PageResources = _loader.default.loadPageSync(`/404.html`); 90 | 91 | let custom404; 92 | 93 | if (real404PageResources) { 94 | custom404 = _react.default.createElement(_queryResultStore.PageQueryStore, (0, _extends2.default)({}, this.props, { 95 | pageResources: real404PageResources 96 | })); 97 | } 98 | 99 | return _react.default.createElement(_navigation.RouteUpdates, { 100 | location: location 101 | }, _react.default.createElement(_router.Router, { 102 | basepath: __BASE_PATH__, 103 | location: location, 104 | id: "gatsby-focus-wrapper" 105 | }, _react.default.createElement(RouteHandler, { 106 | path: location.pathname, 107 | location: location, 108 | pageResources: dev404PageResources, 109 | custom404: custom404 110 | }))); 111 | } 112 | 113 | } 114 | 115 | const Root = () => _react.default.createElement(_router.Location, null, locationContext => _react.default.createElement(LocationHandler, locationContext)); // Let site, plugins wrap the site e.g. for Redux. 116 | 117 | 118 | const WrappedRoot = (0, _apiRunnerBrowser.apiRunner)(`wrapRootElement`, { 119 | element: _react.default.createElement(Root, null) 120 | }, _react.default.createElement(Root, null), ({ 121 | result, 122 | plugin 123 | }) => { 124 | return { 125 | element: result 126 | }; 127 | }).pop(); 128 | 129 | var _default = () => _react.default.createElement(_queryResultStore.StaticQueryStore, null, WrappedRoot); 130 | 131 | exports.default = _default; -------------------------------------------------------------------------------- /src/useKeyCapture/useKeyCaptureUtils.js: -------------------------------------------------------------------------------- 1 | import { useCallback } from 'react'; 2 | 3 | const initialState = { 4 | // Pressed key 5 | key: null, 6 | 7 | // Command Keys 8 | isEnter: false, 9 | 10 | isBackspace: false, 11 | 12 | isEscape: false, 13 | isCapsLock: false, 14 | isTab: false, 15 | isSpace: false, 16 | 17 | // Function keys 18 | isFunctionKey: false, 19 | 20 | // Arrow keys 21 | isArrow: false, 22 | isArrowRight: false, 23 | isArrowLeft: false, 24 | isArrowUp: false, 25 | isArrowDown: false, 26 | 27 | // Modifier keys 28 | isWithShift: false, 29 | isWithCtrl: false, 30 | isWithMeta: false, 31 | isWithAlt: false, 32 | 33 | // Character varients 34 | isCaps: false, 35 | isSmall: false, 36 | isNumber: false, 37 | 38 | // For special character 39 | isSpecialCharacter: false 40 | }; 41 | 42 | const useKeyActionTypes = { 43 | ENTER_KEY: 'ENTER_KEY', 44 | ESCAPE_KEY: 'ESCAPE_KEY', 45 | RESET_CAPTURES: 'RESET_CAPTURES', 46 | CAPS_ALPHABET: 'CAPS', 47 | SMALL_ALPHABET: 'SMALL', 48 | NUMBER: 'NUMBER', 49 | SPACE: 'SPACE', 50 | ARROWS: 'ARROWS', 51 | SPECIAL: 'SPECIAL', 52 | TAB: 'TAB', 53 | CAPSLOCK: 'CAPSLOCK', 54 | SHIFT: 'SHIFT', 55 | BACKSPACE: 'BACKSPACE' 56 | }; 57 | 58 | const modifierKeys = { 59 | ctrlKey: 'Ctrl', 60 | shiftKey: 'Shift', 61 | altKey: 'Alt', 62 | metaKey: 'Meta' 63 | }; 64 | 65 | const keyCodeMapper = { 66 | Enter: useKeyActionTypes.ENTER_KEY, 67 | Escape: useKeyActionTypes.ESCAPE_KEY, 68 | Tab: useKeyActionTypes.TAB, 69 | CapsLock: useKeyActionTypes.CAPSLOCK, 70 | Shift: useKeyActionTypes.SHIFT, 71 | Backspace: useKeyActionTypes.BACKSPACE, 72 | // eslint-disable-next-line no-useless-computed-key 73 | [' ']: useKeyActionTypes.SPACE 74 | }; 75 | 76 | const getArrowKeysPayload = key => { 77 | return { 78 | [`is${key}`]: true 79 | }; 80 | }; 81 | 82 | const isCapitalLetterPressed = key => /^[A-Z]$/.test(key); 83 | const isSmallLetterPressed = key => /^[a-z]$/.test(key); 84 | const isNumberPressed = key => /^[0-9]/.test(key); 85 | const isSpecialCharacter = key => 86 | /^[!@#$%^&*()_+<>?:"{}[\]';.,|/\-\\=_+~`]/.test(key); 87 | 88 | const isSpecialCharacterPressed = key => { 89 | return ( 90 | !isCapitalLetterPressed(key) && 91 | !isSmallLetterPressed(key) && 92 | !isNumberPressed(key) && 93 | !keyCodeMapper[key] && 94 | isSpecialCharacter(key) 95 | ); 96 | }; 97 | 98 | const getModifierPayload = eventDetails => { 99 | let modifierPayloadObj = {}; 100 | const modifierObjKeys = Object.keys(modifierKeys); 101 | 102 | for (let key of modifierObjKeys) { 103 | if (eventDetails[key]) { 104 | modifierPayloadObj[`isWith${modifierKeys[key]}`] = true; 105 | } 106 | } 107 | 108 | return modifierPayloadObj; 109 | }; 110 | 111 | /** 112 | * Returns the action type for the key pressed 113 | * @param {KeyboardEvent} eventDetails keyboard event object 114 | * @return {String} action type 115 | */ 116 | const getAction = eventDetails => { 117 | if (!eventDetails) { 118 | throw new Error('Event called with no details'); 119 | } 120 | 121 | const { key } = eventDetails; 122 | 123 | if (key.includes('Arrow')) { 124 | return { 125 | type: useKeyActionTypes.ARROWS, 126 | payload: { 127 | ...getArrowKeysPayload(key), 128 | ...getModifierPayload(eventDetails), 129 | key 130 | } 131 | }; 132 | } 133 | 134 | let type; 135 | 136 | if (keyCodeMapper[key]) type = keyCodeMapper[key]; 137 | 138 | if (isCapitalLetterPressed(key)) { 139 | type = useKeyActionTypes.CAPS_ALPHABET; 140 | } 141 | 142 | if (isSmallLetterPressed(key)) { 143 | type = useKeyActionTypes.SMALL_ALPHABET; 144 | } 145 | 146 | if (isNumberPressed(key)) { 147 | type = useKeyActionTypes.NUMBER; 148 | } 149 | 150 | if (!type && isSpecialCharacterPressed(key)) { 151 | type = useKeyActionTypes.SPECIAL; 152 | } 153 | 154 | if (!type) { 155 | type = 'SOME_OTHER_KEY'; 156 | } 157 | 158 | return { 159 | type, 160 | payload: { ...getModifierPayload(eventDetails), key } 161 | }; 162 | }; 163 | 164 | const targetItemPropsDefaultValue = { 165 | type: 'text' 166 | }; 167 | 168 | function handleRefAssignment(...refs) { 169 | return node => { 170 | refs.forEach(ref => { 171 | if (typeof ref === 'function') { 172 | ref(node); 173 | } else if (ref) { 174 | ref.current = node; 175 | } 176 | }); 177 | }; 178 | } 179 | 180 | const useEnhancedReducer = reducer => 181 | useCallback( 182 | (state, action) => { 183 | return reducer(state, action); 184 | }, 185 | [reducer] 186 | ); 187 | 188 | export { 189 | getAction, 190 | initialState, 191 | targetItemPropsDefaultValue, 192 | useKeyActionTypes, 193 | useEnhancedReducer, 194 | handleRefAssignment 195 | }; 196 | -------------------------------------------------------------------------------- /.docz/public/component---docs-index-mdx-3927419ecd2651d24dd3.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"sources":["webpack:///../docs/index.mdx"],"names":["_frontmatter","layoutProps","MDXLayout","DefaultLayout","MDXContent","components","props","mdxType","parentName","isMDXComponent"],"mappings":"kfAMO,IAAMA,EAAe,Q,gMAE5B,IAKMC,EAAc,CAClBD,gBAEIE,EAAYC,IACH,SAASC,EAAT,GAGZ,IAFDC,EAEC,EAFDA,WACGC,E,oIACF,mBACD,OAAO,YAACJ,EAAD,KAAeD,EAAiBK,EAAhC,CAAuCD,WAAYA,EAAYE,QAAQ,cAG5E,iBAAQ,CACN,GAAM,mBADR,mBAGA,8JAA6I,sBAAQC,WAAW,KAAnB,UAA7I,0FAAkR,sBAAQA,WAAW,KAAnB,YAAlR,KACA,iBAAQ,CACN,GAAM,gBADR,gBAGA,qBAAG,sBAAQA,WAAW,KAAnB,QACH,uBAAK,sBAAMA,WAAW,OAAU,CAC5B,UAAa,kBADZ,4BAIL,qBAAG,sBAAQA,WAAW,KAAnB,SACH,uBAAK,sBAAMA,WAAW,OAAU,CAC5B,UAAa,kBADZ,+BAIL,iBAAQ,CACN,GAAM,kBADR,kBAGA,uBAAK,sBAAMA,WAAW,OAAU,CAC5B,UAAa,iBADZ,8GAML,iBAAQ,CACN,GAAM,cADR,cAGA,yBACE,qBAAOA,WAAW,SAChB,kBAAIA,WAAW,SACb,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,iBAGA,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,iBAKJ,qBAAOA,WAAW,SAChB,kBAAIA,WAAW,SACb,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,WAGA,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,8BAIF,kBAAIA,WAAW,SACb,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,gBAGA,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,qCAMN,iBAAQ,CACN,GAAM,sBADR,sBAGA,yBACE,qBAAOA,WAAW,SAChB,kBAAIA,WAAW,SACb,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,iBAGA,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,iBAKJ,qBAAOA,WAAW,SAChB,kBAAIA,WAAW,SACb,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,kBAGA,oBAAIA,WAAW,MAAS,CACtB,MAAS,OADX,kD,uLAUVJ,EAAWK,gBAAiB","file":"component---docs-index-mdx-3927419ecd2651d24dd3.js","sourcesContent":["import React from 'react'\n /* @jsx mdx */\nimport { mdx } from '@mdx-js/react';\n/* @jsx mdx */\n\nimport DefaultLayout from \"/Users/pranesh.g/Documents/opensource/use-key-capture-2/node_modules/gatsby-theme-docz/src/base/Layout.js\";\nexport const _frontmatter = {};\n\nconst makeShortcode = name => function MDXDefaultShortcode(props) {\n console.warn(\"Component \" + name + \" was not imported, exported, or provided by MDXProvider as global scope\");\n return
;\n};\n\nconst layoutProps = {\n _frontmatter\n};\nconst MDXLayout = DefaultLayout;\nexport default function MDXContent({\n components,\n ...props\n}) {\n return \n\n\n

{`use-key-capture`}

\n

{`use-key-capture is a custom hook which will let us not to worry about the key-press event. Just plugin in use-key-capture hook to the `}{`target`}{` we want to listen for key press event or by default it can listen for key-press event `}{`globally`}{`.`}

\n

{`Installation`}

\n

{`npm`}

\n
{`npm i use-key-capture\n`}
\n

{`yarn`}

\n
{`yarn add use-key-capture\n`}
\n

{`How it is used`}

\n
{`import useKey from 'use-key-capture';\n...\nconst { keyData, resetKeyData, getTargetProps } = useKey();\n`}
\n

{`Properties`}

\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
{`Property name`}{`Description`}
{`keyData`}{`gives pressed key details`}
{`resetKeyData`}{`resets the pressed key details`}
\n

{`Target Prop getter`}

\n \n \n \n \n \n \n \n \n \n \n \n \n \n
{`Property name`}{`Description`}
{`getTargetProps`}{`gives the required props to target element`}
\n\n
;\n}\n;\nMDXContent.isMDXComponent = true;\n "],"sourceRoot":""} -------------------------------------------------------------------------------- /.docz/public/component---docs-pages-props-mdx-592d10813f233ead71ef.js: -------------------------------------------------------------------------------- 1 | (window.webpackJsonp=window.webpackJsonp||[]).push([[4],{"5cM7":function(t,e,a){"use strict";a.r(e),a.d(e,"_frontmatter",(function(){return l})),a.d(e,"default",(function(){return i}));a("5hJT"),a("W1QL"),a("K/PF"),a("t91x"),a("75LO"),a("PJhk"),a("mXGw");var n=a("/FXl"),r=a("TjRS");a("aD51");function b(){return(b=Object.assign||function(t){for(var e=1;e=0||(r[a]=t[a]);return r}(t,["components"]);return Object(n.b)(o,b({},p,a,{components:e,mdxType:"MDXLayout"}),Object(n.b)("h2",{id:"props"},"Props"),Object(n.b)("h3",{id:"keydata"},"keyData"),Object(n.b)("p",null,"It will be the most used props from ",Object(n.b)("inlineCode",{parentName:"p"},"useKeyCapture"),". It gives the key/key varient/key combinations pressed."),Object(n.b)("table",null,Object(n.b)("thead",{parentName:"table"},Object(n.b)("tr",{parentName:"thead"},Object(n.b)("th",b({parentName:"tr"},{align:null}),"Property"),Object(n.b)("th",b({parentName:"tr"},{align:null}),"Type"))),Object(n.b)("tbody",{parentName:"table"},Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"key"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"String")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isEnter"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isBackspace"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isEscape"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isCapsLock"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isTab"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isSpace"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isArrow"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isArrowRight"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isArrowLeft"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isArrowUp"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isArrowDown"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isWithShift"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isWithCtrl"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isWithMeta"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isWithAlt"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isCaps"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isSmall"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isNumber"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")),Object(n.b)("tr",{parentName:"tbody"},Object(n.b)("td",b({parentName:"tr"},{align:null}),"isSpecialCharacter"),Object(n.b)("td",b({parentName:"tr"},{align:null}),"Boolean")))),Object(n.b)("h3",{id:"gettargetprops"},"getTargetProps"),Object(n.b)("p",null,Object(n.b)("inlineCode",{parentName:"p"},"type: function({})")),Object(n.b)("p",null,"A prop getter to be given if a target (input, textarea) have to be listened for key-press."),Object(n.b)("h3",{id:"resetkeydata"},"resetKeyData"),Object(n.b)("p",null,Object(n.b)("inlineCode",{parentName:"p"},"type: function({})")),Object(n.b)("p",null,"It will reset all the values in ",Object(n.b)("inlineCode",{parentName:"p"},"keyData")," props to the initial values."))}i&&i===Object(i)&&Object.isExtensible(i)&&!i.hasOwnProperty("__filemeta")&&Object.defineProperty(i,"__filemeta",{configurable:!0,value:{name:"MDXContent",filename:"docs/pages/props.mdx"}}),i.isMDXComponent=!0}}]); 2 | //# sourceMappingURL=component---docs-pages-props-mdx-592d10813f233ead71ef.js.map -------------------------------------------------------------------------------- /.docz/.cache/production-app.js: -------------------------------------------------------------------------------- 1 | import { apiRunner, apiRunnerAsync } from "./api-runner-browser" 2 | import React from "react" 3 | import ReactDOM from "react-dom" 4 | import { Router, navigate, Location, BaseContext } from "@reach/router" 5 | import { ScrollContext } from "gatsby-react-router-scroll" 6 | import domReady from "@mikaelkristiansson/domready" 7 | import { 8 | shouldUpdateScroll, 9 | init as navigationInit, 10 | RouteUpdates, 11 | } from "./navigation" 12 | import emitter from "./emitter" 13 | import PageRenderer from "./page-renderer" 14 | import asyncRequires from "./async-requires" 15 | import { setLoader, ProdLoader, publicLoader } from "./loader" 16 | import EnsureResources from "./ensure-resources" 17 | import stripPrefix from "./strip-prefix" 18 | 19 | // Generated during bootstrap 20 | import matchPaths from "./match-paths.json" 21 | 22 | const loader = new ProdLoader(asyncRequires, matchPaths) 23 | setLoader(loader) 24 | loader.setApiRunner(apiRunner) 25 | 26 | window.asyncRequires = asyncRequires 27 | window.___emitter = emitter 28 | window.___loader = publicLoader 29 | 30 | navigationInit() 31 | 32 | apiRunnerAsync(`onClientEntry`).then(() => { 33 | // Let plugins register a service worker. The plugin just needs 34 | // to return true. 35 | if (apiRunner(`registerServiceWorker`).length > 0) { 36 | require(`./register-service-worker`) 37 | } 38 | 39 | // In gatsby v2 if Router is used in page using matchPaths 40 | // paths need to contain full path. 41 | // For example: 42 | // - page have `/app/*` matchPath 43 | // - inside template user needs to use `/app/xyz` as path 44 | // Resetting `basepath`/`baseuri` keeps current behaviour 45 | // to not introduce breaking change. 46 | // Remove this in v3 47 | const RouteHandler = props => ( 48 | 54 | 55 | 56 | ) 57 | 58 | class LocationHandler extends React.Component { 59 | render() { 60 | const { location } = this.props 61 | return ( 62 | 63 | {({ pageResources, location }) => ( 64 | 65 | 69 | 74 | 88 | 89 | 90 | 91 | )} 92 | 93 | ) 94 | } 95 | } 96 | 97 | const { pagePath, location: browserLoc } = window 98 | 99 | // Explicitly call navigate if the canonical path (window.pagePath) 100 | // is different to the browser path (window.location.pathname). But 101 | // only if NONE of the following conditions hold: 102 | // 103 | // - The url matches a client side route (page.matchPath) 104 | // - it's a 404 page 105 | // - it's the offline plugin shell (/offline-plugin-app-shell-fallback/) 106 | if ( 107 | pagePath && 108 | __BASE_PATH__ + pagePath !== browserLoc.pathname && 109 | !( 110 | loader.findMatchPath(stripPrefix(browserLoc.pathname, __BASE_PATH__)) || 111 | pagePath === `/404.html` || 112 | pagePath.match(/^\/404\/?$/) || 113 | pagePath.match(/^\/offline-plugin-app-shell-fallback\/?$/) 114 | ) 115 | ) { 116 | navigate(__BASE_PATH__ + pagePath + browserLoc.search + browserLoc.hash, { 117 | replace: true, 118 | }) 119 | } 120 | 121 | publicLoader.loadPage(browserLoc.pathname).then(page => { 122 | if (!page || page.status === `error`) { 123 | throw new Error( 124 | `page resources for ${browserLoc.pathname} not found. Not rendering React` 125 | ) 126 | } 127 | 128 | window.___webpackCompilationHash = page.page.webpackCompilationHash 129 | 130 | const Root = () => ( 131 | 132 | {locationContext => } 133 | 134 | ) 135 | 136 | const WrappedRoot = apiRunner( 137 | `wrapRootElement`, 138 | { element: }, 139 | , 140 | ({ result }) => { 141 | return { element: result } 142 | } 143 | ).pop() 144 | 145 | const NewRoot = () => WrappedRoot 146 | 147 | const renderer = apiRunner( 148 | `replaceHydrateFunction`, 149 | undefined, 150 | ReactDOM.hydrate 151 | )[0] 152 | 153 | domReady(() => { 154 | renderer( 155 | , 156 | typeof window !== `undefined` 157 | ? document.getElementById(`___gatsby`) 158 | : void 0, 159 | () => { 160 | apiRunner(`onInitialClientRender`) 161 | } 162 | ) 163 | }) 164 | }) 165 | }) 166 | -------------------------------------------------------------------------------- /.docz/.cache/commonjs/production-app.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); 4 | 5 | var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); 6 | 7 | var _apiRunnerBrowser = require("./api-runner-browser"); 8 | 9 | var _react = _interopRequireDefault(require("react")); 10 | 11 | var _reactDom = _interopRequireDefault(require("react-dom")); 12 | 13 | var _router = require("@reach/router"); 14 | 15 | var _gatsbyReactRouterScroll = require("gatsby-react-router-scroll"); 16 | 17 | var _domready = _interopRequireDefault(require("@mikaelkristiansson/domready")); 18 | 19 | var _navigation = require("./navigation"); 20 | 21 | var _emitter = _interopRequireDefault(require("./emitter")); 22 | 23 | var _pageRenderer = _interopRequireDefault(require("./page-renderer")); 24 | 25 | var _asyncRequires = _interopRequireDefault(require("./async-requires")); 26 | 27 | var _loader = require("./loader"); 28 | 29 | var _ensureResources = _interopRequireDefault(require("./ensure-resources")); 30 | 31 | var _stripPrefix = _interopRequireDefault(require("./strip-prefix")); 32 | 33 | var _matchPaths = _interopRequireDefault(require("./match-paths.json")); 34 | 35 | // Generated during bootstrap 36 | const loader = new _loader.ProdLoader(_asyncRequires.default, _matchPaths.default); 37 | (0, _loader.setLoader)(loader); 38 | loader.setApiRunner(_apiRunnerBrowser.apiRunner); 39 | window.asyncRequires = _asyncRequires.default; 40 | window.___emitter = _emitter.default; 41 | window.___loader = _loader.publicLoader; 42 | (0, _navigation.init)(); 43 | (0, _apiRunnerBrowser.apiRunnerAsync)(`onClientEntry`).then(() => { 44 | // Let plugins register a service worker. The plugin just needs 45 | // to return true. 46 | if ((0, _apiRunnerBrowser.apiRunner)(`registerServiceWorker`).length > 0) { 47 | require(`./register-service-worker`); 48 | } // In gatsby v2 if Router is used in page using matchPaths 49 | // paths need to contain full path. 50 | // For example: 51 | // - page have `/app/*` matchPath 52 | // - inside template user needs to use `/app/xyz` as path 53 | // Resetting `basepath`/`baseuri` keeps current behaviour 54 | // to not introduce breaking change. 55 | // Remove this in v3 56 | 57 | 58 | const RouteHandler = props => _react.default.createElement(_router.BaseContext.Provider, { 59 | value: { 60 | baseuri: `/`, 61 | basepath: `/` 62 | } 63 | }, _react.default.createElement(_pageRenderer.default, props)); 64 | 65 | class LocationHandler extends _react.default.Component { 66 | render() { 67 | const { 68 | location 69 | } = this.props; 70 | return _react.default.createElement(_ensureResources.default, { 71 | location: location 72 | }, ({ 73 | pageResources, 74 | location 75 | }) => _react.default.createElement(_navigation.RouteUpdates, { 76 | location: location 77 | }, _react.default.createElement(_gatsbyReactRouterScroll.ScrollContext, { 78 | location: location, 79 | shouldUpdateScroll: _navigation.shouldUpdateScroll 80 | }, _react.default.createElement(_router.Router, { 81 | basepath: __BASE_PATH__, 82 | location: location, 83 | id: "gatsby-focus-wrapper" 84 | }, _react.default.createElement(RouteHandler, (0, _extends2.default)({ 85 | path: pageResources.page.path === `/404.html` ? (0, _stripPrefix.default)(location.pathname, __BASE_PATH__) : encodeURI(pageResources.page.matchPath || pageResources.page.path) 86 | }, this.props, { 87 | location: location, 88 | pageResources: pageResources 89 | }, pageResources.json)))))); 90 | } 91 | 92 | } 93 | 94 | const { 95 | pagePath, 96 | location: browserLoc 97 | } = window; // Explicitly call navigate if the canonical path (window.pagePath) 98 | // is different to the browser path (window.location.pathname). But 99 | // only if NONE of the following conditions hold: 100 | // 101 | // - The url matches a client side route (page.matchPath) 102 | // - it's a 404 page 103 | // - it's the offline plugin shell (/offline-plugin-app-shell-fallback/) 104 | 105 | if (pagePath && __BASE_PATH__ + pagePath !== browserLoc.pathname && !(loader.findMatchPath((0, _stripPrefix.default)(browserLoc.pathname, __BASE_PATH__)) || pagePath === `/404.html` || pagePath.match(/^\/404\/?$/) || pagePath.match(/^\/offline-plugin-app-shell-fallback\/?$/))) { 106 | (0, _router.navigate)(__BASE_PATH__ + pagePath + browserLoc.search + browserLoc.hash, { 107 | replace: true 108 | }); 109 | } 110 | 111 | _loader.publicLoader.loadPage(browserLoc.pathname).then(page => { 112 | if (!page || page.status === `error`) { 113 | throw new Error(`page resources for ${browserLoc.pathname} not found. Not rendering React`); 114 | } 115 | 116 | window.___webpackCompilationHash = page.page.webpackCompilationHash; 117 | 118 | const Root = () => _react.default.createElement(_router.Location, null, locationContext => _react.default.createElement(LocationHandler, locationContext)); 119 | 120 | const WrappedRoot = (0, _apiRunnerBrowser.apiRunner)(`wrapRootElement`, { 121 | element: _react.default.createElement(Root, null) 122 | }, _react.default.createElement(Root, null), ({ 123 | result 124 | }) => { 125 | return { 126 | element: result 127 | }; 128 | }).pop(); 129 | 130 | const NewRoot = () => WrappedRoot; 131 | 132 | const renderer = (0, _apiRunnerBrowser.apiRunner)(`replaceHydrateFunction`, undefined, _reactDom.default.hydrate)[0]; 133 | (0, _domready.default)(() => { 134 | renderer(_react.default.createElement(NewRoot, null), typeof window !== `undefined` ? document.getElementById(`___gatsby`) : void 0, () => { 135 | (0, _apiRunnerBrowser.apiRunner)(`onInitialClientRender`); 136 | }); 137 | }); 138 | }); 139 | }); -------------------------------------------------------------------------------- /.docz/.cache/navigation.js: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import PropTypes from "prop-types" 3 | import loader from "./loader" 4 | import redirects from "./redirects.json" 5 | import { apiRunner } from "./api-runner-browser" 6 | import emitter from "./emitter" 7 | import { navigate as reachNavigate } from "@reach/router" 8 | import { parsePath } from "gatsby-link" 9 | 10 | // Convert to a map for faster lookup in maybeRedirect() 11 | const redirectMap = redirects.reduce((map, redirect) => { 12 | map[redirect.fromPath] = redirect 13 | return map 14 | }, {}) 15 | 16 | function maybeRedirect(pathname) { 17 | const redirect = redirectMap[pathname] 18 | 19 | if (redirect != null) { 20 | if (process.env.NODE_ENV !== `production`) { 21 | const pageResources = loader.loadPageSync(pathname) 22 | 23 | if (pageResources != null) { 24 | console.error( 25 | `The route "${pathname}" matches both a page and a redirect; this is probably not intentional.` 26 | ) 27 | } 28 | } 29 | 30 | window.___replace(redirect.toPath) 31 | return true 32 | } else { 33 | return false 34 | } 35 | } 36 | 37 | const onPreRouteUpdate = (location, prevLocation) => { 38 | if (!maybeRedirect(location.pathname)) { 39 | apiRunner(`onPreRouteUpdate`, { location, prevLocation }) 40 | } 41 | } 42 | 43 | const onRouteUpdate = (location, prevLocation) => { 44 | if (!maybeRedirect(location.pathname)) { 45 | apiRunner(`onRouteUpdate`, { location, prevLocation }) 46 | // Temp hack while awaiting https://github.com/reach/router/issues/119 47 | window.__navigatingToLink = false 48 | } 49 | } 50 | 51 | const navigate = (to, options = {}) => { 52 | // Temp hack while awaiting https://github.com/reach/router/issues/119 53 | if (!options.replace) { 54 | window.__navigatingToLink = true 55 | } 56 | 57 | let { pathname } = parsePath(to) 58 | const redirect = redirectMap[pathname] 59 | 60 | // If we're redirecting, just replace the passed in pathname 61 | // to the one we want to redirect to. 62 | if (redirect) { 63 | to = redirect.toPath 64 | pathname = parsePath(to).pathname 65 | } 66 | 67 | // If we had a service worker update, no matter the path, reload window and 68 | // reset the pathname whitelist 69 | if (window.___swUpdated) { 70 | window.location = pathname 71 | return 72 | } 73 | 74 | // Start a timer to wait for a second before transitioning and showing a 75 | // loader in case resources aren't around yet. 76 | const timeoutId = setTimeout(() => { 77 | emitter.emit(`onDelayedLoadPageResources`, { pathname }) 78 | apiRunner(`onRouteUpdateDelayed`, { 79 | location: window.location, 80 | }) 81 | }, 1000) 82 | 83 | loader.loadPage(pathname).then(pageResources => { 84 | // If no page resources, then refresh the page 85 | // Do this, rather than simply `window.location.reload()`, so that 86 | // pressing the back/forward buttons work - otherwise when pressing 87 | // back, the browser will just change the URL and expect JS to handle 88 | // the change, which won't always work since it might not be a Gatsby 89 | // page. 90 | if (!pageResources || pageResources.status === `error`) { 91 | window.history.replaceState({}, ``, location.href) 92 | window.location = pathname 93 | } 94 | // If the loaded page has a different compilation hash to the 95 | // window, then a rebuild has occurred on the server. Reload. 96 | if (process.env.NODE_ENV === `production` && pageResources) { 97 | if ( 98 | pageResources.page.webpackCompilationHash !== 99 | window.___webpackCompilationHash 100 | ) { 101 | // Purge plugin-offline cache 102 | if ( 103 | `serviceWorker` in navigator && 104 | navigator.serviceWorker.controller !== null && 105 | navigator.serviceWorker.controller.state === `activated` 106 | ) { 107 | navigator.serviceWorker.controller.postMessage({ 108 | gatsbyApi: `clearPathResources`, 109 | }) 110 | } 111 | 112 | console.log(`Site has changed on server. Reloading browser`) 113 | window.location = pathname 114 | } 115 | } 116 | reachNavigate(to, options) 117 | clearTimeout(timeoutId) 118 | }) 119 | } 120 | 121 | function shouldUpdateScroll(prevRouterProps, { location }) { 122 | const { pathname, hash } = location 123 | const results = apiRunner(`shouldUpdateScroll`, { 124 | prevRouterProps, 125 | // `pathname` for backwards compatibility 126 | pathname, 127 | routerProps: { location }, 128 | getSavedScrollPosition: args => this._stateStorage.read(args), 129 | }) 130 | if (results.length > 0) { 131 | // Use the latest registered shouldUpdateScroll result, this allows users to override plugin's configuration 132 | // @see https://github.com/gatsbyjs/gatsby/issues/12038 133 | return results[results.length - 1] 134 | } 135 | 136 | if (prevRouterProps) { 137 | const { 138 | location: { pathname: oldPathname }, 139 | } = prevRouterProps 140 | if (oldPathname === pathname) { 141 | // Scroll to element if it exists, if it doesn't, or no hash is provided, 142 | // scroll to top. 143 | return hash ? decodeURI(hash.slice(1)) : [0, 0] 144 | } 145 | } 146 | return true 147 | } 148 | 149 | function init() { 150 | // Temp hack while awaiting https://github.com/reach/router/issues/119 151 | window.__navigatingToLink = false 152 | 153 | window.___push = to => navigate(to, { replace: false }) 154 | window.___replace = to => navigate(to, { replace: true }) 155 | window.___navigate = (to, options) => navigate(to, options) 156 | 157 | // Check for initial page-load redirect 158 | maybeRedirect(window.location.pathname) 159 | } 160 | 161 | class RouteAnnouncer extends React.Component { 162 | constructor(props) { 163 | super(props) 164 | this.announcementRef = React.createRef() 165 | } 166 | 167 | componentDidUpdate(prevProps, nextProps) { 168 | requestAnimationFrame(() => { 169 | let pageName = `new page at ${this.props.location.pathname}` 170 | if (document.title) { 171 | pageName = document.title 172 | } 173 | const pageHeadings = document 174 | .getElementById(`gatsby-focus-wrapper`) 175 | .getElementsByTagName(`h1`) 176 | if (pageHeadings && pageHeadings.length) { 177 | pageName = pageHeadings[0].textContent 178 | } 179 | const newAnnouncement = `Navigated to ${pageName}` 180 | const oldAnnouncement = this.announcementRef.current.innerText 181 | if (oldAnnouncement !== newAnnouncement) { 182 | this.announcementRef.current.innerText = newAnnouncement 183 | } 184 | }) 185 | } 186 | 187 | render() { 188 | return ( 189 |
206 | ) 207 | } 208 | } 209 | 210 | // Fire on(Pre)RouteUpdate APIs 211 | class RouteUpdates extends React.Component { 212 | constructor(props) { 213 | super(props) 214 | onPreRouteUpdate(props.location, null) 215 | } 216 | 217 | componentDidMount() { 218 | onRouteUpdate(this.props.location, null) 219 | } 220 | 221 | componentDidUpdate(prevProps, prevState, shouldFireRouteUpdate) { 222 | if (shouldFireRouteUpdate) { 223 | onRouteUpdate(this.props.location, prevProps.location) 224 | } 225 | } 226 | 227 | getSnapshotBeforeUpdate(prevProps) { 228 | if (this.props.location.pathname !== prevProps.location.pathname) { 229 | onPreRouteUpdate(this.props.location, prevProps.location) 230 | return true 231 | } 232 | 233 | return false 234 | } 235 | 236 | render() { 237 | return ( 238 | 239 | {this.props.children} 240 | 241 | 242 | ) 243 | } 244 | } 245 | 246 | RouteUpdates.propTypes = { 247 | location: PropTypes.object.isRequired, 248 | } 249 | 250 | export { init, shouldUpdateScroll, RouteUpdates } 251 | --------------------------------------------------------------------------------