From 8079e2d4f578fbb4e808b1cb56b16a2641154697 Mon Sep 17 00:00:00 2001 From: XiaoDaiGua-Ray <51957438+XiaoDaiGua-Ray@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:04:49 +0800 Subject: [PATCH] feat(table)!: consolidate TablePro and refresh table demos Group table demos and share their dataset across the development Mock API and static previews. Restore focus after maximizing content and add column preferences, printing, and CSV export to TablePro. BREAKING CHANGE: RTable and the legacy registration hooks are removed. Use RTablePro props, slots, or the exposed instance instead. --- __test__/components/table-pro-columns.spec.ts | 211 +++++++ __test__/components/table-pro-exports.spec.ts | 99 ++++ __test__/components/table-pro.spec.ts | 320 +++++++++++ __test__/layout/slots.spec.ts | 35 +- __test__/mock/database.spec.ts | 57 +- docs/architecture.md | 2 +- docs/toolchain-upgrade.md | 1 + docs/ui-design.md | 1 + harness/scopes.json | 2 +- mock/demo/person.mock.ts | 50 +- mock/shared/database.ts | 19 - mock/shared/utils.ts | 57 -- src/api/demo/mock/person.ts | 38 +- src/components/README.md | 2 +- src/components/base/RTable/index.ts | 13 - src/components/base/RTable/src/Table.tsx | 391 ------------- .../base/RTable/src/components/C.tsx | 267 --------- .../base/RTable/src/components/Fullscreen.tsx | 39 -- .../base/RTable/src/components/Print.tsx | 50 -- .../base/RTable/src/components/Props.tsx | 80 --- .../base/RTable/src/components/Size.tsx | 66 --- .../RTable/src/hooks/useCheckedRowKeys.ts | 361 ------------ .../base/RTable/src/hooks/useTable.ts | 188 ------- src/components/base/RTable/src/index.scss | 16 - src/components/base/RTable/src/props.ts | 252 --------- src/components/base/RTable/src/shared.ts | 15 - src/components/base/RTable/src/types.ts | 88 --- src/components/base/RTablePro/README.md | 66 +++ src/components/base/RTablePro/index.ts | 9 + .../base/RTablePro/src/TablePanel.tsx | 291 ++++++++++ .../base/RTablePro/src/TablePro.tsx | 297 ++++++++++ src/components/base/RTablePro/src/columns.ts | 201 +++++++ .../base/RTablePro/src/components/C.tsx | 191 +++++++ .../RTablePro/src/components/Fullscreen.tsx | 25 + .../base/RTablePro/src/components/Props.tsx | 28 + .../base/RTablePro/src/components/Search.tsx | 87 +++ .../base/RTablePro/src/components/Size.tsx | 32 ++ .../RTablePro/src/components/ToolButton.tsx | 34 ++ src/components/base/RTablePro/src/csv.ts | 63 +++ src/components/base/RTablePro/src/index.scss | 165 ++++++ src/components/base/RTablePro/src/printing.ts | 187 ++++++ src/components/base/RTablePro/src/props.ts | 26 + src/components/base/RTablePro/src/shared.ts | 8 + src/components/base/RTablePro/src/types.ts | 46 ++ src/components/index.ts | 4 +- src/components/pro/RTablePro/index.ts | 24 - src/components/pro/RTablePro/src/TablePro.tsx | 188 ------- .../pro/RTablePro/src/hooks/useTablePro.ts | 271 --------- src/components/pro/RTablePro/src/props.ts | 136 ----- src/components/pro/RTablePro/src/types.ts | 247 -------- src/demo-data/people.ts | 66 +++ src/layout/components/MenuTag/index.tsx | 3 +- src/layout/components/SiderBar/index.tsx | 8 +- src/layout/components/SiderBar/shared.ts | 4 +- src/layout/default/ContentWrapper/index.scss | 7 - src/layout/default/ContentWrapper/index.tsx | 35 +- src/layout/index.scss | 51 +- src/layout/index.tsx | 71 ++- src/locales/lang/en-US/layout.json | 2 + src/locales/lang/en-US/menu.json | 11 +- src/locales/lang/en-US/table.json | 51 ++ src/locales/lang/zh-CN/layout.json | 2 + src/locales/lang/zh-CN/menu.json | 9 +- src/locales/lang/zh-CN/table.json | 51 ++ src/router/modules/demo/mock.ts | 19 - src/router/modules/demo/table-auto-height.ts | 19 - src/router/modules/demo/table-pro.ts | 18 - src/router/modules/demo/table.ts | 18 - src/router/modules/demo/tables.ts | 51 ++ src/router/routes.ts | 5 + src/views/demo/mock-demo/index.tsx | 168 ------ .../router-demo/router-demo-home/index.tsx | 4 +- src/views/demo/table-auto-height.tsx | 216 ------- src/views/demo/table-pro-demo.tsx | 532 ------------------ src/views/demo/table/index.tsx | 382 ------------- src/views/demo/tables/auto-height.tsx | 57 ++ src/views/demo/tables/basic.tsx | 28 + src/views/demo/tables/columns.tsx | 49 ++ src/views/demo/tables/custom.tsx | 90 +++ src/views/demo/tables/people.ts | 18 + src/views/demo/tables/printing.tsx | 54 ++ src/views/demo/tables/remote.tsx | 110 ++++ vite.plugin.config.ts | 2 +- 83 files changed, 3282 insertions(+), 4275 deletions(-) create mode 100644 __test__/components/table-pro-columns.spec.ts create mode 100644 __test__/components/table-pro-exports.spec.ts create mode 100644 __test__/components/table-pro.spec.ts delete mode 100644 mock/shared/database.ts delete mode 100644 mock/shared/utils.ts delete mode 100644 src/components/base/RTable/index.ts delete mode 100644 src/components/base/RTable/src/Table.tsx delete mode 100644 src/components/base/RTable/src/components/C.tsx delete mode 100644 src/components/base/RTable/src/components/Fullscreen.tsx delete mode 100644 src/components/base/RTable/src/components/Print.tsx delete mode 100644 src/components/base/RTable/src/components/Props.tsx delete mode 100644 src/components/base/RTable/src/components/Size.tsx delete mode 100644 src/components/base/RTable/src/hooks/useCheckedRowKeys.ts delete mode 100644 src/components/base/RTable/src/hooks/useTable.ts delete mode 100644 src/components/base/RTable/src/index.scss delete mode 100644 src/components/base/RTable/src/props.ts delete mode 100644 src/components/base/RTable/src/shared.ts delete mode 100644 src/components/base/RTable/src/types.ts create mode 100644 src/components/base/RTablePro/README.md create mode 100644 src/components/base/RTablePro/index.ts create mode 100644 src/components/base/RTablePro/src/TablePanel.tsx create mode 100644 src/components/base/RTablePro/src/TablePro.tsx create mode 100644 src/components/base/RTablePro/src/columns.ts create mode 100644 src/components/base/RTablePro/src/components/C.tsx create mode 100644 src/components/base/RTablePro/src/components/Fullscreen.tsx create mode 100644 src/components/base/RTablePro/src/components/Props.tsx create mode 100644 src/components/base/RTablePro/src/components/Search.tsx create mode 100644 src/components/base/RTablePro/src/components/Size.tsx create mode 100644 src/components/base/RTablePro/src/components/ToolButton.tsx create mode 100644 src/components/base/RTablePro/src/csv.ts create mode 100644 src/components/base/RTablePro/src/index.scss create mode 100644 src/components/base/RTablePro/src/printing.ts create mode 100644 src/components/base/RTablePro/src/props.ts create mode 100644 src/components/base/RTablePro/src/shared.ts create mode 100644 src/components/base/RTablePro/src/types.ts delete mode 100644 src/components/pro/RTablePro/index.ts delete mode 100644 src/components/pro/RTablePro/src/TablePro.tsx delete mode 100644 src/components/pro/RTablePro/src/hooks/useTablePro.ts delete mode 100644 src/components/pro/RTablePro/src/props.ts delete mode 100644 src/components/pro/RTablePro/src/types.ts create mode 100644 src/demo-data/people.ts create mode 100644 src/locales/lang/en-US/table.json create mode 100644 src/locales/lang/zh-CN/table.json delete mode 100644 src/router/modules/demo/mock.ts delete mode 100644 src/router/modules/demo/table-auto-height.ts delete mode 100644 src/router/modules/demo/table-pro.ts delete mode 100644 src/router/modules/demo/table.ts create mode 100644 src/router/modules/demo/tables.ts delete mode 100644 src/views/demo/mock-demo/index.tsx delete mode 100644 src/views/demo/table-auto-height.tsx delete mode 100644 src/views/demo/table-pro-demo.tsx delete mode 100644 src/views/demo/table/index.tsx create mode 100644 src/views/demo/tables/auto-height.tsx create mode 100644 src/views/demo/tables/basic.tsx create mode 100644 src/views/demo/tables/columns.tsx create mode 100644 src/views/demo/tables/custom.tsx create mode 100644 src/views/demo/tables/people.ts create mode 100644 src/views/demo/tables/printing.tsx create mode 100644 src/views/demo/tables/remote.tsx diff --git a/__test__/components/table-pro-columns.spec.ts b/__test__/components/table-pro-columns.spec.ts new file mode 100644 index 00000000..a1561aa6 --- /dev/null +++ b/__test__/components/table-pro-columns.spec.ts @@ -0,0 +1,211 @@ +import { RTablePro } from '@/components/base/RTablePro' +import { useColumnVisibility } from '@/components/base/RTablePro/src/columns' +import ColumnSettings from '@/components/base/RTablePro/src/components/C' +import { prefixCacheKey } from '@/utils/app/prefix-cache-key' +import { mount } from '@vue/test-utils' +import { NDataTable, NTree } from 'naive-ui' +import type { DataTableColumn } from 'naive-ui' +import { effectScope, nextTick, ref, shallowRef } from 'vue' + +const name = { key: 'name', title: 'Name' } +const email = { key: 'email', title: 'Email' } +const region = { key: 'region', title: 'Region' } +const group = { key: 'contact', title: 'Contact', children: [name, email] } +const selection = { type: 'selection' as const } +const columns = shallowRef([selection, group, region]) +const cacheKey = (key: string) => prefixCacheKey(`table-pro:columns:v1:${key}`) + +afterEach(() => { + localStorage.clear() + columns.value = [selection, group, region] +}) + +it('stores only hidden leaf keys, restores them on mount, and isolates separate keys', () => { + const scope = effectScope() + const second = effectScope() + const key = ref('directory') + + try { + const first = scope.run(() => useColumnVisibility(columns, key))! + + expect(first.visibleColumns.value).toBe(columns.value) + expect(localStorage.length).toBe(0) + first.setColumnVisible('email', false) + expect(first.visibleColumns.value).toEqual([ + selection, + { ...group, children: [name] }, + region, + ]) + expect(JSON.parse(localStorage.getItem(cacheKey('directory'))!)).toEqual([ + 'email', + ]) + + const restored = second.run(() => useColumnVisibility(columns, key))! + const other = second.run(() => useColumnVisibility(columns, ref('other')))! + + expect(restored.visibleColumns.value).toEqual(first.visibleColumns.value) + expect(other.visibleColumns.value).toBe(columns.value) + restored.resetColumns() + expect(localStorage.getItem(cacheKey('directory'))).toBeNull() + } finally { + scope.stop() + second.stop() + } +}) + +it('ignores stale keys, shows new columns, and keeps one data column visible', async () => { + localStorage.setItem( + cacheKey('directory'), + JSON.stringify(['name', 'region', 'removed', false]), + ) + const scope = effectScope() + + try { + const state = scope.run(() => + useColumnVisibility(columns, ref('directory')), + )! + + expect(state.hiddenKeys.value).toEqual(new Set(['name', 'region'])) + state.setColumnVisible('email', false) + expect(state.visibleColumns.value).toEqual([ + selection, + { ...group, children: [email] }, + ]) + + columns.value = [selection, name, { key: 'created', title: 'Created' }] + await nextTick() + expect(state.visibleColumns.value).toEqual([ + selection, + { key: 'created', title: 'Created' }, + ]) + + columns.value = [selection, name] + expect(state.visibleColumns.value).toEqual([selection, name]) + } finally { + scope.stop() + } +}) + +it('updates visibility without touching storage when no key is configured', () => { + const scope = effectScope() + + try { + const state = scope.run(() => useColumnVisibility(columns, ref()))! + + state.setColumnVisible('email', false) + expect(state.hiddenKeys.value.has('email')).toBe(true) + expect(localStorage.length).toBe(0) + } finally { + scope.stop() + } +}) + +it('provides the full settings with a frozen plain columns array and keeps adjustments when definitions change', async () => { + const input: DataTableColumn[] = [ + selection, + { ...name, width: 120 }, + { ...email, width: 180 }, + ] + + input.forEach(Object.freeze) + Object.freeze(input) + + const wrapper = mount(RTablePro, { + props: { + columns: input, + data: [{ id: 1, name: 'Alice', email: 'alice@example.test' }], + }, + }) + + try { + const settings = wrapper.getComponent(ColumnSettings) + const table = wrapper.getComponent(NDataTable) + + await settings.get('button').trigger('click') + const tree = wrapper.getComponent(NTree) + const drop = tree.props('onDrop') + + expect(tree.props('draggable')).toBe(true) + + if (typeof drop !== 'function') + throw new Error('Missing column drop handler') + + drop({ + node: { key: 'name' }, + dragNode: { key: 'email' }, + dropPosition: 'before', + event: new DragEvent('drop'), + }) + settings.vm.$emit('patchColumn', 'email', { + fixed: 'left', + resizable: true, + }) + await nextTick() + + expect(table.props('columns')).toEqual([ + selection, + { ...input[2], fixed: 'left', resizable: true }, + input[1], + ]) + expect(input).toEqual([ + selection, + { ...name, width: 120 }, + { ...email, width: 180 }, + ]) + + settings.vm.$emit('toggleColumn', 'name', false) + await wrapper.setProps({ + columns: [ + selection, + { ...name, width: 130 }, + region, + { ...email, title: 'Work email', width: 220 }, + ], + }) + expect(table.props('columns')).toEqual([ + selection, + { + ...email, + title: 'Work email', + width: 220, + fixed: 'left', + resizable: true, + }, + region, + ]) + + settings.vm.$emit('toggleColumn', 'name', true) + await nextTick() + expect(table.props('columns')?.at(-1)).toEqual({ ...name, width: 130 }) + } finally { + wrapper.unmount() + } +}) + +it('lets v-model own the full column definitions without removing hidden columns from the emitted value', async () => { + const input = [selection, name, email] + const update = vi.fn() + const wrapper = mount(RTablePro, { + props: { columns: input, 'onUpdate:columns': update }, + }) + + try { + const settings = wrapper.getComponent(ColumnSettings) + const table = wrapper.getComponent(NDataTable) + + settings.vm.$emit('toggleColumn', 'email', false) + settings.vm.$emit('reorderColumns', ['email', 'name']) + await nextTick() + + expect(update).toHaveBeenCalledExactlyOnceWith([selection, email, name]) + expect(table.props('columns')).toEqual([selection, name]) + + await wrapper.setProps({ columns: update.mock.calls[0][0] }) + settings.vm.$emit('toggleColumn', 'email', true) + await nextTick() + expect(table.props('columns')).toEqual([selection, email, name]) + expect(update).toHaveBeenCalledTimes(1) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/components/table-pro-exports.spec.ts b/__test__/components/table-pro-exports.spec.ts new file mode 100644 index 00000000..b8fef09b --- /dev/null +++ b/__test__/components/table-pro-exports.spec.ts @@ -0,0 +1,99 @@ +import { RTablePro } from '@/components/base/RTablePro' +import type { TableProInst } from '@/components/base/RTablePro' +import { buildTableCsv } from '@/components/base/RTablePro/src/csv' +import * as printing from '@/components/base/RTablePro/src/printing' +import { mount } from '@vue/test-utils' +import type { DataTableColumn } from 'naive-ui' + +afterEach(() => vi.restoreAllMocks()) + +it('prints every row from the active page, even with virtual rows, without UI chrome', async () => { + const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true) + const wrapper = mount(RTablePro, { + props: { + data: Array.from({ length: 24 }, (_, id) => ({ + id, + name: `Person ${id}`, + })), + columns: [{ type: 'selection' }, { key: 'name', title: 'Name' }], + search: [{ key: 'name', label: 'Search name' }], + autoHeight: true, + virtualScroll: true, + pageSize: 12, + }, + slots: { tableFooter: 'Only on screen' }, + }) + + try { + const instance = wrapper.vm as unknown as TableProInst + + await instance.setPage(2) + expect(await instance.print()).toBe(true) + + const content = print.mock.calls[0][0] + + expect(content.tagName).toBe('TABLE') + expect(content.querySelectorAll('th')).toHaveLength(1) + expect(content.querySelectorAll('tbody tr')).toHaveLength(12) + expect(content.querySelector('tbody tr')?.textContent).toBe('Person 12') + expect(content.textContent).not.toMatch( + /Search name|Only on screen|Person 11/, + ) + } finally { + wrapper.unmount() + } +}) + +it('prints only the chosen region and leaves the source untouched', async () => { + const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true) + const target = document.createElement('section') + + target.innerHTML = + '

Summary

' + const wrapper = mount(RTablePro, { + props: { data: [{ id: 1 }], columns: [{ key: 'id', title: 'ID' }] }, + }) + + try { + const instance = wrapper.vm as unknown as TableProInst + + expect( + await instance.print({ target: () => target, title: 'Report' }), + ).toBe(true) + expect(await instance.print({ target: () => null })).toBe(false) + expect(print).toHaveBeenCalledTimes(1) + const [content, options] = print.mock.calls[0] + + expect(content.querySelector('h2')?.textContent).toBe('Summary') + expect(content.querySelector('button')?.hasAttribute('onclick')).toBe(false) + expect(content.querySelector('table')).toBeNull() + expect(target.querySelector('button')?.hasAttribute('onclick')).toBe(true) + expect(options.title).toBe('Report') + } finally { + wrapper.unmount() + } +}) + +it('exports group children with correct CSV escaping and neutralizes formula text', () => { + const columns: DataTableColumn[] = [ + { type: 'selection' }, + { + key: 'group', + children: [ + { key: 'name', title: 'Name' }, + { key: 'note', title: 'Note' }, + { key: 'private', title: 'Private', allowExport: false }, + ], + }, + { key: 'score', title: 'Score' }, + ] + + expect( + buildTableCsv(columns, [ + { name: 'A, "B"', note: '=2+2', score: -2 }, + { name: 'Array value', note: ['=2+2', 'text'], score: -2n }, + ]), + ).toBe( + '"Name","Note","Score"\r\n"A, ""B""","\'=2+2","-2"\r\n"Array value","\'=2+2,text","-2"', + ) +}) diff --git a/__test__/components/table-pro.spec.ts b/__test__/components/table-pro.spec.ts new file mode 100644 index 00000000..a5b61488 --- /dev/null +++ b/__test__/components/table-pro.spec.ts @@ -0,0 +1,320 @@ +import { RTablePro } from '@/components/base/RTablePro' +import type { + TableProInst, + TableProParams, + TableProResult, +} from '@/components/base/RTablePro' +import { flushPromises, mount } from '@vue/test-utils' +import { NDataTable, NPagination } from 'naive-ui' + +const columns = [{ title: 'Name', key: 'name' }] +const response = (name: string, total = 30): TableProResult => ({ + data: [{ id: name, name }], + total, +}) + +it('loads and paginates once per action, without rewriting the filter object', async () => { + const request = vi.fn(async (_params: TableProParams) => response('Alice')) + const filters = { email: '@example.test', page: 99 } + const wrapper = mount(RTablePro, { + props: { columns, request, params: filters, tool: false }, + }) + + try { + await flushPromises() + expect(request.mock.calls).toEqual([ + [ + { email: '@example.test', page: 1, pageSize: 10 }, + expect.any(AbortSignal), + ], + ]) + const table = wrapper.getComponent(NDataTable) + + expect(table.props('remote')).toBe(true) + expect(table.props('data')).toEqual(response('Alice').data) + expect(wrapper.getComponent(NPagination).props('itemCount')).toBe(30) + + const instance = wrapper.vm as unknown as TableProInst + + await instance.setPage(2) + await instance.setPageSize(20) + await instance.setPage(2) + await wrapper.setProps({ params: { email: 'alice' } }) + await flushPromises() + + expect(request.mock.calls.map(([params]) => params)).toEqual([ + { email: '@example.test', page: 1, pageSize: 10 }, + { email: '@example.test', page: 2, pageSize: 10 }, + { email: '@example.test', page: 1, pageSize: 20 }, + { email: '@example.test', page: 2, pageSize: 20 }, + { email: 'alice', page: 1, pageSize: 20 }, + ]) + expect(filters).toEqual({ email: '@example.test', page: 99 }) + } finally { + wrapper.unmount() + } +}) + +it('ignores stale data even if the loader ignores cancellation', async () => { + const first = Promise.withResolvers() + const second = Promise.withResolvers() + const request = vi + .fn((_params: TableProParams, _signal: AbortSignal) => first.promise) + .mockImplementationOnce(() => first.promise) + .mockImplementationOnce(() => second.promise) + const wrapper = mount(RTablePro, { props: { columns, request, tool: false } }) + + try { + const instance = wrapper.vm as unknown as TableProInst + const next = instance.setPage(2) + + expect(request.mock.calls[0][1].aborted).toBe(true) + second.resolve(response('New page')) + await next + first.resolve(response('Old page')) + await flushPromises() + + expect(wrapper.text()).toContain('New page') + expect(wrapper.text()).not.toContain('Old page') + expect(wrapper.getComponent(NDataTable).props('loading')).toBe(false) + } finally { + wrapper.unmount() + } +}) + +it('shows a retry for a failed request and omits paging fields when pagination is off', async () => { + const request = vi + .fn(async (_params: TableProParams) => response('Recovered', 1)) + .mockRejectedValueOnce(new Error('offline')) + const wrapper = mount(RTablePro, { + props: { columns, request, pagination: false, tool: false }, + }) + + 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') + await flushPromises() + + expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}]) + expect(wrapper.find('.n-alert').exists()).toBe(false) + expect(wrapper.text()).toContain('Recovered') + } finally { + wrapper.unmount() + } +}) + +it('can paginate local data without requiring a request or a row key function', async () => { + const data = [ + { id: 1, name: 'First' }, + { id: 2, name: 'Second' }, + ] + const wrapper = mount(RTablePro, { + props: { columns, data, pageSize: 1, tool: false }, + }) + + try { + expect(wrapper.getComponent(NDataTable).props('remote')).toBe(false) + expect(wrapper.text()).toContain('First') + expect(wrapper.text()).not.toContain('Second') + const instance = wrapper.vm as unknown as TableProInst + + await instance.setPage(2) + expect(wrapper.text()).toContain('Second') + } finally { + wrapper.unmount() + } +}) + +it('renders bare data without a toolbar or pagination by default', () => { + const wrapper = mount(RTablePro, { + props: { bare: true, columns, data: response('Bare row', 1).data }, + }) + + try { + expect(wrapper.text()).toContain('Bare row') + expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false) + expect(wrapper.find('header').exists()).toBe(false) + } finally { + wrapper.unmount() + } +}) + +it('submits the search and resets the page without requiring form state in the caller', async () => { + const request = vi.fn(async (_params: TableProParams) => response('Alice')) + const wrapper = mount(RTablePro, { + props: { + columns, + request, + search: [{ key: 'name', label: 'Name' }], + tool: false, + }, + }) + + try { + const instance = wrapper.vm as unknown as TableProInst + + await instance.setPage(2) + await wrapper.get('input').setValue(' Alice ') + expect(request).toHaveBeenCalledTimes(2) + await wrapper.get('form').trigger('submit') + await flushPromises() + expect(request).toHaveBeenCalledTimes(3) + expect(request.mock.lastCall?.[0]).toEqual({ + name: 'Alice', + page: 1, + pageSize: 10, + }) + + await wrapper.get('form button[type="button"]').trigger('click') + await flushPromises() + expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 }) + } finally { + wrapper.unmount() + } +}) + +it('enables the table body scroller with a single autoHeight prop', () => { + const wrapper = mount(RTablePro, { + props: { + autoHeight: true, + columns, + data: response('Row', 1).data, + tool: false, + }, + }) + + try { + expect(wrapper.getComponent(NDataTable).props('flexHeight')).toBe(true) + expect(wrapper.classes()).toContain('r-table--fill') + } finally { + wrapper.unmount() + } +}) + +it('returns to the last available remote page when the total shrinks', async () => { + const request = vi + .fn(async (_params: TableProParams) => response('First page', 5)) + .mockResolvedValueOnce(response('Initial', 30)) + .mockResolvedValueOnce({ data: [], total: 5 }) + const wrapper = mount(RTablePro, { props: { columns, request, tool: false } }) + + try { + await flushPromises() + const instance = wrapper.vm as unknown as TableProInst + + await instance.setPage(3) + + expect(request.mock.calls.map(([params]) => params.page)).toEqual([1, 3, 1]) + expect(wrapper.text()).toContain('First page') + } finally { + wrapper.unmount() + } +}) + +it('passes native pagination settings and totals through for a manually controlled remote table', async () => { + const onUpdatePage = vi.fn() + const wrapper = mount(RTablePro, { + props: { + columns, + remote: true, + data: [{ id: 1, name: 'Loaded by caller' }], + pagination: { + page: 3, + pageSize: 20, + itemCount: 80, + showQuickJumper: true, + onUpdatePage, + }, + tool: false, + }, + }) + + try { + const pager = wrapper.getComponent(NPagination) + + expect(pager.props()).toMatchObject({ + page: 3, + pageSize: 20, + itemCount: 80, + showQuickJumper: true, + }) + await pager.findAll('.n-pagination-item--button').at(-1)!.trigger('click') + expect(onUpdatePage).toHaveBeenCalledOnce() + expect(onUpdatePage).toHaveBeenCalledWith(4) + } finally { + wrapper.unmount() + } +}) + +it('uses native initial paging options with managed requests and validates imperative values', async () => { + const request = vi.fn(async (_params: TableProParams) => + response('Loaded', 100), + ) + const wrapper = mount(RTablePro, { + props: { + columns, + request, + pagination: { defaultPage: 2, defaultPageSize: 20 }, + tool: false, + }, + }) + + try { + await flushPromises() + const instance = wrapper.vm as unknown as TableProInst + + await instance.setPage(0) + await instance.setPageSize(Number.NaN) + expect(request.mock.calls.map(([params]) => params)).toEqual([ + { page: 2, pageSize: 20 }, + ]) + } finally { + wrapper.unmount() + } +}) + +it('keeps TablePro state in sync when DataTable changes its page directly', async () => { + const data = [ + { id: 1, name: 'First' }, + { id: 2, name: 'Second' }, + ] + const onUpdatePage = vi.fn() + const wrapper = mount(RTablePro, { + props: { data, columns, pageSize: 1, onUpdatePage, tool: false }, + }) + + try { + const instance = wrapper.vm as unknown as TableProInst + + instance.getTableInstance()?.page(2) + await wrapper.vm.$nextTick() + + expect(wrapper.getComponent(NPagination).props('page')).toBe(2) + expect(wrapper.text()).toContain('Second') + expect(onUpdatePage).toHaveBeenCalledOnce() + } finally { + wrapper.unmount() + } +}) + +it('supports an optional title slot for actions without putting controls inside a heading', () => { + const wrapper = mount(RTablePro, { + props: { + columns, + data: [{ id: 1, name: 'Alice' }], + title: 'Default title', + tool: false, + }, + slots: { title: '' }, + }) + + try { + expect(wrapper.get('header button').text()).toBe('Quick action') + expect(wrapper.find('header h2').exists()).toBe(false) + expect(wrapper.text()).not.toContain('Default title') + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/layout/slots.spec.ts b/__test__/layout/slots.spec.ts index 3c95720c..b3ac9b59 100644 --- a/__test__/layout/slots.spec.ts +++ b/__test__/layout/slots.spec.ts @@ -1,8 +1,9 @@ import { shallowMount } from '@vue/test-utils' import { createPinia, disposePinia, setActivePinia } from 'pinia' -import { h } from 'vue' +import { h, nextTick } from 'vue' import Layout from '../../src/layout' import { router } from '../../src/router' +import { piniaRuntimeStore } from '../../src/store/modules/runtime' import { piniaSettingStore } from '../../src/store/modules/setting' it('lets a custom header replace the complete default header and top navigation', () => { @@ -32,3 +33,35 @@ it('lets a custom header replace the complete default header and top navigation' disposePinia(pinia) } }) + +it('offers a restore button for custom content and also exits with Escape', async () => { + const pinia = createPinia() + + setActivePinia(pinia) + const runtime = piniaRuntimeStore() + const wrapper = shallowMount(Layout, { + global: { renderStubDefaultSlot: true, plugins: [router, pinia] }, + slots: { + default: () => h('div', { 'data-test': 'custom-content' }, 'Custom'), + }, + }) + + try { + expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe( + false, + ) + runtime.setRuntimeState('layoutContentMaximize', true) + await nextTick() + expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true) + await wrapper.get('.r-layout-content-restore__button').trigger('click') + expect(runtime.layoutContentMaximize).toBe(false) + + runtime.setRuntimeState('layoutContentMaximize', true) + await nextTick() + window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })) + expect(runtime.layoutContentMaximize).toBe(false) + } finally { + wrapper.unmount() + disposePinia(pinia) + } +}) diff --git a/__test__/mock/database.spec.ts b/__test__/mock/database.spec.ts index 6d922329..033c8f3d 100644 --- a/__test__/mock/database.spec.ts +++ b/__test__/mock/database.spec.ts @@ -1,21 +1,52 @@ -import { tableMock } from '../../mock/shared/database' +import { listPeople } from '@/demo-data/people' -describe('tableMock', () => { - it('preserves the person response fields after the data generator upgrade', () => { - const person = tableMock({ source: 'demo' }) +describe('person demo data', () => { + it('serves consistent, non-overlapping pages with the documented record shape', () => { + const first = listPeople({ page: 1, pageSize: 10 }) + const second = listPeople({ page: 2, pageSize: 10 }) - expect(person).toMatchObject({ - source: 'demo', - id: expect.any(String), - address: expect.any(String), - email: expect.any(String), + expect(first.total).toBe(100) + expect(second.total).toBe(100) + expect(first.data).toHaveLength(10) + expect(second.data).toHaveLength(10) + expect(first.data[0]).toMatchObject({ + id: expect.stringMatching(/^[0-9a-f-]{36}$/i), name: expect.any(String), + email: expect.stringContaining('@'), + address: expect.any(String), age: expect.any(Number), createDate: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/), }) - expect(person.id).toMatch(/^[0-9a-f-]{36}$/i) - expect(person.age).toBeGreaterThanOrEqual(18) - expect(person.age).toBeLessThanOrEqual(60) - expect(person.email).toContain('@') + expect( + new Set([...first.data, ...second.data].map(({ id }) => id)).size, + ).toBe(20) + expect(listPeople({ page: 1, pageSize: 10 })).toEqual(first) + }) + + it('filters all rows before paginating and reports the filtered total', () => { + const { data } = listPeople() + const person = data.at(-1)! + const email = person.email.toUpperCase() + const matches = data.filter((row) => row.email === person.email) + + expect(listPeople({ email, page: 1, pageSize: 1 })).toMatchObject({ + data: matches.slice(0, 1), + total: matches.length, + }) + expect( + listPeople({ email: 'no such email', page: 1, pageSize: 10 }), + ).toMatchObject({ + data: [], + total: 0, + }) }) }) + +it('sorts the complete filtered data before splitting into pages', () => { + const first = listPeople({ page: 1, pageSize: 10, sortAge: 'descend' }) + const second = listPeople({ page: 2, pageSize: 10, sortAge: 'descend' }) + const ages = [...first.data, ...second.data].map(({ age }) => age) + + expect(ages).toEqual([...ages].sort((a, b) => b - a)) + expect(first.total).toBe(100) +}) diff --git a/docs/architecture.md b/docs/architecture.md index 7cd7c03e..aab42ffa 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -16,7 +16,7 @@ Ray Template 是前端中后台模板,包含可运行的组件与路由示例 | 权限与守卫 | `src/router/utils/vue-router-register.ts`、`src/router/utils/permission.ts` | 同时检查菜单显示与实际导航;前端权限不能替代后端授权 | | 全局状态 | `src/store/modules`、`src/store/hooks` | [Store 文档](../src/store/README.md),持久化配置使用 `pick`/`omit` | | 请求与接口 | `src/api`、`src/axios` | [请求文档](../src/axios/README.md),请求/响应拦截器分开注册 | -| 演示接口 | `mock/demo`、`mock/shared` | `vite-plugin-mock-dev-server`,生产环境按实际后端切换 | +| 演示接口 | `mock/demo`、`src/demo-data` | `vite-plugin-mock-dev-server`,生产环境按实际后端切换 | | 通用组件 | `src/components/base`、`src/components/pro` | 组件、props、types、hook、样式放在同一功能目录 | | 模板绑定组件 | `src/app-components` | [组件说明](../src/app-components/README.md) | | 公共工具 | `src/utils` | [分包、兼容入口和测试](../src/utils/README.md) | diff --git a/docs/toolchain-upgrade.md b/docs/toolchain-upgrade.md index b8e63eaf..c1344130 100644 --- a/docs/toolchain-upgrade.md +++ b/docs/toolchain-upgrade.md @@ -44,6 +44,7 @@ - Vitest 测试只复用 Vue/TSX 与自动导入转换,不启动 Mock 服务、HTML 注入、图标扫描或压缩插件。修复遗漏 `await` 的断言,更新水印/全屏用例中的过期预期,保留行为断言。 - 既有颜色转换回归暴露 rgba 空格不一致与八位 hex 透明度丢失,已修正;图表异常保留原始 `cause`。 - Mock.js 存在未修复的原型污染公告,且包含直接 `eval`;替换为 Faker 的中文实例,保持人员字段、分页接口和表格示例能力。新版 Mock 插件的 include 相对 `dir` 匹配,修正原先重复的 `mock/` 前缀并等待首次加载,实际验证了 API 响应。 +- 开发时打开 `#/tables/remote`,在 Network 的 Fetch/XHR 分类查看 `GET /api/list?page=1&pageSize=10`。接口使用站点根路径 `/api/list`,不带 `/ray-template/`。Vite 按启动日志中的实际端口访问;静态构建的页面使用同一套本地示例生成逻辑,不依赖 Mock 服务器。 - 浏览器构建和 Autoprefixer 统一到 Vite 8 Baseline Widely Available。开发服务默认 loopback,局域网访问需显式 `--host`。监听排除全部构建目录和 `.ai-local`,避免构建报告时触发页面重复重载。 - CI 与 Docker 使用同一 Node/pnpm,冻结锁文件安装。CI 合并重复流程并覆盖类型、lint、格式、测试、构建;保留检查通过后部署 `main` 到 `dist` 分支的行为。 diff --git a/docs/ui-design.md b/docs/ui-design.md index 4691edaa..f8d750bb 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -8,6 +8,7 @@ - `src/styles/base.scss` 是全局样式入口,`design-system.scss` 管理主题变量与基础焦点样式,`setting.scss` 管理布局尺度。`naive.scss` 仅维护模板通用的控件默认值;布局与组件内部规则放在对应组件目录,避免影响嵌套的 Naive UI 实例。 - 控件通常为 8px 圆角、卡片为 12px;页面区块间距使用 20–28px。强调色用于选择与主要操作,正文、说明、眉题使用不同文字层级。 - 顶栏、标签栏和侧栏使用轻分割线,不叠加区域阴影;少量内容卡片使用两层轻阴影。 +- 内容最大化时,布局提供置顶的退出操作,使用按钮或 Esc 恢复。 - 页面标题复用 `AppPageHeader`:眉题、一个主标题、简短说明与可选操作区。不要以大段说明或同等权重的卡片标题代替页面层级。 ## 页面组织 diff --git a/harness/scopes.json b/harness/scopes.json index 23329013..c176dcba 100644 --- a/harness/scopes.json +++ b/harness/scopes.json @@ -35,7 +35,7 @@ }, "api": { "description": "API、Axios 拦截器与演示 Mock", - "paths": ["src/api", "src/axios/README.md", "mock/demo", "mock/shared"], + "paths": ["src/api", "src/axios/README.md", "mock/demo", "src/demo-data"], "tests": ["__test__/axios/", "__test__/mock/"] }, "icons": { diff --git a/mock/demo/person.mock.ts b/mock/demo/person.mock.ts index 864e49a0..5fa8363b 100644 --- a/mock/demo/person.mock.ts +++ b/mock/demo/person.mock.ts @@ -1,41 +1,19 @@ -import { tableMock } from '@mock/shared/database' -import { array, pagination, response, stringify } from '@mock/shared/utils' +import { listPeople } from '@/demo-data/people' import { defineMock } from 'vite-plugin-mock-dev-server' -export const getPersonList = defineMock({ +export default defineMock({ url: '/api/list', method: 'GET', - delay: 500, - response: (req, res) => { - const { - query: { page, pageSize, email }, - } = req - let list = array(100).map(() => tableMock()) - let length = list.length - - if (!page || !pageSize) { - res.end( - stringify( - response(list, 200, '请求成功', { - total: length, - }), - ), - ) - } else { - list = pagination(page, pageSize, list) - - if (email) { - list = list.filter((curr) => curr.email.includes(email)) - length = list.length - } - - res.end( - stringify( - response(list, 200, '请求成功', { - total: length, - }), - ), - ) - } - }, + delay: 250, + body: ({ query }) => + listPeople({ + page: Number(query.page), + pageSize: Number(query.pageSize), + email: typeof query.email === 'string' ? query.email : void 0, + name: typeof query.name === 'string' ? query.name : void 0, + sortAge: + query.sortAge === 'ascend' || query.sortAge === 'descend' + ? query.sortAge + : void 0, + }), }) diff --git a/mock/shared/database.ts b/mock/shared/database.ts deleted file mode 100644 index 2b1eca0c..00000000 --- a/mock/shared/database.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { faker } from '@faker-js/faker/locale/zh_CN' - -/** - * - * @param option 自定义配置 - * - * 基础表格数据 - */ -export function tableMock(option?: object) { - return { - ...option, - id: faker.string.uuid(), - address: faker.location.state() + faker.location.city(), - email: faker.internet.email(), - name: faker.person.fullName(), - age: faker.number.int({ min: 18, max: 60 }), - createDate: faker.date.past().toISOString().slice(0, 10), - } -} diff --git a/mock/shared/utils.ts b/mock/shared/utils.ts deleted file mode 100644 index c1e2a811..00000000 --- a/mock/shared/utils.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ - -export function array(length: number) { - return new Array(length).fill(0) -} - -/** - * - * @param pageCurrent 当前页码 - * @param pageSize 分页展示条数 - * @param array 数据 - * - * mock 分页展示数据 - */ -export function pagination( - pageCurrent: number, - pageSize: number, - array: T[], -): T[] { - const offset = (pageCurrent - 1) * Number(pageSize) - - return offset + Number(pageSize) >= array.length - ? array.slice(offset, array.length) - : array.slice(offset, offset + Number(pageSize)) -} - -/** - * - * @param value 原始数据 - * - * 格式化数据为 json 格式 - */ -export function stringify(value: T) { - return JSON.stringify(value) -} - -/** - * - * @param res 数据 - * @param code 响应码 - * @param msg 响应信息 - */ -export function response( - res: T, - code: number, - msg: string, - params?: object, -) { - const basic = { - code, - msg, - data: res, - ...params, - } - - return basic -} diff --git a/src/api/demo/mock/person.ts b/src/api/demo/mock/person.ts index 2ced3ef9..e4d7ccbd 100644 --- a/src/api/demo/mock/person.ts +++ b/src/api/demo/mock/person.ts @@ -1,26 +1,24 @@ import { request } from '@/axios' +import type { Person, PersonListParams } from '@/demo-data/people' import type { PaginationResponse } from '@/types' -export interface MockListParams { - page: number - pageSize: number -} +export type { Person, PersonListParams } from '@/demo-data/people' -export interface Person { - name: string - id: string - age: number - address: string - createDate: string - email: string | null -} - -export const getPersonList = ( - params: Partial>, +export const getPersonList = async ( + params: PersonListParams, + signal?: AbortSignal, ) => { - return request>({ - url: '/api/list', - method: 'get', - params, - }) + if (import.meta.env.DEV) { + return request>({ + url: '/api/list', + method: 'get', + params, + signal, + cancelConfig: { cancel: !signal }, + }) + } + + const { listPeople } = await import('@/demo-data/people') + + return listPeople(params) } diff --git a/src/components/README.md b/src/components/README.md index 5aff0c3f..71a4e77f 100644 --- a/src/components/README.md +++ b/src/components/README.md @@ -7,7 +7,7 @@ - `RCollapseGrid` 基于 Naive UI Grid,子项需要使用 `NGridItem`;折叠表单 `RCollapse` 的表单项需要使用 `NFormItemGi` / `NGridItem`。不要用普通容器替代 Grid 子项。 - `RChart` 与 `useChart` 负责实例初始化、销毁、尺寸与主题同步;调用方维护 ECharts options,需要的图表与组件按现有 ECharts 注册方式引入。 - `PageResult` 基于 Naive UI Result,可作为组件或错误页面使用,保留继承的 props 与 slots。 -- `RTable` 的列顺序配置以第一层列为单位,深层子列跟随根列;大量列数据的性能需按实际业务验证。 +- [TablePro](base/RTablePro/README.md) 统一支持纯表格、搜索与分页及自适应高度。列顺序配置以第一层列为单位,深层子列跟随根列。 - `RIcon.name` 为生成的完整分包路径类型,图标改动会在开发、HMR 和构建时同步;不要手工修改生成清单。 组件样式随组件入口加载。调整 Naive UI 内部元素时,使用当前组件的类名限定作用范围;组件需填满容器时由调用处或组件自身声明尺寸。全屏 `RModal` 的卡片正文仅在溢出时滚动,`RBarcode` 的加载区域随条码尺寸或响应式容器伸缩。 diff --git a/src/components/base/RTable/index.ts b/src/components/base/RTable/index.ts deleted file mode 100644 index 9478543a..00000000 --- a/src/components/base/RTable/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { ExtractPublicPropTypes } from 'vue' -import useCheckedRowKeys from './src/hooks/useCheckedRowKeys' -import type { UseCheckedRowKeysReturn } from './src/hooks/useCheckedRowKeys' -import useTable from './src/hooks/useTable' -import type { UseTableReturn } from './src/hooks/useTable' -import tableProps from './src/props' -import RTable from './src/Table' -import type * as RTableType from './src/types' - -export type TableProps = ExtractPublicPropTypes -export type { RTableType, UseTableReturn, UseCheckedRowKeysReturn } - -export { RTable, tableProps, useTable, useCheckedRowKeys } diff --git a/src/components/base/RTable/src/Table.tsx b/src/components/base/RTable/src/Table.tsx deleted file mode 100644 index ac878768..00000000 --- a/src/components/base/RTable/src/Table.tsx +++ /dev/null @@ -1,391 +0,0 @@ -import './index.scss' -import type { ComponentSize } from '@/types' -import { call, completeSize, renderNode, uuid } from '@/utils' -import { pick } from 'lodash-es' -import { NCard, NDataTable, NDropdown, NFlex } from 'naive-ui' -import type { DataTableProps, DropdownOption } from 'naive-ui' -import { useTemplateRef } from 'vue' -import C from './components/C' -import Fullscreen from './components/Fullscreen' -import Print from './components/Print' -import TablePropsSelect from './components/Props' -import Size from './components/Size' -import props from './props' -import { config } from './shared' -import type { - C as CType, - PropsComponentPopselectKeys, - RTableInst, -} from './types' - -export default defineComponent({ - name: 'RTable', - inheritAttrs: false, - props, - setup(props, ctx) { - const { expose } = ctx - - const rTableInst = useTemplateRef('rTableInst') - const wrapperRef = useTemplateRef('wrapperRef') - const uuidWrapper = uuid(16) - const uuidTable = uuid(16) - /** - * - * x: 横坐标 - * y: 纵坐标 - * showContextMenu: 是否显示右键菜单 - */ - const contextMenuReactive = reactive({ - x: 0, - y: 0, - showContextMenu: false, - }) - /** - * - * size: table size,内部私有状态管理 - */ - const privateReactive = reactive({ - size: props.size, - }) - const propsPopselectValue = ref( - Object.assign( - { - striped: false, - bordered: false, - }, - pick(props, 'striped', 'bordered'), - ), - ) - // 默认设置 card header style - const cardHeaderStyle = computed(() => { - const { title, tool, cardProps } = props - const { headerStyle = {} } = cardProps ?? {} - - if (!title && !tool) { - return Object.assign( - {}, - { - paddingTop: '0px', - }, - headerStyle, - ) - } - - return headerStyle - }) - // 如果启用了 flexAutoHeight 属性,则自动继承高度 - const flexAutoHeightStyle = computed(() => { - const { flexAutoHeight } = props - - if (!flexAutoHeight) { - return null - } - - return { - height: '100%', - flex: 1, - } - }) - - /** - * - * @param key 当前选中项的 key - * @param option 当前选中项 - * - * @description - * 右键菜单选择事件回调。 - */ - const contextMenuSelect = ( - key: number | string, - option: DropdownOption, - ) => { - contextMenuReactive.showContextMenu = false - - const { onContextMenuClick } = props - - if (onContextMenuClick) { - call(onContextMenuClick, key, option) - } - } - - /** - * - * @param e 鼠标点击事件 - * - * @description - * 处理右键菜单事件。 - */ - const tableContextMenu = (e: MouseEvent) => { - e.preventDefault() - contextMenuReactive.showContextMenu = false - - nextTick().then(() => { - contextMenuReactive.showContextMenu = true - contextMenuReactive.x = e.clientX - contextMenuReactive.y = e.clientY - }) - } - - /** - * - * @param row 当前行数据 - * @param idx 当前行索引 - * - * @description - * 合并 RTable 的所有 rowProps,如果开启了右键菜单功能,自动会拦截右键事件。 - */ - const combineRowProps = (row: Record, idx: number) => { - const interceptRowProps = props.rowProps?.(row, idx) || {} - - if (props.disabledContextMenu) { - return interceptRowProps - } - - return { - ...interceptRowProps, - onContextmenu: tableContextMenu, - } - } - - /** - * - * @param size 表格尺寸 - * - * @description - * 修改表格尺寸。 - */ - const changeTableSize = (size: ComponentSize) => { - privateReactive.size = size - } - - /** - * - * @param options 表格列配置项 - * - * @description - * 更新 table columns,同时触发 onUpdateColumns 和 onUpdate:columns 事件。 - */ - const updateTableColumn = (options: CType[]) => { - const { onUpdateColumns, 'onUpdate:columns': $onUpdateColumns } = props - - if (onUpdateColumns) { - call(onUpdateColumns, options) - } - - if ($onUpdateColumns) { - call($onUpdateColumns, options) - } - } - - /** - * - * @description - * 处理自定义的 toolOptions。 - * 匹配所有符合条件的 toolOptions,然后执行。 - */ - const renderToolOptions = () => { - const { toolOptions } = props - - return toolOptions - ?.filter(Boolean) - .map((curr) => (typeof curr === 'function' ? curr() : curr)) - } - - const popselectChange = (value: PropsComponentPopselectKeys[]) => { - const keys = Object.keys(propsPopselectValue.value) - - keys.forEach((key) => { - propsPopselectValue.value[ - key as keyof typeof propsPopselectValue.value - ] = value.includes(key as PropsComponentPopselectKeys) - }) - } - - /** - * - * @description - * 渲染默认工具栏。 - */ - const renderDefaultToolOptions = () => { - const { onUpdateColumns, 'onUpdate:columns': rOnUpdateColumns } = props - const needSettingComponent = !!onUpdateColumns || !!rOnUpdateColumns - - return ( - - - - - {needSettingComponent ? ( - - ) : null} - - - ) - } - - /** - * - * @param p props - * - * @description - * 处理 toolOptions,合并渲染所有的 toolOptions。 - */ - const tool = (p: typeof props) => { - if (!p.tool) { - return - } - - if (!p.toolOptions) { - return renderDefaultToolOptions - } - - if (p.coverTool) { - return () => {renderToolOptions()} - } - - return () => ( - - {renderDefaultToolOptions()} - {renderToolOptions()} - - ) - } - - onMounted(() => { - // 主动调用 register 方法,满足 useTable 方法正常调用 - const { onRegister } = props - - if (onRegister && rTableInst.value) { - call(onRegister, rTableInst.value, { - uuidTable, - uuidWrapper, - wrapperRef, - tableRef: rTableInst, - }) - } - }) - - provide(config.tableKey, { - uuidTable, - uuidWrapper, - wrapperRef, - }) - expose() - - return { - uuidWrapper, - uuidTable, - contextMenuReactive, - rTableInst, - combineRowProps, - contextMenuSelect, - privateReactive, - tool, - wrapperRef, - propsPopselectValue, - cardHeaderStyle, - flexAutoHeightStyle, - tableContextMenu, - } - }, - render() { - const { - $props, - $attrs, - $slots, - uuidTable, - contextMenuReactive, - uuidWrapper, - privateReactive, - propsPopselectValue, - cardHeaderStyle, - flexAutoHeightStyle, - } = this - const { class: className, ...restAttrs } = $attrs - const { tool, combineRowProps, contextMenuSelect } = this - const { - renderWrapperHeader, - wrapperBordered, - disabledContextMenu, - contextMenuOptions, - title, - tableFlexHeight, - cardProps, - flexAutoHeight, - flexHeight, - ...restProps - } = $props - const { headerStyle, ...restCardProps } = cardProps ?? {} - - return ( - - {{ - default: () => ( - <> - - {{ - ...$slots, - }} - - {!disabledContextMenu ? ( - - (contextMenuReactive.showContextMenu = false) - } - onSelect={contextMenuSelect.bind(this)} - /> - ) : null} - - ), - header: renderWrapperHeader - ? renderNode(title, { - defaultElement:
, - }) - : null, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - 'header-extra': tool($props as any), - footer: () => $slots.tableFooter?.(), - action: () => $slots.tableAction?.(), - }} -
- ) - }, -}) diff --git a/src/components/base/RTable/src/components/C.tsx b/src/components/base/RTable/src/components/C.tsx deleted file mode 100644 index 4a7d43ce..00000000 --- a/src/components/base/RTable/src/components/C.tsx +++ /dev/null @@ -1,267 +0,0 @@ -import { RIcon } from '@/components' -import type { IconName } from '@/icons' -import type { AnyFn, MaybeArray } from '@/types' -import { call } from '@/utils' -import { cloneDeep, isEmpty } from 'lodash-es' -import { NFlex, NPopover, NTree } from 'naive-ui' -import type { TreeDropInfo, TreeOption } from 'naive-ui' -import props from '../props' -import { config } from '../shared' -import type { C } from '../types' - -type FixedClick = (type: 'left' | 'right', option: C, index: number) => void - -const renderSwitcherIcon = () => ( - -) - -const RowIconRender = ({ - icon, - title, - onClick, - customClassName, -}: { - icon: IconName - title: string - onClick?: AnyFn - customClassName?: string -}) => { - return ( - - {{ - trigger: () => ( - - ), - default: () => title, - }} - - ) -} - -/** - * 查找节点的兄弟节点和索引 - * - * @param node 要查找的节点 - * @param nodes 节点列表 - * @returns 如果找到节点,则返回包含兄弟节点列表和索引的元组,否则返回 [null, null] - */ -const findSiblingsAndIndex = ( - node: TreeOption, - nodes?: TreeOption[], -): [TreeOption[], number] | [null, null] => { - if (!nodes) { - return [null, null] - } - - for (let i = 0; i < nodes.length; ++i) { - const siblingNode = nodes[i] - - if (siblingNode.key === node.key) { - return [nodes, i] - } - - const [siblings, index] = findSiblingsAndIndex(node, siblingNode.children) - - if (siblings && index !== null) { - return [siblings, index] - } - } - - return [null, null] -} - -const R_TABLE_C_TOOL_ICON_ACTIVE = 'r-table__c-tool-icon--active' - -export default defineComponent({ - name: 'TableC', - props: { - ...props, - onUpdateColumn: { - type: [Function, Array] as PropType void>>, - default: null, - }, - }, - setup(props) { - let tableColumnType: C - // 深拷贝 columns 避免修改源数据 - const treeDataSource = computed({ - get: () => { - const cloneColumns = cloneDeep(props.columns).filter((curr) => { - if (curr.type) { - tableColumnType = curr as unknown as C - - return false - } - - return true - }) - - return cloneColumns.map((curr, idx) => { - const { key, title, children, fixed, isResizable, ...args } = - curr as C - const isLeftFixedActivated = fixed === 'left' - const isRightFixedActivated = fixed === 'right' - const attr = { - ...args, - title, - key, - fixed, - isLeftFixedActivated, - isRightFixedActivated, - isResizable, - } - - return { - ...attr, - suffix: () => ( - - - - {{ - trigger: () => ( - - ), - default: () => '修改列宽', - }} - - - - ), - } - }) as C[] - }, - - set: () => {}, - }) - - const event = (options: C[]) => { - const { onUpdateColumn } = props - - if (onUpdateColumn) { - // 使用 nextTick 确保 DOM 更新后再触发事件 - nextTick(() => { - call(onUpdateColumn, options) - }) - } - } - - const resizableClick = (option: C, index: number) => { - option['isResizable'] = !option['isResizable'] - option['resizable'] = option['isResizable'] - treeDataSource.value[index] = option - - event(treeDataSource.value) - } - - const fixedClick: FixedClick = (type, option, index) => { - const key = `${type}FixedActivated` as const - const otherKey = - `${type === 'left' ? 'right' : 'left'}FixedActivated` as const - - option[otherKey] = false - option[key] = !option[key] - option[key] ? (option['fixed'] = type) : (option['fixed'] = void 0) - treeDataSource.value[index] = option - - event(treeDataSource.value) - } - - // 拖拽节点的处理函数 - const treeDrop = ({ node, dragNode, dropPosition }: TreeDropInfo) => { - const [dragNodeSiblings, dragNodeIndex] = findSiblingsAndIndex( - dragNode, - treeDataSource.value as TreeOption[], - ) - - if (dragNodeSiblings === null || dragNodeIndex === null) { - return - } - - // 从兄弟节点中移除拖拽节点 - dragNodeSiblings.splice(dragNodeIndex, 1) - - const [nodeSiblings, nodeIndex] = findSiblingsAndIndex( - node, - treeDataSource.value as TreeOption[], - ) - - if (nodeSiblings === null || nodeIndex === null) { - return - } - - // 根据拖拽位置将拖拽节点插入到目标节点的前面或后面 - dropPosition === 'before' - ? nodeSiblings.splice(nodeIndex, 0, dragNode) - : nodeSiblings.splice(nodeIndex + 1, 0, dragNode) - - if (!isEmpty(tableColumnType)) { - nodeSiblings.unshift(tableColumnType as TreeOption) - } - - // 触发事件,更新树形数据源 - event(nodeSiblings as C[]) - } - - return { - treeDataSource, - treeDrop, - } - }, - render() { - return ( - - {{ - trigger: () => ( - - ), - default: () => ( - - ), - }} - - ) - }, -}) diff --git a/src/components/base/RTable/src/components/Fullscreen.tsx b/src/components/base/RTable/src/components/Fullscreen.tsx deleted file mode 100644 index 95e93c72..00000000 --- a/src/components/base/RTable/src/components/Fullscreen.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import { RIcon } from '@/components' -import { useFullscreen } from 'vue-hooks-plus' -import { config } from '../shared' -import type { TableProvider } from '../types' - -export default defineComponent({ - name: 'TableFullscreen', - setup() { - const { wrapperRef } = inject( - config.tableKey, - {} as TableProvider, - ) - const [isFullscreen, { toggleFullscreen, isEnabled }] = - useFullscreen(wrapperRef) - - return { - toggleFullscreen, - isEnabled, - } - }, - render() { - const { toggleFullscreen, isEnabled, $t } = this - - return ( - { - if (!isEnabled) { - window.$message.warning($t('globalMessage.isEnabledFullscreen')) - } - - toggleFullscreen() - }} - /> - ) - }, -}) diff --git a/src/components/base/RTable/src/components/Print.tsx b/src/components/base/RTable/src/components/Print.tsx deleted file mode 100644 index a9141815..00000000 --- a/src/components/base/RTable/src/components/Print.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { RIcon } from '@/components' -import { printDom } from '@/utils/dom' -import props from '../props' -import { config } from '../shared' -import type { TableProvider } from '../types' - -export default defineComponent({ - name: 'TablePrint', - props, - setup(props) { - const { wrapperRef } = inject( - config.tableKey, - {} as TableProvider, - ) - - const printTableClick = () => { - const { - printTableOptions: { printOptions = {}, domToImageOptions } = {}, - title, - } = props - - if ( - printOptions.documentTitle === '' || - printOptions.documentTitle === void 0 || - printOptions.documentTitle === null - ) { - printOptions.documentTitle = typeof title === 'string' ? title : '' - } - - printDom(wrapperRef, { - printOptions, - domToImageOptions, - }) - } - - return { - printTableClick, - } - }, - render() { - return ( - - ) - }, -}) diff --git a/src/components/base/RTable/src/components/Props.tsx b/src/components/base/RTable/src/components/Props.tsx deleted file mode 100644 index 7214e9d1..00000000 --- a/src/components/base/RTable/src/components/Props.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import { RIcon } from '@/components' -import type { MaybeArray } from '@/types' -import { call } from '@/utils' -import { NPopselect } from 'naive-ui' -import props from '../props' -import { config, propsOptions } from '../shared' -import type { PropsComponentPopselectKeys } from '../types' - -export default defineComponent({ - name: 'TablePropsSelect', - props: { - ...props, - onPopselectChange: { - type: [Function, Array] as PropType< - MaybeArray<(size: PropsComponentPopselectKeys[]) => void> - >, - default: null, - }, - onInitialed: { - type: [Function, Array] as PropType< - MaybeArray<(size: PropsComponentPopselectKeys[]) => void> - >, - default: null, - }, - }, - setup(props) { - const popoverShow = ref(false) - const propsPopselectValue = ref([]) - - const updatePopselectValue = (value: PropsComponentPopselectKeys[]) => { - const { onPopselectChange } = props - - if (onPopselectChange) { - call(onPopselectChange, value) - } - } - - const initialPopselectValue = () => { - const { striped, bordered, onInitialed } = props - - if (striped) { - propsPopselectValue.value.push('striped') - } - - if (bordered) { - propsPopselectValue.value.push('bordered') - } - - if (onInitialed) { - call(onInitialed, propsPopselectValue.value) - } - } - - initialPopselectValue() - - return { - propsPopselectValue, - popoverShow, - updatePopselectValue, - } - }, - render() { - return ( - - - - ) - }, -}) diff --git a/src/components/base/RTable/src/components/Size.tsx b/src/components/base/RTable/src/components/Size.tsx deleted file mode 100644 index 85cfd9aa..00000000 --- a/src/components/base/RTable/src/components/Size.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import { RIcon } from '@/components' -import type { ComponentSize, MaybeArray } from '@/types' -import { call } from '@/utils' -import { NPopselect } from 'naive-ui' -import props from '../props' -import { config } from '../shared' - -export default defineComponent({ - name: 'TableSizeSelect', - props: { - onChangeSize: { - type: [Function, Array] as PropType< - MaybeArray<(size: ComponentSize) => void> - >, - default: null, - }, - ...props, - }, - setup(props) { - const size = ref(props.size) - const sizeOptions = [ - { - label: '默认', - value: 'medium', - }, - { - label: '紧凑', - value: 'small', - }, - { - label: '宽松', - value: 'large', - }, - ] - - const updatePopselectValue = (value: string | number) => { - const { onChangeSize } = props - - if (onChangeSize) { - call(onChangeSize, value as ComponentSize) - } - } - - return { - size, - sizeOptions, - updatePopselectValue, - } - }, - render() { - return ( - - - - ) - }, -}) diff --git a/src/components/base/RTable/src/hooks/useCheckedRowKeys.ts b/src/components/base/RTable/src/hooks/useCheckedRowKeys.ts deleted file mode 100644 index 85d528c2..00000000 --- a/src/components/base/RTable/src/hooks/useCheckedRowKeys.ts +++ /dev/null @@ -1,361 +0,0 @@ -/* eslint-disable @typescript-eslint/no-explicit-any */ -import type { Recordable } from '@/types' -import { effectDispose } from '@/utils' -import type { DataTableColumns, DataTableSelectionColumn } from 'naive-ui' -import type { MaybeRef } from 'vue' - -export type RowKey = string | number - -export type Action = - 'check' | 'uncheck' | 'checkAll' | 'uncheckAll' | 'multipleCheck' - -export interface UseCheckedRowKeysOptions { - /** - * - * @description - * 绑定在 DataTable 组件的唯一关键字段,用于标识每一行数据。 - * 在该组件中,默认使用 key 作为关键字段,你可以通过该属性来自定义。 - */ - rowKey: string - /** - * - * @param keys 选中的 keys - * @param rows 选中的 rows - * @param meta 当前操作的元数据 - * - * @description - * 每当 keys 变化时,会触发该回调函数。 - */ - onChange?: ( - keys: RowKey[], - rows: T[], - meta: { row: T | undefined; action: Action }, - ) => void -} - -/** - * - * @param tableData DataTable data - * @param bindRowKey DataTable rowKey - * @param key target key - * - * @description - * 递归查找指定 key 的行数据。 - * 因为 DataTable data 允许树结构,所以需要递归查找。 - */ -const findRow = ( - tableData: Recordable[], - bindRowKey: string, - key: RowKey, -): Recordable | undefined => { - if (!tableData.length) { - return void 0 - } - - for (const curr of tableData) { - if (curr[bindRowKey] === key) { - return curr - } - - if (curr?.children?.length) { - const foundRow = findRow(curr.children, bindRowKey, key) - - if (foundRow) { - return foundRow - } - } - } - - return void 0 -} - -const isMultiple = (columns: MaybeRef | undefined>) => { - const unrefColumns = unref(columns) - - if (unrefColumns) { - const idx = unrefColumns.findIndex((column) => { - const { type, multiple } = column as DataTableSelectionColumn - - if ( - type === 'selection' && - (multiple === void 0 || multiple === null || multiple === true) - ) { - return true - } - }) - - return idx !== -1 - } - - return true -} - -const matchRowsBySelectionKeys = ( - data: MaybeRef, - keys: RowKey[], - currentRows: MaybeRef, - bindRowKey: string, -) => { - const unrefData = unref(data) - - if (!unrefData) { - return currentRows - } - - return keys.reduce((pre, key) => { - const findByCurrentRows = unref(currentRows).findIndex( - (f) => f[bindRowKey] === key, - ) - - if (findByCurrentRows !== -1) { - pre.push(unref(currentRows)[findByCurrentRows]) - - return pre - } - - const findByData = unrefData.findIndex((f) => f[bindRowKey] === key) - - if (findByData !== -1) { - pre.push(unrefData[findByData]) - - return pre - } - - return pre - }, [] as T[]) -} - -/** - * - * @param data 当前 DataTable 组件的数据 - * @param options 配置项 - * - * @description - * 该方法用于便捷的管理 checkedRowKeys。 - * - * 该方法依赖 rowKey,该字段用于标识每一行数据,与组件的约定保持一致。 - * - * 如果需要该方法去接管 onUpdateCheckedRowKeys 事件,需要手动去注册 checkedRowKeysBind 方法。 - * 并且在使用的时候,需要手动绑定 v-model:checkedRowKeys。 - * - * @example - * - * - */ -const useCheckedRowKeys = < - T extends Recordable, - C extends DataTableColumns, ->( - data: MaybeRef, - columns: MaybeRef, - options?: UseCheckedRowKeysOptions, -) => { - const keysRef = ref([]) - const rowsRef = ref([]) - const { rowKey: bindRowKey = 'key', onChange } = options || {} - const currentColumnIsMultiple = computed(() => isMultiple(columns)) - - /** - * - * @param keys 选中 keys 数据 - * @param rows 选中 rows 数据 - * @param meta 当前选中元数据与操作类型 - * - * @description - * 用于绑定 onUpdateCheckedRowKeys 事件。 - */ - const bind = ( - keys: RowKey[], - rows: Recordable[], - meta: { - row: Recordable | undefined - action: Action - }, - ) => { - keysRef.value = keys - rowsRef.value = unref( - matchRowsBySelectionKeys(data, keys, rowsRef, bindRowKey), - ) - - onChange?.( - keys, - rowsRef.value, - meta as { - row: any | undefined - action: Action - }, - ) - - isMultiple(columns) - } - - /** - * - * @description - * 获取所有已选择行的 key。 - * key 为你手动绑定的唯一关键字段,与 DataTable 组件需要的 rowKey 保持一致。 - */ - const getKeys = () => keysRef.value - - /** - * - * @description - * 获取所有已选择行的数据。 - */ - const getRows = () => rowsRef.value as T[] - - /** - * - * @description - * 清理所有已选择行的 key 和 rows。 - */ - const clearAll = () => { - keysRef.value = [] - rowsRef.value = [] - - onChange?.(keysRef.value, rowsRef.value, { - row: void 0, - action: 'uncheckAll', - }) - } - - /** - * - * @param key 需要清理的 key - * @param rowKey 绑定 key 的字段,默认为 'key',与 DataTable 组件需要的 rowKey 保持一致 - * - * @description - * 清理指定 key。 - * - * 实际上,在 naive ui 中,key 与 rows 是关联起来的。 - * 所以,为了避免歧义的存在,当你清理掉某个 key 时,对应的 rows 也会被清理掉。 - */ - const clearKey = (key: RowKey) => { - if (key === null || key === void 0) { - return - } - - let _row!: Recordable - - keysRef.value = keysRef.value.filter((curr) => curr !== key) - rowsRef.value = rowsRef.value.filter((curr) => { - if (curr[bindRowKey] === key) { - _row = curr - - return false - } - - return true - }) - - onChange?.(keysRef.value, rowsRef.value, { - row: _row as any, - action: 'uncheck', - }) - } - - /** - * - * @param keys 选中的 keys - * - * @description - * 选中指定的 keys。 - * 当你调用该方法时,会将 keys 与 data 中的 rows 进行比对,将匹配的 rows 添加到已选中的 rows 中。 - * - * 如果 multiple 为 false,那么只会选中一个 key;重复的选择,将会以最后一次绑定的 key 为准。 - * 所以,如果你需要选中多个 key,需要将 multiple 设置为 true。 - */ - const selectKey = (key: RowKey) => { - if (keysRef.value.includes(key)) { - return - } - - const multiple = !currentColumnIsMultiple.value && keysRef.value.length >= 1 - const row = findRow(unref(data) || [], bindRowKey, key) - - multiple ? (keysRef.value = [key]) : keysRef.value.push(key) - - if (row) { - multiple ? (rowsRef.value = [row]) : rowsRef.value.push(row) - - onChange?.(keysRef.value, rowsRef.value, { - row: row as any, - action: 'check', - }) - } - } - - /** - * - * @param keys 批量选中的 keys - * - * @description - * 批量选中指定的 keys。 - */ - const selectKeys = (keys: RowKey[]) => { - keys.forEach((key) => selectKey(key)) - } - - /** - * - * @param key 需要切换的 key - * - * @description - * 切换指定 key 的选中状态。 - */ - const toggleKey = (key: RowKey) => { - if (keysRef.value.includes(key)) { - clearKey(key) - } else { - selectKey(key) - } - } - - /** - * - * @param key 需要检查的 key - * - * @description - * 检查指定 key 是否被选中。 - */ - const isKeySelected = (key: RowKey) => { - return keysRef.value.includes(key) - } - - effectDispose(() => { - clearAll() - }) - - return [ - keysRef, - { - checkedRows: rowsRef as Ref, - checkedRowKeysBind: bind, - getKeys, - getRows, - clearAll, - clearKey, - selectKey, - selectKeys, - toggleKey, - isKeySelected, - }, - ] as const -} - -export type UseCheckedRowKeysReturn = ReturnType - -export default useCheckedRowKeys diff --git a/src/components/base/RTable/src/hooks/useTable.ts b/src/components/base/RTable/src/hooks/useTable.ts deleted file mode 100644 index 1b0363c5..00000000 --- a/src/components/base/RTable/src/hooks/useTable.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { printDom } from '@/utils' -import type { PrintDomOptions } from '@/utils' -import type { - ColumnKey, - CsvOptionsType, - FilterState, - RTableInst, - ScrollToOptions, - SortOrder, - TableProvider, - UseTableRegister, -} from '../types' - -/** - * - * @description - * 获取 RTable 实例。 - * 让你能够便捷的调用相关的一些已封装方法。 - * - * @warning - * 值得注意的是,必须手动调用 register 方法,否则不能正常使用。 - * 在使用 相关 hooks 的时候,需要注意生命周期,确保 register 方法已经被调用与表格实例已经被初始化; - * 不要在父组件 create 阶段就去调用 hook,如果需要,请使用 nextTick 包裹。 - * - * @example - * defineComponent({ - * setup() { - * const [register, { ...Hooks }] = useTable() - * - * return { - * register, - * ...Hooks, - * } - * }, - * render() { - * const { register, ...Hooks } = this - * - * return - * }, - * }) - */ -const useTable = () => { - const tableRef = shallowRef() - const extraRef = shallowRef({} as TableProvider) - - const register: UseTableRegister = (inst, extraInfo) => { - if (inst) { - tableRef.value = inst - extraRef.value = extraInfo - } - } - - /** - * - * @description - * 获取 RTable 实例。 - */ - const getTableInstance = () => { - if (!tableRef.value) { - throw new Error( - '[useTable]: table instance is not ready yet. if you are using useTable, please make sure you have called register method in onRegister event.', - ) - } - - return tableRef.value - } - - /** - * - * @description - * 清空所有 filter 状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter - */ - const clearFilters = () => getTableInstance().clearFilters.call(null) - - /** - * - * @description - * 清空所有 sort 状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter - */ - const clearSorter = () => getTableInstance().clearSorter.call(null) - - /** - * - * @description - * 下载 CSV。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#export-csv.vue - */ - const downloadCsv = (options?: CsvOptionsType) => - getTableInstance().downloadCsv.call(null, options) - - /** - * - * @description - * 设定表格当前的过滤器。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter - */ - const filters = (filters: FilterState | null) => - getTableInstance().filters.call(null, filters) - - /** - * - * @description - * 手动设置 page。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const page = (page: number) => getTableInstance().page.call(null, page) - - /** - * - * @description - * 滚动内容。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const scrollTo: ScrollToOptions = (options) => - // eslint-disable-next-line @typescript-eslint/no-explicit-any - getTableInstance().scrollTo(options as any) - - /** - * - * @description - * 设定表格的过滤状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const sort = (columnKey: ColumnKey, order: SortOrder) => - getTableInstance().sort.call(null, columnKey, order) - - /** - * - * @description - * 打印表格。 - */ - const print = (options?: PrintDomOptions) => { - const { uuidWrapper } = extraRef.value ?? {} - - if (uuidWrapper) { - const tableWrapperElement = document.getElementById(uuidWrapper) - - printDom(tableWrapperElement, options) - } - } - - /** - * - * @description - * 设定表格的过滤状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const filter = (filters: FilterState | null) => - getTableInstance().filter.call(null, filters) - - /** - * - * @description - * 获取 Table 组件配置。 - */ - const getTableConfig = () => extraRef.value - - return [ - register, - { - getTableInstance, - clearFilters, - clearSorter, - downloadCsv, - filters, - page, - scrollTo, - sort, - print, - filter, - getTableConfig, - }, - ] as const -} - -export type UseTableReturn = ReturnType - -export default useTable diff --git a/src/components/base/RTable/src/index.scss b/src/components/base/RTable/src/index.scss deleted file mode 100644 index beacafc6..00000000 --- a/src/components/base/RTable/src/index.scss +++ /dev/null @@ -1,16 +0,0 @@ -.r-table__c-tree { - & .n-tree-node-switcher.n-tree-node-switcher--hide { - visibility: visible; - } - - & .r-icon { - &.r-table__c-tool-icon--active { - color: var(--r-theme-primary-color); - } - } -} - -.r-table__setting:hover { - transform: rotate(180deg); - transition: transform 0.3s var(--r-bezier); -} diff --git a/src/components/base/RTable/src/props.ts b/src/components/base/RTable/src/props.ts deleted file mode 100644 index cc37b16d..00000000 --- a/src/components/base/RTable/src/props.ts +++ /dev/null @@ -1,252 +0,0 @@ -import type { MaybeArray, Recordable } from '@/types' -import { dataTableProps } from 'naive-ui' -import type { DataTableColumn, DropdownOption } from 'naive-ui' -import type { PropType, VNode } from 'vue' -import type { - DownloadCsvTableOptions, - PrintTableOptions, - RTableCardProps, - RTableInst, - UseTableRegister, -} from './types' - -const props = { - ...dataTableProps, - /** - * - * @description - * 当设置表格高度为弹性高度时,手动设置表格的高度。 - * - * @default undefined - */ - tableFlexHeight: { - type: [String, Number] as PropType, - default: void 0, - }, - /** - * - * @description - * 是否渲染外层容器 header,默认渲染。 - * 如果配置为 false,则不会显示外层容器的头部。 - * - * @default true - */ - renderWrapperHeader: { - type: Boolean, - default: true, - }, - /** - * - * @description - * 配置表格外层容器 props,也就是 NCard 的配置项。 - */ - cardProps: { - type: Object as PropType, - default: () => ({}), - }, - /** - * - * @description - * 是否启用表格工具栏。 - * - * 当设置为 false 时,不会显示表格工具栏。不论是否配置了 toolOptions。 - * - * @default true - */ - tool: { - type: Boolean, - default: true, - }, - /** - * - * @description - * 下载表格配置项。 - * - * @default {} - */ - downloadCsvTableOptions: { - type: Object as PropType, - default: () => ({}), - }, - /** - * - * @description - * 表格标题,支持 VNode。 - * - * @default null - */ - title: { - type: [String, Number, Object] as PropType, - default: null, - }, - /** - * - * @description - * 自定义工具栏配置项。 - * - * @default undefined - */ - toolOptions: { - type: Array as PropType<(VNode | (() => VNode))[]>, - }, - /** - * - * @description - * 是否覆盖原工具栏功能按钮。 - * - * @default false - */ - coverTool: { - type: Boolean, - default: false, - }, - /** - * - * @description - * 右键菜单配置项。 - * - * 基于 NDropdown 实现。 - * - * @default undefined - */ - contextMenuOptions: { - type: Array as PropType, - }, - /** - * - * @description - * 是否禁用右键菜单。 - * - * 如果设置为 false 则不会唤起右键菜单。 - * - * @default false - */ - disabledContextMenu: { - type: Boolean, - default: false, - }, - /** - * - * @description - * 右键菜单点击事件回调。 - * - * 该属性用于配置右键菜单点击事件。 - * - * @default null - */ - onContextMenuClick: { - type: [Function, Array] as PropType< - MaybeArray<(key: string | number, option: DropdownOption) => void> - >, - default: null, - }, - /** - * - * @description - * 表格容器边框。 - * - * 与表格边框为两个不同配置项。 - * - * @default true - */ - wrapperBordered: { - type: Boolean, - default: true, - }, - /** - * - * @description - * 表格边框。 - * - * @default true - */ - bordered: { - type: Boolean, - default: true, - }, - /** - * - * @description - * 打印表格配置项。 - * - * 基于 dom printDom 实现。 - * - * @default {} - */ - printTableOptions: { - type: Object as PropType, - default: () => ({}), - }, - /** - * - * @description - * 双向绑定列表列配置项事件。 - * - * 当配置为 v-model:columns 时,或者是单独调用 onUpdateColumns 时,该属性生效。 - * 双向绑定语法糖事件。 - * - * @default null - */ - onUpdateColumns: { - type: [Function, Array] as PropType< - MaybeArray<(arr: DataTableColumn[]) => void> - >, - default: null, - }, - /** - * - * @description - * 双向绑定列表列配置项事件。 - * - * 当配置为 v-model:columns 时,或者是单独调用 onUpdateColumns 时,该属性生效。 - * 双向绑定语法糖事件。 - * - * @default null - */ - 'onUpdate:columns': { - type: [Function, Array] as PropType< - MaybeArray<(arr: DataTableColumn[]) => void> - >, - default: null, - }, - /** - * - * @description - * 该属性用于启用右键菜单后被 Table 强行代理后的右键点击事件回调。 - * - * 当右键菜单不启用时,不生效。只需要使用 rowProps 属性配置右键菜单事件即可。 - * - * @default null - */ - onContextmenu: { - type: [Function, Array] as PropType< - MaybeArray<(row: Recordable, index: number, e: MouseEvent) => void> - >, - default: null, - }, - /** - * - * @description - * RTable 注册挂载成功后触发的事件。 - * 可以结合 useTable 方法中的 register 方法使用,然后便捷的使用 hooks。 - * - * @default null - */ - onRegister: { - type: [Function, Array] as PropType>, - default: null, - }, - /** - * - * @description - * 是否自动继承高度。 - * - * @default false - */ - flexAutoHeight: { - type: Boolean, - default: false, - }, -} as const - -export default props diff --git a/src/components/base/RTable/src/shared.ts b/src/components/base/RTable/src/shared.ts deleted file mode 100644 index dd498c40..00000000 --- a/src/components/base/RTable/src/shared.ts +++ /dev/null @@ -1,15 +0,0 @@ -export const config = { - tableIconSize: '18', - tableKey: Symbol('r-table'), -} - -export const propsOptions = [ - { - label: '斑马条纹', - value: 'striped', - }, - { - label: '表格边框', - value: 'bordered', - }, -] diff --git a/src/components/base/RTable/src/types.ts b/src/components/base/RTable/src/types.ts deleted file mode 100644 index 55976739..00000000 --- a/src/components/base/RTable/src/types.ts +++ /dev/null @@ -1,88 +0,0 @@ -import type { Recordable } from '@/types' -import type { PrintDomOptions } from '@/utils/dom' -import type { - CardProps, - DataTableBaseColumn, - DataTableColumn, - DataTableInst, - DropdownDividerOption, - DropdownGroupOption, - DropdownOption, - DropdownRenderOption, -} from 'naive-ui' -import type { CSSProperties, ShallowRef, VNode } from 'vue' - -export interface RTableCardProps extends CardProps { - style?: CSSProperties -} - -export type TableActionIcon = string | (() => VNode) - -export type DropdownMixedOption = - | DropdownOption - | DropdownGroupOption - | DropdownDividerOption - | DropdownRenderOption - -export interface DownloadCsvTableOptions { - fileName?: string - keepOriginalData?: boolean -} - -export interface PrintTableOptions extends PrintDomOptions {} - -export interface TableProvider { - uuidWrapper: string - uuidTable: string - wrapperRef: Readonly> - tableRef: Readonly> -} - -export interface C extends DataTableBaseColumn { - leftFixedActivated?: boolean - rightFixedActivated?: boolean - resizable?: boolean - isResizable?: boolean - isLeftFixedActivated?: boolean - isRightFixedActivated?: boolean - children?: C[] -} - -export interface RTableInst extends Omit { - /** - * - * @description - * 打印表格。 - */ - print: (options?: PrintDomOptions) => void - config: TableProvider -} - -export type OverridesTableColumn = C | DataTableColumn - -export interface TableInst extends Omit { - rTableInst: RTableInst -} - -export type PropsComponentPopselectKeys = 'striped' | 'bordered' - -type DownloadCsvParameters = Parameters - -export type CsvOptionsType = DownloadCsvParameters[0] - -type FiltersParameters = Parameters - -export type FilterState = FiltersParameters[0] - -export type ScrollToOptions = RTableInst['scrollTo'] - -type SortParameters = Parameters - -export type ColumnKey = SortParameters[0] - -export type SortOrder = SortParameters[1] - -export type UseTableRegister = ( - tableInst: RTableInst, - extra: TableProvider, -) => void diff --git a/src/components/base/RTablePro/README.md b/src/components/base/RTablePro/README.md new file mode 100644 index 00000000..3698a3de --- /dev/null +++ b/src/components/base/RTablePro/README.md @@ -0,0 +1,66 @@ +# TablePro + +统一从 `@/components` 导入 `RTablePro`。它沿用 Naive UI 的列、排序、选择和渲染配置;搜索、分页和工具栏按场景启用。 + +```tsx +import { RTablePro } from '@/components' + +// 纯表格:只渲染数据表,默认无工具栏和分页。 + + +// 完整模式:内置搜索,自动加载并分页。 + + +// 自适应高度:表格填充当前内容区,行在内部滚动。 + +``` + +- `data` 用于本地数据;`request(params, signal)` 用于远端数据,返回 `Promise<{ data: Row[]; total: number }>`。`total` 是应用筛选后的总数;传递 `signal` 给 HTTP 客户端可以取消上一条请求。 +- 搜索字段有 `key`、`label` 和可选的 `placeholder`、`options`(下拉选项)。输入文字只更新草稿,提交后回到第 1 页。本地文字匹配忽略大小写,下拉按值匹配;远端模式把搜索值传给 `request`。外部筛选可用 `params`,复杂表单可用 `filters` 插槽及其 `submit(values)` 方法。 +- 完整模式默认使用 DataTable 底部自带的分页器,每页 10 条。空间不足时使用 Naive UI 的简洁分页,也可通过 `pagination.simple` 指定模式。用 `pageSize`、`pagination={{ pageSizes: [10, 20, 50] }}` 调整,或用 `pagination={false}` 关闭。关闭时请求不附加 `page`、`pageSize`;`bare pagination` 可以单独保留分页。 +- 搜索区在结果上方。表格左上方可用 `title` 传文字,或用同名插槽放筛选开关、快捷操作等;都不传时不占位。`toolbar` 插槽和默认工具集中在表格右上方。 +- 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。 +- `autoHeight` 默认使用当前布局的可用高度,宿主外部使用视口高度;嵌入特定区域时可以用 CSS 变量 `--r-table-height` 覆盖。较短的屏幕保留表格的最小操作高度。 +- 只接收最新的请求结果。失败时保留已加载的数据并显示重试;可以用 `onRequestError` 处理错误,或用 `error` 插槽定制提示。 +- 需要实例时使用 `shallowRef()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`downloadCsv`、`print` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。 + +迁移时,把旧 `RTable` 改为 `RTablePro bare`(需要完整工具栏时省略 `bare`),把 `useTable` / `useTablePro` 的注册改为可选的实例 ref。旧版 `requestConfig` 可改为 `params` 或请求函数内的字段映射;`takeoverAutoHeight`、`flexAutoHeight` 改为 `autoHeight`。 + +## 列显示与缓存 + +只传普通 `columns` 数组,就能在同一套「列设置」里勾选显示、拖动顺序、固定列或启用列宽调整。默认由 TablePro 在当前实例内维护这些操作,不修改传入的数组。想跨刷新记住显示选择时,加一个稳定的表格标识: + +```tsx + +``` + +- 使用 Naive UI 的列 `key`,同一表的列 key 唯一且稳定。勾选状态独立于列定义;列分组会跟随子列,选择列和展开列不会被勾选隐藏。至少保留一个数据列。 +- 缓存是按表格标识分隔的本地偏好。只保存隐藏列的 key,启用或切换标识时读一次,用户改动时才写入。新增列默认显示,失效 key 不影响渲染,恢复全部列会清除缓存。不传标识时仅保留实例内状态。需要按账号或租户隔离时,将其标识纳入 key。 +- 页面需要接管列顺序、固定位置或 `resizable` 时,可以用 `v-model:columns`;收到的是完整列定义,包含已隐藏的列。显隐始终由列设置维护,固定列仍遵守 Naive UI 的数字列宽约定。 +- 不缓存行数据、列定义、回调、列宽、固定或顺序。默认模式用列 key 维护实例内的调整;更新列标题、渲染器等定义不会抹掉用户调整。 + +## 打印和 CSV + +内置打印按当前排序、筛选和分页打印**当前页数据和可见列**。使用单独的白底 HTML 表格,跨纸页重复表头;不打印搜索、操作、复选框、展开区、分页或插槽。虚拟滚动不影响取数。需要特殊单元格文本时用 `formatCell`;未配置时沿用 `getCsvCell` 或字段值。自定义 Vue 单元格、树展开状态和合并格不会复刻为打印布局;需要复刻时指定自定义区域。 + +```tsx + +``` + +内置按钮使用 `printTableOptions`。单次打印可以用 `table.value?.print({ target: reportRef, title: '报表', style: '@page { size: landscape; }' })` 覆盖配置;目标支持元素、ref 或 getter。自定义区域以独立打印文档呈现,可用 `style` 提供专用 CSS,或用 `data-print-ignore` 排除其中的控件。旧版 `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`。 + +在「表格」菜单下,可分别查看纯表格、远端查询与分页(含服务端排序和错误重试)、自适应高度(含虚拟滚动)、列设置与缓存、默认和自定义打印、插槽与实例操作。旧示例路径会重定向到对应子页。 diff --git a/src/components/base/RTablePro/index.ts b/src/components/base/RTablePro/index.ts new file mode 100644 index 00000000..2423e7a3 --- /dev/null +++ b/src/components/base/RTablePro/index.ts @@ -0,0 +1,9 @@ +export { default as RTablePro } from './src/TablePro' +export type { TableProInst, TableProProps } from './src/TablePro' +export type { + TableProParams, + TableProRequest, + TableProResult, + TableProSearchField, + TableProPrintOptions, +} from './src/types' diff --git a/src/components/base/RTablePro/src/TablePanel.tsx b/src/components/base/RTablePro/src/TablePanel.tsx new file mode 100644 index 00000000..bcfc97d4 --- /dev/null +++ b/src/components/base/RTablePro/src/TablePanel.tsx @@ -0,0 +1,291 @@ +import './index.scss' +import { useI18n } from '@/hooks/template/useI18n' +import { useElementSize } from '@vueuse/core' +import { NDataTable, NDropdown } 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 Fullscreen from './components/Fullscreen' +import TablePropsSelect from './components/Props' +import Size from './components/Size' +import ToolButton from './components/ToolButton' +import { buildTableCsv, downloadTableCsv } from './csv' +import { + buildPrintableTable, + printTableContent, + resolvePrintContent, +} from './printing' +import props from './props' +import { config } from './shared' +import type { PropsComponentPopselectKeys, TablePanelInst } from './types' + +export default defineComponent({ + name: 'TablePanel', + inheritAttrs: false, + props, + setup(props, { attrs, slots, expose }) { + const { t } = useI18n('table') + const table = useTemplateRef('dataTable') + const wrapper = useTemplateRef('wrapper') + const responsivePager = computed(() => + typeof props.pagination === 'object' && props.pagination.simple == null + ? wrapper.value + : null, + ) + const { width } = useElementSize(responsivePager) + const { layoutColumns, reorderColumns, patchColumn } = useColumnLayout( + toRef(props, 'columns'), + toRef(props, 'onUpdate:columns'), + ) + const { hiddenKeys, visibleColumns, setColumnVisible, resetColumns } = + useColumnVisibility(layoutColumns, toRef(props, 'columnStateKey')) + const printing = ref(false) + + 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 }) + + watch( + () => props.size, + (value) => { + size.value = value + }, + ) + watch( + () => props.striped, + (value) => { + appearance.striped = value + }, + ) + watch( + () => props.bordered, + (value) => { + appearance.bordered = value + }, + ) + + const handle: TablePanelInst = { + getTableInstance: () => table.value, + downloadCsv: (options) => { + const { fileName, keepOriginalData } = { + ...props.downloadCsvTableOptions, + ...options, + } + const rows = keepOriginalData + ? props.data + : table.value?.getCurrentPageData() + + if (rows) + downloadTableCsv( + buildTableCsv( + visibleColumns.value, + rows, + props.getCsvCell, + props.getCsvHeader, + ), + fileName, + ) + }, + print: async (options) => { + if (printing.value || props.loading) return false + + const printOptions = { + title: typeof props.title === 'string' ? props.title : '', + formatCell: props.getCsvCell, + formatHeader: props.getCsvHeader, + ...props.printTableOptions, + ...options, + } + + printing.value = true + + try { + const content = resolvePrintContent(printOptions, () => { + const rows = table.value?.getCurrentPageData() + + return rows + ? buildPrintableTable( + document, + visibleColumns.value, + rows, + printOptions, + ) + : null + }) + + return !!content && (await printTableContent(content, printOptions)) + } catch (error) { + console.error('[TablePro]: Could not open print preview.', error) + + return false + } finally { + printing.value = false + } + }, + } + + expose(handle) + + const rowProps: NonNullable = (row, index) => { + const original = props.rowProps?.(row, index) + + if (!props.contextMenuOptions?.length) return original ?? {} + + return { + ...original, + onContextmenu: (event: PointerEvent) => { + original?.onContextmenu?.(event) + + if (event.defaultPrevented) return + + event.preventDefault() + Object.assign(context, { + x: event.clientX, + y: event.clientY, + show: true, + }) + }, + } + } + + const changeAppearance = (values: PropsComponentPopselectKeys[]) => { + appearance.striped = values.includes('striped') + appearance.bordered = values.includes('bordered') + } + + return () => { + const { + bare, + autoHeight, + title, + tool, + contextMenuOptions, + onContextMenuClick, + 'onUpdate:columns': updateColumns, + downloadCsvTableOptions, + printTableOptions, + columnStateKey, + pagination, + ...dataTableProps + } = props + const { + filters, + title: titleSlot, + toolbar, + notice, + tableFooter, + tableAction, + ...dataTableSlots + } = slots + const showToolbar = !bare && (tool || toolbar) + const headerTitle = bare ? null : titleSlot ? ( + titleSlot() + ) : typeof title === 'string' && title ? ( +

{title}

+ ) : ( + title + ) + const extras = tableFooter?.() + const actions = tableAction?.() + const mergedPagination = + typeof pagination === 'object' && width.value > 0 && width.value < 600 + ? { simple: true, ...pagination } + : pagination + + return ( +
+ {filters?.()} + {notice?.()} +
+ {headerTitle || showToolbar ? ( +
+ {headerTitle ? ( +
{headerTitle}
+ ) : null} + {showToolbar ? ( +
+ {toolbar?.()} + {tool ? ( + <> + { + if (!(await handle.print())) + window.$message?.error(t('printError')) + }} + /> + { + size.value = value + }} + /> + + {props.columns.length ? ( + + ) : null} + + + ) : null} +
+ ) : null} +
+ ) : null} + + {dataTableSlots} + +
+ {extras ? : null} + {actions ?
{actions}
: null} + {contextMenuOptions?.length ? ( + { + context.show = false + }} + onSelect={(key, option) => { + context.show = false + onContextMenuClick?.(key, option) + }} + /> + ) : null} +
+ ) + } + }, +}) diff --git a/src/components/base/RTablePro/src/TablePro.tsx b/src/components/base/RTablePro/src/TablePro.tsx new file mode 100644 index 00000000..5c4133f3 --- /dev/null +++ b/src/components/base/RTablePro/src/TablePro.tsx @@ -0,0 +1,297 @@ +import { useI18n } from '@/hooks/template/useI18n' +import { call } from '@/utils/vue/call' +import { NAlert, NButton } from 'naive-ui' +import type { PaginationProps } from 'naive-ui' +import type { ExtractPublicPropTypes, PropType } from 'vue' +import Search from './components/Search' +import tableProps from './props' +import TablePanel from './TablePanel' +import type { + TablePanelInst, + TableProParams, + TableProRequest, + TableProResult, + TableProSearchField, + TableSearchValues, +} from './types' + +const positiveInteger = (value: number) => + Number.isSafeInteger(value) && value > 0 + +const props = { + ...tableProps, + pagination: { + type: [Boolean, Object] as PropType, + default: void 0, + }, + pageSize: { type: Number, default: 10 }, + request: Function as PropType, + params: Object, + search: Array as PropType, + rowKey: { + type: tableProps.rowKey, + default: (row: { id?: string | number; key?: string | number }) => + row.id ?? row.key, + }, +} + +export type TableProProps = ExtractPublicPropTypes + +export interface TableProInst extends TablePanelInst { + reload: (resetPage?: boolean) => Promise + setPage: (page: number) => Promise + setPageSize: (pageSize: number) => Promise +} + +export default defineComponent({ + name: 'RTablePro', + inheritAttrs: false, + props, + emits: { 'request-error': (_error: unknown) => true }, + setup(props, { attrs, slots, expose, emit }) { + const { t } = useI18n('table') + const table = shallowRef() + const result = shallowRef({ data: [], total: 0 }) + const loading = ref(false) + const failed = ref(false) + const searchValues = shallowRef({}) + const pagination = computed(() => props.pagination ?? !props.bare) + const pagerOptions = computed(() => + typeof props.pagination === 'object' ? props.pagination : void 0, + ) + const configuredPageSize = computed(() => { + const size = + pagerOptions.value?.pageSize ?? + pagerOptions.value?.defaultPageSize ?? + props.pageSize + + return positiveInteger(size) ? size : 10 + }) + const firstPage = pagerOptions.value?.defaultPage ?? 1 + const page = ref(positiveInteger(firstPage) ? firstPage : 1) + const pageSize = ref(configuredPageSize.value) + const localRows = computed(() => { + const entries = Object.entries(searchValues.value) + + if (!entries.length) return props.data + + const selects = new Set( + props.search?.filter(({ options }) => options).map(({ key }) => key), + ) + + return props.data.filter((row) => + entries.every(([key, value]) => { + const cell = row[key] + + return typeof value === 'number' || selects.has(key) + ? cell === value + : String(cell ?? '') + .toLowerCase() + .includes(value.toLowerCase()) + }), + ) + }) + let pending: AbortController | undefined + + const reload = async (resetPage = false) => { + if (resetPage) page.value = 1 + + pending?.abort() + failed.value = false + const { request, params } = props + + if (!request) { + pending = void 0 + loading.value = false + + return + } + + const current = new AbortController() + + pending = current + loading.value = true + + // 分页字段由表格统一管理,筛选参数不能覆盖当前页码。 + const query: TableProParams = { ...params, ...searchValues.value } + + if (pagination.value !== false) { + 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 (pagination.value !== false && page.value > lastPage) { + page.value = lastPage + + if (response.total) { + await reload() + + return + } + } + + result.value = response + } catch (error) { + if (current.signal.aborted) return + + failed.value = true + emit('request-error', error) + } finally { + if (pending === current) { + pending = void 0 + loading.value = false + } + } + } + + const setPage = async (value: number) => { + if (!positiveInteger(value) || page.value === value) return + + page.value = value + await reload() + } + + const setPageSize = async (value: number) => { + if (!positiveInteger(value) || pageSize.value === value) return + + pageSize.value = value + await reload(true) + } + + const submitSearch = (values: TableSearchValues) => { + searchValues.value = values + + return reload(true) + } + + watch( + [ + () => props.request, + () => props.params, + () => pagination.value === false, + configuredPageSize, + ], + (_values, previous) => { + 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 = { + reload, + setPage, + setPageSize, + getTableInstance: () => table.value?.getTableInstance() ?? null, + print: (options) => table.value?.print(options) ?? Promise.resolve(false), + downloadCsv: (options) => table.value?.downloadCsv(options), + } + + expose(instance) + + return () => { + const { + request, + params, + pagination: _pagination, + pageSize: _pageSize, + search, + loading: externalLoading, + remote, + onUpdatePage, + onUpdatePageSize, + ...rest + } = props + const options = pagerOptions.value + const { filters, error, notice, ...panelSlots } = slots + const paginationProps: false | PaginationProps = + pagination.value === false + ? false + : { + 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), + ...(request + ? { itemCount: result.value.total, pageCount: void 0 } + : {}), + } + + return ( + { + void setPage(value) + + if (onUpdatePage) call(onUpdatePage, value) + }} + onUpdatePageSize={(value) => { + void setPageSize(value) + + if (onUpdatePageSize) call(onUpdatePageSize, value) + }} + > + {{ + ...panelSlots, + filters: filters + ? () => filters({ submit: submitSearch }) + : search?.length + ? () => + : void 0, + notice: () => + failed.value + ? (error?.({ reload }) ?? ( + + reload()}> + {t('retry')} + + + )) + : notice?.(), + }} + + ) + } + }, +}) diff --git a/src/components/base/RTablePro/src/columns.ts b/src/components/base/RTablePro/src/columns.ts new file mode 100644 index 00000000..c42c7972 --- /dev/null +++ b/src/components/base/RTablePro/src/columns.ts @@ -0,0 +1,201 @@ +import { getStorage, removeStorage, setStorage } from '@/utils/cache' +import type { DataTableColumn } from 'naive-ui' +import type { Ref } from 'vue' + +export type TableColumnKey = string | number +export type KeyedColumn = Extract +export type LeafColumn = Exclude +export type ColumnLayoutPatch = Partial< + Pick +> + +export const hasColumnKey = (column: DataTableColumn): column is KeyedColumn => + 'key' in column + +export const getLeafColumns = (columns: DataTableColumn[]): LeafColumn[] => + columns.flatMap((column) => + !hasColumnKey(column) + ? [] + : 'children' in column + ? getLeafColumns(column.children) + : [column], + ) + +const applyRootOrder = ( + columns: DataTableColumn[], + order: TableColumnKey[], +) => { + const orderedKeys = new Set(order) + const byKey = new Map( + columns.filter(hasColumnKey).map((column) => [column.key, column]), + ) + const ordered = order.flatMap((key) => byKey.get(key) ?? []) + let index = 0 + + // 新列和选择/展开列保留输入的位置,已有列按 key 恢复顺序。 + return columns.map((column) => + hasColumnKey(column) && orderedKeys.has(column.key) + ? ordered[index++] + : column, + ) +} + +export const useColumnLayout = ( + columns: Ref, + onUpdate: Ref<((columns: DataTableColumn[]) => void) | undefined>, +) => { + const order = shallowRef() + const patches = shallowRef>() + + const layoutColumns = computed(() => { + if (onUpdate.value) return columns.value + + const arranged = order.value + ? applyRootOrder(columns.value, order.value) + : columns.value + const adjustments = patches.value + + if (!adjustments?.size) return arranged + + return arranged.map((column) => { + const patch = hasColumnKey(column) && adjustments.get(column.key) + + return patch ? { ...column, ...patch } : column + }) + }) + + const reorderColumns = (keys: TableColumnKey[]) => { + if (onUpdate.value) { + onUpdate.value(applyRootOrder(columns.value, keys)) + } else { + order.value = keys + } + } + + const patchColumn = (key: TableColumnKey, patch: ColumnLayoutPatch) => { + if (onUpdate.value) { + onUpdate.value( + columns.value.map((column) => + hasColumnKey(column) && column.key === key + ? { ...column, ...patch } + : column, + ), + ) + } else { + const next = new Map(patches.value) + + next.set(key, { ...next.get(key), ...patch }) + patches.value = next + } + } + + return { layoutColumns, reorderColumns, patchColumn } +} + +const filterColumns = ( + columns: DataTableColumn[], + hidden: ReadonlySet, +): DataTableColumn[] => { + const filtered = columns.flatMap((column): DataTableColumn[] => { + if (!hasColumnKey(column)) return [column] + + if (!('children' in column)) return hidden.has(column.key) ? [] : [column] + + const children = column.children.filter((child) => !hidden.has(child.key)) + + if (!children.length) return [] + + return [ + children.length === column.children.length + ? column + : { ...column, children }, + ] + }) + + return filtered.length === columns.length && + filtered.every((column, index) => column === columns[index]) + ? columns + : filtered +} + +const storageKey = (key?: string) => { + const scope = key?.trim() + + return scope ? `table-pro:columns:v1:${scope}` : '' +} +const storageOptions = { prefix: true } as const +const isColumnKey = (value: unknown): value is TableColumnKey => + typeof value === 'string' || + (typeof value === 'number' && Number.isFinite(value)) + +export const useColumnVisibility = ( + columns: Ref, + scope: Ref, +) => { + const hidden = shallowRef(new Set()) + const keys = computed(() => [ + ...new Set(getLeafColumns(columns.value).map(({ key }) => key)), + ]) + + watch( + () => storageKey(scope.value), + (key) => { + const stored = key + ? getStorage(key, 'localStorage', storageOptions) + : null + + hidden.value = new Set( + Array.isArray(stored) ? stored.filter(isColumnKey) : [], + ) + }, + { immediate: true }, + ) + + const hiddenKeys = computed(() => { + if (!hidden.value.size) return hidden.value + + const active = new Set(keys.value.filter((key) => hidden.value.has(key))) + + // 列定义动态收缩时,至少保留一个可用的数据列。 + if (active.size && active.size === keys.value.length) + active.delete(keys.value[0]) + + return active + }) + const visibleColumns = computed(() => + hiddenKeys.value.size + ? filterColumns(columns.value, hiddenKeys.value) + : columns.value, + ) + const visibleCount = computed(() => keys.value.length - hiddenKeys.value.size) + + const persist = (next: Set) => { + hidden.value = next + const key = storageKey(scope.value) + + if (!key) return + + if (next.size) setStorage(key, [...next], 'localStorage', storageOptions) + else removeStorage(key, 'localStorage', storageOptions) + } + + const setColumnVisible = (key: TableColumnKey, visible: boolean) => { + if (!keys.value.includes(key) || visible !== hiddenKeys.value.has(key)) + return + + if (!visible && visibleCount.value <= 1) return + + const next = new Set(hiddenKeys.value) + + if (visible) next.delete(key) + else next.add(key) + + persist(next) + } + + const resetColumns = () => { + if (hidden.value.size) persist(new Set()) + } + + return { hiddenKeys, visibleColumns, setColumnVisible, resetColumns } +} diff --git a/src/components/base/RTablePro/src/components/C.tsx b/src/components/base/RTablePro/src/components/C.tsx new file mode 100644 index 00000000..5c30d156 --- /dev/null +++ b/src/components/base/RTablePro/src/components/C.tsx @@ -0,0 +1,191 @@ +import { useI18n } from '@/hooks/template/useI18n' +import { NButton, NFlex, NPopover, NTree } from 'naive-ui' +import type { TreeDropInfo, TreeOption } from 'naive-ui' +import type { PropType } from 'vue' +import { getLeafColumns, hasColumnKey } from '../columns' +import type { ColumnLayoutPatch, KeyedColumn, TableColumnKey } from '../columns' +import props from '../props' +import ToolButton from './ToolButton' + +export default defineComponent({ + name: 'TableColumns', + props: { + columns: props.columns, + hiddenKeys: { + type: Object as PropType>, + required: true, + }, + }, + emits: { + reorderColumns: (_keys: TableColumnKey[]) => true, + patchColumn: (_key: TableColumnKey, _patch: ColumnLayoutPatch) => true, + toggleColumn: (_key: TableColumnKey, _visible: boolean) => true, + resetColumns: () => true, + }, + setup(props, { emit }) { + const { t } = useI18n('table') + const columns = computed(() => props.columns.filter(hasColumnKey)) + const rootKeys = computed( + () => new Set(columns.value.map(({ key }) => key)), + ) + const leaves = computed(() => getLeafColumns(props.columns)) + const visibleCount = computed( + () => leaves.value.filter(({ key }) => !props.hiddenKeys.has(key)).length, + ) + + const reorder = ({ node, dragNode, dropPosition }: TreeDropInfo) => { + if ( + dropPosition === 'inside' || + node.key === dragNode.key || + node.key == null + ) + return + + const dragged = columns.value.find(({ key }) => key === dragNode.key) + const remaining = columns.value.filter(({ key }) => key !== dragNode.key) + const targetIndex = remaining.findIndex(({ key }) => key === node.key) + + if (!dragged || targetIndex < 0) return + + remaining.splice( + targetIndex + (dropPosition === 'after' ? 1 : 0), + 0, + dragged, + ) + emit( + 'reorderColumns', + remaining.map(({ key }) => key), + ) + } + + const arrangeTools = (column: KeyedColumn) => { + const hasWidth = + 'children' in column + ? column.children.every((child) => typeof child.width === 'number') + : typeof column.width === 'number' + + return ( + + + emit('patchColumn', column.key, { + fixed: column.fixed === 'left' ? void 0 : 'left', + }) + } + /> + {!('children' in column) ? ( + + emit('patchColumn', column.key, { + resizable: !column.resizable, + }) + } + /> + ) : null} + + emit('patchColumn', column.key, { + fixed: column.fixed === 'right' ? void 0 : 'right', + }) + } + /> + + ) + } + + const toTree = (items: KeyedColumn[], root: boolean): TreeOption[] => + items.map((column) => ({ + 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, + })) + + const tree = computed(() => toTree(columns.value, true)) + + return () => + columns.value.length ? ( + + {{ + trigger: () => ( + + ), + default: () => ( +
+ {t('visibleColumns')} + + node.key != null && + rootKeys.value.has(node.key) && + dropPosition !== 'inside' + } + onDrop={reorder} + renderLabel={({ option }) => { + const { key, label, children } = option + + if (children || key == null) return label + + const checked = !props.hiddenKeys.has(key) + + return ( + + ) + }} + /> + emit('resetColumns')} + > + {t('showAllColumns')} + +
+ ), + }} +
+ ) : null + }, +}) diff --git a/src/components/base/RTablePro/src/components/Fullscreen.tsx b/src/components/base/RTablePro/src/components/Fullscreen.tsx new file mode 100644 index 00000000..5e3cd7b8 --- /dev/null +++ b/src/components/base/RTablePro/src/components/Fullscreen.tsx @@ -0,0 +1,25 @@ +import { useI18n } from '@/hooks/template/useI18n' +import { useFullscreen } from 'vue-hooks-plus' +import { config } from '../shared' +import ToolButton from './ToolButton' + +export default defineComponent({ + name: 'TableFullscreen', + setup() { + const wrapper = inject(config.wrapperKey) + const [isFullscreen, { toggleFullscreen, isEnabled }] = + useFullscreen(wrapper) + const { t } = useI18n('headerTooltip') + + return () => ( + + ) + }, +}) diff --git a/src/components/base/RTablePro/src/components/Props.tsx b/src/components/base/RTablePro/src/components/Props.tsx new file mode 100644 index 00000000..346c4ff2 --- /dev/null +++ b/src/components/base/RTablePro/src/components/Props.tsx @@ -0,0 +1,28 @@ +import { useI18n } from '@/hooks/template/useI18n' +import { NPopselect } from 'naive-ui' +import type { PropsComponentPopselectKeys } from '../types' +import ToolButton from './ToolButton' + +export default defineComponent({ + name: 'TablePropsSelect', + props: { striped: Boolean, bordered: Boolean }, + emits: { change: (_value: PropsComponentPopselectKeys[]) => true }, + setup(props, { emit }) { + const { t } = useI18n('table') + const keys = ['striped', 'bordered'] as const + + return () => ( + props[key])} + options={keys.map((key) => ({ label: t(key), value: key }))} + trigger="click" + multiple + onUpdateValue={(value) => + emit('change', value as PropsComponentPopselectKeys[]) + } + > + + + ) + }, +}) diff --git a/src/components/base/RTablePro/src/components/Search.tsx b/src/components/base/RTablePro/src/components/Search.tsx new file mode 100644 index 00000000..24f1a714 --- /dev/null +++ b/src/components/base/RTablePro/src/components/Search.tsx @@ -0,0 +1,87 @@ +import { useI18n } from '@/hooks/template/useI18n' +import { NButton, NInput, NSelect } from 'naive-ui' +import { useId } from 'vue' +import type { PropType } from 'vue' +import type { TableProSearchField, TableSearchValues } from '../types' + +export default defineComponent({ + name: 'TableProSearch', + props: { + fields: { type: Array as PropType, required: true }, + }, + emits: { search: (_values: TableSearchValues) => true }, + setup(props, { emit }) { + const { t } = useI18n('table') + const id = useId() + const values = reactive>({}) + const submit = (event: SubmitEvent) => { + event.preventDefault() + const result: TableSearchValues = {} + + for (const { key } of props.fields) { + const value = values[key] + const normalized = typeof value === 'string' ? value.trim() : value + + if (normalized != null && normalized !== '') result[key] = normalized + } + + emit('search', result) + } + + const reset = () => { + Object.keys(values).forEach((key) => delete values[key]) + emit('search', {}) + } + + return () => ( + + ) + }, +}) diff --git a/src/components/base/RTablePro/src/components/Size.tsx b/src/components/base/RTablePro/src/components/Size.tsx new file mode 100644 index 00000000..ca6defd1 --- /dev/null +++ b/src/components/base/RTablePro/src/components/Size.tsx @@ -0,0 +1,32 @@ +import { useI18n } from '@/hooks/template/useI18n' +import { NPopselect } from 'naive-ui' +import type { DataTableProps } from 'naive-ui' +import tableProps from '../props' +import ToolButton from './ToolButton' + +export default defineComponent({ + name: 'TableSizeSelect', + props: { size: tableProps.size }, + emits: { change: (_size: DataTableProps['size']) => true }, + setup(props, { emit }) { + const { t } = useI18n('table') + + return () => ( + { + if (value === 'small' || value === 'medium' || value === 'large') + emit('change', value) + }} + > + + + ) + }, +}) diff --git a/src/components/base/RTablePro/src/components/ToolButton.tsx b/src/components/base/RTablePro/src/components/ToolButton.tsx new file mode 100644 index 00000000..2c80e115 --- /dev/null +++ b/src/components/base/RTablePro/src/components/ToolButton.tsx @@ -0,0 +1,34 @@ +import { RIcon } from '@/components/base/RIcon' +import type { IconName } from '@/icons' +import { NButton } from 'naive-ui' +import type { PropType } from 'vue' +import { config } from '../shared' + +export default defineComponent({ + props: { + icon: { type: String as PropType, required: true }, + label: { type: String, required: true }, + disabled: Boolean, + onClick: { + type: Function as PropType<(event: MouseEvent) => unknown>, + default: void 0, + }, + }, + setup(props) { + return () => ( + + {{ + icon: () => , + }} + + ) + }, +}) diff --git a/src/components/base/RTablePro/src/csv.ts b/src/components/base/RTablePro/src/csv.ts new file mode 100644 index 00000000..e7a32bf0 --- /dev/null +++ b/src/components/base/RTablePro/src/csv.ts @@ -0,0 +1,63 @@ +import { get } from 'lodash-es' +import type { DataTableColumn, DataTableProps } from 'naive-ui' +import { getLeafColumns } from './columns' + +const encodeCell = (value: unknown) => { + const text = value == null ? '' : String(value) + const formula = + typeof value !== 'number' && + typeof value !== 'bigint' && + /^[\s\uFEFF]*[=+\-@=+-@]|^[\t\r\n]/u.test(text) + + return `"${formula ? "'" : ''}${text.replaceAll('"', '""')}"` +} + +export const buildTableCsv = ( + columns: DataTableColumn[], + data: Record[], + getCell?: DataTableProps['getCsvCell'], + getHeader?: DataTableProps['getCsvHeader'], +) => { + const leaves = getLeafColumns(columns).filter( + (column) => column.allowExport !== false, + ) + const header = leaves + .map((column) => + encodeCell( + getHeader?.(column) ?? + (typeof column.title === 'string' ? column.title : column.key), + ), + ) + .join(',') + + return [ + header, + ...data.map((row) => + leaves + .map((column) => { + const value = get(row, column.key) + + return encodeCell(getCell ? getCell(value, row, column) : value) + }) + .join(','), + ), + ].join('\r\n') +} + +export const downloadTableCsv = (csv: string, fileName = 'data.csv') => { + const url = URL.createObjectURL( + new Blob(['\uFEFF', csv], { type: 'text/csv;charset=utf-8' }), + ) + const link = document.createElement('a') + + link.href = url + link.download = fileName.endsWith('.csv') ? fileName : `${fileName}.csv` + document.body.append(link) + + try { + link.click() + } finally { + link.remove() + setTimeout(() => URL.revokeObjectURL(url), 0) + } +} diff --git a/src/components/base/RTablePro/src/index.scss b/src/components/base/RTablePro/src/index.scss new file mode 100644 index 00000000..3f4db069 --- /dev/null +++ b/src/components/base/RTablePro/src/index.scss @@ -0,0 +1,165 @@ +.r-table { + container: table-panel / inline-size; + display: flex; + flex-direction: column; + gap: 16px; + inline-size: 100%; + min-inline-size: 0; + + &__result { + display: flex; + flex-direction: column; + gap: 8px; + min-inline-size: 0; + } + + &__header { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px 16px; + + h2 { + color: var(--r-text); + font-size: 18px; + font-weight: 650; + line-height: 1.4; + } + } + + &__toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: flex-end; + gap: 6px; + margin-inline-start: auto; + } + + &__heading { + min-inline-size: 0; + } + + &--fill { + block-size: var( + --r-table-height, + max( + 20rem, + calc( + var(--layout-content-height, 100dvh) - 2 * + var(--layout-content-gutter, 16px) + ) + ) + ); + + > .r-table__result, + > .r-table__result > .n-data-table { + flex: 1; + min-block-size: 0; + } + } + + &:fullscreen { + box-sizing: border-box; + padding: 12px; + background: var(--r-surface); + overflow: auto; + } + + &__footer, + &__action { + color: var(--r-text-secondary); + font-size: 13px; + } + + &__tool[aria-pressed='true'] { + color: var(--r-selected-text); + background: var(--r-surface-hover); + } +} + +.r-table-search { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 12px; + + &__field { + display: grid; + flex: 0 1 16rem; + min-inline-size: min(100%, 12rem); + gap: 6px; + color: var(--r-text-secondary); + font-size: 13px; + font-weight: 550; + } + + &__actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + } +} + +.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; + } + + .r-table__tool { + inline-size: 30px; + padding-inline: 0; + } + + .r-table-search__field { + flex: 1 1 100%; + } + + .r-table-search__actions { + margin-inline-start: auto; + } +} + +.r-table-columns { + min-inline-size: 0; + max-inline-size: min(26rem, calc(100vw - 36px)); + max-block-size: min(28rem, 65dvh); + overflow: auto; + padding: 0; + border: 0; + + legend { + margin-block-end: 6px; + color: var(--r-text); + font-weight: 600; + } + + &__check { + display: inline-flex; + align-items: center; + min-block-size: 44px; + gap: 8px; + cursor: pointer; + + input { + inline-size: 16px; + block-size: 16px; + flex: none; + accent-color: var(--r-theme-primary-color); + } + + span { + overflow-wrap: anywhere; + } + } +} diff --git a/src/components/base/RTablePro/src/printing.ts b/src/components/base/RTablePro/src/printing.ts new file mode 100644 index 00000000..aa500a6e --- /dev/null +++ b/src/components/base/RTablePro/src/printing.ts @@ -0,0 +1,187 @@ +import { unrefElement } from '@/utils/vue/unref-element' +import { get } from 'lodash-es' +import type { DataTableColumn } from 'naive-ui' +import { getLeafColumns, hasColumnKey } from './columns' +import type { TableProPrintOptions } from './types' + +const printStyles = ` + @page { margin: 12mm; } + :root { color-scheme: light; } + body { margin: 0; background: white; color: #171717; font: 9pt/1.4 system-ui, sans-serif; } + table { width: 100%; border-collapse: collapse; } + thead { display: table-header-group; } + tr { break-inside: avoid; } + th, td { padding: 3pt 5pt; border: 1px solid #b7bec6; text-align: start; overflow-wrap: anywhere; vertical-align: top; } + th { font-weight: 650; background: #f1f3f5; word-break: keep-all; overflow-wrap: break-word; } + img, svg { max-width: 100%; } + [data-print-ignore] { display: none !important; } +` + +const displayText = (value: unknown): string => { + if (value == null) return '' + + if (Array.isArray(value)) return value.map(displayText).join(', ') + + if (value instanceof Date) return value.toLocaleString() + + return ['string', 'number', 'boolean', 'bigint'].includes(typeof value) + ? String(value) + : '' +} + +export const buildPrintableTable = ( + doc: Document, + columns: DataTableColumn[], + rows: Record[], + { formatHeader, formatCell }: TableProPrintOptions = {}, +) => { + const table = doc.createElement('table') + const leaves = getLeafColumns(columns) + const header = table.createTHead() + const depth = (items: DataTableColumn[]): number => + Math.max( + 0, + ...items + .filter(hasColumnKey) + .map((column) => + 'children' in column + ? getLeafColumns(column.children).length + ? 1 + depth(column.children) + : 0 + : 1, + ), + ) + const headers = Array.from({ length: depth(columns) }, () => + header.insertRow(), + ) + + const appendHeaders = (items: DataTableColumn[], level: number) => { + for (const column of items.filter(hasColumnKey)) { + const children = + 'children' in column ? getLeafColumns(column.children) : null + + if (children && !children.length) continue + + const cell = doc.createElement('th') + + cell.textContent = + (children + ? void 0 + : formatHeader?.(column as (typeof leaves)[number])) ?? + (typeof column.title === 'string' ? column.title : String(column.key)) + + if ('children' in column) { + cell.colSpan = children!.length + cell.scope = 'colgroup' + appendHeaders(column.children, level + 1) + } else { + cell.rowSpan = headers.length - level + cell.scope = 'col' + } + + headers[level].append(cell) + } + } + + appendHeaders(columns, 0) + const body = table.createTBody() + + for (const row of rows) { + const tr = body.insertRow() + + for (const column of leaves) { + const value = get(row, column.key) + + tr.insertCell().textContent = + formatCell?.(value, row, column) ?? displayText(value) + } + } + + return table +} + +const cloneRegion = (target: HTMLElement) => { + const clone = target.cloneNode(true) as HTMLElement + + clone + .querySelectorAll('script, iframe, object, embed, link, base, meta') + .forEach((node) => node.remove()) + + for (const node of [clone, ...clone.querySelectorAll('*')]) { + for (const name of node.getAttributeNames()) { + if (name.startsWith('on')) node.removeAttribute(name) + } + } + + return clone +} + +export const resolvePrintContent = ( + options: TableProPrintOptions, + defaultTable: () => HTMLElement | null, +) => { + if (options.target == null) return defaultTable() + + const target = unrefElement(options.target) + + return target instanceof HTMLElement ? cloneRegion(target) : null +} + +export const printTableContent = async ( + content: HTMLElement, + options: TableProPrintOptions, +) => { + const frame = document.createElement('iframe') + + frame.tabIndex = -1 + frame.setAttribute('sandbox', 'allow-same-origin allow-modals') + frame.setAttribute('aria-hidden', 'true') + frame.title = options.title || 'TablePro print' + frame.style.cssText = 'position:fixed;inset:0;width:0;height:0;border:0;' + document.body.append(frame) + + let cleanupTimer: ReturnType | undefined + const cleanup = () => { + clearTimeout(cleanupTimer) + frame.remove() + } + + try { + const doc = frame.contentDocument + const view = frame.contentWindow + + if (!doc || !view) throw new Error('Print document is unavailable.') + + doc.documentElement.lang = document.documentElement.lang + doc.title = options.title ?? '' + const style = doc.createElement('style') + + style.textContent = printStyles + (options.style ?? '') + doc.head.append(style) + doc.body.append(content) + + const images = [...doc.images] + + if (images.length) { + let imageTimer: ReturnType | undefined + + await Promise.race([ + Promise.allSettled(images.map((img) => img.decode())), + new Promise((resolve) => { + imageTimer = setTimeout(resolve, 1500) + }), + ]).finally(() => clearTimeout(imageTimer)) + } + + view.addEventListener('afterprint', cleanup, { once: true }) + // 浏览器未派发 afterprint 时,兜底释放打印文档。 + cleanupTimer = setTimeout(cleanup, 120_000) + view.focus() + view.print() + + return true + } catch (error) { + cleanup() + throw error + } +} diff --git a/src/components/base/RTablePro/src/props.ts b/src/components/base/RTablePro/src/props.ts new file mode 100644 index 00000000..dc6b0d4e --- /dev/null +++ b/src/components/base/RTablePro/src/props.ts @@ -0,0 +1,26 @@ +import { dataTableProps } from 'naive-ui' +import type { DataTableColumn, DataTableInst, DropdownOption } from 'naive-ui' +import type { PropType, VNode } from 'vue' +import type { TableProPrintOptions } from './types' + +const props = { + ...dataTableProps, + bare: Boolean, + autoHeight: Boolean, + tool: { type: Boolean, default: true }, + title: [String, Object] as PropType, + downloadCsvTableOptions: Object as PropType< + Parameters[0] + >, + printTableOptions: Object as PropType, + columnStateKey: String, + contextMenuOptions: Array as PropType, + onContextMenuClick: Function as PropType< + (key: string | number, option: DropdownOption) => void + >, + 'onUpdate:columns': Function as PropType< + (columns: DataTableColumn[]) => void + >, +} as const + +export default props diff --git a/src/components/base/RTablePro/src/shared.ts b/src/components/base/RTablePro/src/shared.ts new file mode 100644 index 00000000..2951ece5 --- /dev/null +++ b/src/components/base/RTablePro/src/shared.ts @@ -0,0 +1,8 @@ +import type { InjectionKey, ShallowRef } from 'vue' + +export const config = { + tableIconSize: '18', + wrapperKey: Symbol('table-pro-wrapper') as InjectionKey< + Readonly> + >, +} diff --git a/src/components/base/RTablePro/src/types.ts b/src/components/base/RTablePro/src/types.ts new file mode 100644 index 00000000..958ba3ee --- /dev/null +++ b/src/components/base/RTablePro/src/types.ts @@ -0,0 +1,46 @@ +import type { BasicTarget } from '@/types' +import type { DataTableInst, DataTableProps, SelectOption } from 'naive-ui' +import type { LeafColumn } from './columns' + +export interface TableProPrintOptions { + target?: BasicTarget + title?: string + style?: string + formatHeader?: (column: LeafColumn) => string + formatCell?: ( + value: unknown, + row: Record, + column: LeafColumn, + ) => string +} + +export interface TablePanelInst { + getTableInstance: () => DataTableInst | null + print: (options?: TableProPrintOptions) => Promise + downloadCsv: DataTableInst['downloadCsv'] +} + +export interface TableProParams extends Record { + page?: number + pageSize?: number +} + +export interface TableProResult { + data: NonNullable + total: number +} + +export type TableProRequest = ( + params: TableProParams, + signal: AbortSignal, +) => Promise + +export type TableProSearchField = { + key: string + label: string + placeholder?: string + options?: SelectOption[] +} + +export type TableSearchValues = Record +export type PropsComponentPopselectKeys = 'striped' | 'bordered' diff --git a/src/components/index.ts b/src/components/index.ts index f642879e..9efb993c 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -8,12 +8,11 @@ export * from './base/RIcon' export * from './base/RIframe' export * from './base/RModal' export * from './base/RMoreDropdown' -export * from './base/RTable' +export * from './base/RTablePro' export * from './base/RTransitionComponent' export * from './base/RForm' export * from './base/RSegment' export * from './base/RBarcode' -export * from '../components/pro/RTablePro' export * from './base/RFlow' export { RCollapse, RDraggableCard } @@ -21,7 +20,6 @@ export { RCollapse, RDraggableCard } export type * from './base/RChart/src/types' export type * from './base/RCollapseGrid/src/types' export type * from './base/RIframe/src/types' -export type * from './base/RTable/src/types' export type * from './base/RTransitionComponent/src/types' export type * from './base/RForm/src/types' export type * from './base/RModal/src/types' diff --git a/src/components/pro/RTablePro/index.ts b/src/components/pro/RTablePro/index.ts deleted file mode 100644 index a92a95e2..00000000 --- a/src/components/pro/RTablePro/index.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { ExtractPropTypes } from 'vue' -import { useTablePro } from './src/hooks/useTablePro' -import tableProProps from './src/props' -import RTablePro from './src/TablePro' -import type { - BasePagination, - FormatRangeTime, - TablePagination, - TableProFieldNames, - TableRequestConfig, -} from './src/types' - -type TableProProps = ExtractPropTypes - -export type { - TableProProps, - BasePagination, - TablePagination, - FormatRangeTime, - TableRequestConfig, - TableProFieldNames, -} - -export { RTablePro, useTablePro, tableProProps } diff --git a/src/components/pro/RTablePro/src/TablePro.tsx b/src/components/pro/RTablePro/src/TablePro.tsx deleted file mode 100644 index 3a70cd33..00000000 --- a/src/components/pro/RTablePro/src/TablePro.tsx +++ /dev/null @@ -1,188 +0,0 @@ -import { usePagination } from '@/hooks' -import type { Recordable } from '@/types' -import { call, removeDuplicateKeys } from '@/utils' -import { omit } from 'lodash-es' -import { NFlex } from 'naive-ui' -import type { RTableInst } from '../../..' -import { RTable } from '../../../base/RTable' -import useTable from '../../../base/RTable/src/hooks/useTable' -import props from './props' -import type { TablePagination, TableProInst, TableRequestConfig } from './types' - -export default defineComponent({ - name: 'RTablePro', - props, - setup(props, ctx) { - const { expose } = ctx - - const [register, tableFns] = useTable() - const [ - paginationRef, - { - getPage, - getPageSize, - setCallback, - setItemCount, - resetPagination, - getItemCount, - setPage, - setPageSize, - }, - ] = usePagination(void 0, { - prefix: props.paginationPrefix, - }) - // 获取最新 pagination 值 - 使用 computed 避免函数重新创建 - const tablePagination = computed(() => ({ - page: getPage(), - pageSize: getPageSize(), - itemCount: getItemCount(), - })) - - // 派发表格更新事件 - const emitTableUpdate = () => { - const { onTablePaginationUpdate } = props - - if (onTablePaginationUpdate) { - call(onTablePaginationUpdate, tablePagination.value) - } - } - - // 合并请求参数 - const combineRequestParams = ( - extraConfig?: TableRequestConfig, - ) => { - const config = Object.assign({}, props.requestConfig, extraConfig) - - const { - formatRangeTime, - excludeParams, - autoDeleteDuplicateKeys = true, - } = config - let params: Recordable = config.params || {} - - // 转换时间范围,该功能仅支持 NDatePicker range 模式参数 - if (formatRangeTime?.length && params) { - formatRangeTime.forEach(({ key, target }) => { - const val = params[key] as [number, number] | null - - if (val && target?.length === 2) { - params[target[0]] = val[0] - params[target[1]] = val[1] - } - - // 清空时间参数的 key - delete params[key] - }) - } - - if (autoDeleteDuplicateKeys) { - params = removeDuplicateKeys(params) - } - - // 排除指定的请求参数 - if (excludeParams) { - params = omit(params, excludeParams) - } - - const requestParams = Object.assign({}, params, { - page: getPage(), - pageSize: getPageSize(), - }) - - return requestParams as T & { page: number; pageSize: number } - } - - // 同步执行 request 请求,允许重置 pagination 请求 - const runResetPaginationRequest: TableProInst['runTableRequest'] = ( - extraConfig, - reset = true, - ) => { - if (reset) { - resetPagination() - } - - const requestParams = combineRequestParams(extraConfig) - - props.request?.(requestParams) - } - - // 异步执行 request 请求,允许重置 pagination 请求,返回 Promise 对象 - const runResetPaginationRequestAsync: TableProInst['runAsyncTableRequest'] = - async (extraConfig, reset = true) => { - if (reset) { - resetPagination() - } - - const requestParams = combineRequestParams(extraConfig) - - await props.request?.(requestParams) - } - - watchEffect(() => { - setItemCount(props.paginationCount) - setCallback(() => { - const { manual } = props - - if (!manual) { - runResetPaginationRequest(void 0, false) - } - - emitTableUpdate() - }) - }) - - onMounted(() => { - const { onRegister } = props - - if (onRegister) { - call(onRegister, { - ...(tableFns as unknown as RTableInst), - getTablePagination: () => tablePagination.value, - runTableRequest: runResetPaginationRequest, - runAsyncTableRequest: runResetPaginationRequestAsync, - getCurrentTableRequestParams: combineRequestParams, - resetTablePagination: resetPagination, - setPage, - setPageSize, - getPage, - getPageSize, - }) - } - }) - - expose() - - return { - register, - paginationRef, - } - }, - render() { - const { register, $props, paginationRef, $slots } = this - const { - onRegister, - showPagination, - takeoverAutoHeight, - flexAutoHeight, - ...rest - } = $props - const { collapse, ...restSlots } = $slots - const baseProps = { - onRegister: register, - pagination: showPagination ? paginationRef : void 0, - flexAutoHeight: takeoverAutoHeight || flexAutoHeight, - ...rest, - } - - if (takeoverAutoHeight) { - return ( - - {collapse?.()} - {restSlots} - - ) - } - - return {restSlots} - }, -}) diff --git a/src/components/pro/RTablePro/src/hooks/useTablePro.ts b/src/components/pro/RTablePro/src/hooks/useTablePro.ts deleted file mode 100644 index 61a5d060..00000000 --- a/src/components/pro/RTablePro/src/hooks/useTablePro.ts +++ /dev/null @@ -1,271 +0,0 @@ -import type { - ColumnKey, - CsvOptionsType, - FilterState, - ScrollToOptions, - SortOrder, -} from '@/components/base/RTable/src/types' -import type { Recordable } from '@/types' -import type { PrintDomOptions } from '@/utils' -import type { TableProInst, TableRequestConfig } from '../types' - -/** - * - * @description - * 获取 TablePro 实例上的一些方法。 - * 使用方法与 useTable 类似。 - */ -export const useTablePro = () => { - const tableInst = ref() - - const register = (inst: TableProInst) => { - if (inst) { - tableInst.value = inst - } - } - - /** - * - * @description - * 获取 TablePro 实例。 - */ - const getTableProInstance = () => { - if (!tableInst.value) { - throw new Error( - '[useTablePro]: table instance is not ready yet. if you are using useTablePro, please make sure you have called register method in onRegister event.', - ) - } - - return tableInst.value - } - - /** - * - * @description - * 获取 statistics, pagination 更新信息。 - */ - const getTablePagination = () => - getTableProInstance().getTablePagination.call(null) - - /** - * - * @param extraConfig 额外请求合并配置项 - * @param reset 是否重置分页请求 - * - * @description - * 手动触发表格请求,用于手动刷新表格。 - * 如果设置了 manual 为 true,则需要手动调用该函数。 - * 该函数会自动匹配 statistics, pagination 更新的值去请求。 - * - * 允许手动配置 TableRequestConfig 参数,会自动合并 props tableRequestConfig 配置。 - * 并且,运行该函数会重置 pagination 为初始状态。 - */ - const runTableRequest = < - T extends Recordable, - ExcludeParams extends keyof T = keyof T, - >( - extraConfig?: TableRequestConfig, - reset?: boolean, - ) => getTableProInstance().runTableRequest.call(null, extraConfig, reset) - - /** - * - * @description - * 清空所有 filter 状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter - */ - const clearFilters = () => getTableProInstance().clearFilters.call(null) - - /** - * - * @description - * 清空所有 sort 状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter - */ - const clearSorter = () => getTableProInstance().clearSorter.call(null) - - /** - * - * @param options 下载 CSV 配置项 - * - * @description - * 下载 CSV。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#export-csv.vue - */ - const downloadCsv = (options?: CsvOptionsType) => - getTableProInstance().downloadCsv.call(null, options) - - /** - * - * @param filters 过滤器状态配置 - * - * @description - * 设定表格当前的过滤器。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#filter-and-sorter - */ - const filters = (filters: FilterState | null) => - getTableProInstance().filters.call(null, filters) - - /** - * - * @param page 页数 - * - * @description - * 手动设置 page。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const page = (page: number) => getTableProInstance().page.call(null, page) - - /** - * - * @param options 滚动配置项 - * - * @description - * 滚动内容。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const scrollTo: ScrollToOptions = (options) => - // eslint-disable-next-line @typescript-eslint/no-explicit-any - getTableProInstance().scrollTo(options as any) - - /** - * - * @param columnKey 列键 - * @param order 排序顺序 - * - * @description - * 设定表格的过滤状态。 - * - * @see https://www.naiveui.com/zh-CN/dark/components/data-table#DataTable-Methods - */ - const sort = (columnKey: ColumnKey, order: SortOrder) => - getTableProInstance().sort.call(null, columnKey, order) - - /** - * - * @param options 打印选项 - * - * @description - * 打印表格。 - */ - const print = (options?: PrintDomOptions) => - getTableProInstance().print.call(null, options) - - /** - * - * @param extraConfig 额外请求合并配置项 - * @param excludeParams 排除的请求参数 - * - * @description - * 获取当前内部表格请求参数。 - */ - const getCurrentTableRequestParams = < - T extends Recordable, - ExcludeParams extends keyof T = keyof T, - >( - extraConfig?: TableRequestConfig, - ): T & Recordable => - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - getTableProInstance().getCurrentTableRequestParams.call(null, extraConfig) - - /** - * - * @param extraConfig 额外请求合并配置项 - * - * @description - * 重置表格分页。 - */ - const resetTablePagination = () => - getTableProInstance().resetTablePagination.call(null) - - /** - * - * @param extraConfig 额外请求合并配置项 - * @param reset 是否重置分页请求 - * - * @description - * 异步手动触发表格请求,用于手动刷新表格。 - */ - const runAsyncTableRequest = < - T extends Recordable, - ExcludeParams extends keyof T = keyof T, - >( - extraConfig?: TableRequestConfig, - reset?: boolean, - ) => getTableProInstance().runAsyncTableRequest.call(null, extraConfig, reset) - - /** - * - * @description - * 获取 TablePro 组件配置。 - */ - const getTableProConfig = () => getTableProInstance().config - - /** - * - * @description - * 获取表格分页页码。 - */ - const getPage = () => getTableProInstance().getPage.call(null) - - /** - * - * @description - - /** - * - * @description - * 获取表格分页每页条数。 - */ - const getPageSize = () => getTableProInstance().getPageSize.call(null) - - /** - * - * @description - * 设置表格分页页码。 - */ - const setPage = (page: number) => - getTableProInstance().setPage.call(null, page) - - /** - * - * @description - * 设置表格分页每页条数。 - */ - const setPageSize = (pageSize: number) => - getTableProInstance().setPageSize.call(null, pageSize) - - return [ - register, - { - clearFilters, - getTableProInstance, - clearSorter, - downloadCsv, - filters, - page, - scrollTo, - sort, - getTablePagination, - runTableRequest, - print, - getCurrentTableRequestParams, - resetTablePagination, - runAsyncTableRequest, - getTableProConfig, - getPage, - getPageSize, - setPage, - setPageSize, - }, - ] as const -} - -export type UseTableProReturn = ReturnType diff --git a/src/components/pro/RTablePro/src/props.ts b/src/components/pro/RTablePro/src/props.ts deleted file mode 100644 index 4b79893d..00000000 --- a/src/components/pro/RTablePro/src/props.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { tableProps } from '@/components' -import type { AnyFn } from '@/types' -import { omit } from 'lodash-es' -import type { PropType } from 'vue' -import type { - PaginationPrefix, - TablePaginationUpdate, - TableProInst, - TableRequestConfig, -} from './types' - -const props = { - ...omit(tableProps, ['pagination']), - /** - * - * @description - * 分页总数。 - * - * @default 1 - */ - paginationCount: { - type: Number, - default: 1, - }, - /** - * - * @description - * 注册 useTablePro 钩子函数。 - * - * @default undefined - */ - onRegister: { - type: Function as PropType<(inst: TableProInst) => void>, - default: void 0, - }, - /** - * - * @description - * 是否需要手动控制表格的刷新。 - * 如果设置为 true,在 Pagination 更新时,不会自动触发表格的刷新。 - * - * @default false - */ - manual: { - type: Boolean, - default: false, - }, - /** - * - * @description - * 刷新表格的请求函数。 - * 该属性用于配置表格的刷新请求函数。 - * - * 如果设置了该属性,则会在表格刷新时调用该函数。 - * - * @default undefined - */ - request: { - type: Function as PropType, - }, - /** - * - * @description - * pagination 更新时的回调函数。 - * - * @default undefined - */ - onTablePaginationUpdate: { - type: Function as PropType, - }, - /** - * - * @description - * 请求函数的参数。 - * 该属性用于配置请求函数的参数。 - * - * @default undefined - */ - requestConfig: { - type: Object as PropType, - }, - /** - * - * @description - * 是否显示分页器。 - * 如果需要显示分页器,则设置为 true。 - * - * @default false - */ - showPagination: { - type: Boolean, - default: false, - }, - /** - * - * @description - * 设置表格数据为异步状态。 - * 当你使用该组件的时候,会默认认为你总是异步获取数据,所以重写了原组件的 remote, - * 现在 remote 默认为开启状态,也就是默认为 true。 - * - * @default true - */ - remote: { - type: Boolean, - default: true, - }, - /** - * - * @description - * 分页器前缀。 - * 自定义配置分页器前缀。 - * - * @default (info) => `共 ${info.itemCount} 条` - */ - paginationPrefix: { - type: Function as PropType, - default: (info: Parameters>[0]) => - `共 ${info.itemCount} 条`, - }, - /** - * - * @description - * 是否接管表格的渲染。 - * 如果你觉得配置 flexAutoHeight 属性过于麻烦,可以设置为 true,然后就能直接使用 flexAutoHeight,无需做过多的配置。 - * - * 并且,一旦启用该属性,flexAutoHeight 属性将强制启用。 - * - * @default false - */ - takeoverAutoHeight: { - type: Boolean, - default: false, - }, -} - -export default props diff --git a/src/components/pro/RTablePro/src/types.ts b/src/components/pro/RTablePro/src/types.ts deleted file mode 100644 index 4b03dfec..00000000 --- a/src/components/pro/RTablePro/src/types.ts +++ /dev/null @@ -1,247 +0,0 @@ -import type { RTableInst, TableProps } from '@/components' -import type { UsePaginationOptions } from '@/hooks' -import type { Recordable } from '@/types' - -export type FormatRangeTime = { - /** - * - * @description - * 请求参数中需要格式化的时间参数字段。 - */ - key: string | number - /** - * - * @description - * 后端接口中需要的起止时间参数字段。 - */ - target: [string | number, string | number] -} - -export interface BasePagination { - page: number - pageSize: number - itemCount: number -} - -/** - * - * @description - * Pagination 分页配置。 - */ -export type TablePagination = BasePagination - -export type TablePaginationUpdate = ( - pagination: Readonly, -) => void - -export type PaginationPrefix = UsePaginationOptions['prefix'] - -export interface TableRequestConfig< - Params = Recordable, - ExcludeParams extends keyof Params = keyof Params, -> { - /** - * - * @description - * 请求参数。 - * @default undefined - */ - params?: Params - /** - * - * @description - * 格式化时间范围,该字段用于格式化时间范围。 - * 并且仅支持 NDatePicker range 模式。 - * 如果在请求的参数中,有时间段的字段,且需要格式化时间段,则需要配置该字段。 - * - * @default undefined - */ - formatRangeTime?: FormatRangeTime[] - /** - * - * @description - * 排除的请求参数,该字段用于排除请求参数。 - * - * @default undefined - */ - excludeParams?: ExcludeParams[] - /** - * - * @description - * 是否自动移除重复的请求参数。 - * - * @default true - */ - autoDeleteDuplicateKeys?: boolean -} - -export type TableProProps = Omit - -export interface TableProInst extends Omit { - /** - * - * @description - * 获取 pagination 更新值。 - * - * @example - * const [register, { getTablePagination }] = useTablePro() - * - * // 获取当前 pagination 的值 - * const pagination = getTablePagination() - */ - getTablePagination: () => TablePagination - /** - * - * @param extraConfig 额外请求合并配置项 - * @param reset 是否重置分页请求 - * - * @description - * 手动触发表格请求,用于手动刷新表格。 - * - * @example - * const [register, { runTableRequest }] = useTablePro() - * - * // 重置分页请求 - * runTableRequest(void 0, true) - * runTableRequest() - * // 不重置分页请求 - * runTableRequest(void 0, false) - */ - runTableRequest: < - T extends Recordable, - ExcludeParams extends keyof T = keyof T, - >( - extraConfig?: TableRequestConfig, - reset?: boolean, - ) => void - /** - * - * @param extraConfig 额外请求合并配置项 - * @param reset 是否重置分页请求 - * - * @description - * 异步手动触发表格请求,用于手动刷新表格。 - * - * @example - * const [register, { runAsyncTableRequest }] = useTablePro() - * - * // 重置分页请求 - * runAsyncTableRequest(void 0, true) - * runAsyncTableRequest() - * // 不重置分页请求 - * runAsyncTableRequest(void 0, false) - */ - runAsyncTableRequest: < - T extends Recordable, - ExcludeParams extends keyof T = keyof T, - >( - extraConfig?: TableRequestConfig, - reset?: boolean, - ) => Promise - /** - * - * @param extraConfig 额外请求合并配置项 - * - * @description - * 获取当前内部表格请求参数。 - * - * @example - * const [register, { getCurrentTableRequestParams }] = useTablePro() - * - * // 获取当前内部表格请求参数 - * const params = getCurrentTableRequestParams() - */ - getCurrentTableRequestParams: < - T extends Recordable, - ExcludeParams extends keyof T = keyof T, - >( - extraConfig?: TableRequestConfig, - ) => TableRequestConfig['params'] & Recordable - /** - * - * @description - * 重置表格分页。 - * - * @example - * const [register, { resetTablePagination }] = useTablePro() - * - * // 重置表格分页为初始化状态,即第 1 页,每页 10 条数据 - * resetTablePagination() - */ - resetTablePagination: () => void - /** - * - * @description - * 设置表格分页页码。 - * - * @example - * const [register, { setPage }] = useTablePro() - * - * // 设置表格分页页码为 2 - * setPage(2) - */ - setPage: (page: number) => void - /** - * - * @description - * 设置表格分页每页条数。 - * - * @example - * const [register, { setPageSize }] = useTablePro() - * - * // 设置表格分页每页条数为 20 - * setPageSize(20) - */ - setPageSize: (pageSize: number) => void - /** - * - * @description - * 获取表格分页页码。 - * - * @example - * const [register, { getPage }] = useTablePro() - * - * // 获取表格分页页码 - * const page = getPage() - */ - getPage: () => number - /** - * - * @description - * 获取表格分页每页条数。 - * - * @example - * const [register, { getPageSize }] = useTablePro() - * - * // 获取表格分页每页条数 - * const pageSize = getPageSize() - */ - getPageSize: () => number -} - -export interface TableProFieldNames { - /** - * - * @description - * 分页器页码字段。 - * - * @default 'page' - */ - page: string - /** - * - * @description - * 分页器每页条数字段。 - * - * @default 'pageSize' - */ - pageSize: string - /** - * - * @description - * 分页器总条数字段。 - * - * @default 'itemCount' - */ - itemCount: string -} diff --git a/src/demo-data/people.ts b/src/demo-data/people.ts new file mode 100644 index 00000000..f44dfbfc --- /dev/null +++ b/src/demo-data/people.ts @@ -0,0 +1,66 @@ +import type { PaginationResponse } from '@/types/modules/axios' +import { faker } from '@faker-js/faker/locale/zh_CN' + +export interface Person { + id: string + name: string + age: number + address: string + createDate: string + email: string +} + +export interface PersonListParams { + page?: number + pageSize?: number + email?: string + name?: string + sortAge?: 'ascend' | 'descend' +} + +let people: Person[] | undefined + +export const listPeople = ({ + page, + pageSize, + email, + name, + sortAge, +}: PersonListParams = {}): PaginationResponse => { + // 同一会话内复用数据,让翻页和从上一页复制的搜索词都可重复使用。 + people ??= Array.from({ length: 100 }, () => ({ + id: faker.string.uuid(), + address: faker.location.state() + faker.location.city(), + email: faker.internet.email(), + name: faker.person.fullName(), + age: faker.number.int({ min: 18, max: 60 }), + createDate: faker.date.past().toISOString().slice(0, 10), + })) + + const emailQuery = email?.trim().toLowerCase() + const nameQuery = name?.trim().toLowerCase() + const matches = people.filter( + (person) => + (!emailQuery || person.email.toLowerCase().includes(emailQuery)) && + (!nameQuery || person.name.toLowerCase().includes(nameQuery)), + ) + + if (sortAge) { + const direction = sortAge === 'ascend' ? 1 : -1 + + matches.sort((left, right) => direction * (left.age - right.age)) + } + + const validPage = page !== void 0 && Number.isSafeInteger(page) && page > 0 + const validSize = + pageSize !== void 0 && Number.isSafeInteger(pageSize) && pageSize > 0 + const start = validPage && validSize ? (page - 1) * pageSize : 0 + + return { + code: 200, + msg: '请求成功', + data: + validPage && validSize ? matches.slice(start, start + pageSize) : matches, + total: matches.length, + } +} diff --git a/src/layout/components/MenuTag/index.tsx b/src/layout/components/MenuTag/index.tsx index ddd87759..be37c3f3 100644 --- a/src/layout/components/MenuTag/index.tsx +++ b/src/layout/components/MenuTag/index.tsx @@ -550,7 +550,8 @@ export default defineComponent({ {{ diff --git a/src/layout/components/SiderBar/index.tsx b/src/layout/components/SiderBar/index.tsx index 2f12e460..2ed90894 100644 --- a/src/layout/components/SiderBar/index.tsx +++ b/src/layout/components/SiderBar/index.tsx @@ -109,6 +109,7 @@ export default defineComponent({ return { t, + isFullscreen, leftIconOptions, rightTooltipIconOptions, toolIconClick, @@ -172,16 +173,17 @@ export default defineComponent({ class="override-button__layout" quaternary size="medium" - key={curr.name} + key={curr.eventKey ?? curr.name} aria-label={this.t( curr.eventKey === 'setting' ? 'headerTooltip.Setting' : curr.eventKey === 'github' ? 'headerTooltip.Github' - : 'headerTooltip.FullScreen', + : this.isFullscreen + ? 'headerTooltip.CancelFullScreen' + : 'headerTooltip.FullScreen', )} onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)} - focusable={false} > diff --git a/src/layout/components/SiderBar/shared.ts b/src/layout/components/SiderBar/shared.ts index 37a00d4c..14a0c576 100644 --- a/src/layout/components/SiderBar/shared.ts +++ b/src/layout/components/SiderBar/shared.ts @@ -101,11 +101,11 @@ export const createLeftIconOptions = (opts: IconOptionsFC) => { * - false: 不展示搜索按钮 */ export const createRightIconOptions = (opts: IconOptionsFC) => { - const { isTabletOrSmaller } = opts + const { isTabletOrSmaller, isFullscreen } = opts const basicOptions: IconOptions[] = [ { - name: 'action/fullscreen', + name: isFullscreen.value ? 'action/fullscreen_fold' : 'action/fullscreen', size: 18, eventKey: 'fullscreen', }, diff --git a/src/layout/default/ContentWrapper/index.scss b/src/layout/default/ContentWrapper/index.scss index 4b45dc4c..6ceb3eb3 100644 --- a/src/layout/default/ContentWrapper/index.scss +++ b/src/layout/default/ContentWrapper/index.scss @@ -17,10 +17,3 @@ display: none; } } - -.layout-content__maximize-out { - position: fixed; - top: 12px; - right: 20px; - z-index: 1000; -} diff --git a/src/layout/default/ContentWrapper/index.tsx b/src/layout/default/ContentWrapper/index.tsx index ce6bc1a0..8454e772 100644 --- a/src/layout/default/ContentWrapper/index.tsx +++ b/src/layout/default/ContentWrapper/index.tsx @@ -2,10 +2,10 @@ import { useRuntimeGetters } from '@/store' import './index.scss' import AppRequestCancelerProvider from '@/app-components/provider/AppRequestCancelerProvider' import { LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE } from '@/app-config' -import { RIcon, RTransitionComponent } from '@/components' -import { useI18n, useMaximize } from '@/hooks' +import { RTransitionComponent } from '@/components' +import { useI18n } from '@/hooks' import { useSettingGetters } from '@/store' -import { NButton, NSpin } from 'naive-ui' +import { NSpin } from 'naive-ui' import type { GlobalThemeOverrides } from 'naive-ui' export default defineComponent({ @@ -14,17 +14,12 @@ export default defineComponent({ const router = useRouter() const { t } = useI18n() - const { maximize } = useMaximize() const { getContentTransition } = useSettingGetters() const spinning = ref(false) const themeOverridesSpin: GlobalThemeOverrides['Spin'] = { opacitySpinning: '0', } - const { - globalMainLayoutLoad, - layoutContentMaximize, - layoutContentSpinning, - } = useRuntimeGetters() + const { globalMainLayoutLoad, layoutContentSpinning } = useRuntimeGetters() const setupLayoutContentSpin = () => { const removeBefore = router.beforeEach(() => { @@ -53,17 +48,13 @@ export default defineComponent({ spinning, themeOverridesSpin, getContentTransition, - layoutContentMaximize, - maximize, layoutContentSpinning, } }, render() { const { globalMainLayoutLoad, - layoutContentMaximize, layoutContentSpinning, - maximize, spinning, themeOverridesSpin, getContentTransition, @@ -76,24 +67,8 @@ export default defineComponent({ description={this.t('layout.loading')} size="large" themeOverrides={themeOverridesSpin} - class={[ - 'layout-content-spin', - layoutContentMaximize - ? 'r-layout-full__viewer-content--maximize' - : null, - ]} + class="layout-content-spin" > - {layoutContentMaximize ? ( - { - maximize(false) - }} - > - - - ) : null} {globalMainLayoutLoad ? ( { - if (event.key === 'Escape' && layoutContentMaximize.value) maximize(false) + if ( + event.key === 'Escape' && + !event.defaultPrevented && + layoutContentMaximize.value + ) + maximize(false) }) + watch( + layoutContentMaximize, + (active) => { + if (!active) return + + const focused = document.activeElement + + previouslyFocused = focused instanceof HTMLElement ? focused : null + }, + { flush: 'sync' }, + ) + watch( + layoutContentMaximize, + (active) => { + if (!active && previouslyFocused?.isConnected) { + previouslyFocused.focus({ preventScroll: true }) + } + }, + { flush: 'post' }, + ) onBeforeUnmount(() => setRuntimeState('layoutContentMaximize', false)) const header = () => ( -
+
{slots.header ? ( slots.header() ) : ( @@ -68,13 +101,21 @@ export default defineComponent({ ) const tabs = () => getMenuTagSwitch.value ? ( -
+
{slots.tabs?.() ?? }
) : null const footer = () => getCopyrightSwitch.value ? ( -