fix: SelectField bad layout when missing label

Massimo Melina committed Mar 22, 2022 at 17:17 UTC 1d5f943926c3207388a4c453a63af1a8d11ae52a
1 file changed +6 -4
admin/src/Form.ts
+6 -4
@@ -15,6 +15,7 @@ import {
15 import { Save } from '@mui/icons-material'
16 import { LoadingButton } from '@mui/lab'
17 import _ from 'lodash'
18 +import { SxProps } from '@mui/system'
19
20 interface FieldDescriptor {
21 k:string
@@ -235,7 +236,7 @@ type SelectOption<T> = SelectPair<T> | (T extends string | number ? T : never)
236 interface SelectPair<T> { label: string, value:T }
237
238 export function SelectField<T>(props: FieldProps<T> & { options:SelectOptions<T> }) {
238 - const { value, onChange, options, ...rest } = props
239 + const { value, onChange, options, sx, ...rest } = props
240 return h(TextField, { // using TextField because Select is not displaying label correctly
241 ...commonSelectProps(props),
242 ...rest,
@@ -251,9 +252,9 @@ export function SelectField<T>(props: FieldProps<T> & { options:SelectOptions<T>
252 }
253
254 export function MultiSelectField<T>(props: FieldProps<T[]> & { options:SelectOptions<T> }) {
254 - const { value, options, ...rest } = props
255 + const { value, options, sx, ...rest } = props
256 return h(TextField, {
256 - ...commonSelectProps({ ...props, value:undefined }),
257 + ...commonSelectProps({ ...props, value: undefined }),
258 ...rest,
259 SelectProps: { multiple: true },
260 value: !Array.isArray(value) ? [] : value.map(x => JSON.stringify(x)),
@@ -268,7 +269,7 @@ export function MultiSelectField<T>(props: FieldProps<T[]> & { options:SelectOpt
269 })
270 }
271
271 -function commonSelectProps<T>(props: { value?: T, disabled?: boolean, options:SelectOptions<T> }) {
272 +function commonSelectProps<T>(props: { sx?:SxProps, label?: FieldProps<T>['label'], value?: T, disabled?: boolean, options:SelectOptions<T> }) {
273 const { options, disabled } = props
274 const normalizedOptions = !Array.isArray(options) ? Object.entries(options).map(([label,value]) => ({ value, label }))
275 : options.map(o => typeof o === 'string' || typeof o === 'number' ? { value: o, label: String(o) } : o as SelectPair<T>)
@@ -277,6 +278,7 @@ function commonSelectProps<T>(props: { value?: T, disabled?: boolean, options:Se
278 return {
279 select: true,
280 fullWidth: true,
281 + sx: props.label ? props.sx : Object.assign({ '& .MuiInputBase-input': { pt: 1 } }, props.sx),
282 // avoid warning for invalid option. This can easily happen for a split-second when you keep value in a useState (or other async way) and calculate options with a useMemo (or other sync way) causing a temporary misalignment.
283 value: currentOption ? jsonValue : '',
284 disabled: !normalizedOptions?.length || disabled,