mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-11-21 10:53:33 +08:00
feat(table): add advanced search and interactive demos
This commit is contained in:
parent
7de2e4cebf
commit
58fc0b63a6
648
__test__/components/table-pro-search.spec.ts
Normal file
648
__test__/components/table-pro-search.spec.ts
Normal file
@ -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<string, string | number>) => Promise<void>
|
||||
}) =>
|
||||
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<void>()
|
||||
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<TableProParams>()
|
||||
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()
|
||||
}
|
||||
})
|
||||
@ -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',
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -43,6 +43,7 @@
|
||||
"TablePrinting": "打印与自定义区域",
|
||||
"TableCustom": "插槽与实例操作",
|
||||
"TableHooksQuery": "Hooks · 查询与分页",
|
||||
"TableSearch": "高级搜索",
|
||||
"TableHooksSelection": "Hooks · 选择与批量操作",
|
||||
"TableHooksOutput": "Hooks · 导出与打印",
|
||||
"RouteManagement": "路由管理",
|
||||
|
||||
@ -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',
|
||||
|
||||
@ -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',
|
||||
|
||||
171
apps/admin/src/views/demo/tables/search-copy.ts
Normal file
171
apps/admin/src/views/demo/tables/search-copy.ts
Normal file
@ -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',
|
||||
},
|
||||
},
|
||||
}
|
||||
104
apps/admin/src/views/demo/tables/search-fixtures.ts
Normal file
104
apps/admin/src/views/demo/tables/search-fixtures.ts
Normal file
@ -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<void>((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 })
|
||||
})
|
||||
}
|
||||
85
apps/admin/src/views/demo/tables/search.scss
Normal file
85
apps/admin/src/views/demo/tables/search.scss
Normal file
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
678
apps/admin/src/views/demo/tables/search.tsx
Normal file
678
apps/admin/src/views/demo/tables/search.tsx
Normal file
@ -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<Scenario>()
|
||||
const listPayload = shallowRef<TableProParams>({})
|
||||
const mapped = shallowRef<Readonly<Record<string, unknown>>>(initialValues)
|
||||
const trace = shallowRef<readonly Trace[]>([])
|
||||
let requestId = 0
|
||||
let failListOnce = false
|
||||
let failOwnerOnce = false
|
||||
|
||||
const track = async <T,>(
|
||||
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 (
|
||||
<dl class="r-search-demo__order">
|
||||
{details.map(([label, value]) => (
|
||||
<div key={label}>
|
||||
<dt>{label}</dt>
|
||||
<dd>{value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
)
|
||||
},
|
||||
}
|
||||
const columns = computed<TableProColumn[]>(() => [
|
||||
...(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<string, unknown>) =>
|
||||
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<TableProSearchOptions>(() => {
|
||||
const labels = copy.value
|
||||
|
||||
return {
|
||||
initialValues,
|
||||
submitMode: submitMode.value,
|
||||
debounce: instantDelay,
|
||||
searchText: labels.apply,
|
||||
resetText: labels.reset,
|
||||
renderActions: ({ defaultActions, submit }) => (
|
||||
<>
|
||||
<NButton
|
||||
text
|
||||
attrType="button"
|
||||
onClick={() => {
|
||||
fillDraft({})
|
||||
void submit()
|
||||
}}
|
||||
>
|
||||
{labels.clear}
|
||||
</NButton>
|
||||
{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 }) => (
|
||||
<NRadioGroup
|
||||
name={inputId}
|
||||
aria-labelledby={labelId}
|
||||
value={typeof value === 'string' ? value : 'any'}
|
||||
onUpdateValue={(next) => setValue(next === 'any' ? null : next)}
|
||||
>
|
||||
<NFlex size="small">
|
||||
<NRadio value="any">{labels.any}</NRadio>
|
||||
<NRadio value="standard">{labels.standard}</NRadio>
|
||||
<NRadio value="express">{labels.express}</NRadio>
|
||||
</NFlex>
|
||||
</NRadioGroup>
|
||||
),
|
||||
},
|
||||
{
|
||||
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 (
|
||||
<DemoPage title={labels.title} description={labels.description}>
|
||||
<NCard size="small">
|
||||
<div class="r-search-demo__guide">
|
||||
<strong>{labels.tryScenario}</strong>
|
||||
<NFlex size="small">
|
||||
{scenarios.map((key) => (
|
||||
<NButton
|
||||
key={key}
|
||||
size="small"
|
||||
secondary
|
||||
type={scenario.value === key ? 'primary' : 'default'}
|
||||
disabled={!table.isReady.value}
|
||||
onClick={() => void startScenario(key)}
|
||||
>
|
||||
{labels[key]}
|
||||
</NButton>
|
||||
))}
|
||||
</NFlex>
|
||||
{scenario.value && <p role="status">{scenarioHint.value}</p>}
|
||||
<div class="r-search-demo__settings">
|
||||
<NRadioGroup
|
||||
name={`${id}-source`}
|
||||
aria-label={labels.source}
|
||||
value={source.value}
|
||||
onUpdateValue={(value) => {
|
||||
source.value = value === 'remote' ? 'remote' : 'local'
|
||||
}}
|
||||
>
|
||||
<NFlex size="small">
|
||||
<NRadio value="local">{labels.local}</NRadio>
|
||||
<NRadio value="remote">{labels.remote}</NRadio>
|
||||
</NFlex>
|
||||
</NRadioGroup>
|
||||
<NRadioGroup
|
||||
name={`${id}-mode`}
|
||||
aria-label={labels.submitMode}
|
||||
value={submitMode.value}
|
||||
onUpdateValue={(value) => {
|
||||
submitMode.value = value === 'change' ? 'change' : 'manual'
|
||||
}}
|
||||
>
|
||||
<NFlex size="small">
|
||||
<NRadio value="manual">{labels.manual}</NRadio>
|
||||
<NRadio value="change">{labels.instant}</NRadio>
|
||||
</NFlex>
|
||||
</NRadioGroup>
|
||||
</div>
|
||||
<p>
|
||||
{submitMode.value === 'manual'
|
||||
? labels.manualHint
|
||||
: labels.instantHint}
|
||||
</p>
|
||||
<NCheckbox
|
||||
checked={more.value}
|
||||
onUpdateChecked={(checked) => {
|
||||
more.value = checked
|
||||
|
||||
if (!checked)
|
||||
table.setSearchValues(
|
||||
Object.fromEntries(extraKeys.map((key) => [key, null])),
|
||||
)
|
||||
}}
|
||||
>
|
||||
{labels.more}
|
||||
</NCheckbox>
|
||||
</div>
|
||||
</NCard>
|
||||
|
||||
<RTablePro
|
||||
onRegister={register}
|
||||
columns={columns.value}
|
||||
search={search.value}
|
||||
data={source.value === 'local' ? rows.value : void 0}
|
||||
request={source.value === 'remote' ? request : void 0}
|
||||
pageSize={5}
|
||||
pagination={pagination}
|
||||
scrollX={more.value ? 700 : 645}
|
||||
tool={false}
|
||||
onSearch={({ params }) => {
|
||||
mapped.value = params
|
||||
}}
|
||||
/>
|
||||
|
||||
<div role="status">
|
||||
<NFlex size="small" align="center">
|
||||
<NTag size="small" type={dirty.value ? 'warning' : 'success'}>
|
||||
{dirty.value ? labels.dirty : labels.clean}
|
||||
</NTag>
|
||||
<NTag size="small">{labels.pageRows(pageRows.value)}</NTag>
|
||||
{query?.total != null && (
|
||||
<NTag size="small">{labels.matchedRows(query.total)}</NTag>
|
||||
)}
|
||||
</NFlex>
|
||||
</div>
|
||||
|
||||
<details class="r-search-demo__details" open>
|
||||
<summary>{labels.inspector}</summary>
|
||||
<div class="r-search-demo__values">
|
||||
{(
|
||||
[
|
||||
[labels.draft, draft.value],
|
||||
[labels.applied, applied.value],
|
||||
output,
|
||||
] as const
|
||||
).map(([label, values]) => (
|
||||
<div class="r-demo-result" key={label}>
|
||||
<span class="r-demo-result__label">{label}</span>
|
||||
<div class="r-demo-result__value">
|
||||
<pre>{JSON.stringify(values, null, 2)}</pre>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<NCard size="small">
|
||||
<div class="r-search-demo__trace-head">
|
||||
<strong>{labels.trace}</strong>
|
||||
<NFlex size="small">
|
||||
<NButton
|
||||
size="small"
|
||||
secondary
|
||||
disabled={!table.isReady.value}
|
||||
onClick={failOwner}
|
||||
>
|
||||
{labels.failOwner}
|
||||
</NButton>
|
||||
{source.value === 'remote' && (
|
||||
<NButton
|
||||
size="small"
|
||||
secondary
|
||||
disabled={!table.isReady.value || query?.loading}
|
||||
onClick={failList}
|
||||
>
|
||||
{labels.failList}
|
||||
</NButton>
|
||||
)}
|
||||
</NFlex>
|
||||
</div>
|
||||
{trace.value.length ? (
|
||||
<ol class="r-search-demo__trace" aria-label={labels.trace}>
|
||||
{trace.value.map(({ id, kind, detail, phase }) => (
|
||||
<li key={id}>
|
||||
<span>
|
||||
{kind === 'list'
|
||||
? labels.listRequest
|
||||
: labels.ownerRequest}
|
||||
</span>
|
||||
<span>
|
||||
{typeof detail === 'number'
|
||||
? labels.page(detail)
|
||||
: labels.teams[detail === 'north' ? 0 : 1]}
|
||||
</span>
|
||||
<NTag size="small" type={traceTypes[phase]}>
|
||||
{labels.phases[phase]}
|
||||
</NTag>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
) : (
|
||||
<p class="r-search-demo__empty">{labels.emptyTrace}</p>
|
||||
)}
|
||||
</NCard>
|
||||
</DemoPage>
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
@ -3,6 +3,7 @@
|
||||
<script setup>
|
||||
import { useData } from 'vitepress'
|
||||
import { defineAsyncComponent } from 'vue'
|
||||
import AdminExample from '../examples/AdminExample.vue'
|
||||
|
||||
const { isDark, lang } = useData()
|
||||
const TableProDemo = defineAsyncComponent(() => import('../examples/TableProDemo.vue'))
|
||||
@ -52,6 +53,54 @@ const renderRemote = () => (
|
||||
- 默认每页 10 条;用 `pageSize`、`pagination.pageSizes` 调整,或传 `pagination={false}` 关闭。关闭时不添加分页字段;`bare pagination` 可单独开启分页。
|
||||
- 初始页用 `pagination.defaultPage`。远端模式下组件管理当前页、每页条数和总数;调用方已有自己的远端控制时可传 `remote + data + pagination`。
|
||||
|
||||
## 高级搜索
|
||||
|
||||
从下面四个场景任选一个开始。在表格下方对照草稿、已应用条件和请求参数,看看哪一步真正改变了列表。
|
||||
|
||||
- **组合筛选**填入状态多选与创建日期区间。切到模拟远端后点击「应用条件」,查看拆分后的 `createdFrom` 和 `createdTo`,再翻页确认条件仍然有效。
|
||||
- **快速切换组织**连续发起北区和南区的候选请求。负责人会清空,最近请求里会显示北区请求已取消。打开负责人下拉,搜索南区的「王雨」。
|
||||
- **交付与金额**填入商品级联、仓库树、最低金额、开票状态、自定义配送方式和交付时间。应用后展开匹配订单核对交付信息,留意请求中保留了 `minAmount: 0` 与 `invoiced: false`。
|
||||
- **试试校验**提交一个字符的关键词,查看校验提示及保留的列表。修正输入后,可以切换「输入后自动应用」,快速连续编辑并观察列表请求。
|
||||
|
||||
在「最近请求」里还能让负责人或列表请求失败一次,再用对应的内置「重试」恢复。
|
||||
|
||||
<AdminExample path="/tables/search" title="组合筛选、组织联动与失败重试" :height="960" />
|
||||
|
||||
::: details 查看示例源码
|
||||
<<< ../../admin/src/views/demo/tables/search.tsx
|
||||
:::
|
||||
|
||||
### 字段配置
|
||||
|
||||
`search` 接受原有数组、`TableProSearchOptions` 对象或 `false`。数组中不传 `type` 时,有 `options` 渲染单选,无 `options` 渲染文本。对象模式可用 `fields` 独立声明搜索字段,也可以省略 `fields`,从标记了 `search: true` 或 `search: { type, ... }` 的数据列生成。列分组、选择列和展开列不会生成字段,显示列设置也不会移除搜索条件。显式提供的 `fields` 优先,包括空数组。每个字段用唯一的 `key` 标识。
|
||||
|
||||
| `type` | 草稿和提交的值 | 默认本地匹配 |
|
||||
| ---------------------------------- | --------------------------------------- | -------------------------------- |
|
||||
| `text` | 字符串,提交时去掉首尾空白 | 忽略大小写,包含匹配 |
|
||||
| `number`、`boolean` | 数字、布尔值。布尔字段可以清空为不限 | 精确匹配 |
|
||||
| `select`、`treeSelect`、`cascader` | 字符串或数字,`multiple: true` 时为数组 | 单选精确匹配。多选任一值命中即可 |
|
||||
| `date`、`dateRange` | `yyyy-MM-dd` 字符串或二元组 | 单日精确匹配,区间包含首尾两天 |
|
||||
| `datetime`、`datetimeRange` | 毫秒时间戳或二元组 | 单值精确匹配,区间包含两端 |
|
||||
| `time` | `HH:mm:ss` 字符串 | 精确匹配 |
|
||||
| `custom` | 字符串、数字、布尔值或字符串/数字数组 | 单值精确匹配,数组任一值命中即可 |
|
||||
|
||||
字段之间用 AND。默认读取 `row[key]`,嵌套数据、时间戳转业务日期等情况可用 `getValue(row)`,特殊匹配用 `matches(cell, value, row)`。控件支持 `placeholder` 和类型化的 `fieldProps`。树选择和级联的节点、懒加载等原生配置从 `fieldProps` 传入。自定义控件用 `render({ value, setValue, values, inputId, labelId })`,并为可聚焦控件关联标签。
|
||||
|
||||
### 提交和请求
|
||||
|
||||
- `initialValues` 优先于字段的 `initialValue`。默认条件参与首查,重置恢复默认并重新查询。字段配置 `rules` 后,查询按钮和 `submitSearch()` 会校验,失败保留上次结果。重置会清理校验提示并应用默认值。空值、空白文本和空数组省略,`0` 和 `false` 保留。
|
||||
- `transform(value, values)` 返回请求参数片段。例如日期区间可返回 `{ createdFrom, createdTo }`,原字段不再进入参数。本地匹配仍使用字段值。列表请求按外部 `params`、转换后的搜索参数、表格的 `page` 和 `pageSize` 合并,提交回到第 1 页,分页和重试沿用已提交的条件。
|
||||
- `onSearch` 接收 `{ values, params, reason }`,`reason` 为 `submit` 或 `reset`。使用对象式 `search` 与 `remote + data + pagination` 时,可在事件中自行取数并控制页码和总数。转换函数抛错会触发 `onSearchError`,保留上次条件。
|
||||
- 实例和 `useTablePro()` 都提供 `getSearchValues('draft' | 'applied')`、`setSearchValues(patch)`、`submitSearch()`、`resetSearch()`。读取默认是草稿。提交和重置返回 `Promise<boolean>`,表示是否成功应用条件。设 `submitMode: 'change'` 可在编辑时防抖提交,`debounce` 默认 300 ms。
|
||||
|
||||
### 远程选项、联动和布局
|
||||
|
||||
`select.loadOptions({ keyword, values, signal })` 用于查询候选项。将 `signal` 传给请求客户端可取消旧请求,忽略取消的请求结果也不会覆盖新候选。关键词输入默认防抖 250 ms,可用 `optionDebounce` 调整。候选加载或失败重试独立于列表请求。
|
||||
|
||||
`dependsOn: ['orgId']` 会在组织变化时清除负责人草稿,并以新组织加载负责人选项。一次 `setSearchValues` 可以同时传入组织和新的负责人。用 `visible: ({ orgId }) => orgId != null` 在组织为空时隐藏负责人并排除该条件。折叠只改变布局,仍会提交和校验折叠区域里的字段。
|
||||
|
||||
用 `defaultCollapsed`、`collapsedRows`、`maxColumns` 和字段 `span` 控制容器内布局。标签位置和宽度用 `labelPlacement` / `labelWidth`,按钮文案用 `searchText` / `resetText`。用 `renderActions` 扩展默认按钮或自行调用 `submit`、`reset` 和 `setCollapsed`。如果页面已有完整自定义表单,仍可用优先渲染的 `filters` 插槽调用 `submit(values)`。
|
||||
|
||||
## 布局、工具与实例
|
||||
|
||||
`autoHeight` 让表格填充当前工作区;嵌入自定义区域时可用 `--r-table-height` 设定可用高度。宽表设置列宽与 `scrollX`,使横向滚动留在表格内。
|
||||
@ -140,7 +189,7 @@ Naive UI DataTable 的列定义、选择、展开、加载、空态和虚拟滚
|
||||
| `pagination` | 普通模式缺省开,`false` 关闭;对象透传 Naive UI Pagination。容器小于 600px 时默认简洁模式,显式 `simple` 优先。 |
|
||||
| `pageSize` | 默认 10;`pagination.pageSize`、`pagination.defaultPageSize` 依次优先。远端初始页读 `pagination.defaultPage`。 |
|
||||
| `request` / `params` | 配置 `request` 时组件管理远端数据。`params` 深层变化会从第 1 页重查。 |
|
||||
| `search` | `{ key, label, placeholder?, options? }[]`。输入只更新草稿,提交才生效。 |
|
||||
| `search` | 兼容原有字段数组,支持 `TableProSearchOptions` 和 `false`。见[高级搜索](#高级搜索)。 |
|
||||
| `rowKey` | 默认 `row.id ?? row.key`,业务数据缺少两者时必须提供稳定键。 |
|
||||
| `columnStateKey` | 缺省不持久化。传稳定标识可记住隐藏列。 |
|
||||
| `downloadCsvTableOptions` | 内置导出默认配置,模板实现使用 `fileName`、`keepOriginalData`。 |
|
||||
|
||||
@ -20,7 +20,7 @@ import { RTablePro } from '@/components'
|
||||
```
|
||||
|
||||
- `data` 用于本地数据;`request(params, signal)` 用于远端数据,返回 `Promise<{ data: Row[]; total: number }>`。`total` 是应用筛选后的总数;传递 `signal` 给 HTTP 客户端可以取消上一条请求。
|
||||
- 搜索字段有 `key`、`label` 和可选的 `placeholder`、`options`(下拉选项)。输入文字只更新草稿,提交后回到第 1 页。本地文字匹配忽略大小写,下拉按值匹配;远端模式把搜索值传给 `request`。外部筛选可用 `params`,复杂表单可用 `filters` 插槽及其 `submit(values)` 方法。
|
||||
- `search` 支持原有字段数组和 `TableProSearchOptions`。编辑只更新草稿,提交后回到第 1 页。外部筛选可用 `params`,自定义完整表单可用 `filters` 插槽及其 `submit(values)` 方法。
|
||||
- 完整模式默认使用 DataTable 底部自带的分页器,每页 10 条。空间不足时使用 Naive UI 的简洁分页,也可通过 `pagination.simple` 指定模式。用 `pageSize`、`pagination={{ pageSizes: [10, 20, 50] }}` 调整,或用 `pagination={false}` 关闭。关闭时请求不附加 `page`、`pageSize`;`bare pagination` 可以单独保留分页。
|
||||
- 搜索区在结果上方。表格左上方可用 `title` 传文字,或用同名插槽放筛选开关、快捷操作等;都不传时不占位。`toolbar` 插槽和默认工具集中在表格右上方。
|
||||
- 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。
|
||||
@ -80,4 +80,4 @@ CSV 默认导出当前页可见数据列;`keepOriginalData` 使用传入的整
|
||||
|
||||
普通列配置、选择、展开、排序、筛选、汇总、虚拟滚动、固定列、空状态和加载插槽沿用 [DataTable API](https://www.naiveui.com/zh-CN/components/data-table)。`pagination` 对象透传 [Pagination API](https://www.naiveui.com/zh-CN/components/pagination) 的配置,包括快速跳页、页码模板和回调。配置了 `request` 时页码、每页条数和总数由 TablePro 管理;初始页用 `pagination.defaultPage`,运行时跳页用实例 `setPage`。手动远端模式可以直接传 `remote + data + pagination`。服务端排序、过滤继续使用 Naive UI 的事件,在调用方将条件传给 `params`,组件不会推断接口字段。页数很大时可配置 `pagination.showQuickJumpDropdown: false`。
|
||||
|
||||
在「表格」菜单下,除了纯表格、远端查询、自适应高度、列设置、打印和插槽示例,还可以查看三个独立的 Hooks 示例:查询与分页、选择与批量操作、导出与打印。旧示例路径会重定向到对应子页。
|
||||
在「表格 → 高级搜索」可以切换本地筛选和模拟远端查询,查看日期区间拆分和组织到负责人的联动。配置、值类型和实例方法见[高级搜索参考](../../../../apps/docs/reference/table-pro.md#高级搜索)。在「表格」菜单下也可以查看查询与分页、选择与批量操作、导出与打印三个 Hooks 示例。
|
||||
|
||||
@ -2,10 +2,19 @@ export { default as RTablePro } from './src/TablePro'
|
||||
export { useTablePro } from './src/useTablePro'
|
||||
export type { TableProInst, TableProProps } from './src/TablePro'
|
||||
export type {
|
||||
TableProColumn,
|
||||
TableProParams,
|
||||
TableProQueryState,
|
||||
TableProRequest,
|
||||
TableProResult,
|
||||
TableProSearchField,
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchActions,
|
||||
TableProSearchConfig,
|
||||
TableProSearchOptionContext,
|
||||
TableProSearchOptions,
|
||||
TableProSearchSubmission,
|
||||
TableProSearchValue,
|
||||
TableProSearchValues,
|
||||
TableProPrintOptions,
|
||||
} from './src/types'
|
||||
|
||||
@ -5,33 +5,55 @@ import {
|
||||
computed,
|
||||
defineComponent,
|
||||
onBeforeUnmount,
|
||||
onBeforeUpdate,
|
||||
onMounted,
|
||||
ref,
|
||||
shallowRef,
|
||||
useTemplateRef,
|
||||
watch,
|
||||
} from 'vue'
|
||||
import type { ExtractPublicPropTypes, PropType } from 'vue'
|
||||
import Search from './components/Search'
|
||||
import type { TableSearchFormInst } from './components/Search'
|
||||
import { useTableLocale } from './locale'
|
||||
import tableProps from './props'
|
||||
import {
|
||||
copySearchValues,
|
||||
createSearchPredicate,
|
||||
isSearchArray,
|
||||
normalizeSearchValues,
|
||||
resolveSearchFields,
|
||||
resolveSearchOptions,
|
||||
sameSearchField,
|
||||
toSearchParams,
|
||||
} from './search'
|
||||
import TablePanel from './TablePanel'
|
||||
import type {
|
||||
TablePanelInst,
|
||||
TableProColumn,
|
||||
TableProParams,
|
||||
TableProQueryState,
|
||||
TableProRequest,
|
||||
TableProResult,
|
||||
TableProSearchField,
|
||||
TableSearchValues,
|
||||
TableProSearchConfig,
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchSubmission,
|
||||
TableProSearchValues,
|
||||
} from './types'
|
||||
import { useTableSearch } from './useTableSearch'
|
||||
|
||||
const positiveInteger = (value: number) =>
|
||||
Number.isSafeInteger(value) && value > 0
|
||||
|
||||
const emptyRemoteRows: TableProResult['data'] = []
|
||||
const emptySearchFields: readonly TableProSearchFieldConfig[] = []
|
||||
|
||||
const props = {
|
||||
...tableProps,
|
||||
columns: {
|
||||
...tableProps.columns,
|
||||
type: Array as PropType<TableProColumn[]>,
|
||||
},
|
||||
pagination: {
|
||||
type: [Boolean, Object] as PropType<boolean | PaginationProps>,
|
||||
default: void 0,
|
||||
@ -40,7 +62,10 @@ const props = {
|
||||
request: Function as PropType<TableProRequest>,
|
||||
onRegister: Function as PropType<(instance: TableProInst) => void>,
|
||||
params: Object,
|
||||
search: Array as PropType<TableProSearchField[]>,
|
||||
search: {
|
||||
type: [Array, Object, Boolean] as PropType<TableProSearchConfig>,
|
||||
default: void 0,
|
||||
},
|
||||
rowKey: {
|
||||
type: tableProps.rowKey,
|
||||
default: (row: { id?: string | number; key?: string | number }) =>
|
||||
@ -56,20 +81,79 @@ export interface TableProInst extends TablePanelInst {
|
||||
setPage: (page: number) => Promise<void>
|
||||
setPageSize: (pageSize: number) => Promise<void>
|
||||
getCurrentPageData: () => readonly Readonly<Record<string, unknown>>[]
|
||||
getSearchValues: (source?: 'draft' | 'applied') => TableProSearchValues
|
||||
setSearchValues: (values: TableProSearchValues) => void
|
||||
submitSearch: () => Promise<boolean>
|
||||
resetSearch: () => Promise<boolean>
|
||||
}
|
||||
|
||||
function createSearchSnapshot(
|
||||
values: TableProSearchValues,
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
) {
|
||||
return {
|
||||
values,
|
||||
params: toSearchParams(fields, copySearchValues(values)),
|
||||
matches: createSearchPredicate(fields, values),
|
||||
}
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: 'RTablePro',
|
||||
inheritAttrs: false,
|
||||
props,
|
||||
emits: { 'request-error': (_error: unknown) => true },
|
||||
emits: {
|
||||
'request-error': (_error: unknown) => true,
|
||||
'search-error': (_error: unknown) => true,
|
||||
search: (_submission: TableProSearchSubmission) => true,
|
||||
},
|
||||
setup(props, { attrs, slots, expose, emit }) {
|
||||
const { t } = useTableLocale()
|
||||
const table = shallowRef<TablePanelInst>()
|
||||
const result = shallowRef<TableProResult>()
|
||||
const requestPhase = ref<'idle' | 'loading' | 'failed'>('idle')
|
||||
const searchValues = shallowRef<TableSearchValues>({})
|
||||
const searchForm = useTemplateRef<TableSearchFormInst>('searchForm')
|
||||
const customFilters = ref(!!slots.filters)
|
||||
const searchFailed = ref(false)
|
||||
const searchOptions = computed(() => resolveSearchOptions(props.search))
|
||||
const searchFields = computed(() => {
|
||||
const options = searchOptions.value
|
||||
|
||||
if (customFilters.value || !options) return emptySearchFields
|
||||
|
||||
return resolveSearchFields(options, props.columns)
|
||||
})
|
||||
const searchModel = useTableSearch(
|
||||
() => searchFields.value,
|
||||
() => searchOptions.value,
|
||||
(isCurrent) =>
|
||||
searchFields.value.some((field) => field.type && field.rules)
|
||||
? (searchForm.value?.validate(isCurrent) ?? true)
|
||||
: true,
|
||||
() => searchForm.value?.restoreValidation(),
|
||||
(values, reason) => applySearch(values, searchFields.value, reason),
|
||||
)
|
||||
const applied = shallowRef(createSearchSnapshot({}, emptySearchFields))
|
||||
|
||||
try {
|
||||
applied.value = createSearchSnapshot(
|
||||
normalizeSearchValues(searchFields.value, searchModel.draft.value),
|
||||
searchFields.value,
|
||||
)
|
||||
} catch (error) {
|
||||
searchFailed.value = true
|
||||
emit('search-error', error)
|
||||
}
|
||||
|
||||
const manualSearch = computed(
|
||||
() =>
|
||||
props.remote &&
|
||||
!!searchOptions.value &&
|
||||
!isSearchArray(props.search) &&
|
||||
!customFilters.value,
|
||||
)
|
||||
const pagination = computed(() => props.pagination ?? !props.bare)
|
||||
const paginated = computed(() => pagination.value !== false)
|
||||
const pagerOptions = computed(() =>
|
||||
typeof props.pagination === 'object' ? props.pagination : void 0,
|
||||
)
|
||||
@ -87,36 +171,20 @@ export default defineComponent({
|
||||
const queryState = computed<TableProQueryState | null>(() => {
|
||||
if (!props.request) return null
|
||||
|
||||
const paginated = pagination.value !== false
|
||||
|
||||
return Object.freeze({
|
||||
loading: requestPhase.value === 'loading',
|
||||
failed: requestPhase.value === 'failed',
|
||||
page: paginated ? page.value : null,
|
||||
pageSize: paginated ? pageSize.value : null,
|
||||
page: paginated.value ? page.value : null,
|
||||
pageSize: paginated.value ? pageSize.value : null,
|
||||
total: result.value?.total ?? null,
|
||||
})
|
||||
})
|
||||
const localRows = computed(() => {
|
||||
const entries = Object.entries(searchValues.value)
|
||||
const { matches } = applied.value
|
||||
|
||||
if (!entries.length) return props.data
|
||||
|
||||
const selects = new Set(
|
||||
props.search?.filter(({ options }) => options).map(({ key }) => key),
|
||||
)
|
||||
|
||||
return props.data.filter((row) =>
|
||||
entries.every(([key, value]) => {
|
||||
const cell = row[key]
|
||||
|
||||
return typeof value === 'number' || selects.has(key)
|
||||
? cell === value
|
||||
: String(cell ?? '')
|
||||
.toLowerCase()
|
||||
.includes(value.toLowerCase())
|
||||
}),
|
||||
)
|
||||
return matches && !manualSearch.value
|
||||
? props.data.filter(matches)
|
||||
: props.data
|
||||
})
|
||||
let pending: AbortController | undefined
|
||||
|
||||
@ -139,9 +207,12 @@ export default defineComponent({
|
||||
requestPhase.value = 'loading'
|
||||
|
||||
// 分页字段由表格统一管理,筛选参数不能覆盖当前页码。
|
||||
const query: TableProParams = { ...params, ...searchValues.value }
|
||||
const query: TableProParams = {
|
||||
...params,
|
||||
...copySearchValues(applied.value.params),
|
||||
}
|
||||
|
||||
if (pagination.value !== false) {
|
||||
if (paginated.value) {
|
||||
query.page = page.value
|
||||
query.pageSize = pageSize.value
|
||||
} else {
|
||||
@ -167,7 +238,7 @@ export default defineComponent({
|
||||
|
||||
const lastPage = Math.max(1, Math.ceil(response.total / pageSize.value))
|
||||
|
||||
if (pagination.value !== false && page.value > lastPage) {
|
||||
if (paginated.value && page.value > lastPage) {
|
||||
page.value = lastPage
|
||||
|
||||
if (response.total) {
|
||||
@ -206,20 +277,85 @@ export default defineComponent({
|
||||
await reload(true)
|
||||
}
|
||||
|
||||
const submitSearch = (values: TableSearchValues) => {
|
||||
searchValues.value = values
|
||||
async function applySearch(
|
||||
values: TableProSearchValues,
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
reason?: TableProSearchSubmission['reason'],
|
||||
) {
|
||||
let snapshot: ReturnType<typeof createSearchSnapshot>
|
||||
|
||||
return reload(true)
|
||||
try {
|
||||
snapshot = createSearchSnapshot(copySearchValues(values), fields)
|
||||
} catch (error) {
|
||||
searchFailed.value = true
|
||||
emit('search-error', error)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
searchFailed.value = false
|
||||
applied.value = snapshot
|
||||
page.value = 1
|
||||
|
||||
if (reason) {
|
||||
emit('search', {
|
||||
values: copySearchValues(snapshot.values),
|
||||
params: copySearchValues(snapshot.params),
|
||||
reason,
|
||||
})
|
||||
}
|
||||
|
||||
await reload()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const submitFilters = async (values: Record<string, string | number>) => {
|
||||
const fields =
|
||||
searchOptions.value?.fields?.filter(({ type }) => !type) ??
|
||||
emptySearchFields
|
||||
|
||||
await applySearch(values, fields, 'submit')
|
||||
}
|
||||
|
||||
onBeforeUpdate(() => {
|
||||
customFilters.value = !!slots.filters
|
||||
})
|
||||
watch(searchFields, (fields, previous) => {
|
||||
const previousByKey = new Map(previous.map((field) => [field.key, field]))
|
||||
const retainedKeys = new Set(
|
||||
fields
|
||||
.filter((field) =>
|
||||
sameSearchField(field, previousByKey.get(field.key)),
|
||||
)
|
||||
.map(({ key }) => key),
|
||||
)
|
||||
|
||||
if (
|
||||
retainedKeys.size === fields.length &&
|
||||
fields.length === previous.length
|
||||
)
|
||||
return
|
||||
|
||||
searchModel.reconcile(retainedKeys)
|
||||
const retained = Object.fromEntries(
|
||||
Object.entries(applied.value.values).filter(([key]) =>
|
||||
retainedKeys.has(key),
|
||||
),
|
||||
)
|
||||
|
||||
if (
|
||||
Object.keys(retained).length !==
|
||||
Object.keys(applied.value.values).length
|
||||
)
|
||||
void applySearch(normalizeSearchValues(fields, retained), fields)
|
||||
})
|
||||
|
||||
watch(
|
||||
[
|
||||
() => props.request,
|
||||
() => props.params,
|
||||
() => pagination.value === false,
|
||||
configuredPageSize,
|
||||
],
|
||||
[() => props.request, () => props.params, paginated, configuredPageSize],
|
||||
(_values, previous) => {
|
||||
if (!previous.length && searchFailed.value) return
|
||||
|
||||
void reload(previous.length > 0)
|
||||
},
|
||||
{ deep: true, immediate: true },
|
||||
@ -243,6 +379,21 @@ export default defineComponent({
|
||||
reload,
|
||||
setPage,
|
||||
setPageSize,
|
||||
getSearchValues: (source = 'draft') =>
|
||||
source === 'applied'
|
||||
? copySearchValues(applied.value.values)
|
||||
: searchModel.getValues(),
|
||||
setSearchValues: (values) => {
|
||||
if (searchFields.value.length) searchModel.setValues(values)
|
||||
},
|
||||
submitSearch: () =>
|
||||
searchFields.value.length
|
||||
? searchModel.submit()
|
||||
: Promise.resolve(false),
|
||||
resetSearch: () =>
|
||||
searchFields.value.length
|
||||
? searchModel.reset()
|
||||
: Promise.resolve(false),
|
||||
getTableInstance: () => table.value?.getTableInstance() ?? null,
|
||||
getCurrentPageData: () =>
|
||||
table.value?.getTableInstance()?.getCurrentPageData() ?? [],
|
||||
@ -311,9 +462,23 @@ export default defineComponent({
|
||||
{{
|
||||
...panelSlots,
|
||||
filters: filters
|
||||
? () => filters({ submit: submitSearch })
|
||||
: search?.length
|
||||
? () => <Search fields={search} onSearch={submitSearch} />
|
||||
? () => filters({ submit: submitFilters })
|
||||
: searchFields.value.length
|
||||
? () => (
|
||||
<Search
|
||||
ref="searchForm"
|
||||
fields={searchFields.value}
|
||||
values={searchModel.draft.value}
|
||||
options={searchOptions.value}
|
||||
legacy={isSearchArray(search)}
|
||||
failed={searchFailed.value}
|
||||
submit={instance.submitSearch}
|
||||
reset={instance.resetSearch}
|
||||
setValue={(key, value) =>
|
||||
searchModel.setValues({ [key]: value })
|
||||
}
|
||||
/>
|
||||
)
|
||||
: void 0,
|
||||
notice: () =>
|
||||
requestPhase.value === 'failed'
|
||||
|
||||
@ -1,87 +1,289 @@
|
||||
import { NButton, NInput, NSelect } from 'naive-ui'
|
||||
import { defineComponent, reactive, useId } from 'vue'
|
||||
import { useElementSize } from '@vueuse/core'
|
||||
import { NButton, NForm, NFormItem, NGrid, NGridItem } from 'naive-ui'
|
||||
import type { FormInst } from 'naive-ui'
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
nextTick,
|
||||
ref,
|
||||
useId,
|
||||
useTemplateRef,
|
||||
} from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import { useTableLocale } from '../locale'
|
||||
import type { TableProSearchField, TableSearchValues } from '../types'
|
||||
import { isSearchFieldVisible, normalizeSearchValues } from '../search'
|
||||
import type {
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchOptions,
|
||||
TableProSearchValue,
|
||||
TableProSearchValues,
|
||||
} from '../types'
|
||||
import SearchControl from './SearchControl'
|
||||
|
||||
export interface TableSearchFormInst {
|
||||
validate: (isCurrent: () => boolean) => Promise<boolean>
|
||||
restoreValidation: () => void
|
||||
}
|
||||
|
||||
const gridSize = (size: number | undefined, fallback: number) =>
|
||||
size && Number.isSafeInteger(size) && size > 0 ? size : fallback
|
||||
|
||||
export default defineComponent({
|
||||
name: 'TableProSearch',
|
||||
props: {
|
||||
fields: { type: Array as PropType<TableProSearchField[]>, required: true },
|
||||
fields: {
|
||||
type: Array as PropType<readonly TableProSearchFieldConfig[]>,
|
||||
required: true,
|
||||
},
|
||||
options: {
|
||||
type: Object as PropType<TableProSearchOptions>,
|
||||
default: void 0,
|
||||
},
|
||||
values: {
|
||||
type: Object as PropType<TableProSearchValues>,
|
||||
required: true,
|
||||
},
|
||||
legacy: Boolean,
|
||||
failed: Boolean,
|
||||
submit: {
|
||||
type: Function as PropType<() => Promise<boolean>>,
|
||||
required: true,
|
||||
},
|
||||
reset: {
|
||||
type: Function as PropType<() => Promise<boolean>>,
|
||||
required: true,
|
||||
},
|
||||
setValue: {
|
||||
type: Function as PropType<
|
||||
(key: string, value: TableProSearchValue | null) => void
|
||||
>,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
emits: { search: (_values: TableSearchValues) => true },
|
||||
setup(props, { emit }) {
|
||||
setup(props, { expose }) {
|
||||
const { t } = useTableLocale()
|
||||
const id = useId()
|
||||
const values = reactive<Record<string, string | number | null>>({})
|
||||
const submit = (event: SubmitEvent) => {
|
||||
event.preventDefault()
|
||||
const result: TableSearchValues = {}
|
||||
const wrapper = useTemplateRef<HTMLElement>('wrapper')
|
||||
const form = useTemplateRef<FormInst>('form')
|
||||
const { width } = useElementSize(wrapper)
|
||||
const collapsed = ref(props.options?.defaultCollapsed ?? false)
|
||||
const columns = computed(() =>
|
||||
Math.min(
|
||||
gridSize(props.options?.maxColumns, 4),
|
||||
width.value >= 1320
|
||||
? 4
|
||||
: width.value >= 960
|
||||
? 3
|
||||
: width.value >= 600
|
||||
? 2
|
||||
: 1,
|
||||
),
|
||||
)
|
||||
const collapsedRows = computed(() =>
|
||||
gridSize(props.options?.collapsedRows, 1),
|
||||
)
|
||||
const items = computed(() =>
|
||||
props.fields.flatMap((field, index) =>
|
||||
isSearchFieldVisible(field, props.values)
|
||||
? [
|
||||
{
|
||||
field,
|
||||
path: `field-${index}`,
|
||||
span: Math.min(
|
||||
columns.value,
|
||||
gridSize(field.type ? field.span : void 0, 1),
|
||||
),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
)
|
||||
const canCollapse = computed(() => {
|
||||
if (props.legacy) return false
|
||||
|
||||
for (const { key } of props.fields) {
|
||||
const value = values[key]
|
||||
const normalized = typeof value === 'string' ? value.trim() : value
|
||||
const cols = columns.value
|
||||
let used = 0
|
||||
|
||||
if (normalized != null && normalized !== '') result[key] = normalized
|
||||
for (const { span } of items.value) {
|
||||
const row = used % cols
|
||||
|
||||
if (row + span > cols) used += cols - row
|
||||
|
||||
used += span
|
||||
}
|
||||
|
||||
emit('search', result)
|
||||
return used > cols * collapsedRows.value
|
||||
})
|
||||
const model = computed(() => {
|
||||
const values = normalizeSearchValues(props.fields, props.values)
|
||||
|
||||
return Object.fromEntries(
|
||||
items.value.map(({ field, path }) => [path, values[field.key]]),
|
||||
)
|
||||
})
|
||||
const validate = async (isCurrent: () => boolean) => {
|
||||
// 实例方法可以先更新草稿再提交,等待表单接收到最新 model 和规则。
|
||||
await nextTick()
|
||||
|
||||
if (!isCurrent()) return false
|
||||
|
||||
try {
|
||||
await form.value?.validate()
|
||||
|
||||
return true
|
||||
} catch (errors) {
|
||||
if (!isCurrent()) {
|
||||
form.value?.restoreValidation()
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
collapsed.value = false
|
||||
await nextTick()
|
||||
|
||||
if (Array.isArray(errors)) {
|
||||
const path: unknown = errors[0]?.[0]?.field
|
||||
|
||||
if (typeof path === 'string' && /^field-\d+$/.test(path)) {
|
||||
wrapper.value
|
||||
?.querySelector<HTMLElement>(
|
||||
`[data-search-field="${path}"] :is(input, textarea, button, [tabindex="0"])`,
|
||||
)
|
||||
?.focus()
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const reset = () => {
|
||||
Object.keys(values).forEach((key) => delete values[key])
|
||||
emit('search', {})
|
||||
let pendingValidation = Promise.resolve(true)
|
||||
const instance: TableSearchFormInst = {
|
||||
validate: (isCurrent) => {
|
||||
// Naive UI 的异步规则会直接更新表单提示,串行校验避免旧结果覆盖新提示。
|
||||
pendingValidation = pendingValidation.then(() => validate(isCurrent))
|
||||
|
||||
return pendingValidation
|
||||
},
|
||||
restoreValidation: () => form.value?.restoreValidation(),
|
||||
}
|
||||
|
||||
expose(instance)
|
||||
|
||||
const renderItem = ({ field, path }: (typeof items.value)[number]) => {
|
||||
const labelId = `${id}-${path}-label`
|
||||
const inputId = `${id}-${path}-input`
|
||||
const hasInput =
|
||||
field.type === 'text' ||
|
||||
field.type === 'number' ||
|
||||
(!field.type && !field.options)
|
||||
|
||||
return (
|
||||
<NFormItem
|
||||
class="r-table-search__item"
|
||||
data-search-field={path}
|
||||
label={field.label}
|
||||
labelProps={{ id: labelId, for: hasInput ? inputId : void 0 }}
|
||||
path={path}
|
||||
rule={field.type ? field.rules : void 0}
|
||||
showFeedback={!!(field.type && field.rules)}
|
||||
>
|
||||
<SearchControl
|
||||
field={field}
|
||||
values={props.values}
|
||||
labelId={labelId}
|
||||
inputId={inputId}
|
||||
setValue={(value) => props.setValue(field.key, value)}
|
||||
/>
|
||||
</NFormItem>
|
||||
)
|
||||
}
|
||||
|
||||
const renderActions = () => {
|
||||
const defaultActions = [
|
||||
canCollapse.value && (
|
||||
<NButton
|
||||
attrType="button"
|
||||
text
|
||||
aria-expanded={!collapsed.value}
|
||||
aria-controls={`${id}-fields`}
|
||||
onClick={() => {
|
||||
collapsed.value = !collapsed.value
|
||||
}}
|
||||
>
|
||||
{t(collapsed.value ? 'expandSearch' : 'collapseSearch')}
|
||||
</NButton>
|
||||
),
|
||||
<NButton attrType="button" onClick={() => void props.reset()}>
|
||||
{props.options?.resetText ?? t('reset')}
|
||||
</NButton>,
|
||||
<NButton
|
||||
attrType="submit"
|
||||
type="primary"
|
||||
class="r-table-search__submit"
|
||||
>
|
||||
{props.options?.searchText ?? t('search')}
|
||||
</NButton>,
|
||||
]
|
||||
|
||||
return (
|
||||
<div class="r-table-search__actions">
|
||||
{props.options?.renderActions
|
||||
? props.options.renderActions({
|
||||
submit: props.submit,
|
||||
reset: props.reset,
|
||||
collapsed: collapsed.value,
|
||||
canCollapse: canCollapse.value,
|
||||
setCollapsed: (value) => {
|
||||
collapsed.value = value
|
||||
},
|
||||
defaultActions,
|
||||
})
|
||||
: defaultActions}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return () => (
|
||||
<form class="r-table-search" onSubmit={submit}>
|
||||
{props.fields.map(({ key, label, placeholder, options }, index) => {
|
||||
const fieldId = `${id}-${index}`
|
||||
|
||||
return (
|
||||
<div class="r-table-search__field" key={key}>
|
||||
<label
|
||||
for={options ? void 0 : fieldId}
|
||||
id={options ? fieldId : void 0}
|
||||
<div ref="wrapper" class="r-table-search-shell">
|
||||
<NForm
|
||||
ref="form"
|
||||
class={props.legacy ? 'r-table-search' : 'r-table-search--advanced'}
|
||||
model={model.value}
|
||||
labelPlacement={props.options?.labelPlacement ?? 'top'}
|
||||
labelWidth={props.options?.labelWidth}
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void props.submit()
|
||||
}}
|
||||
>
|
||||
{props.legacy ? (
|
||||
items.value.map((item) => (
|
||||
<div class="r-table-search__field" key={item.field.key}>
|
||||
{renderItem(item)}
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div id={`${id}-fields`}>
|
||||
<NGrid
|
||||
cols={columns.value}
|
||||
xGap={12}
|
||||
yGap={12}
|
||||
collapsed={canCollapse.value && collapsed.value}
|
||||
collapsedRows={collapsedRows.value}
|
||||
>
|
||||
{label}
|
||||
</label>
|
||||
{options ? (
|
||||
<NSelect
|
||||
clearable
|
||||
aria-labelledby={fieldId}
|
||||
value={values[key] ?? null}
|
||||
options={options}
|
||||
placeholder={placeholder}
|
||||
onUpdateValue={(value) => {
|
||||
values[key] = value
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<NInput
|
||||
clearable
|
||||
inputProps={{ id: fieldId }}
|
||||
value={String(values[key] ?? '')}
|
||||
placeholder={placeholder}
|
||||
onUpdateValue={(value) => {
|
||||
values[key] = value
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{items.value.map((item) => (
|
||||
<NGridItem key={item.field.key} span={item.span}>
|
||||
{renderItem(item)}
|
||||
</NGridItem>
|
||||
))}
|
||||
</NGrid>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div class="r-table-search__actions">
|
||||
<NButton onClick={reset}>{t('reset')}</NButton>
|
||||
<NButton
|
||||
attrType="submit"
|
||||
type="primary"
|
||||
class="r-table-search__submit"
|
||||
>
|
||||
{t('search')}
|
||||
</NButton>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{renderActions()}
|
||||
{props.failed && <div role="alert">{t('searchError')}</div>}
|
||||
</NForm>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
161
packages/ui/src/RTablePro/src/components/SearchControl.tsx
Normal file
161
packages/ui/src/RTablePro/src/components/SearchControl.tsx
Normal file
@ -0,0 +1,161 @@
|
||||
import {
|
||||
NCascader,
|
||||
NDatePicker,
|
||||
NInput,
|
||||
NInputNumber,
|
||||
NSelect,
|
||||
NTimePicker,
|
||||
NTreeSelect,
|
||||
} from 'naive-ui'
|
||||
import { useTableLocale } from '../locale'
|
||||
import type {
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchValue,
|
||||
TableProSearchValues,
|
||||
} from '../types'
|
||||
import SearchSelect from './SearchSelect'
|
||||
|
||||
export default function SearchControl({
|
||||
field,
|
||||
values,
|
||||
inputId,
|
||||
labelId,
|
||||
setValue,
|
||||
}: {
|
||||
field: TableProSearchFieldConfig
|
||||
values: TableProSearchValues
|
||||
inputId: string
|
||||
labelId: string
|
||||
setValue: (value: TableProSearchValue | null) => void
|
||||
}) {
|
||||
const { t } = useTableLocale()
|
||||
const value = values[field.key] ?? null
|
||||
const common = {
|
||||
clearable: true,
|
||||
placeholder: field.placeholder,
|
||||
'aria-labelledby': labelId,
|
||||
}
|
||||
const inputProps = { id: inputId, 'aria-labelledby': labelId }
|
||||
|
||||
switch (field.type) {
|
||||
case 'custom':
|
||||
return <>{field.render({ value, setValue, values, inputId, labelId })}</>
|
||||
case 'text':
|
||||
return (
|
||||
<NInput
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
inputProps={{ ...field.fieldProps?.inputProps, ...inputProps }}
|
||||
value={(value as string | null) ?? ''}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'number':
|
||||
return (
|
||||
<NInputNumber
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
inputProps={{ ...field.fieldProps?.inputProps, ...inputProps }}
|
||||
value={value as number | null}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'boolean':
|
||||
return (
|
||||
<NSelect
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
inputProps={{ ...field.fieldProps?.inputProps, ...inputProps }}
|
||||
options={[
|
||||
{ label: t('searchYes'), value: 1 },
|
||||
{ label: t('searchNo'), value: 0 },
|
||||
]}
|
||||
value={value == null ? null : Number(value)}
|
||||
onUpdateValue={(value: number | null) =>
|
||||
setValue(value == null ? null : value === 1)
|
||||
}
|
||||
/>
|
||||
)
|
||||
case 'select':
|
||||
return (
|
||||
<SearchSelect
|
||||
key={JSON.stringify(field.dependsOn?.map((key) => values[key]))}
|
||||
field={field}
|
||||
values={values}
|
||||
inputId={inputId}
|
||||
labelId={labelId}
|
||||
setValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'date':
|
||||
case 'dateRange':
|
||||
return (
|
||||
<NDatePicker
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
type={field.type === 'date' ? 'date' : 'daterange'}
|
||||
valueFormat="yyyy-MM-dd"
|
||||
formattedValue={value as string | [string, string] | null}
|
||||
onUpdateFormattedValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'datetime':
|
||||
case 'datetimeRange':
|
||||
return (
|
||||
<NDatePicker
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
type={field.type === 'datetime' ? 'datetime' : 'datetimerange'}
|
||||
value={value as number | [number, number] | null}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'time':
|
||||
return (
|
||||
<NTimePicker
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
valueFormat="HH:mm:ss"
|
||||
formattedValue={value as string | null}
|
||||
onUpdateFormattedValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'cascader':
|
||||
return (
|
||||
<NCascader
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
multiple={field.multiple}
|
||||
value={value as string | number | (string | number)[] | null}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
)
|
||||
case 'treeSelect':
|
||||
return (
|
||||
<NTreeSelect
|
||||
{...common}
|
||||
{...field.fieldProps}
|
||||
multiple={field.multiple}
|
||||
value={value as string | number | (string | number)[] | null}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
)
|
||||
default:
|
||||
return field.options ? (
|
||||
<NSelect
|
||||
{...common}
|
||||
inputProps={inputProps}
|
||||
options={field.options}
|
||||
value={value as string | number | null}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
) : (
|
||||
<NInput
|
||||
{...common}
|
||||
inputProps={inputProps}
|
||||
value={(value as string | null) ?? ''}
|
||||
onUpdateValue={setValue}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
137
packages/ui/src/RTablePro/src/components/SearchSelect.tsx
Normal file
137
packages/ui/src/RTablePro/src/components/SearchSelect.tsx
Normal file
@ -0,0 +1,137 @@
|
||||
import { call } from '@ray-template/composables/vue/call'
|
||||
import { NButton, NSelect } from 'naive-ui'
|
||||
import type { SelectProps } from 'naive-ui'
|
||||
import { defineComponent, ref, shallowRef, watch } from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import { useTableLocale } from '../locale'
|
||||
import { copySearchValues } from '../search'
|
||||
import type {
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchValue,
|
||||
TableProSearchValues,
|
||||
} from '../types'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'TableProSearchSelect',
|
||||
props: {
|
||||
field: {
|
||||
type: Object as PropType<
|
||||
Extract<TableProSearchFieldConfig, { type: 'select' }>
|
||||
>,
|
||||
required: true,
|
||||
},
|
||||
values: { type: Object as PropType<TableProSearchValues>, required: true },
|
||||
inputId: { type: String, required: true },
|
||||
labelId: { type: String, required: true },
|
||||
setValue: {
|
||||
type: Function as PropType<(value: TableProSearchValue | null) => void>,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
setup(props) {
|
||||
const { t } = useTableLocale()
|
||||
const keyword = ref('')
|
||||
const retry = ref(0)
|
||||
const options = shallowRef<SelectProps['options']>()
|
||||
const loading = ref(false)
|
||||
const failed = ref(false)
|
||||
|
||||
watch(
|
||||
[() => props.field.loadOptions, keyword, retry],
|
||||
(
|
||||
[load, query, attempt],
|
||||
[previousLoad, previousQuery, previousAttempt],
|
||||
onCleanup,
|
||||
) => {
|
||||
options.value = void 0
|
||||
failed.value = false
|
||||
loading.value = !!load
|
||||
|
||||
if (!load) return
|
||||
|
||||
const controller = new AbortController()
|
||||
const values = copySearchValues(props.values)
|
||||
const run = async () => {
|
||||
try {
|
||||
const result = await load({
|
||||
keyword: query,
|
||||
values,
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!controller.signal.aborted) options.value = result
|
||||
} catch {
|
||||
if (!controller.signal.aborted) failed.value = true
|
||||
} finally {
|
||||
if (!controller.signal.aborted) loading.value = false
|
||||
}
|
||||
}
|
||||
const delay =
|
||||
load === previousLoad &&
|
||||
attempt === previousAttempt &&
|
||||
query !== previousQuery
|
||||
? (props.field.optionDebounce ?? 250)
|
||||
: 0
|
||||
const timer = delay > 0 ? setTimeout(() => void run(), delay) : void 0
|
||||
|
||||
onCleanup(() => {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
})
|
||||
|
||||
if (timer === void 0) void run()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
return () => {
|
||||
const { field, values, inputId, labelId, setValue } = props
|
||||
const { loadOptions, fieldProps } = field
|
||||
|
||||
return (
|
||||
<div class="r-table-search__select">
|
||||
<NSelect
|
||||
clearable
|
||||
placeholder={field.placeholder}
|
||||
aria-labelledby={labelId}
|
||||
{...fieldProps}
|
||||
inputProps={{
|
||||
...fieldProps?.inputProps,
|
||||
id: inputId,
|
||||
'aria-labelledby': labelId,
|
||||
}}
|
||||
multiple={field.multiple}
|
||||
filterable={fieldProps?.filterable ?? !!loadOptions}
|
||||
remote={loadOptions ? true : fieldProps?.remote}
|
||||
loading={loading.value || (fieldProps?.loading ?? false)}
|
||||
options={options.value ?? field.options}
|
||||
value={
|
||||
(values[field.key] ?? null) as
|
||||
string | number | (string | number)[] | null
|
||||
}
|
||||
onUpdateValue={setValue}
|
||||
onSearch={(value) => {
|
||||
if (loadOptions) keyword.value = value
|
||||
|
||||
if (fieldProps?.onSearch) call(fieldProps.onSearch, value)
|
||||
}}
|
||||
/>
|
||||
{failed.value && (
|
||||
<div class="r-table-search__option-error" role="status">
|
||||
<span>{t('searchOptionsError')}</span>
|
||||
<NButton
|
||||
text
|
||||
attrType="button"
|
||||
onClick={() => {
|
||||
retry.value += 1
|
||||
}}
|
||||
>
|
||||
{t('retry')}
|
||||
</NButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
},
|
||||
})
|
||||
@ -11,6 +11,12 @@
|
||||
"emailHint": "Enter part of an email address",
|
||||
"reset": "Reset",
|
||||
"search": "Search",
|
||||
"expandSearch": "Show filters",
|
||||
"collapseSearch": "Hide filters",
|
||||
"searchYes": "Yes",
|
||||
"searchNo": "No",
|
||||
"searchError": "Couldn't prepare the search",
|
||||
"searchOptionsError": "Couldn't load options",
|
||||
"reload": "Refresh",
|
||||
"csv": "Export CSV",
|
||||
"print": "Print table",
|
||||
|
||||
@ -101,6 +101,53 @@
|
||||
}
|
||||
}
|
||||
|
||||
.r-table-search-shell {
|
||||
min-inline-size: 0;
|
||||
}
|
||||
|
||||
.r-table-search--advanced {
|
||||
display: grid;
|
||||
min-inline-size: 0;
|
||||
gap: 12px;
|
||||
|
||||
.r-table-search__actions {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
.r-table-search__item {
|
||||
min-inline-size: 0;
|
||||
|
||||
.n-form-item-blank
|
||||
> :is(
|
||||
.n-input,
|
||||
.n-input-number,
|
||||
.n-base-selection,
|
||||
.n-select,
|
||||
.n-date-picker,
|
||||
.n-time-picker,
|
||||
.n-cascader,
|
||||
.n-tree-select
|
||||
) {
|
||||
inline-size: 100%;
|
||||
min-inline-size: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.r-table-search__select {
|
||||
inline-size: 100%;
|
||||
min-inline-size: 0;
|
||||
}
|
||||
|
||||
.r-table-search__option-error {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
margin-block-start: 4px;
|
||||
color: var(--r-text-secondary);
|
||||
}
|
||||
|
||||
.r-template--dark .r-table-search__submit.n-button {
|
||||
&,
|
||||
&:hover,
|
||||
|
||||
332
packages/ui/src/RTablePro/src/search.ts
Normal file
332
packages/ui/src/RTablePro/src/search.ts
Normal file
@ -0,0 +1,332 @@
|
||||
import { getLeafColumns } from './columns'
|
||||
import type {
|
||||
TableProColumn,
|
||||
TableProSearchConfig,
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchOptions,
|
||||
TableProSearchValue,
|
||||
TableProSearchValues,
|
||||
} from './types'
|
||||
|
||||
type Row = Readonly<Record<string, unknown>>
|
||||
|
||||
export function isSearchArray(
|
||||
search: TableProSearchConfig | undefined,
|
||||
): search is readonly TableProSearchFieldConfig[] {
|
||||
return Array.isArray(search)
|
||||
}
|
||||
|
||||
export function resolveSearchOptions(
|
||||
search: TableProSearchConfig | undefined,
|
||||
): TableProSearchOptions | undefined {
|
||||
return isSearchArray(search) ? { fields: search } : search || void 0
|
||||
}
|
||||
|
||||
export function resolveSearchFields(
|
||||
options: TableProSearchOptions,
|
||||
columns: TableProColumn[],
|
||||
) {
|
||||
const fields =
|
||||
options.fields ??
|
||||
getLeafColumns(columns).flatMap((column) => {
|
||||
const { search } = column as TableProColumn
|
||||
|
||||
if (!search) return []
|
||||
|
||||
const key = String(column.key)
|
||||
const label = typeof column.title === 'string' ? column.title : key
|
||||
|
||||
return [
|
||||
search === true
|
||||
? { key, label }
|
||||
: { ...search, key: search.key ?? key, label: search.label ?? label },
|
||||
]
|
||||
})
|
||||
const seen = new Set<string>()
|
||||
|
||||
return fields.filter(({ key }) => {
|
||||
if (seen.has(key)) return false
|
||||
|
||||
seen.add(key)
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export function copySearchValues<Value>(
|
||||
values: Readonly<Record<string, Value>>,
|
||||
): Record<string, Value> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(values).map(([key, value]) => [
|
||||
key,
|
||||
Array.isArray(value) ? ([...value] as Value) : value,
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
export function isSearchFieldVisible(
|
||||
field: TableProSearchFieldConfig,
|
||||
values: TableProSearchValues,
|
||||
) {
|
||||
return !field.type || (field.visible?.(values) ?? true)
|
||||
}
|
||||
|
||||
const isNumber = (value: unknown): value is number =>
|
||||
typeof value === 'number' && Number.isFinite(value)
|
||||
|
||||
const isKey = (value: unknown) => typeof value === 'string' || isNumber(value)
|
||||
|
||||
const isDay = (value: unknown) => {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
return false
|
||||
}
|
||||
|
||||
const date = new Date(value)
|
||||
|
||||
return (
|
||||
Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value
|
||||
)
|
||||
}
|
||||
|
||||
const isTimestamp = (value: unknown) =>
|
||||
isNumber(value) && Math.abs(value) <= 8.64e15
|
||||
|
||||
function sanitizeValue(
|
||||
field: TableProSearchFieldConfig,
|
||||
value: TableProSearchValues[string],
|
||||
): TableProSearchValue | null {
|
||||
if (value == null) return null
|
||||
|
||||
switch (field.type) {
|
||||
case 'text':
|
||||
return typeof value === 'string' ? value : null
|
||||
case 'number':
|
||||
return isNumber(value) ? value : null
|
||||
case 'boolean':
|
||||
return typeof value === 'boolean' ? value : null
|
||||
case 'date':
|
||||
return isDay(value) ? value : null
|
||||
case 'datetime':
|
||||
return isTimestamp(value) ? value : null
|
||||
case 'time':
|
||||
return typeof value === 'string' &&
|
||||
/^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(value)
|
||||
? value
|
||||
: null
|
||||
case 'dateRange':
|
||||
case 'datetimeRange': {
|
||||
const check = field.type === 'dateRange' ? isDay : isTimestamp
|
||||
|
||||
return Array.isArray(value) &&
|
||||
value.length === 2 &&
|
||||
check(value[0]) &&
|
||||
check(value[1]) &&
|
||||
value[0] <= value[1]
|
||||
? [...value]
|
||||
: null
|
||||
}
|
||||
case 'select':
|
||||
case 'cascader':
|
||||
case 'treeSelect':
|
||||
if (field.multiple)
|
||||
return Array.isArray(value) ? value.filter(isKey) : null
|
||||
|
||||
return isKey(value) ? value : null
|
||||
case 'custom':
|
||||
if (Array.isArray(value)) return value.filter(isKey)
|
||||
|
||||
return typeof value === 'boolean' || isKey(value) ? value : null
|
||||
default:
|
||||
return field.options
|
||||
? isKey(value)
|
||||
? value
|
||||
: null
|
||||
: typeof value === 'string'
|
||||
? value
|
||||
: null
|
||||
}
|
||||
}
|
||||
|
||||
export function pickSearchValues(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
values: TableProSearchValues,
|
||||
): Record<string, TableProSearchValues[string]> {
|
||||
return Object.fromEntries(
|
||||
fields.map((field) => [field.key, sanitizeValue(field, values[field.key])]),
|
||||
)
|
||||
}
|
||||
|
||||
export function initialSearchValues(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
options: TableProSearchOptions | undefined,
|
||||
) {
|
||||
return pickSearchValues(fields, {
|
||||
...Object.fromEntries(
|
||||
fields.map((field) => [
|
||||
field.key,
|
||||
field.type ? field.initialValue : null,
|
||||
]),
|
||||
),
|
||||
...options?.initialValues,
|
||||
})
|
||||
}
|
||||
|
||||
const sameValue = (
|
||||
left: TableProSearchValues[string],
|
||||
right: TableProSearchValues[string],
|
||||
) =>
|
||||
left === right ||
|
||||
(Array.isArray(left) &&
|
||||
Array.isArray(right) &&
|
||||
left.length === right.length &&
|
||||
left.every((value, index) => value === right[index]))
|
||||
|
||||
export function patchSearchValues(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
previous: TableProSearchValues,
|
||||
patch: TableProSearchValues,
|
||||
) {
|
||||
const next = pickSearchValues(fields, { ...previous, ...patch })
|
||||
const changed = new Set(
|
||||
Object.keys(next).filter(
|
||||
(key) => !sameValue(next[key], previous[key] ?? null),
|
||||
),
|
||||
)
|
||||
|
||||
if (!changed.size) return previous
|
||||
|
||||
// 依赖可以跨多级,遍历时把本次被清除的字段也加入变更集合。
|
||||
for (const key of changed) {
|
||||
for (const field of fields) {
|
||||
if (
|
||||
!field.type ||
|
||||
changed.has(field.key) ||
|
||||
Object.hasOwn(patch, field.key)
|
||||
)
|
||||
continue
|
||||
|
||||
if (!field.dependsOn?.includes(key)) continue
|
||||
|
||||
next[field.key] = null
|
||||
changed.add(field.key)
|
||||
}
|
||||
}
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
export function sameSearchField(
|
||||
field: TableProSearchFieldConfig,
|
||||
previous: TableProSearchFieldConfig | undefined,
|
||||
) {
|
||||
if (!previous || previous.type !== field.type) return false
|
||||
|
||||
if (!previous.type && !field.type)
|
||||
return !!previous.options === !!field.options
|
||||
|
||||
return (
|
||||
('multiple' in field && field.multiple === true) ===
|
||||
('multiple' in previous && previous.multiple === true)
|
||||
)
|
||||
}
|
||||
|
||||
export function normalizeSearchValues(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
values: TableProSearchValues,
|
||||
): TableProSearchValues {
|
||||
return Object.fromEntries(
|
||||
fields.flatMap((field) => {
|
||||
if (!isSearchFieldVisible(field, values)) return []
|
||||
|
||||
const raw = sanitizeValue(field, values[field.key])
|
||||
const value =
|
||||
(!field.type || field.type === 'text') && typeof raw === 'string'
|
||||
? raw.trim()
|
||||
: raw
|
||||
|
||||
return value == null ||
|
||||
value === '' ||
|
||||
(Array.isArray(value) && !value.length)
|
||||
? []
|
||||
: [[field.key, value] as const]
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export function toSearchParams(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
values: TableProSearchValues,
|
||||
) {
|
||||
const fieldsByKey = new Map(fields.map((field) => [field.key, field]))
|
||||
const params = Object.fromEntries(
|
||||
Object.entries(values).flatMap<[string, unknown]>(([key, value]) => {
|
||||
if (value == null) return []
|
||||
|
||||
const field = fieldsByKey.get(key)
|
||||
const transform = field?.type && field.transform
|
||||
|
||||
// 值已由对应字段校验。遍历异构字段时,联合类型无法保留这层对应关系。
|
||||
return transform
|
||||
? Object.entries(transform(value as never, values))
|
||||
: [[key, value]]
|
||||
}),
|
||||
)
|
||||
|
||||
delete params.page
|
||||
delete params.pageSize
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
export function createSearchPredicate(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
values: TableProSearchValues,
|
||||
) {
|
||||
const fieldsByKey = new Map(fields.map((field) => [field.key, field]))
|
||||
const checks = Object.entries(values).flatMap(([key, value]) => {
|
||||
if (value == null) return []
|
||||
|
||||
const field = fieldsByKey.get(key)
|
||||
const read = (row: Row) =>
|
||||
field?.type && field.getValue ? field.getValue(row) : row[key]
|
||||
|
||||
return [
|
||||
(row: Row) => {
|
||||
const cell = read(row)
|
||||
|
||||
if (field?.type && field.matches)
|
||||
return field.matches(cell, value as never, row)
|
||||
|
||||
if (field?.type === 'dateRange' || field?.type === 'datetimeRange') {
|
||||
const [from, to] = value as readonly (string | number)[]
|
||||
|
||||
return (
|
||||
(typeof cell === 'string' || typeof cell === 'number') &&
|
||||
typeof cell === typeof from &&
|
||||
cell >= from &&
|
||||
cell <= to
|
||||
)
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return Array.isArray(cell)
|
||||
? cell.some((item: unknown) => value.includes(item))
|
||||
: value.includes(cell)
|
||||
}
|
||||
|
||||
return typeof value === 'string' &&
|
||||
(!field
|
||||
? true
|
||||
: field.type === 'text' || (!field.type && !field.options))
|
||||
? String(cell ?? '')
|
||||
.toLowerCase()
|
||||
.includes(value.toLowerCase())
|
||||
: cell === value
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
return checks.length
|
||||
? (row: Row) => checks.every((check) => check(row))
|
||||
: null
|
||||
}
|
||||
@ -1,5 +1,18 @@
|
||||
import type { BasicTarget } from '@ray-template/composables/types'
|
||||
import type { DataTableInst, DataTableProps, SelectOption } from 'naive-ui'
|
||||
import type {
|
||||
CascaderProps,
|
||||
DataTableInst,
|
||||
DataTableProps,
|
||||
DatePickerProps,
|
||||
FormItemRule,
|
||||
InputNumberProps,
|
||||
InputProps,
|
||||
SelectOption,
|
||||
SelectProps,
|
||||
TimePickerProps,
|
||||
TreeSelectProps,
|
||||
} from 'naive-ui'
|
||||
import type { VNodeChild } from 'vue'
|
||||
import type { LeafColumn } from './columns'
|
||||
|
||||
export interface TableProPrintOptions {
|
||||
@ -43,12 +56,164 @@ export type TableProRequest = (
|
||||
signal: AbortSignal,
|
||||
) => Promise<TableProResult>
|
||||
|
||||
type SearchKey = string | number
|
||||
|
||||
export type TableProSearchValue = SearchKey | boolean | readonly SearchKey[]
|
||||
export type TableProSearchValues = Readonly<
|
||||
Record<string, TableProSearchValue | null | undefined>
|
||||
>
|
||||
|
||||
export type TableProSearchField = {
|
||||
type?: undefined
|
||||
key: string
|
||||
label: string
|
||||
placeholder?: string
|
||||
options?: SelectOption[]
|
||||
}
|
||||
|
||||
export type TableSearchValues = Record<string, string | number>
|
||||
type SearchFieldBase<Value extends TableProSearchValue> = {
|
||||
key: string
|
||||
label: string
|
||||
placeholder?: string
|
||||
initialValue?: Value | null
|
||||
span?: number
|
||||
rules?: FormItemRule | FormItemRule[]
|
||||
visible?: (values: TableProSearchValues) => boolean
|
||||
dependsOn?: readonly string[]
|
||||
transform?: (
|
||||
value: Value,
|
||||
values: TableProSearchValues,
|
||||
) => Record<string, unknown>
|
||||
getValue?: (row: Readonly<Record<string, unknown>>) => unknown
|
||||
matches?: (
|
||||
cell: unknown,
|
||||
value: Value,
|
||||
row: Readonly<Record<string, unknown>>,
|
||||
) => boolean
|
||||
}
|
||||
|
||||
type BindingProps =
|
||||
'value' | 'defaultValue' | 'onUpdateValue' | 'onUpdate:value'
|
||||
type SearchControlProps<Props, Managed extends keyof Props = never> = Omit<
|
||||
Props,
|
||||
BindingProps | Managed
|
||||
>
|
||||
type SearchField<
|
||||
Type,
|
||||
Value extends TableProSearchValue,
|
||||
Props,
|
||||
> = SearchFieldBase<Value> & { type: Type; fieldProps?: Props }
|
||||
|
||||
type SearchSelectField =
|
||||
| (SearchField<'select', SearchKey, SearchSelectProps> & { multiple?: false })
|
||||
| (SearchField<'select', readonly SearchKey[], SearchSelectProps> & {
|
||||
multiple: true
|
||||
})
|
||||
|
||||
type SearchSelectProps = SearchControlProps<SelectProps, 'multiple' | 'options'>
|
||||
|
||||
export interface TableProSearchOptionContext {
|
||||
keyword: string
|
||||
values: TableProSearchValues
|
||||
signal: AbortSignal
|
||||
}
|
||||
|
||||
type DateFieldProps = SearchControlProps<
|
||||
DatePickerProps,
|
||||
| 'type'
|
||||
| 'formattedValue'
|
||||
| 'defaultFormattedValue'
|
||||
| 'valueFormat'
|
||||
| 'onUpdateFormattedValue'
|
||||
| 'onUpdate:formattedValue'
|
||||
>
|
||||
|
||||
type TreeField<Type, Props> =
|
||||
| (SearchField<Type, SearchKey, Props> & { multiple?: false })
|
||||
| (SearchField<Type, readonly SearchKey[], Props> & { multiple: true })
|
||||
|
||||
export type TableProSearchFieldConfig =
|
||||
| TableProSearchField
|
||||
| SearchField<'text', string, SearchControlProps<InputProps, 'pair'>>
|
||||
| SearchField<'number', number, SearchControlProps<InputNumberProps>>
|
||||
| SearchField<'boolean', boolean, SearchSelectProps>
|
||||
| (SearchSelectField & {
|
||||
options?: SelectProps['options']
|
||||
loadOptions?: (
|
||||
context: TableProSearchOptionContext,
|
||||
) => Promise<NonNullable<SelectProps['options']>>
|
||||
optionDebounce?: number
|
||||
})
|
||||
| SearchField<'date', string, DateFieldProps>
|
||||
| SearchField<'dateRange', readonly [string, string], DateFieldProps>
|
||||
| SearchField<'datetime', number, DateFieldProps>
|
||||
| SearchField<'datetimeRange', readonly [number, number], DateFieldProps>
|
||||
| SearchField<
|
||||
'time',
|
||||
string,
|
||||
SearchControlProps<
|
||||
TimePickerProps,
|
||||
| 'formattedValue'
|
||||
| 'defaultFormattedValue'
|
||||
| 'valueFormat'
|
||||
| 'onUpdateFormattedValue'
|
||||
| 'onUpdate:formattedValue'
|
||||
>
|
||||
>
|
||||
| TreeField<'cascader', SearchControlProps<CascaderProps, 'multiple'>>
|
||||
| TreeField<'treeSelect', SearchControlProps<TreeSelectProps, 'multiple'>>
|
||||
| (SearchFieldBase<TableProSearchValue> & {
|
||||
type: 'custom'
|
||||
render: (context: {
|
||||
value: TableProSearchValue | null
|
||||
setValue: (value: TableProSearchValue | null) => void
|
||||
values: TableProSearchValues
|
||||
inputId: string
|
||||
labelId: string
|
||||
}) => VNodeChild
|
||||
})
|
||||
|
||||
type ColumnSearchField<Field = TableProSearchFieldConfig> =
|
||||
Field extends TableProSearchFieldConfig
|
||||
? Omit<Field, 'key' | 'label'> & Partial<Pick<Field, 'key' | 'label'>>
|
||||
: never
|
||||
|
||||
export type TableProColumn = NonNullable<DataTableProps['columns']>[number] & {
|
||||
search?: boolean | ColumnSearchField
|
||||
children?: TableProColumn[]
|
||||
}
|
||||
|
||||
export interface TableProSearchSubmission {
|
||||
values: TableProSearchValues
|
||||
params: Readonly<Record<string, unknown>>
|
||||
reason: 'submit' | 'reset'
|
||||
}
|
||||
|
||||
export interface TableProSearchActions {
|
||||
submit: () => Promise<boolean>
|
||||
reset: () => Promise<boolean>
|
||||
collapsed: boolean
|
||||
canCollapse: boolean
|
||||
setCollapsed: (value: boolean) => void
|
||||
defaultActions: VNodeChild
|
||||
}
|
||||
|
||||
export interface TableProSearchOptions {
|
||||
fields?: readonly TableProSearchFieldConfig[]
|
||||
initialValues?: TableProSearchValues
|
||||
defaultCollapsed?: boolean
|
||||
collapsedRows?: number
|
||||
maxColumns?: number
|
||||
labelPlacement?: 'left' | 'top'
|
||||
labelWidth?: number | 'auto'
|
||||
searchText?: string
|
||||
resetText?: string
|
||||
submitMode?: 'manual' | 'change'
|
||||
debounce?: number
|
||||
renderActions?: (actions: TableProSearchActions) => VNodeChild
|
||||
}
|
||||
|
||||
export type TableProSearchConfig =
|
||||
false | readonly TableProSearchFieldConfig[] | TableProSearchOptions
|
||||
|
||||
export type PropsComponentPopselectKeys = 'striped' | 'bordered'
|
||||
|
||||
@ -35,6 +35,10 @@ export const useTablePro = () => {
|
||||
reload: (resetPage) => getTableProInstance().reload(resetPage),
|
||||
setPage: (page) => getTableProInstance().setPage(page),
|
||||
setPageSize: (pageSize) => getTableProInstance().setPageSize(pageSize),
|
||||
getSearchValues: (source) => getTableProInstance().getSearchValues(source),
|
||||
setSearchValues: (values) => getTableProInstance().setSearchValues(values),
|
||||
submitSearch: () => getTableProInstance().submitSearch(),
|
||||
resetSearch: () => getTableProInstance().resetSearch(),
|
||||
getCurrentPageData: () => getTableProInstance().getCurrentPageData(),
|
||||
getTableInstance: () => getTableProInstance().getTableInstance(),
|
||||
print: (options) => getTableProInstance().print(options),
|
||||
|
||||
100
packages/ui/src/RTablePro/src/useTableSearch.ts
Normal file
100
packages/ui/src/RTablePro/src/useTableSearch.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { onScopeDispose, shallowRef, watch } from 'vue'
|
||||
import {
|
||||
copySearchValues,
|
||||
initialSearchValues,
|
||||
normalizeSearchValues,
|
||||
patchSearchValues,
|
||||
pickSearchValues,
|
||||
} from './search'
|
||||
import type {
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchOptions,
|
||||
TableProSearchSubmission,
|
||||
TableProSearchValues,
|
||||
} from './types'
|
||||
|
||||
export function useTableSearch(
|
||||
fields: () => readonly TableProSearchFieldConfig[],
|
||||
options: () => TableProSearchOptions | undefined,
|
||||
validate: (isCurrent: () => boolean) => true | Promise<boolean>,
|
||||
restoreValidation: () => void,
|
||||
commit: (
|
||||
values: TableProSearchValues,
|
||||
reason: TableProSearchSubmission['reason'],
|
||||
) => Promise<boolean>,
|
||||
) {
|
||||
const draft = shallowRef<TableProSearchValues>(
|
||||
initialSearchValues(fields(), options()),
|
||||
)
|
||||
let revision = 0
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const cancelPending = () => {
|
||||
clearTimeout(timer)
|
||||
revision += 1
|
||||
}
|
||||
|
||||
watch(
|
||||
() => options()?.submitMode,
|
||||
(mode) => {
|
||||
if (mode !== 'change') cancelPending()
|
||||
},
|
||||
)
|
||||
|
||||
const submit = async () => {
|
||||
cancelPending()
|
||||
const current = revision
|
||||
const values = normalizeSearchValues(fields(), draft.value)
|
||||
|
||||
const isCurrent = () => current === revision
|
||||
const validation = validate(isCurrent)
|
||||
|
||||
if (validation !== true && !(await validation)) return false
|
||||
|
||||
if (!isCurrent()) return false
|
||||
|
||||
return commit(values, 'submit')
|
||||
}
|
||||
|
||||
const setValues = (values: TableProSearchValues) => {
|
||||
const next = patchSearchValues(fields(), draft.value, values)
|
||||
|
||||
if (next === draft.value) return
|
||||
|
||||
cancelPending()
|
||||
draft.value = next
|
||||
|
||||
if (options()?.submitMode === 'change') {
|
||||
timer = setTimeout(() => void submit(), options()?.debounce ?? 300)
|
||||
}
|
||||
}
|
||||
|
||||
const reset = () => {
|
||||
cancelPending()
|
||||
draft.value = initialSearchValues(fields(), options())
|
||||
restoreValidation()
|
||||
|
||||
return commit(normalizeSearchValues(fields(), draft.value), 'reset')
|
||||
}
|
||||
|
||||
const reconcile = (retainedKeys: ReadonlySet<string>) => {
|
||||
cancelPending()
|
||||
const defaults = initialSearchValues(fields(), options())
|
||||
const retained = Object.fromEntries(
|
||||
Object.entries(draft.value).filter(([key]) => retainedKeys.has(key)),
|
||||
)
|
||||
|
||||
draft.value = pickSearchValues(fields(), { ...defaults, ...retained })
|
||||
}
|
||||
|
||||
onScopeDispose(cancelPending)
|
||||
|
||||
return {
|
||||
draft,
|
||||
getValues: () => copySearchValues(draft.value),
|
||||
setValues,
|
||||
submit,
|
||||
reset,
|
||||
reconcile,
|
||||
}
|
||||
}
|
||||
@ -11,6 +11,12 @@
|
||||
"emailHint": "输入邮箱关键词",
|
||||
"reset": "重置",
|
||||
"search": "查询",
|
||||
"expandSearch": "展开筛选",
|
||||
"collapseSearch": "收起筛选",
|
||||
"searchYes": "是",
|
||||
"searchNo": "否",
|
||||
"searchError": "无法生成查询条件",
|
||||
"searchOptionsError": "选项加载失败",
|
||||
"reload": "刷新",
|
||||
"csv": "导出 CSV",
|
||||
"print": "打印表格",
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user