|
| 1 | +/** |
| 2 | + * Copyright (c) 2025, RTE (http://www.rte-france.com) |
| 3 | + * This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 | + */ |
| 7 | +import { AutocompleteInputProps, genHelperError } from '@gridsuite/commons-ui'; |
| 8 | + |
| 9 | +import { useController } from 'react-hook-form'; |
| 10 | +import { SyntheticEvent } from 'react'; |
| 11 | +import { Autocomplete, AutocompleteProps, TextField, TextFieldProps, Theme } from '@mui/material'; |
| 12 | + |
| 13 | +const styles = { |
| 14 | + autocomplete: (theme: Theme) => ({ |
| 15 | + '.MuiAutocomplete-inputRoot': { |
| 16 | + display: 'flex', |
| 17 | + alignItems: 'flex-start', |
| 18 | + justifyContent: 'flex-start', |
| 19 | + flexWrap: 'nowrap', |
| 20 | + padding: '1px', |
| 21 | + paddingLeft: '5px', |
| 22 | + }, |
| 23 | + '.Mui-expanded, .Mui-focused, .Mui-focusVisible': { |
| 24 | + width: 'inherit', |
| 25 | + background: theme.palette.tabBackground, |
| 26 | + flexWrap: 'wrap', |
| 27 | + }, |
| 28 | + }), |
| 29 | +}; |
| 30 | + |
| 31 | +type SubstationsAutocompleteProps = Pick<AutocompleteProps<string, true, false, false>, 'disabled'> & { |
| 32 | + name: AutocompleteInputProps['name']; |
| 33 | + label?: TextFieldProps['label']; |
| 34 | + disabled?: boolean; |
| 35 | + substations: string[]; |
| 36 | +}; |
| 37 | + |
| 38 | +export default function SubstationsAutocomplete({ |
| 39 | + name, |
| 40 | + label, |
| 41 | + disabled, |
| 42 | + substations, |
| 43 | + ...props |
| 44 | +}: SubstationsAutocompleteProps) { |
| 45 | + const { |
| 46 | + field: { onChange, value, ref }, |
| 47 | + fieldState: { error }, |
| 48 | + } = useController({ name }); |
| 49 | + |
| 50 | + const handleChange = (_: SyntheticEvent, value: string[]) => { |
| 51 | + onChange(value); |
| 52 | + }; |
| 53 | + |
| 54 | + return ( |
| 55 | + <Autocomplete |
| 56 | + multiple |
| 57 | + disabled={disabled} |
| 58 | + value={value} |
| 59 | + onChange={handleChange} |
| 60 | + options={substations} |
| 61 | + size={'small'} |
| 62 | + sx={styles.autocomplete} |
| 63 | + renderInput={({ inputProps, ...rest }) => ( |
| 64 | + <TextField |
| 65 | + inputRef={ref} |
| 66 | + inputProps={{ ...inputProps }} |
| 67 | + label={label} |
| 68 | + {...genHelperError(error?.message)} |
| 69 | + {...rest} |
| 70 | + /> |
| 71 | + )} |
| 72 | + autoHighlight={true} |
| 73 | + disableCloseOnSelect={true} |
| 74 | + {...props} |
| 75 | + /> |
| 76 | + ); |
| 77 | +} |
0 commit comments