diff --git a/__test__/components/table-pro-search.spec.ts b/__test__/components/table-pro-search.spec.ts new file mode 100644 index 00000000..2875e2ed --- /dev/null +++ b/__test__/components/table-pro-search.spec.ts @@ -0,0 +1,648 @@ +import { RTablePro, useTablePro } from '@ray-template/ui/table-pro' +import type { + TableProParams, + TableProSearchActions, + TableProSearchOptionContext, + TableProSearchOptions, +} from '@ray-template/ui/table-pro' +import { flushPromises, mount } from '@vue/test-utils' +import { NDataTable, NDatePicker, NSelect } from 'naive-ui' +import { defineComponent, h, nextTick, shallowRef } from 'vue' + +const columns = [{ key: 'name', title: 'Name' }] +const statusOptions = [ + { label: 'Open', value: 'open' }, + { label: 'Closed', value: 'closed' }, +] + +it('matches text, multiple values, dates, zero and false before local pagination', async () => { + const [register, actions] = useTablePro() + const data = [ + { + id: 1, + name: 'Other', + status: 'open', + day: '2026-11-02', + amount: 0, + active: false, + }, + { + id: 2, + name: 'Notebook', + status: 'closed', + day: '2026-11-04', + amount: 0, + active: false, + }, + { + id: 3, + name: 'Notebook XL', + status: 'open', + day: '2026-11-05', + amount: 0, + active: false, + }, + { + id: 4, + name: 'Notebook Pro', + status: 'open', + day: '2026-11-03', + amount: 0, + active: true, + }, + ] + const search = { + fields: [ + { key: 'name', label: 'Name', type: 'text' }, + { + key: 'status', + label: 'Status', + type: 'select', + multiple: true, + options: statusOptions, + }, + { key: 'day', label: 'Created', type: 'dateRange' }, + { key: 'amount', label: 'Amount', type: 'number' }, + { key: 'active', label: 'Active', type: 'boolean' }, + ], + } satisfies TableProSearchOptions + const wrapper = mount(RTablePro, { + props: { + columns, + data, + search, + pageSize: 1, + onRegister: register, + tool: false, + }, + }) + + try { + await actions.setPage(2) + actions.setSearchValues({ + name: ' NOTE ', + status: ['open', 'closed'], + day: ['2026-11-02', '2026-11-04'], + amount: 0, + active: false, + }) + await nextTick() + + expect(wrapper.getComponent(NDataTable).props('data')).toEqual(data) + expect(wrapper.getComponent(NDatePicker).props('formattedValue')).toEqual([ + '2026-11-02', + '2026-11-04', + ]) + expect(await actions.submitSearch()).toBe(true) + await nextTick() + + expect(actions.getCurrentPageData()).toEqual([data[1]]) + expect(actions.getSearchValues('applied')).toMatchObject({ + name: 'NOTE', + amount: 0, + active: false, + }) + expect(await actions.resetSearch()).toBe(true) + await nextTick() + expect(actions.getCurrentPageData()).toEqual([data[0]]) + } finally { + wrapper.unmount() + } +}) + +it('serializes remote search once per submit and reuses the applied snapshot when paging', async () => { + const [register, actions] = useTablePro() + const request = vi.fn(async (_params: TableProParams) => ({ + data: [], + total: 80, + })) + const search = { + initialValues: { status: ['open'] }, + fields: [ + { + key: 'status', + label: 'Status', + type: 'select', + multiple: true, + options: statusOptions, + }, + { + key: 'createdAt', + label: 'Created', + type: 'dateRange', + transform: ([from, to]) => ({ from, to, page: 99, pageSize: 99 }), + }, + { key: 'name', label: 'Name', type: 'text' }, + ], + } satisfies TableProSearchOptions + const wrapper = mount(RTablePro, { + props: { + columns, + search, + request, + params: { status: 'external', scope: 'orders', page: 200 }, + onRegister: register, + tool: false, + }, + }) + + try { + const initial = { status: ['open'], scope: 'orders', page: 1, pageSize: 10 } + + expect(request.mock.lastCall?.[0]).toEqual(initial) + await actions.setPage(3) + const status = ['closed'] + + actions.setSearchValues({ + status, + createdAt: ['2026-11-01', '2026-11-04'], + name: ' ', + }) + status.push('open') + expect(request).toHaveBeenCalledTimes(2) + + await wrapper.get('form').trigger('submit') + await flushPromises() + + const applied = { + status: ['closed'], + from: '2026-11-01', + to: '2026-11-04', + scope: 'orders', + page: 1, + pageSize: 10, + } + + expect(request.mock.lastCall?.[0]).toEqual(applied) + expect(wrapper.emitted('search')).toEqual([ + [ + { + reason: 'submit', + values: { + status: ['closed'], + createdAt: ['2026-11-01', '2026-11-04'], + }, + params: { status: ['closed'], from: '2026-11-01', to: '2026-11-04' }, + }, + ], + ]) + actions.setSearchValues({ status: [] }) + await actions.setPage(2) + await actions.reload() + expect(request.mock.calls.slice(-2).map(([params]) => params)).toEqual([ + { ...applied, page: 2 }, + { ...applied, page: 2 }, + ]) + expect(await actions.resetSearch()).toBe(true) + expect(request.mock.lastCall?.[0]).toEqual(initial) + expect(request).toHaveBeenCalledTimes(6) + } finally { + wrapper.unmount() + } +}) + +it('expands a collapsed field when validation rejects and preserves the last query', async () => { + const [register, actions] = useTablePro() + const request = vi.fn(async (_params: TableProParams) => ({ + data: [], + total: 0, + })) + const search: TableProSearchOptions = { + defaultCollapsed: true, + fields: [ + { + key: 'status', + label: 'Status', + type: 'select', + options: statusOptions, + }, + { + key: 'name', + label: 'Name', + type: 'text', + rules: { required: true, message: 'Enter a name' }, + }, + ], + } + const wrapper = mount(RTablePro, { + props: { columns, search, request, onRegister: register, tool: false }, + }) + + try { + expect( + wrapper.get('button[aria-expanded]').attributes('aria-expanded'), + ).toBe('false') + actions.setSearchValues({ name: ' ' }) + expect(await actions.submitSearch()).toBe(false) + expect( + wrapper.get('button[aria-expanded]').attributes('aria-expanded'), + ).toBe('true') + expect(wrapper.text()).toContain('Enter a name') + expect(request).toHaveBeenCalledTimes(1) + actions.setSearchValues({ name: ' Ray ' }) + expect(await actions.submitSearch()).toBe(true) + expect(request.mock.lastCall?.[0]).toEqual({ + name: 'Ray', + page: 1, + pageSize: 10, + }) + } finally { + wrapper.unmount() + } +}) + +it('keeps legacy single-select exact matching and lets filters own submission', async () => { + const [register, actions] = useTablePro() + const data = [ + { id: 1, name: 'Original', status: 'open' }, + { id: 2, name: 'Reopened', status: 'reopened' }, + ] + const props = { + columns, + data, + search: [{ key: 'status', label: 'Status', options: statusOptions }], + onRegister: register, + tool: false, + } + const legacy = mount(RTablePro, { props }) + + try { + expect(legacy.getComponent(NSelect).props('multiple')).toBeFalsy() + actions.setSearchValues({ status: 'open' }) + await legacy.get('form').trigger('submit') + expect(actions.getCurrentPageData()).toEqual([data[0]]) + } finally { + legacy.unmount() + } + + const custom = mount(RTablePro, { + props, + slots: { + filters: ({ + submit, + }: { + submit: (values: Record) => Promise + }) => + h( + 'button', + { onClick: () => void submit({ status: 'open' }) }, + 'Apply', + ), + }, + }) + + try { + expect(custom.find('form').exists()).toBe(false) + await custom.get('button').trigger('click') + expect(actions.getCurrentPageData()).toEqual([data[0]]) + } finally { + custom.unmount() + } +}) + +it('delegates manual remote search to the caller and supports custom actions', async () => { + const data = [{ id: 1, name: 'Original' }] + const onSearch = vi.fn() + const search: TableProSearchOptions = { + fields: [{ key: 'name', label: 'Name', type: 'text' }], + renderActions: ({ submit }: TableProSearchActions) => + h( + 'button', + { type: 'button', onClick: () => void submit() }, + 'Apply filters', + ), + } + const wrapper = mount(RTablePro, { + props: { columns, data, remote: true, search, onSearch, tool: false }, + }) + + try { + await wrapper.get('input').setValue('Different') + await wrapper.get('button').trigger('click') + expect(onSearch).toHaveBeenCalledWith({ + reason: 'submit', + values: { name: 'Different' }, + params: { name: 'Different' }, + }) + expect(wrapper.getComponent(NDataTable).props('data')).toEqual(data) + } finally { + wrapper.unmount() + } +}) + +it('uses explicitly searchable leaf columns and treats explicit fields as authoritative', async () => { + const [register, actions] = useTablePro() + const request = vi.fn(async (_params: TableProParams) => ({ + data: [], + total: 10, + })) + const wrapper = mount(RTablePro, { + props: { + columns: [ + { type: 'selection' }, + { + key: 'group', + title: 'Group', + search: true, + children: [ + { key: 'name', title: 'Name', search: true }, + { + key: 'created', + title: 'Created', + search: { + type: 'dateRange', + transform: ([from, to]) => ({ from, to }), + }, + }, + ], + }, + { key: 'excluded', title: 'Excluded', search: false }, + ], + search: {}, + request, + onRegister: register, + tool: false, + }, + }) + + try { + expect(wrapper.get('form').text()).toContain('Name') + expect(wrapper.get('form').text()).toContain('Created') + expect(wrapper.get('form').text()).not.toMatch(/Group|Excluded/) + actions.setSearchValues({ + name: 'Ray', + created: ['2026-11-01', '2026-11-04'], + }) + await actions.submitSearch() + expect(request.mock.lastCall?.[0]).toEqual({ + name: 'Ray', + from: '2026-11-01', + to: '2026-11-04', + page: 1, + pageSize: 10, + }) + await wrapper.setProps({ search: { fields: [] } }) + expect(wrapper.find('form').exists()).toBe(false) + expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 }) + } finally { + wrapper.unmount() + } +}) + +it('clears a dependent draft, cancels obsolete options and keeps table requests independent', async () => { + const [register, actions] = useTablePro() + const request = vi.fn(async (_params: TableProParams) => ({ + data: [], + total: 40, + })) + const north = Promise.withResolvers<{ label: string; value: string }[]>() + const south = Promise.withResolvers<{ label: string; value: string }[]>() + const loadOptions = vi.fn(({ values }: TableProSearchOptionContext) => + values.org === 'north' ? north.promise : south.promise, + ) + const search: TableProSearchOptions = { + initialValues: { org: 'north', owner: 'n1' }, + fields: [ + { + type: 'select', + key: 'org', + label: 'Organization', + options: [ + { label: 'North', value: 'north' }, + { label: 'South', value: 'south' }, + ], + }, + { + type: 'select', + key: 'owner', + label: 'Owner', + dependsOn: ['org'], + visible: ({ org }) => org != null, + loadOptions, + }, + ], + } + const wrapper = mount(RTablePro, { + props: { columns, search, request, onRegister: register, tool: false }, + }) + + try { + const selects = () => wrapper.get('form').findAllComponents(NSelect) + const spinner = 'svg.n-base-loading__icon' + + expect(loadOptions).toHaveBeenCalledTimes(1) + expect(selects()[0].find(spinner).exists()).toBe(false) + expect(selects()[1].find(spinner).exists()).toBe(true) + actions.setSearchValues({ org: 'south' }) + await nextTick() + + expect(actions.getSearchValues().owner).toBeNull() + expect(actions.getSearchValues('applied').owner).toBe('n1') + expect(loadOptions).toHaveBeenCalledTimes(2) + expect(loadOptions.mock.calls[0][0].signal.aborted).toBe(true) + + south.resolve([{ label: 'South Owner', value: 's1' }]) + await flushPromises() + north.resolve([{ label: 'North Owner', value: 'n1' }]) + await flushPromises() + + expect(selects()[1].props('options')).toEqual([ + { label: 'South Owner', value: 's1' }, + ]) + expect(selects()[1].find(spinner).exists()).toBe(false) + expect(request).toHaveBeenCalledTimes(1) + actions.setSearchValues({ owner: 's1' }) + await actions.submitSearch() + expect(request.mock.lastCall?.[0]).toMatchObject({ + org: 'south', + owner: 's1', + }) + + actions.setSearchValues({ org: null, owner: 's1' }) + await actions.submitSearch() + expect(wrapper.get('form').findAllComponents(NSelect)).toHaveLength(1) + expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 }) + } finally { + wrapper.unmount() + } +}) + +it('debounces option keywords and retries failed options without querying the table', async () => { + vi.useFakeTimers() + const request = vi.fn(async () => ({ data: [], total: 0 })) + const loadOptions = vi + .fn(async ({ keyword }: TableProSearchOptionContext) => [ + { label: keyword, value: keyword }, + ]) + .mockRejectedValueOnce(new Error('Unavailable')) + const wrapper = mount(RTablePro, { + props: { + columns, + request, + search: { + fields: [{ type: 'select', key: 'owner', label: 'Owner', loadOptions }], + }, + tool: false, + }, + }) + + try { + await vi.advanceTimersByTimeAsync(0) + expect(wrapper.get('[role="status"]').text()).toContain( + "Couldn't load options", + ) + const retry = wrapper + .findAll('button') + .find((button) => button.text() === 'Retry') + + await retry?.trigger('click') + expect(loadOptions).toHaveBeenCalledTimes(2) + const searchOptions = wrapper.getComponent(NSelect).props('onSearch') as ( + value: string, + ) => void + + searchOptions('r') + await nextTick() + searchOptions('ray') + await nextTick() + await vi.advanceTimersByTimeAsync(249) + expect(loadOptions).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(loadOptions.mock.lastCall?.[0].keyword).toBe('ray') + expect(wrapper.getComponent(NSelect).props('options')).toEqual([ + { label: 'ray', value: 'ray' }, + ]) + expect(request).toHaveBeenCalledTimes(1) + } finally { + wrapper.unmount() + vi.useRealTimers() + } +}) + +it('debounces table edits and cancels scheduled submits on reset or switching to manual', async () => { + vi.useFakeTimers() + const [register, actions] = useTablePro() + const request = vi.fn(async (_params: TableProParams) => ({ + data: [], + total: 0, + })) + const search: TableProSearchOptions = { + submitMode: 'change', + debounce: 50, + fields: [{ type: 'text', key: 'name', label: 'Name' }], + } + const wrapper = mount(RTablePro, { + props: { columns, request, search, onRegister: register, tool: false }, + }) + + try { + actions.setSearchValues({ name: 'R' }) + await vi.advanceTimersByTimeAsync(40) + actions.setSearchValues({ name: 'Ray' }) + await vi.advanceTimersByTimeAsync(49) + expect(request).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(request.mock.lastCall?.[0]).toEqual({ + name: 'Ray', + page: 1, + pageSize: 10, + }) + + actions.setSearchValues({ name: 'Ray' }) + await vi.advanceTimersByTimeAsync(50) + expect(request).toHaveBeenCalledTimes(2) + actions.setSearchValues({ name: 'Old' }) + await actions.resetSearch() + await vi.advanceTimersByTimeAsync(50) + expect(request).toHaveBeenCalledTimes(3) + expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 }) + + actions.setSearchValues({ name: 'Manual draft' }) + await wrapper.setProps({ search: { ...search, submitMode: 'manual' } }) + await vi.advanceTimersByTimeAsync(50) + expect(request).toHaveBeenCalledTimes(3) + expect(actions.getSearchValues().name).toBe('Manual draft') + expect(actions.getSearchValues('applied')).toEqual({}) + } finally { + wrapper.unmount() + vi.useRealTimers() + } +}) + +it('ignores asynchronous validation that finishes after a reset', async () => { + const [register, actions] = useTablePro() + const request = vi.fn(async () => ({ data: [], total: 0 })) + const validation = Promise.withResolvers() + const validator = vi.fn(() => validation.promise) + const search: TableProSearchOptions = { + fields: [ + { + type: 'text', + key: 'name', + label: 'Name', + rules: { validator }, + }, + ], + } + const wrapper = mount(RTablePro, { + props: { columns, request, search, onRegister: register, tool: false }, + }) + + try { + actions.setSearchValues({ name: 'Old' }) + const submitting = actions.submitSearch() + + await flushPromises() + expect(validator).toHaveBeenCalledOnce() + await actions.resetSearch() + validation.reject(new Error('Obsolete validation')) + expect(await submitting).toBe(false) + expect(wrapper.text()).not.toContain('Obsolete validation') + expect(request).toHaveBeenCalledTimes(2) + } finally { + wrapper.unmount() + } +}) + +it('does not reload when rendering a new pagination object with the same paging state', async () => { + const [register, actions] = useTablePro() + const lastQuery = shallowRef() + const request = vi.fn(async (params: TableProParams) => { + lastQuery.value = params + + return { data: [], total: 30 } + }) + const search: TableProSearchOptions = { + fields: [{ type: 'text', key: 'name', label: 'Name' }], + } + const wrapper = mount( + defineComponent({ + setup: () => () => + h('section', [ + h(RTablePro, { + columns, + request, + search, + pagination: { pageSizes: [10, 20] }, + onRegister: register, + tool: false, + }), + h('pre', JSON.stringify(lastQuery.value)), + ]), + }), + ) + + try { + await flushPromises() + expect(request).toHaveBeenCalledTimes(1) + actions.setSearchValues({ name: 'Ray' }) + await actions.submitSearch() + await flushPromises() + expect(request).toHaveBeenCalledTimes(2) + expect(wrapper.get('pre').text()).toBe( + '{"name":"Ray","page":1,"pageSize":10}', + ) + } finally { + wrapper.unmount() + } +}) diff --git a/apps/admin/src/documentation-example.tsx b/apps/admin/src/documentation-example.tsx index 8cf6da73..717a3cd6 100644 --- a/apps/admin/src/documentation-example.tsx +++ b/apps/admin/src/documentation-example.tsx @@ -13,6 +13,7 @@ import { getStaticAppRoutes, setAppRouteModules, } from '@/router/app-route-modules' +import { routeView } from '@/router/config/views' import { expandRoutes } from '@/router/utils/expand-routes' import { useSettingActions, useSettingGetters } from '@/store' import { useMemoryCache } from '@/utils/cache-backend' @@ -46,6 +47,12 @@ const params = new URLSearchParams(location.search) const withLayout = params.get('layout') === '1' const examples = [ ...getStaticAppRoutes().filter(({ path }) => examplePaths.has(path)), + { + path: '/tables/search', + name: 'TableDemoSearch', + component: routeView('demo/tables/search'), + meta: { i18nKey: 'menu.TableSearch' }, + }, { path: '/docs-core-utils', name: 'DocsCoreUtils', diff --git a/apps/admin/src/locales/lang/en-US/menu.json b/apps/admin/src/locales/lang/en-US/menu.json index fb658c26..f247f39c 100644 --- a/apps/admin/src/locales/lang/en-US/menu.json +++ b/apps/admin/src/locales/lang/en-US/menu.json @@ -43,6 +43,7 @@ "TablePrinting": "Printing and custom regions", "TableCustom": "Slots and instance methods", "TableHooksQuery": "Hooks · Queries and paging", + "TableSearch": "Advanced search", "TableHooksSelection": "Hooks · Selection and bulk actions", "TableHooksOutput": "Hooks · Export and print", "RouteManagement": "Route management", diff --git a/apps/admin/src/locales/lang/zh-CN/menu.json b/apps/admin/src/locales/lang/zh-CN/menu.json index 8647687a..8a54af2a 100644 --- a/apps/admin/src/locales/lang/zh-CN/menu.json +++ b/apps/admin/src/locales/lang/zh-CN/menu.json @@ -43,6 +43,7 @@ "TablePrinting": "打印与自定义区域", "TableCustom": "插槽与实例操作", "TableHooksQuery": "Hooks · 查询与分页", + "TableSearch": "高级搜索", "TableHooksSelection": "Hooks · 选择与批量操作", "TableHooksOutput": "Hooks · 导出与打印", "RouteManagement": "路由管理", diff --git a/apps/admin/src/router/config/views.ts b/apps/admin/src/router/config/views.ts index ff4e0240..f3b04048 100644 --- a/apps/admin/src/router/config/views.ts +++ b/apps/admin/src/router/config/views.ts @@ -135,6 +135,10 @@ const views = { load: () => import('@/views/demo/tables/remote'), name: 'TableDemoRemote', }, + 'demo/tables/search': { + load: () => import('@/views/demo/tables/search'), + name: 'TableDemoSearch', + }, 'demo/template-hooks': { load: () => import('@/views/demo/template-hooks/index'), name: 'TemplateHooks', diff --git a/apps/admin/src/router/modules/demo/tables.ts b/apps/admin/src/router/modules/demo/tables.ts index 9528309d..a908563e 100644 --- a/apps/admin/src/router/modules/demo/tables.ts +++ b/apps/admin/src/router/modules/demo/tables.ts @@ -22,6 +22,12 @@ const tables: AppRouteRecordRaw = { component: routeView('demo/tables/remote'), meta: { i18nKey: t('menu.TableRemote') }, }, + { + path: 'search', + name: 'TableDemoSearch', + component: routeView('demo/tables/search'), + meta: { i18nKey: t('menu.TableSearch') }, + }, { path: 'auto-height', name: 'TableDemoAutoHeight', diff --git a/apps/admin/src/views/demo/tables/search-copy.ts b/apps/admin/src/views/demo/tables/search-copy.ts new file mode 100644 index 00000000..8f50eb15 --- /dev/null +++ b/apps/admin/src/views/demo/tables/search-copy.ts @@ -0,0 +1,171 @@ +export const searchCopy = { + zh: { + title: '高级搜索', + description: + '在订单列表里试一遍组合筛选、负责人联动和请求重试。每次编辑、应用和取数的变化都可以在下方查看。', + tryScenario: '从一个场景开始', + combine: '组合筛选', + race: '快速切换组织', + deliveryRecipe: '交付与金额', + validation: '试试校验', + combineHint: + '已填入待处理、已支付和 11 月 1 日至 8 日。应用后,日期区间会拆成两个请求参数。', + raceHint: + '已从北区切到南区。负责人应清空,候选只剩南区成员。请求记录里可以看到取消的北区请求。', + deliveryHint: + '已填入设备类目、最低金额、未开票和交付时间。试着调整其中一项,对比筛选条件和参数。', + validationHint: + '关键词只有一个字符。校验会拦下提交,继续输入或清空关键词再查。', + source: '数据来源', + local: '本地筛选', + remote: '模拟远端', + submitMode: '应用方式', + manual: '手动应用', + instant: '输入后自动应用', + manualHint: '修改先留在草稿,点「应用条件」才更新列表。', + instantHint: '停止编辑 350 毫秒后应用条件,快速输入只查最后一次。', + more: '显示更多筛选项', + apply: '应用条件', + reset: '恢复默认', + clear: '清空条件', + keyword: '订单关键词', + keywordHint: '输入订单号或商品名', + keywordError: '请输入至少 2 个字符,或清空关键词。', + order: '订单', + product: '商品', + status: '状态', + created: '创建日期', + organization: '组织', + owner: '负责人', + category: '商品类目', + warehouse: '发货仓', + minAmount: '最低金额', + amount: '金额', + invoiced: '已开票', + yes: '是', + no: '否', + delivery: '配送方式', + any: '不限', + standard: '普通', + express: '加急', + deliveryAt: '交付时间区间', + deliveryTime: '交付时段', + teams: ['北区', '南区'], + people: ['陈晨', '林岚', '周宁', '王雨'], + statuses: ['待处理', '已支付', '已关闭'], + products: ['便签', '键盘', '笔记本', '显示器'], + groups: ['办公用品', '电子设备'], + warehouseLabels: ['北区主仓', '北区备仓', '南区主仓', '南区备仓'], + currency: 'CNY', + draft: '草稿', + applied: '已应用条件', + payload: '实际列表请求', + mapped: '转换后的参数', + inspector: '对照草稿、条件和参数', + dirty: '有待应用的更改', + clean: '草稿与已应用条件一致', + pageRows: (count: number) => `本页 ${count} 条`, + matchedRows: (count: number) => `匹配 ${count} 条`, + failList: '模拟列表失败', + failOwner: '模拟负责人加载失败', + trace: '最近请求', + emptyTrace: '切换为模拟远端,或选择一个组织后查看请求。', + listRequest: '列表', + ownerRequest: '负责人', + page: (page: number) => `第 ${page} 页`, + phases: { + pending: '进行中', + success: '成功', + cancelled: '已取消', + failed: '失败', + }, + }, + en: { + title: 'Advanced search', + description: + 'Try combined order filters, linked assignees, and retries. Inspect each change to the draft, applied filters, and requests below.', + tryScenario: 'Try a scenario', + combine: 'Combined filters', + race: 'Switch organizations quickly', + deliveryRecipe: 'Delivery and amount', + validation: 'Try validation', + combineHint: + 'Pending, Paid, and November 1–8 are filled in. Apply them to see the date range split into two request parameters.', + raceHint: + 'Switched from North to South. The assignee clears, and only South options remain. Find the cancelled North request in the log.', + deliveryHint: + 'A device category, minimum amount, uninvoiced orders, and a delivery window are filled in. Change any field and compare the filters and parameters.', + validationHint: + 'The keyword has one character. Validation blocks the query until you type more or clear the field.', + source: 'Data source', + local: 'Local', + remote: 'Simulated remote', + submitMode: 'Apply mode', + manual: 'Manual', + instant: 'As you type', + manualHint: 'Edits stay in the draft until you choose Apply filters.', + instantHint: + 'Filters apply after 350 ms without edits. Rapid typing sends only the last query.', + more: 'Show more filters', + apply: 'Apply filters', + reset: 'Restore defaults', + clear: 'Clear filters', + keyword: 'Order keyword', + keywordHint: 'Order number or product name', + keywordError: 'Enter at least 2 characters or clear the keyword.', + order: 'Order', + product: 'Product', + status: 'Status', + created: 'Created', + organization: 'Organization', + owner: 'Assignee', + category: 'Product category', + warehouse: 'Warehouse', + minAmount: 'Minimum amount', + amount: 'Amount', + invoiced: 'Invoiced', + yes: 'Yes', + no: 'No', + delivery: 'Shipping method', + any: 'Any', + standard: 'Standard', + express: 'Express', + deliveryAt: 'Delivery window', + deliveryTime: 'Delivery time', + teams: ['North', 'South'], + people: ['Chen', 'Lin', 'Zhou', 'Wang'], + statuses: ['Pending', 'Paid', 'Closed'], + products: ['Notes', 'Keyboard', 'Notebook', 'Monitor'], + groups: ['Office supplies', 'Electronics'], + warehouseLabels: [ + 'North main', + 'North backup', + 'South main', + 'South backup', + ], + currency: 'CNY', + draft: 'Draft', + applied: 'Applied filters', + payload: 'Actual list request', + mapped: 'Mapped parameters', + inspector: 'Inspect draft, filters, and parameters', + dirty: 'Unapplied changes', + clean: 'Draft matches applied filters', + pageRows: (count: number) => `${count} on this page`, + matchedRows: (count: number) => `${count} matches`, + failList: 'Fail the list request', + failOwner: 'Fail the assignee request', + trace: 'Recent requests', + emptyTrace: + 'Switch to simulated remote or select an organization to see requests here.', + listRequest: 'List', + ownerRequest: 'Assignees', + page: (page: number) => `Page ${page}`, + phases: { + pending: 'Pending', + success: 'Succeeded', + cancelled: 'Cancelled', + failed: 'Failed', + }, + }, +} diff --git a/apps/admin/src/views/demo/tables/search-fixtures.ts b/apps/admin/src/views/demo/tables/search-fixtures.ts new file mode 100644 index 00000000..8807610e --- /dev/null +++ b/apps/admin/src/views/demo/tables/search-fixtures.ts @@ -0,0 +1,104 @@ +import type { TableProParams } from '@ray-template/ui/table-pro' + +export const statuses = ['pending', 'paid', 'closed'] as const +export const organizations = ['north', 'south'] as const +export const products = ['notes', 'keyboard', 'notebook', 'monitor'] as const +export const warehouses = [ + 'north-main', + 'north-backup', + 'south-main', + 'south-backup', +] as const +export const owners = [ + { id: 'n1', orgId: 'north' }, + { id: 'n2', orgId: 'north' }, + { id: 's1', orgId: 'south' }, + { id: 's2', orgId: 'south' }, +] as const + +export const orders = Array.from({ length: 96 }, (_, index) => { + const ownerIndex = index % owners.length + const { orgId, id: ownerId } = owners[ownerIndex] + const productIndex = Math.floor(index / 3) % products.length + const statusIndex = index % statuses.length + const warehouseIndex = Math.floor(index / 8) % warehouses.length + const day = 1 + (index % 12) + const hour = index % 3 === 0 ? 9 : 14 + + return { + id: index + 1, + orderNo: `ORD-${String(index + 1).padStart(3, '0')}`, + productIndex, + productId: products[productIndex], + statusIndex, + status: statuses[statusIndex], + createdAt: `2026-11-${String(day).padStart(2, '0')}`, + orgId, + ownerId, + ownerIndex, + warehouseIndex, + warehouseId: warehouses[warehouseIndex], + amount: [0, 59, 129, 199, 349, 699, 1299, 2499][index % 8], + invoiced: Math.floor(index / 4) % 2 === 0, + delivery: index % 3 === 0 ? 'express' : 'standard', + deliveryAt: new Date(2026, 10, day + 1, hour).getTime(), + deliveryTime: hour === 9 ? '09:00:00' : '14:00:00', + } +}) + +export function orderMatchesQuery( + row: (typeof orders)[number] & { product: string }, + query: TableProParams, +) { + const { + keyword, + status, + createdFrom, + createdTo, + orgId, + ownerId, + productId, + warehouseId, + minAmount, + invoiced, + delivery, + deliveryFrom, + deliveryTo, + deliveryTime, + } = query + + return ( + `${row.orderNo} ${row.product}` + .toLowerCase() + .includes(String(keyword ?? '').toLowerCase()) && + (!Array.isArray(status) || status.includes(row.status)) && + (typeof createdFrom !== 'string' || row.createdAt >= createdFrom) && + (typeof createdTo !== 'string' || row.createdAt <= createdTo) && + (orgId == null || row.orgId === orgId) && + (ownerId == null || row.ownerId === ownerId) && + (productId == null || row.productId === productId) && + (warehouseId == null || row.warehouseId === warehouseId) && + (typeof minAmount !== 'number' || row.amount >= minAmount) && + (invoiced == null || row.invoiced === invoiced) && + (delivery == null || row.delivery === delivery) && + (typeof deliveryFrom !== 'number' || row.deliveryAt >= deliveryFrom) && + (typeof deliveryTo !== 'number' || row.deliveryAt <= deliveryTo) && + (deliveryTime == null || row.deliveryTime === deliveryTime) + ) +} + +export function waitForDemo(delay: number, signal: AbortSignal) { + return new Promise((resolve, reject) => { + signal.throwIfAborted() + const abort = () => { + clearTimeout(timer) + reject(signal.reason) + } + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort) + resolve() + }, delay) + + signal.addEventListener('abort', abort, { once: true }) + }) +} diff --git a/apps/admin/src/views/demo/tables/search.scss b/apps/admin/src/views/demo/tables/search.scss new file mode 100644 index 00000000..f57aa5d6 --- /dev/null +++ b/apps/admin/src/views/demo/tables/search.scss @@ -0,0 +1,85 @@ +.r-search-demo { + &__guide, + &__trace { + display: grid; + gap: 12px; + } + + &__guide p, + &__empty { + margin: 0; + color: var(--r-text-secondary); + } + + &__settings { + display: flex; + flex-wrap: wrap; + gap: 12px 24px; + padding-block-start: 12px; + border-block-start: 1px solid var(--r-line); + } + + &__details { + min-inline-size: 0; + + summary { + margin-block-end: 12px; + cursor: pointer; + font-weight: 600; + } + } + + &__values { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 210px), 1fr)); + align-items: start; + gap: 12px; + + pre { + overflow-wrap: anywhere; + } + } + + &__trace { + margin: 0; + padding: 0; + list-style: none; + + li { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; + align-items: center; + gap: 8px; + padding-block: 4px; + } + + li + li { + border-block-start: 1px solid var(--r-line); + } + } + + &__trace-head { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-block-end: 12px; + } + + &__order { + display: flex; + flex-wrap: wrap; + gap: 10px 24px; + margin: 0; + + dt { + color: var(--r-text-secondary); + font-size: 12px; + } + + dd { + margin: 0; + } + } +} diff --git a/apps/admin/src/views/demo/tables/search.tsx b/apps/admin/src/views/demo/tables/search.tsx new file mode 100644 index 00000000..abafa3c2 --- /dev/null +++ b/apps/admin/src/views/demo/tables/search.tsx @@ -0,0 +1,678 @@ +import './search.scss' +import { useSettingGetters } from '@/store' +import { RTablePro, useTablePro } from '@ray-template/ui/table-pro' +import type { + TableProColumn, + TableProParams, + TableProRequest, + TableProSearchOptionContext, + TableProSearchOptions, + TableProSearchValues, +} from '@ray-template/ui/table-pro' +import { + NButton, + NCard, + NCheckbox, + NFlex, + NRadio, + NRadioGroup, + NTag, +} from 'naive-ui' +import { + computed, + defineComponent, + nextTick, + ref, + shallowRef, + useId, +} from 'vue' +import DemoPage from '../components/DemoPage' +import { searchCopy } from './search-copy' +import { + orderMatchesQuery, + orders, + organizations, + owners, + products, + statuses, + waitForDemo, + warehouses, +} from './search-fixtures' + +const initialValues: TableProSearchValues = { status: ['pending'] } +const pagination = { pageSizes: [5, 10, 20] } +const instantDelay = 350 +const extraKeys = [ + 'productId', + 'warehouseId', + 'minAmount', + 'invoiced', + 'delivery', + 'deliveryAt', + 'deliveryTime', +] as const + +type Trace = { + id: number + kind: 'list' | 'owner' + detail: number | string + phase: 'pending' | 'success' | 'cancelled' | 'failed' +} + +const traceTypes = { + pending: 'info', + success: 'success', + cancelled: 'default', + failed: 'error', +} as const + +const scenarios = ['combine', 'race', 'deliveryRecipe', 'validation'] as const + +type Scenario = (typeof scenarios)[number] + +function nonemptyValues(values: TableProSearchValues) { + return Object.fromEntries( + Object.entries(values).filter( + ([, value]) => + value != null && + value !== '' && + (!Array.isArray(value) || value.length > 0), + ), + ) +} + +export default defineComponent({ + name: 'TableDemoSearch', + setup() { + const { getLocaleLanguage } = useSettingGetters() + const copy = computed(() => + getLocaleLanguage.value === 'zh-CN' ? searchCopy.zh : searchCopy.en, + ) + const id = useId() + const [register, table] = useTablePro() + const source = ref<'local' | 'remote'>('local') + const submitMode = ref<'manual' | 'change'>('manual') + const more = ref(false) + const scenario = ref() + const listPayload = shallowRef({}) + const mapped = shallowRef>>(initialValues) + const trace = shallowRef([]) + let requestId = 0 + let failListOnce = false + let failOwnerOnce = false + + const track = async ( + kind: Trace['kind'], + detail: Trace['detail'], + delay: number, + signal: AbortSignal, + result: () => T, + ) => { + const id = ++requestId + const entry: Trace = { id, kind, detail, phase: 'pending' } + + trace.value = [entry, ...trace.value].slice(0, 6) + const finish = (phase: Trace['phase']) => { + trace.value = trace.value.map((entry) => + entry.id === id ? { ...entry, phase } : entry, + ) + } + + try { + await waitForDemo(delay, signal) + const value = result() + + finish('success') + + return value + } catch (error) { + finish(signal.aborted ? 'cancelled' : 'failed') + throw error + } + } + + const rows = computed(() => + orders.map((row) => ({ + ...row, + product: copy.value.products[row.productIndex], + statusLabel: copy.value.statuses[row.statusIndex], + organization: copy.value.teams[row.orgId === 'north' ? 0 : 1], + owner: copy.value.people[row.ownerIndex], + })), + ) + const money = computed( + () => + new Intl.NumberFormat(getLocaleLanguage.value, { + style: 'currency', + currency: copy.value.currency, + maximumFractionDigits: 0, + }), + ) + const dateTime = computed( + () => + new Intl.DateTimeFormat(getLocaleLanguage.value, { + dateStyle: 'medium', + timeStyle: 'short', + }), + ) + const deliveryDetails: TableProColumn = { + type: 'expand', + renderExpand: (row: (typeof orders)[number]) => { + const labels = copy.value + const details = [ + [labels.warehouse, labels.warehouseLabels[row.warehouseIndex]], + [labels.invoiced, row.invoiced ? labels.yes : labels.no], + [ + labels.delivery, + row.delivery === 'express' ? labels.express : labels.standard, + ], + [labels.deliveryAt, dateTime.value.format(row.deliveryAt)], + ] + + return ( +
+ {details.map(([label, value]) => ( +
+
{label}
+
{value}
+
+ ))} +
+ ) + }, + } + const columns = computed(() => [ + ...(more.value ? [deliveryDetails] : []), + { key: 'orderNo', title: copy.value.order, minWidth: 92 }, + { key: 'product', title: copy.value.product, minWidth: 90 }, + { key: 'statusLabel', title: copy.value.status, minWidth: 82 }, + { key: 'createdAt', title: copy.value.created, minWidth: 108 }, + { key: 'organization', title: copy.value.organization, minWidth: 90 }, + { key: 'owner', title: copy.value.owner, minWidth: 90 }, + { + key: 'amount', + title: copy.value.amount, + minWidth: 85, + render: (row: Record) => + money.value.format(Number(row.amount)), + }, + ]) + + const draft = computed(() => + table.isReady.value ? nonemptyValues(table.getSearchValues()) : {}, + ) + const applied = computed(() => + table.isReady.value ? table.getSearchValues('applied') : initialValues, + ) + const dirty = computed( + () => JSON.stringify(draft.value) !== JSON.stringify(applied.value), + ) + const pageRows = computed(() => + table.isReady.value ? table.getCurrentPageData().length : 0, + ) + const showExtra = () => more.value + + const fillDraft = (values: TableProSearchValues) => { + table.setSearchValues({ + ...Object.fromEntries( + Object.keys(table.getSearchValues()).map((key) => [key, null]), + ), + ...values, + }) + } + + const loadOwners = ({ + keyword, + values, + signal, + }: TableProSearchOptionContext) => { + const org = values.orgId === 'north' ? 'north' : 'south' + const fail = failOwnerOnce + + failOwnerOnce = false + + return track('owner', org, org === 'north' ? 800 : 450, signal, () => { + if (fail) throw new Error('Simulated assignee request failure') + + return owners.flatMap(({ id, orgId }, index) => { + const label = copy.value.people[index] + + return orgId === org && + label.toLowerCase().includes(keyword.trim().toLowerCase()) + ? [{ label, value: id }] + : [] + }) + }) + } + + const search = computed(() => { + const labels = copy.value + + return { + initialValues, + submitMode: submitMode.value, + debounce: instantDelay, + searchText: labels.apply, + resetText: labels.reset, + renderActions: ({ defaultActions, submit }) => ( + <> + { + fillDraft({}) + void submit() + }} + > + {labels.clear} + + {defaultActions} + + ), + fields: [ + { + key: 'keyword', + label: labels.keyword, + type: 'text', + placeholder: labels.keywordHint, + getValue: (row) => `${row.orderNo} ${row.product}`, + rules: { + trigger: 'blur', + validator: (_rule, value: unknown) => + typeof value !== 'string' || + value.trim().length === 0 || + value.trim().length >= 2 || + new Error(labels.keywordError), + }, + }, + { + key: 'status', + label: labels.status, + type: 'select', + multiple: true, + options: statuses.map((value, index) => ({ + value, + label: labels.statuses[index], + })), + }, + { + key: 'createdAt', + label: labels.created, + type: 'dateRange', + span: 2, + transform: ([createdFrom, createdTo]) => ({ + createdFrom, + createdTo, + }), + }, + { + key: 'orgId', + label: labels.organization, + type: 'select', + options: organizations.map((value, index) => ({ + value, + label: labels.teams[index], + })), + }, + { + key: 'ownerId', + label: labels.owner, + type: 'select', + dependsOn: ['orgId'], + visible: ({ orgId }) => orgId != null, + loadOptions: loadOwners, + }, + { + key: 'productId', + label: labels.category, + type: 'cascader', + visible: showExtra, + fieldProps: { + options: labels.groups.map((label, group) => ({ + label, + value: `category-${group}`, + children: products + .slice(group * 2, group * 2 + 2) + .map((value, index) => ({ + value, + label: labels.products[group * 2 + index], + })), + })), + }, + }, + { + key: 'warehouseId', + label: labels.warehouse, + type: 'treeSelect', + visible: showExtra, + fieldProps: { + defaultExpandAll: true, + options: labels.teams.map((label, region) => ({ + label, + key: `region-${region}`, + disabled: true, + children: warehouses + .slice(region * 2, region * 2 + 2) + .map((key, index) => ({ + key, + label: labels.warehouseLabels[region * 2 + index], + })), + })), + }, + }, + { + key: 'minAmount', + label: labels.minAmount, + type: 'number', + visible: showExtra, + fieldProps: { min: 0, step: 50 }, + getValue: (row) => row.amount, + matches: (cell, minimum) => + typeof cell === 'number' && cell >= minimum, + }, + { + key: 'invoiced', + label: labels.invoiced, + type: 'boolean', + visible: showExtra, + }, + { + key: 'delivery', + label: labels.delivery, + type: 'custom', + visible: showExtra, + render: ({ inputId, labelId, value, setValue }) => ( + setValue(next === 'any' ? null : next)} + > + + {labels.any} + {labels.standard} + {labels.express} + + + ), + }, + { + key: 'deliveryAt', + label: labels.deliveryAt, + type: 'datetimeRange', + span: 2, + visible: showExtra, + transform: ([deliveryFrom, deliveryTo]) => ({ + deliveryFrom, + deliveryTo, + }), + }, + { + key: 'deliveryTime', + label: labels.deliveryTime, + type: 'time', + visible: showExtra, + }, + ], + } + }) + + const request: TableProRequest = (query, signal) => { + const { page = 1, pageSize = 5 } = query + const fail = failListOnce + + listPayload.value = query + failListOnce = false + + return track('list', page, 400, signal, () => { + if (fail) throw new Error('Simulated list request failure') + + const matched = rows.value.filter((row) => + orderMatchesQuery(row, query), + ) + const start = (page - 1) * pageSize + + return { + data: matched.slice(start, start + pageSize), + total: matched.length, + } + }) + } + + const startScenario = async (next: Scenario) => { + scenario.value = next + more.value = next === 'deliveryRecipe' + + switch (next) { + case 'combine': + fillDraft({ + status: ['pending', 'paid'], + createdAt: ['2026-11-01', '2026-11-08'], + }) + break + case 'race': + fillDraft({}) + await nextTick() + table.setSearchValues({ orgId: 'north', ownerId: 'n1' }) + await nextTick() + table.setSearchValues({ orgId: 'south' }) + break + case 'deliveryRecipe': + fillDraft({ + productId: 'notebook', + warehouseId: 'north-main', + minAmount: 0, + invoiced: false, + delivery: 'express', + deliveryAt: [ + new Date(2026, 10, 2).getTime(), + new Date(2026, 10, 10, 23, 59).getTime(), + ], + deliveryTime: '09:00:00', + }) + break + default: + fillDraft({ keyword: 'O' }) + await table.submitSearch() + break + } + } + + const failList = () => { + failListOnce = true + void table.reload() + } + const failOwner = () => { + failOwnerOnce = true + table.setSearchValues({ + orgId: draft.value.orgId === 'north' ? 'south' : 'north', + }) + } + + const scenarioHint = computed( + () => + ({ + combine: copy.value.combineHint, + race: copy.value.raceHint, + deliveryRecipe: copy.value.deliveryHint, + validation: copy.value.validationHint, + })[scenario.value ?? 'combine'], + ) + + return () => { + const labels = copy.value + const query = table.queryState.value + const output = + source.value === 'remote' + ? ([labels.payload, listPayload.value] as const) + : ([labels.mapped, mapped.value] as const) + + return ( + + +
+ {labels.tryScenario} + + {scenarios.map((key) => ( + void startScenario(key)} + > + {labels[key]} + + ))} + + {scenario.value &&

{scenarioHint.value}

} +
+ { + source.value = value === 'remote' ? 'remote' : 'local' + }} + > + + {labels.local} + {labels.remote} + + + { + submitMode.value = value === 'change' ? 'change' : 'manual' + }} + > + + {labels.manual} + {labels.instant} + + +
+

+ {submitMode.value === 'manual' + ? labels.manualHint + : labels.instantHint} +

+ { + more.value = checked + + if (!checked) + table.setSearchValues( + Object.fromEntries(extraKeys.map((key) => [key, null])), + ) + }} + > + {labels.more} + +
+
+ + { + mapped.value = params + }} + /> + +
+ + + {dirty.value ? labels.dirty : labels.clean} + + {labels.pageRows(pageRows.value)} + {query?.total != null && ( + {labels.matchedRows(query.total)} + )} + +
+ +
+ {labels.inspector} +
+ {( + [ + [labels.draft, draft.value], + [labels.applied, applied.value], + output, + ] as const + ).map(([label, values]) => ( +
+ {label} +
+
{JSON.stringify(values, null, 2)}
+
+
+ ))} +
+
+ + +
+ {labels.trace} + + + {labels.failOwner} + + {source.value === 'remote' && ( + + {labels.failList} + + )} + +
+ {trace.value.length ? ( +
    + {trace.value.map(({ id, kind, detail, phase }) => ( +
  1. + + {kind === 'list' + ? labels.listRequest + : labels.ownerRequest} + + + {typeof detail === 'number' + ? labels.page(detail) + : labels.teams[detail === 'north' ? 0 : 1]} + + + {labels.phases[phase]} + +
  2. + ))} +
+ ) : ( +

{labels.emptyTrace}

+ )} +
+
+ ) + } + }, +}) diff --git a/apps/docs/reference/table-pro.md b/apps/docs/reference/table-pro.md index f81a56c8..ef9e1357 100644 --- a/apps/docs/reference/table-pro.md +++ b/apps/docs/reference/table-pro.md @@ -3,6 +3,7 @@