Skip to content
This repository has been archived by the owner on Dec 13, 2020. It is now read-only.

Commit

Permalink
Add <Shortcut> that subscribes to <ShortcutProvider>
Browse files Browse the repository at this point in the history
Issue #1283
  • Loading branch information
pablosichert committed Nov 16, 2017
1 parent 1e77a05 commit ceaba65
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/components/Shortcuts/Shortcut.js
Original file line number Diff line number Diff line change
@@ -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;
}
}
52 changes: 52 additions & 0 deletions src/components/Shortcuts/Shortcut.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});

0 comments on commit ceaba65

Please sign in to comment.