UNPKG

@bigfishtv/cockpit

Version:

104 lines (98 loc) 2.94 kB
import React, { Component } from 'react' import PropTypes from 'prop-types' import _get from 'lodash/get' export default class SelectFolderItemInput extends Component { static propTypes = { folders: PropTypes.array.isRequired, items: PropTypes.array.isRequired, onChange: PropTypes.func, value: PropTypes.any, folderKey: PropTypes.string, folderTitleKey: PropTypes.string, folderParentKey: PropTypes.string, folderChildrenKey: PropTypes.string, itemKey: PropTypes.string, itemTitleKey: PropTypes.string, itemFolderKey: PropTypes.string, folderIcon: PropTypes.string, itemIcon: PropTypes.string, } static defaultProps = { folders: [], items: [], onChange: () => {}, value: null, folderKey: 'id', folderTitleKey: 'title', folderParentKey: 'parent_id', folderChildrenKey: 'children', itemKey: 'id', itemTitleKey: 'title', itemFolderKey: 'folder_id', folderIcon: '📂', itemIcon: '📄', } renderOptions(folder, index = 0, total = 1, sameDepthItemTotal = 0, depth = 0) { let options = [] const { items, folderKey, folderTitleKey, folderChildrenKey, itemKey, itemTitleKey, itemFolderKey, folderIcon, itemIcon, } = this.props const childFolders = _get(folder, folderChildrenKey, []) const childItems = items.filter(item => _get(item, itemFolderKey) === _get(folder, folderKey)) const isFirstFolder = index === 0 const isLastFolder = index == total - 1 const isActualFirstFolder = isFirstFolder && depth === 1 const isLastFolderWithNoSiblingItems = isLastFolder && sameDepthItemTotal === 0 options.push( <option value={null} key={`folder${folder.id}`}> {Array(depth).join('│')} {depth > 0 && (isActualFirstFolder ? '┌' : isLastFolderWithNoSiblingItems ? '└' : '├')} {(depth > 0 ? folderIcon + ' ' : '') + _get(folder, folderTitleKey)} </option> ) if (childFolders.length > 0) { for (let f = 0; f < childFolders.length; f++) { options = [ ...options, this.renderOptions(childFolders[f], f, childFolders.length, childItems.length, depth + 1), ] } } for (let i = 0; i < childItems.length; i++) { const item = childItems[i] const isLast = i === childItems.length - 1 options.push( <option value={_get(item, itemKey)} key={`email${item.id}`}> {Array(depth).join('│')} {depth > 0 && (isLastFolderWithNoSiblingItems ? ' ' : '│')} {isLast ? '└' : '├'} {itemIcon + ' ' + _get(item, itemTitleKey)} </option> ) } return options } render() { const { value, onChange, folders, folderKey, folderTitleKey, folderChildrenKey } = this.props const options = this.renderOptions({ [folderKey]: null, [folderTitleKey]: 'Please select', [folderChildrenKey]: folders, }) return ( <label className="select"> <select value={value} onChange={e => onChange(e.target.value)}> {options} </select> </label> ) } }