UNPKG

ndla-ui

Version:

UI component library for NDLA.

56 lines (44 loc) 1.85 kB
var _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; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /** * Copyright (c) 2016-present, NDLA. * * This source code is licensed under the GPLv3 license found in the * LICENSE file in the root directory of this source tree. * */ import React from 'react'; import PropTypes from 'prop-types'; import Link from 'react-router-dom/Link'; import isString from 'lodash/isString'; var isExternalLink = function isExternalLink(to) { return to && isString(to) && (to.startsWith('https://') || to.startsWith('https://')); }; export var isOldNdlaLink = function isOldNdlaLink(to) { return to && isString(to) && to.match(/(.*)\/?node\/(\d+).*/) !== null; }; // Fallback to normal link if app is missing RouterContext, link is external or is old ndla link var SafeLink = function SafeLink(props, context) { if (!context.router || isExternalLink(props.to) || isOldNdlaLink(props.to)) { var to = props.to, rest = _objectWithoutProperties(props, ['to']); delete rest.replace; var href = typeof to === 'string' ? to : '#'; return React.createElement( 'a', _extends({ href: href }, rest), props.children ); } return React.createElement( Link, props, props.children ); }; SafeLink.propTypes = Link.propTypes; SafeLink.defaultProps = Link.defaultProps; SafeLink.contextTypes = { router: PropTypes.object // eslint-disable-line }; export default SafeLink;