Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: reset search after creating resource tag 🏷️ #436

Merged
merged 3 commits into from
Aug 20, 2024
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
Expand Up @@ -156,7 +156,6 @@ export function ResourceTagsField({
const tags = listFetcher.data?.tags || [];

function reset() {
setSearch('');
setNewTagId(id());
}

Expand Down
8 changes: 6 additions & 2 deletions packages/ui/src/components/multi-combobox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import { Divider } from './divider';
import { getInputCn, type InputProps } from './input';
import { getPillCn } from './pill';
import { setInputValue } from '../utils/core';
import { cx } from '../utils/cx';

type ComboboxValue = {
Expand Down Expand Up @@ -122,10 +123,13 @@ export function MultiComboboxItem({
setValues([...values, { label, value }]);
}

const searchElement = searchRef.current!;

// After an item is selected, we should reset the search value
// and focus the search input.
searchRef.current!.value = '';
searchRef.current!.focus();
setInputValue(searchElement, '');

searchElement.focus();
}}
type="button"
value={value}
Expand Down
35 changes: 35 additions & 0 deletions packages/ui/src/utils/core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Set value on input element.
*
* This should only be used when you need to set value on an input element
* outside of React. It's hacky and should be avoided if possible.
*
* Motivation: When we just try to set the value directly on the input element,
* React doesn't trigger a change event (their event system is different from
* the native one). This function tries to work around that by manually
* creating a change event and dispatching it on the input element.
*
* @param input - Input element to set value on.
* @param value - Value to set on input element.
*
* @see https://github.com/facebook/react/issues/27283
* @see https://github.com/facebook/react/issues/10135
*/
export function setInputValue(input: HTMLInputElement, value: string) {
const descriptor = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype,
'value'
);

const set = descriptor?.set;

if (!set) {
return;
}

set.call(input, value);

const event = new Event('change', { bubbles: true });

input.dispatchEvent(event);
}