An open source design system that's fully customizable and agent ready
TypeScript
powersearch filter implementation (#656)
Andrey Goderd742ded96b4e
diff --git a/apps/storybook/stories/PowerSearchWithTable.stories.tsx b/apps/storybook/stories/PowerSearchWithTable.stories.tsxnew file mode 100644index 0000000000..63f34fddf9--- /dev/null+++ b/apps/storybook/stories/PowerSearchWithTable.stories.tsx@@ -0,0 +1,234 @@+import {useState} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {XDSPowerSearch, usePowerSearchConfig} from '@xds/core/PowerSearch';+import type {PowerSearchFilter} from '@xds/core/PowerSearch';+import {XDSTable, pixel, proportional} from '@xds/core/Table';+import type {XDSTableColumn} from '@xds/core/Table';++// =============================================================================+// Field definitions+// =============================================================================++const genreValues = [+ {value: 'fiction', label: 'Fiction'},+ {value: 'non-fiction', label: 'Non-Fiction'},+ {value: 'sci-fi', label: 'Science Fiction'},+ {value: 'fantasy', label: 'Fantasy'},+ {value: 'mystery', label: 'Mystery'},+ {value: 'romance', label: 'Romance'},+ {value: 'biography', label: 'Biography'},+ {value: 'history', label: 'History'},+];++const fieldDefs = [+ {key: 'title', type: 'string', label: 'Title'},+ {key: 'author', type: 'string', label: 'Author'},+ {key: 'year', type: 'number', label: 'Publication Year'},+ {key: 'genre', type: 'enum', label: 'Genre', enumValues: genreValues},+] as const;++// =============================================================================+// Sample data+// =============================================================================++interface Book extends Record<string, unknown> {+ id: string;+ title: string;+ author: string;+ year: number;+ genre: string;+}++const books: Book[] = [+ {+ id: '1',+ title: 'Dune',+ author: 'Frank Herbert',+ year: 1965,+ genre: 'sci-fi',+ },+ {+ id: '2',+ title: 'Pride and Prejudice',+ author: 'Jane Austen',+ year: 1813,+ genre: 'romance',+ },+ {+ id: '3',+ title: 'The Great Gatsby',+ author: 'F. Scott Fitzgerald',+ year: 1925,+ genre: 'fiction',+ },+ {+ id: '4',+ title: '1984',+ author: 'George Orwell',+ year: 1949,+ genre: 'sci-fi',+ },+ {+ id: '5',+ title: 'To Kill a Mockingbird',+ author: 'Harper Lee',+ year: 1960,+ genre: 'fiction',+ },+ {+ id: '6',+ title: 'The Hobbit',+ author: 'J.R.R. Tolkien',+ year: 1937,+ genre: 'fantasy',+ },+ {+ id: '7',+ title: 'Sapiens',+ author: 'Yuval Noah Harari',+ year: 2011,+ genre: 'non-fiction',+ },+ {+ id: '8',+ title: 'The Name of the Wind',+ author: 'Patrick Rothfuss',+ year: 2007,+ genre: 'fantasy',+ },+ {+ id: '9',+ title: 'Gone Girl',+ author: 'Gillian Flynn',+ year: 2012,+ genre: 'mystery',+ },+ {+ id: '10',+ title: 'Steve Jobs',+ author: 'Walter Isaacson',+ year: 2011,+ genre: 'biography',+ },+ {+ id: '11',+ title: 'A Brief History of Time',+ author: 'Stephen Hawking',+ year: 1988,+ genre: 'non-fiction',+ },+ {+ id: '12',+ title: 'The Shining',+ author: 'Stephen King',+ year: 1977,+ genre: 'mystery',+ },+ {+ id: '13',+ title: "The Handmaid's Tale",+ author: 'Margaret Atwood',+ year: 1985,+ genre: 'sci-fi',+ },+ {+ id: '14',+ title: 'Outlander',+ author: 'Diana Gabaldon',+ year: 1991,+ genre: 'romance',+ },+ {+ id: '15',+ title: 'The Guns of August',+ author: 'Barbara Tuchman',+ year: 1962,+ genre: 'history',+ },+];++const columns: XDSTableColumn<Book>[] = [+ {key: 'title', header: 'Title', width: proportional(2)},+ {key: 'author', header: 'Author', width: proportional(2)},+ {key: 'year', header: 'Year', width: pixel(100)},+ {+ key: 'genre',+ header: 'Genre',+ width: pixel(140),+ renderCell: (book: Book) =>+ genreValues.find(g => g.value === book.genre)?.label ?? book.genre,+ },+];++// =============================================================================+// Meta+// =============================================================================++const meta: Meta = {+ title: 'Patterns/PowerSearch + Table',+ tags: ['autodocs'],+ decorators: [+ Story => (+ <div style={{width: 800}}>+ <Story />+ </div>+ ),+ ],+};++export default meta;+type Story = StoryObj;++// =============================================================================+// Stories+// =============================================================================++export const Default: Story = {+ render: () => {+ const [filters, setFilters] = useState<PowerSearchFilter[]>([]);+ const {config, applyFilters} = usePowerSearchConfig(fieldDefs, 'Books');+ const filteredBooks = applyFilters(filters, books);++ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>+ <XDSPowerSearch+ config={config}+ filters={filters}+ onChange={newFilters => setFilters([...newFilters])}+ placeholder="Filter books by title, author, year, genre..."+ resultCount={filteredBooks.length}+ />+ <XDSTable data={filteredBooks} columns={columns} idKey="id" hasHover />+ </div>+ );+ },+};++export const WithPresetFilters: Story = {+ render: () => {+ const [filters, setFilters] = useState<PowerSearchFilter[]>([+ {field: 'genre', operator: 'is', value: {type: 'enum', value: 'sci-fi'}},+ ]);+ const {config, applyFilters} = usePowerSearchConfig(fieldDefs, 'Books');+ const filteredBooks = applyFilters(filters, books);++ return (+ <div style={{display: 'flex', flexDirection: 'column', gap: 16}}>+ <XDSPowerSearch+ config={config}+ filters={filters}+ onChange={newFilters => setFilters([...newFilters])}+ placeholder="Filter books..."+ resultCount={filteredBooks.length}+ />+ <XDSTable+ data={filteredBooks}+ columns={columns}+ idKey="id"+ hasHover+ isStriped+ />+ </div>+ );+ },+};diff --git a/packages/core/src/PowerSearch/index.ts b/packages/core/src/PowerSearch/index.tsindex ae7841fa16..f5e1e3305f 100644--- a/packages/core/src/PowerSearch/index.ts+++ b/packages/core/src/PowerSearch/index.ts@@ -10,6 +10,12 @@export {XDSPowerSearch} from './XDSPowerSearch';export type {XDSPowerSearchProps} from './XDSPowerSearch';+export {+ createPowerSearchConfig,+ usePowerSearchConfig,+} from './usePowerSearchConfig';+export type {FieldDefinition, InferData} from './usePowerSearchConfig';+export type {// Config typesPowerSearchConfig,diff --git a/packages/core/src/PowerSearch/usePowerSearchConfig.test.ts b/packages/core/src/PowerSearch/usePowerSearchConfig.test.tsnew file mode 100644index 0000000000..c71dc51999--- /dev/null+++ b/packages/core/src/PowerSearch/usePowerSearchConfig.test.ts@@ -0,0 +1,804 @@+/**+ * @file usePowerSearchConfig.test.ts+ * @input createPowerSearchConfig utility+ * @output Tests for every field type + operator combination+ * @position Testing; validates usePowerSearchConfig.ts+ */++import {describe, it, expect} from 'vitest';+import {createPowerSearchConfig} from './usePowerSearchConfig';+import type {PowerSearchFilter} from './types';++// =============================================================================+// Test data setup+// =============================================================================++const statusEnumValues = [+ {value: 'active', label: 'Active'},+ {value: 'inactive', label: 'Inactive'},+ {value: 'pending', label: 'Pending'},+] as const;++const defs = [+ {key: 'name', type: 'string', label: 'Name'},+ {key: 'age', type: 'number', label: 'Age'},+ {key: 'createdAt', type: 'date', label: 'Created At'},+ {key: 'active', type: 'boolean', label: 'Active'},+ {+ key: 'role',+ type: 'enum',+ label: 'Role',+ enumValues: [+ {value: 'admin', label: 'Admin'},+ {value: 'user', label: 'User'},+ ],+ },+ {+ key: 'status',+ type: 'enum_list',+ label: 'Status',+ enumValues: statusEnumValues,+ },+ {key: 'tags', type: 'string_list', label: 'Tags'},+] as const;++const {config, applyFilters} = createPowerSearchConfig(defs, 'TestConfig');++const data = [+ {+ name: 'Alice Johnson',+ age: 30,+ createdAt: 1700000000,+ active: true,+ role: 'admin',+ status: 'active',+ tags: ['frontend', 'lead'],+ },+ {+ name: 'Bob Smith',+ age: 25,+ createdAt: 1700100000,+ active: false,+ role: 'user',+ status: 'inactive',+ tags: ['backend'],+ },+ {+ name: 'Charlie Brown',+ age: 35,+ createdAt: 1700200000,+ active: true,+ role: 'user',+ status: 'pending',+ tags: ['frontend', 'backend'],+ },+ {+ name: 'Diana Prince',+ age: 28,+ createdAt: 1700300000,+ active: true,+ role: 'admin',+ status: 'active',+ tags: ['devops'],+ },+] as const;++function filter(+ field: string,+ operator: string,+ value: PowerSearchFilter['value'],+): PowerSearchFilter {+ return {field, operator, value};+}++// =============================================================================+// Config generation+// =============================================================================++describe('createPowerSearchConfig', () => {+ it('generates config with correct name', () => {+ expect(config.name).toBe('TestConfig');+ });++ it('generates a field for each definition', () => {+ expect(config.fields).toHaveLength(7);+ expect(config.fields.map(f => f.key)).toEqual([+ 'name',+ 'age',+ 'createdAt',+ 'active',+ 'role',+ 'status',+ 'tags',+ ]);+ });++ it('uses key as label when label is not provided', () => {+ const {config: c} = createPowerSearchConfig([{key: 'foo', type: 'string'}]);+ expect(c.fields[0].label).toBe('foo');+ });++ it('generates string operators', () => {+ const field = config.fields.find(f => f.key === 'name')!;+ expect(field.operators.map(o => o.key)).toEqual([+ 'contains',+ 'not_contains',+ 'starts_with',+ 'not_starts_with',+ 'ends_with',+ 'not_ends_with',+ 'is',+ 'is_not',+ ]);+ expect(field.defaultOperator).toBe('contains');+ });++ it('generates number operators', () => {+ const field = config.fields.find(f => f.key === 'age')!;+ expect(field.operators.map(o => o.key)).toEqual([+ 'equals',+ 'not_equals',+ 'greater_than',+ 'less_than',+ 'greater_than_or_equal',+ 'less_than_or_equal',+ ]);+ expect(field.defaultOperator).toBe('equals');+ });++ it('generates date operators', () => {+ const field = config.fields.find(f => f.key === 'createdAt')!;+ expect(field.operators.map(o => o.key)).toEqual([+ 'before',+ 'after',+ 'between',+ ]);+ expect(field.defaultOperator).toBe('after');+ });++ it('generates boolean operators', () => {+ const field = config.fields.find(f => f.key === 'active')!;+ expect(field.operators.map(o => o.key)).toEqual(['is_true', 'is_false']);+ expect(field.defaultOperator).toBe('is_true');+ });++ it('generates enum operators with values', () => {+ const field = config.fields.find(f => f.key === 'role')!;+ expect(field.operators.map(o => o.key)).toEqual([+ 'is',+ 'is_not',+ 'is_any_of',+ 'is_none_of',+ ]);+ expect(field.defaultOperator).toBe('is');+ expect(field.operators[0].value).toEqual({+ type: 'enum',+ values: [+ {value: 'admin', label: 'Admin'},+ {value: 'user', label: 'User'},+ ],+ });+ });++ it('generates enum_list operators with values', () => {+ const field = config.fields.find(f => f.key === 'status')!;+ expect(field.operators.map(o => o.key)).toEqual([+ 'is_any_of',+ 'is_none_of',+ ]);+ expect(field.defaultOperator).toBe('is_any_of');+ });++ it('generates string_list operators', () => {+ const field = config.fields.find(f => f.key === 'tags')!;+ expect(field.operators.map(o => o.key)).toEqual([+ 'is_any_of',+ 'is_none_of',+ ]);+ expect(field.defaultOperator).toBe('is_any_of');+ });+});++// =============================================================================+// applyFilters — empty filters+// =============================================================================++describe('applyFilters', () => {+ it('returns all data when no filters are applied', () => {+ expect(applyFilters([], data)).toHaveLength(4);+ });++ // ===========================================================================+ // String operators+ // ===========================================================================++ describe('string: contains', () => {+ it('matches rows containing substring', () => {+ const result = applyFilters(+ [filter('name', 'contains', {type: 'string', value: 'ali'})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Alice Johnson');+ });+ });++ describe('string: not_contains', () => {+ it('excludes rows containing substring', () => {+ const result = applyFilters(+ [filter('name', 'not_contains', {type: 'string', value: 'ali'})],+ data,+ );+ expect(result).toHaveLength(3);+ expect(result.map(r => r.name)).not.toContain('Alice Johnson');+ });+ });++ describe('string: starts_with', () => {+ it('matches rows starting with prefix', () => {+ const result = applyFilters(+ [filter('name', 'starts_with', {type: 'string', value: 'cha'})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Charlie Brown');+ });+ });++ describe('string: not_starts_with', () => {+ it('excludes rows starting with prefix', () => {+ const result = applyFilters(+ [filter('name', 'not_starts_with', {type: 'string', value: 'cha'})],+ data,+ );+ expect(result).toHaveLength(3);+ });+ });++ describe('string: ends_with', () => {+ it('matches rows ending with suffix', () => {+ const result = applyFilters(+ [filter('name', 'ends_with', {type: 'string', value: 'smith'})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Bob Smith');+ });+ });++ describe('string: not_ends_with', () => {+ it('excludes rows ending with suffix', () => {+ const result = applyFilters(+ [filter('name', 'not_ends_with', {type: 'string', value: 'smith'})],+ data,+ );+ expect(result).toHaveLength(3);+ });+ });++ describe('string: is', () => {+ it('matches exact string (case-insensitive)', () => {+ const result = applyFilters(+ [filter('name', 'is', {type: 'string', value: 'bob smith'})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Bob Smith');+ });++ it('does not match partial strings', () => {+ const result = applyFilters(+ [filter('name', 'is', {type: 'string', value: 'bob'})],+ data,+ );+ expect(result).toHaveLength(0);+ });+ });++ describe('string: is_not', () => {+ it('excludes exact match', () => {+ const result = applyFilters(+ [filter('name', 'is_not', {type: 'string', value: 'bob smith'})],+ data,+ );+ expect(result).toHaveLength(3);+ });+ });++ // ===========================================================================+ // Number operators+ // ===========================================================================++ describe('number: equals', () => {+ it('matches exact number', () => {+ const result = applyFilters(+ [filter('age', 'equals', {type: 'float', value: 30})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Alice Johnson');+ });+ });++ describe('number: not_equals', () => {+ it('excludes exact number', () => {+ const result = applyFilters(+ [filter('age', 'not_equals', {type: 'float', value: 30})],+ data,+ );+ expect(result).toHaveLength(3);+ });+ });++ describe('number: greater_than', () => {+ it('matches numbers greater than value', () => {+ const result = applyFilters(+ [filter('age', 'greater_than', {type: 'float', value: 29})],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Alice Johnson',+ 'Charlie Brown',+ ]);+ });+ });++ describe('number: less_than', () => {+ it('matches numbers less than value', () => {+ const result = applyFilters(+ [filter('age', 'less_than', {type: 'float', value: 28})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Bob Smith');+ });+ });++ describe('number: greater_than_or_equal', () => {+ it('matches numbers >= value', () => {+ const result = applyFilters(+ [filter('age', 'greater_than_or_equal', {type: 'float', value: 30})],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Alice Johnson',+ 'Charlie Brown',+ ]);+ });+ });++ describe('number: less_than_or_equal', () => {+ it('matches numbers <= value', () => {+ const result = applyFilters(+ [filter('age', 'less_than_or_equal', {type: 'float', value: 28})],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Bob Smith',+ 'Diana Prince',+ ]);+ });+ });++ // ===========================================================================+ // Date operators+ // ===========================================================================++ describe('date: before', () => {+ it('matches dates before value', () => {+ const result = applyFilters(+ [+ filter('createdAt', 'before', {+ type: 'date_absolute',+ unixSeconds: 1700100000,+ }),+ ],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Alice Johnson');+ });+ });++ describe('date: after', () => {+ it('matches dates after value', () => {+ const result = applyFilters(+ [+ filter('createdAt', 'after', {+ type: 'date_absolute',+ unixSeconds: 1700200000,+ }),+ ],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Diana Prince');+ });+ });++ describe('date: between', () => {+ it('matches dates within absolute range', () => {+ const result = applyFilters(+ [+ filter('createdAt', 'between', {+ type: 'date_range',+ value: {+ start: {type: 'ABSOLUTE', unixSeconds: 1700050000},+ end: {type: 'ABSOLUTE', unixSeconds: 1700250000},+ },+ }),+ ],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Bob Smith',+ 'Charlie Brown',+ ]);+ });++ it('handles NOW range part', () => {+ // All test data timestamps are in the past, so "between <past> and NOW" should include them+ const result = applyFilters(+ [+ filter('createdAt', 'between', {+ type: 'date_range',+ value: {+ start: {type: 'ABSOLUTE', unixSeconds: 1700000000},+ end: {type: 'NOW'},+ },+ }),+ ],+ data,+ );+ expect(result).toHaveLength(4);+ });++ it('handles RELATIVE range part', () => {+ // Use a very large relative range to capture all test data+ const result = applyFilters(+ [+ filter('createdAt', 'between', {+ type: 'date_range',+ value: {+ start: {type: 'RELATIVE', backValue: 3650, unit: 'day'},+ end: {type: 'NOW'},+ },+ }),+ ],+ data,+ );+ expect(result).toHaveLength(4);+ });+ });++ describe('date: works with Date objects', () => {+ it('converts Date to unix seconds', () => {+ const dateData = [+ {+ name: 'Test',+ age: 1,+ createdAt: new Date(1700100000 * 1000),+ active: true,+ role: 'user',+ status: 'active',+ tags: ['a'],+ },+ ];+ const result = applyFilters(+ [+ filter('createdAt', 'after', {+ type: 'date_absolute',+ unixSeconds: 1700000000,+ }),+ ],+ dateData,+ );+ expect(result).toHaveLength(1);+ });+ });++ // ===========================================================================+ // Boolean operators+ // ===========================================================================++ describe('boolean: is_true', () => {+ it('matches truthy values', () => {+ const result = applyFilters(+ [filter('active', 'is_true', {type: 'empty'})],+ data,+ );+ expect(result).toHaveLength(3);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Alice Johnson',+ 'Charlie Brown',+ 'Diana Prince',+ ]);+ });+ });++ describe('boolean: is_false', () => {+ it('matches falsy values', () => {+ const result = applyFilters(+ [filter('active', 'is_false', {type: 'empty'})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Bob Smith');+ });+ });++ // ===========================================================================+ // Enum operators+ // ===========================================================================++ describe('enum: is', () => {+ it('matches exact enum value', () => {+ const result = applyFilters(+ [filter('role', 'is', {type: 'enum', value: 'admin'})],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Alice Johnson',+ 'Diana Prince',+ ]);+ });+ });++ describe('enum: is_not', () => {+ it('excludes exact enum value', () => {+ const result = applyFilters(+ [filter('role', 'is_not', {type: 'enum', value: 'admin'})],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Bob Smith',+ 'Charlie Brown',+ ]);+ });+ });++ describe('enum: is_any_of', () => {+ it('matches when value is in the list', () => {+ const result = applyFilters(+ [+ filter('role', 'is_any_of', {+ type: 'enum_list',+ value: ['admin', 'user'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(4);+ });++ it('matches subset of values', () => {+ const result = applyFilters(+ [+ filter('role', 'is_any_of', {+ type: 'enum_list',+ value: ['admin'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Alice Johnson',+ 'Diana Prince',+ ]);+ });+ });++ describe('enum: is_none_of', () => {+ it('excludes rows matching any value in the list', () => {+ const result = applyFilters(+ [+ filter('role', 'is_none_of', {+ type: 'enum_list',+ value: ['admin'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Bob Smith',+ 'Charlie Brown',+ ]);+ });+ });++ // ===========================================================================+ // Enum list operators+ // ===========================================================================++ describe('enum_list: is_any_of', () => {+ it('matches when value is in the list', () => {+ const result = applyFilters(+ [+ filter('status', 'is_any_of', {+ type: 'enum_list',+ value: ['active', 'pending'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(3);+ });++ it('returns empty when no values match', () => {+ const result = applyFilters(+ [+ filter('status', 'is_any_of', {+ type: 'enum_list',+ value: ['archived'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(0);+ });+ });++ describe('enum_list: is_none_of', () => {+ it('excludes rows matching any value in the list', () => {+ const result = applyFilters(+ [+ filter('status', 'is_none_of', {+ type: 'enum_list',+ value: ['active'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Bob Smith',+ 'Charlie Brown',+ ]);+ });+ });++ // ===========================================================================+ // String list operators+ // ===========================================================================++ describe('string_list: is_any_of', () => {+ it('matches when any array element is in the filter list', () => {+ const result = applyFilters(+ [filter('tags', 'is_any_of', {type: 'string_list', value: ['devops']})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Diana Prince');+ });++ it('matches multiple tags', () => {+ const result = applyFilters(+ [+ filter('tags', 'is_any_of', {+ type: 'string_list',+ value: ['frontend'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Alice Johnson',+ 'Charlie Brown',+ ]);+ });+ });++ describe('string_list: is_none_of', () => {+ it('excludes rows with any matching tag', () => {+ const result = applyFilters(+ [+ filter('tags', 'is_none_of', {+ type: 'string_list',+ value: ['frontend'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(2);+ expect(result.map(r => r.name).sort()).toEqual([+ 'Bob Smith',+ 'Diana Prince',+ ]);+ });++ it('excludes rows matching multiple tags', () => {+ const result = applyFilters(+ [+ filter('tags', 'is_none_of', {+ type: 'string_list',+ value: ['frontend', 'devops'],+ }),+ ],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Bob Smith');+ });+ });++ // ===========================================================================+ // Combined filters (AND logic)+ // ===========================================================================++ describe('multiple filters', () => {+ it('applies all filters with AND logic', () => {+ const result = applyFilters(+ [+ filter('role', 'is', {type: 'enum', value: 'admin'}),+ filter('active', 'is_true', {type: 'empty'}),+ filter('age', 'greater_than', {type: 'float', value: 29}),+ ],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Alice Johnson');+ });++ it('returns empty when filters are contradictory', () => {+ const result = applyFilters(+ [+ filter('active', 'is_true', {type: 'empty'}),+ filter('active', 'is_false', {type: 'empty'}),+ ],+ data,+ );+ expect(result).toHaveLength(0);+ });+ });++ // ===========================================================================+ // Edge cases+ // ===========================================================================++ describe('edge cases', () => {+ it('unknown operator passes through (does not filter)', () => {+ const result = applyFilters(+ [filter('name', 'unknown_op', {type: 'string', value: 'test'})],+ data,+ );+ expect(result).toHaveLength(4);+ });++ it('string operators are case-insensitive', () => {+ const result = applyFilters(+ [filter('name', 'contains', {type: 'string', value: 'ALICE'})],+ data,+ );+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe('Alice Johnson');+ });++ it('handles string_list field with scalar value (non-array)', () => {+ const scalarData = [+ {+ name: 'Test',+ age: 1,+ createdAt: 0,+ active: true,+ role: 'user',+ status: 'active',+ tags: 'solo' as unknown as ReadonlyArray<string>,+ },+ ];+ const result = applyFilters(+ [filter('tags', 'is_any_of', {type: 'string_list', value: ['solo']})],+ scalarData,+ );+ expect(result).toHaveLength(1);+ });+ });+});diff --git a/packages/core/src/PowerSearch/usePowerSearchConfig.ts b/packages/core/src/PowerSearch/usePowerSearchConfig.tsnew file mode 100644index 0000000000..e16be4786d--- /dev/null+++ b/packages/core/src/PowerSearch/usePowerSearchConfig.ts@@ -0,0 +1,564 @@+/**+ * @file usePowerSearchConfig.ts+ * @input Field definitions with simplified types+ * @output PowerSearchConfig + applyFilters function for client-side filtering+ * @position Utility hook; sits alongside PowerSearch core types+ */++import {useMemo} from 'react';+import type {+ DateTimeRangePart,+ EnumItem,+ PowerSearchConfig,+ PowerSearchField,+ PowerSearchFilter,+ PowerSearchOperator,+} from './types';++// =============================================================================+// Public Types+// =============================================================================++type FieldType =+ | 'string'+ | 'number'+ | 'boolean'+ | 'date'+ | 'enum'+ | 'enum_list'+ | 'string_list';++type FieldTypeToJS = {+ string: string;+ number: number;+ boolean: boolean;+ date: Date | number;+ enum: string;+ enum_list: ReadonlyArray<string>;+ string_list: ReadonlyArray<string>;+};++export interface FieldDefinition<+ K extends string = string,+ T extends FieldType = FieldType,+> {+ readonly key: K;+ readonly type: T;+ readonly label?: string;+ /** Required for 'enum' and 'enum_list' field types. */+ readonly enumValues?: ReadonlyArray<EnumItem>;+}++/** Infers the data record type from a tuple of FieldDefinitions. */+export type InferData<D extends ReadonlyArray<FieldDefinition>> = {+ [F in D[number] as F['key']]: FieldTypeToJS[F['type']];+};++// =============================================================================+// Operator key constants+// =============================================================================++const StringOps = {+ CONTAINS: 'contains',+ NOT_CONTAINS: 'not_contains',+ STARTS_WITH: 'starts_with',+ NOT_STARTS_WITH: 'not_starts_with',+ ENDS_WITH: 'ends_with',+ NOT_ENDS_WITH: 'not_ends_with',+ IS: 'is',+ IS_NOT: 'is_not',+} as const;++const NumberOps = {+ EQUALS: 'equals',+ NOT_EQUALS: 'not_equals',+ GREATER_THAN: 'greater_than',+ LESS_THAN: 'less_than',+ GREATER_THAN_OR_EQUAL: 'greater_than_or_equal',+ LESS_THAN_OR_EQUAL: 'less_than_or_equal',+} as const;++const DateOps = {+ BEFORE: 'before',+ AFTER: 'after',+ BETWEEN: 'between',+} as const;++const BooleanOps = {+ IS_TRUE: 'is_true',+ IS_FALSE: 'is_false',+} as const;++const EnumOps = {+ IS: 'is',+ IS_NOT: 'is_not',+} as const;++const EnumListOps = {+ IS_ANY_OF: 'is_any_of',+ IS_NONE_OF: 'is_none_of',+} as const;++const StringListOps = {+ IS_ANY_OF: 'is_any_of',+ IS_NONE_OF: 'is_none_of',+} as const;++// =============================================================================+// Default operators per field type+// =============================================================================++function stringOperators(): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: StringOps.CONTAINS,+ operators: [+ {key: StringOps.CONTAINS, label: 'contains', value: {type: 'string'}},+ {+ key: StringOps.NOT_CONTAINS,+ label: 'does not contain',+ value: {type: 'string'},+ },+ {+ key: StringOps.STARTS_WITH,+ label: 'starts with',+ value: {type: 'string'},+ },+ {+ key: StringOps.NOT_STARTS_WITH,+ label: 'does not start with',+ value: {type: 'string'},+ },+ {key: StringOps.ENDS_WITH, label: 'ends with', value: {type: 'string'}},+ {+ key: StringOps.NOT_ENDS_WITH,+ label: 'does not end with',+ value: {type: 'string'},+ },+ {key: StringOps.IS, label: 'is', value: {type: 'string'}},+ {key: StringOps.IS_NOT, label: 'is not', value: {type: 'string'}},+ ],+ };+}++function numberOperators(): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: NumberOps.EQUALS,+ operators: [+ {+ key: NumberOps.EQUALS,+ label: 'is',+ value: {type: 'float'},+ },+ {+ key: NumberOps.NOT_EQUALS,+ label: 'is not',+ value: {type: 'float'},+ },+ {+ key: NumberOps.GREATER_THAN,+ label: 'is greater than',+ value: {type: 'float'},+ },+ {+ key: NumberOps.LESS_THAN,+ label: 'is less than',+ value: {type: 'float'},+ },+ {+ key: NumberOps.GREATER_THAN_OR_EQUAL,+ label: 'is greater than or equal to',+ value: {type: 'float'},+ },+ {+ key: NumberOps.LESS_THAN_OR_EQUAL,+ label: 'is less than or equal to',+ value: {type: 'float'},+ },+ ],+ };+}++function dateOperators(): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: DateOps.AFTER,+ operators: [+ {+ key: DateOps.BEFORE,+ label: 'is before',+ value: {type: 'date_absolute'},+ },+ {+ key: DateOps.AFTER,+ label: 'is after',+ value: {type: 'date_absolute'},+ },+ {+ key: DateOps.BETWEEN,+ label: 'is between',+ value: {type: 'date_range'},+ },+ ],+ };+}++function booleanOperators(): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: BooleanOps.IS_TRUE,+ operators: [+ {key: BooleanOps.IS_TRUE, label: 'is true', value: {type: 'empty'}},+ {key: BooleanOps.IS_FALSE, label: 'is false', value: {type: 'empty'}},+ ],+ };+}++function enumOperators(values: ReadonlyArray<EnumItem>): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: EnumOps.IS,+ operators: [+ {key: EnumOps.IS, label: 'is', value: {type: 'enum', values}},+ {key: EnumOps.IS_NOT, label: 'is not', value: {type: 'enum', values}},+ {+ key: EnumListOps.IS_ANY_OF,+ label: 'is any of',+ value: {type: 'enum_list', values},+ },+ {+ key: EnumListOps.IS_NONE_OF,+ label: 'is none of',+ value: {type: 'enum_list', values},+ },+ ],+ };+}++function enumListOperators(values: ReadonlyArray<EnumItem>): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: EnumListOps.IS_ANY_OF,+ operators: [+ {+ key: EnumListOps.IS_ANY_OF,+ label: 'is any of',+ value: {type: 'enum_list', values},+ },+ {+ key: EnumListOps.IS_NONE_OF,+ label: 'is none of',+ value: {type: 'enum_list', values},+ },+ ],+ };+}++function stringListOperators(): {+ defaultOperator: string;+ operators: ReadonlyArray<PowerSearchOperator>;+} {+ return {+ defaultOperator: StringListOps.IS_ANY_OF,+ operators: [+ {+ key: StringListOps.IS_ANY_OF,+ label: 'is any of',+ value: {type: 'string_list'},+ },+ {+ key: StringListOps.IS_NONE_OF,+ label: 'is none of',+ value: {type: 'string_list'},+ },+ ],+ };+}++// =============================================================================+// Config builder+// =============================================================================++function buildField(def: FieldDefinition): PowerSearchField {+ const label = def.label ?? def.key;++ switch (def.type) {+ case 'string': {+ const ops = stringOperators();+ return {key: def.key, label, ...ops};+ }+ case 'number': {+ const ops = numberOperators();+ return {key: def.key, label, ...ops};+ }+ case 'date': {+ const ops = dateOperators();+ return {key: def.key, label, ...ops};+ }+ case 'boolean': {+ const ops = booleanOperators();+ return {key: def.key, label, ...ops};+ }+ case 'enum': {+ const values = def.enumValues ?? [];+ const ops = enumOperators(values);+ return {key: def.key, label, ...ops};+ }+ case 'enum_list': {+ const values = def.enumValues ?? [];+ const ops = enumListOperators(values);+ return {key: def.key, label, ...ops};+ }+ case 'string_list': {+ const ops = stringListOperators();+ return {key: def.key, label, ...ops};+ }+ }+}++// =============================================================================+// Filter application+// =============================================================================++function toUnixSeconds(value: Date | number): number {+ if (value instanceof Date) {+ return Math.floor(value.getTime() / 1000);+ }+ return value;+}++function resolveRangePart(part: DateTimeRangePart): number {+ switch (part.type) {+ case 'NOW':+ return Math.floor(Date.now() / 1000);+ case 'ABSOLUTE':+ return part.unixSeconds;+ case 'RELATIVE': {+ const now = Date.now() / 1000;+ const multipliers: Record<string, number> = {+ second: 1,+ minute: 60,+ hour: 3600,+ day: 86400,+ week: 604800,+ month: 2592000,+ year: 31536000,+ };+ return Math.floor(now - part.backValue * (multipliers[part.unit] ?? 0));+ }+ }+}++function matchesFilter(+ row: Record<string, unknown>,+ filter: PowerSearchFilter,+): boolean {+ const fieldValue = row[filter.field];+ const {operator, value: filterValue} = filter;++ switch (filterValue.type) {+ case 'empty': {+ if (operator === BooleanOps.IS_TRUE) return Boolean(fieldValue) === true;+ if (operator === BooleanOps.IS_FALSE)+ return Boolean(fieldValue) === false;+ return true;+ }++ case 'string': {+ const s = String(fieldValue ?? '').toLowerCase();+ const target = filterValue.value.toLowerCase();+ if (operator in stringOpHandlers) {+ return stringOpHandlers[operator as keyof typeof stringOpHandlers](+ s,+ target,+ );+ }+ return true;+ }++ case 'integer':+ case 'float': {+ const n = Number(fieldValue);+ const target = filterValue.value;+ if (operator in numberOpHandlers) {+ return numberOpHandlers[operator as keyof typeof numberOpHandlers](+ n,+ target,+ );+ }+ return true;+ }++ case 'date_absolute': {+ const ts = toUnixSeconds(fieldValue as Date | number);+ if (operator === DateOps.BEFORE) return ts < filterValue.unixSeconds;+ if (operator === DateOps.AFTER) return ts > filterValue.unixSeconds;+ return true;+ }++ case 'date_range': {+ const ts = toUnixSeconds(fieldValue as Date | number);+ if (operator === DateOps.BETWEEN) {+ const start = resolveRangePart(filterValue.value.start);+ const end = resolveRangePart(filterValue.value.end);+ return ts >= start && ts <= end;+ }+ return true;+ }++ case 'enum': {+ if (operator === EnumOps.IS)+ return String(fieldValue) === filterValue.value;+ if (operator === EnumOps.IS_NOT)+ return String(fieldValue) !== filterValue.value;+ return true;+ }++ case 'enum_list': {+ const sv = String(fieldValue);+ if (operator === EnumListOps.IS_ANY_OF)+ return filterValue.value.includes(sv);+ if (operator === EnumListOps.IS_NONE_OF)+ return !filterValue.value.includes(sv);+ return true;+ }++ case 'string_list': {+ const arr = Array.isArray(fieldValue)+ ? (fieldValue as string[])+ : [String(fieldValue)];+ if (operator === StringListOps.IS_ANY_OF) {+ return arr.some(v => filterValue.value.includes(v));+ }+ if (operator === StringListOps.IS_NONE_OF) {+ return arr.every(v => !filterValue.value.includes(v));+ }+ return true;+ }++ default:+ return true;+ }+}++const stringOpHandlers = {+ [StringOps.CONTAINS]: (s: string, t: string) => s.includes(t),+ [StringOps.NOT_CONTAINS]: (s: string, t: string) => !s.includes(t),+ [StringOps.STARTS_WITH]: (s: string, t: string) => s.startsWith(t),+ [StringOps.NOT_STARTS_WITH]: (s: string, t: string) => !s.startsWith(t),+ [StringOps.ENDS_WITH]: (s: string, t: string) => s.endsWith(t),+ [StringOps.NOT_ENDS_WITH]: (s: string, t: string) => !s.endsWith(t),+ [StringOps.IS]: (s: string, t: string) => s === t,+ [StringOps.IS_NOT]: (s: string, t: string) => s !== t,+} as const;++const numberOpHandlers = {+ [NumberOps.EQUALS]: (n: number, t: number) => n === t,+ [NumberOps.NOT_EQUALS]: (n: number, t: number) => n !== t,+ [NumberOps.GREATER_THAN]: (n: number, t: number) => n > t,+ [NumberOps.LESS_THAN]: (n: number, t: number) => n < t,+ [NumberOps.GREATER_THAN_OR_EQUAL]: (n: number, t: number) => n >= t,+ [NumberOps.LESS_THAN_OR_EQUAL]: (n: number, t: number) => n <= t,+} as const;++// =============================================================================+// Public API+// =============================================================================++/**+ * Creates a PowerSearchConfig and an applyFilters function from field definitions.+ *+ * @example+ * ```+ * const defs = [+ * { key: 'name', type: 'string', label: 'Name' },+ * { key: 'age', type: 'number', label: 'Age' },+ * { key: 'active', type: 'boolean', label: 'Active' },+ * ] as const;+ *+ * const { config, applyFilters } = createPowerSearchConfig(defs);+ * const filtered = applyFilters(filters, data);+ * ```+ */+export function createPowerSearchConfig<+ const D extends ReadonlyArray<FieldDefinition>,+>(+ definitions: D,+ configName?: string,+): {+ config: PowerSearchConfig;+ applyFilters: <T extends InferData<D>>(+ filters: ReadonlyArray<PowerSearchFilter>,+ data: ReadonlyArray<T>,+ ) => Array<T>;+} {+ const fields = definitions.map(buildField);++ const config: PowerSearchConfig = {+ name: configName ?? 'PowerSearchConfig',+ fields,+ };++ function applyFilters<T extends InferData<D>>(+ filters: ReadonlyArray<PowerSearchFilter>,+ data: ReadonlyArray<T>,+ ): Array<T> {+ if (filters.length === 0) return [...data];+ return data.filter(row =>+ filters.every(f => matchesFilter(row as Record<string, unknown>, f)),+ );+ }++ return {config, applyFilters};+}++/**+ * React hook that memoizes the result of createPowerSearchConfig.+ *+ * @example+ * ```+ * const defs = [+ * { key: 'name', type: 'string', label: 'Name' },+ * { key: 'status', type: 'enum', label: 'Status', enumValues: [+ * { value: 'active', label: 'Active' },+ * { value: 'inactive', label: 'Inactive' },+ * ]},+ * ] as const;+ *+ * function MyComponent() {+ * const { config, applyFilters } = usePowerSearchConfig(defs);+ * const filtered = applyFilters(filters, data);+ * // ...+ * }+ * ```+ */+export function usePowerSearchConfig<+ const D extends ReadonlyArray<FieldDefinition>,+>(+ definitions: D,+ configName?: string,+): {+ config: PowerSearchConfig;+ applyFilters: <T extends InferData<D>>(+ filters: ReadonlyArray<PowerSearchFilter>,+ data: ReadonlyArray<T>,+ ) => Array<T>;+} {+ return useMemo(+ () => createPowerSearchConfig(definitions, configName),+ [definitions, configName],+ );+}