An open source design system that's fully customizable and agent ready
TypeScript
fix(core): render PowerSearch field groups (#5235)
nynexman446414781b556ebd
diff --git a/.changeset/powersearch-renders-optional-field-groups-while--a8n4.md b/.changeset/powersearch-renders-optional-field-groups-while--a8n4.mdnew file mode 100644index 0000000000..666500dae8--- /dev/null+++ b/.changeset/powersearch-renders-optional-field-groups-while--a8n4.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] PowerSearch now groups fields in the browsing menu using each field's `group` value. Ungrouped fields appear first, while typed search results remain flat. (#5235)+@nynexman4464diff --git a/apps/storybook/stories/PowerSearch.stories.tsx b/apps/storybook/stories/PowerSearch.stories.tsxindex f471a0665d..83fc1a4ae8 100644--- a/apps/storybook/stories/PowerSearch.stories.tsx+++ b/apps/storybook/stories/PowerSearch.stories.tsx@@ -293,6 +293,151 @@ const fullConfig: PowerSearchConfig = {],};+function simpleField(+ key: string,+ label: string,+ group?: string,+): PowerSearchConfig['fields'][number] {+ return {+ key,+ label,+ group,+ defaultOperator: 'contains',+ operators: [+ {key: 'contains', label: 'contains', value: {type: 'string'}},+ {+ key: 'not_contains',+ label: 'does not contain',+ value: {type: 'string'},+ },+ ],+ };+}++const issueTrackerPeople: SearchableItem[] = Array.from(+ {length: 25},+ (_, index) => ({+ id: `person-${index + 1}`,+ label: `Person ${String(index + 1).padStart(2, '0')}`,+ }),+);++const issueTrackerPeopleSource: SearchSource = {+ search: query =>+ issueTrackerPeople.filter(person =>+ person.label.toLowerCase().includes(query.toLowerCase()),+ ),+ bootstrap: () => issueTrackerPeople,+};++function peopleField(+ key: string,+ label: string,+): PowerSearchConfig['fields'][number] {+ return {+ key,+ label,+ group: 'People',+ defaultOperator: 'any_of',+ operators: [+ {+ key: 'any_of',+ label: 'is any of',+ value: {type: 'entity_list', searchSource: issueTrackerPeopleSource},+ },+ ],+ };+}++const issueTrackerConfig: PowerSearchConfig = {+ name: 'IssueTrackerSearch',+ fields: [+ {+ key: 'status',+ label: 'Status',+ defaultOperator: 'any_of',+ operators: [+ {+ key: 'any_of',+ label: 'is any of',+ value: {type: 'enum_list', values: statusValues},+ },+ ],+ },+ {+ key: 'priority',+ label: 'Priority',+ defaultOperator: 'is',+ operators: [+ {key: 'is', label: 'is', value: {type: 'enum', values: priorityValues}},+ ],+ },+ simpleField('title', 'Title'),+ simpleField('labels', 'Labels'),+ peopleField('owner', 'Owner'),+ peopleField('creator', 'Creator'),+ peopleField('subscriber', 'Subscriber'),+ peopleField('reviewer', 'Reviewer'),+ simpleField('project', 'Project', 'Planning'),+ simpleField('milestone', 'Milestone', 'Planning'),+ simpleField('sprint', 'Sprint', 'Planning'),+ simpleField('estimate', 'Estimate', 'Planning'),+ {+ key: 'due_date',+ label: 'Due date',+ group: 'Planning',+ defaultOperator: 'before',+ operators: [+ {+ key: 'before',+ label: 'is before',+ value: {type: 'date_absolute', isDateOnly: true},+ },+ ],+ },+ {+ key: 'created',+ label: 'Created',+ group: 'Activity',+ defaultOperator: 'after',+ operators: [+ {+ key: 'after',+ label: 'is after',+ value: {type: 'date_absolute', isDateOnly: true},+ },+ ],+ },+ {+ key: 'updated',+ label: 'Updated',+ group: 'Activity',+ defaultOperator: 'after',+ operators: [+ {+ key: 'after',+ label: 'is after',+ value: {type: 'date_absolute', isDateOnly: true},+ },+ ],+ },+ {+ key: 'comment_count',+ label: 'Comment count',+ group: 'Activity',+ defaultOperator: 'gt',+ operators: [+ {+ key: 'gt',+ label: 'is greater than',+ value: {type: 'integer', minValue: 0},+ },+ ],+ },+ simpleField('linked_items', 'Linked items', 'Activity'),+ ],+};+// =============================================================================// Meta// =============================================================================@@ -319,6 +464,15 @@ const meta: Meta<typeof PowerSearch> = {isReadOnly: {control: 'boolean'},hasClear: {control: 'boolean'},maxTokenLength: {control: 'number'},+ maxSearchResults: {+ control: 'number',+ description: 'Main ranked results shown after typing a query.',+ },+ maxOperatorMenuItems: {+ control: 'number',+ description:+ 'Value results shown after selecting a field, such as people in the Owner picker.',+ },popoverSaveButtonLabel: {control: 'text'},size: {control: 'radio',@@ -419,6 +573,42 @@ export const FullFeatured: Story = {name: 'Full Featured (All Field Types)',};+export const IssueTracker: Story = {+ render: args => {+ const [filters, setFilters] = useState<PowerSearchFilter[]>([]);+ return (+ <PowerSearch+ {...args}+ config={issueTrackerConfig}+ filters={filters}+ onChange={newFilters => setFilters([...newFilters])}+ />+ );+ },+ args: {+ placeholder: 'Filter issues...',+ hasAutoFocus: true,+ maxSearchResults: 2,+ maxOperatorMenuItems: 2,+ },+ parameters: {+ docs: {+ description: {+ story:+ 'A realistic issue-tracker field set. Open the empty search to browse ungrouped fields first, followed by optional People, Planning, and Activity sections. Typing switches back to a flat ranked list. Use maxSearchResults to cap the main ranked list; use maxOperatorMenuItems for values after selecting a field, such as Owner.',+ },+ },+ },+ decorators: [+ Story => (+ <div style={{width: 700, minHeight: 420}}>+ <Story />+ </div>+ ),+ ],+ name: 'Issue Tracker (Grouped Fields)',+};+export const WithEnumListFilters: Story = {render: args => {const [filters, setFilters] = useState<PowerSearchFilter[]>([@@ -1381,7 +1571,8 @@ export const StatusVariantComparison: Story = {const [a, setA] = useState<PowerSearchFilter[]>([]);const [b, setB] = useState<PowerSearchFilter[]>([]);return (- <div style={{display: 'flex', flexDirection: 'column', gap: 24, width: 400}}>+ <div+ style={{display: 'flex', flexDirection: 'column', gap: 24, width: 400}}><PowerSearchconfig={basicConfig}filters={a}diff --git a/packages/core/src/PowerSearch/PowerSearch.test.tsx b/packages/core/src/PowerSearch/PowerSearch.test.tsxindex 94d34abac6..97545110a0 100644--- a/packages/core/src/PowerSearch/PowerSearch.test.tsx+++ b/packages/core/src/PowerSearch/PowerSearch.test.tsx@@ -640,3 +640,84 @@ describe('field menu sizing', () => {expect(optionCount()).toBe(FIELD_COUNT);});});++describe('field menu grouping', () => {+ const groupedConfig: PowerSearchConfig = {+ name: 'GroupedSearch',+ fields: [+ field('team_a', 'Field Team A', 'Team'),+ field('plain_a', 'Field Plain A'),+ field('time_a', 'Field Time A', 'Time'),+ field('team_b', 'Field Team B', 'Team'),+ field('plain_b', 'Field Plain B'),+ field('time_b', 'Field Time B', 'Time'),+ ],+ };++ function field(key: string, label: string, group?: string) {+ return {+ key,+ label,+ group,+ operators: [{key: 'is', label: 'is', value: {type: 'string'} as const}],+ };+ }++ async function openMenu() {+ const user = userEvent.setup();+ render(+ <PowerSearch config={groupedConfig} filters={[]} onChange={() => {}} />,+ );+ await user.click(screen.getByRole('combobox'));+ await waitFor(() => {+ expect(screen.getByRole('listbox', {hidden: true})).toBeInTheDocument();+ });+ return user;+ }++ it('renders ungrouped fields first and named sections after them', async () => {+ await openMenu();+ const listbox = screen.getByRole('listbox', {hidden: true});+ expect(+ within(listbox)+ .getAllByRole('option', {hidden: true})+ .map(option => option.textContent),+ ).toEqual([+ 'Field Plain A',+ 'Field Plain B',+ 'Field Team A',+ 'Field Team B',+ 'Field Time A',+ 'Field Time B',+ ]);+ expect(+ within(listbox)+ .getAllByRole('group', {hidden: true})+ .map(group => group.getAttribute('aria-label')),+ ).toEqual(['Team', 'Time']);+ });++ it('keeps keyboard navigation flat across section boundaries', async () => {+ const user = await openMenu();+ const input = screen.getByRole('combobox');+ await user.keyboard('{ArrowDown}{ArrowDown}');+ const activeId = input.getAttribute('aria-activedescendant');+ expect(activeId).not.toBeNull();+ expect(document.getElementById(activeId!)?.textContent).toBe(+ 'Field Team A',+ );+ });++ it('keeps ranked results flat while typing', async () => {+ const user = await openMenu();+ await user.type(screen.getByRole('combobox'), 'field');+ await waitFor(() => {+ expect(+ within(screen.getByRole('listbox', {hidden: true})).queryAllByRole(+ 'group',+ {hidden: true},+ ),+ ).toHaveLength(0);+ });+ });+});diff --git a/packages/core/src/PowerSearch/types.ts b/packages/core/src/PowerSearch/types.tsindex 659437153f..736193144d 100644--- a/packages/core/src/PowerSearch/types.ts+++ b/packages/core/src/PowerSearch/types.ts@@ -384,6 +384,8 @@ export interface PowerSearchAuxData {readonly filterValue?: FilterValue;/** Index in the filters array (for editing/removing). */readonly filterIndex?: number;+ /** Section heading for field-browser entries. */+ readonly group?: string;}export type PowerSearchItem = SearchableItem<PowerSearchAuxData>;diff --git a/packages/core/src/PowerSearch/usePowerSearchSource.test.ts b/packages/core/src/PowerSearch/usePowerSearchSource.test.tsindex b642ef2644..392c3514fe 100644--- a/packages/core/src/PowerSearch/usePowerSearchSource.test.ts+++ b/packages/core/src/PowerSearch/usePowerSearchSource.test.ts@@ -97,6 +97,27 @@ const configWithContentSearch: PowerSearchConfig = {contentSearchFieldKey: 'title',};+const groupedConfig: PowerSearchConfig = {+ name: 'GroupedSearch',+ fields: [+ field('team_a', 'Field Team A', 'Team'),+ field('plain_a', 'Field Plain A'),+ field('time_a', 'Field Time A', 'Time'),+ field('team_b', 'Field Team B', 'Team'),+ field('plain_b', 'Field Plain B'),+ field('time_b', 'Field Time B', 'Time'),+ ],+};++function field(key: string, label: string, group?: string) {+ return {+ key,+ label,+ group,+ operators: [{key: 'is', label: 'is', value: {type: 'string'} as const}],+ };+}+// =============================================================================// Tests// =============================================================================@@ -130,6 +151,21 @@ describe('usePowerSearchSource', () => {const source = createSource(baseConfig);expect(syncSearch(source, '')).toEqual(syncBootstrap(source));});++ it('orders ungrouped fields before named groups', () => {+ const items = syncBootstrap(createSource(groupedConfig));+ expect(items.map(item => item.label)).toEqual([+ 'Field Plain A',+ 'Field Plain B',+ 'Field Team A',+ 'Field Team B',+ 'Field Time A',+ 'Field Time B',+ ]);+ expect(+ items.map(item => (item.auxiliaryData as PowerSearchAuxData).group),+ ).toEqual([undefined, undefined, 'Team', 'Team', 'Time', 'Time']);+ });});describe('search (with query)', () => {@@ -181,6 +217,23 @@ describe('usePowerSearchSource', () => {const aux = isItem?.auxiliaryData as PowerSearchAuxData;expect(aux.operatorKey).toBe('is');});++ it('leaves ranked results flat and in relevance order', () => {+ const results = syncSearch(createSource(groupedConfig), 'field');+ expect(results.slice(0, 6).map(item => item.label)).toEqual([+ 'Field Team A',+ 'Field Team A is',+ 'Field Plain A',+ 'Field Plain A is',+ 'Field Time A',+ 'Field Time A is',+ ]);+ expect(+ results.every(+ item => (item.auxiliaryData as PowerSearchAuxData).group == null,+ ),+ ).toBe(true);+ });});describe('contentSearchFieldKey', () => {diff --git a/packages/core/src/PowerSearch/usePowerSearchSource.ts b/packages/core/src/PowerSearch/usePowerSearchSource.tsindex 2dacb1414a..df6b0d6d6d 100644--- a/packages/core/src/PowerSearch/usePowerSearchSource.ts+++ b/packages/core/src/PowerSearch/usePowerSearchSource.ts@@ -14,6 +14,7 @@import {useMemo} from 'react';import type {SearchSource} from '../Typeahead/types';+import {groupItems} from '../utils';import {useTranslator} from '../i18n';import {resolveOperatorLabel} from './resolveOperatorLabel';import type {InternalConfig} from './useInternalConfig';@@ -288,9 +289,12 @@ function buildFieldItems(config: InternalConfig): PowerSearchItem[] {auxiliaryData: {fieldKey: field.key,operatorKey: defaultOp?.key,+ group: field.group,},});}- return items;+ return groupItems(items, {ungroupedFirst: true}).flatMap(+ group => group.items,+ );}diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex 7155722138..65c27b939d 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -41,7 +41,7 @@ import {fontWeightVars,typeScaleVars,} from '../theme/tokens.stylex';-import {getKey, mergeProps} from '../utils';+import {getKey, groupItems, mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';import type {SearchableItem, SearchSource} from './types';import {themeProps} from '../utils/themeProps';@@ -227,6 +227,15 @@ const styles = stylex.create({popover: {minWidth: 'anchor-size(width)',},+ groupHeading: {+ paddingInline: spacingVars['--spacing-2'],+ paddingBlockStart: spacingVars['--spacing-2'],+ paddingBlockEnd: spacingVars['--spacing-1'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ color: colorVars['--color-text-secondary'],+ userSelect: 'none',+ },item: {boxSizing: 'border-box',display: 'flex',@@ -844,37 +853,61 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({{emptySearchResultsText}</div>) : (- results.map((item, index) => {- const itemKey = getKey(item.id, index);- const isSelected = itemKey === selectedKey;- return (- <div- key={itemKey}- id={getItemId(index)}- role="option"- aria-selected={isSelected}- tabIndex={-1}- onClick={() => handleSelect(item)}- onMouseEnter={() => setHighlightedIndex(index)}- {...stylex.props(- styles.item,- itemSizeStyles[size],- index === highlightedIndex && styles.itemHighlighted,- isSelected && styles.itemSelected,- )}>- <span {...stylex.props(styles.itemContent)}>- {renderItem ? (- renderItem(item)- ) : (- <TypeaheadItem item={item} />+ (() => {+ let flatIndex = 0;+ const renderOption = (item: T) => {+ const index = flatIndex++;+ const itemKey = getKey(item.id, index);+ const isSelected = itemKey === selectedKey;+ return (+ <div+ key={itemKey}+ id={getItemId(index)}+ role="option"+ aria-selected={isSelected}+ tabIndex={-1}+ onClick={() => handleSelect(item)}+ onMouseEnter={() => setHighlightedIndex(index)}+ {...stylex.props(+ styles.item,+ itemSizeStyles[size],+ index === highlightedIndex && styles.itemHighlighted,+ isSelected && styles.itemSelected,+ )}>+ <span {...stylex.props(styles.itemContent)}>+ {renderItem ? (+ renderItem(item)+ ) : (+ <TypeaheadItem item={item} />+ )}+ </span>+ {isSelected && (+ <Icon icon="check" size="sm" color="primary" />)}- </span>- {isSelected && (- <Icon icon="check" size="sm" color="primary" />- )}- </div>- );- })+ </div>+ );+ };++ return groupItems(results, {ungroupedFirst: true}).map(group => {+ const options = group.items.map(renderOption);+ if (group.heading == null) {+ return options;+ }+ return (+ <div+ key={`group-${group.heading}`}+ role="group"+ aria-label={group.heading}>+ <div+ aria-hidden="true"+ {...stylex.props(styles.groupHeading)}>+ {group.heading}+ </div>+ {options}+ </div>+ );+ });+ })())}</div>,{diff --git a/packages/core/src/utils/groupItems.ts b/packages/core/src/utils/groupItems.tsindex bc266d1dca..72843b01fa 100644--- a/packages/core/src/utils/groupItems.ts+++ b/packages/core/src/utils/groupItems.ts@@ -19,6 +19,11 @@ export interface ItemGroup<T extends SearchableItem = SearchableItem> {items: T[];}+export interface GroupItemsOptions {+ /** Place ungrouped items before named groups instead of after them. */+ ungroupedFirst?: boolean;+}+/*** Extract the group string from an item's auxiliaryData.*/@@ -52,6 +57,7 @@ export function getItemGroup(item: SearchableItem): string | undefined {*/export function groupItems<T extends SearchableItem>(items: T[],+ {ungroupedFirst = false}: GroupItemsOptions = {},): ItemGroup<T>[] {const hasGroups = items.some(item => getItemGroup(item) != null);@@ -76,14 +82,14 @@ export function groupItems<T extends SearchableItem>(}}- const result: ItemGroup<T>[] = groupOrder.map(heading => ({+ const namedGroups: ItemGroup<T>[] = groupOrder.map(heading => ({heading,items: groups.get(heading) ?? [],}));+ const ungroupedGroup: ItemGroup<T>[] =+ ungrouped.length > 0 ? [{heading: null, items: ungrouped}] : [];- if (ungrouped.length > 0) {- result.push({heading: null, items: ungrouped});- }-- return result;+ return ungroupedFirst+ ? [...ungroupedGroup, ...namedGroups]+ : [...namedGroups, ...ungroupedGroup];}diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex 276b382228..1f8e7157a9 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -86,7 +86,7 @@ export type {ThemeProps,} from './themeProps';export {groupItems, getItemGroup} from './groupItems';-export type {ItemGroup} from './groupItems';+export type {ItemGroup, GroupItemsOptions} from './groupItems';export {observeResize, unobserveResize} from './sharedResizeObserver';export {isRenderable} from './isRenderable';export {getInputARIA} from './inputAria';