An open source design system that's fully customizable and agent ready
TypeScript
feat(PowerSearch): add components map for per-type token and editor overrides (#2076)
Cindy Zhang4ca72875f776
diff --git a/apps/storybook/stories/PowerSearch.stories.tsx b/apps/storybook/stories/PowerSearch.stories.tsxindex 7dbbbc0d0c..55b38f9630 100644--- a/apps/storybook/stories/PowerSearch.stories.tsx+++ b/apps/storybook/stories/PowerSearch.stories.tsx@@ -1,4 +1,4 @@-import {useState} from 'react';+import React, {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {XDSPowerSearch} from '@xds/core/PowerSearch';import type {@@ -1120,3 +1120,102 @@ export const OverflowLayer: Story = {},name: 'Overflow Layer',};++// =============================================================================+// Custom Components Map+// =============================================================================++import type {+ XDSPowerSearchComponents,+ PowerSearchTokenProps,+ PowerSearchEditorProps,+} from '@xds/core/PowerSearch';+import {XDSPowerSearchToken, XDSPowerSearchFilterEditor} from '@xds/core/PowerSearch';+import {XDSToken} from '@xds/core/Token';+import {XDSHStack} from '@xds/core/Stack';++function StatusToken({filter, field, operator, maxLength, onClick, onRemove, isDisabled}: PowerSearchTokenProps) {+ const value = filter.value.type === 'enum' ? filter.value.value : '?';+ const colors: Record<string, string> = {+ open: '#22c55e',+ in_progress: '#3b82f6',+ review: '#a855f7',+ closed: '#6b7280',+ blocked: '#ef4444',+ };+ return (+ <XDSToken+ label={`${field.label}: ${operator.label}`}+ endContent={+ <span style={{fontWeight: 600, color: colors[value] ?? 'inherit'}}>+ {value}+ </span>+ }+ onClick={onClick ? (e: React.MouseEvent) => { e.stopPropagation(); onClick(); } : undefined}+ onRemove={onRemove}+ isDisabled={isDisabled}+ />+ );+}++function CustomIntegerEditor({config, filter, mode, onSave, onCancel, saveButtonLabel, isReadOnly}: PowerSearchEditorProps) {+ const current = filter.value?.type === 'integer' ? filter.value.value : 50;+ return (+ <div style={{padding: 16}}>+ <p style={{margin: '0 0 12px', fontSize: 13}}>Custom range editor for integer fields:</p>+ <XDSHStack gap={2} vAlign="center">+ <input+ type="range"+ min={0}+ max={1000}+ value={current}+ onChange={e => {+ onSave({+ field: filter.field,+ operator: filter.operator!,+ value: {type: 'integer', value: Number(e.target.value)},+ });+ }}+ style={{flex: 1}}+ disabled={isReadOnly}+ />+ <span style={{fontSize: 12, whiteSpace: 'nowrap'}}>{current}</span>+ </XDSHStack>+ <div style={{marginTop: 12, display: 'flex', gap: 8, justifyContent: 'flex-end'}}>+ <button onClick={onCancel}>Cancel</button>+ </div>+ </div>+ );+}++const customComponents: XDSPowerSearchComponents = {+ enum: {Token: StatusToken},+ integer: {Editor: CustomIntegerEditor},+};++export const WithCustomComponents: Story = {+ render: args => {+ const [filters, setFilters] = useState<PowerSearchFilter[]>([+ {field: 'status', operator: 'is', value: {type: 'enum', value: 'open'}},+ {field: 'line_count', operator: 'gt', value: {type: 'integer', value: 200}},+ ]);+ return (+ <div>+ <XDSPowerSearch+ {...args}+ config={fullConfig}+ filters={filters}+ onChange={newFilters => setFilters([...newFilters])}+ components={customComponents}+ />+ <p style={{marginTop: 16, fontSize: 13, color: '#666'}}>+ <strong>Custom overrides:</strong> Status tokens show colored text (custom Token).+ Integer fields use a range slider editor (custom Editor).+ </p>+ </div>+ );+ },+ args: {placeholder: 'Search with custom components...'},+ decorators: [Story => (<div style={{width: 700}}><Story /></div>)],+ name: 'Custom Components Map',+};diff --git a/packages/core/src/PowerSearch/XDSPowerSearch.tsx b/packages/core/src/PowerSearch/XDSPowerSearch.tsxindex 3e40af81ac..511ce4516e 100644--- a/packages/core/src/PowerSearch/XDSPowerSearch.tsx+++ b/packages/core/src/PowerSearch/XDSPowerSearch.tsx@@ -48,6 +48,8 @@ import {PowerSearchEditPopover} from './PowerSearchEditPopover';import type {PowerSearchConfig,PowerSearchFilter,+ PowerSearchField,+ PowerSearchOperator,PartialFilter,PowerSearchItem,PowerSearchAuxData,@@ -56,6 +58,7 @@ import type {FilterValue,OperatorValue,EnumItem,+ XDSPowerSearchComponents,} from './types';// =============================================================================@@ -390,6 +393,11 @@ export interface XDSPowerSearchProps {className?: string;/** Inline styles. */style?: React.CSSProperties;+ /**+ * Per-type component overrides for token and editor rendering.+ * Keys are operator value types (e.g. 'string', 'enum', 'date_absolute').+ */+ components?: XDSPowerSearchComponents;}// =============================================================================@@ -504,6 +512,7 @@ export function XDSPowerSearch({xstyle,className,style,+ components: componentOverrides,}: XDSPowerSearchProps) {const config = useInternalConfig(configProp);const searchSource = usePowerSearchSource(config);@@ -699,6 +708,7 @@ export function XDSPowerSearch({setPopoverState({type: 'idle'});}, [setPopoverState]);+ // Custom token renderer// Custom token rendererconst renderToken = useCallback((item: PowerSearchItem, onRemove: () => void) => {@@ -711,19 +721,41 @@ export function XDSPowerSearch({? config.getOperator(auxData.fieldKey, auxData.operatorKey): undefined;- const fieldLabel = field?.label ?? '';- const operatorLabel = operator?.label ?? '';+ const canInteract = !isReadOnly && !isDisabled && !filter?.isReadOnly;+ const handleClick = canInteract+ ? () => handleTokenClick(filterIndex)+ : undefined;+ const handleRemove = canInteract ? onRemove : undefined;++ // Check for full Token override+ const TokenOverride = operator+ ? componentOverrides?.[operator.value.type]?.Token+ : undefined;- // Build the token label: "Field operator" (space-separated, like reference)- const tokenLabel = `${fieldLabel} ${operatorLabel}`.trim();+ if (TokenOverride && filter && field && operator) {+ return (+ <TokenOverride+ config={configProp}+ filter={filter}+ field={field}+ operator={operator}+ maxLength={maxTokenLength}+ onClick={handleClick}+ onRemove={handleRemove}+ isDisabled={isDisabled}+ />+ );+ }- // Adjust maxTokenLength by subtracting label length (min 10, like reference)+ // Default token rendering+ const fieldLabel = field?.label ?? '';+ const operatorLabel = operator?.label ?? '';+ const tokenLabel = `${fieldLabel}: ${operatorLabel}`.trim();const adjustedMaxLength = Math.max(maxTokenLength - fieldLabel.length - operatorLabel.length,10,);- // Render value as rich content with bold stylingconst valueContent =operator && filter ? (<PowerSearchTokenValue@@ -738,23 +770,19 @@ export function XDSPowerSearch({label={tokenLabel}endContent={valueContent}onClick={- !isReadOnly && !isDisabled && !filter?.isReadOnly+ handleClick? (e: React.MouseEvent) => {e.stopPropagation();- handleTokenClick(filterIndex);+ handleClick();}: undefined}- onRemove={- !isReadOnly && !isDisabled && !filter?.isReadOnly- ? onRemove- : undefined- }+ onRemove={handleRemove}isDisabled={isDisabled}/>);},- [filters, config, maxTokenLength, isReadOnly, isDisabled, handleTokenClick],+ [filters, config, configProp, maxTokenLength, isReadOnly, isDisabled, handleTokenClick, componentOverrides],);// Custom typeahead item renderer — adds field icon and description@@ -792,6 +820,60 @@ export function XDSPowerSearch({const popoverPartialFilter =popoverState.type !== 'idle' ? popoverState.partialFilter : null;+ // Resolve custom Editor override for the current popover filter+ const EditorOverride = useMemo(() => {+ if (!popoverPartialFilter?.field || !popoverPartialFilter?.operator)+ return undefined;+ const op = config.getOperator(+ popoverPartialFilter.field,+ popoverPartialFilter.operator,+ );+ return op ? componentOverrides?.[op.value.type]?.Editor : undefined;+ }, [popoverPartialFilter, config, componentOverrides]);++ // Render popover content — either custom Editor or default+ const popoverContent = useMemo(() => {+ if (!popoverPartialFilter) return null;++ const mode = popoverState.type === 'editing' ? 'edit' : 'create';++ if (EditorOverride) {+ return (+ <EditorOverride+ config={configProp}+ filter={popoverPartialFilter}+ mode={mode}+ onSave={handlePopoverSave}+ onCancel={handlePopoverCancel}+ saveButtonLabel={popoverSaveButtonLabel}+ isReadOnly={isReadOnly}+ />+ );+ }++ return (+ <PowerSearchEditPopover+ config={config}+ filter={popoverPartialFilter}+ mode={mode}+ onSave={handlePopoverSave}+ onCancel={handlePopoverCancel}+ saveButtonLabel={popoverSaveButtonLabel}+ isReadOnly={isReadOnly}+ />+ );+ }, [+ popoverPartialFilter,+ popoverState.type,+ EditorOverride,+ configProp,+ config,+ handlePopoverSave,+ handlePopoverCancel,+ popoverSaveButtonLabel,+ isReadOnly,+ ]);+// Build combined endContent from resultCount + endContent propsconst combinedEndContent = useMemo(() => {let resultCountNode: React.ReactNode = null;@@ -851,24 +933,11 @@ export function XDSPowerSearch({data-testid={testId}/></div>- {popover.render(- popoverPartialFilter ? (- <PowerSearchEditPopover- config={config}- filter={popoverPartialFilter}- mode={popoverState.type === 'editing' ? 'edit' : 'create'}- onSave={handlePopoverSave}- onCancel={handlePopoverCancel}- saveButtonLabel={popoverSaveButtonLabel}- isReadOnly={isReadOnly}- />- ) : null,- {- placement: 'below',- alignment: 'start',- xstyle: [popoverLayerStyles.layer, layerAnimations.below],- },- )}+ {popover.render(popoverContent, {+ placement: 'below',+ alignment: 'start',+ xstyle: [popoverLayerStyles.layer, layerAnimations.below],+ })}</>);}diff --git a/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsx b/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsxnew file mode 100644index 0000000000..bd8a15fe89--- /dev/null+++ b/packages/core/src/PowerSearch/XDSPowerSearchFilterEditor.tsx@@ -0,0 +1,47 @@+'use client';++/**+ * @file XDSPowerSearchFilterEditor.tsx+ * @input PowerSearchEditorProps+ * @output Default editor popover content for PowerSearch filters+ * @position Public component; used internally by XDSPowerSearch and available for consumer composition+ */++import React from 'react';+import {PowerSearchEditPopover} from './PowerSearchEditPopover';+import {useInternalConfig} from './useInternalConfig';+import type {PowerSearchEditorProps} from './types';++/**+ * Default filter editor for PowerSearch.+ *+ * Renders the full editing experience: field selector, operator selector,+ * value editor, and save/cancel buttons. This is the built-in implementation+ * used by XDSPowerSearch — exported so consumers can use it as a base when+ * providing custom `components.Editor` overrides.+ */+export function XDSPowerSearchFilterEditor({+ config: configProp,+ filter,+ mode,+ onSave,+ onCancel,+ saveButtonLabel,+ isReadOnly,+}: PowerSearchEditorProps) {+ const config = useInternalConfig(configProp);++ return (+ <PowerSearchEditPopover+ config={config}+ filter={filter}+ mode={mode}+ onSave={onSave}+ onCancel={onCancel}+ saveButtonLabel={saveButtonLabel}+ isReadOnly={isReadOnly}+ />+ );+}++XDSPowerSearchFilterEditor.displayName = 'XDSPowerSearchFilterEditor';diff --git a/packages/core/src/PowerSearch/XDSPowerSearchToken.tsx b/packages/core/src/PowerSearch/XDSPowerSearchToken.tsxnew file mode 100644index 0000000000..efe2746699--- /dev/null+++ b/packages/core/src/PowerSearch/XDSPowerSearchToken.tsx@@ -0,0 +1,77 @@+'use client';++/**+ * @file XDSPowerSearchToken.tsx+ * @input PowerSearchTokenProps+ * @output Default token pill for PowerSearch filters+ * @position Public component; used internally by XDSPowerSearch and available for consumer composition+ */++import React from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSToken} from '../Token';+import {fontWeightVars} from '../theme/tokens.stylex';+import {formatFilterValue} from './formatFilterValue';+import {useInternalConfig} from './useInternalConfig';+import type {PowerSearchTokenProps} from './types';++const tokenValueStyles = stylex.create({+ value: {+ fontWeight: fontWeightVars['--font-weight-bold'],+ },+});++/**+ * Default token pill for PowerSearch filters.+ *+ * Renders a field label, operator label, and formatted value inside an XDSToken.+ * This is the built-in implementation used by XDSPowerSearch — exported so consumers+ * can use it as a base when providing custom `components.Token` overrides.+ */+export function XDSPowerSearchToken({+ config: configProp,+ filter,+ field,+ operator,+ maxLength,+ onClick,+ onRemove,+ isDisabled,+}: PowerSearchTokenProps) {+ const config = useInternalConfig(configProp);++ const fieldLabel = field.label;+ const operatorLabel = operator.label ? `: ${operator.label}` : '';+ const tokenLabel = `${fieldLabel}${operatorLabel}`;++ const adjustedMaxLength = Math.max(+ maxLength - fieldLabel.length - (operator.label?.length ?? 0),+ 10,+ );++ const valueStr = formatFilterValue(+ config,+ operator.value,+ filter.value,+ adjustedMaxLength,+ );++ const valueContent = valueStr ? (+ <span {...stylex.props(tokenValueStyles.value)}>{valueStr}</span>+ ) : undefined;++ return (+ <XDSToken+ label={tokenLabel}+ endContent={valueContent}+ onClick={onClick ? (e: React.MouseEvent) => {+ e.stopPropagation();+ onClick();+ } : undefined}+ onRemove={onRemove}+ isDisabled={isDisabled}+ />+ );+}++XDSPowerSearchToken.displayName = 'XDSPowerSearchToken';diff --git a/packages/core/src/PowerSearch/index.ts b/packages/core/src/PowerSearch/index.tsindex e8923f1b49..d93f985372 100644--- a/packages/core/src/PowerSearch/index.ts+++ b/packages/core/src/PowerSearch/index.ts@@ -12,6 +12,9 @@export {XDSPowerSearch} from './XDSPowerSearch';export type {XDSPowerSearchProps} from './XDSPowerSearch';+export {XDSPowerSearchToken} from './XDSPowerSearchToken';+export {XDSPowerSearchFilterEditor} from './XDSPowerSearchFilterEditor';+export {createPowerSearchConfig,usePowerSearchConfig,@@ -72,4 +75,10 @@ export type {OperatorTokenizationConfig,PowerSearchChangeType,XDSPowerSearchHandle,++ // Component override types+ PowerSearchTokenProps,+ PowerSearchEditorProps,+ PowerSearchComponentOverride,+ XDSPowerSearchComponents,} from './types';diff --git a/packages/core/src/PowerSearch/types.ts b/packages/core/src/PowerSearch/types.tsindex e3413d52e6..43f830daac 100644--- a/packages/core/src/PowerSearch/types.ts+++ b/packages/core/src/PowerSearch/types.ts@@ -8,7 +8,7 @@* - /packages/core/src/PowerSearch/index.ts*/-import type {ReactNode} from 'react';+import type {ComponentType, ReactNode} from 'react';import type {XDSSearchSource, XDSSearchableItem} from '../Typeahead/types';// =============================================================================@@ -361,3 +361,48 @@ export interface PowerSearchAuxData {}export type PowerSearchItem = XDSSearchableItem<PowerSearchAuxData>;++// =============================================================================+// Components Map — per-type overrides for token and editor rendering+// =============================================================================++/**+ * Props for a custom Token component.+ * Renders the full token pill for a filter of a given type.+ */+export interface PowerSearchTokenProps {+ readonly config: PowerSearchConfig;+ readonly filter: PowerSearchFilter;+ readonly field: PowerSearchField;+ readonly operator: PowerSearchOperator;+ readonly maxLength: number;+ readonly onClick?: () => void;+ readonly onRemove?: () => void;+ readonly isDisabled?: boolean;+}++/**+ * Props for a custom Editor component.+ * Renders the full editor popover content for a filter of a given type.+ */+export interface PowerSearchEditorProps {+ readonly config: PowerSearchConfig;+ readonly filter: PartialFilter;+ readonly mode: 'create' | 'edit';+ readonly onSave: (filter: PowerSearchFilter | null) => void;+ readonly onCancel: () => void;+ readonly saveButtonLabel?: string;+ readonly isReadOnly?: boolean;+ readonly timezoneID?: string;+}++export interface PowerSearchComponentOverride {+ /** Replaces the full token pill for filters of this type. */+ readonly Token?: ComponentType<PowerSearchTokenProps>;+ /** Replaces the full editor popover content for filters of this type. */+ readonly Editor?: ComponentType<PowerSearchEditorProps>;+}++export type XDSPowerSearchComponents = Partial<+ Record<OperatorValue['type'], PowerSearchComponentOverride>+>;