aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ui/Link.tsx
blob: 816798d798f95cb15ea2fc18ca16858ea440e9e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import classnames from 'classnames';
import { inject, observer } from 'mobx-react';
import {
  type CSSProperties,
  Component,
  type MouseEvent,
  type ReactNode,
} from 'react';
import type { StoresProps } from '../../@types/ferdium-components.types';
import matchRoute from '../../helpers/routing-helpers';
import { openExternalUrl } from '../../helpers/url-helpers';

interface IProps extends Partial<StoresProps> {
  children: ReactNode;
  to: string;
  className?: string;
  activeClassName?: string;
  strictFilter?: boolean;
  target?: string;
  style?: CSSProperties;
  disabled?: boolean;
}

// TODO: create container component for this component
@inject('stores')
@observer
class Link extends Component<IProps> {
  onClick(e: MouseEvent<HTMLAnchorElement>): void {
    const { disabled = false, target = '', to } = this.props;
    if (disabled) {
      e.preventDefault();
    } else if (target === '_blank') {
      e.preventDefault();
      openExternalUrl(to, true);
    }
    // Note: if neither of the above, then let the other onClick handlers process it
  }

  render() {
    const {
      children,
      stores,
      to,
      className = '',
      activeClassName = '',
      strictFilter = false,
      disabled = false,
      style = {},
    } = this.props;
    const { router } = stores!;

    const filter = strictFilter ? `${to}` : `${to}(*action)`;
    const match = matchRoute(filter, router.location.pathname);

    const linkClasses = classnames({
      [`${className}`]: true,
      [`${activeClassName}`]: match,
      'is-disabled': disabled,
    });

    return (
      <a
        href={router.history.createHref(to)}
        className={linkClasses}
        style={style}
        onClick={e => this.onClick(e)}
      >
        {children}
      </a>
    );
  }
}

export default Link;