mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-11-17 16:13:36 +08:00
fix(table-pro): harden queries and table interactions
This commit is contained in:
parent
bb925eea6c
commit
bb8a49ae1a
@ -5,7 +5,7 @@ import { NDataTable, NTree } from 'naive-ui'
|
||||
import type { DataTableColumn } from 'naive-ui'
|
||||
import { effectScope, nextTick, ref, shallowRef } from 'vue'
|
||||
import { useColumnVisibility } from '../../packages/ui/src/RTablePro/src/columns'
|
||||
import ColumnSettings from '../../packages/ui/src/RTablePro/src/components/C'
|
||||
import ColumnSettings from '../../packages/ui/src/RTablePro/src/components/ColumnSettings'
|
||||
|
||||
const name = { key: 'name', title: 'Name' }
|
||||
const email = { key: 'email', title: 'Email' }
|
||||
@ -209,3 +209,49 @@ it('lets v-model own the full column definitions without removing hidden columns
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('offers keyboard-operable column ordering and resets layout without revealing hidden columns', async () => {
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns: [selection, { ...name, width: 100 }, email, region],
|
||||
columnStateKey: 'keyboard',
|
||||
},
|
||||
global: { stubs: { teleport: true } },
|
||||
})
|
||||
|
||||
try {
|
||||
const settings = wrapper.getComponent(ColumnSettings)
|
||||
const native = wrapper.getComponent(NDataTable)
|
||||
|
||||
await settings.get('button').trigger('click')
|
||||
const move = wrapper.get('button[aria-label="Move Email up"]')
|
||||
|
||||
expect(move.attributes('type')).toBe('button')
|
||||
await move.trigger('click')
|
||||
settings.vm.$emit('patchColumn', 'name', { fixed: 'left', resizable: true })
|
||||
settings.vm.$emit('toggleColumn', 'region', false)
|
||||
await nextTick()
|
||||
expect(native.props('columns')).toEqual([
|
||||
selection,
|
||||
email,
|
||||
{ ...name, width: 100, fixed: 'left', resizable: true },
|
||||
])
|
||||
|
||||
const reset = wrapper
|
||||
.findAll('button')
|
||||
.find((button) => button.text() === 'Reset column layout')
|
||||
|
||||
expect(reset).toBeDefined()
|
||||
await reset!.trigger('click')
|
||||
expect(native.props('columns')).toEqual([
|
||||
selection,
|
||||
{ ...name, width: 100 },
|
||||
email,
|
||||
])
|
||||
expect(JSON.parse(localStorage.getItem(cacheKey('keyboard'))!)).toEqual([
|
||||
'region',
|
||||
])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { RTablePro } from '@/components/RTablePro'
|
||||
import type { TableProInst } from '@/components/RTablePro'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import type { DataTableColumn } from 'naive-ui'
|
||||
import { buildTableCsv } from '../../packages/ui/src/RTablePro/src/csv'
|
||||
import * as printing from '../../packages/ui/src/RTablePro/src/printing'
|
||||
@ -97,3 +97,111 @@ it('exports group children with correct CSV escaping and neutralizes formula tex
|
||||
'"Name","Note","Score"\r\n"A, ""B""","\'=2+2","-2"\r\n"Array value","\'=2+2,text","-2"',
|
||||
)
|
||||
})
|
||||
|
||||
it('copies current form values into custom print content without copying credentials', () => {
|
||||
const target = document.createElement('section')
|
||||
|
||||
target.innerHTML =
|
||||
'<input value="default"><input type="checkbox"><textarea>old</textarea><select><option>A</option><option>B</option></select><input type="password" value="placeholder">'
|
||||
target.querySelector('input')!.value = 'edited'
|
||||
target.querySelector<HTMLInputElement>('[type="checkbox"]')!.checked = true
|
||||
target.querySelector('textarea')!.value = 'new'
|
||||
target.querySelector('select')!.value = 'B'
|
||||
target.querySelector<HTMLInputElement>('[type="password"]')!.value = 'private'
|
||||
|
||||
const clone = printing.resolvePrintContent({ target }, () => null)!
|
||||
|
||||
expect(clone.querySelector('input')?.value).toBe('edited')
|
||||
expect(
|
||||
clone.querySelector<HTMLInputElement>('[type="checkbox"]')?.checked,
|
||||
).toBe(true)
|
||||
expect(clone.querySelector('textarea')?.value).toBe('new')
|
||||
expect(clone.querySelector('select')?.value).toBe('B')
|
||||
expect(
|
||||
clone.querySelector<HTMLInputElement>('[type="password"]')?.value,
|
||||
).toBe('')
|
||||
expect(
|
||||
target.querySelector<HTMLInputElement>('[type="password"]')?.value,
|
||||
).toBe('private')
|
||||
})
|
||||
|
||||
it('shares page styles with a custom print frame and removes it after printing', async () => {
|
||||
const target = document.createElement('section')
|
||||
const stylesheet = document.createElement('style')
|
||||
|
||||
target.className = 'print-fixture'
|
||||
stylesheet.textContent = '.print-fixture { color: rebeccapurple; }'
|
||||
document.head.append(stylesheet)
|
||||
const append = document.body.append.bind(document.body)
|
||||
|
||||
vi.spyOn(document.body, 'append').mockImplementation((...nodes) => {
|
||||
for (const node of nodes)
|
||||
if (node instanceof HTMLIFrameElement) node.srcdoc = '<!doctype html>'
|
||||
|
||||
append(...nodes)
|
||||
})
|
||||
|
||||
const printDocument = document.implementation.createHTMLDocument()
|
||||
const printWindow = Object.assign(new EventTarget(), {
|
||||
focus: vi.fn(),
|
||||
print: vi.fn(() => {
|
||||
expect(document.querySelector('iframe')).not.toBeNull()
|
||||
expect(printDocument.head.textContent).toContain('rebeccapurple')
|
||||
printWindow.dispatchEvent(new Event('afterprint'))
|
||||
}),
|
||||
})
|
||||
|
||||
vi.spyOn(HTMLIFrameElement.prototype, 'contentWindow', 'get').mockReturnValue(
|
||||
printWindow as unknown as Window,
|
||||
)
|
||||
vi.spyOn(
|
||||
HTMLIFrameElement.prototype,
|
||||
'contentDocument',
|
||||
'get',
|
||||
).mockReturnValue(printDocument)
|
||||
|
||||
try {
|
||||
expect(
|
||||
await printing.printTableContent(target.cloneNode(true) as HTMLElement, {
|
||||
target,
|
||||
}),
|
||||
).toBe(true)
|
||||
expect(printWindow.print).toHaveBeenCalledOnce()
|
||||
expect(document.querySelector('iframe')).toBeNull()
|
||||
} finally {
|
||||
stylesheet.remove()
|
||||
document.querySelector('iframe')?.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels a print still preparing when the request scope changes', async () => {
|
||||
const print = vi.spyOn(printing, 'printTableContent').mockImplementation(
|
||||
(_content, _options, signal) =>
|
||||
new Promise((resolve) => {
|
||||
signal?.addEventListener('abort', () => resolve(false), { once: true })
|
||||
}),
|
||||
)
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns: [{ key: 'name', title: 'Name' }],
|
||||
params: { account: 'a' },
|
||||
request: async ({ account }) => ({
|
||||
data: [{ id: 1, name: account }],
|
||||
total: 1,
|
||||
}),
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
const table = wrapper.vm as unknown as TableProInst
|
||||
const preview = table.print()
|
||||
|
||||
expect(print).toHaveBeenCalledOnce()
|
||||
await wrapper.setProps({ params: { account: 'b' } })
|
||||
expect(print.mock.calls[0][2]?.aborted).toBe(true)
|
||||
expect(await preview).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
@ -646,3 +646,172 @@ it('does not reload when rendering a new pagination object with the same paging
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('notifies the owner when search, reset, and instance methods change controlled paging', async () => {
|
||||
const [register, table] = useTablePro()
|
||||
const pager = { page: 2, pageSize: 1 }
|
||||
const pagination = () => ({
|
||||
...pager,
|
||||
'onUpdate:page': updatePage,
|
||||
'onUpdate:pageSize': updatePageSize,
|
||||
})
|
||||
const updatePage = vi.fn((page: number) => {
|
||||
pager.page = page
|
||||
void wrapper.setProps({ pagination: pagination() })
|
||||
})
|
||||
const updatePageSize = vi.fn((pageSize: number) => {
|
||||
pager.pageSize = pageSize
|
||||
void wrapper.setProps({ pagination: pagination() })
|
||||
})
|
||||
const search: TableProSearchOptions = {
|
||||
fields: [{ type: 'text', key: 'name', label: 'Name' }],
|
||||
}
|
||||
const data = [
|
||||
{ id: 1, name: 'Ray' },
|
||||
{ id: 2, name: 'Ray 2' },
|
||||
{ id: 3, name: 'Other' },
|
||||
]
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns,
|
||||
data,
|
||||
search,
|
||||
tool: false,
|
||||
onRegister: register,
|
||||
pagination: pagination(),
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
table.setSearchValues({ name: 'Ray' })
|
||||
expect(await table.submitSearch()).toBe(true)
|
||||
expect(table.getCurrentPageData()).toEqual([data[0]])
|
||||
await table.setPage(2)
|
||||
expect(table.getCurrentPageData()).toEqual([data[1]])
|
||||
await table.setPageSize(2)
|
||||
expect(table.getCurrentPageData()).toEqual(data.slice(0, 2))
|
||||
await table.setPage(2)
|
||||
await table.resetSearch()
|
||||
expect(updatePage.mock.calls.flat()).toEqual([1, 2, 1, 2, 1])
|
||||
expect(updatePageSize).toHaveBeenCalledExactlyOnceWith(2)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('rebuilds a local search when a compatible field changes its matcher', async () => {
|
||||
const makeSearch = (matches: () => boolean): TableProSearchOptions => ({
|
||||
fields: [{ type: 'text', key: 'name', label: 'Name', matches }],
|
||||
initialValues: { name: 'Ray' },
|
||||
})
|
||||
const data = [{ id: 1, name: 'Ray' }]
|
||||
const [register, table] = useTablePro()
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns,
|
||||
data,
|
||||
search: makeSearch(() => true),
|
||||
tool: false,
|
||||
onRegister: register,
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
expect(table.getCurrentPageData()).toEqual(data)
|
||||
await wrapper.setProps({ search: makeSearch(() => false) })
|
||||
expect(table.getSearchValues('applied')).toEqual({ name: 'Ray' })
|
||||
expect(table.getCurrentPageData()).toEqual([])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('reports visibility and row callback errors while preserving the last applied local query', async () => {
|
||||
const visibility = new Error('Visibility failed')
|
||||
const matcher = new Error('Matcher failed')
|
||||
const search: TableProSearchOptions = {
|
||||
fields: [
|
||||
{
|
||||
type: 'text',
|
||||
key: 'name',
|
||||
label: 'Name',
|
||||
visible: (values) => {
|
||||
if (values.name === 'hidden') throw visibility
|
||||
|
||||
return true
|
||||
},
|
||||
matches: (cell, value) => {
|
||||
if (value === 'error') throw matcher
|
||||
|
||||
return cell === value
|
||||
},
|
||||
},
|
||||
],
|
||||
initialValues: { name: 'Ray' },
|
||||
}
|
||||
const data = [
|
||||
{ id: 1, name: 'Ray' },
|
||||
{ id: 2, name: 'Other' },
|
||||
]
|
||||
const [register, table] = useTablePro()
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: { columns, data, search, tool: false, onRegister: register },
|
||||
})
|
||||
|
||||
try {
|
||||
for (const value of ['hidden', 'error']) {
|
||||
table.setSearchValues({ name: value })
|
||||
expect(await table.submitSearch()).toBe(false)
|
||||
await nextTick()
|
||||
expect(table.getCurrentPageData()).toEqual([data[0]])
|
||||
expect(table.getSearchValues('applied')).toEqual({ name: 'Ray' })
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain("Couldn't prepare")
|
||||
}
|
||||
|
||||
expect(wrapper.emitted('search-error')).toEqual([[visibility], [matcher]])
|
||||
table.setSearchValues({ name: 'Other' })
|
||||
expect(await table.submitSearch()).toBe(true)
|
||||
await nextTick()
|
||||
expect(table.getCurrentPageData()).toEqual([data[1]])
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('reads nested column paths and preserves an explicit search value reader', async () => {
|
||||
const data = [
|
||||
{ id: 1, customer: { name: 'Ray' }, nickname: 'Alias' },
|
||||
{ id: 2, customer: { name: 'Another' }, nickname: 'Ray' },
|
||||
]
|
||||
const [register, table] = useTablePro()
|
||||
const search: TableProSearchOptions = {
|
||||
fields: [
|
||||
{ type: 'text', key: 'customer.name', label: 'Customer' },
|
||||
{
|
||||
type: 'text',
|
||||
key: 'alias',
|
||||
label: 'Alias',
|
||||
getValue: (row) => row.nickname,
|
||||
},
|
||||
],
|
||||
}
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns: [{ key: 'customer.name', title: 'Customer' }],
|
||||
data,
|
||||
search,
|
||||
tool: false,
|
||||
onRegister: register,
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
table.setSearchValues({ 'customer.name': 'ray', alias: 'alias' })
|
||||
expect(await table.submitSearch()).toBe(true)
|
||||
await nextTick()
|
||||
expect(table.getCurrentPageData()).toEqual([data[0]])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
@ -4,8 +4,12 @@ import type {
|
||||
TableProParams,
|
||||
TableProResult,
|
||||
} from '@/components/RTablePro'
|
||||
import { provideUiServices } from '@ray-template/ui/services'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { NDataTable, NPagination } from 'naive-ui'
|
||||
import { NDataTable, NDropdown, NPagination } from 'naive-ui'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import Size from '../../packages/ui/src/RTablePro/src/components/Size'
|
||||
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
|
||||
|
||||
const columns = [{ title: 'Name', key: 'name' }]
|
||||
const response = (name: string, total = 30): TableProResult => ({
|
||||
@ -135,7 +139,7 @@ it('exposes read-only query state during load, failure and retry', async () => {
|
||||
.fn(() => retry.promise)
|
||||
.mockReturnValueOnce(initial.promise)
|
||||
.mockReturnValueOnce(failing.promise)
|
||||
const [register, { queryState, setPageSize }] = useTablePro()
|
||||
const [register, { queryState, reload, setPageSize }] = useTablePro()
|
||||
|
||||
expect(queryState.value).toBeNull()
|
||||
const wrapper = mount(RTablePro, {
|
||||
@ -170,18 +174,19 @@ it('exposes read-only query state during load, failure and retry', async () => {
|
||||
failed: true,
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
total: 42,
|
||||
total: null,
|
||||
})
|
||||
expect(wrapper.text()).toContain('Last successful result')
|
||||
expect(wrapper.text()).not.toContain('Last successful result')
|
||||
|
||||
const retrying = reload()
|
||||
|
||||
await wrapper.get('.n-alert button').trigger('click')
|
||||
expect(queryState.value).toMatchObject({
|
||||
loading: true,
|
||||
failed: false,
|
||||
total: 42,
|
||||
total: null,
|
||||
})
|
||||
retry.resolve(response('Recovered', 7))
|
||||
await flushPromises()
|
||||
await retrying
|
||||
expect(queryState.value).toMatchObject({
|
||||
loading: false,
|
||||
failed: false,
|
||||
@ -194,25 +199,119 @@ it('exposes read-only query state during load, failure and retry', async () => {
|
||||
expect(queryState.value).toBeNull()
|
||||
})
|
||||
|
||||
it('shows a retry for a failed request and omits paging fields when pagination is off', async () => {
|
||||
it('clears rows and blocks output while a different query scope loads or fails', async () => {
|
||||
const failed = Promise.withResolvers<TableProResult>()
|
||||
const request = vi
|
||||
.fn(async (_params: TableProParams) => response('Recovered', 1))
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
.fn(async (_params: TableProParams) => response('Account B'))
|
||||
.mockResolvedValueOnce(response('Account A'))
|
||||
.mockImplementationOnce(() => failed.promise)
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: { columns, request, pagination: false, tool: false },
|
||||
props: { columns, request, params: { account: { id: 'a' } } },
|
||||
})
|
||||
const table = wrapper.vm as unknown as TableProInst
|
||||
const download = vi
|
||||
.spyOn(csv, 'downloadTableCsv')
|
||||
.mockImplementation(() => {})
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
expect(wrapper.emitted('request-error')).toHaveLength(1)
|
||||
expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false)
|
||||
await wrapper.get('.n-alert button').trigger('click')
|
||||
expect(table.getCurrentPageData()).toEqual(response('Account A').data)
|
||||
await wrapper.setProps({ params: { account: { id: 'b' } } })
|
||||
|
||||
expect(table.queryState).toMatchObject({ loading: true, total: null })
|
||||
expect(table.getCurrentPageData()).toEqual([])
|
||||
expect(table.getTableInstance()).toBeNull()
|
||||
expect(wrapper.getComponent(NDataTable).props('data')).toEqual([])
|
||||
failed.reject(new Error('offline'))
|
||||
await flushPromises()
|
||||
|
||||
expect(table.queryState).toMatchObject({ failed: true, total: null })
|
||||
expect(wrapper.text()).not.toContain('Account A')
|
||||
expect(await table.print()).toBe(false)
|
||||
table.downloadCsv({ keepOriginalData: true })
|
||||
expect(download).not.toHaveBeenCalled()
|
||||
|
||||
await table.reload()
|
||||
expect(table.getCurrentPageData()).toEqual(response('Account B').data)
|
||||
table.downloadCsv()
|
||||
expect(download).toHaveBeenCalledExactlyOnceWith(
|
||||
'"Name"\r\n"Account B"',
|
||||
void 0,
|
||||
)
|
||||
} finally {
|
||||
download.mockRestore()
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('clears even same-query rows on failure and when the request source changes', async () => {
|
||||
const request = vi
|
||||
.fn(async (_params: TableProParams) => response('Previous source'))
|
||||
.mockResolvedValueOnce(response('Previous source'))
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
const replacement = vi.fn(async () => {
|
||||
throw new Error('new source offline')
|
||||
})
|
||||
const wrapper = mount(RTablePro, { props: { columns, request } })
|
||||
const table = wrapper.vm as unknown as TableProInst
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
await table.reload()
|
||||
expect(table.queryState).toMatchObject({ failed: true, total: null })
|
||||
expect(table.getCurrentPageData()).toEqual([])
|
||||
|
||||
await table.reload()
|
||||
expect(table.getCurrentPageData()).toEqual(response('Previous source').data)
|
||||
await wrapper.setProps({ request: replacement })
|
||||
await flushPromises()
|
||||
expect(table.queryState).toMatchObject({ failed: true, total: null })
|
||||
expect(table.getCurrentPageData()).toEqual([])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows a toast and the normal empty state without an inline alert, then allows retry', async () => {
|
||||
const request = vi
|
||||
.fn(async (_params: TableProParams) => response('Recovered', 1))
|
||||
.mockRejectedValueOnce(new Error('offline'))
|
||||
const reportError = vi.fn()
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
provideUiServices({ reportError })
|
||||
|
||||
return () =>
|
||||
h(
|
||||
RTablePro,
|
||||
{ columns, request, pagination: false, tool: false },
|
||||
{
|
||||
empty: () => 'Custom empty state',
|
||||
notice: () => 'Always visible notice',
|
||||
},
|
||||
)
|
||||
},
|
||||
}),
|
||||
)
|
||||
const table = wrapper.getComponent(RTablePro)
|
||||
const instance = table.vm as unknown as TableProInst
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
expect(table.emitted('request-error')).toHaveLength(1)
|
||||
expect(reportError).toHaveBeenCalledExactlyOnceWith(
|
||||
"Couldn't load the data",
|
||||
)
|
||||
expect(table.getComponent(NDataTable).props('pagination')).toBe(false)
|
||||
expect(table.text()).toContain('Custom empty state')
|
||||
expect(table.text()).toContain('Always visible notice')
|
||||
expect(table.find('.n-alert').exists()).toBe(false)
|
||||
await instance.reload()
|
||||
|
||||
expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}])
|
||||
expect(wrapper.find('.n-alert').exists()).toBe(false)
|
||||
expect(wrapper.text()).toContain('Recovered')
|
||||
expect((wrapper.vm as unknown as TableProInst).queryState).toEqual({
|
||||
expect(table.text()).toContain('Recovered')
|
||||
expect(instance.queryState).toEqual({
|
||||
loading: false,
|
||||
failed: false,
|
||||
page: null,
|
||||
@ -267,6 +366,7 @@ it('renders bare data without a toolbar or pagination by default', () => {
|
||||
expect(wrapper.text()).toContain('Bare row')
|
||||
expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false)
|
||||
expect(wrapper.find('header').exists()).toBe(false)
|
||||
expect(wrapper.classes()).not.toContain('r-table--card')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
@ -451,3 +551,97 @@ it('supports an optional title slot for actions without putting controls inside
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('provides the row that opened the context menu and discards it after data changes', async () => {
|
||||
const row = { id: 7, name: 'Alice' }
|
||||
const option = { key: 'edit', label: 'Edit' }
|
||||
const select = vi.fn()
|
||||
const onContextmenu = vi.fn((event: MouseEvent) => event.preventDefault())
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns,
|
||||
data: [row],
|
||||
tool: false,
|
||||
rowProps: () => ({ onContextmenu }),
|
||||
contextMenuOptions: [option],
|
||||
onContextMenuClick: select,
|
||||
},
|
||||
global: { stubs: { teleport: true } },
|
||||
})
|
||||
const menu = wrapper.getComponent(NDropdown)
|
||||
|
||||
try {
|
||||
const entry = wrapper.get('tbody tr')
|
||||
|
||||
await entry.trigger('contextmenu')
|
||||
expect(onContextmenu).toHaveBeenCalledOnce()
|
||||
expect(menu.props('show')).toBe(false)
|
||||
|
||||
expect(entry.attributes('tabindex')).toBe('0')
|
||||
await entry.trigger('keydown', { key: 'F10', shiftKey: true })
|
||||
expect(menu.props('show')).toBe(true)
|
||||
await wrapper.get('.n-dropdown-option-body').trigger('click')
|
||||
expect(select).toHaveBeenCalledExactlyOnceWith('edit', option, {
|
||||
row,
|
||||
index: 0,
|
||||
})
|
||||
|
||||
await entry.trigger('keydown', { key: 'ContextMenu' })
|
||||
expect(menu.props('show')).toBe(true)
|
||||
await wrapper.setProps({ data: [{ id: 8, name: 'Ray' }] })
|
||||
expect(menu.props('show')).toBe(false)
|
||||
const closingOption = wrapper.find('.n-dropdown-option-body')
|
||||
|
||||
if (closingOption.exists()) await closingOption.trigger('click')
|
||||
|
||||
expect(select).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps panel props and slots out of the native table while forwarding its own API', () => {
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns,
|
||||
tool: false,
|
||||
title: 'Panel title',
|
||||
scrollX: 640,
|
||||
columnStateKey: 'directory',
|
||||
},
|
||||
attrs: { id: 'directory' },
|
||||
slots: { empty: 'Native empty slot', tableFooter: 'Panel footer' },
|
||||
})
|
||||
|
||||
try {
|
||||
const native = wrapper.getComponent(NDataTable)
|
||||
|
||||
expect(wrapper.attributes('id')).toBe('directory')
|
||||
expect(wrapper.classes()).toContain('r-table--card')
|
||||
expect(native.props('scrollX')).toBe(640)
|
||||
expect(native.attributes('columnstatekey')).toBeUndefined()
|
||||
expect(native.attributes('id')).toBeUndefined()
|
||||
expect(native.text()).toContain('Native empty slot')
|
||||
expect(native.text()).not.toContain('Panel footer')
|
||||
expect(wrapper.get('.r-table__footer').text()).toBe('Panel footer')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('respects a changed density prop without reviving an earlier local choice', async () => {
|
||||
const wrapper = mount(RTablePro, { props: { columns, size: 'medium' } })
|
||||
const native = wrapper.getComponent(NDataTable)
|
||||
|
||||
try {
|
||||
wrapper.getComponent(Size).vm.$emit('change', 'small')
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(native.props('size')).toBe('small')
|
||||
await wrapper.setProps({ size: 'large' })
|
||||
expect(native.props('size')).toBe('large')
|
||||
await wrapper.setProps({ size: 'medium' })
|
||||
expect(native.props('size')).toBe('medium')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
@ -25,7 +25,9 @@ export default defineComponent({
|
||||
v-model:checkedRowKeys={selected.value}
|
||||
scrollX={944}
|
||||
contextMenuOptions={[{ label: t('contextAction'), key: 'example' }]}
|
||||
onContextMenuClick={() => window.$message?.info(t('contextAction'))}
|
||||
onContextMenuClick={(_key, _option, { row }) =>
|
||||
window.$message?.info(`${t('contextAction')}: ${row.name}`)
|
||||
}
|
||||
>
|
||||
{{
|
||||
filters: ({
|
||||
|
||||
6
apps/admin/src/views/demo/tables/printing.scss
Normal file
6
apps/admin/src/views/demo/tables/printing.scss
Normal file
@ -0,0 +1,6 @@
|
||||
.demo-print-summary {
|
||||
padding: 12pt;
|
||||
border: 1px solid var(--r-control-border, ButtonBorder);
|
||||
border-radius: var(--r-control-radius, 4px);
|
||||
break-inside: avoid;
|
||||
}
|
||||
@ -1,3 +1,4 @@
|
||||
import './printing.scss'
|
||||
import { RTablePro } from '@/components'
|
||||
import type { TableProInst } from '@/components'
|
||||
import { listPeople } from '@/demo-data/people'
|
||||
@ -33,8 +34,6 @@ export default defineComponent({
|
||||
table.value?.print({
|
||||
target: summary,
|
||||
title: t('printSummary'),
|
||||
style:
|
||||
'.demo-print-summary { border: 1px solid #b7bec6; padding: 12pt; }',
|
||||
})
|
||||
}
|
||||
>
|
||||
|
||||
@ -48,10 +48,10 @@ const renderRemote = () => (
|
||||
)
|
||||
```
|
||||
|
||||
- 远端 `request(params, signal)` 返回 `Promise<{ data, total }>`。组件只采用最新请求结果;失败保留旧数据并提供重试。要中止底层 HTTP,请把 signal 交给请求客户端。
|
||||
- 远端 `request(params, signal)` 返回 `Promise<{ data, total }>`。组件只采用最新请求结果;切换请求源或筛选范围时清空旧行和总数,切页或修改每页条数时隐藏旧行。没有当前页结果时,实例取数为空、CSV 和打印不可用。请求失败时清空行与总数,沿用空态,并通过宿主 Toast 提醒;调用方可用实例 `reload()` 重试。要中止底层 HTTP,请把 signal 交给请求客户端。
|
||||
- 搜索提交回到第 1 页。外部筛选用 `params`,复杂表单可从 `filters` 插槽调用 `submit(values)`。服务端排序和过滤由调用方将事件值映射进 `params`。
|
||||
- 默认每页 10 条;用 `pageSize`、`pagination.pageSizes` 调整,或传 `pagination={false}` 关闭。关闭时不添加分页字段;`bare pagination` 可单独开启分页。
|
||||
- 初始页用 `pagination.defaultPage`。远端模式下组件管理当前页、每页条数和总数;调用方已有自己的远端控制时可传 `remote + data + pagination`。
|
||||
- 初始页用 `pagination.defaultPage`。远端模式下组件管理当前页、每页条数和总数;调用方已有自己的远端控制时可传 `remote + data + pagination`,并自行处理范围切换。受控分页由调用方在回调中更新页码和每页条数;搜索重置和实例操作都触发对应回调。
|
||||
|
||||
## 高级搜索
|
||||
|
||||
@ -62,7 +62,7 @@ const renderRemote = () => (
|
||||
- **交付与金额**填入商品级联、仓库树、最低金额、开票状态、自定义配送方式和交付时间。应用后展开匹配订单核对交付信息,留意请求中保留了 `minAmount: 0` 与 `invoiced: false`。
|
||||
- **试试校验**提交一个字符的关键词,查看校验提示及保留的列表。修正输入后,可以切换「输入后自动应用」,快速连续编辑并观察列表请求。
|
||||
|
||||
在「最近请求」里还能让负责人或列表请求失败一次,再用对应的内置「重试」恢复。
|
||||
在「最近请求」里还能让负责人或列表请求失败一次。负责人选项使用字段下方的重试;列表失败显示空态,通过再次查询恢复。
|
||||
|
||||
<AdminExample path="/tables/search" title="组合筛选、组织联动与失败重试" :height="960" />
|
||||
|
||||
@ -90,7 +90,7 @@ const renderRemote = () => (
|
||||
|
||||
- `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`,保留上次条件。
|
||||
- `onSearch` 接收 `{ values, params, reason }`,`reason` 为 `submit` 或 `reset`。使用对象式 `search` 与 `remote + data + pagination` 时,可在事件中自行取数并控制页码和总数。搜索回调抛错会触发 `onSearchError`,并保留上次有效条件;本地默认字段读取支持 `customer.name` 等路径,`getValue` 优先。动态替换字段的匹配、读取、转换或可见规则时,仍兼容的条件会按新规则重新计算。
|
||||
- 实例和 `useTablePro()` 都提供 `getSearchValues('draft' | 'applied')`、`setSearchValues(patch)`、`submitSearch()`、`resetSearch()`。读取默认是草稿。提交和重置返回 `Promise<boolean>`,表示是否成功应用条件。设 `submitMode: 'change'` 可在编辑时防抖提交,`debounce` 默认 300 ms。
|
||||
|
||||
### 远程选项、联动和布局
|
||||
@ -150,11 +150,11 @@ SFC 使用 `<RTablePro @register="register" />`。每张表单独调用一次 Ho
|
||||
| `loading` | 当前请求是否正在执行。只反映 `request`,与外部 `loading` prop 无关。 |
|
||||
| `failed` | 当前请求是否失败。重试开始时清除;错误详情可通过 `onRequestError` 接收。 |
|
||||
| `page` / `pageSize` | 当前页码和每页条数;关闭分页时两者为 `null`。 |
|
||||
| `total` | 最近一次成功结果的筛选后总数。首次成功前为 `null`,刷新和失败期间保留上次的值。 |
|
||||
| `total` | 当前查询范围最近成功结果的筛选后总数。切换范围或请求失败后为 `null`,直至成功。 |
|
||||
|
||||
`queryState` 的值和字段均为只读。未挂载、已卸载、未传 `request`(包括手动远端模式)时,值为 `null`。被取消的旧请求不会覆盖当前查询状态。
|
||||
|
||||
`getCurrentPageData()` 返回当前页的行:本地表格已应用筛选、排序和分页,远端表格返回当前已加载的数据。返回的行用于读取,业务变更通过页面数据完成;虚拟滚动不会缩小取数范围。旧版 `runTableRequest` / `runAsyncTableRequest` 迁移到 `reload`,请求条件通过 `params` 或请求函数传入。
|
||||
`getCurrentPageData()` 返回当前页的行:本地表格已应用筛选、排序和分页,组件管理的远端表格只返回与当前查询和分页匹配的数据。返回的行用于读取,业务变更通过页面数据完成;虚拟滚动不会缩小取数范围。旧版 `runTableRequest` / `runAsyncTableRequest` 迁移到 `reload`,请求条件通过 `params` 或请求函数传入。
|
||||
|
||||
Ray Admin 的「表格」菜单下有三个可运行的完整示例:
|
||||
|
||||
@ -166,11 +166,11 @@ Ray Admin 的「表格」菜单下有三个可运行的完整示例:
|
||||
|
||||
## 列设置与缓存
|
||||
|
||||
每张表使用稳定且唯一的列 key。列设置可以勾选显示、调整根列顺序、固定或启用列宽调整;分组子列跟随根列。使用 `columnStateKey` 跨刷新保留隐藏列,按账户或租户隔离时将标识纳入 key。缓存不存数据、列定义、顺序、固定位置或列宽。调用方接管列配置可用 `v-model:columns`,返回包含隐藏列的完整定义。
|
||||
每张表使用稳定且唯一的列 key。列设置可以勾选显示、拖动或用上移与下移按钮调整根列顺序、固定或启用列宽调整;分组子列跟随根列。使用 `columnStateKey` 跨刷新保留隐藏列,按账户或租户隔离时将标识纳入 key。缓存不存数据、列定义、顺序、固定位置或列宽。调用方接管列配置可用 `v-model:columns`,返回包含隐藏列的完整定义。「恢复列布局」保留显隐;受控列由调用方通过 `onResetColumnLayout` 恢复自己的列定义。
|
||||
|
||||
## 打印与 CSV
|
||||
|
||||
默认取当前页可见数据列。打印按当前筛选和排序输出独立表格,不复刻 Vue 单元格、操作区、展开区或合并布局。报表等专用版式通过 `printTableOptions.target` 指定元素、ref 或 getter;单次调用可传 `title` 和专用 `style`。真实纸张输出由浏览器负责。
|
||||
默认取当前页可见数据列。打印按当前筛选和排序输出独立表格,不复刻 Vue 单元格、操作区、展开区或合并布局。报表等专用版式通过 `printTableOptions.target` 指定元素、ref 或 getter;默认复制宿主样式表、根节点主题和普通表单的当前值,也可设置 `includePageStyles: false`。单次调用可传 `title` 和专用 `style`。依赖区域外祖先、脚本或嵌入内容的区域需要专用打印 CSS;密码和文件值不会复制。真实纸张输出由浏览器负责。
|
||||
|
||||
CSV 的 `keepOriginalData` 使用当前传给表格的整批数据,远端模式不会自动抓取全部页。列级 `allowExport: false` 可排除数据;`getCsvCell` / `getCsvHeader` 返回原始文本,由组件做 CSV 转义。
|
||||
|
||||
@ -180,34 +180,35 @@ CSV 的 `keepOriginalData` 使用当前传给表格的整批数据,远端模
|
||||
|
||||
Naive UI DataTable 的列定义、选择、展开、加载、空态和虚拟滚动继续使用。下面列出模板层的配置与覆盖行为。
|
||||
|
||||
| 配置 | 默认 / 行为 |
|
||||
| ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `bare` | 默认关。隐藏标题及工具栏,省略 `pagination` 时不分页;显式搜索、底部插槽仍可使用。 |
|
||||
| `autoHeight` | 默认关;开启时让内部 DataTable 使用 `flexHeight`,适合有可用高度的布局。 |
|
||||
| `tool` | 默认开,控制打印、密度、全屏、列设置和外观等内置工具。关掉仍可用自定义 `toolbar`。 |
|
||||
| `title` | 字符串或 VNode。存在 `title` 插槽时优先渲染插槽。 |
|
||||
| `pagination` | 普通模式缺省开,`false` 关闭;对象透传 Naive UI Pagination。容器小于 600px 时默认简洁模式,显式 `simple` 优先。 |
|
||||
| `pageSize` | 默认 10;`pagination.pageSize`、`pagination.defaultPageSize` 依次优先。远端初始页读 `pagination.defaultPage`。 |
|
||||
| `request` / `params` | 配置 `request` 时组件管理远端数据。`params` 深层变化会从第 1 页重查。 |
|
||||
| `search` | 兼容原有字段数组,支持 `TableProSearchOptions` 和 `false`。见[高级搜索](#高级搜索)。 |
|
||||
| `rowKey` | 默认 `row.id ?? row.key`,业务数据缺少两者时必须提供稳定键。 |
|
||||
| `columnStateKey` | 缺省不持久化。传稳定标识可记住隐藏列。 |
|
||||
| `downloadCsvTableOptions` | 内置导出默认配置,模板实现使用 `fileName`、`keepOriginalData`。 |
|
||||
| `printTableOptions` | 打印配置,支持 `target`、`title`、`style`、`formatHeader`、`formatCell`。 |
|
||||
| `contextMenuOptions` / `onContextMenuClick` | 行右键菜单选项及选择回调 `(key, option)`;回调不直接收到行。先调用业务 `rowProps.onContextmenu`,可用 `preventDefault()` 阻止打开。 |
|
||||
| 配置 | 默认 / 行为 |
|
||||
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `bare` | 默认关。移除卡片外观并隐藏标题及工具栏,省略 `pagination` 时不分页;显式搜索、底部插槽仍可使用。 |
|
||||
| `autoHeight` | 默认关;开启时让内部 DataTable 使用 `flexHeight`,适合有可用高度的布局。 |
|
||||
| `tool` | 默认开,控制打印、密度、全屏、列设置和外观等内置工具。关掉仍可用自定义 `toolbar`。 |
|
||||
| `title` | 字符串或 VNode。存在 `title` 插槽时优先渲染插槽。 |
|
||||
| `pagination` | 普通模式缺省开,`false` 关闭;对象透传 Naive UI Pagination。容器小于 600px 时默认简洁模式,显式 `simple` 优先。 |
|
||||
| `pageSize` | 默认 10;`pagination.pageSize`、`pagination.defaultPageSize` 依次优先。远端初始页读 `pagination.defaultPage`。 |
|
||||
| `request` / `params` | 配置 `request` 时组件管理远端数据。`params` 深层变化会从第 1 页重查。 |
|
||||
| `search` | 兼容原有字段数组,支持 `TableProSearchOptions` 和 `false`。见[高级搜索](#高级搜索)。 |
|
||||
| `rowKey` | 默认 `row.id ?? row.key`,业务数据缺少两者时必须提供稳定键。 |
|
||||
| `columnStateKey` | 缺省不持久化。传稳定标识可记住隐藏列。 |
|
||||
| `downloadCsvTableOptions` | 内置导出默认配置,模板实现使用 `fileName`、`keepOriginalData`。 |
|
||||
| `onResetColumnLayout` | 受控列的恢复布局回调。调用方在回调里更新 `columns`。 |
|
||||
| `printTableOptions` | 打印配置,支持 `target`、`title`、`style`、`includePageStyles`、`formatHeader`、`formatCell`。 |
|
||||
| `contextMenuOptions` / `onContextMenuClick` | 行菜单选项及选择回调 `(key, option, { row, index })`。右键、Shift+F10 或菜单键打开;业务行事件可用 `preventDefault()` 阻止。 |
|
||||
|
||||
常用事件有 `onRequestError(error)`(或 SFC `@request-error`)、`onUpdatePage`、`onUpdatePageSize`、`onUpdate:columns`。内部分页先变更,再触发外部事件。行选择、排序等依然沿用 DataTable 事件;需要服务端排序时,将条件写入 `params`。
|
||||
常用事件有 `onRequestError(error)`(或 SFC `@request-error`)、`onUpdatePage`、`onUpdatePageSize`、`onUpdate:columns`。内部更新和受控回调走同一入口;已传入受控值时由调用方更新对应值。行选择、排序等依然沿用 DataTable 事件;需要服务端排序时,将条件写入 `params`。
|
||||
|
||||
| 插槽 | 参数与位置 |
|
||||
| ----------------------------- | ------------------------------------------------------------------------------------------------ |
|
||||
| `filters` | 表格上方;接收 `{ submit(values) }`,传入字符串或数字键值,提交后回第一页。优先于内置 `search`。 |
|
||||
| `title` / `toolbar` | 标题区左侧 / 操作区右侧;`bare` 下两者隐藏。 |
|
||||
| `notice` | 正常情况下显示自定义提示。 |
|
||||
| `error` | 请求失败时替换 `notice`,接收 `{ reload }`。未提供则显示错误和重试按钮。 |
|
||||
| `error` | 显式提供时在请求失败后替换 `notice`,接收 `{ reload }` 并接管默认 Toast。 |
|
||||
| `tableFooter` / `tableAction` | DataTable 之后的额外区域。 |
|
||||
| 其余插槽 | 转给 Naive UI DataTable,例如空态和加载。 |
|
||||
|
||||
`TableProInst` 的 `reload(resetPage?)`、`setPage(page)`、`setPageSize(size)` 返回 `Promise<void>`。请求错误由事件报告并保留旧数据;该 Promise 的完成不能用作业务成功判据。`getTableInstance()` 可能为 `null`;`print(options?)` 返回 `Promise<boolean>` 表示是否发起预览;`downloadCsv(options?)` 发起浏览器下载。
|
||||
`TableProInst` 的 `reload(resetPage?)`、`setPage(page)`、`setPageSize(size)` 返回 `Promise<void>`。请求错误由事件报告;该 Promise 的完成不能用作业务成功判据。`getTableInstance()` 可能为 `null`;`print(options?)` 返回 `Promise<boolean>` 表示是否发起预览;`downloadCsv(options?)` 发起浏览器下载。
|
||||
|
||||
远端请求将 `params` 与已提交筛选合并,后者覆盖同名项,页码字段最后由表格写入。关闭分页时也会删除传入的 `page` 和 `pageSize`。`total` 需要是非负安全整数,`data` 必须是数组。若筛选或删除数据后当前页超出范围,会收敛到最后一页,并在有结果时重查。
|
||||
|
||||
|
||||
45
docs/table-pro-review.md
Normal file
45
docs/table-pro-review.md
Normal file
@ -0,0 +1,45 @@
|
||||
# TablePro 代码审查 · 2026-11-05
|
||||
|
||||
基线:`d15966cf`。覆盖 RTablePro、TablePanel、useTablePro、搜索控件和状态、列设置、CSV/打印、样式、公开类型、应用与文档示例。下文保留基线发现,修复结果见文末。
|
||||
|
||||
P1 表示应在继续扩展前处理;P2 表示有明确的功能或使用限制;P3 表示可随相关改动处理。以下“复现”表示本地 Vitest 重现了现有行为,其余为源码推导。
|
||||
|
||||
## P1
|
||||
|
||||
1. **切换查询范围后仍能操作旧范围数据(复现)。** [TablePro.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePro.tsx#L191-L257) 在 request、params 或分页条件改变时启动查询,但仅在成功时替换 result。先加载 `scope=a`,再切到返回错误的 `scope=b`,表格、total、`getCurrentPageData()` 和导出仍取 A。保留同范围刷新结果符合文档;如果范围代表账号、租户或订单,保留其他范围的结果会误导批量操作。建议把成功结果与查询快照绑定,至少在业务范围或数据源切换时清空或禁用操作;单独保留同范围失败时的旧数据。
|
||||
|
||||
## P2
|
||||
|
||||
2. **本地受控分页时,提交搜索和实例跳页无法落实(复现)。** [TablePro.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePro.tsx#L266-L308) 只写内部 page;[渲染](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePro.tsx#L423-L459) 优先用外部 `pagination.page`,而回调只由表格分页器动作触发。给定 `pagination.page=2`,提交搜索后传给 DataTable 的仍为 2。统一用户点击、搜索重置与实例操作的受控写入语义;文档区分 request 模式、手动远端与本地模式。
|
||||
3. **相同字段类型换搜索规则,已生效的规则仍旧(复现)。** [search.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/search.ts#L218-L231) 只按类型和 multiple 判断字段能否保留;[TablePro.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePro.tsx#L324-L352) 把“能保留值”当成“无需重建快照”。把同一个字段的 `matches` 从恒真改为恒假,表中依然显示旧行。更新 `getValue`、`transform` 或 `visible` 也可能保留旧条件。值兼容检查和查询语义变更应分开,后者重建 predicate/params。
|
||||
4. **搜索可见性或匹配函数异常绕过错误边界。** [useTableSearch.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/useTableSearch.ts#L44-L56) 在调用 commit 前归一化,`visible` 抛错会让 submit Promise reject(复现);[模板](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/components/Search.tsx#L255-L258) 未处理 rejection。另有 [TablePro.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePro.tsx#L182-L187) 在 render 依赖的 computed 执行 `getValue/matches`,异常同样进不了 search-error。定义回调异常是开发者错误还是可恢复错误;如选择后者,在提交与执行谓词两处都保留上次有效结果并报告。
|
||||
5. **本地列字段的读取规则与 Naive UI 和导出不一致。** [search.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/search.ts#L289-L291) 用 `row[key]`,而 [CSV](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/csv.ts#L33-L40) 和 [打印](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/printing.ts#L89-L96) 用 lodash `get`。给嵌套对象配置 `key: 'customer.name'` 时,搜索不到界面上展示的值;当前需为字段显式提供 getValue。建议共享默认取值语义,保留显式 getValue 优先级。
|
||||
6. **行右键菜单回调拿不到触发的行。** [TablePanel.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePanel.tsx#L149-L168) 已拿到 row 和 index,但仅存坐标;[选择菜单项](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePanel.tsx#L293-L299) 只发 key/option,无法安全用于行级编辑或删除,也没有键盘等价入口。将行上下文随回调提供并在关闭时清理,或明确该功能是表级菜单。
|
||||
7. **自定义打印区域会丢失宿主样式及部分实时控件状态。** [printing.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/printing.ts#L103-L116) 克隆 DOM,再放进仅有打印样式的 [独立 iframe](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/printing.ts#L155-L169)。如区域依赖应用 CSS、异步字体、canvas 像素或不可克隆的状态,预览与屏幕不一致。文档已有专用 `style` 选项,应补充其边界,并在 Chrome/Safari 验收报表和取消打印后的清理。
|
||||
|
||||
## P3
|
||||
|
||||
8. **本地搜索的热点可以减少分配与重复计算。** [search.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/search.ts#L294-L330) 对每行重复计算搜索文本的小写,多选条件对数组使用嵌套线性查找;[联动](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/search.ts#L184-L213) 每改一个依赖再次扫描全部字段。预编译小写查询与 Set,字段量大时再为依赖建立反向索引;虚拟滚动只限制 DOM,不能降低过滤成本。这里未做大数据基准。
|
||||
9. **分页宽度触发不必要更新,字典反复浅拷贝。** [TablePanel.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePanel.tsx#L42-L46) 的 ResizeObserver 将连续宽度带入 [render](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePanel.tsx#L210-L213);只在跨过 600px 时改变分页模式即可。[locale.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/locale.ts#L9-L17) 每次翻译先克隆整份字典,即使宿主翻译已命中。预建固定字典,宿主翻译优先。此项未做性能量化。
|
||||
10. **公开 Props 的透传边界不易核对。** [props.ts](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/props.ts#L6-L23) 全量继承 Naive UI,再在 [TablePro](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePro.tsx#L407-L440) 与 [TablePanel](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/TablePanel.tsx#L176-L199) 两次拆分。新增包装层字段或升级 Naive UI 时容易把不适用的选项暴露给调用方。优先明确哪些字段由包装层控制;补对受控分页、受控列及 slots 的契约用例。内部 `C.tsx`、`Props.tsx` 可按实际职责命名,减少检索成本。
|
||||
11. **列工具只能拖拽排序,显示状态与布局恢复是两套语义。** [C.tsx](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/components/C.tsx#L136-L177) 提供鼠标拖拽和键盘勾选,没有键盘排序动作;“显示全部”仅清除隐藏状态,[顺序与固定列补丁](https://github.com/XiaoDaiGua-Ray/ray-template/blob/d15966cf637fe8bb6d488c45945a56c26b52e158/packages/ui/src/RTablePro/src/columns.ts#L44-L93) 仍保留。若需要完整恢复和键盘可操作,可添加显式上移/下移与独立的布局重置;目前仅持久化显隐符合文档。
|
||||
|
||||
## 保留的设计
|
||||
|
||||
请求成功前校验 `total` 和数据形状,AbortSignal 既透传给调用方又用于拦截过期结果。搜索草稿和生效快照分开,过期异步校验有版本号;列显隐不会直接修改 props,CSV 单元格做公式前缀防护,默认打印使用 textContent 和隔离 iframe。建议在修复中保留这些边界。
|
||||
|
||||
四个标注“复现”的路径使用 Vue Test Utils / Vitest 独立验证。复现用例与输出保存在本机 `.harness-local/table-pro-review-repro.local.spec.ts` 和 `.harness-local/table-pro-review-repro.log`;未将已知缺陷写成仓库的长期断言。真实性能、原生打印对话框及读屏软件不在本次运行验证范围。
|
||||
|
||||
## 修复批次
|
||||
|
||||
| 批次 | 项目 | 结果 |
|
||||
| ---- | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 1 | 1 | 以请求函数、有效筛选条件和分页绑定成功结果。范围切换立即失效,切页只保留同范围总数,请求失败后清空行和总数,展示空态并由宿主 Toast 提醒。结果不匹配时拦截取数、底层实例、CSV 和打印。 |
|
||||
| 2 | 2–5 | 分页操作和搜索重置复用受控回调;兼容字段采用最新规则;回调失败统一报告并保留已生效条件;字段读取与 Naive UI、打印、CSV 一致。 |
|
||||
| 2 | 6–7 | 行菜单回传行和索引,支持键盘,换数据后关闭。自定义打印复制页面样式、根节点主题、普通表单状态和可复制的画布,等待资源有上限;允许关闭样式继承。 |
|
||||
| 3 | 8–9 | 搜索预计算小写查询、集合和反向依赖;分页只在跨越容器宽度阈值时改变模式;语言回退字典固定复用。 |
|
||||
| 3 | 10–11 | 集中声明 Naive UI 与包装层的透传边界,命名列及外观设置组件;列排序增加键盘按钮,显隐和布局可分别恢复。 |
|
||||
|
||||
回归见 [查询、分页和行菜单](../__test__/components/table-pro.spec.ts)、[搜索](../__test__/components/table-pro-search.spec.ts)、[打印和导出](../__test__/components/table-pro-exports.spec.ts)及[列设置](../__test__/components/table-pro-columns.spec.ts)。受控表格与打印定制方式见 [TablePro 契约](../packages/ui/src/RTablePro/README.md)。手动远端由调用方管理其数据范围;原生打印对话框和页面性能的验证边界见交付记录。
|
||||
|
||||
追补:TablePanel 复用 Naive UI 卡片的表面、描边、圆角和内边距层次,`bare` 不带卡片外观。表格密度、斑马纹和边框以计算值合成,不镜像 props;保留的侦听负责重查、同步搜索配置、上报错误、取消打印及关闭行菜单。
|
||||
@ -2,12 +2,14 @@
|
||||
|
||||
用于 `RTablePro`、`useTablePro`、高级搜索、远端分页、列设置、导出或打印。共享包拥有实现,后台和文档站分别消费同一公开 API。
|
||||
|
||||
| 要查什么 | 先读 | 接着追踪 |
|
||||
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 导出、Props、实例方法 | [共享入口](../../packages/ui/src/RTablePro/index.ts)、[Props](../../packages/ui/src/RTablePro/src/props.ts)、[类型](../../packages/ui/src/RTablePro/src/types.ts) | [注册 Hook](../../packages/ui/src/RTablePro/src/useTablePro.ts)、[包导出](../../packages/ui/package.json)、[应用组件入口](../../apps/admin/src/components/index.ts) |
|
||||
| 搜索草稿、校验、条件生效、请求竞争 | [搜索状态](../../packages/ui/src/RTablePro/src/useTableSearch.ts)、[搜索值处理](../../packages/ui/src/RTablePro/src/search.ts)、[分页与请求](../../packages/ui/src/RTablePro/src/TablePro.tsx) | [搜索控件](../../packages/ui/src/RTablePro/src/components/Search.tsx)、[后台搜索示例](../../apps/admin/src/views/demo/tables/search.tsx)、[搜索回归](../../__test__/components/table-pro-search.spec.ts) |
|
||||
| 列可见性、布局、当前页导出与打印 | [表格面板](../../packages/ui/src/RTablePro/src/TablePanel.tsx)、[列设置](../../packages/ui/src/RTablePro/src/columns.ts) | [CSV](../../packages/ui/src/RTablePro/src/csv.ts)、[打印](../../packages/ui/src/RTablePro/src/printing.ts)、[列回归](../../__test__/components/table-pro-columns.spec.ts) |
|
||||
| 示例、文案和公开约定 | [组件契约](../../packages/ui/src/RTablePro/README.md)、[文档参考](../../apps/docs/reference/table-pro.md) | [后台示例和夹具](../../apps/admin/src/views/demo/tables)、[文档轻量示例](../../apps/docs/examples/TableProDemo.vue)、[组件语言资源](../../packages/ui/src/RTablePro/src/locale.ts) |
|
||||
| 要查什么 | 先读 | 接着追踪 |
|
||||
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 导出、Props、实例方法 | [共享入口](../../packages/ui/src/RTablePro/index.ts)、[Props](../../packages/ui/src/RTablePro/src/props.ts)、[类型](../../packages/ui/src/RTablePro/src/types.ts) | [注册 Hook](../../packages/ui/src/RTablePro/src/useTablePro.ts)、[包导出](../../packages/ui/package.json)、[应用组件入口](../../apps/admin/src/components/index.ts) |
|
||||
| 搜索草稿、校验、条件生效、请求竞争 | [搜索状态](../../packages/ui/src/RTablePro/src/useTableSearch.ts)、[搜索值处理](../../packages/ui/src/RTablePro/src/search.ts)、[分页](../../packages/ui/src/RTablePro/src/pagination.ts)、[远端请求](../../packages/ui/src/RTablePro/src/useTableRequest.ts) | [搜索控件](../../packages/ui/src/RTablePro/src/components/Search.tsx)、[后台搜索示例](../../apps/admin/src/views/demo/tables/search.tsx)、[搜索回归](../../__test__/components/table-pro-search.spec.ts) |
|
||||
| 列可见性、布局、当前页导出与打印 | [表格面板](../../packages/ui/src/RTablePro/src/TablePanel.tsx)、[列设置](../../packages/ui/src/RTablePro/src/columns.ts) | [CSV](../../packages/ui/src/RTablePro/src/csv.ts)、[打印](../../packages/ui/src/RTablePro/src/printing.ts)、[列回归](../../__test__/components/table-pro-columns.spec.ts) |
|
||||
| 示例、文案和公开约定 | [组件契约](../../packages/ui/src/RTablePro/README.md)、[文档参考](../../apps/docs/reference/table-pro.md) | [后台示例和夹具](../../apps/admin/src/views/demo/tables)、[文档轻量示例](../../apps/docs/examples/TableProDemo.vue)、[组件语言资源](../../packages/ui/src/RTablePro/src/locale.ts) |
|
||||
|
||||
[本轮专项代码审查](../../docs/table-pro-review.md)记录已复现的问题、修复批次和验证边界。
|
||||
|
||||
远端 `total` 是筛选后的总数,取消需要请求函数透传 `signal`。修改实例能力时同时检查组件暴露、Hook 和公开导出;修改示例参数时确认是文档轻量示例还是[嵌入后台示例](docs.md)。
|
||||
|
||||
|
||||
@ -22,10 +22,10 @@ import { RTablePro } from '@/components'
|
||||
- `data` 用于本地数据;`request(params, signal)` 用于远端数据,返回 `Promise<{ data: Row[]; total: number }>`。`total` 是应用筛选后的总数;传递 `signal` 给 HTTP 客户端可以取消上一条请求。
|
||||
- `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` 插槽和默认工具集中在表格右上方。
|
||||
- 普通模式按 Naive UI 卡片组织搜索、表头工具、数据与页脚。搜索区在结果上方;`bare` 保留纯表格外观。表格左上方可用 `title` 传文字,或用同名插槽放筛选开关、快捷操作等;都不传时不占位。`toolbar` 插槽和默认工具集中在表格右上方。
|
||||
- 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。
|
||||
- `autoHeight` 默认使用当前布局的可用高度,宿主外部使用视口高度;嵌入特定区域时可以用 CSS 变量 `--r-table-height` 覆盖。较短的屏幕保留表格的最小操作高度。
|
||||
- 只接收最新的请求结果。失败时保留已加载的数据并显示重试;可以用 `onRequestError` 处理错误,或用 `error` 插槽定制提示。
|
||||
- 只接收最新的请求结果。切换请求源或有效筛选条件会立即清空旧行和总数;切页或修改每页条数会隐藏旧行并保留同一范围的总数。当前页未加载时,实例取数返回空、底层实例返回 `null`,CSV 和打印不会启动。请求失败后显示空态并清空总数,通过宿主 Toast 提醒。可用 `onRequestError` 接收详情、用实例 `reload()` 重试,或显式提供 `error` 插槽接管提示。
|
||||
- 需要实例时使用 `shallowRef<TableProInst>()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。
|
||||
|
||||
## 注册 Hook
|
||||
@ -41,15 +41,15 @@ const reloadFromFirstPage = () => reload(true)
|
||||
|
||||
在 SFC 中使用 `@register="register"`。注册发生在表格挂载后,卸载时清除绑定。`actions` 可解构,包含 `TableProInst` 的方法、`getTableProInstance()` 和只读 `isReady`。表格外的按钮可用 `disabled={!isReady.value}`;`isReady` 只表示实例已绑定,未绑定时调用实例方法会抛错。
|
||||
|
||||
`actions.queryState.value` 是组件管理的远端查询状态,实例 ref 则用 `table.value?.queryState`。未挂载或未传 `request` 时为 `null`。只读快照包含 `loading`、`failed`、`page`、`pageSize` 和 `total`;关闭分页时页码和每页条数为 `null`。`total` 在首次成功前为 `null`,刷新和失败时保留上次成功结果。外部 `loading` 不计入查询状态,错误详情由 `onRequestError` 报告。
|
||||
`actions.queryState.value` 是组件管理的远端查询状态,实例 ref 则用 `table.value?.queryState`。未挂载或未传 `request` 时为 `null`。只读快照包含 `loading`、`failed`、`page`、`pageSize` 和 `total`;关闭分页时页码和每页条数为 `null`。`total` 在当前查询范围首次成功前为 `null`,同一范围加载期间可保留最近的成功总数,请求失败后清空。外部 `loading` 不计入查询状态,错误详情由 `onRequestError` 报告。
|
||||
|
||||
`getCurrentPageData()` 适合本页批量操作。本地模式读取排序、筛选、分页后的行;远端模式读取当前已加载的数据,不会请求其他页。它返回对行的只读引用,不受虚拟滚动窗口影响;选择和批量变更仍由页面通过 `v-model:checkedRowKeys` 和业务数据管理。
|
||||
`getCurrentPageData()` 适合本页批量操作。本地模式读取排序、筛选、分页后的行;组件管理的远端模式只读取与当前查询及分页匹配的数据,不会请求其他页。它返回对行的只读引用,不受虚拟滚动窗口影响;选择和批量变更仍由页面通过 `v-model:checkedRowKeys` 和业务数据管理。
|
||||
|
||||
迁移时,把旧 `RTable` 改为 `RTablePro bare`(需要完整工具栏时省略 `bare`),用 `useTablePro` 或实例 ref 替代 `useTable`。旧版 `runTableRequest` / `runAsyncTableRequest` 改用 `reload`,需要回第一页时调用 `reload(true)`。`requestConfig` 改用 `params` 或在请求函数内映射字段;`takeoverAutoHeight`、`flexAutoHeight` 改为 `autoHeight`。
|
||||
|
||||
## 列显示与缓存
|
||||
|
||||
只传普通 `columns` 数组,就能在同一套「列设置」里勾选显示、拖动顺序、固定列或启用列宽调整。默认由 TablePro 在当前实例内维护这些操作,不修改传入的数组。想跨刷新记住显示选择时,加一个稳定的表格标识:
|
||||
只传普通 `columns` 数组,就能在同一套「列设置」里勾选显示、拖动顺序、固定列或启用列宽调整。默认由 TablePro 在当前实例内维护这些操作,不修改传入的数组。拖动或使用上移、下移按钮调整根列顺序。想跨刷新记住显示选择时,加一个稳定的表格标识:
|
||||
|
||||
```tsx
|
||||
<RTablePro columns={columns} data={rows} columnStateKey="orders:list" />
|
||||
@ -58,6 +58,7 @@ const reloadFromFirstPage = () => reload(true)
|
||||
- 使用 Naive UI 的列 `key`,同一表的列 key 唯一且稳定。勾选状态独立于列定义;列分组会跟随子列,选择列和展开列不会被勾选隐藏。至少保留一个数据列。
|
||||
- 缓存是按表格标识分隔的本地偏好。只保存隐藏列的 key,启用或切换标识时读一次,用户改动时才写入。新增列默认显示,失效 key 不影响渲染,恢复全部列会清除缓存。不传标识时仅保留实例内状态。需要按账号或租户隔离时,将其标识纳入 key。
|
||||
- 页面需要接管列顺序、固定位置或 `resizable` 时,可以用 `v-model:columns`;收到的是完整列定义,包含已隐藏的列。显隐始终由列设置维护,固定列仍遵守 Naive UI 的数字列宽约定。
|
||||
- 「恢复列布局」恢复根列顺序、固定和调整宽度开关,保留隐藏列;「恢复全部列」只恢复显隐。受控列由调用方提供 `onResetColumnLayout` 并应用自己的初始定义,未提供时不显示恢复布局按钮。
|
||||
- 不缓存行数据、列定义、回调、列宽、固定或顺序。默认模式用列 key 维护实例内的调整;更新列标题、渲染器等定义不会抹掉用户调整。
|
||||
|
||||
## 打印和 CSV
|
||||
@ -72,12 +73,14 @@ const reloadFromFirstPage = () => reload(true)
|
||||
/>
|
||||
```
|
||||
|
||||
内置按钮使用 `printTableOptions`。单次打印可以用 `table.value?.print({ target: reportRef, title: '报表', style: '@page { size: landscape; }' })` 覆盖配置;目标支持元素、ref 或 getter。自定义区域以独立打印文档呈现,可用 `style` 提供专用 CSS,或用 `data-print-ignore` 排除其中的控件。旧版 `printOptions.documentTitle` 改用 `title`,截图配置不再适用。
|
||||
内置按钮使用 `printTableOptions`。单次打印可以用 `table.value?.print({ target: reportRef, title: '报表', style: '@page { size: landscape; }' })` 覆盖配置;目标支持元素、ref 或 getter。自定义区域以独立打印文档呈现。默认复制页面样式表、根节点主题和普通表单的当前值;设置 `includePageStyles: false` 可只用打印样式。用 `style` 添加覆盖,或用 `data-print-ignore` 排除控件。依赖区域外祖先、运行时脚本或嵌入内容的样式需自行在打印 CSS 中补齐;密码和文件值不会复制。图片和字体等待有上限,未就绪时可能使用替代样式。旧版 `printOptions.documentTitle` 改用 `title`,截图配置不再适用。
|
||||
|
||||
CSV 默认导出当前页可见数据列;`keepOriginalData` 使用传入的整批数据(远端模式不会为导出额外请求)。`allowExport: false` 排除对应列,`getCsvCell` / `getCsvHeader` 返回原始文本,由组件处理 CSV 转义。
|
||||
|
||||
## Naive UI 的配置边界
|
||||
|
||||
普通列配置、选择、展开、排序、筛选、汇总、虚拟滚动、固定列、空状态和加载插槽沿用 [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`。
|
||||
普通列配置、选择、展开、排序、筛选、汇总、虚拟滚动、固定列、空状态和加载插槽沿用 [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`,由调用方负责切换范围时清空旧数据。本地和手动远端受控模式由调用方在分页回调中更新 `pagination.page/pageSize`;搜索重置和实例操作也会触发同一回调。服务端排序、过滤继续使用 Naive UI 的事件,在调用方将条件传给 `params`,组件不会推断接口字段。页数很大时可配置 `pagination.showQuickJumpDropdown: false`。
|
||||
|
||||
在「表格 → 高级搜索」可以切换本地筛选和模拟远端查询,查看日期区间拆分和组织到负责人的联动。配置、值类型和实例方法见[高级搜索参考](../../../../apps/docs/reference/table-pro.md#高级搜索)。在「表格」菜单下也可以查看查询与分页、选择与批量操作、导出与打印三个 Hooks 示例。
|
||||
|
||||
行菜单通过 `contextMenuOptions` 启用。右键点击一行,或聚焦后按 Shift+F10 / 菜单键打开;选择后调用 `onContextMenuClick(key, option, { row, index })`。既有两个参数的回调可继续使用。
|
||||
|
||||
@ -5,6 +5,7 @@ export type {
|
||||
TableProColumn,
|
||||
TableProParams,
|
||||
TableProQueryState,
|
||||
TableProRowContext,
|
||||
TableProRequest,
|
||||
TableProResult,
|
||||
TableProSearchField,
|
||||
|
||||
@ -1,22 +1,23 @@
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
onBeforeUnmount,
|
||||
provide,
|
||||
reactive,
|
||||
ref,
|
||||
shallowRef,
|
||||
toRef,
|
||||
watch,
|
||||
} from 'vue'
|
||||
import { useUiServices } from '../../services'
|
||||
import './index.scss'
|
||||
import { useElementSize } from '@vueuse/core'
|
||||
import { NDataTable, NDropdown } from 'naive-ui'
|
||||
import { NDataTable, NDropdown, useThemeVars } from 'naive-ui'
|
||||
import type { DataTableInst, DataTableProps } from 'naive-ui'
|
||||
import { useTemplateRef } from 'vue'
|
||||
import { useColumnLayout, useColumnVisibility } from './columns'
|
||||
import C from './components/C'
|
||||
import AppearanceSettings from './components/AppearanceSettings'
|
||||
import ColumnSettings from './components/ColumnSettings'
|
||||
import Fullscreen from './components/Fullscreen'
|
||||
import TablePropsSelect from './components/Props'
|
||||
import Size from './components/Size'
|
||||
import ToolButton from './components/ToolButton'
|
||||
import { buildTableCsv, downloadTableCsv } from './csv'
|
||||
@ -26,17 +27,44 @@ import {
|
||||
printTableContent,
|
||||
resolvePrintContent,
|
||||
} from './printing'
|
||||
import props from './props'
|
||||
import { tablePanelProps, toNativeTableProps } from './props'
|
||||
import { config } from './shared'
|
||||
import type { PropsComponentPopselectKeys, TablePanelInst } from './types'
|
||||
import type {
|
||||
PropsComponentPopselectKeys,
|
||||
TablePanelInst,
|
||||
TableProRowContext,
|
||||
} from './types'
|
||||
|
||||
const useLocalOverride = <Value,>(prop: () => Value) => {
|
||||
const source = computed(() => ({ value: prop() }))
|
||||
const local = shallowRef<{ source: typeof source.value; value: Value }>()
|
||||
|
||||
return computed({
|
||||
get: () =>
|
||||
local.value?.source === source.value
|
||||
? local.value.value
|
||||
: source.value.value,
|
||||
set: (value: Value) => {
|
||||
local.value = { source: source.value, value }
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: 'TablePanel',
|
||||
inheritAttrs: false,
|
||||
props,
|
||||
props: tablePanelProps,
|
||||
setup(props, { attrs, slots, expose }) {
|
||||
const { t } = useTableLocale()
|
||||
const { columnStorage, reportError } = useUiServices()
|
||||
const theme = useThemeVars()
|
||||
const cardStyle = computed(() => ({
|
||||
'--r-table-card-surface': theme.value.cardColor,
|
||||
'--r-table-card-divider': theme.value.dividerColor,
|
||||
'--r-table-card-radius': theme.value.borderRadius,
|
||||
'--r-table-card-text': theme.value.textColor1,
|
||||
'--r-table-card-muted': theme.value.textColor2,
|
||||
}))
|
||||
const table = useTemplateRef<DataTableInst>('dataTable')
|
||||
const wrapper = useTemplateRef<HTMLElement>('wrapper')
|
||||
const responsivePager = computed(() =>
|
||||
@ -45,9 +73,24 @@ export default defineComponent({
|
||||
: null,
|
||||
)
|
||||
const { width } = useElementSize(responsivePager)
|
||||
const { layoutColumns, reorderColumns, patchColumn } = useColumnLayout(
|
||||
const narrowPager = computed(() => width.value > 0 && width.value < 600)
|
||||
const mergedPagination = computed(() =>
|
||||
typeof props.pagination === 'object' &&
|
||||
props.pagination.simple == null &&
|
||||
narrowPager.value
|
||||
? { ...props.pagination, simple: true }
|
||||
: props.pagination,
|
||||
)
|
||||
const {
|
||||
layoutColumns,
|
||||
reorderColumns,
|
||||
patchColumn,
|
||||
resetLayout,
|
||||
layoutChanged,
|
||||
} = useColumnLayout(
|
||||
toRef(props, 'columns'),
|
||||
toRef(props, 'onUpdate:columns'),
|
||||
toRef(props, 'onResetColumnLayout'),
|
||||
)
|
||||
const { hiddenKeys, visibleColumns, setColumnVisible, resetColumns } =
|
||||
useColumnVisibility(
|
||||
@ -56,37 +99,39 @@ export default defineComponent({
|
||||
columnStorage,
|
||||
)
|
||||
const printing = ref(false)
|
||||
let pendingPrint: AbortController | undefined
|
||||
const cancelPrint = () => pendingPrint?.abort()
|
||||
|
||||
onBeforeUnmount(cancelPrint)
|
||||
|
||||
provide(config.wrapperKey, wrapper)
|
||||
const size = ref(props.size)
|
||||
const appearance = reactive({
|
||||
striped: props.striped,
|
||||
bordered: props.bordered,
|
||||
})
|
||||
const context = reactive({ x: 0, y: 0, show: false })
|
||||
const size = useLocalOverride(() => props.size)
|
||||
const striped = useLocalOverride(() => props.striped)
|
||||
const bordered = useLocalOverride(() => props.bordered)
|
||||
const context = shallowRef<TableProRowContext & { x: number; y: number }>()
|
||||
const closeContext = () => {
|
||||
context.value = void 0
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.size,
|
||||
(value) => {
|
||||
size.value = value
|
||||
},
|
||||
)
|
||||
watch(
|
||||
() => props.striped,
|
||||
(value) => {
|
||||
appearance.striped = value
|
||||
},
|
||||
)
|
||||
watch(
|
||||
() => props.bordered,
|
||||
(value) => {
|
||||
appearance.bordered = value
|
||||
[
|
||||
() => props.data,
|
||||
() => props.rowActionsDisabled,
|
||||
() => props.contextMenuOptions,
|
||||
],
|
||||
([data, disabled], [previousData, previouslyDisabled]) => {
|
||||
closeContext()
|
||||
|
||||
if (data !== previousData || disabled !== previouslyDisabled)
|
||||
cancelPrint()
|
||||
},
|
||||
)
|
||||
|
||||
const handle: TablePanelInst = {
|
||||
getTableInstance: () => table.value,
|
||||
downloadCsv: (options) => {
|
||||
if (props.rowActionsDisabled) return
|
||||
|
||||
const { fileName, keepOriginalData } = {
|
||||
...props.downloadCsvTableOptions,
|
||||
...options,
|
||||
@ -107,7 +152,8 @@ export default defineComponent({
|
||||
)
|
||||
},
|
||||
print: async (options) => {
|
||||
if (printing.value || props.loading) return false
|
||||
if (printing.value || props.loading || props.rowActionsDisabled)
|
||||
return false
|
||||
|
||||
const printOptions = {
|
||||
title: typeof props.title === 'string' ? props.title : '',
|
||||
@ -117,6 +163,9 @@ export default defineComponent({
|
||||
...options,
|
||||
}
|
||||
|
||||
const current = new AbortController()
|
||||
|
||||
pendingPrint = current
|
||||
printing.value = true
|
||||
|
||||
try {
|
||||
@ -133,12 +182,16 @@ export default defineComponent({
|
||||
: null
|
||||
})
|
||||
|
||||
return !!content && (await printTableContent(content, printOptions))
|
||||
return (
|
||||
!!content &&
|
||||
(await printTableContent(content, printOptions, current.signal))
|
||||
)
|
||||
} catch (error) {
|
||||
console.error('[TablePro]: Could not open print preview.', error)
|
||||
|
||||
return false
|
||||
} finally {
|
||||
pendingPrint = void 0
|
||||
printing.value = false
|
||||
}
|
||||
},
|
||||
@ -149,30 +202,50 @@ export default defineComponent({
|
||||
const rowProps: NonNullable<DataTableProps['rowProps']> = (row, index) => {
|
||||
const original = props.rowProps?.(row, index)
|
||||
|
||||
if (!props.contextMenuOptions?.length) return original ?? {}
|
||||
if (!props.contextMenuOptions?.length || props.rowActionsDisabled)
|
||||
return original ?? {}
|
||||
|
||||
return {
|
||||
...original,
|
||||
onContextmenu: (event: PointerEvent) => {
|
||||
class: [original?.class, 'r-table__context-row'],
|
||||
tabindex: original?.tabindex ?? 0,
|
||||
'aria-keyshortcuts': original?.['aria-keyshortcuts'] ?? 'Shift+F10',
|
||||
onContextmenu: (event) => {
|
||||
original?.onContextmenu?.(event)
|
||||
|
||||
if (event.defaultPrevented) return
|
||||
|
||||
event.preventDefault()
|
||||
Object.assign(context, {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
show: true,
|
||||
})
|
||||
context.value = { row, index, x: event.clientX, y: event.clientY }
|
||||
},
|
||||
onKeydown: (event) => {
|
||||
original?.onKeydown?.(event)
|
||||
|
||||
if (
|
||||
event.defaultPrevented ||
|
||||
event.target !== event.currentTarget ||
|
||||
(event.key !== 'ContextMenu' &&
|
||||
!(event.shiftKey && event.key === 'F10'))
|
||||
)
|
||||
return
|
||||
|
||||
const rect = (
|
||||
event.currentTarget as HTMLElement
|
||||
).getBoundingClientRect()
|
||||
|
||||
event.preventDefault()
|
||||
context.value = { row, index, x: rect.left, y: rect.bottom }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const changeAppearance = (values: PropsComponentPopselectKeys[]) => {
|
||||
appearance.striped = values.includes('striped')
|
||||
appearance.bordered = values.includes('bordered')
|
||||
striped.value = values.includes('striped')
|
||||
bordered.value = values.includes('bordered')
|
||||
}
|
||||
|
||||
const nativeProps = computed(() => toNativeTableProps(props))
|
||||
|
||||
return () => {
|
||||
const {
|
||||
bare,
|
||||
@ -181,12 +254,7 @@ export default defineComponent({
|
||||
tool,
|
||||
contextMenuOptions,
|
||||
onContextMenuClick,
|
||||
'onUpdate:columns': updateColumns,
|
||||
downloadCsvTableOptions,
|
||||
printTableOptions,
|
||||
columnStateKey,
|
||||
pagination,
|
||||
...dataTableProps
|
||||
rowActionsDisabled,
|
||||
} = props
|
||||
const {
|
||||
filters,
|
||||
@ -207,16 +275,17 @@ export default defineComponent({
|
||||
)
|
||||
const extras = tableFooter?.()
|
||||
const actions = tableAction?.()
|
||||
const mergedPagination =
|
||||
typeof pagination === 'object' && width.value > 0 && width.value < 600
|
||||
? { simple: true, ...pagination }
|
||||
: pagination
|
||||
|
||||
return (
|
||||
<section
|
||||
{...attrs}
|
||||
ref="wrapper"
|
||||
class={['r-table', { 'r-table--fill': autoHeight }, attrs.class]}
|
||||
class={[
|
||||
'r-table',
|
||||
{ 'r-table--card': !bare, 'r-table--fill': autoHeight },
|
||||
attrs.class,
|
||||
]}
|
||||
style={[cardStyle.value, attrs.style]}
|
||||
>
|
||||
{filters?.()}
|
||||
{notice?.()}
|
||||
@ -234,7 +303,11 @@ export default defineComponent({
|
||||
<ToolButton
|
||||
icon="action/print"
|
||||
label={t('print')}
|
||||
disabled={props.loading || printing.value}
|
||||
disabled={
|
||||
rowActionsDisabled ||
|
||||
props.loading ||
|
||||
printing.value
|
||||
}
|
||||
onClick={async () => {
|
||||
if (!(await handle.print()))
|
||||
reportError?.(t('printError'))
|
||||
@ -248,17 +321,20 @@ export default defineComponent({
|
||||
/>
|
||||
<Fullscreen />
|
||||
{props.columns.length ? (
|
||||
<C
|
||||
<ColumnSettings
|
||||
columns={layoutColumns.value}
|
||||
hiddenKeys={hiddenKeys.value}
|
||||
onReorderColumns={reorderColumns}
|
||||
onPatchColumn={patchColumn}
|
||||
onToggleColumn={setColumnVisible}
|
||||
onResetColumns={resetColumns}
|
||||
canResetLayout={layoutChanged.value}
|
||||
onResetLayout={resetLayout}
|
||||
/>
|
||||
) : null}
|
||||
<TablePropsSelect
|
||||
{...appearance}
|
||||
<AppearanceSettings
|
||||
striped={striped.value}
|
||||
bordered={bordered.value}
|
||||
onChange={changeAppearance}
|
||||
/>
|
||||
</>
|
||||
@ -268,12 +344,13 @@ export default defineComponent({
|
||||
</header>
|
||||
) : null}
|
||||
<NDataTable
|
||||
{...dataTableProps}
|
||||
{...appearance}
|
||||
{...nativeProps.value}
|
||||
striped={striped.value}
|
||||
bordered={bordered.value}
|
||||
ref="dataTable"
|
||||
columns={visibleColumns.value}
|
||||
pagination={mergedPagination}
|
||||
flexHeight={autoHeight || dataTableProps.flexHeight}
|
||||
pagination={mergedPagination.value}
|
||||
flexHeight={autoHeight || props.flexHeight}
|
||||
rowProps={rowProps}
|
||||
size={size.value}
|
||||
>
|
||||
@ -284,18 +361,26 @@ export default defineComponent({
|
||||
{actions ? <div class="r-table__action">{actions}</div> : null}
|
||||
{contextMenuOptions?.length ? (
|
||||
<NDropdown
|
||||
show={context.show}
|
||||
show={!!context.value}
|
||||
placement="bottom-start"
|
||||
trigger="manual"
|
||||
x={context.x}
|
||||
y={context.y}
|
||||
x={context.value?.x ?? 0}
|
||||
y={context.value?.y ?? 0}
|
||||
options={contextMenuOptions}
|
||||
onClickoutside={() => {
|
||||
context.show = false
|
||||
onClickoutside={closeContext}
|
||||
onUpdateShow={(show) => {
|
||||
if (!show) closeContext()
|
||||
}}
|
||||
onSelect={(key, option) => {
|
||||
context.show = false
|
||||
onContextMenuClick?.(key, option)
|
||||
const current = context.value
|
||||
|
||||
closeContext()
|
||||
|
||||
if (current && !rowActionsDisabled) {
|
||||
const { row, index } = current
|
||||
|
||||
onContextMenuClick?.(key, option, { row, index })
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
import { call } from '@ray-template/composables/vue/call'
|
||||
import { NAlert, NButton } from 'naive-ui'
|
||||
import { isEqual } from 'lodash-es'
|
||||
import type { PaginationProps } from 'naive-ui'
|
||||
import {
|
||||
computed,
|
||||
defineComponent,
|
||||
onBeforeUnmount,
|
||||
onBeforeUpdate,
|
||||
onMounted,
|
||||
ref,
|
||||
@ -13,10 +12,12 @@ import {
|
||||
watch,
|
||||
} from 'vue'
|
||||
import type { ExtractPublicPropTypes, PropType } from 'vue'
|
||||
import { useUiServices } from '../../services'
|
||||
import Search from './components/Search'
|
||||
import type { TableSearchFormInst } from './components/Search'
|
||||
import { useTableLocale } from './locale'
|
||||
import tableProps from './props'
|
||||
import { splitPaginationOptions } from './pagination'
|
||||
import tableProps, { toPanelProps } from './props'
|
||||
import {
|
||||
copySearchValues,
|
||||
createSearchPredicate,
|
||||
@ -24,8 +25,10 @@ import {
|
||||
normalizeSearchValues,
|
||||
resolveSearchFields,
|
||||
resolveSearchOptions,
|
||||
sameSearchBehavior,
|
||||
sameSearchField,
|
||||
toSearchParams,
|
||||
visibleSearchFields,
|
||||
} from './search'
|
||||
import TablePanel from './TablePanel'
|
||||
import type {
|
||||
@ -40,6 +43,7 @@ import type {
|
||||
TableProSearchSubmission,
|
||||
TableProSearchValues,
|
||||
} from './types'
|
||||
import { useTableRequest } from './useTableRequest'
|
||||
import { useTableSearch } from './useTableSearch'
|
||||
|
||||
const positiveInteger = (value: number) =>
|
||||
@ -109,19 +113,30 @@ export default defineComponent({
|
||||
},
|
||||
setup(props, { attrs, slots, expose, emit }) {
|
||||
const { t } = useTableLocale()
|
||||
const { reportError } = useUiServices()
|
||||
const table = shallowRef<TablePanelInst>()
|
||||
const result = shallowRef<TableProResult>()
|
||||
const requestPhase = ref<'idle' | 'loading' | 'failed'>('idle')
|
||||
const searchForm = useTemplateRef<TableSearchFormInst>('searchForm')
|
||||
const customFilters = ref(!!slots.filters)
|
||||
const searchFailed = ref(false)
|
||||
let lastSearchError: unknown
|
||||
const reportSearchError = (error: unknown): false => {
|
||||
if (!searchFailed.value || error !== lastSearchError) {
|
||||
lastSearchError = error
|
||||
searchFailed.value = true
|
||||
emit('search-error', error)
|
||||
}
|
||||
|
||||
return 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)
|
||||
return resolveSearchFields(options, props.columns).map((field) => ({
|
||||
...field,
|
||||
}))
|
||||
})
|
||||
const searchModel = useTableSearch(
|
||||
() => searchFields.value,
|
||||
@ -131,18 +146,45 @@ export default defineComponent({
|
||||
? (searchForm.value?.validate(isCurrent) ?? true)
|
||||
: true,
|
||||
() => searchForm.value?.restoreValidation(),
|
||||
reportSearchError,
|
||||
(values, reason) => applySearch(values, searchFields.value, reason),
|
||||
)
|
||||
const applied = shallowRef(createSearchSnapshot({}, emptySearchFields))
|
||||
|
||||
const draftFields = computed(
|
||||
(
|
||||
previous:
|
||||
| { fields: typeof searchFields.value; error?: { cause: unknown } }
|
||||
| undefined,
|
||||
) => {
|
||||
try {
|
||||
return {
|
||||
fields: visibleSearchFields(
|
||||
searchFields.value,
|
||||
searchModel.draft.value,
|
||||
),
|
||||
}
|
||||
} catch (cause) {
|
||||
return {
|
||||
fields: previous?.fields ?? emptySearchFields,
|
||||
error: { cause },
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
try {
|
||||
const values = searchModel.draft.value
|
||||
|
||||
applied.value = createSearchSnapshot(
|
||||
normalizeSearchValues(searchFields.value, searchModel.draft.value),
|
||||
normalizeSearchValues(
|
||||
visibleSearchFields(searchFields.value, values),
|
||||
values,
|
||||
),
|
||||
searchFields.value,
|
||||
)
|
||||
} catch (error) {
|
||||
searchFailed.value = true
|
||||
emit('search-error', error)
|
||||
reportSearchError(error)
|
||||
}
|
||||
|
||||
const manualSearch = computed(
|
||||
@ -165,115 +207,120 @@ export default defineComponent({
|
||||
|
||||
return positiveInteger(size) ? size : 10
|
||||
})
|
||||
const pager = computed(() => splitPaginationOptions(pagerOptions.value))
|
||||
const firstPage = pagerOptions.value?.defaultPage ?? 1
|
||||
const page = ref(positiveInteger(firstPage) ? firstPage : 1)
|
||||
const pageSize = ref(configuredPageSize.value)
|
||||
const queryState = computed<TableProQueryState | null>(() => {
|
||||
if (!props.request) return null
|
||||
const displayedPage = computed(() =>
|
||||
props.request ? page.value : (pagerOptions.value?.page ?? page.value),
|
||||
)
|
||||
const displayedPageSize = computed(() =>
|
||||
props.request
|
||||
? pageSize.value
|
||||
: (pagerOptions.value?.pageSize ?? pageSize.value),
|
||||
)
|
||||
|
||||
return Object.freeze({
|
||||
loading: requestPhase.value === 'loading',
|
||||
failed: requestPhase.value === 'failed',
|
||||
page: paginated.value ? page.value : null,
|
||||
pageSize: paginated.value ? pageSize.value : null,
|
||||
total: result.value?.total ?? null,
|
||||
})
|
||||
})
|
||||
const localRows = computed(() => {
|
||||
const { matches } = applied.value
|
||||
|
||||
return matches && !manualSearch.value
|
||||
? props.data.filter(matches)
|
||||
: props.data
|
||||
})
|
||||
let pending: AbortController | undefined
|
||||
|
||||
const reload = async (resetPage = false) => {
|
||||
if (resetPage) page.value = 1
|
||||
|
||||
pending?.abort()
|
||||
const { request, params } = props
|
||||
|
||||
if (!request) {
|
||||
pending = void 0
|
||||
requestPhase.value = 'idle'
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const current = new AbortController()
|
||||
|
||||
pending = current
|
||||
requestPhase.value = 'loading'
|
||||
|
||||
// 分页字段由表格统一管理,筛选参数不能覆盖当前页码。
|
||||
const query: TableProParams = {
|
||||
...params,
|
||||
...copySearchValues(applied.value.params),
|
||||
}
|
||||
|
||||
if (paginated.value) {
|
||||
query.page = page.value
|
||||
query.pageSize = pageSize.value
|
||||
} else {
|
||||
delete query.page
|
||||
delete query.pageSize
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await request(query, current.signal)
|
||||
|
||||
// 快速切页或筛选时,只接收最后一次请求的结果。
|
||||
if (current.signal.aborted) return
|
||||
|
||||
if (
|
||||
!Array.isArray(response.data) ||
|
||||
!Number.isSafeInteger(response.total) ||
|
||||
response.total < 0
|
||||
) {
|
||||
throw new TypeError(
|
||||
'[RTablePro] Expected { data: Row[], total: number }.',
|
||||
)
|
||||
}
|
||||
|
||||
const lastPage = Math.max(1, Math.ceil(response.total / pageSize.value))
|
||||
|
||||
if (paginated.value && page.value > lastPage) {
|
||||
page.value = lastPage
|
||||
|
||||
if (response.total) {
|
||||
await reload()
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
result.value = response
|
||||
} catch (error) {
|
||||
if (current.signal.aborted) return
|
||||
|
||||
requestPhase.value = 'failed'
|
||||
emit('request-error', error)
|
||||
} finally {
|
||||
if (pending === current) {
|
||||
pending = void 0
|
||||
|
||||
if (requestPhase.value === 'loading') requestPhase.value = 'idle'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const setPage = async (value: number) => {
|
||||
if (!positiveInteger(value) || page.value === value) return
|
||||
const updatePage = (value: number) => {
|
||||
if (
|
||||
!paginated.value ||
|
||||
!positiveInteger(value) ||
|
||||
displayedPage.value === value
|
||||
)
|
||||
return false
|
||||
|
||||
page.value = value
|
||||
await reload()
|
||||
pager.value.notifyPage(value)
|
||||
|
||||
for (const handler of [
|
||||
props.onUpdatePage,
|
||||
props['onUpdate:page'],
|
||||
props.onPageChange,
|
||||
])
|
||||
if (handler) call(handler, value)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const {
|
||||
reload: load,
|
||||
activeResult,
|
||||
total,
|
||||
phase: requestPhase,
|
||||
state: queryState,
|
||||
} = useTableRequest({
|
||||
request: () => props.request,
|
||||
filters: () => ({ ...props.params, ...applied.value.params }),
|
||||
paging: () =>
|
||||
paginated.value
|
||||
? { page: page.value, pageSize: pageSize.value }
|
||||
: void 0,
|
||||
updatePage,
|
||||
reportError: (error) => {
|
||||
emit('request-error', error)
|
||||
|
||||
if (!slots.error) reportError?.(t('requestError'))
|
||||
},
|
||||
})
|
||||
const reload = (resetPage = false) => {
|
||||
if (resetPage) updatePage(1)
|
||||
|
||||
return load()
|
||||
}
|
||||
|
||||
type LocalRows = {
|
||||
source: typeof props.data
|
||||
rows: typeof props.data
|
||||
error?: { cause: unknown }
|
||||
}
|
||||
const localRows = computed<LocalRows>((previous) => {
|
||||
const source = props.data
|
||||
const { matches } = applied.value
|
||||
|
||||
if (!matches || props.request || manualSearch.value)
|
||||
return { source, rows: source }
|
||||
|
||||
try {
|
||||
return { source, rows: source.filter(matches) }
|
||||
} catch (cause) {
|
||||
return {
|
||||
source,
|
||||
rows: previous?.source === source ? previous.rows : [],
|
||||
error: { cause },
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
[() => draftFields.value.error, () => localRows.value.error],
|
||||
(errors, previous) => {
|
||||
errors.forEach((error, index) => {
|
||||
if (error && error !== previous[index]) reportSearchError(error.cause)
|
||||
})
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
const setPage = async (value: number) => {
|
||||
if (updatePage(value)) await reload()
|
||||
}
|
||||
|
||||
const setPageSize = async (value: number) => {
|
||||
if (!positiveInteger(value) || pageSize.value === value) return
|
||||
if (
|
||||
!paginated.value ||
|
||||
!positiveInteger(value) ||
|
||||
displayedPageSize.value === value
|
||||
)
|
||||
return
|
||||
|
||||
pageSize.value = value
|
||||
pager.value.notifyPageSize(value)
|
||||
|
||||
for (const handler of [
|
||||
props.onPageSizeChange,
|
||||
props.onUpdatePageSize,
|
||||
props['onUpdate:pageSize'],
|
||||
])
|
||||
if (handler) call(handler, value)
|
||||
|
||||
await reload(true)
|
||||
}
|
||||
|
||||
@ -281,21 +328,36 @@ export default defineComponent({
|
||||
values: TableProSearchValues,
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
reason?: TableProSearchSubmission['reason'],
|
||||
normalize = true,
|
||||
) {
|
||||
let snapshot: ReturnType<typeof createSearchSnapshot>
|
||||
const previous = applied.value
|
||||
|
||||
try {
|
||||
snapshot = createSearchSnapshot(copySearchValues(values), fields)
|
||||
} catch (error) {
|
||||
searchFailed.value = true
|
||||
emit('search-error', error)
|
||||
const normalized = normalize
|
||||
? normalizeSearchValues(visibleSearchFields(fields, values), values)
|
||||
: values
|
||||
|
||||
return false
|
||||
applied.value = createSearchSnapshot(
|
||||
copySearchValues(normalized),
|
||||
fields,
|
||||
)
|
||||
|
||||
const error = localRows.value.error
|
||||
|
||||
if (error) throw error.cause
|
||||
} catch (error) {
|
||||
applied.value = previous
|
||||
|
||||
return reportSearchError(error)
|
||||
}
|
||||
|
||||
searchFailed.value = false
|
||||
applied.value = snapshot
|
||||
page.value = 1
|
||||
const snapshot = applied.value
|
||||
|
||||
if (!reason && props.request && isEqual(previous.params, snapshot.params))
|
||||
return true
|
||||
|
||||
updatePage(1)
|
||||
|
||||
if (reason) {
|
||||
emit('search', {
|
||||
@ -315,7 +377,7 @@ export default defineComponent({
|
||||
searchOptions.value?.fields?.filter(({ type }) => !type) ??
|
||||
emptySearchFields
|
||||
|
||||
await applySearch(values, fields, 'submit')
|
||||
await applySearch(values, fields, 'submit', false)
|
||||
}
|
||||
|
||||
onBeforeUpdate(() => {
|
||||
@ -333,7 +395,10 @@ export default defineComponent({
|
||||
|
||||
if (
|
||||
retainedKeys.size === fields.length &&
|
||||
fields.length === previous.length
|
||||
fields.length === previous.length &&
|
||||
fields.every((field) =>
|
||||
sameSearchBehavior(field, previousByKey.get(field.key)),
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
@ -344,33 +409,21 @@ export default defineComponent({
|
||||
),
|
||||
)
|
||||
|
||||
if (
|
||||
Object.keys(retained).length !==
|
||||
Object.keys(applied.value.values).length
|
||||
)
|
||||
void applySearch(normalizeSearchValues(fields, retained), fields)
|
||||
if (Object.keys(applied.value.values).length)
|
||||
void applySearch(retained, fields)
|
||||
})
|
||||
|
||||
watch(
|
||||
[() => props.request, () => props.params, paginated, configuredPageSize],
|
||||
(_values, previous) => {
|
||||
([, , , configuredSize], previous) => {
|
||||
if (configuredSize !== previous[3]) pageSize.value = configuredSize
|
||||
|
||||
if (!previous.length && searchFailed.value) return
|
||||
|
||||
void reload(previous.length > 0)
|
||||
},
|
||||
{ deep: true, immediate: true },
|
||||
)
|
||||
watch(
|
||||
configuredPageSize,
|
||||
(value) => {
|
||||
pageSize.value = value
|
||||
},
|
||||
{ flush: 'sync' },
|
||||
)
|
||||
onBeforeUnmount(() => {
|
||||
pending?.abort()
|
||||
pending = void 0
|
||||
})
|
||||
|
||||
const instance: TableProInst = {
|
||||
get queryState() {
|
||||
@ -394,31 +447,31 @@ export default defineComponent({
|
||||
searchFields.value.length
|
||||
? searchModel.reset()
|
||||
: Promise.resolve(false),
|
||||
getTableInstance: () => table.value?.getTableInstance() ?? null,
|
||||
getTableInstance: () =>
|
||||
props.request && !activeResult.value
|
||||
? null
|
||||
: (table.value?.getTableInstance() ?? null),
|
||||
getCurrentPageData: () =>
|
||||
table.value?.getTableInstance()?.getCurrentPageData() ?? [],
|
||||
print: (options) => table.value?.print(options) ?? Promise.resolve(false),
|
||||
downloadCsv: (options) => table.value?.downloadCsv(options),
|
||||
props.request
|
||||
? (activeResult.value?.data ?? emptyRemoteRows)
|
||||
: (table.value?.getTableInstance()?.getCurrentPageData() ?? []),
|
||||
print: (options) =>
|
||||
(!props.request || activeResult.value
|
||||
? table.value?.print(options)
|
||||
: void 0) ?? Promise.resolve(false),
|
||||
downloadCsv: (options) => {
|
||||
if (!props.request || activeResult.value)
|
||||
table.value?.downloadCsv(options)
|
||||
},
|
||||
}
|
||||
|
||||
expose(instance)
|
||||
onMounted(() => props.onRegister?.(instance))
|
||||
|
||||
const panelProps = computed(() => toPanelProps(props))
|
||||
|
||||
return () => {
|
||||
const {
|
||||
request,
|
||||
onRegister: _onRegister,
|
||||
params,
|
||||
pagination: _pagination,
|
||||
pageSize: _pageSize,
|
||||
search,
|
||||
loading: externalLoading,
|
||||
remote,
|
||||
onUpdatePage,
|
||||
onUpdatePageSize,
|
||||
...rest
|
||||
} = props
|
||||
const options = pagerOptions.value
|
||||
const { request, search, loading: externalLoading, remote } = props
|
||||
const { filters, error, notice, ...panelSlots } = slots
|
||||
const paginationProps: false | PaginationProps =
|
||||
pagination.value === false
|
||||
@ -427,37 +480,30 @@ export default defineComponent({
|
||||
showSizePicker: true,
|
||||
pageSizes: [10, 20, 50, 100],
|
||||
prefix: ({ itemCount }) => t('total', { count: itemCount }),
|
||||
...options,
|
||||
page: request ? page.value : (options?.page ?? page.value),
|
||||
pageSize: request
|
||||
? pageSize.value
|
||||
: (options?.pageSize ?? pageSize.value),
|
||||
...pager.value.view,
|
||||
page: displayedPage.value,
|
||||
pageSize: displayedPageSize.value,
|
||||
...(request
|
||||
? { itemCount: result.value?.total ?? 0, pageCount: void 0 }
|
||||
? { itemCount: total.value ?? 0, pageCount: void 0 }
|
||||
: {}),
|
||||
}
|
||||
|
||||
return (
|
||||
<TablePanel
|
||||
{...attrs}
|
||||
{...rest}
|
||||
{...panelProps.value}
|
||||
ref={table}
|
||||
remote={!!request || remote}
|
||||
data={
|
||||
request ? (result.value?.data ?? emptyRemoteRows) : localRows.value
|
||||
request
|
||||
? (activeResult.value?.data ?? emptyRemoteRows)
|
||||
: localRows.value.rows
|
||||
}
|
||||
rowActionsDisabled={!!request && !activeResult.value}
|
||||
loading={requestPhase.value === 'loading' || externalLoading}
|
||||
pagination={paginationProps}
|
||||
onUpdatePage={(value) => {
|
||||
void setPage(value)
|
||||
|
||||
if (onUpdatePage) call(onUpdatePage, value)
|
||||
}}
|
||||
onUpdatePageSize={(value) => {
|
||||
void setPageSize(value)
|
||||
|
||||
if (onUpdatePageSize) call(onUpdatePageSize, value)
|
||||
}}
|
||||
onUpdatePage={setPage}
|
||||
onUpdatePageSize={setPageSize}
|
||||
>
|
||||
{{
|
||||
...panelSlots,
|
||||
@ -467,7 +513,7 @@ export default defineComponent({
|
||||
? () => (
|
||||
<Search
|
||||
ref="searchForm"
|
||||
fields={searchFields.value}
|
||||
fields={draftFields.value.fields}
|
||||
values={searchModel.draft.value}
|
||||
options={searchOptions.value}
|
||||
legacy={isSearchArray(search)}
|
||||
@ -480,16 +526,10 @@ export default defineComponent({
|
||||
/>
|
||||
)
|
||||
: void 0,
|
||||
notice: () =>
|
||||
requestPhase.value === 'failed'
|
||||
? (error?.({ reload }) ?? (
|
||||
<NAlert type="error" title={t('requestError')}>
|
||||
<NButton size="small" secondary onClick={() => reload()}>
|
||||
{t('retry')}
|
||||
</NButton>
|
||||
</NAlert>
|
||||
))
|
||||
: notice?.(),
|
||||
notice:
|
||||
requestPhase.value === 'failed' && error
|
||||
? () => error({ reload })
|
||||
: notice,
|
||||
}}
|
||||
</TablePanel>
|
||||
)
|
||||
|
||||
@ -44,6 +44,7 @@ const applyRootOrder = (
|
||||
export const useColumnLayout = (
|
||||
columns: Ref<DataTableColumn[]>,
|
||||
onUpdate: Ref<((columns: DataTableColumn[]) => void) | undefined>,
|
||||
onReset: Ref<(() => void) | undefined>,
|
||||
) => {
|
||||
const order = shallowRef<TableColumnKey[]>()
|
||||
const patches = shallowRef<Map<TableColumnKey, ColumnLayoutPatch>>()
|
||||
@ -90,7 +91,28 @@ export const useColumnLayout = (
|
||||
}
|
||||
}
|
||||
|
||||
return { layoutColumns, reorderColumns, patchColumn }
|
||||
const layoutChanged = computed(() =>
|
||||
onUpdate.value ? !!onReset.value : !!(order.value || patches.value?.size),
|
||||
)
|
||||
|
||||
const resetLayout = () => {
|
||||
if (onUpdate.value) {
|
||||
onReset.value?.()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
order.value = void 0
|
||||
patches.value = void 0
|
||||
}
|
||||
|
||||
return {
|
||||
layoutColumns,
|
||||
reorderColumns,
|
||||
patchColumn,
|
||||
resetLayout,
|
||||
layoutChanged,
|
||||
}
|
||||
}
|
||||
|
||||
const filterColumns = (
|
||||
|
||||
@ -9,9 +9,10 @@ import props from '../props'
|
||||
import ToolButton from './ToolButton'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'TableColumns',
|
||||
name: 'TableColumnSettings',
|
||||
props: {
|
||||
columns: props.columns,
|
||||
canResetLayout: Boolean,
|
||||
hiddenKeys: {
|
||||
type: Object as PropType<ReadonlySet<TableColumnKey>>,
|
||||
required: true,
|
||||
@ -22,6 +23,7 @@ export default defineComponent({
|
||||
patchColumn: (_key: TableColumnKey, _patch: ColumnLayoutPatch) => true,
|
||||
toggleColumn: (_key: TableColumnKey, _visible: boolean) => true,
|
||||
resetColumns: () => true,
|
||||
resetLayout: () => true,
|
||||
},
|
||||
setup(props, { emit }) {
|
||||
const { t } = useTableLocale()
|
||||
@ -59,14 +61,51 @@ export default defineComponent({
|
||||
)
|
||||
}
|
||||
|
||||
const arrangeTools = (column: KeyedColumn) => {
|
||||
const moveColumn = (index: number, offset: -1 | 1) => {
|
||||
const keys = columns.value.map(({ key }) => key)
|
||||
const target = index + offset
|
||||
|
||||
if (target < 0 || target >= keys.length) return
|
||||
|
||||
;[keys[index], keys[target]] = [keys[target], keys[index]]
|
||||
emit('reorderColumns', keys)
|
||||
}
|
||||
|
||||
const arrangeTools = (column: KeyedColumn, index: number) => {
|
||||
const label =
|
||||
typeof column.title === 'string' ? column.title : String(column.key)
|
||||
const hasWidth =
|
||||
'children' in column
|
||||
? column.children.every((child) => typeof child.width === 'number')
|
||||
: typeof column.width === 'number'
|
||||
|
||||
return (
|
||||
<NFlex align="center" size={4}>
|
||||
<NFlex align="center" size={2} wrap={false}>
|
||||
{([-1, 1] as const).map((offset) => {
|
||||
const action = t(offset < 0 ? 'moveColumnUp' : 'moveColumnDown', {
|
||||
column: label,
|
||||
})
|
||||
|
||||
return (
|
||||
<button
|
||||
key={offset}
|
||||
type="button"
|
||||
class="r-table-columns__move"
|
||||
aria-label={action}
|
||||
title={action}
|
||||
aria-disabled={
|
||||
index + offset < 0 || index + offset >= columns.value.length
|
||||
}
|
||||
onKeydown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation()
|
||||
moveColumn(index, offset)
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true">{offset < 0 ? '↑' : '↓'}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
<ToolButton
|
||||
icon="directional/row_head"
|
||||
label={t(
|
||||
@ -112,13 +151,13 @@ export default defineComponent({
|
||||
}
|
||||
|
||||
const toTree = (items: KeyedColumn[], root: boolean): TreeOption[] =>
|
||||
items.map((column) => ({
|
||||
items.map((column, index) => ({
|
||||
key: column.key,
|
||||
label:
|
||||
typeof column.title === 'string' ? column.title : String(column.key),
|
||||
children:
|
||||
'children' in column ? toTree(column.children, false) : void 0,
|
||||
suffix: root ? () => arrangeTools(column) : void 0,
|
||||
suffix: root ? () => arrangeTools(column, index) : void 0,
|
||||
}))
|
||||
|
||||
const tree = computed(() => toTree(columns.value, true))
|
||||
@ -175,14 +214,25 @@ export default defineComponent({
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<NButton
|
||||
size="small"
|
||||
quaternary
|
||||
disabled={!props.hiddenKeys.size}
|
||||
onClick={() => emit('resetColumns')}
|
||||
>
|
||||
{t('showAllColumns')}
|
||||
</NButton>
|
||||
<NFlex size={4}>
|
||||
<NButton
|
||||
size="small"
|
||||
quaternary
|
||||
disabled={!props.hiddenKeys.size}
|
||||
onClick={() => emit('resetColumns')}
|
||||
>
|
||||
{t('showAllColumns')}
|
||||
</NButton>
|
||||
{props.canResetLayout && (
|
||||
<NButton
|
||||
size="small"
|
||||
quaternary
|
||||
onClick={() => emit('resetLayout')}
|
||||
>
|
||||
{t('resetColumnLayout')}
|
||||
</NButton>
|
||||
)}
|
||||
</NFlex>
|
||||
</fieldset>
|
||||
),
|
||||
}}
|
||||
@ -11,7 +11,7 @@ import {
|
||||
} from 'vue'
|
||||
import type { PropType } from 'vue'
|
||||
import { useTableLocale } from '../locale'
|
||||
import { isSearchFieldVisible, normalizeSearchValues } from '../search'
|
||||
import { normalizeSearchValues } from '../search'
|
||||
import type {
|
||||
TableProSearchFieldConfig,
|
||||
TableProSearchOptions,
|
||||
@ -83,20 +83,14 @@ export default defineComponent({
|
||||
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),
|
||||
),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
props.fields.map((field, index) => ({
|
||||
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
|
||||
|
||||
@ -52,6 +52,9 @@
|
||||
"contextAction": "Row context menu action",
|
||||
"firstPage": "Go to first page",
|
||||
"twentyRows": "20 per page",
|
||||
"customFooter": "Right-click a row to open the example context menu.",
|
||||
"pinNeedsWidth": "Set a numeric column width before pinning"
|
||||
"customFooter": "Right-click a row or press Shift+F10 on it to open its menu.",
|
||||
"pinNeedsWidth": "Set a numeric column width before pinning",
|
||||
"moveColumnUp": "Move {column} up",
|
||||
"moveColumnDown": "Move {column} down",
|
||||
"resetColumnLayout": "Reset column layout"
|
||||
}
|
||||
|
||||
@ -6,6 +6,15 @@
|
||||
inline-size: 100%;
|
||||
min-inline-size: 0;
|
||||
|
||||
&--card {
|
||||
box-sizing: border-box;
|
||||
padding: clamp(12px, 2.5%, 24px);
|
||||
border: 1px solid var(--r-line, var(--r-table-card-divider));
|
||||
border-radius: var(--r-radius, var(--r-table-card-radius));
|
||||
background: var(--r-surface, var(--r-table-card-surface));
|
||||
color: var(--r-text, var(--r-table-card-text));
|
||||
}
|
||||
|
||||
&__result {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@ -20,7 +29,7 @@
|
||||
gap: 10px 16px;
|
||||
|
||||
h2 {
|
||||
color: var(--r-text);
|
||||
color: var(--r-text, var(--r-table-card-text));
|
||||
font-size: 18px;
|
||||
font-weight: 650;
|
||||
line-height: 1.4;
|
||||
@ -62,13 +71,13 @@
|
||||
&:fullscreen {
|
||||
box-sizing: border-box;
|
||||
padding: 12px;
|
||||
background: var(--r-surface);
|
||||
background: var(--r-surface, var(--r-table-card-surface));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
&__footer,
|
||||
&__action {
|
||||
color: var(--r-text-secondary);
|
||||
color: var(--r-text-secondary, var(--r-table-card-muted));
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@ -148,16 +157,6 @@
|
||||
color: var(--r-text-secondary);
|
||||
}
|
||||
|
||||
.r-template--dark .r-table-search__submit.n-button {
|
||||
&,
|
||||
&:hover,
|
||||
&:focus-visible,
|
||||
&:active {
|
||||
color: var(--r-text);
|
||||
background-color: var(--r-surface-hover);
|
||||
}
|
||||
}
|
||||
|
||||
@container table-panel (inline-size < 600px) {
|
||||
.r-table__toolbar {
|
||||
gap: 4px;
|
||||
@ -191,6 +190,25 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
&__move {
|
||||
min-inline-size: 24px;
|
||||
min-block-size: 24px;
|
||||
border: 0;
|
||||
border-radius: var(--r-control-radius, 4px);
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--r-surface-hover);
|
||||
}
|
||||
|
||||
&[aria-disabled='true'] {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
}
|
||||
|
||||
&__check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@ -210,3 +228,8 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.r-table__context-row:focus-visible {
|
||||
outline: 2px solid var(--r-theme-primary-color, Highlight);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
@ -2,35 +2,30 @@ import { useUiServices } from '../../services'
|
||||
import en from './en-US.json'
|
||||
import zh from './zh-CN.json'
|
||||
|
||||
const labelsByLocale = {
|
||||
zh: { ...zh, fullscreen: '全屏', exitFullscreen: '退出全屏' },
|
||||
en: { ...en, fullscreen: 'Full screen', exitFullscreen: 'Exit full screen' },
|
||||
}
|
||||
|
||||
export function useTableLocale() {
|
||||
const { translate, locale } = useUiServices()
|
||||
|
||||
return {
|
||||
t: (key: string, params: Record<string, unknown> = {}) => {
|
||||
const chinese = locale?.() === 'zh-CN'
|
||||
const labels = chinese
|
||||
? { ...zh, fullscreen: '全屏', exitFullscreen: '退出全屏' }
|
||||
: {
|
||||
...en,
|
||||
fullscreen: 'Full screen',
|
||||
exitFullscreen: 'Exit full screen',
|
||||
}
|
||||
const translationKey =
|
||||
key === 'fullscreen' || key === 'exitFullscreen'
|
||||
? `headerTooltip.${key === 'fullscreen' ? 'FullScreen' : 'CancelFullScreen'}`
|
||||
: `table.${key}`
|
||||
const translated = translate?.(translationKey, params)
|
||||
|
||||
if (key === 'fullscreen' || key === 'exitFullscreen') {
|
||||
return (
|
||||
translate?.(
|
||||
`headerTooltip.${key === 'fullscreen' ? 'FullScreen' : 'CancelFullScreen'}`,
|
||||
) ?? labels[key]
|
||||
)
|
||||
}
|
||||
if (translated != null && translated !== translationKey) return translated
|
||||
|
||||
const labels =
|
||||
locale?.() === 'zh-CN' ? labelsByLocale.zh : labelsByLocale.en
|
||||
const label = labels[key as keyof typeof labels] ?? key
|
||||
|
||||
return (
|
||||
translate?.(`table.${key}`, params) ??
|
||||
label.replace(/\{(\w+)\}/g, (token, name: string) =>
|
||||
String(params[name] ?? token),
|
||||
)
|
||||
return label.replace(/\{(\w+)\}/g, (token, name: string) =>
|
||||
String(params[name] ?? token),
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
30
packages/ui/src/RTablePro/src/pagination.ts
Normal file
30
packages/ui/src/RTablePro/src/pagination.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { call } from '@ray-template/composables/vue/call'
|
||||
import type { PaginationProps } from 'naive-ui'
|
||||
|
||||
export const splitPaginationOptions = (options: PaginationProps = {}) => {
|
||||
const {
|
||||
onUpdatePage,
|
||||
'onUpdate:page': updatePage,
|
||||
onChange,
|
||||
onUpdatePageSize,
|
||||
'onUpdate:pageSize': updatePageSize,
|
||||
onPageSizeChange,
|
||||
...view
|
||||
} = options
|
||||
|
||||
return {
|
||||
view,
|
||||
notifyPage: (page: number) => {
|
||||
for (const handler of [onChange, onUpdatePage, updatePage])
|
||||
if (handler) call(handler, page)
|
||||
},
|
||||
notifyPageSize: (size: number) => {
|
||||
for (const handler of [
|
||||
onPageSizeChange,
|
||||
onUpdatePageSize,
|
||||
updatePageSize,
|
||||
])
|
||||
if (handler) call(handler, size)
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -100,22 +100,130 @@ export const buildPrintableTable = (
|
||||
return table
|
||||
}
|
||||
|
||||
const omittedElements = 'script, iframe, object, embed, link, base, meta'
|
||||
|
||||
const cloneRegion = (target: HTMLElement) => {
|
||||
if (target.matches(omittedElements)) return null
|
||||
|
||||
const clone = target.cloneNode(true) as HTMLElement
|
||||
const sources = [target, ...target.querySelectorAll('*')]
|
||||
const copies = [clone, ...clone.querySelectorAll('*')]
|
||||
|
||||
clone
|
||||
.querySelectorAll('script, iframe, object, embed, link, base, meta')
|
||||
.forEach((node) => node.remove())
|
||||
for (const [index, node] of copies.entries()) {
|
||||
if (node.matches(omittedElements)) {
|
||||
node.remove()
|
||||
continue
|
||||
}
|
||||
|
||||
for (const node of [clone, ...clone.querySelectorAll('*')]) {
|
||||
for (const name of node.getAttributeNames()) {
|
||||
if (name.startsWith('on')) node.removeAttribute(name)
|
||||
}
|
||||
|
||||
const source = sources[index]
|
||||
|
||||
if (
|
||||
source instanceof HTMLInputElement &&
|
||||
node instanceof HTMLInputElement
|
||||
) {
|
||||
node.value =
|
||||
source.type === 'password' || source.type === 'file' ? '' : source.value
|
||||
node.defaultValue = node.value
|
||||
node.checked = source.checked
|
||||
node.indeterminate = source.indeterminate
|
||||
} else if (
|
||||
source instanceof HTMLTextAreaElement &&
|
||||
node instanceof HTMLTextAreaElement
|
||||
) {
|
||||
node.value = source.value
|
||||
node.defaultValue = source.value
|
||||
} else if (
|
||||
source instanceof HTMLOptionElement &&
|
||||
node instanceof HTMLOptionElement
|
||||
) {
|
||||
node.selected = source.selected
|
||||
node.defaultSelected = source.selected
|
||||
} else if (
|
||||
source instanceof HTMLCanvasElement &&
|
||||
node instanceof HTMLCanvasElement
|
||||
) {
|
||||
try {
|
||||
node.getContext('2d')?.drawImage(source, 0, 0)
|
||||
} catch {
|
||||
// 无法读取的画布仍保留尺寸和替代内容。
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return clone
|
||||
}
|
||||
|
||||
const copyStyleContext = (source: HTMLElement, destination: HTMLElement) => {
|
||||
destination.className = source.className
|
||||
destination.dir = source.dir
|
||||
|
||||
for (const name of Array.from(source.style)) {
|
||||
if (name.startsWith('--'))
|
||||
destination.style.setProperty(name, source.style.getPropertyValue(name))
|
||||
}
|
||||
}
|
||||
|
||||
const copyPageStyles = (source: Document, destination: Document) => {
|
||||
const base = destination.createElement('base')
|
||||
|
||||
base.href = source.baseURI
|
||||
destination.head.append(base)
|
||||
copyStyleContext(source.documentElement, destination.documentElement)
|
||||
copyStyleContext(source.body, destination.body)
|
||||
|
||||
const links: Promise<void>[] = []
|
||||
|
||||
for (const stylesheet of source.querySelectorAll<
|
||||
HTMLStyleElement | HTMLLinkElement
|
||||
>('style, link[rel~="stylesheet"]')) {
|
||||
if (stylesheet.sheet?.disabled) continue
|
||||
|
||||
if (stylesheet.tagName === 'LINK') {
|
||||
const link = stylesheet as HTMLLinkElement
|
||||
|
||||
if (link.disabled) continue
|
||||
|
||||
const copy = destination.createElement('link')
|
||||
|
||||
copy.rel = 'stylesheet'
|
||||
copy.href = link.href
|
||||
copy.media = link.media
|
||||
|
||||
if (link.crossOrigin !== null) copy.crossOrigin = link.crossOrigin
|
||||
|
||||
if (link.integrity) copy.integrity = link.integrity
|
||||
|
||||
if (link.referrerPolicy) copy.referrerPolicy = link.referrerPolicy
|
||||
|
||||
links.push(
|
||||
new Promise<void>((resolve) => {
|
||||
copy.onload = () => resolve()
|
||||
copy.onerror = () => resolve()
|
||||
}),
|
||||
)
|
||||
destination.head.append(copy)
|
||||
} else {
|
||||
const style = stylesheet as HTMLStyleElement
|
||||
const copy = destination.createElement('style')
|
||||
|
||||
copy.media = style.media
|
||||
|
||||
if (style.nonce) copy.nonce = style.nonce
|
||||
|
||||
copy.textContent = style.sheet
|
||||
? Array.from(style.sheet.cssRules, (rule) => rule.cssText).join('\n')
|
||||
: style.textContent
|
||||
destination.head.append(copy)
|
||||
}
|
||||
}
|
||||
|
||||
return links
|
||||
}
|
||||
|
||||
export const resolvePrintContent = (
|
||||
options: TableProPrintOptions,
|
||||
defaultTable: () => HTMLElement | null,
|
||||
@ -130,7 +238,11 @@ export const resolvePrintContent = (
|
||||
export const printTableContent = async (
|
||||
content: HTMLElement,
|
||||
options: TableProPrintOptions,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
if (signal?.aborted) return false
|
||||
|
||||
const source = content.ownerDocument
|
||||
const frame = document.createElement('iframe')
|
||||
|
||||
frame.tabIndex = -1
|
||||
@ -152,25 +264,50 @@ export const printTableContent = async (
|
||||
|
||||
if (!doc || !view) throw new Error('Print document is unavailable.')
|
||||
|
||||
doc.documentElement.lang = document.documentElement.lang
|
||||
doc.documentElement.lang = source.documentElement.lang
|
||||
doc.title = options.title ?? ''
|
||||
const links =
|
||||
options.target != null && options.includePageStyles !== false
|
||||
? copyPageStyles(source, doc)
|
||||
: []
|
||||
const style = doc.createElement('style')
|
||||
|
||||
style.textContent = printStyles + (options.style ?? '')
|
||||
doc.head.append(style)
|
||||
doc.body.append(content)
|
||||
|
||||
const images = [...doc.images]
|
||||
let assetTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const cancelAssets = Promise.withResolvers<void>()
|
||||
const stopWaiting = () => cancelAssets.resolve()
|
||||
|
||||
if (images.length) {
|
||||
let imageTimer: ReturnType<typeof setTimeout> | undefined
|
||||
signal?.addEventListener('abort', stopWaiting, { once: true })
|
||||
|
||||
try {
|
||||
const images = Array.from(doc.querySelectorAll('img'), (img) => {
|
||||
img.loading = 'eager'
|
||||
|
||||
return img.decode()
|
||||
})
|
||||
const stylesAndFonts = Promise.all(links).then(async () => {
|
||||
await doc.fonts?.ready
|
||||
})
|
||||
|
||||
await Promise.race([
|
||||
Promise.allSettled(images.map((img) => img.decode())),
|
||||
Promise.allSettled([...images, stylesAndFonts]),
|
||||
cancelAssets.promise,
|
||||
new Promise<void>((resolve) => {
|
||||
imageTimer = setTimeout(resolve, 1500)
|
||||
assetTimer = setTimeout(resolve, 2000)
|
||||
}),
|
||||
]).finally(() => clearTimeout(imageTimer))
|
||||
])
|
||||
} finally {
|
||||
clearTimeout(assetTimer)
|
||||
signal?.removeEventListener('abort', stopWaiting)
|
||||
}
|
||||
|
||||
if (signal?.aborted) {
|
||||
cleanup()
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
view.addEventListener('afterprint', cleanup, { once: true })
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
import { omit, pick } from 'lodash-es'
|
||||
import { dataTableProps } from 'naive-ui'
|
||||
import type { DataTableColumn, DataTableInst, DropdownOption } from 'naive-ui'
|
||||
import type { PropType, VNode } from 'vue'
|
||||
import type { TableProPrintOptions } from './types'
|
||||
import type { ExtractPropTypes, PropType, VNode } from 'vue'
|
||||
import type { TableProPrintOptions, TableProRowContext } from './types'
|
||||
|
||||
const props = {
|
||||
...dataTableProps,
|
||||
const panelControls = {
|
||||
bare: Boolean,
|
||||
autoHeight: Boolean,
|
||||
tool: { type: Boolean, default: true },
|
||||
@ -14,13 +14,67 @@ const props = {
|
||||
>,
|
||||
printTableOptions: Object as PropType<TableProPrintOptions>,
|
||||
columnStateKey: String,
|
||||
onResetColumnLayout: Function as PropType<() => void>,
|
||||
contextMenuOptions: Array as PropType<DropdownOption[]>,
|
||||
onContextMenuClick: Function as PropType<
|
||||
(key: string | number, option: DropdownOption) => void
|
||||
(
|
||||
key: string | number,
|
||||
option: DropdownOption,
|
||||
context: TableProRowContext,
|
||||
) => void
|
||||
>,
|
||||
'onUpdate:columns': Function as PropType<
|
||||
(columns: DataTableColumn[]) => void
|
||||
>,
|
||||
} as const
|
||||
|
||||
export default props
|
||||
export const tablePanelProps = {
|
||||
...dataTableProps,
|
||||
...panelControls,
|
||||
rowActionsDisabled: Boolean,
|
||||
}
|
||||
|
||||
const keysOf = <T extends object>(value: T) => Object.keys(value) as (keyof T)[]
|
||||
|
||||
const nativeTableKeys = keysOf(
|
||||
omit(dataTableProps, [
|
||||
'columns',
|
||||
'pagination',
|
||||
'rowProps',
|
||||
'size',
|
||||
'striped',
|
||||
'bordered',
|
||||
'flexHeight',
|
||||
]),
|
||||
)
|
||||
|
||||
export const toNativeTableProps = (
|
||||
props: ExtractPropTypes<typeof tablePanelProps>,
|
||||
) => pick(props, nativeTableKeys)
|
||||
|
||||
const managedPanelKeys = [
|
||||
'data',
|
||||
'pagination',
|
||||
'remote',
|
||||
'loading',
|
||||
'rowActionsDisabled',
|
||||
'onUpdatePage',
|
||||
'onUpdate:page',
|
||||
'onPageChange',
|
||||
'onUpdatePageSize',
|
||||
'onUpdate:pageSize',
|
||||
'onPageSizeChange',
|
||||
] as const
|
||||
|
||||
const panelKeys = keysOf(omit(tablePanelProps, managedPanelKeys))
|
||||
|
||||
export const toPanelProps = <
|
||||
Props extends Pick<
|
||||
ExtractPropTypes<typeof tablePanelProps>,
|
||||
(typeof panelKeys)[number]
|
||||
>,
|
||||
>(
|
||||
props: Props,
|
||||
) => pick(props, panelKeys)
|
||||
|
||||
export default omit(tablePanelProps, ['rowActionsDisabled'])
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { get } from 'lodash-es'
|
||||
import { getLeafColumns } from './columns'
|
||||
import type {
|
||||
TableProColumn,
|
||||
@ -181,10 +182,30 @@ const sameValue = (
|
||||
left.length === right.length &&
|
||||
left.every((value, index) => value === right[index]))
|
||||
|
||||
export const createSearchDependencies = (
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
) => {
|
||||
const dependents = new Map<string, string[]>()
|
||||
|
||||
for (const field of fields) {
|
||||
if (!field.type) continue
|
||||
|
||||
for (const key of field.dependsOn ?? []) {
|
||||
const group = dependents.get(key)
|
||||
|
||||
if (group) group.push(field.key)
|
||||
else dependents.set(key, [field.key])
|
||||
}
|
||||
}
|
||||
|
||||
return dependents
|
||||
}
|
||||
|
||||
export function patchSearchValues(
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
previous: TableProSearchValues,
|
||||
patch: TableProSearchValues,
|
||||
dependents: ReadonlyMap<string, readonly string[]>,
|
||||
) {
|
||||
const next = pickSearchValues(fields, { ...previous, ...patch })
|
||||
const changed = new Set(
|
||||
@ -197,18 +218,11 @@ export function patchSearchValues(
|
||||
|
||||
// 依赖可以跨多级,遍历时把本次被清除的字段也加入变更集合。
|
||||
for (const key of changed) {
|
||||
for (const field of fields) {
|
||||
if (
|
||||
!field.type ||
|
||||
changed.has(field.key) ||
|
||||
Object.hasOwn(patch, field.key)
|
||||
)
|
||||
continue
|
||||
for (const dependent of dependents.get(key) ?? []) {
|
||||
if (changed.has(dependent) || Object.hasOwn(patch, dependent)) continue
|
||||
|
||||
if (!field.dependsOn?.includes(key)) continue
|
||||
|
||||
next[field.key] = null
|
||||
changed.add(field.key)
|
||||
next[dependent] = null
|
||||
changed.add(dependent)
|
||||
}
|
||||
}
|
||||
|
||||
@ -230,14 +244,33 @@ export function sameSearchField(
|
||||
)
|
||||
}
|
||||
|
||||
export function sameSearchBehavior(
|
||||
field: TableProSearchFieldConfig,
|
||||
previous: TableProSearchFieldConfig | undefined,
|
||||
) {
|
||||
if (!sameSearchField(field, previous)) return false
|
||||
|
||||
if (!field.type || !previous?.type) return true
|
||||
|
||||
return (
|
||||
field.visible === previous.visible &&
|
||||
field.getValue === previous.getValue &&
|
||||
field.matches === previous.matches &&
|
||||
field.transform === previous.transform
|
||||
)
|
||||
}
|
||||
|
||||
export const visibleSearchFields = (
|
||||
fields: readonly TableProSearchFieldConfig[],
|
||||
values: TableProSearchValues,
|
||||
) => fields.filter((field) => isSearchFieldVisible(field, values))
|
||||
|
||||
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'
|
||||
@ -288,17 +321,20 @@ export function createSearchPredicate(
|
||||
|
||||
const field = fieldsByKey.get(key)
|
||||
const read = (row: Row) =>
|
||||
field?.type && field.getValue ? field.getValue(row) : row[key]
|
||||
field?.type && field.getValue ? field.getValue(row) : get(row, key)
|
||||
|
||||
return [
|
||||
(row: Row) => {
|
||||
const cell = read(row)
|
||||
if (field?.type && field.matches) {
|
||||
const matches = field.matches
|
||||
|
||||
if (field?.type && field.matches)
|
||||
return field.matches(cell, value as never, row)
|
||||
return [(row: Row) => matches(read(row), value as never, row)]
|
||||
}
|
||||
|
||||
if (field?.type === 'dateRange' || field?.type === 'datetimeRange') {
|
||||
const [from, to] = value as readonly (string | number)[]
|
||||
if (field?.type === 'dateRange' || field?.type === 'datetimeRange') {
|
||||
const [from, to] = value as readonly (string | number)[]
|
||||
|
||||
return [
|
||||
(row: Row) => {
|
||||
const cell = read(row)
|
||||
|
||||
return (
|
||||
(typeof cell === 'string' || typeof cell === 'number') &&
|
||||
@ -306,24 +342,39 @@ export function createSearchPredicate(
|
||||
cell >= from &&
|
||||
cell <= to
|
||||
)
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const selected = new Set<unknown>(value)
|
||||
|
||||
return [
|
||||
(row: Row) => {
|
||||
const cell = read(row)
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return Array.isArray(cell)
|
||||
? cell.some((item: unknown) => value.includes(item))
|
||||
: value.includes(cell)
|
||||
}
|
||||
? cell.some((item: unknown) => selected.has(item))
|
||||
: selected.has(cell)
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
return typeof value === 'string' &&
|
||||
(!field
|
||||
? true
|
||||
: field.type === 'text' || (!field.type && !field.options))
|
||||
? String(cell ?? '')
|
||||
.toLowerCase()
|
||||
.includes(value.toLowerCase())
|
||||
: cell === value
|
||||
},
|
||||
]
|
||||
if (
|
||||
typeof value === 'string' &&
|
||||
(!field || field.type === 'text' || (!field.type && !field.options))
|
||||
) {
|
||||
const needle = value.toLowerCase()
|
||||
|
||||
return [
|
||||
(row: Row) =>
|
||||
String(read(row) ?? '')
|
||||
.toLowerCase()
|
||||
.includes(needle),
|
||||
]
|
||||
}
|
||||
|
||||
return [(row: Row) => read(row) === value]
|
||||
})
|
||||
|
||||
return checks.length
|
||||
|
||||
@ -3,6 +3,7 @@ import type {
|
||||
CascaderProps,
|
||||
DataTableInst,
|
||||
DataTableProps,
|
||||
DataTableRowData,
|
||||
DatePickerProps,
|
||||
FormItemRule,
|
||||
InputNumberProps,
|
||||
@ -19,6 +20,7 @@ export interface TableProPrintOptions {
|
||||
target?: BasicTarget<HTMLElement>
|
||||
title?: string
|
||||
style?: string
|
||||
includePageStyles?: boolean
|
||||
formatHeader?: (column: LeafColumn) => string
|
||||
formatCell?: (
|
||||
value: unknown,
|
||||
@ -27,6 +29,11 @@ export interface TableProPrintOptions {
|
||||
) => string
|
||||
}
|
||||
|
||||
export interface TableProRowContext {
|
||||
row: Readonly<DataTableRowData>
|
||||
index: number
|
||||
}
|
||||
|
||||
export interface TablePanelInst {
|
||||
getTableInstance: () => DataTableInst | null
|
||||
print: (options?: TableProPrintOptions) => Promise<boolean>
|
||||
|
||||
154
packages/ui/src/RTablePro/src/useTableRequest.ts
Normal file
154
packages/ui/src/RTablePro/src/useTableRequest.ts
Normal file
@ -0,0 +1,154 @@
|
||||
import { cloneDeep, isEqual } from 'lodash-es'
|
||||
import { computed, onBeforeUnmount, ref, shallowRef } from 'vue'
|
||||
import type {
|
||||
TableProParams,
|
||||
TableProQueryState,
|
||||
TableProRequest,
|
||||
TableProResult,
|
||||
} from './types'
|
||||
|
||||
type RequestScope = { request: TableProRequest; filters: TableProParams }
|
||||
type Paging = { page: number; pageSize: number }
|
||||
|
||||
export function useTableRequest({
|
||||
request,
|
||||
filters,
|
||||
paging,
|
||||
updatePage,
|
||||
reportError,
|
||||
}: {
|
||||
request: () => TableProRequest | undefined
|
||||
filters: () => TableProParams
|
||||
paging: () => Paging | undefined
|
||||
updatePage: (page: number) => void
|
||||
reportError: (error: unknown) => void
|
||||
}) {
|
||||
const phase = ref<'idle' | 'loading' | 'failed'>('idle')
|
||||
const result = shallowRef<{
|
||||
scope: RequestScope
|
||||
paging: Paging | undefined
|
||||
response: TableProResult
|
||||
}>()
|
||||
const scope = computed<RequestScope | undefined>((previous) => {
|
||||
const load = request()
|
||||
|
||||
if (!load) return
|
||||
|
||||
const values = filters()
|
||||
|
||||
delete values.page
|
||||
delete values.pageSize
|
||||
|
||||
return previous?.request === load && isEqual(previous.filters, values)
|
||||
? previous
|
||||
: { request: load, filters: cloneDeep(values) }
|
||||
})
|
||||
|
||||
const scopedResult = computed(() =>
|
||||
result.value?.scope === scope.value ? result.value : void 0,
|
||||
)
|
||||
const activeResult = computed(() => {
|
||||
const current = scopedResult.value
|
||||
|
||||
return current && isEqual(current.paging, paging())
|
||||
? current.response
|
||||
: void 0
|
||||
})
|
||||
const total = computed(() => scopedResult.value?.response.total ?? null)
|
||||
const state = computed<TableProQueryState | null>(() => {
|
||||
if (!request()) return null
|
||||
|
||||
const currentPage = paging()
|
||||
|
||||
return Object.freeze({
|
||||
loading: phase.value === 'loading',
|
||||
failed: phase.value === 'failed',
|
||||
page: currentPage?.page ?? null,
|
||||
pageSize: currentPage?.pageSize ?? null,
|
||||
total: total.value,
|
||||
})
|
||||
})
|
||||
let pending: AbortController | undefined
|
||||
|
||||
const reload = async () => {
|
||||
pending?.abort()
|
||||
const currentScope = scope.value
|
||||
|
||||
// 总数可以跨页复用;请求源或筛选范围改变时,之前的结果全部失效。
|
||||
if (result.value?.scope !== currentScope) result.value = void 0
|
||||
|
||||
if (!currentScope) {
|
||||
pending = void 0
|
||||
phase.value = 'idle'
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const currentPaging = paging()
|
||||
const current = new AbortController()
|
||||
const isCurrent = () =>
|
||||
!current.signal.aborted &&
|
||||
currentScope === scope.value &&
|
||||
isEqual(currentPaging, paging())
|
||||
|
||||
pending = current
|
||||
phase.value = 'loading'
|
||||
|
||||
try {
|
||||
const response = await currentScope.request(
|
||||
cloneDeep({ ...currentScope.filters, ...currentPaging }),
|
||||
current.signal,
|
||||
)
|
||||
|
||||
if (!isCurrent()) return
|
||||
|
||||
if (
|
||||
!Array.isArray(response.data) ||
|
||||
!Number.isSafeInteger(response.total) ||
|
||||
response.total < 0
|
||||
) {
|
||||
throw new TypeError(
|
||||
'[RTablePro] Expected { data: Row[], total: number }.',
|
||||
)
|
||||
}
|
||||
|
||||
if (currentPaging) {
|
||||
const lastPage = Math.max(
|
||||
1,
|
||||
Math.ceil(response.total / currentPaging.pageSize),
|
||||
)
|
||||
|
||||
if (currentPaging.page > lastPage) {
|
||||
updatePage(lastPage)
|
||||
|
||||
if (response.total) {
|
||||
await reload()
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result.value = { scope: currentScope, paging: paging(), response }
|
||||
} catch (error) {
|
||||
if (!isCurrent()) return
|
||||
|
||||
result.value = void 0
|
||||
phase.value = 'failed'
|
||||
reportError(error)
|
||||
} finally {
|
||||
if (pending === current) {
|
||||
pending = void 0
|
||||
|
||||
if (phase.value === 'loading') phase.value = 'idle'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
pending?.abort()
|
||||
pending = void 0
|
||||
})
|
||||
|
||||
return { reload, activeResult, total, phase, state }
|
||||
}
|
||||
@ -1,8 +1,8 @@
|
||||
import { onScopeDispose, shallowRef, watch } from 'vue'
|
||||
import { computed, onScopeDispose, shallowRef, watch } from 'vue'
|
||||
import {
|
||||
copySearchValues,
|
||||
createSearchDependencies,
|
||||
initialSearchValues,
|
||||
normalizeSearchValues,
|
||||
patchSearchValues,
|
||||
pickSearchValues,
|
||||
} from './search'
|
||||
@ -18,6 +18,7 @@ export function useTableSearch(
|
||||
options: () => TableProSearchOptions | undefined,
|
||||
validate: (isCurrent: () => boolean) => true | Promise<boolean>,
|
||||
restoreValidation: () => void,
|
||||
reportError: (error: unknown) => false,
|
||||
commit: (
|
||||
values: TableProSearchValues,
|
||||
reason: TableProSearchSubmission['reason'],
|
||||
@ -26,6 +27,7 @@ export function useTableSearch(
|
||||
const draft = shallowRef<TableProSearchValues>(
|
||||
initialSearchValues(fields(), options()),
|
||||
)
|
||||
const dependents = computed(() => createSearchDependencies(fields()))
|
||||
let revision = 0
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
@ -44,20 +46,27 @@ export function useTableSearch(
|
||||
const submit = async () => {
|
||||
cancelPending()
|
||||
const current = revision
|
||||
const values = normalizeSearchValues(fields(), draft.value)
|
||||
|
||||
const values = draft.value
|
||||
const isCurrent = () => current === revision
|
||||
const validation = validate(isCurrent)
|
||||
|
||||
if (validation !== true && !(await validation)) return false
|
||||
try {
|
||||
const validation = validate(isCurrent)
|
||||
|
||||
if (!isCurrent()) return false
|
||||
if (validation !== true && !(await validation)) return false
|
||||
|
||||
return commit(values, 'submit')
|
||||
return isCurrent() ? await commit(values, 'submit') : false
|
||||
} catch (error) {
|
||||
return isCurrent() ? reportError(error) : false
|
||||
}
|
||||
}
|
||||
|
||||
const setValues = (values: TableProSearchValues) => {
|
||||
const next = patchSearchValues(fields(), draft.value, values)
|
||||
const next = patchSearchValues(
|
||||
fields(),
|
||||
draft.value,
|
||||
values,
|
||||
dependents.value,
|
||||
)
|
||||
|
||||
if (next === draft.value) return
|
||||
|
||||
@ -74,7 +83,7 @@ export function useTableSearch(
|
||||
draft.value = initialSearchValues(fields(), options())
|
||||
restoreValidation()
|
||||
|
||||
return commit(normalizeSearchValues(fields(), draft.value), 'reset')
|
||||
return commit(draft.value, 'reset')
|
||||
}
|
||||
|
||||
const reconcile = (retainedKeys: ReadonlySet<string>) => {
|
||||
|
||||
@ -52,6 +52,9 @@
|
||||
"contextAction": "触发行右键菜单操作",
|
||||
"firstPage": "回到第 1 页",
|
||||
"twentyRows": "每页 20 条",
|
||||
"customFooter": "示例:右键表格行可打开自定义菜单。",
|
||||
"pinNeedsWidth": "固定列需要数字列宽"
|
||||
"customFooter": "右键点击表格行,或聚焦该行后按 Shift+F10 打开菜单。",
|
||||
"pinNeedsWidth": "固定列需要数字列宽",
|
||||
"moveColumnUp": "上移「{column}」",
|
||||
"moveColumnDown": "下移「{column}」",
|
||||
"resetColumnLayout": "恢复列布局"
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user