From ceaba65335fd1a02657b9fcfefb66a2d91a07a44 Mon Sep 17 00:00:00 2001 From: Pablo Sichert Date: Thu, 16 Nov 2017 05:31:40 +0100 Subject: [PATCH] Add that subscribes to Issue #1283 --- src/components/Shortcuts/Shortcut.js | 35 +++++++++++++++ src/components/Shortcuts/Shortcut.test.js | 52 +++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 src/components/Shortcuts/Shortcut.js create mode 100644 src/components/Shortcuts/Shortcut.test.js diff --git a/src/components/Shortcuts/Shortcut.js b/src/components/Shortcuts/Shortcut.js new file mode 100644 index 000000000..d7b0d0a82 --- /dev/null +++ b/src/components/Shortcuts/Shortcut.js @@ -0,0 +1,35 @@ +import { Component } from 'react'; +import PropTypes from 'prop-types'; +import keymap from './keymap'; + +export default class Shortcut extends Component { + static contextTypes = { + shortcuts: PropTypes.shape({ + subscribe: PropTypes.func.isRequired, + unsubscribe: PropTypes.func.isRequired + }).isRequired + }; + + static propTypes = { + name: PropTypes.oneOf(Object.keys(keymap)).isRequired, + handler: PropTypes.func.isRequired + }; + + componentWillMount() { + const { subscribe } = this.context.shortcuts; + const { name, handler } = this.props; + + subscribe(name, handler); + } + + componentWillUnmount() { + const { unsubscribe } = this.context.shortcuts; + const { name, handler } = this.props; + + unsubscribe(name, handler); + } + + render() { + return null; + } +} diff --git a/src/components/Shortcuts/Shortcut.test.js b/src/components/Shortcuts/Shortcut.test.js new file mode 100644 index 000000000..2a91ad6a3 --- /dev/null +++ b/src/components/Shortcuts/Shortcut.test.js @@ -0,0 +1,52 @@ +/* eslint-env mocha */ +import chai, { expect } from 'chai'; +import { spy } from 'sinon'; +import sinonChai from 'sinon-chai'; +import { Component } from 'react'; +import Shortcut from './Shortcut'; + +chai.use(sinonChai); + +describe('Shortcut', () => { + it('should be a React component', () => { + expect(Shortcut).to.be.an.instanceOf(Component.constructor); + }); + + it('should return null from render()', () => { + const shortcut = new Shortcut; + + expect(shortcut.render()).to.equal(null); + }); + + it('should subscribe when mounting', () => { + const shortcut = new Shortcut; + + const subscribe = spy(); + + const name = 'Foo'; + const handler = () => {}; + + shortcut.props = { name, handler }; + shortcut.context = { shortcuts: { subscribe } }; + + shortcut.componentWillMount(); + + expect(subscribe).to.have.been.calledWith(name, handler); + }); + + it('should unsubscribe when mounting', () => { + const shortcut = new Shortcut; + + const unsubscribe = spy(); + + const name = 'Foo'; + const handler = () => {}; + + shortcut.props = { name, handler }; + shortcut.context = { shortcuts: { unsubscribe } }; + + shortcut.componentWillUnmount(); + + expect(unsubscribe).to.have.been.calledWith(name, handler); + }); +});