Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(PowerSearch): fix three editor bugs — searchSource, photo round-trip, creatable tokens (#1116)

Cindy Zhang70e297ab279f
diff --git a/apps/storybook/stories/Tokenizer.stories.tsx b/apps/storybook/stories/Tokenizer.stories.tsx
index d3192563e4..0651c04deb 100644
--- a/apps/storybook/stories/Tokenizer.stories.tsx
+++ b/apps/storybook/stories/Tokenizer.stories.tsx
@@ -294,3 +294,59 @@ export const WithEndContent: Story = {
},
name: 'With End Content',
};
+
+// Empty source for free-text-only tokenizers
+const emptySource: XDSSearchSource = {
+ search: () => [],
+ bootstrap: () => [],
+};
+
+export const Creatable: Story = {
+ render: args => {
+ const [tags, setTags] = useState<XDSSearchableItem[]>([]);
+ return (
+ <div>
+ <XDSTokenizer
+ {...args}
+ searchSource={emptySource}
+ value={tags}
+ onChange={(items, change) => {
+ setTags(items);
+ }}
+ hasCreate
+ placeholder="Type a tag and press Enter..."
+ />
+ <p style={{marginTop: 8, fontSize: 14, color: '#666'}}>
+ {tags.length} tag{tags.length !== 1 ? 's' : ''} added
+ </p>
+ </div>
+ );
+ },
+ args: {
+ label: 'Tags',
+ },
+ name: 'Creatable (Free Text)',
+};
+
+export const CreatableWithSearch: Story = {
+ render: args => {
+ const [value, setValue] = useState<XDSSearchableItem[]>([]);
+ return (
+ <XDSTokenizer
+ {...args}
+ searchSource={userSource}
+ value={value}
+ onChange={(items, change) => {
+ setValue(items);
+ }}
+ hasCreate
+ hasEntriesOnFocus
+ placeholder="Search or type a new name..."
+ />
+ );
+ },
+ args: {
+ label: 'Team Members',
+ },
+ name: 'Creatable + Search',
+};
diff --git a/internal/vibe-tests/creatable-naming-test/prompts.json b/internal/vibe-tests/creatable-naming-test/prompts.json
new file mode 100644
index 0000000000..21b6ab3ed2
--- /dev/null
+++ b/internal/vibe-tests/creatable-naming-test/prompts.json
@@ -0,0 +1,67 @@
+{
+ "name": "creatable-naming",
+ "description": "Vibe test comparing prop names for XDSTokenizer free-text token creation: isCreatable vs hasCreate vs hasAddNew",
+ "variants": [
+ "isCreatable",
+ "hasCreate",
+ "hasAddNew"
+ ],
+ "prompts": [
+ {
+ "id": "cr-1",
+ "category": "tag-input",
+ "prompt": "Build a blog post editor form with a title field, body textarea, and a tag input where users can type custom tags and add them. Tags don't come from a predefined list \u2014 users create whatever tags they want.",
+ "tests": "Basic free-text token creation, no search source needed",
+ "notes": "Core use case \u2014 does the LLM discover and use the creatable prop for a pure free-text tag input?"
+ },
+ {
+ "id": "cr-2",
+ "category": "tag-input",
+ "prompt": "Create a project settings page with a 'Labels' section. Users should be able to search from existing labels (Bug, Feature, Enhancement, Documentation, Question) but also type and create new custom labels that don't exist yet.",
+ "tests": "Hybrid: search source + creatable mode together",
+ "notes": "Tests whether the LLM combines searchSource with the creatable prop correctly"
+ },
+ {
+ "id": "cr-3",
+ "category": "invite-flow",
+ "prompt": "Build an invite flow where users type email addresses to invite team members. Each email becomes a token chip. Users should be able to type any email, not just pick from a list. Show validation that emails are properly formatted.",
+ "tests": "Free-text creation with validation pattern",
+ "notes": "Tests whether the LLM naturally reaches for creatable when building an email input"
+ },
+ {
+ "id": "cr-4",
+ "category": "filter-builder",
+ "prompt": "Create a search filter component for a log viewer. Users can add multiple search terms as token chips \u2014 each term is free text that they type. Include a clear-all button.",
+ "tests": "Free-text tokens in a non-tag context (search terms)",
+ "notes": "Tests whether 'creatable' naming generalizes beyond the tag metaphor"
+ },
+ {
+ "id": "cr-5",
+ "category": "tag-input",
+ "prompt": "Build a recipe ingredient entry. Users type ingredient names (like 'flour', 'sugar', 'vanilla extract') and each one becomes a chip. The list is open-ended \u2014 any ingredient name is valid. Show a count of total ingredients added.",
+ "tests": "Domain-specific free-text, count display alongside tokenizer",
+ "notes": "Tests creatable in a domain where no search source makes sense"
+ },
+ {
+ "id": "cr-6",
+ "category": "hybrid",
+ "prompt": "Build a skills selector for a job posting form. Provide a search source with common skills (React, TypeScript, Python, Java, CSS, SQL, Docker, AWS, Node.js, GraphQL) but let hiring managers also type and add niche skills that aren't in the predefined list.",
+ "tests": "Hybrid with onChange distinguishing created vs selected",
+ "notes": "Tests whether the LLM uses the change.type to distinguish 'add' vs 'create'"
+ },
+ {
+ "id": "cr-7",
+ "category": "filter-builder",
+ "prompt": "Create a CSV column mapper. Show a tokenizer for each target field where users can either search from detected CSV headers (Name, Email, Phone, Address, City, State, Zip) or type a custom column name if the CSV has different headers.",
+ "tests": "Multiple tokenizers with maxEntries=1 and creatable",
+ "notes": "Tests creatable with maxEntries constraint \u2014 single-select creatable typeahead pattern"
+ },
+ {
+ "id": "cr-8",
+ "category": "invite-flow",
+ "prompt": "Build a notification rules editor. Users configure alert recipients by typing Slack channel names (like #engineering, #incidents, #on-call). Channels are free-text \u2014 no predefined list. Each channel becomes a removable chip. Limit to 5 channels max.",
+ "tests": "Free-text creation with maxEntries limit",
+ "notes": "Tests creatable + maxEntries interaction"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/internal/vibe-tests/creatable-naming-test/variant-hasAddNew.md b/internal/vibe-tests/creatable-naming-test/variant-hasAddNew.md
new file mode 100644
index 0000000000..893d833e8f
--- /dev/null
+++ b/internal/vibe-tests/creatable-naming-test/variant-hasAddNew.md
@@ -0,0 +1,107 @@
+# XDSTokenizer — Multi-select Typeahead with Token Chips
+
+A multi-select input that combines typeahead search with token chips. Users search for items via a dropdown and selected items appear as removable chips. Supports free-text token creation for open-ended inputs like tags, emails, or custom values.
+
+## Import
+
+```tsx
+import {XDSTokenizer} from '@xds/core';
+```
+
+## Basic Usage — Search Only
+
+```tsx
+const userSource = {
+ search: query => users.filter(u => u.label.includes(query)),
+ bootstrap: () => users.slice(0, 5),
+};
+
+<XDSTokenizer
+ label="Team Members"
+ searchSource={userSource}
+ value={selected}
+ onChange={items => setSelected(items)}
+ placeholder="Search people..."
+/>;
+```
+
+## Free-Text Token Creation
+
+When `hasAddNew` is true, users can type any value and commit it as a new token — even if the search source returns no results. A "Create" option appears in the dropdown.
+
+```tsx
+// Tags — no search source, pure free-text
+const emptySource = {search: () => [], bootstrap: () => []};
+
+<XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={tags}
+ onChange={(items, change) => {
+ setTags(items);
+ if (change.type === 'addNew') {
+ console.log('New tag created:', change.item.label);
+ }
+ }}
+ hasAddNew
+ placeholder="Type a tag and press Enter..."
+/>;
+```
+
+## Hybrid — Search + Create
+
+Combine a search source with `hasAddNew` so users can pick existing items OR create new ones:
+
+```tsx
+<XDSTokenizer
+ label="Skills"
+ searchSource={skillSource}
+ value={skills}
+ onChange={(items, change) => {
+ setSkills(items);
+ if (change.type === 'addNew') {
+ // Persist the new skill to the backend
+ saveNewSkill(change.item.label);
+ }
+ }}
+ hasAddNew
+ placeholder="Search or add skills..."
+/>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| ------------------- | ---------------------------------- | ------- | ------------------------------------------------------------------------------------------- |
+| `label` | `string` | — | Accessible label (required) |
+| `searchSource` | `XDSSearchSource<T>` | — | Data source for search + bootstrap (required) |
+| `value` | `T[]` | — | Currently selected items (required) |
+| `onChange` | `(items: T[], change) => void` | — | Selection change callback. `change.type` is `'add'`, `'addNew'`, `'remove'`, or `'reorder'` |
+| `hasAddNew` | `boolean` | `false` | Enable free-text token creation from typed input |
+| `placeholder` | `string` | — | Input placeholder (shown when no tokens selected) |
+| `maxEntries` | `number` | — | Maximum selections allowed |
+| `hasClear` | `boolean` | `false` | Show clear-all button |
+| `renderItem` | `(item: T) => ReactNode` | — | Custom dropdown item renderer |
+| `renderToken` | `(item: T, onRemove) => ReactNode` | — | Custom token chip renderer |
+| `hasEntriesOnFocus` | `boolean` | `false` | Show bootstrap results on focus |
+| `isDisabled` | `boolean` | `false` | Disable the input |
+| `debounceMs` | `number` | `150` | Search debounce delay (0 for sync sources) |
+| `size` | `'sm' \| 'md'` | `'md'` | Input and token size |
+
+## Change Types
+
+The `onChange` callback's second argument tells you what happened:
+
+| `change.type` | Meaning |
+| ------------- | ------------------------------------------------ |
+| `'add'` | User selected an existing item from the dropdown |
+| `'addNew'` | User created a new token from typed free-text |
+| `'remove'` | User removed a token |
+| `'reorder'` | Tokens were reordered |
+
+## Keyboard
+
+- **Enter** — Select highlighted item, or create a token from typed text when `hasAddNew` is true
+- **Backspace** — On empty input, removes the last token
+- **Arrow keys** — Navigate dropdown items
+- **Escape** — Close dropdown
diff --git a/internal/vibe-tests/creatable-naming-test/variant-hasCreate.md b/internal/vibe-tests/creatable-naming-test/variant-hasCreate.md
new file mode 100644
index 0000000000..f4be88fd5e
--- /dev/null
+++ b/internal/vibe-tests/creatable-naming-test/variant-hasCreate.md
@@ -0,0 +1,107 @@
+# XDSTokenizer — Multi-select Typeahead with Token Chips
+
+A multi-select input that combines typeahead search with token chips. Users search for items via a dropdown and selected items appear as removable chips. Supports free-text token creation for open-ended inputs like tags, emails, or custom values.
+
+## Import
+
+```tsx
+import {XDSTokenizer} from '@xds/core';
+```
+
+## Basic Usage — Search Only
+
+```tsx
+const userSource = {
+ search: query => users.filter(u => u.label.includes(query)),
+ bootstrap: () => users.slice(0, 5),
+};
+
+<XDSTokenizer
+ label="Team Members"
+ searchSource={userSource}
+ value={selected}
+ onChange={items => setSelected(items)}
+ placeholder="Search people..."
+/>;
+```
+
+## Free-Text Token Creation
+
+When `hasCreate` is true, users can type any value and commit it as a new token — even if the search source returns no results. A "Create" option appears in the dropdown.
+
+```tsx
+// Tags — no search source, pure free-text
+const emptySource = {search: () => [], bootstrap: () => []};
+
+<XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={tags}
+ onChange={(items, change) => {
+ setTags(items);
+ if (change.type === 'create') {
+ console.log('New tag created:', change.item.label);
+ }
+ }}
+ hasCreate
+ placeholder="Type a tag and press Enter..."
+/>;
+```
+
+## Hybrid — Search + Create
+
+Combine a search source with `hasCreate` so users can pick existing items OR create new ones:
+
+```tsx
+<XDSTokenizer
+ label="Skills"
+ searchSource={skillSource}
+ value={skills}
+ onChange={(items, change) => {
+ setSkills(items);
+ if (change.type === 'create') {
+ // Persist the new skill to the backend
+ saveNewSkill(change.item.label);
+ }
+ }}
+ hasCreate
+ placeholder="Search or add skills..."
+/>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| ------------------- | ---------------------------------- | ------- | ------------------------------------------------------------------------------------------- |
+| `label` | `string` | — | Accessible label (required) |
+| `searchSource` | `XDSSearchSource<T>` | — | Data source for search + bootstrap (required) |
+| `value` | `T[]` | — | Currently selected items (required) |
+| `onChange` | `(items: T[], change) => void` | — | Selection change callback. `change.type` is `'add'`, `'create'`, `'remove'`, or `'reorder'` |
+| `hasCreate` | `boolean` | `false` | Enable free-text token creation from typed input |
+| `placeholder` | `string` | — | Input placeholder (shown when no tokens selected) |
+| `maxEntries` | `number` | — | Maximum selections allowed |
+| `hasClear` | `boolean` | `false` | Show clear-all button |
+| `renderItem` | `(item: T) => ReactNode` | — | Custom dropdown item renderer |
+| `renderToken` | `(item: T, onRemove) => ReactNode` | — | Custom token chip renderer |
+| `hasEntriesOnFocus` | `boolean` | `false` | Show bootstrap results on focus |
+| `isDisabled` | `boolean` | `false` | Disable the input |
+| `debounceMs` | `number` | `150` | Search debounce delay (0 for sync sources) |
+| `size` | `'sm' \| 'md'` | `'md'` | Input and token size |
+
+## Change Types
+
+The `onChange` callback's second argument tells you what happened:
+
+| `change.type` | Meaning |
+| ------------- | ------------------------------------------------ |
+| `'add'` | User selected an existing item from the dropdown |
+| `'create'` | User created a new token from typed free-text |
+| `'remove'` | User removed a token |
+| `'reorder'` | Tokens were reordered |
+
+## Keyboard
+
+- **Enter** — Select highlighted item, or create a token from typed text when `hasCreate` is true
+- **Backspace** — On empty input, removes the last token
+- **Arrow keys** — Navigate dropdown items
+- **Escape** — Close dropdown
diff --git a/internal/vibe-tests/creatable-naming-test/variant-isCreatable.md b/internal/vibe-tests/creatable-naming-test/variant-isCreatable.md
new file mode 100644
index 0000000000..391958686f
--- /dev/null
+++ b/internal/vibe-tests/creatable-naming-test/variant-isCreatable.md
@@ -0,0 +1,107 @@
+# XDSTokenizer — Multi-select Typeahead with Token Chips
+
+A multi-select input that combines typeahead search with token chips. Users search for items via a dropdown and selected items appear as removable chips. Supports free-text token creation for open-ended inputs like tags, emails, or custom values.
+
+## Import
+
+```tsx
+import {XDSTokenizer} from '@xds/core';
+```
+
+## Basic Usage — Search Only
+
+```tsx
+const userSource = {
+ search: query => users.filter(u => u.label.includes(query)),
+ bootstrap: () => users.slice(0, 5),
+};
+
+<XDSTokenizer
+ label="Team Members"
+ searchSource={userSource}
+ value={selected}
+ onChange={items => setSelected(items)}
+ placeholder="Search people..."
+/>;
+```
+
+## Free-Text Token Creation
+
+When `isCreatable` is true, users can type any value and commit it as a new token — even if the search source returns no results. A "Create" option appears in the dropdown.
+
+```tsx
+// Tags — no search source, pure free-text
+const emptySource = {search: () => [], bootstrap: () => []};
+
+<XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={tags}
+ onChange={(items, change) => {
+ setTags(items);
+ if (change.type === 'create') {
+ console.log('New tag created:', change.item.label);
+ }
+ }}
+ isCreatable
+ placeholder="Type a tag and press Enter..."
+/>;
+```
+
+## Hybrid — Search + Create
+
+Combine a search source with `isCreatable` so users can pick existing items OR create new ones:
+
+```tsx
+<XDSTokenizer
+ label="Skills"
+ searchSource={skillSource}
+ value={skills}
+ onChange={(items, change) => {
+ setSkills(items);
+ if (change.type === 'create') {
+ // Persist the new skill to the backend
+ saveNewSkill(change.item.label);
+ }
+ }}
+ isCreatable
+ placeholder="Search or add skills..."
+/>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| ------------------- | ---------------------------------- | ------- | ------------------------------------------------------------------------------------------- |
+| `label` | `string` | — | Accessible label (required) |
+| `searchSource` | `XDSSearchSource<T>` | — | Data source for search + bootstrap (required) |
+| `value` | `T[]` | — | Currently selected items (required) |
+| `onChange` | `(items: T[], change) => void` | — | Selection change callback. `change.type` is `'add'`, `'create'`, `'remove'`, or `'reorder'` |
+| `isCreatable` | `boolean` | `false` | Enable free-text token creation from typed input |
+| `placeholder` | `string` | — | Input placeholder (shown when no tokens selected) |
+| `maxEntries` | `number` | — | Maximum selections allowed |
+| `hasClear` | `boolean` | `false` | Show clear-all button |
+| `renderItem` | `(item: T) => ReactNode` | — | Custom dropdown item renderer |
+| `renderToken` | `(item: T, onRemove) => ReactNode` | — | Custom token chip renderer |
+| `hasEntriesOnFocus` | `boolean` | `false` | Show bootstrap results on focus |
+| `isDisabled` | `boolean` | `false` | Disable the input |
+| `debounceMs` | `number` | `150` | Search debounce delay (0 for sync sources) |
+| `size` | `'sm' \| 'md'` | `'md'` | Input and token size |
+
+## Change Types
+
+The `onChange` callback's second argument tells you what happened:
+
+| `change.type` | Meaning |
+| ------------- | ------------------------------------------------ |
+| `'add'` | User selected an existing item from the dropdown |
+| `'create'` | User created a new token from typed free-text |
+| `'remove'` | User removed a token |
+| `'reorder'` | Tokens were reordered |
+
+## Keyboard
+
+- **Enter** — Select highlighted item, or create a token from typed text when `isCreatable` is true
+- **Backspace** — On empty input, removes the last token
+- **Arrow keys** — Navigate dropdown items
+- **Escape** — Close dropdown
diff --git a/packages/core/src/PowerSearch/PowerSearchValueEditor.test.tsx b/packages/core/src/PowerSearch/PowerSearchValueEditor.test.tsx
new file mode 100644
index 0000000000..18415593a0
--- /dev/null
+++ b/packages/core/src/PowerSearch/PowerSearchValueEditor.test.tsx
@@ -0,0 +1,407 @@
+/**
+ * @file PowerSearchValueEditor.test.tsx
+ * @input Uses vitest, @testing-library/react, PowerSearchValueEditor
+ * @output Unit tests for PowerSearch editor bugs #1103, #1106, #1107
+ * @position Testing; validates PowerSearchValueEditor.tsx
+ */
+
+import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
+import {render, screen, fireEvent, act} from '@testing-library/react';
+import {PowerSearchValueEditor} from './PowerSearchValueEditor';
+import type {
+ OperatorValue,
+ FilterValue,
+ FilterValueEntityList,
+ PowerSearchEntity,
+} from './types';
+import type {InternalConfig} from './useInternalConfig';
+import type {XDSSearchableItem, XDSSearchSource} from '../Typeahead/types';
+
+// =============================================================================
+// Test infrastructure
+// =============================================================================
+
+const originalMatches = HTMLElement.prototype.matches;
+const popoverOpenState = new WeakMap<HTMLElement, boolean>();
+
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+beforeAll(() => {
+ globalThis.ResizeObserver =
+ MockResizeObserver as unknown as typeof ResizeObserver;
+ HTMLElement.prototype.showPopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, true);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'open'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.hidePopover = vi.fn(function (this: HTMLElement) {
+ popoverOpenState.set(this, false);
+ const event = new Event('toggle');
+ Object.defineProperty(event, 'newState', {value: 'closed'});
+ this.dispatchEvent(event);
+ });
+ HTMLElement.prototype.matches = function (selector: string) {
+ if (selector === ':popover-open') {
+ return popoverOpenState.get(this) ?? false;
+ }
+ return originalMatches.call(this, selector);
+ };
+});
+
+afterAll(() => {
+ HTMLElement.prototype.matches = originalMatches;
+});
+
+// Minimal config stub — editors don't use it directly
+const stubConfig: InternalConfig = {
+ fieldsMap: new Map(),
+ operatorsMap: new Map(),
+} as unknown as InternalConfig;
+
+// =============================================================================
+// Helpers
+// =============================================================================
+
+function createSearchSource(
+ items: XDSSearchableItem[],
+): XDSSearchSource<XDSSearchableItem> {
+ return {
+ search: (query: string) =>
+ items.filter(i => i.label.toLowerCase().includes(query.toLowerCase())),
+ bootstrap: () => items.slice(0, 5),
+ };
+}
+
+// =============================================================================
+// #1103 — StringEditor ignores searchSource
+// =============================================================================
+
+describe('StringEditor (#1103)', () => {
+ it('renders a typeahead when searchSource is provided', () => {
+ const source = createSearchSource([
+ {id: 'us', label: 'United States'},
+ {id: 'uk', label: 'United Kingdom'},
+ ]);
+
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'string', searchSource: source}}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // Should render a combobox (typeahead), not a plain textbox
+ const combobox = screen.queryByRole('combobox');
+ expect(combobox).toBeInTheDocument();
+ });
+
+ it('renders a plain text input when no searchSource', () => {
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'string'}}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // Should render a textbox (XDSTextInput), not a combobox
+ const textbox = screen.queryByRole('textbox');
+ expect(textbox).toBeInTheDocument();
+ });
+
+ it('calls onChange with string FilterValue when typeahead item is selected', async () => {
+ const source = createSearchSource([
+ {id: 'us', label: 'United States'},
+ {id: 'uk', label: 'United Kingdom'},
+ ]);
+
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'string', searchSource: source}}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ const combobox = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(combobox, {target: {value: 'United'}});
+ });
+
+ // Wait for debounce + results
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 200));
+ });
+
+ // Select the first result
+ const option = screen.queryByText('United States');
+ if (option) {
+ fireEvent.click(option);
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({type: 'string'}),
+ true,
+ );
+ }
+ });
+
+ it('allows arbitrary string input when isArbitraryStringAllowed + searchSource', () => {
+ const source = createSearchSource([{id: 'us', label: 'United States'}]);
+
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{
+ type: 'string',
+ searchSource: source,
+ isArbitraryStringAllowed: true,
+ }}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // Should still render a combobox (typeahead with suggestions)
+ const combobox = screen.queryByRole('combobox');
+ expect(combobox).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// #1106 — EntityListEditor drops photo, no renderItem
+// =============================================================================
+
+describe('EntityListEditor (#1106)', () => {
+ const entitiesWithPhoto: PowerSearchEntity[] = [
+ {id: 'u1', label: 'Alice', photo: 'https://example.com/alice.jpg'},
+ {id: 'u2', label: 'Bob', photo: 'https://example.com/bob.jpg'},
+ ];
+
+ const entitySource = createSearchSource(
+ entitiesWithPhoto.map(e => ({
+ id: e.id,
+ label: e.label,
+ auxiliaryData: {photo: e.photo},
+ })),
+ );
+
+ it('round-trips photo through onChange', () => {
+ const onChange = vi.fn();
+ const filterValue: FilterValueEntityList = {
+ type: 'entity_list',
+ value: entitiesWithPhoto,
+ };
+
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'entity_list', searchSource: entitySource}}
+ filterValue={filterValue}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // Tokens for Alice and Bob should render
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ expect(screen.getByText('Bob')).toBeInTheDocument();
+
+ // Remove Alice — the remaining value should still have Bob's photo
+ const removeBtn = screen.getByRole('button', {name: 'Remove Alice'});
+ fireEvent.click(removeBtn);
+
+ expect(onChange).toHaveBeenCalled();
+ const newFilterValue = onChange.mock.calls[0][0] as FilterValueEntityList;
+ expect(newFilterValue.type).toBe('entity_list');
+ expect(newFilterValue.value).toHaveLength(1);
+ expect(newFilterValue.value[0].id).toBe('u2');
+ expect(newFilterValue.value[0].label).toBe('Bob');
+ // Bug #1106: photo should be preserved, not dropped
+ expect(newFilterValue.value[0].photo).toBe('https://example.com/bob.jpg');
+ });
+
+ it('preserves photo when mapping filter value to tokenizer', () => {
+ const onChange = vi.fn();
+ const filterValue: FilterValueEntityList = {
+ type: 'entity_list',
+ value: [
+ {id: 'u1', label: 'Alice', photo: 'https://example.com/alice.jpg'},
+ ],
+ };
+
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'entity_list', searchSource: entitySource}}
+ filterValue={filterValue}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // The token should render — verifies the entity was properly mapped
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ });
+
+ it('passes renderItem from operatorValue to XDSTokenizer', () => {
+ const customRenderItem = vi.fn((item: {id: string; label: string}) => (
+ <span data-testid="custom-render">{item.label}</span>
+ ));
+
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{
+ type: 'entity_list',
+ searchSource: entitySource,
+ renderItem: customRenderItem,
+ }}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // The tokenizer should render — renderItem is passed through
+ // (we can't easily assert it was passed as a prop in unit tests,
+ // but we verify the component renders without error with renderItem)
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ });
+});
+
+// =============================================================================
+// #1107 — StringListEditor without searchSource is non-functional
+// =============================================================================
+
+describe('StringListEditor (#1107)', () => {
+ it('shows a "Create" item in the dropdown when typing free-text without searchSource', async () => {
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'string_list'}}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+
+ // Type a free-text value — should show 'Create "my-tag"' in the dropdown
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'my-tag'}});
+ });
+
+ // Wait for debounce
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ const createOption = screen.queryByText('Create "my-tag"');
+ expect(createOption).toBeInTheDocument();
+ });
+
+ it('commits free-text token when clicking the Create item', async () => {
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'string_list'}}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'my-tag'}});
+ });
+
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ const createOption = screen.getByText('Create "my-tag"');
+ await act(async () => {
+ fireEvent.click(createOption);
+ });
+
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'string_list',
+ value: expect.arrayContaining(['my-tag']),
+ }),
+ );
+ });
+
+ it('commits free-text via Enter when the Create item is highlighted', async () => {
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{
+ type: 'string_list',
+ isArbitraryStringAllowed: true,
+ }}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'custom-value'}});
+ });
+
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ // Arrow down to highlight the Create item, then Enter
+ await act(async () => {
+ fireEvent.keyDown(input, {key: 'ArrowDown'});
+ });
+ await act(async () => {
+ fireEvent.keyDown(input, {key: 'Enter'});
+ });
+
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'string_list',
+ value: expect.arrayContaining(['custom-value']),
+ }),
+ );
+ });
+
+ it('still works with a searchSource (existing behavior)', () => {
+ const source = createSearchSource([
+ {id: 'tag1', label: 'frontend'},
+ {id: 'tag2', label: 'backend'},
+ ]);
+
+ const onChange = vi.fn();
+ render(
+ <PowerSearchValueEditor
+ operatorValue={{type: 'string_list', searchSource: source}}
+ filterValue={undefined}
+ onChange={onChange}
+ config={stubConfig}
+ />,
+ );
+
+ // Should render the tokenizer with a combobox
+ expect(screen.getByRole('combobox')).toBeInTheDocument();
+ });
+});
diff --git a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
index 42515e3af0..1664a0b176 100644
--- a/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
+++ b/packages/core/src/PowerSearch/PowerSearchValueEditor.tsx
@@ -10,7 +10,6 @@
* - /packages/core/src/PowerSearch/index.ts
*/
-
import React, {useCallback, useMemo} from 'react';
import type {
OperatorValue,
@@ -30,6 +29,7 @@ import {XDSDateInput} from '../DateInput';
import {XDSTimeInput} from '../TimeInput';
import {XDSSelector} from '../Selector';
import {XDSTokenizer} from '../Tokenizer';
+import {XDSTypeahead} from '../Typeahead';
export interface PowerSearchValueEditorProps {
operatorValue: OperatorValue;
@@ -85,6 +85,32 @@ function StringEditor({
}) {
const currentValue = filterValue?.type === 'string' ? filterValue.value : '';
+ // When a searchSource is provided, render a typeahead instead of a plain
+ // text input so users get suggestions (#1103).
+ if (operatorValue.searchSource) {
+ const selectedItem: XDSSearchableItem | null = currentValue
+ ? {id: currentValue, label: currentValue}
+ : null;
+
+ return (
+ <XDSTypeahead
+ label="Value"
+ isLabelHidden
+ searchSource={operatorValue.searchSource}
+ value={selectedItem}
+ onChange={item => {
+ if (item) {
+ onChange({type: 'string', value: item.label}, true);
+ } else {
+ onChange({type: 'string', value: ''});
+ }
+ }}
+ placeholder="Search..."
+ debounceMs={150}
+ />
+ );
+ }
+
return (
<XDSTextInput
label="Value"
@@ -123,6 +149,11 @@ function StringListEditor({
};
}, [operatorValue.searchSource]);
+ // Enable creatable mode when no searchSource is provided (free-text tags)
+ // or when isArbitraryStringAllowed is explicitly set (#1107).
+ const hasCreate =
+ operatorValue.isArbitraryStringAllowed || !operatorValue.searchSource;
+
return (
<XDSTokenizer
label="Values"
@@ -137,6 +168,7 @@ function StringListEditor({
}}
placeholder="Add values..."
debounceMs={operatorValue.searchSource ? 150 : 0}
+ hasCreate={hasCreate}
/>
);
}
@@ -497,11 +529,13 @@ function EntityListEditor({
};
}, [operatorValue.searchSource]);
+ // Preserve photo in auxiliaryData so it round-trips through the tokenizer (#1106).
const currentValue: XDSSearchableItem[] = useMemo(() => {
if (filterValue?.type !== 'entity_list') return [];
return filterValue.value.map((entity: PowerSearchEntity) => ({
id: entity.id,
label: entity.label,
+ auxiliaryData: entity.photo ? {photo: entity.photo} : undefined,
}));
}, [filterValue]);
@@ -514,12 +548,18 @@ function EntityListEditor({
onChange={items => {
onChange({
type: 'entity_list',
- value: items.map(item => ({
- id: item.id,
- label: item.label,
- })),
+ // Round-trip photo from auxiliaryData back to PowerSearchEntity (#1106).
+ value: items.map(item => {
+ const aux = item.auxiliaryData as {photo?: string} | undefined;
+ return {
+ id: item.id,
+ label: item.label,
+ ...(aux?.photo ? {photo: aux.photo} : {}),
+ };
+ }),
});
}}
+ renderItem={operatorValue.renderItem}
placeholder="Search..."
debounceMs={operatorValue.searchSource ? 150 : 0}
/>
diff --git a/packages/core/src/PowerSearch/types.ts b/packages/core/src/PowerSearch/types.ts
index 143fddc60f..e3413d52e6 100644
--- a/packages/core/src/PowerSearch/types.ts
+++ b/packages/core/src/PowerSearch/types.ts
@@ -103,6 +103,8 @@ export interface EntityListOperatorValue {
readonly isArbitraryStringAllowed?: boolean;
/** Tokenization config for paste behavior. */
readonly tokenization?: OperatorTokenizationConfig;
+ /** Custom renderer for items in the search dropdown. */
+ readonly renderItem?: (item: XDSSearchableItem) => ReactNode;
}
export interface CustomOperatorValue {
diff --git a/packages/core/src/Tokenizer/Tokenizer.doc.mjs b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
index 6d63b885bb..154ba1fb39 100644
--- a/packages/core/src/Tokenizer/Tokenizer.doc.mjs
+++ b/packages/core/src/Tokenizer/Tokenizer.doc.mjs
@@ -29,7 +29,7 @@ export const docs = {
name: 'onChange',
type: '(items: T[], change: XDSTokenizerChange<T>) => void',
description:
- "Called when selection changes. The change argument includes the affected item and type ('add' | 'remove' | 'reorder').",
+ "Called when selection changes. The change argument includes the affected item and type ('add' | 'create' | 'remove' | 'reorder').",
required: true,
},
{
@@ -139,6 +139,13 @@ export const docs = {
'Debounce delay in ms before triggering search. Set to 0 for synchronous sources.',
default: '150',
},
+ {
+ name: 'hasCreate',
+ type: 'boolean',
+ description:
+ "Allow users to create new tokens from free-text input. When true, a \"Create\" option appears in the dropdown for typed text that doesn't match existing results. The onChange change type is 'create' for these items.",
+ default: 'false',
+ },
{
name: 'onChangeQuery',
type: '(query: string) => void',
@@ -185,6 +192,24 @@ export const docs = {
maxEntries={5}
hasClear
placeholder="Add up to 5 tags..."
+/>`,
+ },
+ {
+ label: 'Free-text tags (hasCreate)',
+ code: `const emptySource = { search: () => [], bootstrap: () => [] };
+
+<XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={tags}
+ onChange={(items, change) => {
+ setTags(items);
+ if (change.type === 'create') {
+ console.log('New tag:', change.item.label);
+ }
+ }}
+ hasCreate
+ placeholder="Type a tag and press Enter..."
/>`,
},
{
@@ -212,7 +237,8 @@ export const docs = {
'Clear all button for bulk removal of all tokens',
'Custom token and item rendering via renderToken and renderItem',
'Backspace on empty input removes the last token',
- "Change metadata: onChange receives a second argument with type ('add' | 'remove' | 'reorder')",
+ "Change metadata: onChange receives a second argument with type ('add' | 'create' | 'remove' | 'reorder')",
+ 'Free-text token creation via hasCreate prop — shows a "Create" option in the dropdown for new values',
],
theming: {
targets: [
@@ -258,7 +284,7 @@ export const docsZh = {
name: 'onChange',
type: '(items: T[], change: XDSTokenizerChange<T>) => void',
description:
- "选择变更时调用。change 参数包含受影响的项目和类型('add' | 'remove' | 'reorder')。",
+ "选择变更时调用。change 参数包含受影响的项目和类型('add' | 'create' | 'remove' | 'reorder')。",
required: true,
},
{
@@ -441,7 +467,8 @@ export const docsZh = {
'全部清除按钮用于批量移除所有标记',
'通过 renderToken 和 renderItem 自定义标记和项目渲染',
'在空输入框上按退格键移除最后一个标记',
- "变更元数据:onChange 接收第二个参数,包含类型('add' | 'remove' | 'reorder')",
+ "变更元数据:onChange 接收第二个参数,包含类型('add' | 'create' | 'remove' | 'reorder')",
+ '通过 hasCreate 属性支持自由文本令牌创建 — 在下拉列表中为新值显示 "Create" 选项',
],
theming: {
targets: [
@@ -468,7 +495,8 @@ export const docsDense = {
'Clear all button for bulk removal of all tokens',
'Custom token+item rendering via renderToken+renderItem',
'Backspace on empty input removes last token',
- "Change metadata: onChange receives second arg w/ type ('add'|'remove'|'reorder')",
+ "Change metadata: onChange receives second arg w/ type ('add'|'create'|'remove'|'reorder')",
+ 'Free-text token creation via hasCreate — "Create" option in dropdown for new values',
],
accessibility: [
'Wrapped in XDSField for label, description, status message association.',
@@ -481,7 +509,8 @@ export const docsDense = {
label: 'Accessible label for input.',
searchSource: 'Data source w/ search+bootstrap methods for populating dropdown.',
value: 'Array of currently selected items.',
- onChange: "Fired on selection change. Change arg includes affected item+type ('add'|'remove'|'reorder').",
+ onChange: "Fired on selection change. Change arg includes affected item+type ('add'|'create'|'remove'|'reorder').",
+ hasCreate: 'Enable free-text token creation. Shows "Create" dropdown option for unmatched typed text.',
placeholder: 'Input placeholder. Only shown when no tokens selected.',
maxEntries: 'Max selections allowed. Input hidden at limit.',
hasClear: 'Clear-all button for bulk removal.',
diff --git a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx b/packages/core/src/Tokenizer/XDSTokenizer.test.tsx
index 3a7f98a011..6ec7186d8a 100644
--- a/packages/core/src/Tokenizer/XDSTokenizer.test.tsx
+++ b/packages/core/src/Tokenizer/XDSTokenizer.test.tsx
@@ -467,4 +467,164 @@ describe('XDSTokenizer', () => {
expect(wrapper).toBeInTheDocument();
});
});
+
+ describe('hasCreate', () => {
+ const emptySource: XDSSearchSource = {
+ search: () => [],
+ bootstrap: () => [],
+ };
+
+ it('shows a "Create" option when typing with hasCreate', async () => {
+ render(
+ <XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'new-tag'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ expect(screen.queryByText('Create "new-tag"')).toBeInTheDocument();
+ });
+
+ it('fires onChange with type "create" when the Create item is clicked', async () => {
+ const onChange = vi.fn();
+ render(
+ <XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={[]}
+ onChange={onChange}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'new-tag'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ const createOption = screen.getByText('Create "new-tag"');
+ await act(async () => {
+ fireEvent.click(createOption);
+ });
+
+ expect(onChange).toHaveBeenCalledWith(
+ [{id: 'new-tag', label: 'new-tag'}],
+ {item: {id: 'new-tag', label: 'new-tag'}, type: 'create'},
+ );
+ });
+
+ it('does not show Create option for already-selected values', async () => {
+ render(
+ <XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={[{id: 'existing', label: 'existing'}]}
+ onChange={() => {}}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'existing'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ expect(screen.queryByText('Create "existing"')).not.toBeInTheDocument();
+ });
+
+ it('does not show Create option when hasCreate is false', async () => {
+ render(
+ <XDSTokenizer
+ label="Tags"
+ searchSource={emptySource}
+ value={[]}
+ onChange={() => {}}
+ hasCreate={false}
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'something'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ expect(screen.queryByText('Create "something"')).not.toBeInTheDocument();
+ });
+
+ it('appends Create option alongside real search results', async () => {
+ const onChange = vi.fn();
+ render(
+ <XDSTokenizer
+ label="Tags"
+ searchSource={userSource}
+ value={[]}
+ onChange={onChange}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ // "Ali" matches Alice but "Ali" itself is a new value
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'Ali'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ // Both the real result and the Create option should appear
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ expect(screen.getByText('Create "Ali"')).toBeInTheDocument();
+ });
+
+ it('does not show Create when typed text exactly matches a result label', async () => {
+ render(
+ <XDSTokenizer
+ label="Tags"
+ searchSource={userSource}
+ value={[]}
+ onChange={() => {}}
+ hasCreate
+ debounceMs={0}
+ />,
+ );
+
+ const input = screen.getByRole('combobox');
+ await act(async () => {
+ fireEvent.change(input, {target: {value: 'Alice'}});
+ });
+ await act(async () => {
+ await new Promise(r => setTimeout(r, 50));
+ });
+
+ // "Alice" exactly matches a result — no Create option
+ expect(screen.getByText('Alice')).toBeInTheDocument();
+ expect(screen.queryByText('Create "Alice"')).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/packages/core/src/Tokenizer/XDSTokenizer.tsx b/packages/core/src/Tokenizer/XDSTokenizer.tsx
index 9b607d7b1e..f4f0e015ed 100644
--- a/packages/core/src/Tokenizer/XDSTokenizer.tsx
+++ b/packages/core/src/Tokenizer/XDSTokenizer.tsx
@@ -62,6 +62,7 @@ export type {
*/
export type XDSTokenizerChange<T extends XDSSearchableItem> =
| {item: T; type: 'add'}
+ | {item: T; type: 'create'}
| {item: T; type: 'remove'}
| {type: 'reorder'};
@@ -155,6 +156,13 @@ export interface XDSTokenizerProps<T extends XDSSearchableItem> {
* @default 150
*/
debounceMs?: number;
+ /**
+ * Allow users to create new tokens from free-text input.
+ * When true, pressing Enter with text in the input commits the typed value
+ * as a new token — even if the search source returned no results.
+ * @default false
+ */
+ hasCreate?: boolean;
/** Query change callback. */
onChangeQuery?: (query: string) => void;
/**
@@ -287,6 +295,10 @@ const styles = stylex.create({
// Component
// =============================================================================
+// Sentinel prefix for creatable items — used to distinguish
+// "Create: X" suggestions from real search results.
+const CREATABLE_ID_PREFIX = '__xds_create__';
+
/**
* Multi-select input with token chips and typeahead search.
*
@@ -349,6 +361,7 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
size = 'md',
tokenOverflowBehavior = 'none',
debounceMs,
+ hasCreate = false,
onChangeQuery,
xstyle,
className,
@@ -443,18 +456,43 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
[value],
);
+ // Track the current query for creatable mode
+ const [creatableQuery, setCreatableQuery] = useState('');
+
const filteredSource: XDSSearchSource<T> = useMemo(
() => ({
search: async (query: string) => {
const results = await searchSource.search(query);
- return results.filter(item => !selectedIds.has(item.id));
+ const filtered = results.filter(item => !selectedIds.has(item.id));
+
+ // Append a "Create: X" synthetic item when hasCreate is true,
+ // the user has typed something, and it doesn't exactly match an
+ // existing result.
+ if (hasCreate && query.trim()) {
+ const trimmed = query.trim();
+ const alreadyExists =
+ selectedIds.has(trimmed) ||
+ filtered.some(
+ item => item.label.toLowerCase() === trimmed.toLowerCase(),
+ );
+ if (!alreadyExists) {
+ const creatableItem = {
+ id: `${CREATABLE_ID_PREFIX}${trimmed}`,
+ label: `Create "${trimmed}"`,
+ auxiliaryData: {__createdValue: trimmed},
+ } as unknown as T;
+ filtered.push(creatableItem);
+ }
+ }
+
+ return filtered;
},
bootstrap: async () => {
const results = await searchSource.bootstrap();
return results.filter(item => !selectedIds.has(item.id));
},
}),
- [searchSource, selectedIds],
+ [searchSource, selectedIds, hasCreate],
);
const emptySource: XDSSearchSource<T> = useMemo(
@@ -465,17 +503,31 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
[],
);
- // Handle adding an item
+ // Handle adding an item — detect creatable synthetic items
const handleAdd = useCallback(
(item: T | null) => {
if (!item) return;
if (isAtMax) return;
- if (selectedIds.has(item.id)) return;
+ // Detect "Create: X" synthetic items from the creatable source
+ if (
+ hasCreate &&
+ typeof item.id === 'string' &&
+ item.id.startsWith(CREATABLE_ID_PREFIX)
+ ) {
+ const createdValue = item.id.slice(CREATABLE_ID_PREFIX.length);
+ if (selectedIds.has(createdValue)) return;
+ const realItem = {id: createdValue, label: createdValue} as T;
+ const newItems = [...value, realItem];
+ onChange(newItems, {item: realItem, type: 'create'});
+ return;
+ }
+
+ if (selectedIds.has(item.id)) return;
const newItems = [...value, item];
onChange(newItems, {item, type: 'add'});
},
- [value, onChange, isAtMax, selectedIds],
+ [value, onChange, isAtMax, selectedIds, hasCreate],
);
// Handle removing an item
@@ -645,7 +697,14 @@ export function XDSTokenizer<T extends XDSSearchableItem>({
hasAutoFocus={hasAutoFocus}
inputId={inputId}
ariaDescribedBy={ariaDescribedBy}
- onChangeQuery={onChangeQuery}
+ onChangeQuery={
+ hasCreate
+ ? (q: string) => {
+ setCreatableQuery(q);
+ onChangeQuery?.(q);
+ }
+ : onChangeQuery
+ }
debounceMs={debounceMs}
onKeyDown={handleKeyDown}
anchorRef={wrapperRef}