aboutsummaryrefslogtreecommitdiff
path: root/components/PathCrumbs/index.tsx
blob: 41875ec5fca46c6a76afa42f37d32f705a6e065b (plain)
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
import React, { FC } from 'react';

import assert from '../../utils/assert';
import { DISPLAY_DOMAIN } from '../../utils/env';

const urlPathComponents = (path : string): string[] => {
  assert(path.length > 0, "empty path");

  let canonicalizedPath = path[path.length - 1] === '/' ?
    path.substr(0, path.length - 1) : path;

  if(canonicalizedPath.length === 0) {
    return [];
  } else {
    canonicalizedPath = canonicalizedPath[0] == '/' ?
      path.substr(1, path.length - 1) : path;
  }

  return canonicalizedPath.split('/')
}

const urlPathComponentsToFullPath = (urlPathComponents : string[]): string[] => {
  const fullPaths = new Array<string>(urlPathComponents.length + 1);

  fullPaths[0] = '';

  for(let i = 0; i < urlPathComponents.length; i++) {
    fullPaths[i + 1] = fullPaths[i] + '/' + urlPathComponents[i];
  }

  fullPaths[0] = '/';

  return fullPaths;
};

export type PathCrumbsProps = {
  path: string;
  style?: React.CSSProperties;
};

import { BreadCrumbs , LinkCrumb } from '../../components/BreadCrumbs';

const PathCrumbs: FC<PathCrumbsProps> = ({ path, style }) => {

  const pathComponents = urlPathComponents(path);
  const fullPaths = urlPathComponentsToFullPath(pathComponents);

  const linksComponents = fullPaths.map((fullPath, i) => (
    <LinkCrumb href={fullPath} key={fullPath}>
      { i === 0 ? DISPLAY_DOMAIN : pathComponents[i - 1] }
    </LinkCrumb>
  ));

  return (
    <BreadCrumbs style={style}>
      {linksComponents}
    </BreadCrumbs>
  );
};

export default PathCrumbs;