Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
@@ -0,0 +1,6 @@
---
'@astryxdesign/core': patch
---

[feat] Typeahead and Tokenizer take `query` and `defaultQuery` so an app can set or clear the typed text. Pass `query` with `onChangeQuery` to restore a search, clear it from another control, or keep the text after a pick. `onChangeQuery` keeps reporting every change, its own included, so a controlled field stays in sync. A change from outside does not move focus, and it does not open the listbox or announce a result count unless the field has focus. Omit `query` and the field still owns its text; `defaultQuery` sets the starting value.
@mvanhorn
49 changes: 46 additions & 3 deletions packages/core/src/Tokenizer/Tokenizer.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,23 @@ export const docs = {
"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: 'query',
type: 'string',
description:
'The typed query. When set, the field is controlled: it shows this text and reports every change through onChangeQuery, including a pick and a clear. Hold this value after a pick to keep the text. A change from outside does not move focus, and it does not open the listbox or announce a result count unless the field has focus. Clearing this value while the field is focused does what emptying the field does: the listbox closes, or shows the focus entries with hasEntriesOnFocus.',
},
{
name: 'defaultQuery',
type: 'string',
description:
'Initial typed query when query is not set. Use this to restore a search without owning the text afterward.',
},
{
name: 'onChangeQuery',
type: '(query: string) => void',
description: 'Callback fired when the search query text changes.',
description:
'Callback fired when the search query text changes, including a pick and a clear, so a controlled field stays in sync.',
},
{
name: 'startIcon',
Expand Down Expand Up @@ -352,6 +365,11 @@ export const docs = {
description:
'Use inside InputGroup only when the tokenizer needs a short prefix or suffix addon as part of one decorated input surface; the grouped row stays single-line, so keep selections few (maxEntries) or use tokenOverflowBehavior to summarize them.',
},
{
guidance: true,
description:
'Pass query and onChangeQuery to restore a search, clear it from another control, or keep the text after a pick. Pass defaultQuery when the field should start with text and then own it.',
},
{
guidance: false,
description:
Expand Down Expand Up @@ -602,11 +620,23 @@ export const docsZh = {
'触发搜索前的防抖延迟(毫秒)。同步数据源,以及通过 `context.update` 显示本地匹配项并自行延迟服务器请求的数据源,设置为 0。',
default: '150',
},
{
name: 'query',
type: 'string',
description:
'已输入的查询。设置后字段为受控:显示该文本,并通过 onChangeQuery 报告每一次变更(包括选择和清除),以便受控用法保持同步。选择后继续传入该值即可保留文本。从外部设置查询不会移动焦点;字段未聚焦时不会打开列表框,也不会播报结果数量。字段聚焦时将查询清空,效果与用户清空输入相同:列表框关闭,或在设置 hasEntriesOnFocus 时显示聚焦条目。',
},
{
name: 'defaultQuery',
type: 'string',
description:
'未设置 query 时的初始查询。用于恢复一次搜索,之后由字段自行管理文本。',
},
{
name: 'onChangeQuery',
type: '(query: string) => void',
description:
'\u641c\u7d22\u67e5\u8be2\u6587\u672c\u53d8\u66f4\u65f6\u89e6\u53d1\u7684\u56de\u8c03\u3002',
'搜索查询文本变更时触发的回调,包括选择和清除,以便受控字段保持同步。',
},
{
name: 'startIcon',
Expand Down Expand Up @@ -716,6 +746,11 @@ export const docsZh = {
description:
'Use inside InputGroup only when the tokenizer needs a short prefix or suffix addon as part of one decorated input surface; the grouped row stays single-line, so keep selections few (maxEntries) or use tokenOverflowBehavior to summarize them.',
},
{
guidance: true,
description:
'Pass query and onChangeQuery to restore a search, clear it from another control, or keep the text after a pick. Pass defaultQuery when the field should start with text and then own it.',
},
{
guidance: false,
description:
Expand Down Expand Up @@ -816,6 +851,11 @@ export const docsDense = {
description:
'Use inside InputGroup only for a short prefix or suffix addon; the grouped row stays single-line, so keep selections few (maxEntries) or use tokenOverflowBehavior.',
},
{
guidance: true,
description:
'Pass query and onChangeQuery to restore, clear, or keep the text after a pick. Pass defaultQuery to start with text the field then owns.',
},
{
guidance: false,
description:
Expand Down Expand Up @@ -882,7 +922,10 @@ export const docsDense = {
hasAutoFocus: 'Auto-focus input on mount.',
size: 'Input+token size; the group size applies inside InputGroup.',
debounceMs: 'Search debounce delay ms. 0 for sync sources.',
onChangeQuery: 'Fired on search query text change.',
query:
'Controlled typed query. Reports every change through onChangeQuery, including a pick and a clear. Hold it after a pick to keep the text. Setting it from outside does not move focus or open the listbox, and announces a result count only while focused.',
Comment thread
mvanhorn marked this conversation as resolved.
Resolved
defaultQuery: 'Initial typed query when query is not set.',
onChangeQuery: 'Fired on query text change, including a pick and a clear.',
startIcon:
'Icon at input start, before tokens. Icon name, SVG component, or ReactNode.',
endContent: 'Content at input row end. For buttons, counts, controls.',
Expand Down
79 changes: 79 additions & 0 deletions packages/core/src/Tokenizer/Tokenizer.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2740,6 +2740,85 @@ describe('Tokenizer', () => {
});
});

it('keeps the Added announcement and does not reopen the list when the app echoes an empty query after a pick', async () => {
const bootstrap = vi.fn(() => users.slice(0, 3));
const source: SearchSource = {
search: (query: string) =>
users.filter(u =>
u.label.toLowerCase().includes(query.toLowerCase()),
),
bootstrap,
};
function Controlled() {
const [query, setQuery] = useState('');
const [value, setValue] = useState<SearchableItem[]>([]);
return (
<Tokenizer
label="Members"
searchSource={source}
value={value}
onChange={setValue}
query={query}
onChangeQuery={setQuery}
hasEntriesOnFocus
debounceMs={0}
presentation="popover"
/>
);
}
render(<Controlled />);
const input = screen.getByRole('combobox');
fireEvent.focus(input);
fireEvent.change(input, {target: {value: 'Ali'}});
await waitFor(() => {
expect(
screen.getByRole('option', {name: 'Alice', hidden: true}),
).toBeInTheDocument();
});
const bootstrapCallsAtPick = bootstrap.mock.calls.length;
fireEvent.click(
screen.getByRole('option', {name: 'Alice', hidden: true}),
);
await waitFor(() => {
expect(politeRegion()?.textContent).toMatch(/Added Alice/);
});
expect(input).toHaveAttribute('aria-expanded', 'false');
expect(bootstrap.mock.calls.length).toBe(bootstrapCallsAtPick);
});

it('keeps the Added announcement when the app echoes an empty query after a pick with default props', async () => {
function Controlled() {
const [query, setQuery] = useState('');
const [value, setValue] = useState<SearchableItem[]>([]);
return (
<Tokenizer
label="Members"
searchSource={userSource}
value={value}
onChange={setValue}
query={query}
onChangeQuery={setQuery}
/>
);
}
render(<Controlled />);
const input = screen.getByRole('combobox');
fireEvent.focus(input);
fireEvent.change(input, {target: {value: 'Ali'}});
await waitFor(() => {
expect(
screen.getByRole('option', {name: 'Alice', hidden: true}),
).toBeInTheDocument();
});
fireEvent.click(
screen.getByRole('option', {name: 'Alice', hidden: true}),
);
await waitFor(() => {
expect(politeRegion()?.textContent).toMatch(/Added Alice/);
});
expect(input).toHaveValue('');
});

it('announces addition politely when creating a token with hasCreate', async () => {
const emptySource: SearchSource = {
search: () => [],
Expand Down
26 changes: 23 additions & 3 deletions packages/core/src/Tokenizer/Tokenizer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,22 @@ export interface TokenizerProps<T extends SearchableItem> extends Omit<
* @default false
*/
hasCreate?: boolean;
/** Query change callback. */
/**
* The typed query. When set, the field is controlled: it shows this text
* and reports every change through `onChangeQuery`, including a pick and a
* clear. Hold this value after a pick to keep the text. A change from
* outside does not move focus. It does not open the listbox or announce a
* result count unless the field has focus.
*/
query?: string;
/**
* Initial typed query when `query` is not set.
*/
defaultQuery?: string;
/**
* Query change callback. Fires for every text change, including a pick and
* a clear, so a controlled field stays in sync.
*/
onChangeQuery?: (query: string) => void;
/** Fires when focus enters the tokenizer from outside. */
onFocus?: (e: React.FocusEvent) => void;
Expand Down Expand Up @@ -1033,6 +1048,8 @@ export function Tokenizer<T extends SearchableItem>({
tokenOverflowBehavior = 'none',
debounceMs,
hasCreate = false,
query: queryProp,
defaultQuery,
onChangeQuery,
onFocus,
onBlur,
Expand Down Expand Up @@ -1190,7 +1207,7 @@ export function Tokenizer<T extends SearchableItem>({
// from a press until its exit completes, and a close the field forces
// keeps the query (FR18). The ref follows every report; the press
// snapshots it into the state the next presentation starts from.
const sheetQueryRef = useRef('');
const sheetQueryRef = useRef(queryProp ?? defaultQuery ?? '');
const [sheetInitialQuery, setSheetInitialQuery] = useState('');
const handleSheetQueryChange = useCallback(
(query: string) => {
Expand Down Expand Up @@ -2054,6 +2071,8 @@ export function Tokenizer<T extends SearchableItem>({
.filter(Boolean)
.join(' ') || undefined
}
query={queryProp}
defaultQuery={defaultQuery}
onChangeQuery={onChangeQuery}
// The resolved required state reaches the combobox, also when a
// FormLayout default hides the visible marker (component:FormLayout
Expand Down Expand Up @@ -2288,7 +2307,7 @@ export function Tokenizer<T extends SearchableItem>({
return;
}
setIsSheetPresented(true);
setSheetInitialQuery(sheetQueryRef.current);
setSheetInitialQuery(queryProp ?? sheetQueryRef.current);
setIsSheetOpen(true);
},
// Typed for the input by the base props; here the control is the
Expand Down Expand Up @@ -2372,6 +2391,7 @@ export function Tokenizer<T extends SearchableItem>({
onOpenChange={setIsSheetOpen}
finalFocusRef={triggerRef}
initialQuery={sheetInitialQuery}
query={queryProp}
label={label}
searchSource={searchSource}
value={value}
Expand Down
19 changes: 15 additions & 4 deletions packages/core/src/Tokenizer/TokenizerBottomSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ export interface TokenizerBottomSheetProps<T extends SearchableItem> {
* (`component:Tokenizer` FR18).
*/
initialQuery: string;
/**
* The typed query. When set, the sheet is controlled and shows this text.
*/
query?: string;
/** The field label; names the sheet, the search field, and the list. */
label: string;
searchSource: SearchSource<T>;
Expand Down Expand Up @@ -327,6 +331,7 @@ type TokenizerSheetContentProps<T extends SearchableItem> = Omit<
function TokenizerSheetContent<T extends SearchableItem>({
isOpen,
initialQuery,
query: queryProp,
clearQueryRef,
requestDismissRef,
onCloseSheet,
Expand Down Expand Up @@ -405,7 +410,9 @@ function TokenizerSheetContent<T extends SearchableItem>({
// ---- sheet session ----
// Starts from the field's copy, which `onChangeQuery` keeps current, so the
// query survives the sheet's unmount between presentations (FR18).
const [query, setQuery] = useState(initialQuery);
const isQueryControlled = queryProp !== undefined;
const [uncontrolledQuery, setUncontrolledQuery] = useState(initialQuery);
const query = isQueryControlled ? queryProp : uncontrolledQuery;
const [sourceResults, setSourceResults] = useState<T[]>([]);
const trimmedQueryForSearch = query.trim();
// A query shorter than `minQueryLength` is never searched: no source rows,
Expand Down Expand Up @@ -501,11 +508,13 @@ function TokenizerSheetContent<T extends SearchableItem>({
clearQueryRef,
() => () => {
if (query !== '') {
setQuery('');
if (!isQueryControlled) {
setUncontrolledQuery('');
}
onChangeQuery?.('');
}
},
[query, onChangeQuery],
[query, isQueryControlled, onChangeQuery],
);

// The source is read through a ref at request time, as the inline field
Expand Down Expand Up @@ -706,7 +715,9 @@ function TokenizerSheetContent<T extends SearchableItem>({
} else {
announcedSearchIdRef.current = searchId;
}
setQuery(next);
if (!isQueryControlled) {
Comment thread
mvanhorn marked this conversation as resolved.
Resolved
setUncontrolledQuery(next);
}
onChangeQuery?.(next);
};

Expand Down
35 changes: 32 additions & 3 deletions packages/core/src/Typeahead/BaseTypeahead.doc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -239,10 +239,23 @@ export const docs = {
description:
'Additional keydown handler called before internal keyboard navigation. Call e.preventDefault() to skip internal handling.',
},
{
name: 'query',
type: 'string',
description:
'The typed query. When set, the field is controlled: it shows this text and reports every change through onChangeQuery, including a pick and a clear. Hold this value after a pick to keep the text. A change from outside does not move focus, and it does not open the listbox or announce a result count unless the field has focus. Clearing this value while the field is focused does what emptying the field does: the listbox closes, or shows the focus entries with hasEntriesOnFocus.',
},
{
name: 'defaultQuery',
type: 'string',
description:
'Initial typed query when query is not set. Use this to restore a search without owning the text afterward.',
},
{
name: 'onChangeQuery',
type: '(query: string) => void',
description: 'Callback fired when the search query text changes.',
description:
'Callback fired when the search query text changes, including a pick and a clear, so a controlled field stays in sync.',
},
{
name: 'onOpenChange',
Expand Down Expand Up @@ -409,10 +422,23 @@ export const docsZh = {
description:
'在内部键盘导航之前调用的附加 keydown 处理函数。调用 e.preventDefault() 可跳过内部处理。',
},
{
name: 'query',
type: 'string',
description:
'已输入的查询。设置后字段为受控:显示该文本,并通过 onChangeQuery 报告每一次变更(包括选择和清除),以便受控用法保持同步。选择后继续传入该值即可保留文本。从外部设置查询不会移动焦点;字段未聚焦时不会打开列表框,也不会播报结果数量。字段聚焦时将查询清空,效果与用户清空输入相同:列表框关闭,或在设置 hasEntriesOnFocus 时显示聚焦条目。',
},
{
name: 'defaultQuery',
type: 'string',
description:
'未设置 query 时的初始查询。用于恢复一次搜索,之后由字段自行管理文本。',
},
{
name: 'onChangeQuery',
type: '(query: string) => void',
description: '搜索查询文本变更时触发的回调。',
description:
'搜索查询文本变更时触发的回调,包括选择和清除,以便受控字段保持同步。',
},
{
name: 'onOpenChange',
Expand Down Expand Up @@ -517,7 +543,10 @@ export const docsDense = {
'Legacy tabIndex alias; defined alias wins, otherwise native tabIndex passes through.',
onKeyDown:
'Keydown before internal nav. preventDefault() skips internal handling.',
onChangeQuery: 'Fired on query text change.',
query:
'Controlled typed query. Reports every change through onChangeQuery, including a pick and a clear. Hold it after a pick to keep the text. Setting it from outside does not move focus or open the listbox, and announces a result count only while focused.',
Comment thread
mvanhorn marked this conversation as resolved.
Resolved
defaultQuery: 'Initial typed query when query is not set.',
onChangeQuery: 'Fired on query text change, including a pick and a clear.',
onOpenChange: 'Fired on dropdown open/close.',
menu: "Menu content: {role:'listbox', render?({listbox,query,isBusy,isEmptySearch,close})} (info around the list; actions stay results) | {role:'dialog', label, render({query,close})} (takes focus; close returns focus to opener, else input). Astryx owns the layer. open() from onChange keeps it open across a role switch.",
handleRef:
Expand Down
Loading