Manual Reference Source

basic/PageFilter.js

  1. /**
  2. * Created by jakubniezgoda on 21/05/2018.
  3. */
  4.  
  5. import React from 'react';
  6. import PropTypes from 'prop-types';
  7. import { connect } from 'react-redux';
  8.  
  9. import Form from './form/Form';
  10.  
  11. /**
  12. * PageFilter - a component showing dropdown with list of currently available pages.
  13. *
  14. * ## Access
  15. * `Stage.Basic.PageFilter`
  16. *
  17. * ## Usage
  18. * ![PageFilter](manual/asset/PageFilter_0.png)
  19. *
  20. * ```
  21. * let value = 'dashboard';
  22. * <PageFilter name='pageId' value={value} />
  23. * ```
  24. *
  25. */
  26. class PageFilter extends React.Component {
  27. constructor(props, context) {
  28. super(props, context);
  29.  
  30. this.state = PageFilter.initialState(props);
  31. }
  32.  
  33. /**
  34. * propTypes
  35. *
  36. * @property {string} name name of the field
  37. * @property {string} value value of the field
  38. * @property {Array} pages array containing page objects - {id, name} - it is fetched from redux store automatically
  39. * @property {Function} [onChange=()=>{}] function called on input value change
  40. */
  41. static propTypes = {
  42. name: PropTypes.string.isRequired,
  43. value: PropTypes.string.isRequired,
  44. pages: PropTypes.array.isRequired,
  45. onChange: PropTypes.func,
  46. allowDrillDownPages: PropTypes.bool
  47. };
  48.  
  49. static initialState = props => ({
  50. pageId: props.value,
  51. allowDrillDownPages: false
  52. });
  53.  
  54. _handleInputChange(event, field) {
  55. this.setState({ pageId: field.value }, () => {
  56. this.props.onChange(event, {
  57. name: this.props.name,
  58. value: this.state.pageId
  59. });
  60. });
  61. }
  62.  
  63. _getPageName(pages, pageId) {
  64. const page = _.find(pages, { id: pageId });
  65. if (page.isDrillDown) {
  66. return `${this._getPageName(pages, page.parent)} > ${page.name}`;
  67. }
  68. return page.name;
  69. }
  70.  
  71. render() {
  72. const pages = this.props.allowDrillDownPages
  73. ? this.props.pages
  74. : _.filter(this.props.pages, page => !page.isDrillDown);
  75. const pagesOptions = _.map(pages, page => ({
  76. text: this._getPageName(pages, page.id),
  77. value: page.id,
  78. key: page.id
  79. }));
  80. pagesOptions.sort((a, b) => a.text.localeCompare(b.text));
  81. const defaultValue = pagesOptions[0].value;
  82.  
  83. return (
  84. <Form.Dropdown
  85. name="pageId"
  86. search
  87. selection
  88. value={this.state.pageId || defaultValue}
  89. options={pagesOptions}
  90. onChange={this._handleInputChange.bind(this)}
  91. />
  92. );
  93. }
  94. }
  95.  
  96. const mapStateToProps = state => {
  97. return {
  98. pages: state.pages
  99. };
  100. };
  101.  
  102. export default connect(mapStateToProps)(PageFilter);