"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _url = _interopRequireDefault(require("url"));

var _querystring = _interopRequireDefault(require("querystring"));

var _components = require("@patternplate/components");

var _lodash = require("lodash");

var _reactRedux = require("react-redux");

var _reactRouterRedux = require("react-router-redux");

var _redux = require("redux");

var _actions = require("../actions");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var _default = (0, _reactRedux.connect)(mapState, mapDispatch)(_components.Link.RawLink);

exports.default = _default;

function mapState(state, own) {
  const location = state.routing.locationBeforeTransitions;
  return Object.assign({}, own, {
    href: getHref(own, {
      base: state.base,
      location
    })
  });
}

function mapDispatch(dispatch, ownProps) {
  return (0, _redux.bindActionCreators)({
    onClick(e) {
      if (ownProps.external) {
        return {
          type: null
        };
      }

      e.preventDefault();

      const parsed = _url.default.parse(e.currentTarget.href);

      if (parsed.hash) {
        (0, _actions.scrollTo)(parsed.hash.slice(1));
      }

      return (0, _reactRouterRedux.push)([parsed.path, parsed.hash].join(""));
    }

  }, dispatch);
}

function getHref(props, context) {
  if (props.external === true || !context.location) {
    return props.href;
  }

  const parsed = props.href ? _url.default.parse(props.href) : {
    pathname: context.location.pathname,
    query: _querystring.default.stringify(context.location.query)
  };
  parsed.query = _querystring.default.parse(parsed.query);
  const query = props.query === null ? {} : (0, _lodash.pickBy)(Object.assign({}, context.location.query, parsed.query, props.query || context.location.query), (value, key) => {
    // TODO: deduce this for all keys from reduce config
    // special case "navigation-enabled", invert logic
    if (key === "navigation-enabled") {
      return value !== true && value !== "true";
    } // if the key is not in the current query, add it


    if (!context.location.query.hasOwnProperty(key)) {
      return true;
    } // omit "falsy" values to keep url shorter


    return value !== "false" && value !== "0" && !!value;
  });
  const pathname = typeof parsed.pathname === "string" ? prefix(context.base, parsed.pathname) : context.location.pathname;
  return _url.default.format({
    pathname: pathname + "/",
    query,
    hash: props.hash || (parsed.hash || "#").slice(1)
  });
}

function prefix(base, pathname) {
  const b = norm(base);
  const p = norm(pathname);

  if (p === "") {
    return `/${b}`;
  }

  if (p.startsWith(b)) {
    return `/${p}`;
  }

  return `/${[norm(base), norm(pathname)].join("/")}`;
}

function norm(p) {
  return p.split("/").filter(Boolean).join("/");
}
//# sourceMappingURL=link.js.map