2
0

PagePath.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 pagePath = page.path.replace(this.props.excludePathString.replace(/^\//, ''), '');
  25. const shortPath = this.getShortPath(pagePath);
  26. const shortPathEscaped = escapeStringRegexp(shortPath);
  27. const pathPrefix = pagePath.replace(new RegExp(shortPathEscaped + '(/)?$'), '');
  28. return (
  29. <span className="page-path">
  30. {pathPrefix}<strong>{shortPath}</strong>
  31. </span>
  32. );
  33. }
  34. }
  35. PagePath.propTypes = {
  36. page: PropTypes.object.isRequired,
  37. };
  38. PagePath.defaultProps = {
  39. page: {},
  40. excludePathString: '',
  41. };