|
| 1 | +import { css } from '@emotion/css'; |
| 2 | +import React, { ComponentProps, FC } from 'react'; |
| 3 | + |
| 4 | +import { GrafanaTheme2 } from '@grafana/data'; |
| 5 | +import { useTheme2, ReactUtils, Field, Icon, PopoverContent, Tooltip } from '@grafana/ui'; |
| 6 | + |
| 7 | +interface EditorFieldProps extends ComponentProps<typeof Field> { |
| 8 | + label: string; |
| 9 | + children: React.ReactElement; |
| 10 | + width?: number | string; |
| 11 | + optional?: boolean; |
| 12 | + tooltip?: PopoverContent; |
| 13 | +} |
| 14 | + |
| 15 | +const EditorField: FC<EditorFieldProps> = (props) => { |
| 16 | + const { label, optional, tooltip, children, width, ...fieldProps } = props; |
| 17 | + |
| 18 | + const theme = useTheme2(); |
| 19 | + const styles = getStyles(theme, width); |
| 20 | + |
| 21 | + // Null check for backward compatibility |
| 22 | + const childInputId = fieldProps?.htmlFor || ReactUtils?.getChildId(children); |
| 23 | + |
| 24 | + const labelEl = ( |
| 25 | + <> |
| 26 | + <label className={styles.label} htmlFor={childInputId}> |
| 27 | + {label} |
| 28 | + {optional && <span className={styles.optional}> - optional</span>} |
| 29 | + {tooltip && ( |
| 30 | + <Tooltip placement="top" content={tooltip} theme="info"> |
| 31 | + <Icon name="info-circle" size="sm" className={styles.icon} /> |
| 32 | + </Tooltip> |
| 33 | + )} |
| 34 | + </label> |
| 35 | + </> |
| 36 | + ); |
| 37 | + |
| 38 | + return ( |
| 39 | + <div className={styles.root}> |
| 40 | + <Field className={styles.field} label={labelEl} {...fieldProps}> |
| 41 | + {children} |
| 42 | + </Field> |
| 43 | + </div> |
| 44 | + ); |
| 45 | +}; |
| 46 | + |
| 47 | +export default EditorField; |
| 48 | + |
| 49 | +const getStyles = (theme: GrafanaTheme2, width?: number | string) => { |
| 50 | + return { |
| 51 | + root: css({ |
| 52 | + paddingLeft: theme.spacing(1), |
| 53 | + minWidth: theme.spacing(width ?? 0), |
| 54 | + }), |
| 55 | + label: css({ |
| 56 | + fontSize: 12, |
| 57 | + fontWeight: theme.typography.fontWeightMedium, |
| 58 | + }), |
| 59 | + optional: css({ |
| 60 | + fontStyle: 'italic', |
| 61 | + color: theme.colors.text.secondary, |
| 62 | + }), |
| 63 | + field: css({ |
| 64 | + marginBottom: 0, // GrafanaUI/Field has a bottom margin which we must remove |
| 65 | + }), |
| 66 | + icon: css({ |
| 67 | + color: theme.colors.text.secondary, |
| 68 | + marginLeft: theme.spacing(1), |
| 69 | + ':hover': { |
| 70 | + color: theme.colors.text.primary, |
| 71 | + }, |
| 72 | + }), |
| 73 | + }; |
| 74 | +}; |
0 commit comments