Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { inputDefaultProps, inputStylesApiSelectors, tests } from '@mantine-tests/core';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { inputDefaultProps, inputStylesApiSelectors, render, tests } from '@mantine-tests/core';
import { TagsInput, TagsInputProps, TagsInputStylesNames } from './TagsInput';

const defaultProps: TagsInputProps = {
Expand Down Expand Up @@ -47,4 +49,22 @@ describe('@mantine/core/TagsInput', () => {
props: defaultProps,
selector: 'input',
});

it('isDuplicate test', async () => {
const user = userEvent.setup();
render(
<TagsInput
role="combobox"
data={['test-1']}
isDuplicate={(value) => value.startsWith('test')}
/>
);

const input = screen.getByRole('combobox');

await user.type(input, 'test-2');
await user.keyboard('{Enter}');

expect(screen.queryByText('test-2')).not.toBeInTheDocument();
});
});
12 changes: 9 additions & 3 deletions packages/@mantine/core/src/components/TagsInput/TagsInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ export interface TagsInputProps

/** Determines whether the value typed in by the user but not submitted should be accepted when the input is blurred, `true` by default */
acceptValueOnBlur?: boolean;

/** Custom function to determine if a tag is duplicate. Accepts tag value and array of current values. By default checks if tag exists case-insensitively. */
isDuplicate?: (value: string, currentValues: string[]) => boolean;
}

export type TagsInputFactory = Factory<{
Expand Down Expand Up @@ -192,6 +195,7 @@ export const TagsInput = factory<TagsInputFactory>((_props, ref) => {
onClear,
scrollAreaProps,
acceptValueOnBlur,
isDuplicate,
...others
} = props;

Expand Down Expand Up @@ -251,13 +255,15 @@ export const TagsInput = factory<TagsInputFactory>((_props, ref) => {
});

const handleValueSelect = (val: string) => {
const isDuplicate = _value.some((tag) => tag.toLowerCase() === val.toLowerCase());
const duplicateCheck = isDuplicate
? isDuplicate(val, _value)
: _value.some((tag) => tag.toLowerCase() === val.toLowerCase());

if (isDuplicate) {
if (duplicateCheck) {
onDuplicate?.(val);
}

if ((!isDuplicate || (isDuplicate && allowDuplicates)) && _value.length < maxTags!) {
if ((!duplicateCheck || (duplicateCheck && allowDuplicates)) && _value.length < maxTags!) {
onOptionSubmit?.(val);
handleSearchChange('');
if (val.length > 0) {
Expand Down