UNPKG

2.36 kBJavaScriptView Raw
1const _excluded = ["kind", "story", "children"];
2
3function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
4
5function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
6
7import React, { PureComponent } from 'react';
8import { navigate, hrefTo } from '../../utils'; // FIXME: copied from Typography.Link. Code is duplicated to
9// avoid emotion dependency which breaks React 15.x back-compat
10// Cmd/Ctrl/Shift/Alt + Click should trigger default browser behaviour. Same applies to non-left clicks
11
12const LEFT_BUTTON = 0;
13
14const isPlainLeftClick = e => e.button === LEFT_BUTTON && !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey;
15
16const cancelled = (e, cb = _e => {}) => {
17 if (isPlainLeftClick(e)) {
18 e.preventDefault();
19 cb(e);
20 }
21};
22
23export default class LinkTo extends PureComponent {
24 constructor(...args) {
25 super(...args);
26 this.state = {
27 href: '/'
28 };
29
30 this.updateHref = async () => {
31 const {
32 kind,
33 story
34 } = this.props;
35 const href = await hrefTo(kind, story);
36 this.setState({
37 href
38 });
39 };
40
41 this.handleClick = () => {
42 navigate(this.props);
43 };
44 }
45
46 componentDidMount() {
47 this.updateHref();
48 }
49
50 componentDidUpdate(prevProps) {
51 const {
52 kind,
53 story
54 } = this.props;
55
56 if (prevProps.kind !== kind || prevProps.story !== story) {
57 this.updateHref();
58 }
59 }
60
61 render() {
62 const _this$props = this.props,
63 {
64 children
65 } = _this$props,
66 rest = _objectWithoutPropertiesLoose(_this$props, _excluded);
67
68 const {
69 href
70 } = this.state;
71 return /*#__PURE__*/React.createElement("a", _extends({
72 href: href,
73 onClick: e => cancelled(e, this.handleClick)
74 }, rest), children);
75 }
76
77}
78LinkTo.defaultProps = {
79 kind: null,
80 story: null,
81 children: undefined
82};
\No newline at end of file