( options: OptionType[], children: React.ReactNode, fieldNames: FieldNames, optionFilterProp: string, optionLabelProp: string, )
| 7 | * Then flatten the `options`. |
| 8 | */ |
| 9 | const useOptions = <OptionType>( |
| 10 | options: OptionType[], |
| 11 | children: React.ReactNode, |
| 12 | fieldNames: FieldNames, |
| 13 | optionFilterProp: string, |
| 14 | optionLabelProp: string, |
| 15 | ) => { |
| 16 | return React.useMemo(() => { |
| 17 | let mergedOptions = options; |
| 18 | const childrenAsData = !options; |
| 19 | |
| 20 | if (childrenAsData) { |
| 21 | mergedOptions = convertChildrenToData(children); |
| 22 | } |
| 23 | |
| 24 | const valueOptions = new Map<RawValueType, OptionType>(); |
| 25 | const labelOptions = new Map<React.ReactNode, OptionType>(); |
| 26 | |
| 27 | const setLabelOptions = ( |
| 28 | labelOptionsMap: Map<React.ReactNode, OptionType>, |
| 29 | option: OptionType, |
| 30 | key: string | number, |
| 31 | ) => { |
| 32 | if (key && typeof key === 'string') { |
| 33 | labelOptionsMap.set(option[key], option); |
| 34 | } |
| 35 | }; |
| 36 | |
| 37 | const dig = (optionList: OptionType[], isChildren = false) => { |
| 38 | // for loop to speed up collection speed |
| 39 | for (let i = 0; i < optionList.length; i += 1) { |
| 40 | const option = optionList[i]; |
| 41 | if (!option[fieldNames.options] || isChildren) { |
| 42 | valueOptions.set(option[fieldNames.value], option); |
| 43 | setLabelOptions(labelOptions, option, fieldNames.label); |
| 44 | // https://github.com/ant-design/ant-design/issues/35304 |
| 45 | setLabelOptions(labelOptions, option, optionFilterProp); |
| 46 | setLabelOptions(labelOptions, option, optionLabelProp); |
| 47 | } else { |
| 48 | dig(option[fieldNames.options], true); |
| 49 | } |
| 50 | } |
| 51 | }; |
| 52 | |
| 53 | dig(mergedOptions); |
| 54 | |
| 55 | return { |
| 56 | options: mergedOptions, |
| 57 | valueOptions, |
| 58 | labelOptions, |
| 59 | }; |
| 60 | }, [options, children, fieldNames, optionFilterProp, optionLabelProp]); |
| 61 | }; |
| 62 | |
| 63 | export default useOptions; |
no test coverage detected
searching dependent graphs…