PagePath.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import React from 'react';
  2. import PropTypes from 'prop-types';
  3. import escapeStringRegexp from 'escape-string-regexp';
  4. export default class PagePath extends React.Component {
  5. getShortPath(path) {
  6. const name = path.replace(/(\/)$/, '');
  7. // /.../hoge/YYYY/MM/DD 形式のページ
  8. if (name.match(/.+\/([^/]+\/\d{4}\/\d{2}\/\d{2})$/)) {
  9. return name.replace(/.+\/([^/]+\/\d{4}\/\d{2}\/\d{2})$/, '$1');
  10. }
  11. // /.../hoge/YYYY/MM 形式のページ
  12. if (name.match(/.+\/([^/]+\/\d{4}\/\d{2})$/)) {
  13. return name.replace(/.+\/([^/]+\/\d{4}\/\d{2})$/, '$1');
  14. }
  15. // /.../hoge/YYYY 形式のページ
  16. if (name.match(/.+\/([^/]+\/\d{4})$/)) {
  17. return name.replace(/.+\/([^/]+\/\d{4})$/, '$1');
  18. }
  19. // ページの末尾を拾う
  20. return name.replace(/.+\/(.+)?$/, '$1');
  21. }
  22. render() {
  23. const page = this.props.page;
  24. const isShortPathOnly = this.props.isShortPathOnly;
  25. const pagePath = decodeURIComponent(page.path.replace(this.props.excludePathString.replace(/^\//, ''), ''));
  26. const shortPath = this.getShortPath(pagePath);
  27. const shortPathEscaped = escapeStringRegexp(shortPath);
  28. const pathPrefix = pagePath.replace(new RegExp(`${shortPathEscaped}(/)?$`), '');
  29. let classNames = ['page-path'];
  30. classNames = classNames.concat(this.props.additionalClassNames);
  31. if (isShortPathOnly) {
  32. return <span className={classNames.join(' ')}>{shortPath}</span>;
  33. }
  34. return <span className={classNames.join(' ')}>{pathPrefix}<strong>{shortPath}</strong></span>;
  35. }
  36. }
  37. PagePath.propTypes = {
  38. page: PropTypes.object.isRequired,
  39. isShortPathOnly: PropTypes.bool,
  40. excludePathString: PropTypes.string,
  41. additionalClassNames: PropTypes.array,
  42. };
  43. PagePath.defaultProps = {
  44. additionalClassNames: [],
  45. excludePathString: '',
  46. };