TagsInput: Prevent adding duplicate tags + refactor, restyle (#56485)

This commit is contained in:
kay delaney 2022-10-10 15:56:02 +01:00 committed by GitHub
parent fb31daa92f
commit efed72096f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 96 additions and 101 deletions

View File

@ -1,9 +1,9 @@
import { css } from '@emotion/css'; import { css } from '@emotion/css';
import React, { FC } from 'react'; import React, { useMemo } from 'react';
import { GrafanaTheme } from '@grafana/data'; import { GrafanaTheme2 } from '@grafana/data';
import { stylesFactory, useTheme } from '../../themes'; import { useStyles2 } from '../../themes';
import { getTagColorsFromName } from '../../utils'; import { getTagColorsFromName } from '../../utils';
import { IconButton } from '../IconButton/IconButton'; import { IconButton } from '../IconButton/IconButton';
@ -13,61 +13,60 @@ interface Props {
onRemove: (tag: string) => void; onRemove: (tag: string) => void;
} }
const getStyles = stylesFactory(({ theme, name }: { theme: GrafanaTheme; name: string }) => {
const { color, borderColor } = getTagColorsFromName(name);
const height = theme.spacing.formInputHeight - 8;
return {
itemStyle: css`
display: flex;
align-items: center;
height: ${height}px;
line-height: ${height - 2}px;
background-color: ${color};
color: ${theme.palette.white};
border: 1px solid ${borderColor};
border-radius: 3px;
padding: 0 ${theme.spacing.xs};
margin-right: 3px;
white-space: nowrap;
text-shadow: none;
font-weight: 500;
font-size: ${theme.typography.size.sm};
`,
nameStyle: css`
margin-right: 3px;
`,
buttonStyles: css`
margin: 0;
&:hover::before {
display: none;
}
`,
};
});
/** /**
* @internal * @internal
* Only used internally by TagsInput * Only used internally by TagsInput
* */ * */
export const TagItem: FC<Props> = ({ name, disabled, onRemove }) => { export const TagItem = ({ name, disabled, onRemove }: Props) => {
const theme = useTheme(); const { color, borderColor } = useMemo(() => getTagColorsFromName(name), [name]);
const styles = getStyles({ theme, name }); const styles = useStyles2(getStyles);
return ( return (
<div className={styles.itemStyle}> <li className={styles.itemStyle} style={{ backgroundColor: color, borderColor }}>
<span className={styles.nameStyle}>{name}</span> <span className={styles.nameStyle}>{name}</span>
<IconButton <IconButton
name="times" name="times"
size="lg" size="lg"
disabled={disabled} disabled={disabled}
ariaLabel={`Remove ${name}`} ariaLabel={`Remove "${name}" tag`}
onClick={() => onRemove(name)} onClick={() => onRemove(name)}
type="button" type="button"
className={styles.buttonStyles} className={styles.buttonStyles}
/> />
</div> </li>
); );
}; };
const getStyles = (theme: GrafanaTheme2) => {
const height = theme.spacing.gridSize * 3;
return {
itemStyle: css({
display: 'flex',
gap: '3px',
alignItems: 'center',
height: `${height}px`,
lineHeight: `${height - 2}px`,
color: '#fff',
borderWidth: '1px',
borderStyle: 'solid',
borderRadius: '3px',
padding: `0 ${theme.spacing(0.5)}`,
whiteSpace: 'nowrap',
textShadow: 'none',
fontWeight: 500,
fontSize: theme.typography.size.sm,
}),
nameStyle: css({
maxWidth: '25ch',
textOverflow: 'ellipsis',
overflow: 'hidden',
}),
buttonStyles: css({
margin: 0,
'&:hover::before': {
display: 'none',
},
}),
};
};

View File

@ -8,7 +8,7 @@ describe('TagsInput', () => {
const onChange = jest.fn(); const onChange = jest.fn();
render(<TagsInput onChange={onChange} tags={['One', 'Two']} />); render(<TagsInput onChange={onChange} tags={['One', 'Two']} />);
fireEvent.click(await screen.findByRole('button', { name: /remove one/i })); fireEvent.click(await screen.findByRole('button', { name: /Remove \"One\"/i }));
expect(onChange).toHaveBeenCalledWith(['Two']); expect(onChange).toHaveBeenCalledWith(['Two']);
}); });
@ -17,7 +17,7 @@ describe('TagsInput', () => {
const onChange = jest.fn(); const onChange = jest.fn();
render(<TagsInput onChange={onChange} tags={['One', 'Two']} disabled />); render(<TagsInput onChange={onChange} tags={['One', 'Two']} disabled />);
fireEvent.click(await screen.findByRole('button', { name: /remove one/i })); fireEvent.click(await screen.findByRole('button', { name: /Remove \"One\"/i }));
expect(onChange).not.toHaveBeenCalled(); expect(onChange).not.toHaveBeenCalled();
}); });

View File

@ -1,9 +1,9 @@
import { css, cx } from '@emotion/css'; import { css, cx } from '@emotion/css';
import React, { ChangeEvent, KeyboardEvent, FC, useState } from 'react'; import React, { useCallback, useState } from 'react';
import { GrafanaTheme } from '@grafana/data'; import { GrafanaTheme2 } from '@grafana/data';
import { useStyles, useTheme2 } from '../../themes/ThemeContext'; import { useStyles2, useTheme2 } from '../../themes/ThemeContext';
import { Button } from '../Button'; import { Button } from '../Button';
import { Input } from '../Input/Input'; import { Input } from '../Input/Input';
@ -25,7 +25,7 @@ export interface Props {
invalid?: boolean; invalid?: boolean;
} }
export const TagsInput: FC<Props> = ({ export const TagsInput = ({
placeholder = 'New tag (enter key to add)', placeholder = 'New tag (enter key to add)',
tags = [], tags = [],
onChange, onChange,
@ -35,25 +35,25 @@ export const TagsInput: FC<Props> = ({
addOnBlur, addOnBlur,
invalid, invalid,
id, id,
}) => { }: Props) => {
const [newTagName, setNewName] = useState(''); const [newTagName, setNewTagName] = useState('');
const styles = useStyles(getStyles); const styles = useStyles2(getStyles);
const theme = useTheme2(); const theme = useTheme2();
const onNameChange = (event: ChangeEvent<HTMLInputElement>) => { const onNameChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
setNewName(event.target.value); setNewTagName(event.target.value);
}; }, []);
const onRemove = (tagToRemove: string) => { const onRemove = (tagToRemove: string) => {
onChange(tags.filter((x) => x !== tagToRemove)); onChange(tags.filter((x) => x !== tagToRemove));
}; };
const onAdd = (event?: React.MouseEvent) => { const onAdd = (event?: React.MouseEvent | React.KeyboardEvent) => {
event?.preventDefault(); event?.preventDefault();
if (!tags.includes(newTagName)) { if (!tags.includes(newTagName)) {
onChange(tags.concat(newTagName)); onChange(tags.concat(newTagName));
} }
setNewName(''); setNewTagName('');
}; };
const onBlur = () => { const onBlur = () => {
@ -62,65 +62,61 @@ export const TagsInput: FC<Props> = ({
} }
}; };
const onKeyboardAdd = (event: KeyboardEvent) => { const onKeyboardAdd = (event: React.KeyboardEvent) => {
event.preventDefault();
if (event.key === 'Enter' && newTagName !== '') { if (event.key === 'Enter' && newTagName !== '') {
onChange(tags.concat(newTagName)); onAdd(event);
setNewName('');
} }
}; };
return ( return (
<div className={cx(styles.wrapper, className, width ? css({ width: theme.spacing(width) }) : '')}> <div className={cx(styles.wrapper, className, width ? css({ width: theme.spacing(width) }) : '')}>
<div className={tags?.length ? styles.tags : undefined}> <Input
{tags?.map((tag: string, index: number) => { id={id}
return <TagItem key={`${tag}-${index}`} name={tag} onRemove={onRemove} disabled={disabled} />; disabled={disabled}
})} placeholder={placeholder}
</div> onChange={onNameChange}
<div> value={newTagName}
<Input onKeyDown={onKeyboardAdd}
id={id} onBlur={onBlur}
disabled={disabled} invalid={invalid}
placeholder={placeholder} suffix={
onChange={onNameChange} <Button
value={newTagName} fill="text"
onKeyUp={onKeyboardAdd} className={styles.addButtonStyle}
onKeyDown={(e) => { onClick={onAdd}
// onKeyDown is triggered before onKeyUp, triggering submit behaviour on Enter press if this component size="md"
// is used inside forms. Moving onKeyboardAdd callback here doesn't work since text input is not captured in onKeyDown disabled={newTagName.length <= 0}
if (e.key === 'Enter') { >
e.preventDefault(); Add
} </Button>
}} }
onBlur={onBlur} />
invalid={invalid} {tags?.length > 0 && (
suffix={ <ul className={styles.tags}>
newTagName.length > 0 && ( {tags.map((tag) => (
<Button fill="text" className={styles.addButtonStyle} onClick={onAdd} size="md"> <TagItem key={tag} name={tag} onRemove={onRemove} disabled={disabled} />
Add ))}
</Button> </ul>
) )}
}
/>
</div>
</div> </div>
); );
}; };
const getStyles = (theme: GrafanaTheme) => ({ const getStyles = (theme: GrafanaTheme2) => ({
wrapper: css` wrapper: css`
min-height: ${theme.spacing.formInputHeight}px; min-height: ${theme.spacing(4)};
align-items: center;
display: flex; display: flex;
flex-direction: column;
gap: ${theme.spacing(1)};
flex-wrap: wrap; flex-wrap: wrap;
`, `,
tags: css` tags: css`
display: flex; display: flex;
justify-content: flex-start; justify-content: flex-start;
flex-wrap: wrap; flex-wrap: wrap;
margin-right: ${theme.spacing.xs}; gap: ${theme.spacing(0.5)};
`, `,
addButtonStyle: css` addButtonStyle: css`
margin: 0 -${theme.spacing.sm}; margin: 0 -${theme.spacing(1)};
`, `,
}); });

View File

@ -101,7 +101,7 @@ export function GeneralSettingsUnconnected({
<Input id="description-input" name="description" onBlur={onBlur} defaultValue={dashboard.description} /> <Input id="description-input" name="description" onBlur={onBlur} defaultValue={dashboard.description} />
</Field> </Field>
<Field label="Tags"> <Field label="Tags">
<TagsInput id="tags-input" tags={dashboard.tags} onChange={onTagsChange} /> <TagsInput id="tags-input" tags={dashboard.tags} onChange={onTagsChange} width={40} />
</Field> </Field>
<Field label="Folder"> <Field label="Folder">
<FolderPicker <FolderPicker

View File

@ -94,7 +94,7 @@ export const LinkSettingsEdit: React.FC<LinkSettingsEditProps> = ({ editLinkIdx,
{linkSettings.type === 'dashboards' && ( {linkSettings.type === 'dashboards' && (
<> <>
<Field label="With tags"> <Field label="With tags">
<TagsInput tags={linkSettings.tags} placeholder="add tags" onChange={onTagsChange} /> <TagsInput tags={linkSettings.tags} onChange={onTagsChange} />
</Field> </Field>
</> </>
)} )}

View File

@ -49,7 +49,7 @@ export const AnnotationEditor = (props: QueryEditorProps<GraphiteDatasource, Gra
<div className="gf-form"> <div className="gf-form">
<InlineFormLabel width={12}>Graphite events tags</InlineFormLabel> <InlineFormLabel width={12}>Graphite events tags</InlineFormLabel>
<TagsInput id="tags-input" tags={tags} onChange={onTagsChange} placeholder="Example: event_tag" /> <TagsInput id="tags-input" width={50} tags={tags} onChange={onTagsChange} placeholder="Example: event_tag" />
</div> </div>
</div> </div>
); );