PagePath.jsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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);
  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. additionalClassNames: PropTypes.array,
  41. };
  42. PagePath.defaultProps = {
  43. additionalClassNames: [],
  44. };