All files / src/domain/BreadcrumbsBuilder index.js

96.3% Statements 26/27
94.44% Branches 17/18
100% Functions 8/8
95.83% Lines 23/24
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      1x 1x       6x   6x 32x   6x 10x   15x 10x 10x       6x   6x 11x 11x 9x 3x 3x         9x 9x 11x                 6x 4x     6x      
import log from 'domain/log';
import is from 'is_js';
 
const ACCEPTABLE_LABELS_TYPES = new Set(['string', 'object', 'function']);
const ALWAYS_APPLIED_PARAMS = { mode: '' };
 
export default {
  buildWithProps: (props) => {
    const { params, routes, buildRoute } = props;
 
    const getRouteSegments = () =>
      routes.filter((route) => is.string(route.path));
 
    const buildRouteHref = (toRouteIdx) => {
      const paths = getRouteSegments()
        .slice(0, toRouteIdx + 1)
        .map((route) => route.path);
      const path = paths.join('/');
      return buildRoute(path,
          Object.assign({}, params, ALWAYS_APPLIED_PARAMS || {}));
    };
 
    const breadcrumbs = [];
 
    getRouteSegments().forEach((routeDescriptor, routeIdx) => {
      let labels = routeDescriptor.breadcrumbLabels;
      if (! ACCEPTABLE_LABELS_TYPES.has(typeof labels)) return;
      if (is.function(labels)) {
        try {
          labels = labels(props);
        } catch (err) {
          log.warn(`Error in \`breadcrumbLabels\` in route \`${routeDescriptor.path}\``, err);
        }
      }
      labels = is.array(labels) ? labels : [labels];
      Array.prototype.push.apply(breadcrumbs,
        labels.filter((l) => l).map((labelOrObject) => ({
          label: labelOrObject.label || labelOrObject,
          href: labelOrObject.href || buildRouteHref(routeIdx),
          clickable: is.boolean(labelOrObject.clickable) ? labelOrObject.clickable : true,
          backLinkHref: is.string(labelOrObject.backLinkHref) ? labelOrObject.backLinkHref : null,
        })));
    });
 
    // the last one shouldn't be clickable
    if (breadcrumbs.length > 1) {
      breadcrumbs[breadcrumbs.length - 1].clickable = false;
    }
 
    return breadcrumbs;
  },
};