PagePath.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. let 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. else {
  35. return <span className={classNames.join(' ')}>{pathPrefix}<strong>{shortPath}</strong></span>;
  36. }
  37. }
  38. }
  39. PagePath.propTypes = {
  40. page: PropTypes.object.isRequired,
  41. isShortPathOnly: PropTypes.bool,
  42. excludePathString: PropTypes.string,
  43. additionalClassNames: PropTypes.array,
  44. };
  45. PagePath.defaultProps = {
  46. page: {},
  47. additionalClassNames: [],
  48. excludePathString: '',
  49. };