|
| 1 | +import React from "react"; |
| 2 | +import MaterialAutocomplete from "../value/MaterialAutocomplete"; |
| 3 | + |
| 4 | +const itemsToListValues = (items, level = 0) => ( |
| 5 | + items.map(item => { |
| 6 | + const {items, path, label, disabled, grouplabel} = item; |
| 7 | + const prefix = "\u00A0\u00A0".repeat(level); |
| 8 | + if (items) { |
| 9 | + return itemsToListValues(items, level+1); |
| 10 | + } else { |
| 11 | + return { |
| 12 | + title: label, |
| 13 | + renderTitle: prefix+label, |
| 14 | + value: path, |
| 15 | + disabled, |
| 16 | + groupTitle: level > 0 ? prefix+grouplabel : null, |
| 17 | + }; |
| 18 | + } |
| 19 | + }).flat(Infinity) |
| 20 | +); |
| 21 | + |
| 22 | +const filterOptionsConfig = { |
| 23 | + stringify: (option) => { |
| 24 | + const keysForFilter = ["title", "value", "grouplabel", "label"]; |
| 25 | + const valueForFilter = keysForFilter |
| 26 | + .map(k => (typeof option[k] == "string" ? option[k] : "")) |
| 27 | + .join("\0"); |
| 28 | + return valueForFilter; |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +const fieldAdapter = ({items, selectedKey, setField, ...rest}) => { |
| 33 | + const listValues = itemsToListValues(items); |
| 34 | + const groupBy = (option) => option.groupTitle; |
| 35 | + const value = selectedKey; |
| 36 | + const setValue = (value, _asyncValues) => { |
| 37 | + if (!value) return undefined; |
| 38 | + return setField(value); |
| 39 | + }; |
| 40 | + |
| 41 | + return { |
| 42 | + ...rest, |
| 43 | + listValues, |
| 44 | + setValue, |
| 45 | + groupBy, |
| 46 | + filterOptionsConfig, |
| 47 | + allowCustomValues: false, |
| 48 | + multiple: false, |
| 49 | + value, |
| 50 | + }; |
| 51 | +}; |
| 52 | + |
| 53 | +export default (props) => { |
| 54 | + return <MaterialAutocomplete {...fieldAdapter(props)} />; |
| 55 | +}; |
0 commit comments