From 1409d4a028bbf197c2e619b62130e9d0d47e2b58 Mon Sep 17 00:00:00 2001 From: XiaoDaiGua-Ray <51957438+XiaoDaiGua-Ray@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:14:55 +0800 Subject: [PATCH] feat: refine workspace UI and harden shared components --- .vscode/settings.json | 1 + AGENTS.md | 1 + __test__/app/boot-feedback.spec.ts | 79 ++++ __test__/app/dashboard-shortcuts.spec.tsx | 115 +++++ __test__/app/doctor.spec.ts | 109 +++++ __test__/app/workspace-states.spec.tsx | 241 ++++++++++ __test__/app/wrapper-lifecycle.spec.tsx | 90 ++++ .../basic/arrayBufferToBase64Image.spec.ts | 37 ++ __test__/basic/uuid.spec.ts | 23 + __test__/cache/shared-storage.spec.ts | 67 +++ __test__/components/barcode.spec.tsx | 57 +++ __test__/components/chart-themes.spec.ts | 167 +++++++ __test__/components/draggable-card.spec.tsx | 66 +++ __test__/components/flow.spec.tsx | 98 ++++ __test__/components/table-pro-columns.spec.ts | 147 +++++- .../components/table-pro-image-svg.spec.ts | 161 +++++++ __test__/components/table-pro-image.spec.tsx | 412 +++++++++++++++++ .../components/table-pro-pagination.spec.ts | 42 ++ .../components/table-pro-toolbar.spec.tsx | 134 ++++++ __test__/components/table-pro.spec.ts | 7 +- .../components/wrapper-contracts.spec.tsx | 214 +++++++++ __test__/hooks/useAccess.spec.ts | 31 ++ __test__/hooks/useElementFullscreen.spec.ts | 3 + __test__/hooks/usePagination.spec.ts | 22 + __test__/hooks/useSiderBar.spec.ts | 418 ++++++++++-------- __test__/hooks/useTheme.spec.ts | 27 +- __test__/layout/content-loading.spec.tsx | 89 ++++ __test__/layout/navigation-history.spec.ts | 2 + __test__/layout/preferences.spec.ts | 42 ++ __test__/router/config.spec.ts | 30 +- __test__/router/initialization.spec.ts | 43 ++ __test__/router/permission.spec.ts | 84 +++- __test__/router/workspace-errors.spec.ts | 110 +++++ apps/admin/index.html | 180 ++++++-- apps/admin/src/App.tsx | 1 + apps/admin/src/__ray-template/README.md | 12 - apps/admin/src/__ray-template/index.ts | 16 - .../valid/valid-app-root-path.ts | 28 -- .../src/__ray-template/valid/valid-local.ts | 99 ----- apps/admin/src/app-components/README.md | 4 +- .../app-components/app/AppAvatar/index.tsx | 13 +- .../app/AppGlobalSpin/index.tsx | 9 +- .../app/AppLockScreen/appLockVar.ts | 7 + .../components/LockScreen/index.tsx | 51 ++- .../components/UnlockScreen/index.tsx | 158 ++++--- .../app/AppLockScreen/index.tsx | 6 +- .../app/AppLockScreen/shared.ts | 42 +- .../app/AppShareLink/index.scss | 2 +- .../app-components/app/AppShareLink/index.tsx | 2 +- .../provider/AppAutocompleteDefaults/index.ts | 9 + .../provider/AppVersionProvider/index.tsx | 11 +- apps/admin/src/components/README.md | 2 + apps/admin/src/doctor/README.md | 21 + apps/admin/src/doctor/index.ts | 33 ++ apps/admin/src/doctor/locale-config.ts | 63 +++ apps/admin/src/documentation-example.tsx | 8 +- apps/admin/src/hooks/README.md | 7 +- apps/admin/src/hooks/template/useAccess.ts | 24 +- apps/admin/src/hooks/template/useAppRoot.ts | 10 +- apps/admin/src/hooks/template/useBadge.ts | 12 + .../src/hooks/template/useContentScroll.ts | 9 +- apps/admin/src/hooks/template/useI18n.ts | 14 + apps/admin/src/hooks/template/useMaximize.ts | 16 +- apps/admin/src/hooks/template/useSiderBar.ts | 147 +++--- .../src/hooks/template/useSiderScroll.ts | 8 + apps/admin/src/hooks/template/useSpinning.ts | 19 + apps/admin/src/hooks/template/useTheme.ts | 32 +- apps/admin/src/hooks/template/useWatermark.ts | 4 + apps/admin/src/hooks/web/useDayjs.ts | 5 + .../src/layout/components/MenuTag/index.tsx | 26 +- .../components/Search/GlobalSearch/index.tsx | 5 +- .../default/ContentWrapper/ContentLoading.tsx | 8 +- .../layout/default/ContentWrapper/index.scss | 84 +++- .../src/locales/lang/en-US/appComponents.json | 25 ++ apps/admin/src/locales/lang/en-US/hooks.json | 7 +- .../locales/lang/en-US/workspaceStates.json | 38 ++ .../src/locales/lang/zh-CN/appComponents.json | 25 ++ apps/admin/src/locales/lang/zh-CN/hooks.json | 7 +- .../locales/lang/zh-CN/workspaceStates.json | 38 ++ apps/admin/src/main.ts | 8 +- apps/admin/src/router/README.md | 14 +- apps/admin/src/router/app-route-modules.ts | 13 +- apps/admin/src/router/config/contract.ts | 6 +- apps/admin/src/router/constant/index.ts | 29 +- apps/admin/src/router/index.ts | 6 +- apps/admin/src/router/routes.ts | 55 ++- apps/admin/src/router/utils/permission.ts | 43 +- .../utils/redirect-router-to-dashboard.ts | 31 +- .../src/router/utils/resolve-landing-path.ts | 62 ++- .../src/router/utils/setup-router-errors.ts | 39 ++ .../src/router/utils/vue-router-register.ts | 2 + apps/admin/src/store/README.md | 4 +- .../src/store/hooks/useKeepAliveStore.ts | 4 +- apps/admin/src/store/hooks/useSettingStore.ts | 2 +- .../src/store/modules/keep-alive/index.ts | 14 + apps/admin/src/store/modules/menu/index.ts | 189 +++++--- apps/admin/src/store/modules/menu/utils.ts | 18 +- .../store/modules/navigation-history/index.ts | 2 + apps/admin/src/store/modules/setting/index.ts | 37 +- apps/admin/src/store/modules/setting/types.ts | 1 + apps/admin/src/store/modules/signing/index.ts | 8 +- .../src/utils/app/get-app-environment.ts | 4 + apps/admin/src/utils/cache-backend.ts | 18 + apps/admin/src/utils/dom.ts | 11 + apps/admin/src/views/dashboard/index.scss | 11 +- apps/admin/src/views/dashboard/index.tsx | 31 +- apps/admin/src/views/demo/barcode-demo.tsx | 1 - apps/admin/src/views/demo/draggable-card.tsx | 1 - apps/admin/src/views/demo/form/index.tsx | 10 +- .../src/views/demo/hooks/HookExample.tsx | 2 +- apps/admin/src/views/demo/tables/printing.tsx | 1 + apps/admin/src/views/demo/tables/remote.tsx | 14 - .../src/views/demo/template-hooks/index.tsx | 35 +- .../src/views/error/PageResult/index.scss | 46 +- .../src/views/error/PageResult/index.tsx | 142 +++--- apps/admin/src/views/error/README.md | 13 +- .../src/views/error/views/Error403/index.tsx | 6 + .../src/views/error/views/Error404/index.tsx | 11 +- .../src/views/error/views/Error500/index.tsx | 11 +- .../views/login/components/Signing/index.tsx | 6 +- apps/admin/src/views/welcome/index.scss | 165 +++++++ apps/admin/src/views/welcome/index.tsx | 120 +++++ apps/docs/examples/CollapseGridDemo.vue | 3 +- apps/docs/examples/RBarcodeDemo.vue | 1 - apps/docs/examples/RouteConfigDemo.vue | 1 - apps/docs/examples/ThemeScopeExample.vue | 65 +++ apps/docs/guide/appearance.md | 117 ++++- apps/docs/guide/routing.md | 14 +- apps/docs/reference/components.md | 30 +- apps/docs/reference/components/barcode.md | 20 +- apps/docs/reference/components/chart.md | 4 + .../reference/components/collapse-grid.md | 10 +- .../reference/components/draggable-card.md | 2 +- apps/docs/reference/components/flow.md | 20 +- apps/docs/reference/components/form.md | 22 +- apps/docs/reference/components/iframe.md | 20 +- .../reference/components/more-dropdown.md | 13 +- apps/docs/reference/hooks.md | 16 +- apps/docs/reference/hooks/browser.md | 2 +- apps/docs/reference/hooks/interaction.md | 2 +- apps/docs/reference/hooks/layout.md | 2 +- apps/docs/reference/hooks/navigation.md | 31 +- apps/docs/reference/hooks/output.md | 2 + apps/docs/reference/table-pro-examples.md | 8 +- apps/docs/reference/table-pro.md | 32 +- apps/docs/reference/utils/core.md | 2 +- apps/docs/reference/utils/storage.md | 2 + docs/architecture.md | 2 + docs/reviews/2026-11-components.md | 67 +++ docs/reviews/2026-11-hooks-utils.md | 121 +++++ docs/reviews/2026-11-quality-review.md | 66 +++ docs/reviews/2026-11-refinements.md | 43 ++ docs/reviews/2026-11-routing.md | 48 ++ docs/reviews/2026-11-ui.md | 67 +++ docs/reviews/2026-11-workspace-states.md | 25 ++ docs/ui-design.md | 68 ++- harness/context/layout.md | 2 +- harness/context/ui.md | 2 + packages/composables/src/element.ts | 2 +- packages/composables/src/useDayjs.ts | 6 + packages/composables/src/useDomToImage.ts | 31 +- .../composables/src/useElementFullscreen.ts | 24 + packages/composables/src/usePagination.ts | 21 +- packages/icons/ICON-SOURCES.md | 124 +++--- packages/icons/src/A_README.md | 2 + packages/icons/src/action/copy-image.svg | 6 + packages/icons/src/action/external-link.svg | 7 + packages/icons/src/manifest.ts | 2 + packages/icons/src/navigation/table.svg | 13 +- packages/icons/src/status/error.svg | 10 +- packages/icons/src/status/success.svg | 10 +- packages/routing/src/contract.ts | 35 +- packages/ui/src/RBarcode/src/Barcode.tsx | 109 ++--- packages/ui/src/RBarcode/src/props.ts | 2 +- packages/ui/src/RChart/src/hooks/useChart.ts | 40 +- .../src/RChart/src/hooks/useChartProvider.ts | 2 +- packages/ui/src/RChart/src/themes/README.md | 6 + .../src/themes/naive/ray-naive-dark.json | 4 +- .../RChart/src/themes/naive/ray-naive.json | 4 +- .../src/themes/plain/ray-plain-dark.json | 4 +- .../RChart/src/themes/plain/ray-plain.json | 4 +- packages/ui/src/RChart/src/types.ts | 7 + .../src/utils/get-custom-echart-theme.ts | 8 + .../src/RChart/src/utils/loading-options.ts | 27 +- .../RChart/src/utils/set-echart-options.ts | 6 +- packages/ui/src/RCollapseGrid/src/index.scss | 17 + packages/ui/src/RCollapseGrid/src/index.tsx | 17 +- packages/ui/src/RCollapseGrid/src/props.ts | 11 +- .../ui/src/RDraggableCard/DraggableCard.tsx | 70 +-- packages/ui/src/RDraggableCard/index.scss | 4 + packages/ui/src/RFlow/src/Flow.tsx | 78 ++-- packages/ui/src/RFlow/src/constant.ts | 2 + packages/ui/src/RFlow/src/hooks/useFlow.ts | 18 +- packages/ui/src/RFlow/src/props.ts | 2 +- packages/ui/src/RForm/src/Form.tsx | 100 ++++- packages/ui/src/RForm/src/hooks/useForm.ts | 81 ++-- packages/ui/src/RForm/src/props.ts | 8 +- packages/ui/src/RIcon/src/index.scss | 6 +- packages/ui/src/RIframe/src/Iframe.tsx | 10 +- packages/ui/src/RIframe/src/types.ts | 7 +- packages/ui/src/RModal/src/hooks/useModal.ts | 17 +- packages/ui/src/RModal/src/index.scss | 2 + .../ui/src/RMoreDropdown/src/MoreDropdown.tsx | 25 +- packages/ui/src/RMoreDropdown/src/props.ts | 6 + packages/ui/src/RSegment/src/Segment.tsx | 7 +- packages/ui/src/RSegment/src/types.ts | 2 +- packages/ui/src/RTablePro/README.md | 37 +- packages/ui/src/RTablePro/index.ts | 2 + packages/ui/src/RTablePro/src/TablePanel.tsx | 308 +++++++++++-- packages/ui/src/RTablePro/src/TablePro.tsx | 24 +- packages/ui/src/RTablePro/src/columns.ts | 82 +++- .../src/components/AppearanceSettings.tsx | 29 -- .../src/components/ColumnSettings.tsx | 4 +- .../ui/src/RTablePro/src/components/Size.tsx | 33 -- .../RTablePro/src/components/ToolButton.tsx | 2 + packages/ui/src/RTablePro/src/csv.ts | 20 + packages/ui/src/RTablePro/src/en-US.json | 8 + packages/ui/src/RTablePro/src/image-svg.ts | 307 +++++++++++++ packages/ui/src/RTablePro/src/image.ts | 333 ++++++++++++++ packages/ui/src/RTablePro/src/index.scss | 26 +- packages/ui/src/RTablePro/src/locale.ts | 7 + packages/ui/src/RTablePro/src/pagination.ts | 26 +- packages/ui/src/RTablePro/src/printing.ts | 38 +- packages/ui/src/RTablePro/src/props.ts | 34 +- packages/ui/src/RTablePro/src/search.ts | 124 ++++++ packages/ui/src/RTablePro/src/types.ts | 30 ++ packages/ui/src/RTablePro/src/useTablePro.ts | 20 + .../ui/src/RTablePro/src/useTableRequest.ts | 13 + .../ui/src/RTablePro/src/useTableSearch.ts | 42 ++ packages/ui/src/RTablePro/src/zh-CN.json | 8 + packages/ui/src/services.ts | 15 + packages/ui/src/theme-presets.ts | 26 +- packages/ui/src/theme.css | 2 - packages/utils/src/core/index.ts | 13 +- packages/utils/src/files/index.ts | 24 +- packages/utils/src/precision.ts | 7 + packages/utils/src/storage.ts | 39 +- 237 files changed, 7810 insertions(+), 1593 deletions(-) create mode 100644 __test__/app/boot-feedback.spec.ts create mode 100644 __test__/app/dashboard-shortcuts.spec.tsx create mode 100644 __test__/app/doctor.spec.ts create mode 100644 __test__/app/workspace-states.spec.tsx create mode 100644 __test__/app/wrapper-lifecycle.spec.tsx create mode 100644 __test__/cache/shared-storage.spec.ts create mode 100644 __test__/components/barcode.spec.tsx create mode 100644 __test__/components/chart-themes.spec.ts create mode 100644 __test__/components/draggable-card.spec.tsx create mode 100644 __test__/components/flow.spec.tsx create mode 100644 __test__/components/table-pro-image-svg.spec.ts create mode 100644 __test__/components/table-pro-image.spec.tsx create mode 100644 __test__/components/table-pro-pagination.spec.ts create mode 100644 __test__/components/table-pro-toolbar.spec.tsx create mode 100644 __test__/components/wrapper-contracts.spec.tsx create mode 100644 __test__/hooks/useAccess.spec.ts create mode 100644 __test__/layout/content-loading.spec.tsx create mode 100644 __test__/router/initialization.spec.ts create mode 100644 __test__/router/workspace-errors.spec.ts delete mode 100644 apps/admin/src/__ray-template/README.md delete mode 100644 apps/admin/src/__ray-template/index.ts delete mode 100644 apps/admin/src/__ray-template/valid/valid-app-root-path.ts delete mode 100644 apps/admin/src/__ray-template/valid/valid-local.ts create mode 100644 apps/admin/src/doctor/README.md create mode 100644 apps/admin/src/doctor/index.ts create mode 100644 apps/admin/src/doctor/locale-config.ts create mode 100644 apps/admin/src/locales/lang/en-US/appComponents.json create mode 100644 apps/admin/src/locales/lang/en-US/workspaceStates.json create mode 100644 apps/admin/src/locales/lang/zh-CN/appComponents.json create mode 100644 apps/admin/src/locales/lang/zh-CN/workspaceStates.json create mode 100644 apps/admin/src/router/utils/setup-router-errors.ts create mode 100644 apps/admin/src/views/error/views/Error403/index.tsx create mode 100644 apps/admin/src/views/welcome/index.scss create mode 100644 apps/admin/src/views/welcome/index.tsx create mode 100644 apps/docs/examples/ThemeScopeExample.vue create mode 100644 docs/reviews/2026-11-components.md create mode 100644 docs/reviews/2026-11-hooks-utils.md create mode 100644 docs/reviews/2026-11-quality-review.md create mode 100644 docs/reviews/2026-11-refinements.md create mode 100644 docs/reviews/2026-11-routing.md create mode 100644 docs/reviews/2026-11-ui.md create mode 100644 docs/reviews/2026-11-workspace-states.md create mode 100644 packages/icons/src/action/copy-image.svg create mode 100644 packages/icons/src/action/external-link.svg delete mode 100644 packages/ui/src/RTablePro/src/components/AppearanceSettings.tsx delete mode 100644 packages/ui/src/RTablePro/src/components/Size.tsx create mode 100644 packages/ui/src/RTablePro/src/image-svg.ts create mode 100644 packages/ui/src/RTablePro/src/image.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 3d4ca2fa..ba0a1133 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -88,6 +88,7 @@ "Popselect", "precommit", "qrcode", + "rgba", "sider", "siderbar", "snapline", diff --git a/AGENTS.md b/AGENTS.md index 2b4f67c1..7925063a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,5 +7,6 @@ A Vue 3 + TSX admin template with an admin application, a documentation site, an - For complex tasks, the lead agent may choose to use subagents under the [delegation guidelines](harness/README.md#using-subagents-when-useful), when the host supports them and current permissions allow it. Delegation needs no separate approval. The lead agent owns integration and final verification. - Write agent guidance and internal engineering documentation in English. Preserve the intended languages of product copy and reader-facing documentation. - Follow the [comment style](docs/comment-style.md) when adding or editing comments. Maintain both Chinese and English product copy. For visible behavior changes, use [browser verification](harness/README.md#browser-verification) only for affected pages, actions, and dimensions. +- For custom CSS, follow the [style contract](docs/ui-design.md#custom-css-contract): consume semantic theme tokens and the shell's runtime layout variables so style, color mode, primary color, and layout preferences keep working. Keep provider ownership and scoped overrides explicit. - Select relevant tests or `pnpm harness verify ` using the [verification scope](harness/README.md#choosing-the-verification-scope). Small changes do not default to full checks or a UI/UX sweep. Use full checks for integration risk, releases, or an explicit request; CI keeps `pnpm check`. Within one task, rerun only checks affected by subsequent changes. Report what was and was not verified. - Establish engineering facts from current source, manifests, and the lockfile. Keep sensitive data out of source, prompts, and evidence. Commits, pushes, and deployments require user authorization. diff --git a/__test__/app/boot-feedback.spec.ts b/__test__/app/boot-feedback.spec.ts new file mode 100644 index 00000000..1a19c8d3 --- /dev/null +++ b/__test__/app/boot-feedback.spec.ts @@ -0,0 +1,79 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { runInNewContext } from 'node:vm' + +const html = readFileSync( + resolve(process.cwd(), 'apps/admin/index.html'), + 'utf8', +) +const source = new DOMParser() + .parseFromString(html, 'text/html') + .querySelector('script:not([type])')!.textContent! + +describe('pre-bundle startup failure feedback', () => { + let splash: HTMLElement + let listener: EventListener + + beforeEach(() => { + splash = document.createElement('div') + splash.id = 'pre-loading-animation' + document.body.append(splash) + const subscribe = vi.spyOn(window, 'addEventListener') + + runInNewContext(source, { + window, + document, + localStorage, + HTMLScriptElement, + ErrorEvent, + }) + listener = subscribe.mock.calls.find( + ([type]) => type === 'error', + )![1] as EventListener + subscribe.mockRestore() + }) + + afterEach(() => { + window.removeEventListener('error', listener, true) + splash.remove() + vi.restoreAllMocks() + }) + + it('captures a non-bubbling entry/module-graph load error', () => { + const script = document.createElement('script') + + script.type = 'module' + document.body.append(script) + script.dispatchEvent(new Event('error')) + expect(splash.dataset.state).toBe('failed') + script.remove() + }) + + it('handles parse, link, or evaluation errors reported on the window', () => { + window.dispatchEvent( + new ErrorEvent('error', { + message: 'The requested module does not provide an export', + error: new SyntaxError('Missing export'), + }), + ) + expect(splash.dataset.state).toBe('failed') + }) + + it('does not mistake a decorative image failure for a startup failure', () => { + const image = document.createElement('img') + + document.body.append(image) + image.dispatchEvent(new Event('error')) + expect(splash.dataset.state).toBeUndefined() + image.remove() + }) + + it('stops observing after the mounted application has removed the splash', () => { + const unsubscribe = vi.spyOn(window, 'removeEventListener') + + splash.remove() + window.dispatchEvent(new ErrorEvent('error')) + expect(unsubscribe).toHaveBeenCalledWith('error', listener, true) + expect(document.getElementById('pre-loading-animation')).toBeNull() + }) +}) diff --git a/__test__/app/dashboard-shortcuts.spec.tsx b/__test__/app/dashboard-shortcuts.spec.tsx new file mode 100644 index 00000000..664bb55b --- /dev/null +++ b/__test__/app/dashboard-shortcuts.spec.tsx @@ -0,0 +1,115 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { nextTick, ref } from 'vue' +import { createMemoryHistory, createRouter } from 'vue-router' +import type { AppMenuOption } from '../../apps/admin/src/types' +import Dashboard from '../../apps/admin/src/views/dashboard' + +const menus = ref([]) + +vi.mock('@/store', () => ({ + useMenuGetters: () => ({ getMenuOptions: menus }), +})) +vi.mock('@/hooks', () => ({ + useI18n: () => ({ t: (key: string) => key }), +})) + +const menu = ( + path: string, + children?: AppMenuOption[], + show = true, +): AppMenuOption => ({ + path, + fullPath: path, + key: path, + name: path, + label: path, + meta: {}, + children, + show, +}) + +const setupDashboard = async () => { + const router = createRouter({ + history: createMemoryHistory(), + routes: ['/dashboard', '/template-hooks', '/layout-demo', '/svg-icons'].map( + (path) => ({ + path, + component: { render: () => null }, + }), + ), + }) + + await router.push('/dashboard') + const wrapper = mount(Dashboard, { global: { plugins: [router] } }) + const links = () => wrapper.findAll('.r-dashboard-shortcut') + + return { router, wrapper, links } +} + +it('shows declared destinations below visible menu groups and navigates to the chosen page', async () => { + menus.value = [ + menu('/examples', [ + menu('/hooks', [menu('/template-hooks')]), + menu('/layout-demo'), + menu('/resources', [menu('/svg-icons')]), + ]), + ] + const { router, wrapper, links } = await setupDashboard() + + try { + expect(links().map((link) => link.attributes('href'))).toEqual([ + '/template-hooks', + '/layout-demo', + '/svg-icons', + ]) + await links()[2].trigger('click') + await flushPromises() + expect(router.currentRoute.value.path).toBe('/svg-icons') + } finally { + wrapper.unmount() + } +}) + +it('prunes hidden ancestors and hidden leaves instead of exposing their destinations', async () => { + menus.value = [ + menu('/hidden-root', [menu('/template-hooks')], false), + menu('/visible-root', [ + menu('/hidden-nested', [menu('/layout-demo')], false), + menu('/svg-icons'), + ]), + ] + const { wrapper, links } = await setupDashboard() + + try { + expect(links().map((link) => link.attributes('href'))).toEqual([ + '/svg-icons', + ]) + menus.value[1].children![1].show = false + await nextTick() + expect(links()).toHaveLength(0) + expect(wrapper.find('.r-dashboard-shortcuts').exists()).toBe(false) + } finally { + wrapper.unmount() + } +}) + +it('reacts to the current permitted tree without inventing a default or treating external entries as pages', async () => { + menus.value = [menu('/template-hooks')] + const { router, wrapper, links } = await setupDashboard() + + try { + expect(links()).toHaveLength(1) + menus.value = [menu('/unrelated')] + await nextTick() + expect(links()).toHaveLength(0) + expect(router.currentRoute.value.path).toBe('/dashboard') + + menus.value = [ + { ...menu('/svg-icons'), meta: { windowOpen: 'https://example.com' } }, + ] + await nextTick() + expect(links()).toHaveLength(0) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/app/doctor.spec.ts b/__test__/app/doctor.spec.ts new file mode 100644 index 00000000..519cc316 --- /dev/null +++ b/__test__/app/doctor.spec.ts @@ -0,0 +1,109 @@ +import { runAppDoctor } from '@/doctor' +import * as localeDiagnostics from '@/doctor/locale-config' +import type { LocaleConfiguration } from '@/doctor/locale-config' + +const configuration = vi.hoisted(() => ({ + options: [{ key: 'zh-CN' }, { key: 'en-US' }], + defaultLocale: 'zh-CN', + fallbackLocale: 'zh-CN', + dayjsLocales: { 'zh-CN': 'zh-cn', 'en-US': 'en' }, + defaultDayjsLocale: 'zh-cn', +})) + +vi.mock('../../apps/admin/src/app-config/local-config', () => ({ + get LOCAL_OPTIONS() { + return configuration.options + }, + get SYSTEM_DEFAULT_LOCAL() { + return configuration.defaultLocale + }, + get SYSTEM_FALLBACK_LOCALE() { + return configuration.fallbackLocale + }, + get DAYJS_LOCAL_MAP() { + return configuration.dayjsLocales + }, + get DEFAULT_DAYJS_LOCAL() { + return configuration.defaultDayjsLocale + }, +})) + +beforeEach(() => { + configuration.defaultLocale = 'zh-CN' + configuration.fallbackLocale = 'zh-CN' +}) +afterEach(() => vi.restoreAllMocks()) + +it('accepts a consistent immutable locale snapshot without changing it', () => { + const input = Object.freeze({ + options: Object.freeze([{ key: 'en-US' }]), + defaultLocale: 'en-US', + fallbackLocale: 'en-US', + dayjsLocales: Object.freeze({ 'en-US': 'en' }), + defaultDayjsLocale: 'en', + }) + + expect(localeDiagnostics.getLocaleConfigIssues(input)).toEqual([]) + expect(input.options).toEqual([{ key: 'en-US' }]) +}) + +it('reports duplicate choices and all independent membership problems together', () => { + const input: LocaleConfiguration = { + ...configuration, + options: [{ key: 'en-US' }, { key: 'en-US' }, { key: 'en-US' }], + defaultLocale: 'zh-CN', + fallbackLocale: 'fr-FR', + defaultDayjsLocale: 'fr', + } + const issues = localeDiagnostics.getLocaleConfigIssues(input) + + expect(issues).toEqual( + expect.arrayContaining([ + 'LOCAL_OPTIONS contains duplicate locale "en-US".', + 'SYSTEM_DEFAULT_LOCAL "zh-CN" is missing from LOCAL_OPTIONS.', + 'SYSTEM_FALLBACK_LOCALE "fr-FR" is missing from LOCAL_OPTIONS.', + 'DAYJS_LOCAL_MAP locale "zh-CN" is missing from LOCAL_OPTIONS.', + 'DEFAULT_DAYJS_LOCAL "fr" is missing from DAYJS_LOCAL_MAP values.', + ]), + ) + expect(issues).toHaveLength(5) +}) + +it('finds a selectable language that has no date-locale mapping', () => { + expect( + localeDiagnostics.getLocaleConfigIssues({ + ...configuration, + dayjsLocales: { 'zh-CN': 'zh-cn' }, + }), + ).toEqual(['DAYJS_LOCAL_MAP is missing locale "en-US" from LOCAL_OPTIONS.']) +}) + +it('reports configuration warnings locally and inspects fresh state on each mount', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + configuration.defaultLocale = 'missing' + expect(() => runAppDoctor()).not.toThrow() + expect(warn).toHaveBeenCalledExactlyOnceWith( + '[Ray Admin doctor] SYSTEM_DEFAULT_LOCAL "missing" is missing from LOCAL_OPTIONS.', + ) + configuration.defaultLocale = 'zh-CN' + warn.mockClear() + runAppDoctor() + expect(warn).not.toHaveBeenCalled() +}) + +it('contains an unexpected diagnostic exception instead of rejecting application startup', () => { + const error = new Error('diagnostic failed') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + vi.spyOn(localeDiagnostics, 'getLocaleConfigIssues').mockImplementationOnce( + () => { + throw error + }, + ) + expect(() => runAppDoctor()).not.toThrow() + expect(warn).toHaveBeenCalledExactlyOnceWith( + '[Ray Admin doctor] Locale diagnostics could not complete.', + error, + ) +}) diff --git a/__test__/app/workspace-states.spec.tsx b/__test__/app/workspace-states.spec.tsx new file mode 100644 index 00000000..3313c32b --- /dev/null +++ b/__test__/app/workspace-states.spec.tsx @@ -0,0 +1,241 @@ +import { readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { flushPromises, mount } from '@vue/test-utils' +import { NResult } from 'naive-ui' +import { h, nextTick, ref } from 'vue' +import { createMemoryHistory, createRouter } from 'vue-router' +import type { AppMenuOption } from '../../apps/admin/src/types' +import PageResult from '../../apps/admin/src/views/error/PageResult' +import Welcome from '../../apps/admin/src/views/welcome' + +const menus = ref([]) +const recentPaths = ref([]) +const locale = ref('en-US') +const messages: Record< + string, + Record> +> = Object.fromEntries( + ['en-US', 'zh-CN'].map((language) => [ + language, + JSON.parse( + readFileSync( + resolve( + process.cwd(), + `apps/admin/src/locales/lang/${language}/workspaceStates.json`, + ), + 'utf8', + ), + ), + ]), +) + +vi.mock('@/store', () => ({ + useMenuGetters: () => ({ getMenuOptions: menus }), + useNavigationHistoryGetters: () => ({ recentPaths }), + piniaSigningStore: () => ({ signingCallback: { role: 'viewer' } }), +})) + +vi.mock('@/hooks', () => ({ + useI18n: (namespace?: string) => ({ + t: (key: string) => { + if (namespace !== 'workspaceStates') return key + + const [section, field] = key.split('.') + + return messages[locale.value][section]?.[field] ?? key + }, + }), +})) + +const menu = ( + path: string, + extra: Partial = {}, +): AppMenuOption => ({ + path, + fullPath: path, + key: path, + name: path, + label: path, + breadcrumbLabel: path, + meta: {}, + ...extra, +}) + +const createPageRouter = async (path = '/welcome') => { + const page = { render: () => null } + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/welcome', name: 'RWelcome', component: page }, + { path: '/403', name: 'ErrorPage403', component: page }, + { path: '/404', name: 'ErrorPage404', component: page }, + { path: '/500', name: 'ErrorPage500', component: page }, + { path: '/reports', name: 'Reports', component: page }, + { path: '/users', name: 'Users', component: page }, + { + path: '/restricted', + name: 'Restricted', + component: page, + meta: { role: ['admin'] }, + }, + ], + }) + + await router.push(path) + + return router +} + +beforeEach(() => { + menus.value = [] + recentPaths.value = [] + locale.value = 'en-US' +}) + +it('ranks current visible menu entries by recent visits without opening a page', async () => { + menus.value = [ + menu('/group', { children: [menu('/reports'), menu('/users')] }), + menu('/hidden', { show: false, children: [menu('/hidden/child')] }), + menu('/restricted', { show: false }), + menu('/external', { meta: { windowOpen: 'https://example.com' } }), + menu('/details/:id'), + ] + recentPaths.value = ['/removed', '/restricted', '/users'] + const router = await createPageRouter() + const wrapper = mount(Welcome, { global: { plugins: [router] } }) + + try { + expect( + wrapper + .findAll('.r-welcome__link') + .map((link) => link.attributes('href')), + ).toEqual(['/users', '/reports']) + expect(wrapper.findAll('h1')).toHaveLength(1) + expect(router.currentRoute.value.path).toBe('/welcome') + expect(wrapper.text()).not.toContain('/removed') + + menus.value = [menu('/reports')] + await nextTick() + expect( + wrapper + .findAll('.r-welcome__link') + .map((link) => link.attributes('href')), + ).toEqual(['/reports']) + } finally { + wrapper.unmount() + } +}) + +it('shows an honest no-access state and updates its language', async () => { + const router = await createPageRouter() + const wrapper = mount(Welcome, { global: { plugins: [router] } }) + + try { + expect(wrapper.find('nav').exists()).toBe(false) + expect(wrapper.text()).toContain(messages['en-US'].welcome.noPagesTitle) + locale.value = 'zh-CN' + await nextTick() + expect(wrapper.text()).toContain(messages['zh-CN'].welcome.noPagesTitle) + expect(wrapper.get('h1').text()).toBe(messages['zh-CN'].welcome.title) + } finally { + wrapper.unmount() + } +}) + +it.each([ + ['403', 'forbidden'], + ['404', 'notFound'], + ['500', 'serverError'], +] as const)( + 'renders %s with its own identity and neutral recovery action', + async (status, key) => { + const router = await createPageRouter(`/${status}`) + const wrapper = mount(PageResult, { + props: { status }, + global: { plugins: [router] }, + }) + + try { + expect(wrapper.getComponent(NResult).props('status')).toBe(status) + expect(wrapper.get('h1').text()).toBe(messages['en-US'][key].title) + expect(wrapper.get('.error-page__mark').text()).toBe(status) + await wrapper.get('button').trigger('click') + await flushPromises() + expect(router.currentRoute.value.path).toBe('/welcome') + } finally { + wrapper.unmount() + } + }, +) + +it('retries an authorized failed route with its query and hash intact', async () => { + const router = await createPageRouter( + '/500?from=%2Freports%3Fperiod%3Dweek%23chart', + ) + const wrapper = mount(PageResult, { + props: { status: '500' }, + global: { plugins: [router] }, + }) + + try { + const retry = wrapper + .findAll('button') + .find((button) => button.text() === messages['en-US'].actions.retry)! + + await retry.trigger('click') + await flushPromises() + expect(router.currentRoute.value.fullPath).toBe( + '/reports?period=week#chart', + ) + } finally { + wrapper.unmount() + } +}) + +it.each(['//example.com', '/500', '/restricted'])( + 'omits retry for unsafe/unavailable target %s', + async (from) => { + const router = await createPageRouter( + `/500?from=${encodeURIComponent(from)}`, + ) + const wrapper = mount(PageResult, { + props: { status: '500' }, + global: { plugins: [router] }, + }) + + try { + expect(wrapper.findAll('button').map((button) => button.text())).toEqual([ + messages['en-US'].actions.workspace, + ]) + } finally { + wrapper.unmount() + } + }, +) + +it('preserves custom title, description, content and footer configuration', async () => { + const router = await createPageRouter('/404') + const wrapper = mount(PageResult, { + props: { + status: '404', + title: 'Custom title', + description: 'Custom explanation', + }, + slots: { + default: () => h('p', 'Details'), + footer: () => h('button', 'Custom recovery'), + }, + global: { plugins: [router] }, + }) + + try { + expect(wrapper.get('h1').text()).toBe('Custom title') + expect(wrapper.text()).toContain('Custom explanation') + expect(wrapper.text()).toContain('Details') + expect(wrapper.findAll('button').map((button) => button.text())).toEqual([ + 'Custom recovery', + ]) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/app/wrapper-lifecycle.spec.tsx b/__test__/app/wrapper-lifecycle.spec.tsx new file mode 100644 index 00000000..f0a81863 --- /dev/null +++ b/__test__/app/wrapper-lifecycle.spec.tsx @@ -0,0 +1,90 @@ +import { mount } from '@vue/test-utils' +import { NAvatar, NButton, NSpin } from 'naive-ui' +import { nextTick } from 'vue' +import AppAvatar from '../../apps/admin/src/app-components/app/AppAvatar' +import AppGlobalSpin from '../../apps/admin/src/app-components/app/AppGlobalSpin' +import UnlockScreen from '../../apps/admin/src/app-components/app/AppLockScreen/components/UnlockScreen' + +vi.mock('@/store', async () => { + const { ref } = await import('vue') + + return { + useSigningGetters: () => ({ + getSigningCallback: ref({ name: 'Tester', avatar: '' }), + }), + useRuntimeGetters: () => ({ globalSpinning: ref(true) }), + useSettingActions: () => ({ updateSettingState: vi.fn() }), + useSettingGetters: () => ({ getLocaleLanguage: ref('en-US') }), + useSigningActions: () => ({ logout: vi.fn() }), + useLockScreenActions: () => ({ setLocked: vi.fn() }), + useLockScreenGetters: () => ({ getLocked: ref(true) }), + } +}) + +vi.mock('@/hooks', () => ({ + useI18n: () => ({ t: (key: string) => key }), + useDevice: () => ({ isTabletOrSmaller: false }), +})) + +it('honors avatar shape, native size, and keyboard focus', () => { + const wrapper = mount(AppAvatar, { + props: { round: false, size: 42, objectFit: 'contain' }, + }) + + try { + expect(wrapper.findComponent(NAvatar).props()).toMatchObject({ + round: false, + size: 42, + objectFit: 'contain', + }) + expect(wrapper.findComponent(NButton).props('focusable')).toBe(true) + } finally { + wrapper.unmount() + } +}) + +it('merges global spin overrides while preserving its owned busy state', () => { + const wrapper = mount(AppGlobalSpin, { + props: { show: false, themeOverrides: { opacitySpinning: '0.7' } }, + }) + + try { + expect(wrapper.findComponent(NSpin).props()).toMatchObject({ + show: true, + themeOverrides: { opacitySpinning: '0.7' }, + }) + } finally { + wrapper.unmount() + } +}) + +it('updates the lock-screen date at midnight and cancels its minute timer', async () => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-11-06T23:59:59')) + vi.spyOn(document, 'hidden', 'get').mockReturnValue(false) + const wrapper = mount(UnlockScreen, { + global: { + stubs: { + AppAvatar: true, + RForm: { template: '
' }, + NFormItem: { template: '
' }, + NInput: true, + NButton: true, + NFlex: { template: '
' }, + }, + }, + }) + + try { + expect(wrapper.text()).toContain('2026-11-06') + await vi.advanceTimersByTimeAsync(1_000) + await nextTick() + expect(wrapper.text()).toContain('2026-11-07') + wrapper.unmount() + expect(vi.getTimerCount()).toBe(0) + } finally { + wrapper.unmount() + vi.restoreAllMocks() + vi.useRealTimers() + } +}) diff --git a/__test__/basic/arrayBufferToBase64Image.spec.ts b/__test__/basic/arrayBufferToBase64Image.spec.ts index c6ae0aa5..5a064716 100644 --- a/__test__/basic/arrayBufferToBase64Image.spec.ts +++ b/__test__/basic/arrayBufferToBase64Image.spec.ts @@ -16,3 +16,40 @@ describe('arrayBufferToBase64Image', () => { expect(base64Image.startsWith(base64ImagePrefix)).toBe(true) }) }) + +it('preserves byte values across chunk boundaries for a large buffer', () => { + const bytes = Uint8Array.from({ length: 262145 }, (_, index) => index % 256) + + expect(arrayBufferToBase64Image(bytes.buffer)).toBe( + 'data:image/png;base64,' + Buffer.from(bytes).toString('base64'), + ) + expect(arrayBufferToBase64Image(new ArrayBuffer(0))).toBe( + 'data:image/png;base64,', + ) +}) + +it('keeps a compatible encoding path when native typed-array Base64 is unavailable', () => { + const descriptor = Object.getOwnPropertyDescriptor( + Uint8Array.prototype, + 'toBase64', + ) + + // eslint-disable-next-line no-extend-native -- 模拟缺少原生 API 的浏览器,finally 恢复描述符。 + Object.defineProperty(Uint8Array.prototype, 'toBase64', { + configurable: true, + value: void 0, + }) + + try { + const bytes = Uint8Array.from({ length: 65539 }, (_, index) => index % 256) + + expect(arrayBufferToBase64Image(bytes.buffer)).toBe( + 'data:image/png;base64,' + Buffer.from(bytes).toString('base64'), + ) + } finally { + if (descriptor) + // eslint-disable-next-line no-extend-native -- 恢复测试前的原生描述符。 + Object.defineProperty(Uint8Array.prototype, 'toBase64', descriptor) + else Reflect.deleteProperty(Uint8Array.prototype, 'toBase64') + } +}) diff --git a/__test__/basic/uuid.spec.ts b/__test__/basic/uuid.spec.ts index d739799e..41825107 100644 --- a/__test__/basic/uuid.spec.ts +++ b/__test__/basic/uuid.spec.ts @@ -31,3 +31,26 @@ it('enforces the requested radix and rejects invalid bounds', () => { expect(() => uuid(-1)).toThrow(RangeError) expect(() => uuid(Infinity)).toThrow(RangeError) }) + +it('rejects biased samples while filling identifiers across several batches', () => { + let batch = 0 + const random = vi + .spyOn(crypto, 'getRandomValues') + .mockImplementation((samples) => { + const values = samples as Uint32Array + + values.fill(batch++ === 0 ? 0xffffffff : 9) + + return samples + }) + + try { + expect(uuid(257, 10)).toBe('9'.repeat(257)) + } finally { + random.mockRestore() + } +}) + +it('supports long identifiers without exceeding the Web Crypto byte quota', () => { + expect(uuid(70000, 10)).toMatch(/^\d{70000}$/) +}) diff --git a/__test__/cache/shared-storage.spec.ts b/__test__/cache/shared-storage.spec.ts new file mode 100644 index 00000000..b1d43989 --- /dev/null +++ b/__test__/cache/shared-storage.spec.ts @@ -0,0 +1,67 @@ +import { createStorage } from '@ray-template/utils/storage' + +it('namespaces JSON values and reads the current backend instead of caching a copy', () => { + const backend = new Map() + const storage = createStorage( + { + getItem: (key) => backend.get(key) ?? null, + setItem: (key, value) => { + backend.set(key, value) + }, + removeItem: (key) => { + backend.delete(key) + }, + }, + 'table:', + ) + + storage.set('columns', ['name']) + expect(backend.get('table:columns')).toBe('["name"]') + backend.set('table:columns', '["status"]') + expect(storage.get('columns')).toEqual(['status']) + storage.remove('columns') + expect(storage.get('columns')).toBeNull() +}) + +it('preserves a saved value when a replacement cannot be serialized', () => { + const setItem = vi.fn() + const storage = createStorage({ + getItem: () => '"saved"', + setItem, + removeItem: vi.fn(), + }) + const circular: { self?: unknown } = {} + + circular.self = circular + + for (const value of [void 0, Symbol('value'), () => 1, circular, 1n]) { + storage.set('value', value) + } + + expect(setItem).not.toHaveBeenCalled() + expect(storage.get('value')).toBe('saved') + storage.set('value', null) + expect(setItem).toHaveBeenCalledExactlyOnceWith('value', 'null') +}) + +it('contains unavailable-backend errors and malformed JSON', () => { + const fail = () => { + throw new Error('storage denied') + } + const storage = createStorage({ + getItem: fail, + setItem: fail, + removeItem: fail, + }) + + expect(storage.get('value')).toBeNull() + expect(() => storage.set('value', 1)).not.toThrow() + expect(() => storage.remove('value')).not.toThrow() + expect( + createStorage({ + getItem: () => '{bad', + setItem: vi.fn(), + removeItem: vi.fn(), + }).get('value'), + ).toBeNull() +}) diff --git a/__test__/components/barcode.spec.tsx b/__test__/components/barcode.spec.tsx new file mode 100644 index 00000000..997d80d3 --- /dev/null +++ b/__test__/components/barcode.spec.tsx @@ -0,0 +1,57 @@ +import { flushPromises, mount } from '@vue/test-utils' +import barcode from 'jsbarcode' +import { reactive } from 'vue' +import { RBarcode } from '../../packages/ui/src/RBarcode' + +vi.mock('jsbarcode', () => ({ default: vi.fn() })) + +beforeEach(() => vi.mocked(barcode).mockClear()) + +it('redraws changed format, options and renderer without changing text', async () => { + const options = reactive({ lineColor: '#123456' }) + const wrapper = mount(RBarcode, { props: { text: '123456', options } }) + + try { + await flushPromises() + expect(barcode).toHaveBeenCalledTimes(1) + await wrapper.setProps({ format: 'CODE39' }) + expect(barcode).toHaveBeenLastCalledWith( + expect.any(HTMLCanvasElement), + '123456', + expect.objectContaining({ format: 'CODE39' }), + ) + options.lineColor = '#abcdef' + await flushPromises() + expect(barcode).toHaveBeenLastCalledWith( + expect.any(HTMLCanvasElement), + '123456', + expect.objectContaining({ lineColor: '#abcdef' }), + ) + await wrapper.setProps({ barcodeRender: 'svg' }) + expect(vi.mocked(barcode).mock.lastCall?.[0]).toBe( + wrapper.get('svg').element, + ) + } finally { + wrapper.unmount() + } +}) + +it('honors watchText and resumes with the latest value when enabled', async () => { + const wrapper = mount(RBarcode, { props: { text: '123', watchText: false } }) + + try { + await flushPromises() + const count = vi.mocked(barcode).mock.calls.length + + await wrapper.setProps({ text: '456' }) + expect(barcode).toHaveBeenCalledTimes(count) + await wrapper.setProps({ watchText: true }) + expect(barcode).toHaveBeenLastCalledWith( + expect.anything(), + '456', + expect.anything(), + ) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/components/chart-themes.spec.ts b/__test__/components/chart-themes.spec.ts new file mode 100644 index 00000000..319008a2 --- /dev/null +++ b/__test__/components/chart-themes.spec.ts @@ -0,0 +1,167 @@ +import { color } from 'echarts/core' +import { darkTheme, lightTheme } from 'naive-ui' +import { getCustomEchartTheme } from '../../packages/ui/src/RChart/src/utils/get-custom-echart-theme' +import { loadingOptions } from '../../packages/ui/src/RChart/src/utils/loading-options' +import { + themeStyleOverrides, + themeStyles, +} from '../../packages/ui/src/theme-presets' + +const registeredThemes = getCustomEchartTheme() +const themes = new Map(registeredThemes.map(({ name, theme }) => [name, theme])) +const variants = themeStyles.flatMap((style) => + (['light', 'dark'] as const).map((mode) => ({ + style, + mode, + name: `ray-${style}${mode === 'dark' ? '-dark' : ''}`, + })), +) + +const composite = (foreground: number[], background: number[]) => + foreground + .slice(0, 3) + .map( + (channel, index) => + channel * foreground[3] + background[index] * (1 - foreground[3]), + ) + +const luminance = (rgb: number[]) => + rgb + .map((channel) => { + const value = channel / 255 + + return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4 + }) + .reduce( + (sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], + 0, + ) + +const contrast = (foreground: string, background: string, surface = '#fff') => { + // 暗色 Naive/Plain 文本和指示线含透明度;必须先与实际底色合成再计算对比度。 + const back = composite(color.parse(background), color.parse(surface)) + const front = composite(color.parse(foreground), back) + const [lighter, darker] = [luminance(front), luminance(back)].sort( + (a, b) => b - a, + ) + + return (lighter + 0.05) / (darker + 0.05) +} + +it('registers every style in both modes with unique deterministic names', () => { + expect(registeredThemes).toHaveLength(themes.size) + expect([...themes.keys()]).toEqual( + expect.arrayContaining(variants.map(({ name }) => name)), + ) +}) + +it.each(variants)( + '$name matches the owning page surface', + ({ style, mode, name }) => { + const theme = themes.get(name)! + const common = { + ...(mode === 'dark' ? darkTheme : lightTheme).common, + ...themeStyleOverrides[style][mode].common, + } + + expect(color.parse(theme.backgroundColor)).toEqual( + color.parse(common.cardColor), + ) + expect(theme.darkMode).toBe(mode === 'dark') + expect(color.parse(theme.pie.itemStyle.borderColor)).toEqual( + color.parse(common.cardColor), + ) + }, +) + +it.each(variants)( + '$name keeps text, data, and active pointers legible', + ({ name }) => { + const theme = themes.get(name)! + const background = theme.backgroundColor + const textColors = [ + theme.textStyle.color, + theme.title.textStyle.color, + theme.title.subtextStyle.color, + theme.legend.textStyle.color, + ...['categoryAxis', 'valueAxis', 'timeAxis', 'logAxis'].map( + (axis) => theme[axis].axisLabel.color, + ), + ] + + for (const foreground of textColors) { + expect( + contrast(foreground, background), + `${name}: text ${foreground}`, + ).toBeGreaterThanOrEqual(4.5) + } + + expect( + contrast( + theme.tooltip.textStyle.color, + theme.tooltip.backgroundColor, + background, + ), + ).toBeGreaterThanOrEqual(4.5) + const pointer = theme.tooltip.axisPointer + + expect( + contrast(pointer.label.color, pointer.label.backgroundColor, background), + ).toBeGreaterThanOrEqual(4.5) + + for (const foreground of [ + ...theme.color, + pointer.lineStyle.color, + pointer.crossStyle.color, + ]) { + expect( + contrast(foreground, background), + `${name}: mark ${foreground}`, + ).toBeGreaterThanOrEqual(3) + } + }, +) + +it.each(variants)( + '$name supplies a matching loading layer without mutating its theme', + ({ mode, name }) => { + const theme = themes.get(name)! + const before = JSON.stringify(theme) + const loading = loadingOptions(theme, mode === 'dark', 'Loading', {}) + const background = color.parse(theme.backgroundColor) + + expect(color.parse(loading.maskColor)).toEqual([ + ...background.slice(0, 3), + 0.9, + ]) + expect(loading.color).toBe(theme.color[0]) + expect(loading.textColor).toBe(theme.textStyle.color) + expect(JSON.stringify(theme)).toBe(before) + }, +) + +it.each(['transparent', 'rgba(0, 0, 0, 0)', 'invalid', void 0])( + 'uses a mode-aware surface for a missing/transparent loading background (%s)', + (backgroundColor) => { + const theme = { backgroundColor } + + expect( + color.parse(loadingOptions(theme, false, 'Loading', {}).maskColor), + ).toEqual([255, 255, 255, 0.9]) + expect( + color.parse(loadingOptions(theme, true, 'Loading', {}).maskColor), + ).toEqual([23, 33, 49, 0.9]) + }, +) + +it('preserves caller loading overrides', () => { + const overrides = { + maskColor: 'transparent', + showSpinner: false, + text: 'Preparing', + } + + expect( + loadingOptions(themes.get('ray-modern'), false, 'Loading', overrides), + ).toMatchObject(overrides) +}) diff --git a/__test__/components/draggable-card.spec.tsx b/__test__/components/draggable-card.spec.tsx new file mode 100644 index 00000000..7e679e66 --- /dev/null +++ b/__test__/components/draggable-card.spec.tsx @@ -0,0 +1,66 @@ +import { flushPromises, mount } from '@vue/test-utils' +import interact from 'interactjs' +import RDraggableCard from '../../packages/ui/src/RDraggableCard/DraggableCard' + +const mocks = vi.hoisted(() => ({ + instances: [] as Array<{ + draggable: ReturnType + resizable: ReturnType + unset: ReturnType + }>, +})) + +vi.mock('interactjs', () => ({ + default: Object.assign( + vi.fn(() => { + const instance = { + draggable: vi.fn().mockReturnThis(), + resizable: vi.fn().mockReturnThis(), + unset: vi.fn(), + } + + mocks.instances.push(instance) + + return instance + }), + { modifiers: { restrictRect: vi.fn((value) => value) } }, + ), +})) + +beforeEach(() => { + mocks.instances.length = 0 + vi.mocked(interact).mockClear() +}) + +it('releases drag listeners on disable/unmount and removes only the final shared container', async () => { + const first = mount(RDraggableCard, { props: { title: 'First' } }) + const second = mount(RDraggableCard, { props: { title: 'Second' } }) + + await flushPromises() + expect(interact).toHaveBeenCalledTimes(2) + await first.setProps({ dad: false }) + expect(mocks.instances[0].unset).toHaveBeenCalledOnce() + await first.setProps({ dad: true }) + expect(interact).toHaveBeenCalledTimes(3) + first.unmount() + expect(mocks.instances[2].unset).toHaveBeenCalledOnce() + expect(document.getElementById('r-draggable-card-container')).not.toBeNull() + second.unmount() + expect(mocks.instances[1].unset).toHaveBeenCalledOnce() + expect(document.getElementById('r-draggable-card-container')).toBeNull() +}) + +it('repositions and rebinds after boundary changes without keeping the previous interaction', async () => { + const wrapper = mount(RDraggableCard, { props: { title: 'Test' } }) + + try { + await flushPromises() + await wrapper.setProps({ defaultPosition: { x: 24, y: 36 } }) + expect(mocks.instances[0].unset).toHaveBeenCalledOnce() + expect( + document.querySelector('.r-draggable-card')?.style.transform, + ).toBe('translate(24px, 36px)') + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/components/flow.spec.tsx b/__test__/components/flow.spec.tsx new file mode 100644 index 00000000..92028256 --- /dev/null +++ b/__test__/components/flow.spec.tsx @@ -0,0 +1,98 @@ +import LogicFlow from '@logicflow/core' +import { flushPromises, mount } from '@vue/test-utils' +import { RFlow, useFlow } from '../../packages/ui/src/RFlow' +import flowProps from '../../packages/ui/src/RFlow/src/props' + +const mocks = vi.hoisted(() => ({ + instances: [] as Array<{ + render: ReturnType + renderRawData: ReturnType + destroy: ReturnType + updateEditConfig: ReturnType + keyboard: { disabled: boolean; disable: ReturnType } + }>, +})) + +vi.mock('@logicflow/core', () => { + class FakeFlow { + static use = vi.fn() + render = vi.fn() + renderRawData = vi.fn() + destroy = vi.fn() + updateEditConfig = vi.fn() + keyboard = { disabled: true, disable: vi.fn() } + getEditConfig = () => ({ + isSilentMode: false, + textEdit: false, + adjustNodePosition: false, + }) + constructor() { + mocks.instances.push(this) + } + } + + return { default: FakeFlow } +}) + +beforeEach(() => { + mocks.instances.length = 0 + vi.mocked(LogicFlow.use).mockClear() +}) + +it('registers later plugin sets, renders initial data, and releases each instance', async () => { + const [register, actions] = useFlow() + const data = { nodes: [{ id: 'start' }], edges: [] } + const plugin = { pluginName: 'later-plugin', install: vi.fn() } + const first = mount(RFlow) + const second = mount(RFlow, { + props: { data, use: [plugin], onRegister: register }, + }) + + expect(LogicFlow.use).toHaveBeenCalledWith(plugin) + expect(mocks.instances[1].render).toHaveBeenCalledWith(data) + expect(actions.getFlowInstance()).toBe(mocks.instances[1]) + await second.setProps({ data: void 0 }) + expect(mocks.instances[1].renderRawData).toHaveBeenLastCalledWith({ + nodes: [], + edges: [], + }) + first.unmount() + second.unmount() + await flushPromises() + expect( + mocks.instances.every( + (instance) => instance.destroy.mock.calls.length === 1, + ), + ).toBe(true) + expect(() => actions.getFlowInstance()).toThrow('flow instance is not ready') +}) + +it('restores configured editing and keyboard behavior after readonly mode', async () => { + const wrapper = mount(RFlow) + const instance = mocks.instances[0] + + try { + expect(instance.updateEditConfig).not.toHaveBeenCalled() + await wrapper.setProps({ readonly: true }) + expect(instance.updateEditConfig).toHaveBeenLastCalledWith({ + isSilentMode: true, + }) + await wrapper.setProps({ readonly: false }) + expect(instance.updateEditConfig).toHaveBeenLastCalledWith({ + isSilentMode: false, + textEdit: false, + adjustNodePosition: false, + }) + expect(instance.keyboard.disable).toHaveBeenCalledOnce() + } finally { + wrapper.unmount() + } +}) + +it('creates independent nested default options for every instance', () => { + const first = flowProps.options.default() + const second = flowProps.options.default() + + expect(first).not.toBe(second) + expect(first.keyboard).not.toBe(second.keyboard) +}) diff --git a/__test__/components/table-pro-columns.spec.ts b/__test__/components/table-pro-columns.spec.ts index af355b4a..e7e5c654 100644 --- a/__test__/components/table-pro-columns.spec.ts +++ b/__test__/components/table-pro-columns.spec.ts @@ -4,7 +4,10 @@ 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' -import { useColumnVisibility } from '../../packages/ui/src/RTablePro/src/columns' +import { + getLeafColumns, + useColumnVisibility, +} from '../../packages/ui/src/RTablePro/src/columns' import ColumnSettings from '../../packages/ui/src/RTablePro/src/components/ColumnSettings' const name = { key: 'name', title: 'Name' } @@ -20,6 +23,28 @@ afterEach(() => { columns.value = [selection, group, region] }) +it('filters nested leaves and prunes empty groups while retaining unaffected branches', () => { + const scope = effectScope() + const nested = { key: 'outer', children: [group] } + const source = shallowRef([nested, region]) + + try { + const state = scope.run(() => useColumnVisibility(source, ref()))! + + state.setColumnVisible('email', false) + expect( + getLeafColumns(state.visibleColumns.value).map(({ key }) => key), + ).toEqual(['name', 'region']) + expect(state.visibleColumns.value[1]).toBe(region) + state.setColumnVisible('name', false) + expect(state.visibleColumns.value).toEqual([region]) + state.resetColumns() + expect(state.visibleColumns.value).toBe(source.value) + } finally { + scope.stop() + } +}) + it('stores only hidden leaf keys, restores them on mount, and isolates separate keys', () => { const scope = effectScope() const second = effectScope() @@ -100,6 +125,126 @@ it('updates visibility without touching storage when no key is configured', () = } }) +it.each([false, true])( + 'pins and unpins every group descendant without mutating source definitions (controlled=%s)', + async (controlled) => { + const renderName = (row: { name: string }) => row.name + const nameColumn = { + ...name, + width: 120, + resizable: true, + render: renderName, + } + const emailColumn = { + ...email, + width: 180, + resizable: false, + fixed: 'right' as const, + } + const children = [nameColumn, emailColumn] + const nested = { key: 'inner', title: 'Details', children } + const grouped = { key: 'contact', title: 'Contact', children: [nested] } + const unaffected = { ...region, width: 140, fixed: 'right' as const } + const input: DataTableColumn[] = [grouped, unaffected] + + for (const value of [ + nameColumn, + emailColumn, + children, + nested, + grouped.children, + grouped, + unaffected, + input, + ]) + Object.freeze(value) + + const update = vi.fn() + const wrapper = mount(RTablePro, { + props: { + columns: input, + data: [ + { id: 1, name: 'Alice', email: 'alice@example.test', region: 'West' }, + ], + scrollX: 440, + ...(controlled ? { 'onUpdate:columns': update } : {}), + }, + }) + + try { + const settings = wrapper.getComponent(ColumnSettings) + const table = wrapper.getComponent(NDataTable) + const patch = async (value: { + fixed?: 'left' | 'right' + resizable?: boolean + }) => { + settings.vm.$emit('patchColumn', 'contact', value) + + if (controlled) + await wrapper.setProps({ columns: update.mock.lastCall![0] }) + else await nextTick() + } + + await patch({ resizable: true }) + expect(table.props('columns')![0]).toMatchObject({ + children: [ + { + children: [ + { resizable: true }, + { resizable: false, fixed: 'right' }, + ], + }, + ], + }) + + for (const fixed of ['left', 'right', void 0] as const) { + await patch({ fixed }) + const result = table.props('columns')! + const leaves = getLeafColumns(result) + + expect(result[0].fixed).toBe(fixed) + expect('children' in result[0] && result[0].children[0].fixed).toBe( + fixed, + ) + expect(leaves[0]).toMatchObject({ + key: 'name', + width: 120, + resizable: true, + render: renderName, + }) + expect(leaves[1]).toMatchObject({ + key: 'email', + width: 180, + resizable: false, + }) + expect(leaves[0].fixed).toBe(fixed) + expect(leaves[1].fixed).toBe(fixed) + expect(result[1]).toBe(unaffected) + + for (const key of ['name', 'email']) { + const cell = wrapper.get(`tbody td[data-col-key="${key}"]`) + + if (fixed) + expect(cell.classes()).toContain(`n-data-table-td--fixed-${fixed}`) + else + expect( + cell.classes().some((name) => name.includes('--fixed-')), + ).toBe(false) + } + } + + expect(nameColumn).not.toHaveProperty('fixed') + expect(emailColumn.fixed).toBe('right') + expect(grouped).not.toHaveProperty('fixed') + expect(nested).not.toHaveProperty('fixed') + expect(grouped.children[0]).toBe(nested) + expect(nested.children).toBe(children) + } finally { + wrapper.unmount() + } + }, +) + it('provides the full settings with a frozen plain columns array and keeps adjustments when definitions change', async () => { const input: DataTableColumn[] = [ selection, diff --git a/__test__/components/table-pro-image-svg.spec.ts b/__test__/components/table-pro-image-svg.spec.ts new file mode 100644 index 00000000..8145c09b --- /dev/null +++ b/__test__/components/table-pro-image-svg.spec.ts @@ -0,0 +1,161 @@ +import { iconSprites } from '@ray-template/icons/manifest' +import { inlineTableSvgUses } from '../../packages/ui/src/RTablePro/src/image-svg' + +const sprite = + '' +const response = (source = sprite) => + new Response(source, { headers: { 'Content-Type': 'image/svg+xml' } }) + +afterEach(() => { + document.querySelectorAll('[data-svg-test]').forEach((node) => node.remove()) + vi.unstubAllGlobals() +}) + +it('inlines repeated registered sprites once, retaining viewport/color without copied IDs or source mutations', async () => { + const fetchAsset = vi.fn(async () => response()) + + vi.stubGlobal('fetch', fetchAsset) + const source = document.createElement('div') + + source.setAttribute('data-svg-test', '') + source.innerHTML = `` + document.body.append(source) + const clone = source.cloneNode(true) as HTMLElement + + document.body.append(clone) + const colors = Array.from( + clone.querySelectorAll('use'), + (use) => getComputedStyle(use).color, + ) + + await inlineTableSvgUses(clone, new AbortController().signal) + expect(fetchAsset).toHaveBeenCalledOnce() + expect(fetchAsset.mock.calls[0]).toEqual([ + new URL(iconSprites.action, document.baseURI).href, + expect.objectContaining({ + credentials: 'omit', + redirect: 'error', + mode: 'same-origin', + signal: expect.any(AbortSignal), + }), + ]) + expect(clone.querySelector('use, [id], [onload]')).toBeNull() + expect(clone.querySelectorAll('path')).toHaveLength(2) + const vectors = clone.querySelectorAll('svg svg') + + expect(vectors[0].getAttribute('viewBox')).toBe('0 0 48 48') + expect(vectors[0].getAttribute('width')).toBe('24') + expect(vectors[1].getAttribute('width')).toBe('18') + expect(vectors[0].parentElement!.style.color).toBe(colors[0]) + expect(vectors[1].parentElement!.style.color).toBe(colors[1]) + expect(clone.querySelector('path')!.getAttribute('stroke')).toBe( + 'currentColor', + ) + expect(source.querySelectorAll('use')).toHaveLength(2) + expect(source.querySelector('path')).toBeNull() +}) + +it('resolves local symbols outside the captured region without a fetch', async () => { + const fetchAsset = vi.fn() + + vi.stubGlobal('fetch', fetchAsset) + const definitions = document.createElement('div') + + definitions.setAttribute('data-svg-test', '') + definitions.innerHTML = + '' + const clone = document.createElement('div') + + clone.setAttribute('data-svg-test', '') + clone.innerHTML = + '' + document.body.append(definitions, clone) + + await inlineTableSvgUses(clone, new AbortController().signal) + expect(fetchAsset).not.toHaveBeenCalled() + expect(clone.querySelector('rect')).not.toBeNull() + expect(clone.querySelector('use, [id]')).toBeNull() + expect(clone.querySelector('svg svg')!.getAttribute('viewBox')).toBe( + '0 0 16 16', + ) + expect(document.getElementById('local-capture-symbol')).not.toBeNull() +}) + +it.each(['https://outside.example/sprite.svg', '/api/admin/private'])( + 'rejects an unrelated source %s without fetching it', + async (url) => { + const fetchAsset = vi.fn() + + vi.stubGlobal('fetch', fetchAsset) + const clone = document.createElement('div') + + clone.innerHTML = `` + await expect( + inlineTableSvgUses(clone, new AbortController().signal), + ).rejects.toThrow('same-origin public assets') + expect(fetchAsset).not.toHaveBeenCalled() + }, +) + +it.each([ + '', + '
Active HTML
', + '', + '', + '', + '', + '', +])( + 'rejects non-static SVG content before inserting it into the snapshot', + async (content) => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => + response( + `${content}`, + ), + ), + ) + const clone = document.createElement('div') + + clone.setAttribute('data-svg-test', '') + clone.innerHTML = '' + document.body.append(clone) + await expect( + inlineTableSvgUses(clone, new AbortController().signal), + ).rejects.toThrow() + expect(clone.querySelector('script, foreignObject, image, path')).toBeNull() + }, +) + +it('bounds streamed source size and forwards cancellation to sprite fetches', async () => { + const clone = document.createElement('div') + + clone.innerHTML = '' + vi.stubGlobal( + 'fetch', + vi.fn(async () => response('x'.repeat(1024 * 1024 + 1))), + ) + await expect( + inlineTableSvgUses(clone, new AbortController().signal), + ).rejects.toThrow('too large') + + const controller = new AbortController() + const fetchAsset = vi.fn( + (_url: string, options: RequestInit) => + new Promise((_resolve, reject) => { + options.signal!.addEventListener( + 'abort', + () => reject(new DOMException('Cancelled', 'AbortError')), + { once: true }, + ) + }), + ) + + vi.stubGlobal('fetch', fetchAsset) + const pending = inlineTableSvgUses(clone, controller.signal) + + controller.abort() + await expect(pending).rejects.toMatchObject({ name: 'AbortError' }) + expect(fetchAsset.mock.calls[0][1].signal).toBe(controller.signal) +}) diff --git a/__test__/components/table-pro-image.spec.tsx b/__test__/components/table-pro-image.spec.tsx new file mode 100644 index 00000000..dae403e5 --- /dev/null +++ b/__test__/components/table-pro-image.spec.tsx @@ -0,0 +1,412 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { h } from 'vue' +import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro' +import type { + TableProInst, + TableProResult, +} from '../../packages/ui/src/RTablePro' +import { + copyTableImage, + createTableImageSnapshot, +} from '../../packages/ui/src/RTablePro/src/image' +import { provideUiServices } from '../../packages/ui/src/services' + +const renderer = vi.hoisted(() => ({ + create: vi.fn(), + options: [] as Record[], + nodes: [] as HTMLElement[], +})) + +vi.mock('@ray-template/composables/useDomToImage', () => ({ + useDomToImage: (node: HTMLElement, options: Record) => { + renderer.nodes.push(node) + renderer.options.push(options) + + return { create: renderer.create } + }, +})) + +class Item { + constructor(readonly data: Record>) {} +} + +const png = () => new Blob(['png'], { type: 'image/png' }) +let write: ReturnType Promise>> +let originalClipboard: PropertyDescriptor | undefined +const columns = [{ key: 'name', title: 'Name' }] +const data = [{ id: 1, name: 'Ray' }] +const tickCapture = () => new Promise((resolve) => setTimeout(resolve, 0)) + +beforeEach(() => { + renderer.create.mockReset().mockResolvedValue(png()) + renderer.options.length = 0 + renderer.nodes.length = 0 + write = vi.fn(async ([item]) => { + await item.data['image/png'] + }) + originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { write }, + }) + vi.stubGlobal('ClipboardItem', Item) + vi.stubGlobal('isSecureContext', true) + vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(640) + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(240) +}) + +afterEach(() => { + document + .querySelectorAll('[data-r-table-image-snapshot]') + .forEach((node) => node.remove()) + + if (originalClipboard) + Object.defineProperty(navigator, 'clipboard', originalClipboard) + else Reflect.deleteProperty(navigator, 'clipboard') + + vi.unstubAllGlobals() + vi.restoreAllMocks() +}) + +it('requests clipboard writing synchronously and supplies an eventual PNG without retaining its snapshot', async () => { + const target = document.createElement('div') + + target.textContent = 'Current table' + document.body.append(target) + + try { + const copying = copyTableImage(target, { pixelRatio: 1 }) + + expect(write).toHaveBeenCalledOnce() + expect(renderer.create).not.toHaveBeenCalled() + expect(write.mock.calls[0][0][0].data['image/png']).toBeInstanceOf(Promise) + await copying + expect(renderer.create).toHaveBeenCalledExactlyOnceWith('blob') + expect(renderer.options[0]).toMatchObject({ + imageType: 'blob', + type: 'image/png', + pixelRatio: 1, + }) + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() + } finally { + target.remove() + } +}) + +it('preserves scroll viewport and input state in an inert clone without touching the live table', () => { + const target = document.createElement('div') + + target.innerHTML = + '
' + const viewport = target.querySelector('.viewport')! + + viewport.scrollLeft = 80 + viewport.scrollTop = 120 + target.querySelector('input')!.checked = true + target.querySelector('textarea')!.value = 'Current' + target.style.setProperty('--example-color', 'rgb(10, 20, 30)') + document.body.append(target) + + const snapshot = createTableImageSnapshot(target) + + try { + expect(snapshot.element.inert).toBe(true) + expect(snapshot.element.getAttribute('aria-hidden')).toBe('true') + expect(snapshot.element.style.width).toBe('640px') + expect(snapshot.element.style.height).toBe('240px') + expect(snapshot.element.style.getPropertyValue('--example-color')).toBe( + 'rgb(10, 20, 30)', + ) + expect( + snapshot.element.querySelector('.rows')!.style.transform, + ).toContain('translate(-80px, -120px)') + expect( + snapshot.element.querySelector('input')!.defaultChecked, + ).toBe(true) + expect( + snapshot.element.querySelector('textarea')!.value, + ).toBe('Current') + expect(viewport.scrollLeft).toBe(80) + expect(viewport.scrollTop).toBe(120) + expect(target.querySelector('.rows')!.style.transform).toBe('') + expect( + target.querySelector('[type="radio"]')!.checked, + ).toBe(true) + expect(snapshot.element.querySelector('[name], [autofocus]')).toBeNull() + } finally { + snapshot.dispose() + target.remove() + } +}) + +it('removes active event attributes and scripts before connecting a snapshot', () => { + const target = document.createElement('div') + + target.innerHTML = + 'Cell' + document.body.append(target) + const snapshot = createTableImageSnapshot(target) + + try { + expect( + snapshot.element.querySelector('script, [onclick], [onload], [onerror]'), + ).toBeNull() + expect(target.querySelector('[onclick]')).not.toBeNull() + expect(target.querySelector('script')).not.toBeNull() + } finally { + snapshot.dispose() + target.remove() + } +}) + +it.each(['iframe', 'object', 'embed', 'audio', 'video'])( + 'rejects %s content before creating a connected clone', + (tag) => { + const target = document.createElement('div') + + target.append(document.createElement(tag)) + vi.spyOn(target, 'isConnected', 'get').mockReturnValue(true) + const clone = vi.spyOn(target, 'cloneNode') + + try { + expect(() => createTableImageSnapshot(target)).toThrow('Embedded media') + expect(clone).not.toHaveBeenCalled() + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() + } finally { + target.remove() + } + }, +) + +it('aborts a pending sprite request on unmount without rasterizing or leaving a snapshot', async () => { + const fetchAsset = vi.fn( + (_url: string, options: RequestInit) => + new Promise((_resolve, reject) => { + options.signal!.addEventListener( + 'abort', + () => reject(new DOMException('Cancelled', 'AbortError')), + { once: true }, + ) + }), + ) + + vi.stubGlobal('fetch', fetchAsset) + const wrapper = mount(RTablePro, { + attachTo: document.body, + props: { + columns: [ + { + key: 'icon', + title: 'Icon', + render: () => + h('svg', [h('use', { href: '/public/sprite.svg#icon' })]), + }, + ], + data, + }, + }) + const copying = (wrapper.vm as unknown as TableProInst).copyImage() + + await tickCapture() + expect(fetchAsset).toHaveBeenCalledOnce() + wrapper.unmount() + expect(await copying).toBe(false) + expect(fetchAsset.mock.calls[0][1].signal!.aborted).toBe(true) + expect(renderer.create).not.toHaveBeenCalled() + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() +}) + +it('copies only the native table region and supports configured options and hidden actions through the hook', async () => { + const [register, actions] = useTablePro() + const wrapper = mount(RTablePro, { + attachTo: document.body, + props: { + columns, + data, + title: 'Excluded heading', + onRegister: register, + search: [{ key: 'name', label: 'Excluded search' }], + copyImageOptions: { pixelRatio: 1, backgroundColor: '#ffffff' }, + }, + slots: { + toolbar: 'Excluded toolbar', + tableFooter: 'Excluded footer', + tableAction: 'Excluded action', + }, + }) + + try { + expect(wrapper.find('[aria-label="Copy table image"]').exists()).toBe(true) + expect(await actions.copyImage({ pixelRatio: 2 })).toBe(true) + const target = renderer.nodes[0] + + expect(target.classList.contains('n-data-table')).toBe(true) + expect(target.textContent).toContain('Ray') + expect(target.querySelector('th')).not.toBeNull() + expect(target.querySelector('.n-data-table__pagination')).not.toBeNull() + expect(target.textContent).not.toMatch(/Excluded/) + expect(renderer.options[0]).toMatchObject({ + pixelRatio: 2, + backgroundColor: '#ffffff', + }) + expect(wrapper.get('[role="status"]').text()).toBe('Table image copied') + await wrapper.setProps({ showCopyImage: false }) + expect(wrapper.find('[aria-label="Copy table image"]').exists()).toBe(false) + expect(await actions.copyImage()).toBe(true) + } finally { + wrapper.unmount() + } +}) + +it('reports unavailable and denied clipboard access without rendering or claiming success', async () => { + const wrapper = mount(RTablePro, { + attachTo: document.body, + props: { columns, data }, + }) + const instance = wrapper.vm as unknown as TableProInst + + try { + vi.stubGlobal('ClipboardItem', void 0) + expect(await instance.copyImage()).toBe(false) + expect(wrapper.get('[role="alert"]').text()).toContain('cannot copy PNG') + expect(write).not.toHaveBeenCalled() + vi.stubGlobal('ClipboardItem', Item) + write.mockRejectedValueOnce(new DOMException('Denied', 'NotAllowedError')) + expect(await instance.copyImage()).toBe(false) + expect(wrapper.get('[role="alert"]').text()).toContain('access was denied') + expect(renderer.create).not.toHaveBeenCalled() + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() + } finally { + wrapper.unmount() + } +}) + +it.each(['reject', 'empty'] as const)( + 'cleans up a %s render result and allows a later retry', + async (failure) => { + if (failure === 'reject') + renderer.create.mockRejectedValueOnce(new Error('Image failed')) + else renderer.create.mockResolvedValueOnce(null) + + const wrapper = mount(RTablePro, { + attachTo: document.body, + props: { columns, data }, + }) + const instance = wrapper.vm as unknown as TableProInst + + try { + expect(await instance.copyImage()).toBe(false) + expect(wrapper.get('[role="alert"]').text()).toContain("Couldn't copy") + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() + expect(await instance.copyImage()).toBe(true) + } finally { + wrapper.unmount() + } + }, +) + +it('deduplicates an in-flight capture and cancels unfinished clipboard data on unmount', async () => { + const pending = Promise.withResolvers() + + renderer.create.mockReturnValueOnce(pending.promise) + const success = vi.fn() + const error = vi.fn() + const wrapper = mount( + { + setup() { + provideUiServices({ reportSuccess: success, reportError: error }) + + return () => h(RTablePro, { columns, data }) + }, + }, + { attachTo: document.body }, + ) + const instance = wrapper.getComponent(RTablePro).vm as unknown as TableProInst + const copying = instance.copyImage() + + await tickCapture() + expect(renderer.create).toHaveBeenCalledOnce() + expect(await instance.copyImage()).toBe(false) + expect(write).toHaveBeenCalledOnce() + wrapper.unmount() + expect(await copying).toBe(false) + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() + pending.resolve(png()) + await flushPromises() + expect(success).not.toHaveBeenCalled() + expect(error).not.toHaveBeenCalled() +}) + +it('does not capture unconfirmed remote results', async () => { + const pending = Promise.withResolvers() + const wrapper = mount(RTablePro, { + attachTo: document.body, + props: { columns, request: () => pending.promise }, + }) + + try { + expect(await (wrapper.vm as unknown as TableProInst).copyImage()).toBe( + false, + ) + expect(write).not.toHaveBeenCalled() + pending.resolve({ data, total: 1 }) + await flushPromises() + expect(await (wrapper.vm as unknown as TableProInst).copyImage()).toBe(true) + } finally { + wrapper.unmount() + } +}) + +it('uses bilingual host feedback and preserves a successful result if the host notifier fails', async () => { + const success = vi.fn(() => { + throw new Error('Notifier unavailable') + }) + const wrapper = mount( + { + setup() { + provideUiServices({ locale: () => 'zh-CN', reportSuccess: success }) + + return () => h(RTablePro, { columns, data }) + }, + }, + { attachTo: document.body }, + ) + + try { + const instance = wrapper.getComponent(RTablePro) + .vm as unknown as TableProInst + + expect(await instance.copyImage()).toBe(true) + expect(success).toHaveBeenCalledExactlyOnceWith('表格图片已复制') + expect(wrapper.get('[role="status"]').text()).toBe('表格图片已复制') + } finally { + wrapper.unmount() + } +}) + +it('cancels pending capture when the displayed dataset changes', async () => { + const pending = Promise.withResolvers() + + renderer.create.mockReturnValueOnce(pending.promise) + const wrapper = mount(RTablePro, { + attachTo: document.body, + props: { columns, data }, + }) + const copying = (wrapper.vm as unknown as TableProInst).copyImage() + + try { + await tickCapture() + expect( + document.querySelector('[data-r-table-image-snapshot]'), + ).not.toBeNull() + await wrapper.setProps({ data: [{ id: 2, name: 'New query' }] }) + expect(await copying).toBe(false) + expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull() + expect(wrapper.find('[role="alert"]').exists()).toBe(false) + pending.resolve(png()) + await flushPromises() + expect(wrapper.find('[role="status"]').exists()).toBe(false) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/components/table-pro-pagination.spec.ts b/__test__/components/table-pro-pagination.spec.ts new file mode 100644 index 00000000..68058706 --- /dev/null +++ b/__test__/components/table-pro-pagination.spec.ts @@ -0,0 +1,42 @@ +import { splitPaginationOptions } from '../../packages/ui/src/RTablePro/src/pagination' +import type { TableProPagination } from '../../packages/ui/src/RTablePro/src/types' + +it('uses only current update handlers and removes them from native view props', () => { + const page = vi.fn() + const modelPage = vi.fn() + const size = vi.fn() + const modelSize = vi.fn() + const options: TableProPagination = { + page: 2, + pageSize: 20, + showSizePicker: true, + onUpdatePage: [page], + 'onUpdate:page': modelPage, + onUpdatePageSize: size, + 'onUpdate:pageSize': [modelSize], + } + const pager = splitPaginationOptions(options) + + pager.notifyPage(3) + pager.notifyPageSize(50) + expect(page).toHaveBeenCalledExactlyOnceWith(3) + expect(modelPage).toHaveBeenCalledExactlyOnceWith(3) + expect(size).toHaveBeenCalledExactlyOnceWith(50) + expect(modelSize).toHaveBeenCalledExactlyOnceWith(50) + expect(pager.view).toEqual({ page: 2, pageSize: 20, showSizePicker: true }) +}) + +it('drops obsolete callback keys from untyped runtime configuration', () => { + const onChange = vi.fn() + const onPageSizeChange = vi.fn() + const legacy = { page: 1, onChange, onPageSizeChange } + const pager = splitPaginationOptions(legacy) + + pager.notifyPage(2) + pager.notifyPageSize(20) + expect(pager.view).toEqual({ page: 1 }) + expect(onChange).not.toHaveBeenCalled() + expect(onPageSizeChange).not.toHaveBeenCalled() + expectTypeOf().not.toHaveProperty('onChange') + expectTypeOf().not.toHaveProperty('onPageSizeChange') +}) diff --git a/__test__/components/table-pro-toolbar.spec.tsx b/__test__/components/table-pro-toolbar.spec.tsx new file mode 100644 index 00000000..6e1e1e35 --- /dev/null +++ b/__test__/components/table-pro-toolbar.spec.tsx @@ -0,0 +1,134 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { NDataTable, NDropdown } from 'naive-ui' +import { RTablePro } from '../../packages/ui/src/RTablePro' +import type { TableProRequest } from '../../packages/ui/src/RTablePro' +import * as csv from '../../packages/ui/src/RTablePro/src/csv' +import * as printing from '../../packages/ui/src/RTablePro/src/printing' + +const columns = [{ key: 'name', title: 'Name' }] +const data = [{ id: 1, name: 'Ray' }] + +afterEach(() => vi.restoreAllMocks()) + +it('hides print by default and groups secondary actions under one menu', async () => { + const wrapper = mount(RTablePro, { props: { columns, data } }) + + try { + const menu = wrapper.getComponent(NDropdown) + const keys = menu.props('options')?.map((option) => option.key) + + expect(keys).toContain('csv') + expect(keys).toContain('density') + expect(keys).not.toContain('print') + expect(wrapper.find('[aria-label="Print table"]').exists()).toBe(false) + expect( + wrapper.get('[aria-label="More actions"]').attributes('aria-haspopup'), + ).toBe('menu') + await wrapper.get('[aria-label="More actions"]').trigger('click') + await flushPromises() + expect(document.body.textContent).not.toContain('Print table') + } finally { + wrapper.unmount() + } +}) + +it('opts into menu printing and retains CSV formatting and output options', async () => { + const download = vi + .spyOn(csv, 'downloadTableCsv') + .mockImplementation(() => {}) + const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true) + const wrapper = mount(RTablePro, { + props: { + columns, + data, + showPrint: true, + downloadCsvTableOptions: { fileName: 'people' }, + printTableOptions: { title: 'People report' }, + getCsvCell: (value) => `Person: ${String(value)}`, + }, + }) + + try { + const menu = wrapper.getComponent(NDropdown) + + expect( + menu.props('options')?.some((option) => option.key === 'print'), + ).toBe(true) + menu.vm.$emit('select', 'csv') + await flushPromises() + expect(download).toHaveBeenCalledExactlyOnceWith( + '"Name"\r\n"Person: Ray"', + 'people', + ) + menu.vm.$emit('select', 'print') + await flushPromises() + expect(print).toHaveBeenCalledOnce() + expect(print.mock.calls[0][1]).toMatchObject({ title: 'People report' }) + await wrapper.setProps({ showPrint: false }) + expect( + menu.props('options')?.some((option) => option.key === 'print'), + ).toBe(false) + menu.vm.$emit('select', 'print') + await flushPromises() + expect(print).toHaveBeenCalledOnce() + } finally { + wrapper.unmount() + } +}) + +it('updates density and appearance without changing caller defaults', async () => { + const wrapper = mount(RTablePro, { + props: { columns, data, size: 'medium', striped: false, bordered: true }, + }) + + try { + const menu = wrapper.getComponent(NDropdown) + + menu.vm.$emit('select', 'density:small') + menu.vm.$emit('select', 'striped') + menu.vm.$emit('select', 'bordered') + await flushPromises() + expect(wrapper.getComponent(NDataTable).props()).toMatchObject({ + size: 'small', + striped: true, + bordered: false, + }) + expect(wrapper.props()).toMatchObject({ + size: 'medium', + striped: false, + bordered: true, + }) + await wrapper.setProps({ size: 'large' }) + expect(wrapper.getComponent(NDataTable).props('size')).toBe('large') + } finally { + wrapper.unmount() + } +}) + +it('refreshes the current remote query and preserves the caller toolbar when tools are disabled', async () => { + const request = vi.fn(async () => ({ data, total: 1 })) + const wrapper = mount(RTablePro, { + props: { columns, request }, + slots: { toolbar: 'Business action' }, + }) + + try { + await flushPromises() + expect(request).toHaveBeenCalledOnce() + await wrapper.get('[aria-label="Refresh"]').trigger('click') + await flushPromises() + expect(request).toHaveBeenCalledTimes(2) + expect(request.mock.lastCall?.[0]).toEqual(request.mock.calls[0][0]) + expect(request.mock.lastCall?.[1]).not.toBe(request.mock.calls[0][1]) + expect(wrapper.get('.r-table__business-actions').text()).toBe( + 'Business action', + ) + await wrapper.setProps({ tool: false }) + expect(wrapper.find('.r-table__utilities').exists()).toBe(false) + expect(wrapper.get('.r-table__business-actions').text()).toBe( + 'Business action', + ) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/components/table-pro.spec.ts b/__test__/components/table-pro.spec.ts index 996fcca0..54901e77 100644 --- a/__test__/components/table-pro.spec.ts +++ b/__test__/components/table-pro.spec.ts @@ -8,7 +8,6 @@ import { provideUiServices } from '@ray-template/ui/services' import { flushPromises, mount } from '@vue/test-utils' import { NDataTable, NDropdown, NPagination } from 'naive-ui' import { defineComponent, h } from 'vue' -import Size from '../../packages/ui/src/RTablePro/src/components/Size' import * as csv from '../../packages/ui/src/RTablePro/src/csv' const columns = [{ title: 'Name', key: 'name' }] @@ -568,7 +567,9 @@ it('provides the row that opened the context menu and discards it after data cha }, global: { stubs: { teleport: true } }, }) - const menu = wrapper.getComponent(NDropdown) + const menu = wrapper + .findAllComponents(NDropdown) + .find((dropdown) => dropdown.props('trigger') === 'manual')! try { const entry = wrapper.get('tbody tr') @@ -634,7 +635,7 @@ it('respects a changed density prop without reviving an earlier local choice', a const native = wrapper.getComponent(NDataTable) try { - wrapper.getComponent(Size).vm.$emit('change', 'small') + wrapper.getComponent(NDropdown).vm.$emit('select', 'density:small') await wrapper.vm.$nextTick() expect(native.props('size')).toBe('small') await wrapper.setProps({ size: 'large' }) diff --git a/__test__/components/wrapper-contracts.spec.tsx b/__test__/components/wrapper-contracts.spec.tsx new file mode 100644 index 00000000..166b99ad --- /dev/null +++ b/__test__/components/wrapper-contracts.spec.tsx @@ -0,0 +1,214 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { NDropdown, NForm, NFormItem, NGrid, NSpin } from 'naive-ui' +import { defineComponent, h, nextTick, ref } from 'vue' +import { RCollapseGrid } from '../../packages/ui/src/RCollapseGrid' +import { RForm, useForm } from '../../packages/ui/src/RForm' +import { RIframe } from '../../packages/ui/src/RIframe' +import type { RIframeInst } from '../../packages/ui/src/RIframe/src/types' +import { RMoreDropdown } from '../../packages/ui/src/RMoreDropdown' +import { RSegment } from '../../packages/ui/src/RSegment' + +it('keeps controlled open state and zero grid gaps consistent', async () => { + const open = ref(false) + const wrapper = mount( + defineComponent(() => () => ( + (open.value = value)} + xGap={0} + yGap={0} + /> + )), + ) + + try { + const button = wrapper.get('button.collapse-icon') + + expect(wrapper.findComponent(NGrid).props()).toMatchObject({ + xGap: 0, + yGap: 0, + collapsed: true, + }) + expect(button.attributes('aria-expanded')).toBe('false') + await button.trigger('click') + expect(open.value).toBe(true) + expect(wrapper.findComponent(NGrid).props('collapsed')).toBe(false) + await button.trigger('click') + expect(open.value).toBe(false) + } finally { + wrapper.unmount() + } +}) + +it('forwards dropdown placement and renders segment label functions', () => { + const dropdown = mount(RMoreDropdown, { + props: { placement: 'top-end', triggerLabel: 'Row actions' }, + }) + const segment = mount(RSegment, { + props: { + options: [{ key: 'one', label: () => h('strong', 'Rendered label') }], + }, + }) + + try { + expect(dropdown.findComponent(NDropdown).props('placement')).toBe('top-end') + expect(dropdown.get('button').attributes('aria-label')).toBe('Row actions') + expect(segment.get('strong').text()).toBe('Rendered label') + } finally { + dropdown.unmount() + segment.unmount() + } +}) + +it('starts iframe loading for every source and exposes the same native element', async () => { + const wrapper = mount(RIframe, { props: { src: '/one.html' } }) + + try { + await nextTick() + const frame = wrapper.get('iframe') + + await frame.trigger('load') + expect(wrapper.findComponent(NSpin).props('show')).toBe(false) + await wrapper.setProps({ src: '/two.html' }) + expect(wrapper.findComponent(NSpin).props('show')).toBe(true) + const instance = wrapper.vm as unknown as RIframeInst + + expect(instance.iframe).toBe(frame.element) + expect(instance.iframeInst).toBe(frame.element) + await frame.trigger('error') + expect(wrapper.findComponent(NSpin).props('show')).toBe(false) + } finally { + wrapper.unmount() + } +}) + +it('submits single-line Enter reactively without consuming IME, multiline, or combobox events', async () => { + const onFinish = vi.fn() + const wrapper = mount(RForm, { + props: { submitWhenEnter: false, onFinish }, + slots: { + default: () => [ + h('input'), + h('textarea'), + h('input', { role: 'combobox' }), + ], + }, + }) + + try { + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + expect(onFinish).not.toHaveBeenCalled() + await wrapper.setProps({ submitWhenEnter: true }) + await wrapper.get('textarea').trigger('keydown', { key: 'Enter' }) + await wrapper.get('[role="combobox"]').trigger('keydown', { key: 'Enter' }) + await wrapper + .get('input') + .trigger('keydown', { key: 'Enter', isComposing: true }) + await flushPromises() + expect(onFinish).not.toHaveBeenCalled() + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + await flushPromises() + expect(onFinish).toHaveBeenCalledOnce() + } finally { + wrapper.unmount() + } +}) + +it('keeps validation failures handled and prevents repeated Enter submissions', async () => { + const pending = Promise.withResolvers() + const onFinish = vi.fn(() => pending.promise) + const wrapper = mount(RForm, { + props: { submitWhenEnter: true, onFinish, model: { name: '' } }, + slots: { + default: () => + h( + NFormItem, + { path: 'name', rule: { required: true, message: 'Required' } }, + () => h('input'), + ), + }, + }) + + try { + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + await flushPromises() + expect(onFinish).not.toHaveBeenCalled() + expect(wrapper.text()).toContain('Required') + await wrapper.setProps({ model: { name: 'Ready' } }) + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + await flushPromises() + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + await flushPromises() + expect(onFinish).toHaveBeenCalledOnce() + pending.resolve() + await flushPromises() + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + await flushPromises() + expect(onFinish).toHaveBeenCalledTimes(2) + } finally { + wrapper.unmount() + } +}) + +it('clears registered form instances when their component unmounts', async () => { + const [register, actions] = useForm({ name: 'Initial', enabled: false }) + const wrapper = mount(RForm, { props: { onRegister: register } }) + + expect(actions.getFormInstance().validate).toBe( + wrapper.findComponent(NForm).vm.validate, + ) + actions.updateFormCondition({ name: 'Updated' }) + expect(actions.formConditionRef.value).toEqual({ + name: 'Updated', + enabled: false, + }) + actions.reset({ enabled: true }) + expect(actions.formConditionRef.value).toEqual({ + name: 'Initial', + enabled: true, + }) + wrapper.unmount() + await nextTick() + expect(() => actions.getFormInstance()).toThrow('form instance is not ready') +}) + +it('allows forwarded key handlers to consume Enter before automatic submission', async () => { + const onFinish = vi.fn() + const onKeydown = vi.fn((event: KeyboardEvent) => event.preventDefault()) + const wrapper = mount(RForm, { + props: { submitWhenEnter: true, onFinish }, + attrs: { onKeydown }, + slots: { default: () => h('input') }, + }) + + try { + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + await flushPromises() + expect(onKeydown).toHaveBeenCalledOnce() + expect(onFinish).not.toHaveBeenCalled() + } finally { + wrapper.unmount() + } +}) + +it('does not submit after its component unmounts during asynchronous validation', async () => { + const validation = Promise.withResolvers() + const onFinish = vi.fn() + const wrapper = mount(RForm, { + props: { submitWhenEnter: true, onFinish, model: { name: 'Ready' } }, + slots: { + default: () => + h( + NFormItem, + { path: 'name', rule: { validator: () => validation.promise } }, + () => h('input'), + ), + }, + }) + + await wrapper.get('input').trigger('keydown', { key: 'Enter' }) + wrapper.unmount() + validation.resolve() + await flushPromises() + expect(onFinish).not.toHaveBeenCalled() +}) diff --git a/__test__/hooks/useAccess.spec.ts b/__test__/hooks/useAccess.spec.ts new file mode 100644 index 00000000..acf34692 --- /dev/null +++ b/__test__/hooks/useAccess.spec.ts @@ -0,0 +1,31 @@ +import { ref } from 'vue' +import { useAccess } from '../../apps/admin/src/hooks/template/useAccess' + +const { state } = vi.hoisted(() => ({ + state: { permissions: void 0 as unknown }, +})) + +vi.mock('../../apps/admin/src/store', () => ({ + useSigningGetters: () => ({ getPermissions: state.permissions }), +})) + +it('preserves all/any semantics and invalidates permission lookups after session changes', () => { + const permissions = ref(['users:read', 'users:write']) + + state.permissions = permissions + const access = useAccess() + + expect(access.permissions).toBe(permissions) + expect(access.hasPermission('users:read')).toBe(true) + expect(access.hasPermission(['users:read', 'users:write'])).toBe(true) + expect(access.hasPermission(['users:read', 'admin:write'])).toBe(false) + expect(access.hasPermission(['users:read', 'admin:write'], 'any')).toBe(true) + expect(access.hasPermission([])).toBe(true) + expect(access.hasPermission([], 'any')).toBe(false) + + permissions.value.splice(1, 1) + expect(access.hasPermission('users:write')).toBe(false) + permissions.value = ['admin:write'] + expect(access.hasPermission('users:read')).toBe(false) + expect(access.hasPermission('admin:write')).toBe(true) +}) diff --git a/__test__/hooks/useElementFullscreen.spec.ts b/__test__/hooks/useElementFullscreen.spec.ts index 8da007f9..4d6df17a 100644 --- a/__test__/hooks/useElementFullscreen.spec.ts +++ b/__test__/hooks/useElementFullscreen.spec.ts @@ -121,6 +121,9 @@ it('restores original style priority and releases ownership even when manual exi expect(element.style.width).toBe('240px') expect(element.style.getPropertyPriority('width')).toBe('important') expect(element.getAttribute('data-element-fullscreen')).toBe('prior') + first.enter() + expect(first.isFullscreen.value).toBe(false) + expect(element.getAttribute('data-element-fullscreen')).toBe('prior') second.enter() expect(second.isFullscreen.value).toBe(true) second.exit() diff --git a/__test__/hooks/usePagination.spec.ts b/__test__/hooks/usePagination.spec.ts index 214ac69d..4485eef0 100644 --- a/__test__/hooks/usePagination.spec.ts +++ b/__test__/hooks/usePagination.spec.ts @@ -94,3 +94,25 @@ it('resets to the first object page size and reports new values to the current c expect(api.getCallback()).toBeUndefined() expect(callback).toHaveBeenCalledOnce() }) + +it('keeps mutable default page-size options local to each instance', () => { + const [first] = usePagination() + const [second] = usePagination() + + first.value.pageSizes!.splice(0, 1, 5) + + expect(second.value.pageSizes).toEqual([10, 20, 50, 100]) + expect(usePagination()[0].value.pageSizes).toEqual([10, 20, 50, 100]) +}) + +it('resets using the currently configured page sizes after replacing them', () => { + const [pagination, api] = usePagination() + + pagination.value.pageSizes = [{ label: 'Twenty five', value: 25 }] + api.resetPagination() + expect(api.getPageSize()).toBe(25) + + pagination.value.pageSizes = [] + api.resetPagination() + expect(api.getPageSize()).toBe(10) +}) diff --git a/__test__/hooks/useSiderBar.spec.ts b/__test__/hooks/useSiderBar.spec.ts index 26524e51..e5292379 100644 --- a/__test__/hooks/useSiderBar.spec.ts +++ b/__test__/hooks/useSiderBar.spec.ts @@ -1,189 +1,243 @@ -import { useAppRoot } from '../../apps/admin/src/hooks/template/useAppRoot' -import { useSiderBar } from '../../apps/admin/src/hooks/template/useSiderBar' -import { useVueRouter } from '../../apps/admin/src/hooks/web/useVueRouter' -import { firstMenuLeaf } from '../../apps/admin/src/layout/navigation' -import { useMenuActions, useMenuGetters } from '../../apps/admin/src/store' -import type { - AppMenuOption, - MenuTagOptions, -} from '../../apps/admin/src/types/modules/app' -import setupMiniApp from '../utils/setupMiniApp' +import { APP_CATCH_KEY } from '@/app-config' +import { useAppRoot } from '@/hooks/template/useAppRoot' +import { useSiderBar } from '@/hooks/template/useSiderBar' +import { setupI18n } from '@/locales' +import { permissionRouter } from '@/router/utils/permission' +import { piniaKeepAliveStore } from '@/store/modules/keep-alive' +import { piniaMenuStore } from '@/store/modules/menu' +import { piniaSettingStore } from '@/store/modules/setting' +import { piniaSigningStore } from '@/store/modules/signing' +import { setStorage } from '@/utils/cache' +import { flushPromises, mount } from '@vue/test-utils' +import type { VueWrapper } from '@vue/test-utils' +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import { defineComponent, h } from 'vue' +import { createMemoryHistory, createRouter } from 'vue-router' +import type { Router } from 'vue-router' -describe('useSiderBar', async () => { - await setupMiniApp() +const state = vi.hoisted(() => ({ + router: null as unknown, + routes: [] as unknown[], +})) - const { setMenuTagOptions, resolveOption } = useMenuActions() - const { - close, - closeAll, - closeRight, - closeLeft, - closeOther, - getCurrentTagIndex, - checkCloseRight, - checkCloseLeft, - } = useSiderBar() +vi.mock('../../apps/admin/src/hooks/template/useVueRouter', () => ({ + useVueRouter: () => ({ router: state.router }), +})) +vi.mock('../../apps/admin/src/router/app-route-modules', () => ({ + getAppRawRoutes: () => state.routes, + appExpandRoutes: () => state.routes, +})) - const updateMenuTagOptions = () => { - const { router } = useVueRouter() - const routes = router.getRoutes() as unknown as AppMenuOption[] +let pinia: ReturnType +let router: Router +let wrapper: VueWrapper +let menu: ReturnType +let actions: ReturnType - routes.forEach((curr) => - setMenuTagOptions( - resolveOption({ - ...curr, - fullPath: curr.path, - }), - true, - ), - ) +beforeEach(async () => { + localStorage.clear() + sessionStorage.clear() + const component = { render: () => h('div') } + const business = [ + { path: '/reports', name: 'Reports', component, meta: { keepAlive: true } }, + { path: '/orders', name: 'Orders', component, meta: {} }, + { + path: '/private', + name: 'Private', + component, + meta: { role: ['admin'], keepAlive: true }, + }, + ] + + state.routes = business + router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/', name: 'RLogin', component }, + { + path: '/welcome', + name: 'RWelcome', + component, + meta: { i18nKey: 'workspaceStates.welcome.title' }, + }, + { + path: '/403', + name: 'ErrorPage403', + component, + meta: { i18nKey: 'workspaceStates.forbidden.title' }, + }, + { path: '/404', name: 'ErrorPage404', component }, + { path: '/500', name: 'ErrorPage500', component }, + { path: '/:catchAll(.*)', name: 'RNotFound', redirect: '/404' }, + ...business, + ], + }) + state.router = router + pinia = createPinia() + setActivePinia(pinia) + piniaSigningStore().signingCallback = { + id: 'one', + name: 'Tester', + role: 'admin', } + setStorage(APP_CATCH_KEY.token, 'token', 'localStorage') + setStorage(APP_CATCH_KEY.appMenuTagOptions, [{ fullPath: '/dashboard' }]) + setStorage(APP_CATCH_KEY.appMenuKey, '/dashboard') + permissionRouter(router) + await router.push('/welcome') + wrapper = mount( + defineComponent({ + setup() { + menu = piniaMenuStore() + actions = useSiderBar() - it('should close target tag', async () => { - updateMenuTagOptions() - - const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [dashboard] = getMenuOptions.value - const beforeIndex = getMenuTagOptions.value.findIndex( - (curr) => curr.fullPath === dashboard.fullPath, - ) - - close(dashboard.fullPath) - - await nextTick() - - const afterIndex = getMenuTagOptions.value.findIndex( - (curr) => curr.fullPath === dashboard.fullPath, - ) - - expect(beforeIndex).not.toBe(afterIndex) - }) - - it('should close all tags', async () => { - updateMenuTagOptions() - - const { getMenuTagOptions } = useMenuGetters() - - closeAll() - - await nextTick() - - const afterLength = getMenuTagOptions.value.length - - expect(afterLength).toBe(1) - }) - - it('should close right tags', async () => { - updateMenuTagOptions() - - const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [dashboard] = getMenuOptions.value - const beforeIndex = getMenuTagOptions.value.findIndex( - (curr) => curr.fullPath === dashboard.fullPath, - ) - - expect(!!getMenuTagOptions.value[beforeIndex + 1]).toBe(true) - - closeRight(dashboard.fullPath) - - await nextTick() - - const afterIndex = getMenuTagOptions.value.findIndex( - (curr) => curr.fullPath === dashboard.fullPath, - ) - - expect(getMenuTagOptions.value[afterIndex + 1]).toBe(void 0) - }) - - it('should close left tags', async () => { - updateMenuTagOptions() - - const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [dashboard] = getMenuOptions.value - - closeLeft(dashboard.fullPath) - - await nextTick() - - const afterIndex = getMenuTagOptions.value.findIndex( - (curr) => curr.fullPath === dashboard.fullPath, - ) - - expect(getMenuTagOptions.value[afterIndex - 1]).toBe(void 0) - }) - - it('should get current tag index', async () => { - updateMenuTagOptions() - - const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [dashboard] = getMenuOptions.value - - const index = getMenuOptions.value.findIndex( - (curr) => curr.fullPath === dashboard.fullPath, - ) - - expect(getCurrentTagIndex()).toBe(index) - }) - - it('should close other tags', async () => { - updateMenuTagOptions() - - const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [dashboard] = getMenuOptions.value - - closeOther(dashboard.fullPath) - - await nextTick() - - expect(getMenuTagOptions.value[0].fullPath).toBe(dashboard.fullPath) - expect(getMenuTagOptions.value.length).toBe(1) - }) - - it('check menuTagOptions left or right can close', async () => { - updateMenuTagOptions() - - const { getMenuOptions, getMenuTagOptions } = useMenuGetters() - const [f, group] = getMenuOptions.value - const s = firstMenuLeaf(group)! - - closeRight(f.fullPath) - - await nextTick() - - const canClose = checkCloseRight(f.fullPath) - - expect(canClose).toBe(false) - - updateMenuTagOptions() - - closeLeft(f.fullPath) - - await nextTick() - - const canCloseLeft = checkCloseLeft(f.fullPath) - - expect(canCloseLeft).toBe(false) - - updateMenuTagOptions() - - expect(checkCloseRight(s.fullPath)).toBe(true) - expect(checkCloseLeft(s.fullPath)).toBe(true) - }) - it('keeps existing tags if the configured home route is no longer registered', () => { - updateMenuTagOptions() - const { getMenuTagOptions } = useMenuGetters() - const { getRootRoute, setRootRoute } = useAppRoot() - const currentRoot = { ...getRootRoute.value } - const currentTags = getMenuTagOptions.value.map((item) => item.fullPath) - - try { - setRootRoute({ path: '/deleted-home-route' }) - closeAll() - expect(getMenuTagOptions.value.map((item) => item.fullPath)).toEqual( - currentTags, - ) - } finally { - setRootRoute(currentRoot) - } - }) + return () => h('div') + }, + }), + { global: { plugins: [pinia, router] } }, + ) + await flushPromises() +}) + +afterEach(() => { + wrapper.unmount() + disposePinia(pinia) + router.options.history.destroy() +}) + +it('starts with no active business page and never injects a missing cached dashboard', () => { + expect(menu.menuTagOptions).toEqual([]) + expect(menu.menuKey).toBeNull() + expect(menu.currentMenuOption).toBeNull() + expect(menu.breadcrumbOptions).toEqual([]) + expect(router.currentRoute.value.path).toBe('/welcome') + expect(menu.options.map(({ fullPath }) => fullPath)).toEqual([ + '/reports', + '/orders', + '/private', + ]) +}) + +it('closes the final business tab, even when it is the legacy root preference', async () => { + useAppRoot().setRootRoute({ path: '/reports', name: 'Reports' }) + await router.push('/reports?sort=asc#summary') + await flushPromises() + expect(actions.getCurrentTagIndex()).toBe(0) + expect(piniaKeepAliveStore().keepAliveInclude).toEqual(['Reports']) + await actions.close(0) + await flushPromises() + expect(menu.menuTagOptions).toEqual([]) + expect(menu.menuKey).toBeNull() + expect(menu.currentMenuOption).toBeNull() + expect(piniaKeepAliveStore().keepAliveInclude).toEqual([]) + expect(router.currentRoute.value.path).toBe('/welcome') +}) + +it('stores one tag per pathname and restores its latest query and hash', async () => { + await router.push('/reports?sort=asc#first') + await router.push('/reports?sort=desc#summary') + await router.push('/orders') + await flushPromises() + expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([ + '/reports?sort=desc#summary', + '/orders', + ]) + await actions.close('/orders') + await flushPromises() + expect(router.currentRoute.value.fullPath).toBe('/reports?sort=desc#summary') + expect(menu.menuKey).toBe('/reports') + expect(actions.getCurrentTagIndex()).toBe(0) +}) + +it('closes left, right and other tabs without protecting any business path', async () => { + for (const path of ['/reports', '/orders', '/private']) + await router.push(path) + + await flushPromises() + expect(actions.checkCloseLeft('/orders')).toBe(true) + expect(actions.checkCloseRight('/orders')).toBe(true) + await actions.closeRight('/orders') + await flushPromises() + expect(router.currentRoute.value.path).toBe('/orders') + expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([ + '/reports', + '/orders', + ]) + await actions.closeLeft('/orders') + await router.push('/reports') + await actions.closeOther('/orders') + await flushPromises() + expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([ + '/orders', + ]) + expect(router.currentRoute.value.path).toBe('/orders') +}) + +it('closes all tags independently of missing or unauthorized root preferences', async () => { + await router.push('/reports') + await router.push('/orders') + useAppRoot().setRootRoute({ path: '/deleted-home' }) + await actions.closeAll() + await flushPromises() + expect(menu.menuTagOptions).toEqual([]) + expect(router.currentRoute.value.path).toBe('/welcome') +}) + +it('keeps status routes out of tabs and clears active business navigation', async () => { + await router.push('/reports') + + for (const path of ['/welcome', '/403', '/404', '/500']) { + await router.push(path) + await flushPromises() + expect(menu.currentMenuOption).toBeNull() + expect(menu.menuKey).toBeNull() + expect(menu.breadcrumbOptions).toEqual([]) + expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([ + '/reports', + ]) + } +}) + +it('removes revoked tags and cached views without choosing another active page', async () => { + await router.push('/reports') + await router.push('/private?mode=edit#section') + piniaSigningStore().signingCallback.role = 'member' + await flushPromises() + expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([ + '/reports', + ]) + expect(piniaKeepAliveStore().keepAliveInclude).toEqual(['Reports']) + expect(menu.currentMenuOption).toBeNull() + expect(router.currentRoute.value.path).toBe('/403') + expect(router.currentRoute.value.query.from).toBe( + '/private?mode=edit#section', + ) +}) + +it('clears account-owned tabs without recreating the still-visible page during logout', async () => { + await router.push('/reports') + piniaSigningStore().signingCallback = {} as never + await flushPromises() + expect(menu.menuTagOptions).toEqual([]) + expect(menu.currentMenuOption).toBeNull() + expect(piniaKeepAliveStore().keepAliveInclude).toEqual([]) +}) + +it('updates neutral and status document titles when the language changes', async () => { + await setupI18n(wrapper.vm.$.appContext.app) + const settings = piniaSettingStore() + + settings.updateLocale('zh-CN') + await router.push('/403') + await flushPromises() + expect(document.title).toContain('暂时无法访问此页面') + settings.updateLocale('en-US') + await flushPromises() + expect(document.title).toContain('This page is not available to you') + await router.push('/welcome') + await flushPromises() + expect(document.title).toContain('Ready for your next task') + settings.updateLocale('zh-CN') + await flushPromises() + expect(document.title).toContain('工作区已就绪') }) diff --git a/__test__/hooks/useTheme.spec.ts b/__test__/hooks/useTheme.spec.ts index a9b0f141..7587c128 100644 --- a/__test__/hooks/useTheme.spec.ts +++ b/__test__/hooks/useTheme.spec.ts @@ -1,5 +1,8 @@ import { useTheme } from '../../apps/admin/src/hooks/template/useTheme' -import { useSettingGetters } from '../../apps/admin/src/store' +import { + useSettingActions, + useSettingGetters, +} from '../../apps/admin/src/store' import setupMiniApp from '../utils/setupMiniApp' describe('useTheme', async () => { @@ -46,6 +49,28 @@ describe('useTheme', async () => { expect(__lightThemeLabel).toBe('Light') }) + it('keeps a reused hook reactive to language and theme changes', () => { + const { updateLocale } = useSettingActions() + const previousLocale = useSettingGetters().getLocaleLanguage.value + + try { + darkTheme() + updateLocale('en-US') + expect(getAppTheme().themeI18nLabel).toBe('Dark') + updateLocale('zh-CN') + expect(getAppTheme().themeI18nLabel).toBe('暗色') + lightTheme() + expect(getAppTheme()).toMatchObject({ + theme: false, + themeLabel: 'Light', + themeI18nLabel: '明亮', + }) + } finally { + updateLocale(previousLocale) + lightTheme() + } + }) + it('selects auto mode and applies the system color preference', () => { const dark = window.matchMedia('(prefers-color-scheme: dark)').matches diff --git a/__test__/layout/content-loading.spec.tsx b/__test__/layout/content-loading.spec.tsx new file mode 100644 index 00000000..0bd644f7 --- /dev/null +++ b/__test__/layout/content-loading.spec.tsx @@ -0,0 +1,89 @@ +import { mount } from '@vue/test-utils' +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import { nextTick } from 'vue' +import ContentLoading from '../../apps/admin/src/layout/default/ContentWrapper/ContentLoading' +import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime' + +vi.mock('@/hooks', () => ({ + useI18n: () => ({ t: () => 'Loading' }), +})) + +describe('content loading feedback', () => { + let pinia: ReturnType + + beforeEach(() => { + vi.useFakeTimers() + pinia = createPinia() + setActivePinia(pinia) + }) + + afterEach(() => { + disposePinia(pinia) + vi.useRealTimers() + }) + + it('delays transient work and exposes a labeled indeterminate progress', async () => { + const wrapper = mount(ContentLoading, { global: { plugins: [pinia] } }) + const runtime = piniaRuntimeStore() + + try { + runtime.setRuntimeState('layoutContentSpinning', true) + await nextTick() + await vi.advanceTimersByTimeAsync(119) + expect(wrapper.find('progress').exists()).toBe(false) + await vi.advanceTimersByTimeAsync(1) + + const progress = wrapper.get('progress') + const label = wrapper.get( + `[id="${progress.attributes('aria-labelledby')}"]`, + ) + + expect(progress.attributes('value')).toBeUndefined() + expect(label.text()).toBe('Loading') + expect( + wrapper.find('button, [role="button"], [role="status"]').exists(), + ).toBe(false) + + runtime.setRuntimeState('layoutContentSpinning', false) + await nextTick() + expect(wrapper.find('progress').exists()).toBe(false) + } finally { + wrapper.unmount() + } + }) + + it('cancels delayed feedback when work finishes or the loading host unmounts', async () => { + const wrapper = mount(ContentLoading, { global: { plugins: [pinia] } }) + const runtime = piniaRuntimeStore() + + runtime.setRuntimeState('layoutContentSpinning', true) + await nextTick() + await vi.advanceTimersByTimeAsync(60) + runtime.setRuntimeState('layoutContentSpinning', false) + await nextTick() + await vi.advanceTimersByTimeAsync(120) + expect(wrapper.find('progress').exists()).toBe(false) + + runtime.setRuntimeState('layoutContentSpinning', true) + await nextTick() + expect(vi.getTimerCount()).toBe(1) + wrapper.unmount() + expect(vi.getTimerCount()).toBe(0) + }) + + it('shows immediately during a content remount and clears when it completes', async () => { + const runtime = piniaRuntimeStore() + + runtime.setRuntimeState('globalMainLayoutLoad', false) + const wrapper = mount(ContentLoading, { global: { plugins: [pinia] } }) + + try { + expect(wrapper.find('progress').exists()).toBe(true) + runtime.setRuntimeState('globalMainLayoutLoad', true) + await nextTick() + expect(wrapper.find('progress').exists()).toBe(false) + } finally { + wrapper.unmount() + } + }) +}) diff --git a/__test__/layout/navigation-history.spec.ts b/__test__/layout/navigation-history.spec.ts index bdf29bf5..bff0323b 100644 --- a/__test__/layout/navigation-history.spec.ts +++ b/__test__/layout/navigation-history.spec.ts @@ -47,6 +47,8 @@ it('isolates accounts and restores each account without storing titles or URL pa store.recordVisit('/system/users') store.recordVisit('/search?private=value') + store.recordVisit('/welcome') + store.toggleFavorite('/500') store.toggleFavorite('/system/users') account('two') expect(store.recentPaths).toEqual([]) diff --git a/__test__/layout/preferences.spec.ts b/__test__/layout/preferences.spec.ts index bf704e71..cc57de43 100644 --- a/__test__/layout/preferences.spec.ts +++ b/__test__/layout/preferences.spec.ts @@ -40,6 +40,48 @@ const mountPersistedSettings = () => { } describe('layout preferences', () => { + it.each([ + { title: 'Ray Admin', migrated: '/welcome' }, + { title: 'Custom workspace', migrated: '/dashboard' }, + ])( + 'migrates only the legacy default logo target ($title)', + ({ title, migrated }) => { + localStorage.setItem( + APP_CATCH_KEY.appPiniaSettingStore, + JSON.stringify({ + sideBarLogo: { + icon: 'logo/ray', + title, + url: '/dashboard', + jumpType: 'station', + }, + appRootRoute: { name: 'Old', path: '/old-unregistered-home' }, + }), + ) + const first = mountPersistedSettings() + const store = piniaSettingStore() + + expect(store.sideBarLogo?.url).toBe(migrated) + expect(store.appRootRoute.path).toBe('/old-unregistered-home') + store.updateSettingState('sideBarLogo', { url: '/dashboard' }) + store.$persist() + first.app.unmount() + disposePinia(first.pinia) + const second = mountPersistedSettings() + + try { + expect(piniaSettingStore().sideBarLogo?.url).toBe('/dashboard') + expect( + piniaSettingStore().exportPreferences().preferences, + ).not.toHaveProperty('workspaceLandingMigrated') + } finally { + second.app.unmount() + disposePinia(second.pinia) + localStorage.removeItem(APP_CATCH_KEY.appPiniaSettingStore) + } + }, + ) + it('adds defaults and bounds persisted or programmatic invalid values', () => { expect(normalizeLayoutConfig(null)).toEqual( getDefaultSettingConfig().layoutConfig, diff --git a/__test__/router/config.spec.ts b/__test__/router/config.spec.ts index 46f841e3..e4d77d17 100644 --- a/__test__/router/config.spec.ts +++ b/__test__/router/config.spec.ts @@ -2,6 +2,7 @@ import { appExpandRoutes, getAppRawRoutes, getStaticAppRoutes, + setAppRouteModules, } from '@/router/app-route-modules' import { exportRouteConfig, @@ -153,10 +154,10 @@ describe('route configuration', () => { [{ ...page, path: '/reports', meta: { keepAlive: true } }], /registered component name/i, ], - [ - [{ ...page, path: '/dashboard', meta: { role: ['editor'] } }], - /all authenticated roles/i, - ], + [[{ ...page, path: '/welcome' }], /reserved/i], + [[{ ...page, path: '/reports', alias: '/403' }], /reserved/i], + [[{ ...page, path: '/reports', name: 'ErrorPage500' }], /reserved/i], + [[{ ...page, path: '/404' }], /reserved/i], [ [{ path: '/external', meta: { windowOpen: 'javascript:alert(1)' } }], /windowOpen/, @@ -188,6 +189,27 @@ describe('route configuration', () => { expect(() => parse(routes)).toThrow(message) }) + it('allows restricted dashboard pages and does not inject one into custom sources', () => { + expect( + parse([{ ...page, path: '/dashboard', meta: { role: ['editor'] } }]) + .routes, + ).toHaveLength(1) + + try { + setAppRouteModules( + toRuntimeRoutes(parse([{ ...page, path: '/reports' }])), + ) + expect(appExpandRoutes().some(({ path }) => path === '/dashboard')).toBe( + false, + ) + expect(appExpandRoutes().some(({ path }) => path === '/reports')).toBe( + true, + ) + } finally { + setAppRouteModules(getStaticAppRoutes()) + } + }) + it('sorts missing order consistently and leaves the input in place', () => { const first = { path: '/first', name: 'A', meta: {} } const second = { path: '/second', name: 'B', meta: { order: 0 } } diff --git a/__test__/router/initialization.spec.ts b/__test__/router/initialization.spec.ts new file mode 100644 index 00000000..778cbc06 --- /dev/null +++ b/__test__/router/initialization.spec.ts @@ -0,0 +1,43 @@ +import type { App } from 'vue' +import { router, setupRouter } from '../../apps/admin/src/router' + +const { load, register } = vi.hoisted(() => ({ + load: vi.fn(), + register: vi.fn(), +})) + +vi.mock('../../apps/admin/src/router/config/source', () => ({ + loadRouteConfig: load, +})) +vi.mock('../../apps/admin/src/router/routes', () => ({ + constantRoutes: [{ path: '/', component: { render: () => null } }], + getLayoutRoutes: () => [], +})) +vi.mock('../../apps/admin/src/router/app-route-modules', () => ({ + setAppRouteModules: vi.fn(), +})) +vi.mock('../../apps/admin/src/router/utils', () => ({ + scrollViewToTop: vi.fn(), + vueRouterRegister: register, +})) + +it('retries failed initialization on remount and shares the successful retry', async () => { + const app = { use: vi.fn() } as unknown as App + + load + .mockRejectedValueOnce(new Error('route endpoint unavailable')) + .mockResolvedValue(void 0) + + try { + await expect(setupRouter(app)).rejects.toThrow('route endpoint unavailable') + expect(register).not.toHaveBeenCalled() + await Promise.all([setupRouter(app), setupRouter(app)]) + expect(load).toHaveBeenCalledTimes(2) + expect(register).toHaveBeenCalledOnce() + await setupRouter(app) + expect(load).toHaveBeenCalledTimes(2) + expect(register).toHaveBeenCalledOnce() + } finally { + router.options.history.destroy() + } +}) diff --git a/__test__/router/permission.spec.ts b/__test__/router/permission.spec.ts index d6b5bb98..a1823fd6 100644 --- a/__test__/router/permission.spec.ts +++ b/__test__/router/permission.spec.ts @@ -1,11 +1,9 @@ import { createMemoryHistory, createRouter } from 'vue-router' import { APP_CATCH_KEY } from '../../apps/admin/src/app-config' import { permissionRouter } from '../../apps/admin/src/router/utils/permission' +import { resolveLandingPath } from '../../apps/admin/src/router/utils/resolve-landing-path' import { setStorage } from '../../apps/admin/src/utils/cache' -vi.mock('../../apps/admin/src/hooks', () => ({ - useAppRoot: () => ({ getRootPath: { value: '/dashboard' } }), -})) vi.mock('../../apps/admin/src/router/utils/valid-role', () => ({ validRole: (meta: { role?: string[] }) => !meta.role?.length || meta.role.includes('admin'), @@ -17,9 +15,14 @@ function setupRouter(rootRole?: string[]) { history: createMemoryHistory(), routes: [ { path: '/', name: 'RLogin', component }, + { path: '/welcome', name: 'RWelcome', component }, + { path: '/403', name: 'ErrorPage403', component }, + { path: '/404', name: 'ErrorPage404', component }, + { path: '/500', name: 'ErrorPage500', component }, { path: '/dashboard', component, meta: { role: rootRole } }, { path: '/allowed', component, meta: { role: ['admin'] } }, { path: '/denied', component, meta: { role: ['editor'] } }, + { path: '/legacy', redirect: '/allowed' }, { path: '/docs', name: 'RayTemplateDoc', @@ -48,13 +51,13 @@ describe('Router 5 permission guard', () => { expect(router.currentRoute.value.path).toBe('/') }) - it('redirects authenticated login to the configured home', async () => { + it('opens the neutral workspace after login without choosing a business home', async () => { setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') const router = setupRouter() await router.push('/') - expect(router.currentRoute.value.path).toBe('/dashboard') + expect(router.currentRoute.value.path).toBe('/welcome') }) it('allows permitted roles and authenticated whitelist routes', async () => { @@ -70,22 +73,85 @@ describe('Router 5 permission guard', () => { expect(router.currentRoute.value.path).toBe('/docs') }) - it('redirects a denied role to home', async () => { + it('shows forbidden state for a denied direct link', async () => { setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') const router = setupRouter() await router.push('/denied') - expect(router.currentRoute.value.path).toBe('/dashboard') + expect(router.currentRoute.value.path).toBe('/403') + expect(router.currentRoute.value.query.from).toBe('/denied') }) - it('cancels when home itself is denied instead of redirecting forever', async () => { + it('does not depend on the legacy dashboard being permitted', async () => { const router = setupRouter(['editor']) await router.push('/') setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') await router.push('/denied') - expect(router.currentRoute.value.path).toBe('/') + expect(router.currentRoute.value.path).toBe('/403') + }) + + it('retains an authorized requested URL through login with query and hash intact', async () => { + const router = setupRouter() + + await router.push('/allowed?filter=open#row-2') + expect(router.currentRoute.value.query.redirect).toBe( + '/allowed?filter=open#row-2', + ) + setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') + await router.replace( + resolveLandingPath(router, router.currentRoute.value.query.redirect), + ) + expect(router.currentRoute.value.fullPath).toBe( + '/allowed?filter=open#row-2', + ) + }) + + it('preserves query and hash when an authenticated login URL supplies a valid redirect', async () => { + setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') + const router = setupRouter() + + await router.push({ + path: '/', + query: { redirect: '/allowed?filter=open#row-2' }, + }) + expect(router.currentRoute.value.fullPath).toBe( + '/allowed?filter=open#row-2', + ) + }) + + it.each([ + '/denied', + '/missing', + '//example.com', + 'https://example.com', + '/500', + '/\\example.com', + ])( + 'does not restore unsafe, inaccessible or status target %s', + async (redirect) => { + setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') + const router = setupRouter() + + await router.push({ path: '/', query: { redirect } }) + expect(router.currentRoute.value.path).toBe('/welcome') + }, + ) + + it('validates redirect destinations while preserving their original requested URL', () => { + expect(resolveLandingPath(setupRouter(), '/legacy?filter=open#row')).toBe( + '/legacy?filter=open#row', + ) + }) + + it('shows not found for an unknown authenticated route', async () => { + setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage') + const router = setupRouter() + + await router.push('/missing?from=test') + expect(router.currentRoute.value.path).toBe('/404') + expect(router.currentRoute.value.query.from).toBe('/missing?from=test') }) }) diff --git a/__test__/router/workspace-errors.spec.ts b/__test__/router/workspace-errors.spec.ts new file mode 100644 index 00000000..80b62512 --- /dev/null +++ b/__test__/router/workspace-errors.spec.ts @@ -0,0 +1,110 @@ +import { setupRouterErrors } from '@/router/utils/setup-router-errors' +import { flushPromises } from '@vue/test-utils' +import { createMemoryHistory, createRouter } from 'vue-router' + +it('routes a failed page import to 500 with its original recovery target', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/welcome', component: { render: () => null } }, + { path: '/500', component: { render: () => null } }, + { + path: '/reports', + component: () => Promise.reject(new Error('chunk unavailable')), + }, + ], + }) + + setupRouterErrors(router) + + try { + await router.push('/welcome') + await expect(router.push('/reports?range=week#chart')).rejects.toThrow( + 'chunk unavailable', + ) + await flushPromises() + expect(router.currentRoute.value.path).toBe('/500') + expect(router.currentRoute.value.query.from).toBe( + '/reports?range=week#chart', + ) + } finally { + router.options.history.destroy() + consoleError.mockRestore() + } +}) + +it('does not retry recursively when the 500 page itself cannot load', async () => { + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + const loader = vi.fn(() => Promise.reject(new Error('status unavailable'))) + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/welcome', component: { render: () => null } }, + { path: '/500', component: loader }, + ], + }) + + setupRouterErrors(router) + + try { + await router.push('/welcome') + await expect(router.push('/500')).rejects.toThrow('status unavailable') + await flushPromises() + expect(loader).toHaveBeenCalledOnce() + expect(router.currentRoute.value.path).toBe('/welcome') + } finally { + router.options.history.destroy() + consoleError.mockRestore() + } +}) + +it.each(['succeeded', 'pending', 'duplicated'] as const)( + 'ignores an older failed import when a newer navigation is %s', + async (newer) => { + const stale = Promise.withResolvers<{ render: () => null }>() + const next = Promise.withResolvers<{ render: () => null }>() + const component = { render: () => null } + const router = createRouter({ + history: createMemoryHistory(), + routes: [ + { path: '/welcome', component }, + { path: '/500', component }, + { path: '/slow', component: () => stale.promise }, + { + path: '/ready', + component: newer === 'pending' ? () => next.promise : component, + }, + ], + }) + + setupRouterErrors(router) + + try { + await router.push('/welcome') + const oldNavigation = router + .push('/slow') + .catch((error: unknown) => error) + + await flushPromises() + const newNavigation = router.push( + newer === 'duplicated' ? '/welcome' : '/ready', + ) + + await flushPromises() + stale.reject(new Error('obsolete chunk')) + await oldNavigation + await flushPromises() + expect(router.currentRoute.value.path).toBe( + newer === 'succeeded' ? '/ready' : '/welcome', + ) + next.resolve(component) + await newNavigation + expect(router.currentRoute.value.path).toBe( + newer === 'duplicated' ? '/welcome' : '/ready', + ) + } finally { + router.options.history.destroy() + } + }, +) diff --git a/apps/admin/index.html b/apps/admin/index.html index 6d0a3826..8fceb775 100644 --- a/apps/admin/index.html +++ b/apps/admin/index.html @@ -8,11 +8,39 @@ + + diff --git a/apps/docs/guide/appearance.md b/apps/docs/guide/appearance.md index 4b0786fc..8b177a94 100644 --- a/apps/docs/guide/appearance.md +++ b/apps/docs/guide/appearance.md @@ -15,13 +15,126 @@ ### 样式放在哪里 -- Naive UI 组件的颜色、圆角、密度和阴影走 [`theme-overrides`](https://www.naiveui.com/zh-CN/docs/customize-theme)。四套预设定义在 `packages/ui/src/theme-presets.ts`。每次用当前风格、明暗模式和用户主色计算配置,页面与离散消息、通知和弹窗共享同一份配置。 +- Naive UI 组件的颜色、圆角、密度和阴影走 [`theme-overrides`](https://github.com/tusen-ai/naive-ui/blob/main/demo/pages/docs/customize-theme/enUS/index.md)。四套预设定义在 `packages/ui/src/theme-presets.ts`,后台现代化风格的应用级配置入口是 `APP_THEME.appNaiveUIThemeOverrides`。每次用当前风格、明暗模式和用户主色计算配置,页面与离散消息、通知和弹窗共享同一份配置。 - 自有导航、标签页和工作区使用 `packages/ui/src/theme.css` 的 `--r-*` 语义变量。后台把 `useThemeVars()` 解析出的值映射到根节点,文档示例把相同映射限制在示例容器。自有元素使用这套变量,以便和组件库一起换肤。 +- 自有卡片和控件分别使用 `--r-radius`、`--r-control-radius`;页面说明文字保留正文级可读性,不直接继承对比度偏低的弱文本色。页面阴影只采用预设显式配置的柔和阴影,Naive UI 浮层继续使用原生样式。 - 全局 Sass 保留 reset、工具和历史表单宽度约定。组件 SCSS 负责布局、滚动和交互;仅在组件库没有合适 API 时,用自有类限定内部结构选择器的范围。不要在全局选择器中给 `.n-*` 写配色或直接依赖 `--n-*` 来切换主题。 -- 首屏启动样式内联于 `apps/admin/index.html`,用于应用挂载前显示品牌、启动状态和明暗模式。图表配色仍由 ECharts 主题和页面 options 管理。 +- 首屏启动样式内联于 `apps/admin/index.html`,在应用挂载前显示品牌和细线加载状态,并读取已保存的界面风格与明暗模式。加载完成即进入应用;启动失败保留中英文提示与重试按钮。系统启用减少动态效果时,入场动画关闭,进度线减速。图表配色仍由 ECharts 主题和页面 options 管理。 全局 Sass 辅助文件通过 `vite.custom.config.ts` 注入;CSS Modules 的名称以 camelCase 暴露。 +## 自定义 CSS:沿用动态配置 {#custom-css} + +后台页面已经由 `AppNaiveGlobalProvider` 提供组件主题,`AppStyleProvider` 将解析后的颜色和尺寸映射到 ``。新增页面直接使用语义变量即可跟随四种风格、明暗模式和自定义主色;不需要再写一组监听器或在每次渲染时读取计算样式。 + +变量的唯一实现来源是 [`theme.css`](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/theme.css) 和 [`createRayThemeStyle`](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/theme-presets.ts)。下表说明用途,不复制整套色值。 + +| 用途 | 变量 | +| ---------------------------------- | --------------------------------------------------------------------- | +| 页面底色、卡片、次级表面、悬停表面 | `--r-canvas`、`--r-surface`、`--r-surface-muted`、`--r-surface-hover` | +| 正文、说明、弱化文字 | `--r-text`、`--r-text-secondary`、`--r-text-muted` | +| 结构分隔线、可识别的控件边框 | `--r-line`、`--r-control-border` | +| 主色、主色悬停值 | `--r-theme-primary-color`、`--r-theme-primary-fade-color` | +| 可读的强调文字、选中文字 | `--r-primary-text`、`--r-selected-text` | +| 卡片圆角、普通控件圆角、柔和阴影 | `--r-radius`、`--r-control-radius`、`--r-shadow-soft` | +| 缓动曲线、等宽字体 | `--r-bezier`、`--r-font-mono` | + +`fade-color` 是历史命名,实际映射主色悬停值,不保证透明。暗色下的强调/选中文字会使用更稳妥的文字色,不保证与用户选择的主色相同。`--r-radius` 优先取 Card 圆角,`--r-control-radius` 取 common 圆角;Material 胶囊按钮等组件专属形状仍交给 Naive UI。未显式配置页面阴影时为 `none`,不会把组件库浮层阴影强加给普通卡片。 + +### 自有结构的写法 + +普通卡片优先使用 `NCard`。确实需要自有结构时,可按下面的 SFC 组织 CSS;标题、说明和按钮文案由调用方传入,便于沿用页面国际化。 + +```vue + + + + + +``` + +TSX 使用相同的 class 和 CSS,样式放在组件旁并从入口 `import './index.scss'`。不要把四种风格各复制一遍选择器;语义变量会沿 DOM 继承。需要自己的间距配置时,在组件边界定义局部变量或 props,避免虚构未提供的全局间距 token。 + +### 在独立项目中使用共享组件 + +独立宿主需要同时提供三个部分:Naive `NConfigProvider`、CSS 变量作用域,以及按需提供的 `provideUiServices` 行为服务。只调用 `provideUiServices` 不会安装主题或写入 CSS。下面的例子只使用包的公开导出,已纳入文档示例类型检查;保存为自己的 `ThemeScope.vue` 后,将业务内容放进插槽。 + +::: details 独立宿主完整示例 +<<< @/examples/ThemeScopeExample.vue +::: + +传入 `theme-style="material"`、`:dark="true"` 即可选择风格和模式。`commonOverrides` 供宿主合并自定义主色;完整交互配色应一起设置 `primaryColor`、`primaryColorHover`、`primaryColorPressed` 和 `primaryColorSuppl`。后台页面则继续使用现有 `useSettingActions().changePrimaryColor()`,不必重复建立宿主。来自存储或 JSON 的风格值先通过 `normalizeThemeStyle()` 处理。 + +示例将导出的 Naive light/dark common 与同一份覆盖配置合并后映射,避免在当前组件中读取尚未成为祖先的 `NConfigProvider`。如果使用 `useThemeVars()`,应把读取逻辑放进 provider 的后代组件。需要翻译、图标地址或其他宿主能力时,补充自己的 `UiServices`;不要在已有后台页面里再提供一份不完整服务,从而遮蔽应用服务。 + +局部主题容器需要同时具有 `.r-theme-scope`、明暗 class 和映射样式。只在子元素改写 `--r-token-*`,却继承祖先已经求值的别名,可能仍读到祖先配色;这属于 [CSS 自定义属性的继承规则](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Cascading_variables/Using_custom_properties)。Vue `Teleport` 保留组件注入关系,但不会保留原来的 DOM 样式继承;自有弹出内容应传送到作用域内部,或为目标容器建立同一主题。 + +仅加载 `theme.css` 而没有映射 provider 时,变量会退回 `Canvas`、`CanvasText`、`Highlight`、`ButtonBorder` 等系统颜色、4px 圆角和无阴影。这不是自动选择某套风格;Naive 组件也会使用自己的默认主题。若连共享样式都没有加载,则需要导入样式或像上例一样提供明确的 `var()` 回退。局部变量映射不会改写整页,但共享样式本身还包含根节点 `color-scheme` 和通用焦点规则。 + +### 尺寸、滚动与动效 + +- 内容区的实时配置由 `AdminShell` 提供:`--layout-content-padding` 是配置值,`--layout-content-gutter` 是含窄屏调整的实际留白,`--layout-content-max-width` 由布局负责应用,`--layout-content-height` 是扣除实测头部、标签栏和页脚后的高度预算。`setting.scss` 的 Sass 变量是编译期值,不会响应偏好设置。 +- 普通页面使用自然高度。确需内部滚动的工作区可使用 `calc(var(--layout-content-height, 100dvh) - 2 * var(--layout-content-gutter, 16px))`,再通过 Flex/Grid、`min-block-size: 0` 和明确的滚动容器分配空间。独立组件优先由父容器给出高度。 +- 使用 `minmax(0, 1fr)`、`min-inline-size: 0` 和逻辑方向属性。组件布局优先根据可用内容宽度调整;容器查询应有祖先 `container-type: inline-size`,断点写成明确尺寸,不能在查询条件中使用 `var()`。 +- 配色、圆角、阴影优先取语义变量;局部间距、图标光学尺寸、断点以及有明确用途的品牌/数据配色可以使用固定值。通用 SVG 使用 `currentColor`,Canvas 图表仍通过图表主题或 options 配色。 +- 动效优先改变 `opacity` / `transform`,在对应组件中处理 `prefers-reduced-motion`。保留键盘焦点和强制颜色模式下的边框/轮廓,不用全局极短动画时长替代适配。 + +修改 Naive 控件优先用 props、插槽或 `themeOverrides`;必要的内部选择器必须限定在自己的组件 class 下。检查实际受影响的风格、明暗模式和窄屏,不必为纯文档修改重跑整站视觉矩阵。 + ## 中英文同时维护 把页面文案放进 `apps/admin/src/locales/lang/zh-CN` 和 `apps/admin/src/locales/lang/en-US` 的对应 JSON;同一语言内的命名空间要唯一。新增语言时同时补 `apps/admin/src/locales/lang/.ts` 与应用的语言配置。 diff --git a/apps/docs/guide/routing.md b/apps/docs/guide/routing.md index c3f4da60..733d0eac 100644 --- a/apps/docs/guide/routing.md +++ b/apps/docs/guide/routing.md @@ -40,7 +40,19 @@ import RouteConfigDemo from '../examples/RouteConfigDemo.vue' ## 登录和角色 -默认登录页为 `/`。守卫启用时,无会话会返回登录页;有会话时按白名单、角色和应用首页决定导航。菜单隐藏的页面仍可能允许直达。接入真实业务时,在后端校验会话、权限和资源归属。 +默认登录页为 `/`。无会话访问业务地址时,守卫将完整地址放入登录页的 `redirect` 参数;登录后仅恢复当前角色仍有权限的已注册业务地址,保留 query 和 hash。没有有效目标时进入 `/welcome`,不会自动选择仪表盘或第一个菜单。菜单隐藏的页面仍可能允许直达。接入真实业务时,在后端校验会话、权限和资源归属。 + +## 空工作区和状态页 + +`/welcome` 表示当前没有活动业务路由,展示可访问的入口。它与 `/403`、`/404`、`/500` 一样属于外壳状态页,不进入业务菜单、标签、访问历史或页面缓存。四个路径及其子路径、别名和对应名称保留给外壳,不能被本机或远端 JSON 覆盖。自定义来源无需提供 `/dashboard`,仪表盘存在时也可以设置角色权限。 + +所有业务标签都可以关闭,包括原首页和最后一项。关闭当前标签后切换到相邻项;关闭最后一项或全部标签进入空工作区,同时释放对应 KeepAlive 缓存。一个具体 pathname 保留一个标签,查询参数或片段变化会更新标签保存的完整地址。角色变化后,失去权限的标签与缓存会被移除,不会自动激活其他业务页。 + +- `/403`:已登录,但当前页面无权限。 +- `/404`:目标页面不存在;原始目标保留在 `query.from`。 +- `/500`:路由解析或页面懒加载失败;只对仍存在且允许访问的 `query.from` 显示重试。 + +状态页始终提供返回工作区的操作;“上一页”和“重试”会先验证站内地址和权限,不直接信任历史记录或查询参数。`useAppRoot` 与旧 `appRootRoute` 偏好仅保留兼容读写,已不影响上述行为,也不再进行启动时首页校验。 ## KeepAlive 排查 diff --git a/apps/docs/reference/components.md b/apps/docs/reference/components.md index c97634af..e915c729 100644 --- a/apps/docs/reference/components.md +++ b/apps/docs/reference/components.md @@ -2,21 +2,21 @@ 通用组件从 `@ray-template/ui` 导入,也可用 `/table-pro`、`/barcode` 等子路径按需加载。Ray Admin 内可以使用 `@/components`。路由过渡位于 `@ray-template/admin-shell`,由应用接入当前路由和缓存状态。许多组件包装 Naive UI:本文列出模板添加、改写或消费的属性、插槽和事件,原始控件的其余能力以锁定依赖的类型为准。 -| 组件 | Props 类型 | 主要用途 | -| ----------------------------------------------------- | ----------------------------- | ------------------------------------------ | -| [RTablePro](./table-pro) | `TableProProps` | 纯表格、远端查询、自适应高度、列设置、打印 | -| [RForm](./components/form) | `FormProps` | 表单加载、校验、重置和键盘提交 | -| [RModal](./components/modal) | `ModalProps` | 受控弹窗、预设宽度和全屏卡片 | -| [RChart](./components/chart) | `ChartProps` | ECharts 初始化、主题和导出 | -| [RFlow](./components/flow) | `FlowProps` | LogicFlow 流程图与只读切换 | -| [RCollapseGrid](./components/collapse-grid) | `CollapseGridProps` | 可折叠筛选区及操作列 | -| [RSegment](./components/segment) | `SegmentProps` | 分段选项、图标和提示 | -| [RMoreDropdown](./components/more-dropdown) | `MoreDropdownProps` | 图标菜单、行操作 | -| [RIframe](./components/iframe) | `IframeProps` | 外部页面与加载状态 | -| [RBarcode](./components/barcode) | `BarcodeProps` | Canvas / SVG 条码 | -| [RDraggableCard](./components/draggable-card) | `DefaultPosition`(位置类型) | 可拖动卡片与拖动边界 | -| [RTransitionComponent](./components/route-transition) | `TransitionComponentProps` | 路由过渡与 KeepAlive | -| [RIcon](./icons#ricon-api) | `IconProps` | 类型化 SVG 雪碧图 | +| 组件 | Props 类型 | 主要用途 | +| ----------------------------------------------------- | ----------------------------- | ---------------------------------------------------- | +| [RTablePro](./table-pro) | `TableProProps` | 纯表格、远端查询、自适应高度、列设置、导出及可选打印 | +| [RForm](./components/form) | `FormProps` | 表单加载、校验、重置和键盘提交 | +| [RModal](./components/modal) | `ModalProps` | 受控弹窗、预设宽度和全屏卡片 | +| [RChart](./components/chart) | `ChartProps` | ECharts 初始化、主题和导出 | +| [RFlow](./components/flow) | `FlowProps` | LogicFlow 流程图与只读切换 | +| [RCollapseGrid](./components/collapse-grid) | `CollapseGridProps` | 可折叠筛选区及操作列 | +| [RSegment](./components/segment) | `SegmentProps` | 分段选项、图标和提示 | +| [RMoreDropdown](./components/more-dropdown) | `MoreDropdownProps` | 图标菜单、行操作 | +| [RIframe](./components/iframe) | `IframeProps` | 外部页面与加载状态 | +| [RBarcode](./components/barcode) | `BarcodeProps` | Canvas / SVG 条码 | +| [RDraggableCard](./components/draggable-card) | `DefaultPosition`(位置类型) | 可拖动卡片与拖动边界 | +| [RTransitionComponent](./components/route-transition) | `TransitionComponentProps` | 路由过渡与 KeepAlive | +| [RIcon](./icons#ricon-api) | `IconProps` | 类型化 SVG 雪碧图 | [应用组件与 Provider](./components/app) 使用模板的状态、主题或路由,按文件导入。[二维码](./components/qr-code) 使用 `vue3-next-qrcode`,不属于 `@/components` 的导出。 diff --git a/apps/docs/reference/components/barcode.md b/apps/docs/reference/components/barcode.md index ac5ddb9c..09361109 100644 --- a/apps/docs/reference/components/barcode.md +++ b/apps/docs/reference/components/barcode.md @@ -34,16 +34,16 @@ export const renderOrderBarcode = (orderNo: string) => ( ) ``` -| 属性 | 默认 | 说明 | -| ------------------ | ----------- | --------------------------------------------------------------------------------------------------------- | -| `text` | 无 | 条码文本。留空或传入不符合格式的值时可能渲染失败。 | -| `format` | `'CODE128'` | 条码制式,覆盖 `options.format`。 | -| `barcodeRender` | `'canvas'` | `canvas` 或 `svg`。 | -| `options` | `{}` | JsBarcode options,如 `displayValue`、`lineColor`、`margin`、条宽和条高。 | -| `width` / `height` | `'auto'` | 显示尺寸,数字按像素。与 `options` 中条码自身的条宽、条高不同。 | -| `responsive` | `false` | 监听容器尺寸;用 `width="responsive"` 或 `height="responsive"` 让对应尺寸随容器调整。 | -| `watchText` | `true` | 文本变化时重绘。独立改变 `format`、`options` 或渲染介质时不要依赖文本 watcher,可以按配置更换组件 `key`。 | -| `loading` | `false` | 控制 Spin;调用方负责开关。 | +| 属性 | 默认 | 说明 | +| ------------------ | ----------- | ----------------------------------------------------------------------------------------------------------- | +| `text` | 无 | 条码文本。留空或传入不符合格式的值时可能渲染失败。 | +| `format` | `'CODE128'` | 条码制式,覆盖 `options.format`。 | +| `barcodeRender` | `'canvas'` | `canvas` 或 `svg`。 | +| `options` | `{}` | JsBarcode options,如 `displayValue`、`lineColor`、`margin`、条宽和条高。 | +| `width` / `height` | `'auto'` | 显示尺寸,数字按像素。与 `options` 中条码自身的条宽、条高不同。 | +| `responsive` | `false` | 监听容器尺寸;用 `width="responsive"` 或 `height="responsive"` 让对应尺寸随容器调整。 | +| `watchText` | `true` | 文本变化时重绘。`format`、`options`(包括响应式嵌套字段)、尺寸和渲染介质变化也会自动重绘,无需更换 `key`。 | +| `loading` | `false` | 控制 Spin;调用方负责开关。 | `onSuccess(text, format, options)`、`onError(error)`、`onFinally()` 支持函数或回调数组。成功回调收到原始 options;组件响应式调整的条宽和条高不写回该对象。绘制异常通过 `onError` 通知,业务代码可据此提示或清理旧预览。 diff --git a/apps/docs/reference/components/chart.md b/apps/docs/reference/components/chart.md index 0f1c1c36..4a1eee76 100644 --- a/apps/docs/reference/components/chart.md +++ b/apps/docs/reference/components/chart.md @@ -57,6 +57,10 @@ export default defineComponent({ 默认使用 `ray-modern`、`ray-naive`、`ray-material` 或 `ray-plain`,各有 `-dark` 变体。`theme="default"` 使用 ECharts 内建主题,`autoChangeTheme=true` 时随应用明暗变化;显式指定其他注册名时固定使用该主题。设置 `autoChangeTheme=false` 可禁用自动选择暗色变体。旧版 `macarons` 与 `macarons-dark` 已移除。 +八套主题的画布、文本、图例、坐标轴、提示层和数据配色成组设计,并与对应风格的卡片表面对齐。现代化使用冷色系,Naive 以绿色起始,Material 使用紫色与柔和色组,朴素使用低饱和分类色;切换应用主色不会单独改写数据色。页面 `options` 的显式样式仍优先于主题。 + +默认加载层使用当前图表配色。自定义主题的透明或无效背景会回退到相应明暗表面色,避免透明背景被转换为黑色遮罩;可通过 `loadingOptions` 显式覆盖遮罩、文字或旋转图标。 + 切换主题会调用 ECharts 6 的 `setTheme`,保留实例和事件监听。ECharts 会重建内部选项模型,图例选择、缩放和通过合并模式写入的增量配置可能被重置。需要保留这些值时,将它们作为完整 `options` 提供。 ## 卡片预设和回调 diff --git a/apps/docs/reference/components/collapse-grid.md b/apps/docs/reference/components/collapse-grid.md index ff549443..40a72f81 100644 --- a/apps/docs/reference/components/collapse-grid.md +++ b/apps/docs/reference/components/collapse-grid.md @@ -4,7 +4,7 @@ import CollapseGridDemo from '../../examples/CollapseGridDemo.vue' -适合有多个条件的搜索表单。底层用 `NGrid` 渲染,子项必须是 `NGridItem`。使用 `cols`、`responsive`、`collapsedRows`、`xGap` 和 `yGap` 配置网格;未指定间距或传 `0` 时当前实现回退到 12。 +适合有多个条件的搜索表单。底层用 `NGrid` 渲染,子项必须是 `NGridItem`。使用 `cols`、`responsive`、`collapsedRows`、`xGap` 和 `yGap` 配置网格;未指定间距时回退到 12,传 `0` 保留零间距。 ## 交互示例 @@ -26,8 +26,8 @@ import CollapseGridDemo from '../../examples/CollapseGridDemo.vue' `default` 渲染筛选项,`action` 渲染查询按钮,`collapse(collapsed)` 可替换展开按钮。自定义折叠插槽只收到布尔值,需要自行绑定按钮并修改 `open`。 -::: warning 受控状态与更新事件 -`onUpdateOpen` 和 `onUpdate:open` 回传的是内部 `collapsed`,与 `open` 相反。当前基线使用受控模式时手动取反,避免直接双向绑定把语义接反。两个监听器同时绑定会各调用一次。 +::: tip 受控状态与更新事件 +`onUpdateOpen` 和 `onUpdate:open` 回传展开状态,可直接绑定 `v-model:open`。旧版接入中为修正事件反向而添加的取反处理应删除。两个监听器同时绑定会各调用一次。默认切换按钮支持键盘,并通过 `aria-expanded` 表示当前状态。 ::: ```tsx @@ -43,8 +43,8 @@ export default defineComponent({ open={open.value} cols={3} collapsedRows={1} - onUpdateOpen={(collapsed) => { - open.value = !collapsed + onUpdateOpen={(value) => { + open.value = value }} > {{ diff --git a/apps/docs/reference/components/draggable-card.md b/apps/docs/reference/components/draggable-card.md index fdcde6d1..a5398113 100644 --- a/apps/docs/reference/components/draggable-card.md +++ b/apps/docs/reference/components/draggable-card.md @@ -16,7 +16,7 @@ import AdminExample from '../../examples/AdminExample.vue' | `width` / `zIndex` | `600` / 无 | 卡片宽度与层级。 | | `animation` | `false` | 启用进场过渡。 | -位置可用 `top-left`、`top-right`、`bottom-left`、`bottom-right`、`center`、`top-center`、`bottom-center`。替换 `defaultPosition` 引用会触发重定位;没有公开拖拽事件或位置持久化。选择器需要在布局中真实存在,容器应有明确尺寸。组件初始化会访问 `document`,仅在浏览器侧渲染。继承 Card 属性和插槽。 +位置可用 `top-left`、`top-right`、`bottom-left`、`bottom-right`、`center`、`top-center`、`bottom-center`。替换 `defaultPosition`、`padding` 或边界引用会触发重定位,开关 `dad` 保留当前位置;没有公开拖拽事件或位置持久化。选择器需要在布局中真实存在,容器应有明确尺寸。服务端不创建拖拽 DOM;浏览器挂载后建立交互,关闭拖拽或卸载时释放监听器,最后一个卡片卸载后移除共享容器。继承 Card 属性和插槽,进场动画尊重减少动态效果设置。 ## 交互示例 diff --git a/apps/docs/reference/components/flow.md b/apps/docs/reference/components/flow.md index e3854016..97fe59a1 100644 --- a/apps/docs/reference/components/flow.md +++ b/apps/docs/reference/components/flow.md @@ -45,15 +45,15 @@ export default defineComponent({ }) ``` -| 属性 | 默认 | 说明 | -| ---------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------- | -| `width` / `height` | `'100%'` | 容器尺寸,需要可计算的高度。 | -| `data` | 无 | 后续引用变化时重绘,嵌套原地修改不触发。当前挂载分支先渲染空图,首屏请在 `onRegister` 里主动渲染。 | -| `watchData` | `true` | 是否监听传入数据。关闭后可从实例控制重绘。 | -| `readonly` | `false` | 同步 LogicFlow 静默模式和节点、边文本编辑状态。 | -| `options` | 网格开、`partial: false`、键盘开 | LogicFlow 初始化配置,包括尺寸、背景、键盘、边、交互、历史和插件等。`container` 由组件管理。 | -| `use` | 无 | LogicFlow 全局插件列表,组件只在首次初始化时注册一次。需要实例级插件时检查 `options.plugins`。 | -| `onRegister(instance)` | 无 | 挂载后取得 LogicFlow,支持回调数组。 | +| 属性 | 默认 | 说明 | +| ---------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `width` / `height` | `'100%'` | 容器尺寸,需要可计算的高度。 | +| `data` | 无 | 首次挂载和后续引用变化时渲染,清空为 `undefined` 时恢复空图;嵌套原地修改不触发。 | +| `watchData` | `true` | 是否监听传入数据。关闭后可从实例控制重绘。 | +| `readonly` | `false` | 启用 LogicFlow 静默模式;退出时恢复进入前的交互和键盘配置,不会强行打开调用方禁用的能力。 | +| `options` | 网格开、`partial: false`、键盘开 | LogicFlow 初始化配置,包括尺寸、背景、键盘、边、交互、历史和插件等。`container` 由组件管理。 | +| `use` | 无 | 每个组件初始化前注册自己的 LogicFlow 全局插件列表,由库按名称去重。实例级插件可用 `options.plugins`。 | +| `onRegister(instance)` | 无 | 挂载后取得 LogicFlow,支持回调数组。 | `FlowOptions` 支持的字段按用途分组: @@ -64,6 +64,6 @@ export default defineComponent({ `FlowGraphData` 用于包装组件的 Props。直接调用底层 `instance.render` 时,使用 `Parameters[0]` 保留 LogicFlow 所要求的节点类型、坐标和连线字段。 -`useFlow()` 返回 `[register, { getFlowInstance }]`。若首屏要填图,可在同一 `onRegister` 回调里先调用 `register(instance)` 再 `instance.render(graph)`。注册之前调用 `getFlowInstance()` 会抛错。程序化编辑、导入和事件监听走 LogicFlow 实例;组件目前没有公开销毁方法或卸载时的显式实例清理,频繁重挂载或绑定自定义监听时,请由接入方处理对应资源释放。 +`useFlow()` 返回 `[register, { getFlowInstance }]`,将 `register` 传给 `onRegister`。首次图数据可直接通过 `data` 提供;注册之前或组件卸载后调用 `getFlowInstance()` 会抛错。组件卸载时销毁 LogicFlow 实例;程序化编辑、导入和事件监听走该实例,接入方仍需清理自己创建的外部资源。 [组件实现](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RFlow/src/Flow.tsx) · [图和选项类型](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RFlow/src/types.ts) · [实例 Hook](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RFlow/src/hooks/useFlow.ts) diff --git a/apps/docs/reference/components/form.md b/apps/docs/reference/components/form.md index 15c1cea1..47934619 100644 --- a/apps/docs/reference/components/form.md +++ b/apps/docs/reference/components/form.md @@ -61,18 +61,18 @@ export default defineComponent({ ## 属性与事件 -除 `onSubmit` 外,继承 `NForm` 的公开属性。默认插槽传给 `NForm`。 +继承 `NForm` 的公开属性和 `onSubmit` 事件,默认插槽传给 `NForm`。 -| 属性 | 默认 | 说明 | -| -------------------- | ------- | ---------------------------------------------------------------------- | -| `loading` | `false` | 外层 Spin 状态,由调用方开关。 | -| `loadingDescription` | 无 | 加载说明。 | -| `autocomplete` | `'off'` | 挂载时写到表单 DOM。 | -| `submitWhenEnter` | `false` | 创建时启用 Enter 捕获,阻止默认行为,校验成功后调用 `onFinish`。 | -| `onFinish` | 无 | Enter 校验完成回调。自定义提交按钮要自行调用 `validate()` 并执行提交。 | -| `onRegister(inst)` | 无 | 挂载后传出 Naive UI Form 实例。接受单函数或回调数组。 | +| 属性 | 默认 | 说明 | +| -------------------- | ------- | -------------------------------------------------------------------------------------------------- | +| `loading` | `false` | 外层 Spin 状态,由调用方开关。 | +| `loadingDescription` | 无 | 加载说明。 | +| `autocomplete` | `'off'` | 挂载时写到表单 DOM。 | +| `submitWhenEnter` | `false` | 可动态启用单行输入的 Enter 提交;校验成功后调用 `onFinish`,加载中或上次提交未结束时忽略重复提交。 | +| `onFinish` | 无 | Enter 校验完成回调。自定义提交按钮要自行调用 `validate()` 并执行提交。 | +| `onRegister(inst)` | 无 | 挂载后传出 Naive UI Form 实例。接受单函数或回调数组。 | -含多行输入、搜索选择器或嵌套表单时,先确认 Enter 是否应被捕获。组件没有把 Form 方法直接暴露为模板 ref。 +输入法确认、多行换行、组合框、按钮、修饰键和已被控件 `preventDefault()` 的 Enter 保留原生行为。键盘提交的校验失败由表单展示;`onFinish` 的异常交给 Vue 的错误处理。调用 `useForm.validate()` 仍需处理其 Promise 拒绝。组件没有把 Form 方法直接暴露为模板 ref。 ## useForm @@ -82,7 +82,7 @@ export default defineComponent({ | ------------------------------------------- | ------------------------------------------------------------------ | | `formConditionRef` | 响应式模型,传给 `RForm.model` 并用于输入绑定。 | | `formModel()` / `formRules()` | 重新取得初始模型和规则。 | -| `getFormInstance()` | 获取已注册实例,未注册时抛错。 | +| `getFormInstance()` | 获取已注册实例,未注册或已卸载时抛错。 | | `validate(callback?, shouldRuleBeApplied?)` | 透传 Naive UI 校验;失败要处理 Promise 拒绝。 | | `validateTargetField(key)` | 按规则对象的唯一 `key` 筛选规则,`key` 不等同于 `NFormItem.path`。 | | `restoreValidation()` | 清除当前校验状态,保留输入。 | diff --git a/apps/docs/reference/components/iframe.md b/apps/docs/reference/components/iframe.md index c7955239..ce434d61 100644 --- a/apps/docs/reference/components/iframe.md +++ b/apps/docs/reference/components/iframe.md @@ -22,16 +22,16 @@ export const renderReport = (url: string) => ( ) ``` -| 属性 | 默认 | 说明 | -| ------------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------- | -| `src` | 必填 | iframe 地址。接收用户输入时应由业务限制可嵌入来源。 | -| `width` / `height` | `'100%'` | CSS 尺寸。百分比高度依赖父级。 | -| `frameborder` | `0` | 模板边框样式变量。 | -| `iframeWrapperClass` / `iframeClass` | 无 | 外层容器与原生 iframe 的类名。 | -| `title` / `name` / `allow` | 无 | 原生 iframe 属性。`title` 用于辅助技术识别。 | -| `lazy` | `true` | 字符串 `'lazy'` 或 `'eager'`。当前实现把布尔 `true` 和 `false` 都映射为 `'lazy'`,主动加载请写 `'eager'`。 | -| `customSpinProps` | `{}` | NSpin 配置,`show` 由组件内状态覆盖。 | +| 属性 | 默认 | 说明 | +| ------------------------------------ | -------- | ---------------------------------------------------------- | +| `src` | 必填 | iframe 地址。接收用户输入时应由业务限制可嵌入来源。 | +| `width` / `height` | `'100%'` | CSS 尺寸。百分比高度依赖父级。 | +| `frameborder` | `0` | 模板边框样式变量。 | +| `iframeWrapperClass` / `iframeClass` | 无 | 外层容器与原生 iframe 的类名。 | +| `title` / `name` / `allow` | 无 | 原生 iframe 属性。`title` 用于辅助技术识别。 | +| `lazy` | `true` | `true` / `'lazy'` 延迟加载,`false` / `'eager'` 主动加载。 | +| `customSpinProps` | `{}` | NSpin 配置,`show` 由组件内状态覆盖。 | -`onSuccess(iframe, event)` 和 `onError` 支持函数或回调数组。当前错误分支只传 `event`,与 Props 类型声明的双参数有差异;需要处理错误时不要假定有元素参数。首次 `load` / `error` 后关闭 Spin,当前实现不在 `src` 变更时重置加载状态;每次切换地址都要显示加载时可给组件不同的 `key`。`iframeInst` 是组件实际暴露的 DOM 引用。额外插槽交给 Spin,但默认内容始终为 iframe。 +`onSuccess(iframe, event)` 和 `onError(event)` 支持函数或回调数组。每次 `src` 变化都会重新显示 Spin,在 `load` / `error` 后关闭。组件 ref 上的 `iframe` 和兼容别名 `iframeInst` 都是原生 DOM 元素(尚未挂载时为 `null`);Vue 已自动解包,无需再访问 `.value`。额外插槽交给 Spin,但默认内容始终为 iframe。 [组件实现](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RIframe/src/Iframe.tsx) · [Props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RIframe/src/props.ts) diff --git a/apps/docs/reference/components/more-dropdown.md b/apps/docs/reference/components/more-dropdown.md index ea10d273..a1fb24d8 100644 --- a/apps/docs/reference/components/more-dropdown.md +++ b/apps/docs/reference/components/more-dropdown.md @@ -16,13 +16,14 @@ import MoreDropdownDemo from '../../examples/MoreDropdownDemo.vue' <<< @/examples/MoreDropdownDemo.vue ::: -| 属性 | 默认 | 说明 | -| ---------- | --------------- | ------------------------------------- | -| `icon` | `'action/more'` | 类型为 `IconName`,使用完整分包路径。 | -| `iconSize` | 跟随 RIcon | 触发图标大小,省略时为 20 px。 | -| `cursor` | `'inherit'` | 默认继承所在控件的指针样式。 | +| 属性 | 默认 | 说明 | +| -------------- | ------------------------------- | ------------------------------------- | +| `icon` | `'action/more'` | 类型为 `IconName`,使用完整分包路径。 | +| `iconSize` | 跟随 RIcon | 触发图标大小,省略时为 20 px。 | +| `cursor` | `'inherit'` | 默认继承所在控件的指针样式。 | +| `triggerLabel` | 跟随注入翻译或 `'More actions'` | 默认图标按钮的可访问名称。 | -`default` 插槽替换图标触发器。只有图标时建议用具有可访问名称的原生按钮或 `NButton`,方便键盘进入。列表行中根据业务需要阻止触发器的点击冒泡,避免同时触发行导航。 +默认触发器是可键盘聚焦的图标按钮。`placement` 默认 `'bottom-start'`,可由调用方覆盖。`default` 插槽替换整个触发器,自定义触发器应使用具有可访问名称的原生按钮或 `NButton`。列表行中根据业务需要阻止点击冒泡,避免同时触发行导航。 ```tsx import { RIcon, RMoreDropdown } from '@/components' diff --git a/apps/docs/reference/hooks.md b/apps/docs/reference/hooks.md index 6184821e..1f10166e 100644 --- a/apps/docs/reference/hooks.md +++ b/apps/docs/reference/hooks.md @@ -2,14 +2,14 @@ 模板的公开 Hooks 从 `@/hooks` 导入。与具体组件一起使用的 `useForm`、`useModal`、`useChart`、`useFlow` 从 `@/components` 导入,请看对应组件页。`useRequest` 从 `@/axios` 导入。 -| 需求 | API | -| -------------------------------------- | ---------------------------------- | -| 跳转页面,切换首页,操作标签和菜单标记 | [导航与菜单](./hooks/navigation) | -| 内容最大化、重载或滚动 | [布局与滚动](./hooks/layout) | -| 主题、语言、水印 | [主题与国际化](./hooks/appearance) | -| 分页与右键菜单 | [组件交互](./hooks/interaction) | -| 窗口尺寸、元素全屏和日期 | [窗口与日期](./hooks/browser) | -| DOM 截图、打印 | [截图与打印](./hooks/output) | +| 需求 | API | +| ---------------------------- | ---------------------------------- | +| 跳转页面,操作标签和菜单标记 | [导航与菜单](./hooks/navigation) | +| 内容最大化、重载或滚动 | [布局与滚动](./hooks/layout) | +| 主题、语言、水印 | [主题与国际化](./hooks/appearance) | +| 分页与右键菜单 | [组件交互](./hooks/interaction) | +| 窗口尺寸、元素全屏和日期 | [窗口与日期](./hooks/browser) | +| DOM 截图、打印 | [截图与打印](./hooks/output) | 需要订阅、事件或清理的 Hook 在 `setup()` 或有效的 Vue effect scope 中创建。在 DOM 挂载后或用户操作时执行截图、打印和全屏。`BasicTarget` 接受元素、ref 或 getter,解析规则和可用元素类型见[Vue 与 DOM 目标](./utils/browser#vue-目标解析)。 diff --git a/apps/docs/reference/hooks/browser.md b/apps/docs/reference/hooks/browser.md index 1363c499..f9c9dfc8 100644 --- a/apps/docs/reference/hooks/browser.md +++ b/apps/docs/reference/hooks/browser.md @@ -46,7 +46,7 @@ export function useListDensity() { | `zIndex` | 指定层级;省略时随进入顺序分配。 | | `backgroundColor` / `transition` | 指定背景与过渡。传 `'none'` 关闭过渡。 | -退出和卸载都会恢复原行内样式并取消待处理动画帧。作用域销毁会直接恢复,随后执行 `exit` 回调。若交互需要 Esc 或按钮关闭,页面应绑定 `exit()`。 +退出和卸载都会恢复原行内样式并取消待处理动画帧。作用域销毁会直接恢复,随后执行 `exit` 回调;销毁后旧实例不能再次进入全屏。若交互需要 Esc 或按钮关闭,页面应绑定 `exit()`。 ```ts import { useElementFullscreen } from '@/hooks' diff --git a/apps/docs/reference/hooks/interaction.md b/apps/docs/reference/hooks/interaction.md index 3e34827c..a67aad2b 100644 --- a/apps/docs/reference/hooks/interaction.md +++ b/apps/docs/reference/hooks/interaction.md @@ -25,7 +25,7 @@ import AdminExample from '../../examples/AdminExample.vue' | `getCallback()` / `setCallback(callback?)` | 读取、替换或移除通用回调。 | | `resetPagination()` | 页码回到 1,每页条数取第一个 `pageSizes` 的数字或对象 `value`,没有候选则用 10。 | -页码和页大小更新先改状态,再调用通用 `callback`,然后通知对应事件。重置同时调用两个专用事件。远端查询建议只在通用回调发请求,避免两次加载。Hook 不会自动请求或裁剪数据,初始加载由页面负责。`RTablePro` 的 `request` 已管理分页,通常无需再套一层本 Hook。 +页码和页大小更新先改状态,再调用通用 `callback`,然后通知对应事件。重置读取当前 `pagination.value.pageSizes`,同时调用两个专用事件;各实例的默认候选数组彼此独立。远端查询建议只在通用回调发请求,避免两次加载。Hook 不会自动请求或裁剪数据,初始加载由页面负责。`RTablePro` 的 `request` 已管理分页,通常无需再套一层本 Hook。 ```ts import { usePagination } from '@/hooks' diff --git a/apps/docs/reference/hooks/layout.md b/apps/docs/reference/hooks/layout.md index d78c86a4..624aa630 100644 --- a/apps/docs/reference/hooks/layout.md +++ b/apps/docs/reference/hooks/layout.md @@ -37,7 +37,7 @@ export function useReportLayout() { | `openSpin()` / `closeSpin()` | 开关布局内容区的加载动画,不改变应用全局 Spin。 | | `reload(wait?)` | 卸载当前内容后重新挂载,缺省等待 800ms。 | -只想表示请求未完成时使用 Spin,并在 `finally` 关闭。`reload` 会丢失当前页面未持久化的本地状态;多次重载时,Runtime Store 只保留最后一次恢复计时。 +内容区用细线进度与普通文本提示呈现加载;`openSpin` 持续超过 120ms 才显示,短操作不会闪烁,`reload` 则立即显示。只想表示请求未完成时调用 `openSpin`,并在 `finally` 用 `closeSpin` 关闭。`reload` 会丢失当前页面未持久化的本地状态;多次重载时,Runtime Store 只保留最后一次恢复计时。 ```ts import { useSpinning } from '@/hooks' diff --git a/apps/docs/reference/hooks/navigation.md b/apps/docs/reference/hooks/navigation.md index 33889798..6dab0d64 100644 --- a/apps/docs/reference/hooks/navigation.md +++ b/apps/docs/reference/hooks/navigation.md @@ -8,7 +8,7 @@ import AdminExample from '../../examples/AdminExample.vue' ## 交互示例 - + ::: details 查看示例源码 <<< @/../admin/src/views/demo/template-hooks/index.tsx @@ -55,17 +55,16 @@ export function useTableNavigation() { } ``` -## useAppRoot +## useAppRoot(兼容接口) -`getRootRoute`、`getRootPath`、`getRootName` 是计算引用。`setRootRoute({ name?, path? })` 与当前首页信息合并并更新设置,不会当场导航。给首页使用已注册的完整路径,路径和名称一起更新,确保目标页有访问权限。启动时校验首页路径是否在 Router 中。 +此接口已废弃,仅为旧调用方保留历史偏好的读写。`getRootRoute`、`getRootPath`、`getRootName` 是计算引用,`setRootRoute({ name?, path? })` 合并更新该字段;它不再控制登录落点、标签保护或关闭全部后的导航,也没有启动时首页校验。空工作区固定使用 `/welcome`。新代码直接通过 Router 显式导航。 ```ts -import { useAppRoot } from '@/hooks' +import { useVueRouter } from '@/hooks' -export function useResetHome() { - const { getRootPath, setRootRoute } = useAppRoot() - const reset = () => setRootRoute({ name: 'Dashboard', path: '/dashboard' }) - return { getRootPath, reset } +export function useOpenWorkspace() { + const { router } = useVueRouter() + return () => router.replace('/welcome') } ``` @@ -73,14 +72,14 @@ export function useResetHome() { 操作工作区的标签页。接受 `CloseMenuTag` 的方法可传从 0 开始的索引、与标签 `fullPath` 匹配的字符串或标签对象。 -| 方法 | 行为 | -| ---------------------------------------------------- | -------------------------------------------------------- | -| `getCurrentTagIndex()` | 当前标签索引;找不到返回 `-1`。 | -| `checkCloseLeft(target)` / `checkCloseRight(target)` | 检查目标对应方向是否有标签可关。 | -| `close(target)` | 关闭一个标签。最后一个标签保留。关闭激活项时切到相邻项。 | -| `closeLeft(target)` / `closeRight(target)` | 关闭目标左侧或右侧标签。需要时切换至目标。 | -| `closeOther(target)` | 只保留目标并激活。 | -| `closeAll()` | 在首页路由存在时清空标签并重新激活首页。 | +| 方法 | 行为 | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| `getCurrentTagIndex()` | 当前标签索引;找不到返回 `-1`。 | +| `checkCloseLeft(target)` / `checkCloseRight(target)` | 检查目标对应方向是否有标签可关。 | +| `close(target)` | 关闭业务标签;激活项切到相邻项,最后一项关闭后进入空工作区。 | +| `closeLeft(target)` / `closeRight(target)` | 关闭目标左侧或右侧标签。需要时切换至目标。 | +| `closeOther(target)` | 只保留目标并激活。 | +| `closeAll()` | 清空业务标签及其缓存,进入 `/welcome`,不依赖业务首页。 | 不要在存在未保存表单的工作流里直接调用批量关闭;这些方法不会替业务处理未保存确认。 diff --git a/apps/docs/reference/hooks/output.md b/apps/docs/reference/hooks/output.md index 55844225..804346a1 100644 --- a/apps/docs/reference/hooks/output.md +++ b/apps/docs/reference/hooks/output.md @@ -25,6 +25,8 @@ import AdminExample from '../../examples/AdminExample.vue' `options` 也可传 html-to-image 的选项,如 `backgroundColor`、`pixelRatio`、`filter`。`beforeCreate(element)` 在目标检查前调用,`created(result, element)` 在成功后调用;回调的结果类型涵盖全部格式,应先检查类型。`createdError(error)` 接收错误,Promise 仍以 `Error` 拒绝;`finally(element)` 每次都会调用,目标未解析时可能为空。截图要在目标挂载后执行,跨域图片和字体需满足浏览器加载限制。 +渲染库在第一次 `create` 时按需加载,未使用截图的页面无需下载该依赖。依赖加载失败也会进入上述错误和清理回调。 + ```ts import { useDomToImage } from '@/hooks' import { ref } from 'vue' diff --git a/apps/docs/reference/table-pro-examples.md b/apps/docs/reference/table-pro-examples.md index a74239b7..ae3fbd5c 100644 --- a/apps/docs/reference/table-pro-examples.md +++ b/apps/docs/reference/table-pro-examples.md @@ -30,7 +30,7 @@ import AdminExample from '../examples/AdminExample.vue' 1. 复制某行姓名或邮箱的一部分,填入上方筛选区并提交。查询回到第 1 页,分页使用筛选后的总数。 2. 清除条件后排序「年龄」并翻页。年龄排序通过 `onUpdateSorter` 转成 `params.sortAge`,在分页前作用于整个结果集。 -3. 分别在两页勾选行;工具栏显示跨页选中总数。「导出 CSV」依然导出当前页可见数据列。 +3. 分别在两页勾选行;工具栏显示跨页选中总数。「更多操作 → 导出 CSV」导出当前页可见数据列。 4. 点击「模拟请求失败」,观察旧行清空和错误提示;点击「刷新」恢复。传给 `request` 的 `signal` 可转交给 HTTP 客户端。 @@ -105,9 +105,13 @@ import AdminExample from '../examples/AdminExample.vue' <<< ../../admin/src/views/demo/tables/custom.tsx ::: +## 复制图片 + +在上方任意完整表格点击「复制表格图片」,再粘贴到支持图片的聊天或文档。可先在列设置中隐藏、固定列,或横向滚动后复制,对比当前表格可视区域。虚拟滚动只复制当前已渲染的可视内容;不会补齐全部行。入口默认显示,可用 `showCopyImage={false}` 隐藏;打印入口仍然默认隐藏。 + ## 打印与 CSV -先按姓名筛选,或在列设置中隐藏一列。点击工具栏的打印图标,预览当前页可见数据列。再点击「打印独立摘要」,预览 `print({ target })` 指向的自定义区域;该区域可有自己的版式。只需查看时,在浏览器的打印对话框选择取消即可。 +本例显式设置 `showPrint`。先按姓名筛选,或在列设置中隐藏一列,再点击「更多操作 → 打印表格」,预览当前页可见数据列;默认表格不会显示打印入口。点击「打印独立摘要」可预览 `print({ target })` 指向的自定义区域。只需查看时,在浏览器的打印对话框选择取消即可。 diff --git a/apps/docs/reference/table-pro.md b/apps/docs/reference/table-pro.md index f32a313f..845713fd 100644 --- a/apps/docs/reference/table-pro.md +++ b/apps/docs/reference/table-pro.md @@ -119,7 +119,9 @@ const renderTable = () => ( ) ``` -实例还提供 `setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print` 和 `getTableInstance`。扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。 +实例还提供 `setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage` 和 `getTableInstance`。扩展表格区域可用 `title`、`toolbar`、`tableFooter`、`tableAction`;错误区域用 `error` 插槽。 + +工具栏分为业务操作与内置工具两组。`request` 模式提供刷新,列设置、复制图片和全屏为直接入口;密度、斑马纹、边框和 CSV 收入「更多操作」。打印默认不显示,设置 `showPrint` 后才加入菜单。`tool={false}` 隐藏内置工具,保留自定义 `toolbar` 插槽。 ### `useTablePro` @@ -164,6 +166,25 @@ SFC 使用 ``。每张表单独调用一次 Ho 试试[在线列设置示例](./table-pro-examples#列设置与缓存)。每张表使用稳定且唯一的列 key。列设置可以勾选显示、拖动或用上移与下移按钮调整根列顺序、固定或启用列宽调整;分组子列跟随根列。使用 `columnStateKey` 跨刷新保留隐藏列,按账户或租户隔离时将标识纳入 key。缓存不存数据、列定义、顺序、固定位置或列宽。调用方接管列配置可用 `v-model:columns`,返回包含隐藏列的完整定义。「恢复列布局」保留显隐;受控列由调用方通过 `onResetColumnLayout` 恢复自己的列定义。 +## 复制表格图片 + +工具栏默认显示「复制表格图片」,把当前表格的表头、行、内部滚动可视区域及原生分页复制为 PNG,然后可粘贴到聊天或文档。图片排除 TablePro 标题、搜索、工具栏、提示区、`tableFooter` 和 `tableAction`;保留当前滚动位置与固定列。捕获范围是表格自身的 DOM 可视盒,虚拟滚动不会补画未挂载行,也不会请求其它页。 + +```tsx +const [register, { copyImage }] = useTablePro() + + + void copyImage()}>复制表格图片 +``` + +`showCopyImage={false}` 只隐藏按钮;实例和 Hook 的 `copyImage(options?)` 仍可使用。输出固定 PNG,`copyImageOptions` 支持 `pixelRatio`、背景、尺寸、样式、过滤、字体与资源请求配置,单次调用参数优先。默认设备像素比最高为 2。过滤回调收到临时快照节点,请按类名或数据属性判断。 + +必须直接从用户点击事件调用,之前不要 `await` 其它任务。图片生成可异步完成,但剪贴板请求需要保留用户激活;实现将 `Promise` 提前交给原生 `ClipboardItem`。[WebKit Clipboard API](https://webkit.org/blog/10855/async-clipboard-api/) + +成功写入返回 `true`;加载中、重复调用、未确认的数据、取消和失败返回 `false`。需要 HTTPS/localhost、支持 PNG 写入的浏览器及剪贴板许可;权限、资源或渲染失败都有反馈。数据更换或卸载会取消尚未就绪的图片并移除临时节点,无法撤销浏览器已经接受的写入。跨源图片、字体和受保护的画布仍受浏览器策略影响;完整当前页数据导出使用 CSV 或打印。 + +RIcon 的同源精灵图和本地 `#symbol` 会在临时副本中展开,保留静态矢量、尺寸与 `currentColor`,不复制导入 ID。只允许同源注册精灵图或公共 `.svg`,不携带凭据或跟随重定向;单次最多 16 个文件、每个 1 MiB。该路径不支持嵌套引用、paint server、样式表和动态 CSS 值。快照会移除脚本及内联事件属性,并拒绝 `iframe/object/embed/audio/video` 活动嵌入内容。 + ## 打印与 CSV 试试[在线打印与 CSV 示例](./table-pro-examples#打印与-csv)。默认取当前页可见数据列。打印按当前筛选和排序输出独立表格,不复刻 Vue 单元格、操作区、展开区或合并布局。报表等专用版式通过 `printTableOptions.target` 指定元素、ref 或 getter;默认复制宿主样式表、根节点主题和普通表单的当前值,也可设置 `includePageStyles: false`。单次调用可传 `title` 和专用 `style`。依赖区域外祖先、脚本或嵌入内容的区域需要专用打印 CSS;密码和文件值不会复制。真实纸张输出由浏览器负责。 @@ -180,7 +201,7 @@ Naive UI DataTable 的列定义、选择、展开、加载、空态和虚拟滚 | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `bare` | 默认关。移除卡片外观并隐藏标题及工具栏,省略 `pagination` 时不分页;显式搜索、底部插槽仍可使用。 | | `autoHeight` | 默认关;开启时让内部 DataTable 使用 `flexHeight`,适合有可用高度的布局。 | -| `tool` | 默认开,控制打印、密度、全屏、列设置和外观等内置工具。关掉仍可用自定义 `toolbar`。 | +| `tool` | 默认开,控制复制图片、密度、全屏、列设置和外观等内置工具。关掉仍可用自定义 `toolbar`。 | | `title` | 字符串或 VNode。存在 `title` 插槽时优先渲染插槽。 | | `pagination` | 普通模式缺省开,`false` 关闭;对象透传 Naive UI Pagination。容器小于 600px 时默认简洁模式,显式 `simple` 优先。 | | `pageSize` | 默认 10;`pagination.pageSize`、`pagination.defaultPageSize` 依次优先。远端初始页读 `pagination.defaultPage`。 | @@ -191,10 +212,15 @@ Naive UI DataTable 的列定义、选择、展开、加载、空态和虚拟滚 | `downloadCsvTableOptions` | 内置导出默认配置,模板实现使用 `fileName`、`keepOriginalData`。 | | `onResetColumnLayout` | 受控列的恢复布局回调。调用方在回调里更新 `columns`。 | | `printTableOptions` | 打印配置,支持 `target`、`title`、`style`、`includePageStyles`、`formatHeader`、`formatCell`。 | +| `showPrint` | 默认 `false`;控制「更多操作」菜单内的打印入口,实例 `print()` 仍可按需调用。 | +| `showCopyImage` | 默认 `true`;控制内置复制 PNG 按钮,实例 `copyImage()` 不受影响。 | +| `copyImageOptions` | PNG 渲染默认配置,单次 `copyImage(options)` 可覆盖;详见[复制表格图片](#复制表格图片)。 | | `contextMenuOptions` / `onContextMenuClick` | 行菜单选项及选择回调 `(key, option, { row, index })`。右键、Shift+F10 或菜单键打开;业务行事件可用 `preventDefault()` 阻止。 | 常用事件有 `onRequestError(error)`(或 SFC `@request-error`)、`onUpdatePage`、`onUpdatePageSize`、`onUpdate:columns`。内部更新和受控回调走同一入口;已传入受控值时由调用方更新对应值。行选择、排序等依然沿用 DataTable 事件;需要服务端排序时,将条件写入 `params`。 +分页对象使用 `TableProPagination`。旧 `pagination.onChange/onPageSizeChange` 及顶层 `onPageChange/onPageSizeChange` 不再调用,请迁移为 `onUpdatePage/onUpdatePageSize` 或 `onUpdate:page/onUpdate:pageSize`;原生分页组件不会再收到旧字段。 + | 插槽 | 参数与位置 | | ----------------------------- | ------------------------------------------------------------------------------------------------ | | `filters` | 表格上方;接收 `{ submit(values) }`,传入字符串或数字键值,提交后回第一页。优先于内置 `search`。 | @@ -204,7 +230,7 @@ Naive UI DataTable 的列定义、选择、展开、加载、空态和虚拟滚 | `tableFooter` / `tableAction` | DataTable 之后的额外区域。 | | 其余插槽 | 转给 Naive UI DataTable,例如空态和加载。 | -`TableProInst` 的 `reload(resetPage?)`、`setPage(page)`、`setPageSize(size)` 返回 `Promise`。请求错误由事件报告;该 Promise 的完成不能用作业务成功判据。`getTableInstance()` 可能为 `null`;`print(options?)` 返回 `Promise` 表示是否发起预览;`downloadCsv(options?)` 发起浏览器下载。 +`TableProInst` 的 `reload(resetPage?)`、`setPage(page)`、`setPageSize(size)` 返回 `Promise`。请求错误由事件报告;该 Promise 的完成不能用作业务成功判据。`getTableInstance()` 可能为 `null`;`print(options?)` 返回 `Promise` 表示是否发起预览;`downloadCsv(options?)` 发起浏览器下载;`copyImage(options?)` 返回是否成功写入 PNG 剪贴板。 远端请求将 `params` 与已提交筛选合并,后者覆盖同名项,页码字段最后由表格写入。关闭分页时也会删除传入的 `page` 和 `pageSize`。`total` 需要是非负安全整数,`data` 必须是数组。若筛选或删除数据后当前页超出范围,会收敛到最后一页,并在有结果时重查。 diff --git a/apps/docs/reference/utils/core.md b/apps/docs/reference/utils/core.md index 62537105..94ecd8b0 100644 --- a/apps/docs/reference/utils/core.md +++ b/apps/docs/reference/utils/core.md @@ -94,6 +94,6 @@ export const amount = format(add('0.1', '0.2'), { export const parts = distribute(10, 3, { precision: 2, type: 'string' }) ``` -分摊或货币结算由业务明确小数位和舍入规则。保留字符串或整数分值跨接口传输可避免展示时的二进制浮点误差。 +分摊或货币结算由业务明确小数位和舍入规则。currency.js 使用 JavaScript Number 存储缩放后的整数,金额乘以 `10 ** precision` 后需仍在安全整数范围内;这些方法不提供任意精度运算。保留字符串或整数分值跨接口传输可避免展示时的二进制浮点误差。 [基础函数](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/utils/src/core/index.ts) · [精度实现](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/utils/src/precision.ts) · [日期选择器辅助](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/get-date-by-naive-date-picker.ts) diff --git a/apps/docs/reference/utils/storage.md b/apps/docs/reference/utils/storage.md index 94c16329..44f7aab6 100644 --- a/apps/docs/reference/utils/storage.md +++ b/apps/docs/reference/utils/storage.md @@ -39,6 +39,8 @@ export const clearOrderFilter = () => removeStorage('order-filter', 'sessionStorage', options) ``` +独立包中的 `createStorage(storage, prefix?)` 为宿主提供的同步后端生成 `get`、`set`、`remove`。它使用相同的 JSON 格式;读取失败返回 `null`,写入或删除失败不向外抛错。不能序列化的值(包括 `undefined`、函数和循环引用)不会覆盖已有内容。前缀直接与键拼接。 + ## 兼容 AES JSON 下面的实验可以比较缓存键前缀,并用示例口令把一段 JSON 加密后还原。 diff --git a/docs/architecture.md b/docs/architecture.md index 0a71edf2..e5e6f720 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -37,6 +37,8 @@ Application `@/components`, `@/hooks`, and `@/utils` include compatibility entry | Documentation examples | Documentation can consume shared packages directly. When application context is required, [AdminExample.vue](../apps/docs/examples/AdminExample.vue) embeds [example.html](../apps/admin/example.html) with isolated bootstrap, restricted routes, and in-memory caching. | [Documentation and examples](../harness/context/docs.md) | | Application configuration | [Vite](../vite.config.ts) injects `__APP_CFG__` and `__DEV__`; [application configuration](../apps/admin/src/app-config) is grouped by design, requests, routing, and caching. | [Build and toolchain](../harness/context/toolchain.md) | +After a successful development mount, [application doctor](../apps/admin/src/doctor/README.md) reports configuration warnings independently of startup failures. It does not initialize services or impose a business home route. + Maintain guides and runnable examples for public behavior changes through [application/documentation coordination](docs-handoff.md). See [visual and layout guidance](ui-design.md) for page design and [comment style](comment-style.md) for code comments. ## TypeScript project configuration diff --git a/docs/reviews/2026-11-components.md b/docs/reviews/2026-11-components.md new file mode 100644 index 00000000..11f02f2a --- /dev/null +++ b/docs/reviews/2026-11-components.md @@ -0,0 +1,67 @@ +# Component implementation review — 2026-11-06 + +## Scope and acceptance + +This review follows the application compatibility exports into all twelve shared `R*` component implementations, the application route-transition adapter, and the app-bound wrappers/providers. It includes component-local hooks, utilities, props, slots, instance APIs, existing tests, and their admin/documentation consumers. Theme palettes and startup/content loading are tracked in the separate UI review. Generic composables and utilities have a separate review. + +The acceptance criteria are correct controlled state, preserved native configuration and callbacks, explicit resource ownership, bounded reactive work, accessible default controls, accurate public contracts, and regression coverage for the defects found. No throughput or browser memory improvement is claimed without a benchmark. + +## Shared components + +| Component | Paths inspected | Findings and disposition | +| -------------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| RBarcode | `RBarcode/src/Barcode.tsx`, props, types, stylesheet, admin and docs demos | Replaced nested watcher/observer creation with one lifecycle-owned observer and a post-render watcher. Format, options, renderer and size changes now redraw without changing text. Equal resize measurements do not redraw. `watchText=false` remains supported. Removed demo `key` workarounds that remounted the component. Rendering and callback error paths retain their existing contract. | +| RChart | `RChart/src/Chart.tsx`, hooks, props/types, options/loading helpers, theme registration, chart regressions | Existing lazy initialization, live `setTheme`, throttled options/resize, cancellation and disposal already have dedicated tests and were retained. Reviewed provider precedence, explicit/default themes, ARIA, download options and initialization failure cleanup. Corrected local hook contracts. The UI review owns the eight palette variants and loading-color correction. `useChart` intentionally retains the last disposed instance so `isDisposed()` and `render()` continue to work after manual disposal. | +| RCollapseGrid | `RCollapseGrid/src/*`, docs example and callers | Fixed the update event to emit the public `open` state instead of its inverse, preserved zero gaps, and made the default toggle a keyboard-operable button with `aria-expanded`. Added local reduced-motion handling. The docs example now uses direct `v-model:open`; old caller-side negation must be removed. | +| RDraggableCard | component, stylesheet, Interact.js adapter, demo | Interaction listeners now release on disabling, rebinding and unmount. Position changes rebind once after the DOM update; toggling drag retains its position. The last card removes the shared owned container. Removed the module-level `HTMLElement` constructor access and guarded server rendering. Reduced-motion preferences suppress the entrance transition. Removed demo remounting for position changes. Native pointer drag is still delegated to Interact.js. | +| RFlow | component, props/types, defaults, `useFlow`, installed LogicFlow implementation and demo | Removed the process-wide first-instance plugin gate so later instances register their plugins. Default nested options are created per instance. Readonly mode saves/restores actual interaction and keyboard state instead of forcing every option to true when disabled. Clearing data clears the graph; re-enabling watching applies the current data. The existing destroy-on-unmount path remains, and the registration hook releases stale instances. | +| RForm | component, props/types, `useForm`, form and lock-screen callers | Enter submission is reactive, uses bubbling, respects previously consumed events, IME, multiline and combobox controls, and prevents duplicate submissions. Field validation rejection is handled; callback errors still reach Vue. Unmounting during async validation prevents a stale `onFinish`. `useForm` clears disposed instances, allows partial updates/reset overrides, and retains its documented shallow reset behavior. Object initial models/rules are cloned; factories keep ownership of their returned objects. | +| RIcon | component, props, styles, sprite/inline fallback services | Retained host sprite resolution and lazy inline-asset fallback, avoiding eager asset work. Removed the unconditional compositing transform from every static icon. Optional path animation now respects reduced motion. Decorative SVG semantics remain; actionable accessible controls are owned by the surrounding button/link. | +| RIframe | component, props/types, loading tests and demo | Source changes restart loading. `iframe` and the existing `iframeInst` alias expose the same automatically unwrapped DOM element; corrected the declared instance shape. Preserved explicit lazy/eager choices, callback arrays, Spin options and slots. Documentation no longer describes already-fixed boolean loading or error-callback mismatches. A native load event is not proof of embedded business success. | +| RModal | component, props/types, styles, legacy hook and tests | Fixed the unused plain-modal width variable. Card/dialog dimensions and fullscreen scrolling retain their existing styles. Native Naive UI props/slots and focus management remain delegated to the library. Documented the deprecated imperative hook's DOM update and resource ownership rather than replacing it with another API. | +| RMoreDropdown | component, inherited dropdown props and docs example | Caller placement now overrides the default. The default icon is a named, keyboard-focusable button, with optional `triggerLabel` and host translation. Custom trigger slots remain unchanged. | +| RSegment | component, props/types, stylesheet and examples | Function-valued labels now render correctly; corrected the legacy `RSegmentProps.options` array type. Controlled/default values, disabled items, popovers, icon rendering, intrinsic widths and native tab behavior were retained. `displayDirective` remains a legacy option field with no panel effect because the wrapper renders tabs, not content panes; this limitation is stated in the reader reference. | +| RTablePro | all query/search/panel components, column, CSV/printing, locale, props/types and regression files | Reviewed local/remote/manual modes, request races/cancellation, paging reconciliation, search drafts/validation/dependencies, option fetching, column state, export scope and print sanitization. Fixed recursive hidden-leaf filtering and empty nested-group pruning while retaining unchanged references. Reworked the toolbar as described below. Added contracts for public component-local hooks/helpers without replacing existing bounded query and search machinery. | +| RTransitionComponent | application adapter plus shared `RouteTransition.vue` | Confirmed the adapter forwards transition props and live KeepAlive inclusion/configuration to the shell owner. Existing cache keys, include/exclude limits and route rendering remain unchanged. No independent wrapper implementation was added. | + +## TablePro toolbar + +Business toolbar content and built-in utilities are separate visual groups. Request-managed tables expose refresh directly; column settings and fullscreen remain direct controls. A single More actions menu contains density, striped/bordered toggles and CSV. Printing is absent by default and appears only with `showPrint`. The explicit instance `print()` method remains available regardless of menu visibility. + +This removes two always-mounted popselect wrappers while preserving their functions. Existing `tool={false}`, `bare`, toolbar slots, request callbacks, CSV formatting/default options, and printing options remain supported. The printing demo opts in; the remote demo uses the built-in refresh/export entries instead of duplicate buttons. Both locales and public references were updated. + +## Application wrappers and providers + +| Wrapper/provider | Review outcome | +| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| AppAvatar | Removed keyboard-focus suppression on the account button. Native size, round and object-fit options now work, while the legacy `avatarSize` override remains supported. Signing state still owns the displayed user. | +| AppGlobalSpin | Keeps runtime ownership of global busy state, but now merges caller theme overrides rather than discarding them. Slots and other Spin props remain delegated. | +| AppLockScreen, LockScreen, UnlockScreen | Removed redundant forced `show`; added bilingual copy and reactive validation messages. Validation failures and repeated attempts are handled. The clock now updates all fields at minute boundaries, pauses while hidden, resynchronizes on visibility, and cancels its timer on unmount; dates no longer wait 24 hours after mounting to change. Removed the detached logout delay. The existing local lock/storage format was preserved. | +| AppPageHeader | Confirmed heading/eyebrow/description and action slot remain lightweight and caller-owned; no change required. | +| AppShareLink | Confirmed both variants, stable keys, translations and external-link semantics. Theme-specific styling is owned by the UI review. | +| AppAutocompleteDefaults | Confirmed first-root scan plus incremental added-subtree scanning, explicit control/form opt-outs and returned observer cleanup. Added the public lifecycle contract. | +| AppNaiveGlobalProvider | Confirmed shared reactive locale/theme configuration, one discrete API lifecycle and `onScopeDispose(unmount)`. Globals remain intended for use only while the provider is mounted, as already documented. | +| AppRequestCancelerProvider | Confirmed route-update cancellation is delegated to the existing request canceler; no additional global listener or cancellation policy added. | +| AppStyleProvider | Read for cross-component theme ownership; all modifications and final acceptance belong to the UI review. | +| AppVersionProvider | Added bilingual version-dialog copy; retained one acknowledgement per cached application version and the existing logout action. | +| AppWatermarkProvider | Confirmed lazy conditional rendering and configuration forwarding; no change required. | + +## Component-local method contracts + +The method audit covered `useChart` and its registration/access/dispose/render methods, `useChartProvider`, `useForm` and its model/rules/validation/reset/update methods, `useFlow`, deprecated `useModal.create`, `useTablePro`, `useTableRequest`, `useTableSearch`, column layout/visibility, search value/parameter/predicate helpers, pagination forwarding, CSV construction/download, printable-content construction and printing, locale resolution, prop selection, and injected UI services. Public helpers now have adjacent multiline contracts using actual parameter names and ordered tags. Interface method properties use short property documentation; private trivial event lambdas remain covered by their owning contract instead of duplicating line-by-line explanations. + +## Verification + +Later browser validation found that group pinning updated header offsets but not body-cell fixed classes in the installed Naive UI implementation. Group pin/unpin now applies `fixed` recursively to descendants in both local and controlled layout paths, without mutating source definitions or cascading unrelated properties. The focused columns suite passed 9 tests, including both ownership modes and actual native fixed-cell classes. + +The follow-up removes deprecated pagination callback aliases from the public TablePro pagination contract and strips them from untyped runtime input. Current update events remain supported. The default toolbar also gains PNG clipboard copying through the existing lazy DOM renderer. Capture is restricted to the native table's visible DOM box, with temporary scroll/sticky snapshots, user-activation-safe promised clipboard data, local/host feedback and cancellation cleanup. This is distinct from full-page data export; virtualized unmounted rows are not synthesized. + +The follow-up's affected table regression set passed 7 files / 63 tests. After the final loading/cancellation adjustment, the image regression file passed all 10 cases; `vue-tsc --build`, touched-file ESLint/Prettier checks, and `git diff --check` passed. Actual native clipboard/paste fidelity is part of the lead's Chrome acceptance, not established by mocked clipboard unit tests. + +Chrome acceptance subsequently reproduced missing external RIcon sprites in PNG output. A focused, private SVG preparation helper now expands registered/same-origin public sprites and local symbols into isolated static vectors before rendering, with per-capture fetch deduplication, anonymous non-redirecting requests, bounded input and cancellation. Static attributes/currentColor/viewBox are retained; imported IDs and handlers are omitted, and resource-dependent or active SVG content is rejected. The connected table snapshot also removes scripts/event attributes and rejects active embedded media before cloning. The two focused image suites passed 29 tests; native sprite fidelity is rechecked by the lead. + +Focused regression coverage includes component wrappers, barcode redraw, flow initialization/readonly/lifecycle, drag cleanup, nested column visibility, toolbar defaults/options/actions, and app-wrapper/clock lifecycle. Existing chart, table search/query/export and modal suites are included in the combined component run. + +Executed: `pnpm test:run __test__/components __test__/app/wrapper-lifecycle.spec.tsx` passed 14 files / 109 tests. ESLint with `--max-warnings=0`, Prettier checks for all files owned by this review, and `git diff --check` passed. The final workspace type/build check belongs to the lead's integration pass; the scoped work emitted no component type errors. + +The lead agent records the final integrated type/lint/format/build results and actual Chrome observations. Unit tests with mocked ECharts, LogicFlow or Interact.js establish wrapper contracts, not canvas-rendering fidelity, pointer gesture physics or browser print output. Scanning a physical barcode, arbitrary third-party iframe policies, and browser-specific printer output are outside this local audit. diff --git a/docs/reviews/2026-11-hooks-utils.md b/docs/reviews/2026-11-hooks-utils.md new file mode 100644 index 00000000..806b2a11 --- /dev/null +++ b/docs/reviews/2026-11-hooks-utils.md @@ -0,0 +1,121 @@ +# Hooks and utilities review — November 2026 + +## Scope and acceptance + +Reviewed every implementation reachable from `apps/admin/src/hooks`, `apps/admin/src/utils`, `packages/composables/src`, and `packages/utils/src`. Compatibility entry points were followed to their owners instead of counted as separate implementations. The source inventory contains 141 named implementations in 44 files, plus the layout-owned `positionSelectedMenuItem` reached through its historical utility export. Inline event callbacks and returned object methods were also inspected. Component-local hooks and utilities are covered by the [component review](2026-11-components.md). + +Acceptance covers observable correctness, reactive state ownership, resource cleanup, bounded allocations, configuration behavior, and accurate function contracts. It does not mean every function needs a rewrite or that a CPU benchmark proves browser responsiveness. + +## Findings and changes + +| Finding | Change | Evidence | +| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Default pagination candidates shared one mutable array across hook instances. | Give each instance its own default `pageSizes` array. Caller-provided arrays retain caller ownership. | Two simultaneous instances and a later instance retain independent defaults after one is mutated. | +| Pagination reset consulted startup candidates after the exposed configuration had changed. | Read `pagination.value.pageSizes` at reset time, including object options and the empty fallback. | Replacement with a 25-row option and then an empty array resets to 25 and 10 respectively. | +| Shared storage could overwrite valid JSON with the non-JSON result of `JSON.stringify(undefined)`. | Serialize first and skip writes when serialization returns `undefined` or throws. Keep the existing backend, prefix, and JSON format. | `undefined`, functions, symbols, cycles, and BigInt preserve saved content; JSON `null` still writes normally. | +| A fullscreen hook could reacquire an element after its effect scope was destroyed, leaving no live cleanup owner. | Mark the instance disposed before restoring it and ignore subsequent entry attempts. | Disposal restores style priorities and previous attributes, blocks the old instance, and lets a new instance acquire the element. | +| Random identifiers invoked Web Crypto separately for every character. | Fill a bounded buffer of at most 128 samples and retain rejection sampling. | Rejected samples, multiple batches, radix boundaries, and a 70,000-character identifier are covered. No random-source weakening or modulo bias was introduced. | +| PNG Base64 conversion created one array entry per byte. | Prefer native `Uint8Array.toBase64`; use bounded 32 KiB string chunks when unavailable. | Empty data, all byte values, large buffers, chunk boundaries, and forced fallback produce identical Base64. | +| Every permission requirement searched the entire permission array. | Cache a computed Set per hook instance and use direct membership checks; rebuild on reactive permission changes. | Single/all/any checks, empty-list semantics, in-place revocation, and replacing session permissions are covered. | +| The screenshot renderer was statically imported even when never used. | Dynamically import `html-to-image` within the existing asynchronous `create` method after validating the target. | Configured/overridden formats, callback ordering, renderer errors, and missing/throwing targets remain covered. Browser/build acceptance is recorded by the integrating review. | + +The Base64 fast path follows the [native typed-array API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array/toBase64); feature detection preserves older browsers. No dependency, package export, persistence key, or ciphertext format was changed. + +The integrating review additionally optimized `useTheme` by capturing its reactive getter, actions and translator once per factory; repeated reads no longer rebuild all settings computed references. A same-instance theme/language change regression confirms the result is not a cached snapshot. + +The later [routing review](2026-11-routing.md) supersedes the original root/tab behavior and documents the final neutral-workspace contract. + +## Per-method disposition + +The directory prefixes below identify authoritative implementations. “Retained” means source, call sites, and existing tests were reviewed and no justified behavioral change was found; it is not a claim of exhaustive runtime proof. + +### Shared composables + +| Implementation | Methods inspected | Disposition | +| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `packages/composables/src/dom.ts` | `printDom` | Retained: resolves the target when capturing, awaits capture/print submission, reports loading success/failure, and returns a boolean. Actual paper output belongs to the browser. | +| `element.ts` | `classTokens`, `setClass`, `removeClass`, `hasClass` | Retained: token matching uses `classList`; reactive targets are watched with Vue scope ownership. `hasClass` intentionally observes target replacement rather than native class mutations. | +| `element.ts` | `autoPrefixStyle`, `cssProperty`, `setStyle`, `removeStyle` | Retained: legacy prefix mapping stays compatible; style updates preserve unrelated declarations and support custom properties and `!important`. Browser parsing handles string declarations. | +| `element.ts` | `colorToRgba`, `queryElements`, `completeSize` | Retained: hex and comma-separated rgb/hsl parsing, invalid selector fallback, and preservation of existing CSS units/expressions are covered. Clarified that color conversion is not a complete CSS color parser. | +| `useContextmenuCoordinate.ts` | `useContextmenuCoordinate`, `getEventOptions`, `updateShow`, `bindContextMenuEvent`, `stop` | Retained: forced non-passive contextmenu handling, latest-generation opening, dynamic ignored elements, outside close, listener cleanup, and idempotent stop. | +| `useDayjs.ts` | `createDayjsTools`, `at`, `locale`, `isDayjs`, `format`, `getStartAndEndOfDay`, `daysDiff`, `isDateInRange` | Retained: local timezone, integer day differences, open-interval boundaries, per-instance locale versus explicit legacy global mode. Completed the factory's parameter/return contract. | +| `useDevice.ts` | `useDevice`, observer callback | Retained: VueUse owns resize listeners; observation tracks only size and breakpoint, so unrelated reactive reads in the observer do not retrigger it. | +| `useDomToImage.ts` | `useDomToImage`, `run` exposed as `create` | Changed to lazy renderer loading. Kept per-call format inference, callbacks, original element resolution, and error/finally behavior. | +| `useElementFullscreen.ts` | `useElementFullscreen`, `enter`, `exit`, `toggleFullscreen`, restoration closure | Fixed post-disposal entry. Retained one-owner-per-element behavior, original style priorities, target replacement handling, configurable transition and callback vetoes. Added method-level lifecycle/error contracts. | +| `usePagination.ts` | `usePagination`, `onUpdatePage`, `onUpdatePageSize`, `getItemCount`, `setItemCount`, `getPage`, `setPage`, `getPageSize`, `setPageSize`, `getPagination`, `getCallback`, `setCallback`, `resetPagination` | Fixed default-array ownership and reset configuration. Retained state-before-callback ordering and callback replacement/removal. Documented getters and mutable configuration ownership. | +| `usePrint.ts` | `usePrint`, `run` exposed as `print` | Retained: current target resolution, HTML default for elements, binary image/PDF conversion, and caller options. Kept the synchronous non-binary contract instead of making every print call asynchronous. | +| `vue/call.ts` | `call` | Retained: ordered synchronous invocation; the first thrown error stops the sequence. | +| `vue/effect-dispose.ts` | `effectDispose` | Retained: registers cleanup only when a scope exists and reports whether registration succeeded. | +| `vue/render-node.ts` | `renderNode` overloads and implementation | Retained: nullish fallback preserves `0` and empty text; callbacks and slots are returned without being invoked early. One contract remains on the public overload. | +| `vue/unref-element.ts` | `unrefElement` | Retained: resolves values, refs, getters, and component roots on demand, with a nullish fallback. | +| `vue/watch-effect-with-target.ts` | `watchEffectWithTarget` | Retained: directly preserves Vue's scheduler, cleanup, scope ownership, and stop handle. | + +### Shared utilities + +| Implementation | Methods inspected | Disposition | +| ---------------------------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `packages/utils/src/core/index.ts` | `isValueType`, `isAsyncFunction`, `isPromise` | Retained: type tags, declared async functions, and awaitable values remain separate concepts. No deep traversal is added. | +| `core/index.ts` | `uuid` | Bounded random batches retain character order, allowed radix/length validation, and unbiased sampling. | +| `core/index.ts` | `callWithErrorHandling`, `callWithAsyncErrorHandling` | Retained: synchronous versus awaited behavior is explicit; callback failures propagate. Arbitrary PromiseLike results are awaited by the async wrapper. | +| `files/index.ts` | `arrayBufferToBase64Image` | Native fast path plus bounded fallback; PNG prefix and synchronous return type preserved. | +| `files/index.ts` | `downloadBase64File`, `downloadAnyFile`, `fileToBase64` | Retained: temporary links removed, object URLs released on failure or after browser handoff, file read errors/abort reject. A resolved download does not mean disk writes completed. | +| `storage.ts` | `createStorage`, `get`, `set`, `remove` | Fixed invalid serialization overwrite; reads remain live and errors contained. Added complete host ownership, prefix, failure, and JSON contracts. | +| `precision.ts` | `isCurrency`, `format`, `add`, `subtract`, `multiply`, `divide`, `distribute` | Retained currency.js operations, eight-digit default precision, mixed input order, signed remainder behavior, and zero-division/count validation. Documented the safe-integer limit instead of claiming arbitrary precision. | +| `equal-router-path.ts` | `equalRouterPath`, `normalize` | Retained: compares path identity after stripping query/hash/trailing slashes; callers needing tab-instance identity must use full paths. | +| `remove-duplicate-keys.ts` | `removeDuplicateKeys` | Retained the compatibility name and shallow-copy semantics, including symbol keys. | +| `update-object-value.ts` | `updateObjectValue` | Retained own-property checks and shallow merging only for two plain objects; arrays and other values are replaced. | +| `app/detect-operating-system.ts` | `detectOperatingSystem` | Retained browserless fallback and desktop-identified iPad handling. User-Agent classification is a display hint, not capability detection. | + +### Application hooks + +| Implementation under `apps/admin/src/hooks` | Methods inspected | Disposition | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `template/useAccess.ts` | `useAccess`, `hasPermission` | Cached permission membership with reactive invalidation. Empty-list all/any behavior preserved; both factory and method now have contracts. | +| `template/useAppNavigation.ts` | `useAppNavigation`, `navigationTo`, `navigate`, `deepNavigation` | Retained invalid-index rejection, first-leaf traversal, resolved dynamic paths, query merging, hash preservation, and Router Promise forwarding. | +| `template/useAppRoot.ts` | `useAppRoot`, `setRootRoute` | Retained preference reads and merge updates as a deprecated compatibility API. The routing follow-up removes all landing, protection and startup-validation effects. | +| `template/useBadge.ts` | `updateBadge`, `useBadge`, `hidden`, `show`, `update` | Retained actual menu-object lookup, metadata merging, and renderer rebuilding; missing targets do not create menus. Documented shared ownership. | +| `template/useContentScroll.ts` | `useContentScroll`, returned `scrollTo` | Retained invocation-time instance lookup and safe no-op when content is unmounted. Documented both coordinate and option forms. | +| `template/useSiderScroll.ts` | `useSiderScroll`, returned `scrollTo` | Retained the same late lookup for optional sidebars; documented arguments. | +| `template/useI18n.ts` | `getI18nKey`, `useI18n`, `translate` exposed as `t`, `locale`, extraction-only `t` | Retained namespace idempotence, initialization/HMR recovery and argument forwarding. Documented that direct locale writes do not replace the app's synchronized settings action. | +| `template/useMaximize.ts` | `useMaximize`, `maximize`, returned `toggleFullscreen` | Retained shared Store state and generation-checked completion callbacks. Documented per-call defaults, callback timing, and user-triggered errors. | +| `template/useSiderBar.ts` | `normalMenuTagOption`, `useSiderBar`, `getCurrentTagIndex`, `checkCloseRight`, `checkCloseLeft`, `close`, `closeAll`, `closeRight`, `closeLeft`, `closeOther` | Retained bounds checks and neighbor selection. The routing follow-up allows every business tab to close, routes final/all closure to Welcome, and preserves full URLs. | +| `template/useSpinning.ts` | `useSpinning`, `openSpin`, `closeSpin`, Store-owned `reload` alias | Retained boolean manual state and Store-owned latest-wins reload timer. Documented ownership and that closing manual feedback does not cancel remounting. Visual changes are covered by the UI review. | +| `template/useTheme.ts` | `useTheme`, `getAppTheme`, `darkTheme`, `lightTheme`, `syncSystemTheme`, `toggleTheme` | Captures the reactive getter, actions and translator once per factory instead of rebuilding all settings getters on each theme read. Existing live theme/language behavior remains covered (6 tests). | +| `template/useVueRouter.ts` | `useVueRouter` | Retained direct shared Router access outside setup; no copied route state. | +| `template/useWatermark.ts` | `useWatermark`, `setWatermarkContent`, `showWatermark`, `hiddenWatermark`, `toggleWatermark` | Retained nonempty content updates, shared visibility, and settings persistence. Completed factory contract. | +| `web/useDayjs.ts` | `useDayjs` | Retained app-language mapping and explicit legacy global-locale behavior; documented the adapter. | + +### Application utilities and compatibility routes + +| Implementation under `apps/admin/src/utils` | Methods inspected | Disposition | +| ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `app/get-app-environment.ts` | `getAppEnvironment` | Retained direct Vite configuration access; documented browser visibility. | +| `app/prefix-cache-key.ts` | `prefixCacheKey` | Retained literal prefix concatenation and historical nonempty custom-prefix fallback. | +| `cache-backend.ts` | `memoryStorage`, Storage `key/getItem/setItem/removeItem/clear`, `useMemoryCache`, `getStorageInstance` | Retained independent local/session in-memory maps for document examples; documented reset and lifetime behavior and browser access exceptions. | +| `cache.ts` | `getKeyWithPrefix`, `hasStorage`, `setStorage`, `getStorage`, `removeStorage`, nested `remove` | Retained serialization-before-write, explicit-null preservation, backend error handling, and reverse iteration for namespace-scoped bulk deletion. | +| `dom.ts` | app `printDom` adapter | Retained global loading-bar injection and shared capture/print behavior; documented that the host loading option overrides the supplied one. | +| `get-date-by-naive-date-picker.ts` | `getDateByNaiveDatePicker` overloads and implementation | Retained typed range-null mapping and original values for other inputs; one contract on the public overload avoids duplication. | +| `legacy-crypto/encrypt.ts` | `encrypt` | Retained JSON validation, legacy passphrase/OpenSSL format, and random-IV raw-key format. | +| `legacy-crypto/decrypt.ts` | `decrypt` | Retained historical formats and contained parse/decrypt failures. No key migration or format replacement was introduced. | +| historical `position-selected-menu-item.ts` entry | layout-owned `positionSelectedMenuItem` | Followed the alias: reads bounds before scrolling, ignores missing nodes, and only scrolls out-of-view selected items. No duplicate implementation created. | +| remaining `index.ts`, `basic.ts`, `c/*`, web/template compatibility paths | export forwarding and type-only declarations | Verified ownership and existing names. These files contain no additional methods to optimize or duplicate comments for. | + +## Comment audit + +Public factories, exported utilities, and returned action methods now have adjacent contract comments where this module owns the declaration. Comments follow the initial blank line, actual parameter names/order, standalone `@description`, and `@param` → `@description` → `@returns` → `@throws` order. They do not add `@returns` to void actions. Public overloads carry one shared contract, while small private normalizers and platform-typed callback bodies use local implementation notes rather than repetitive JSDoc. + +The audit also corrected specificity: the screenshot promise includes dependency loading, fullscreen callbacks do not mean animation completion, `useSpinning` delegates restoration to the Store, color parsing covers comma-separated rgb/hsl, and fixed-point arithmetic is bounded by Number's safe-integer range. + +## Verification and remaining boundaries + +- Initial regression run: `pnpm test:run __test__/hooks __test__/cache __test__/basic __test__/precision __test__/utils-contracts __test__/vue __test__/element __test__/dom` passed 49 files / 218 tests before the final native-Base64 fallback case was added. +- Final affected-case rerun: `pnpm test:run __test__/basic/arrayBufferToBase64Image.spec.ts __test__/cache/shared-storage.spec.ts __test__/hooks/useAccess.spec.ts` passed 3 files / 8 tests. `vue-tsc -p tsconfig.packages.json --noEmit` and `vue-tsc -p tsconfig.test.json --noEmit` passed. ESLint with zero warnings and Prettier checks passed for all owned changed files. +- The integrating agent records final type, lint, formatting, build and browser outcomes for the combined change. Screenshot creation on `/web-hooks` is the affected lazy-load interaction; other hooks keep their visible behavior. +- Browser rendering, image/font cross-origin restrictions, native print dialogs, and physical print output are not established by Happy DOM tests. No physical printing is required for the internal changes in this review. +- No universal speedup, mobile-device latency, memory ceiling, or cross-browser benchmark is claimed. The proven changes remove per-character crypto calls, per-byte fallback array entries, repeated permission scans, and eager screenshot imports while retaining the documented API behavior. +- Large synchronous Base64 requests still allocate the output string. If measured payload sizes block interaction, add an explicitly asynchronous/worker API at that consumer boundary rather than silently changing this synchronous API. +- Native Storage calls remain synchronous; demo memory storage is intended for the small isolated documentation dataset. Existing native DOM class changes do not make `hasClass` reactive. Legacy AES remains a compatibility format, and fixed-point functions remain Number-backed. Revisit those choices only with a concrete workload or migration requirement. + +## Guidance applied + +The Modern Web Guidance `performance` guide recommends “**DO use dynamic imports**”. The screenshot implementation follows that recommendation while leaving the synchronous print API intact. The generic performance guidance does not justify changing date, storage, or compatibility contracts to newer APIs without an observed need. diff --git a/docs/reviews/2026-11-quality-review.md b/docs/reviews/2026-11-quality-review.md new file mode 100644 index 00000000..df60076d --- /dev/null +++ b/docs/reviews/2026-11-quality-review.md @@ -0,0 +1,66 @@ +# Quality review — November 2026 + +## Scope and acceptance + +This review covers all shared component wrappers, application wrappers, generic and application hooks/utilities, the four visual presets, startup/content loading, and all eight RChart palettes. The source audit follows compatibility exports to their owning implementations and records retained behavior as well as changes. + +The accepted follow-up scope removes the protected-root-tab and forced-root-redirect convention. An empty workspace must remain usable when no business page is selected, including when permissions or the route source omit the former dashboard. Welcome and error pages must work without relying on a particular business route. TablePro must hide printing by default and retain an explicit opt-in through its configurable action area. + +Acceptance requires: + +- Distinct, coherent plain, Naive UI, Material, and modern themes in light and dark modes; actual chart canvases, labels, tooltips, and loading feedback must match. +- Startup/content loading that communicates status without a button-like label, respects reduced motion, and offers recovery from startup errors. +- Per-component and per-method findings, contract comments, meaningful regressions, and no speculative performance claims. +- Any business tab can close; closing the last/all tabs reaches an empty welcome workspace. Permission/source changes and direct unknown URLs cannot activate an unavailable dashboard. +- Integrated welcome and error pages with safe recovery actions, bilingual copy, and narrow-screen support. +- TablePro's default actions omit printing; explicit printing, column controls, refresh, export, and configured slots continue to work. + +## Detailed inventories + +- [Visual presets, loading, and chart themes](2026-11-ui.md) +- [Component wrappers and component-local hooks](2026-11-components.md) +- [141 hook/utility methods in 44 owning modules](2026-11-hooks-utils.md) +- [Workspace welcome and error-page design](2026-11-workspace-states.md) +- [Route ownership, permissions, and empty-tab behavior](2026-11-routing.md) + +## Integration evidence + +The accepted scope is implemented and integrated. The review used three implementation agents with separate ownership, a complementary read-only review, and lead-agent browser/command verification. No commits, pushes, or deployments were performed. + +### Command verification + +- `pnpm harness verify all` passed on Node 26.13.0 / pnpm 12.16.1: 94 test files / 470 tests, environment and Harness checks, API/package boundaries, icon synchronization, application/package/test types, zero-warning ESLint, formatting, admin build, and documentation types/build. Report: `.harness-local/runs/all-dyiXvi/report.json`. +- The final cross-review fixes added navigation-error ownership, system-title locale updates, empty-target action disabling, and retryable initialization. The final affected set passed 5 test files / 31 tests: router initialization, navigation errors, sidebar/tab methods, reused theme state, and workspace status UI. This is an overlapping targeted rerun, not 31 additional tests to add to the full-run count. +- Final `pnpm typecheck`, affected-code ESLint, admin production build, and `pnpm docs:check` passed after those fixes. The final outputs were combined with `scripts/assemble-pages.mjs` and checked through a local production preview. +- Final repository-wide formatting, Harness integrity, and `git diff --check` passed. An incidental editor-dictionary addition (`rgba`) was preserved; only its surrounding JSON formatting was normalized. No staged changes were introduced. +- The lead's AST comment audit found no incorrect parameter names, required-tag ordering, or initial blank-line violations in documented methods across hooks, utilities and shared UI. The two public overload implementations share their declaration contracts; the function component follows the convention against component-header JSDoc. The final theme hook reuses its reactive getter/actions/translator rather than recreating 21 getter refs on every snapshot read; theme and locale changes remain live. + +### Browser observations + +- Chrome at 1440 × 1000: inspected the dashboard in all four light/dark presets and the live chart page in all eight palettes, including crosshairs and tooltips. The same ECharts instance survived every style/mode switch; no console errors were reported on the chart page. +- Content loading: the real 800 ms demo opens and closes the indicator; the public `useSpinning` API also produced the quiet line and transparent, borderless label with no button. At 390 × 844, English/dark loading stays inside the viewport, the document remains 390 px wide, reduced-motion sweep is 6 s, and forced-color track/fill borders remain visible. +- Startup probe: a local server substitutes only the entry module in the actual served HTML. Saved Material/dark and English settings restore before Vue; reduced motion removes entry animation and slows the line to 6 s. An actual missing module resource and a missing named export both show the failed/reload UI. Reload changes the document time origin. These are controlled failure probes, not evidence of an external outage. +- Form: blank submission displays field errors; Enter in a populated single-line input submits; Enter in the textarea inserts a newline without submitting again. No console errors were reported. +- Drag card: real pointer dragging changes the card transform; toggling drag off/on remains usable; closing the last card removes its owned Teleport container. No console errors were reported. +- Flow: readonly toggle, reset, graph readback and return to editing work; no console errors were reported. +- Screenshot hook: the actual PNG-preview action yields a complete 1136 × 164 image. The normal HookExample consumer no longer warns about an absent optional documentation injection. +- Barcode: changing text and color updates the existing SVG node; responsive width matches its container. Iframe eager and lazy examples both load the local document. Segment selection updates its displayed state. Documentation CollapseGrid expands and collapses with keyboard input, and the dropdown example selects an action by keyboard. +- Modal/lock screen: card and dialog widths measure 480/380 px and Esc restores the trigger focus. In the isolated demo account, empty lock validation, bilingual copy, successful locking, incorrect unlock feedback and successful unlocking work without application errors. A transient Chromium `aria-hidden` focus warning appeared during native modal dismissal; the final focused trigger is visible and not hidden. No library-wide focus override was introduced to suppress this warning. +- TablePro: default remote tables expose refresh, columns, fullscreen and More actions, with no print entry. The menu updates striped state; request refresh settles with data. The printing example explicitly enables its print item. Production CSV selection invokes a real download (`data.csv`, 1,922 characters in that fixture, expected quoted headers). English/dark controls fit a 390 px viewport; the table scrolls within its container. +- Empty workspace: the actual Close all action and closing the final former-dashboard tab both reach `/welcome`, with zero tags, no current menu/key and an empty KeepAlive include list. Welcome/status routes never become business tabs. +- Permission/source boundary: a separate browser context used a validated local source with one public route and one admin-only route, omitting dashboard. A member session landed on welcome, saw only the public entry, received 403 for the admin route and 404 for `/dashboard`. Changing the public route to admin-only pruned its old tag/cache on reload and left an empty workspace with no invented navigation entry. +- URL restoration: changing only query/hash kept one tab; returning through that tab restored `/quality/public?filter=two#detail` exactly. English system titles update with locale. Empty English/dark welcome and 500 layouts have no horizontal overflow at 390 × 844. +- Error recovery: an intentionally rejected current route loader reached `/500` with a safe retry target; Back to workspace recovered. A delayed failure from an older route left the newer successful route active. These probes used temporary, local route records and were removed afterward. +- Production artifact: the final compiled app loads and removes its splash, demo login lands on welcome, and built documentation iframes load from the combined subpath. The embedded navigation demo's Close all action also reaches welcome with zero tags and no active menu; no application console errors were reported in those production checks. + +Temporary screenshots and probes are kept under `.harness-local/quality-review/`; they are not production assets. Command tests, rendering, controlled failure probes, and physical-device coverage are recorded separately. + +The temporary development, documentation-development and failure-probe servers were stopped. The combined production preview remains available at `http://127.0.0.1:9530/ray-template/` for local review. + +### Compatibility and verification limits + +`useAppRoot` and stored `appRootRoute` remain deprecated compatibility metadata with no landing, permission, protected-tab or startup-validation effect. Existing callers that inverted CollapseGrid's erroneous update event should remove that inversion. Printing remains available through the instance API; its default toolbar visibility is now opt-in. + +Chrome desktop and emulated narrow viewports were tested. No Safari/Firefox/device matrix, physical barcode scan, paper printing, remote CI, deployment, or real-backend acceptance is claimed. Unit tests cover the same-page initialization retry; a real Wujie host was not used. Native printer behavior is unchanged; this task verifies the new menu visibility and existing print contracts, not printer hardware. + +Builds still report large chunks and two ineffective dynamic imports in the existing route-contract/layout graph. No universal speedup or bundle-size target is claimed. The concrete improvements remove duplicate observer/listener work, unnecessary getter and permission allocations, per-character random calls, per-byte fallback array entries, and eager screenshot-renderer loading while retaining error handling and configuration contracts. diff --git a/docs/reviews/2026-11-refinements.md b/docs/reviews/2026-11-refinements.md new file mode 100644 index 00000000..1926b48a --- /dev/null +++ b/docs/reviews/2026-11-refinements.md @@ -0,0 +1,43 @@ +# UI and component refinements — November 2026 + +This follow-up preserves the preceding quality-review changes and covers pagination API migration, app diagnostics, the custom-style contract, PNG clipboard capture, and icon selection. No commit, push, or deployment is part of this work. + +## Decisions and implementation + +- TablePro pagination uses the current `onUpdatePage` / `onUpdatePageSize` events (and their `onUpdate:*` forms). Deprecated nested and table-level change aliases are excluded from its public types and stripped before native forwarding. Reader documentation includes the migration. +- The former `__ray-template` entry only retained locale-configuration checks after removal of the root-route convention. Those checks still detect cross-field drift that individual TypeScript unions cannot. They now live in the app-local `doctor` module, report development diagnostics after mounting, and do not reject a successfully mounted application. A separate workspace package would add no reusable boundary here. +- [The engineering style contract](../ui-design.md) and [reader guide](../../apps/docs/guide/appearance.md#custom-css) explain semantic token consumption, local theme scope, provider ownership, native overrides, Teleport, runtime layout sizing, motion, and explicit exceptions. A public-export-only `ThemeScopeExample.vue` is included in documentation type checking. +- TablePro exposes a default-visible copy-image action, `showCopyImage`, `copyImageOptions`, and the `copyImage()` instance/hook method. Capture includes the visible NDataTable header, body and native pager, excluding the page, search, toolbar and unrelated slots. It does not synthesize unmounted virtual rows or fetch all backend data. Promise-backed PNG clipboard data preserves the originating click; capture is lazy and cancellation owns temporary snapshot cleanup. +- The icon family was retained where it already fits. Five assets were selected from the existing [Iconfont collection](https://www.iconfont.cn/collections/detail?cid=51731), with upstream IconPark attribution and Apache-2.0 licensing retained. Table/status glyphs were replaced, capture/external-link glyphs added, and misleading icon uses corrected. Existing names remain compatible. + +| Asset | Iconfont ID | Reason | +| ---------------------- | ----------- | ----------------------------------------------------------------- | +| `navigation/table` | 43963947 | A table grid distinguishes data tables from bar-chart navigation. | +| `status/success` | 43971726 | Circular check matches the existing question/warning containers. | +| `status/error` | 43971709 | Circular error mark completes the status family. | +| `action/copy-image` | 43970501 | Capture frame denotes the table-region PNG action. | +| `action/external-link` | 43971751 | External navigation is distinct from a three-node share action. | + +The five selected assets retain their source path geometry; rendered SVG source path checksums were compared with the local files. Only export metadata, colors, optical viewBoxes and outline reinforcement were adapted. Generic assets keep `currentColor`; brand marks are unchanged. The icon catalog now contains 67 assets. The icon-library shortcut uses the icon-library glyph, forward arrows point right, and external resource links use the new external-link mark. Dashboard shortcuts now traverse visible menu groups instead of silently disappearing when destinations are nested. + +## Verification record + +Verification is complete. Local evidence is under `.harness-local/refinements/`. + +- `pnpm harness verify all` passed with 100 files / 514 tests, environment and Harness validation, API/package boundaries, icons, types, lint, formatting and both builds. The report is `.harness-local/runs/all-YYEdpT/report.json`. +- A final browser-discovered grouped-column defect was fixed: applying a fixed position only to a group pinned its header but left body columns moving. Explicit group pin/unpin now cascades to descendants in local and controlled modes without mutating source columns. Final whole-suite verification passed **100 files / 516 tests**. Final type checking, affected table regressions, admin build and documentation check/build also passed, and the combined preview was refreshed. +- Icon verification passed 3 files / 10 tests. The five selected path geometries match their observed Iconfont sources. Chrome rendered all four circular status glyphs at matching optical bounds; the new table/capture/external-link glyphs and Dashboard navigation cues were inspected. Grouped visible shortcuts now appear, while hidden ancestors remain excluded. +- Browser clipboard output excludes page/search/toolbar content and preserves table header/body/pager, theme and current viewport. The light fixture yielded 3932 × 1128 PNG; a dark, horizontally scrolled fixed-column fixture yielded 1460 × 1228 PNG with its external SVG icon intact. The final compiled application also produced a 754 × 564 PNG, 106,146 bytes, through the actual ClipboardItem data supplied to the native Chrome write call; the button returned to enabled and no temporary snapshot remained. +- A virtual-row fixture at scrollTop 400 had 10 mounted rows and 6 intersecting the viewport. Its 1460 × 628 PNG contains that visible region, including partial edge rows, instead of synthesizing unmounted rows. In an independent Chrome DevTools session, the native clipboard promise fulfilled, the copy button reenabled, scrollTop remained 400 and the snapshot count returned to zero; the same flow also completed without instrumentation. +- Real group-pin geometry was checked at horizontal offsets 120 and 200: header and body name cells both remained at x = 309.8984375 with sticky positioning. This verifies the new grouped layout behavior as well as the capture scenario. +- Screenshot, pagination and diagnostics regressions cover unsupported/denied APIs, rejected or empty rendering, duplicates, cancellation, form/radio isolation, static SVG validation, modern callback forwarding, and diagnostic error containment. The doctor warning marker is absent from production JavaScript. + +A warm browser-API capture/write sample took about 313 ms on this machine. This is one observation, not a cross-device or OS clipboard benchmark. The Browser Use adapter exposes an isolated clipboard: exact generated PNG items were transferred through its documented clipboard bridge into a paste fixture for visual inspection. One adapter session left its completion state pending despite holding a valid image; independent native Chrome API checks completed normally. No application timeout or false success shortcut was introduced to hide that discrepancy. + +The missing external-SVG glyph reproduced during QA was fixed at the snapshot boundary. Only static local symbols and same-origin public SVG/spritemap references are expanded, with deduplicated bounded requests, cancellation, independent viewBoxes/currentColor and no imported IDs, handlers or resources. Unsupported active embedded content and non-static SVG dependencies fail explicitly. Browser-managed clipboard support, permission and the originating user action remain requirements; Safari/Firefox and a real Wujie host were not exercised. + +Test-only DOM probes, clipboard observers and sizing overrides were cleared, and the native development page's original light-mode preference was restored. The updated production preview remains at `http://127.0.0.1:9530/ray-template/`. + +## Tool and environment boundaries + +Automatic approval review rejected fetching/executing the remote Modern Web Guidance package. Read-only MDN/WebKit references and installed source were used instead; the rejected execution was not retried through another launcher. A later native full-window accessibility read was rejected because it could include unrelated tabs; subsequent verification uses the owned test tab, scoped developer inspection, and the generated image files. Neither restriction requires weakening the implementation or granting broader access. diff --git a/docs/reviews/2026-11-routing.md b/docs/reviews/2026-11-routing.md new file mode 100644 index 00000000..7bd21e32 --- /dev/null +++ b/docs/reviews/2026-11-routing.md @@ -0,0 +1,48 @@ +# Neutral workspace and routing review — November 2026 + +## Resulting contract + +The shell no longer requires or protects a business home route. `/welcome` is the neutral state with no active business page. `/403`, `/404`, and `/500` are recovery states. All four are outside business menus, tab persistence, recent/favorite navigation, and KeepAlive. Their paths, descendants, aliases, and route names are reserved against local or remote JSON collisions. + +Business sources may omit `/dashboard` entirely or restrict it to a role. No fallback dashboard is injected. Startup does not validate a legacy root preference. The menu store follows the actual Router location instead of selecting the cached root or the first permitted menu. + +## Changes traced across owners + +| Owner | Previous implicit behavior | Result | +| ----------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `router/app-route-modules.ts` | Added a bundled dashboard when a custom source omitted it. | Registers the business source plus explicitly owned management routes. | +| Shared route contract | Required dashboard to be unrestricted; had no host status-path reservation. | Treats dashboard like any business view; accepts host `reservedPaths`. `homePath` is ignored and deprecated for compatibility. | +| `router/routes.ts` | Login/management and a catch-all error view were the shell routes. | Registers Welcome, 403, 404, 500 and a catch-all forwarding the attempted URL. `getSystemRoutes` is reused by isolated documentation examples. | +| Permission guard and login | Login and denied navigation returned to the configured root. | Login returns only to an explicitly requested, existing, authorized local business URL, otherwise Welcome. Forbidden direct links show 403. Query/hash are preserved. | +| Landing/recovery resolver | Fell back to dashboard, including when absent or inaccessible. | Rejects external/control-character targets, missing/forbidden/system targets, and redirect cycles. Validates string redirect chains without replacing the original URL. Default is Welcome. | +| Router error handler | Page import failures lacked a consistent status recovery destination. | Navigates to 500 with `query.from`; failure of the 500 route itself does not loop. | +| Menu bootstrap | Restored a cached/first-menu active tab even without an active business URL. | Restores only valid permitted tags, excludes shell states, and derives active selection from the actual URL. | +| URL synchronization | Query/hash were dropped from restored tags. | One tag per concrete pathname retains its latest full URL. The sidebar key stays canonical. | +| Tab actions and MenuTag | Root and final tabs could not close; close-all recreated the root. | Every business tab closes. Active removal selects its neighbor; final/all removal opens Welcome with no active menu or breadcrumb. | +| KeepAlive | Closed/revoked component names could remain allowed. | Prunes names whenever the open tab set changes. Status pages never enter the allowlist. | +| Account/role changes | Menu rebuilding could recreate a still-visible old-account page during logout. | Account removal clears tabs/active state without recreating them. Revoked current pages show 403; revoked tags and cached names are removed. | +| Settings and logo | Default logo and historical root preference implied dashboard availability. | Default logo targets Welcome. One-time migration changes only the recognizable stock logo; explicit custom targets remain. Legacy root fields are inert. | +| Demo/docs | Controls appeared to configure a protected home; documentation fallback forced dashboard. | Removes misleading root controls, documents compatibility-only access, and shares neutral/status routes with documentation iframes. | + +## State and compatibility details + +- `menuKey` remains the canonical sidebar key. `currentMenuOption.fullPath` identifies the active tab's exact URL. Query/hash changes update the existing concrete-path tab rather than adding duplicates. +- System states clear active business selection and breadcrumbs without closing unrelated open business tabs. Explicit close-all clears the list and its cached view names. +- Hidden and `sameLevel` business routes retain their established behavior. Direct same-level pages do not fabricate a default parent tab. Updating a same-level URL replaces its breadcrumb entry instead of accumulating query variants. +- Existing tab cache keys and array format remain readable. Restored entries are re-resolved against the current Router and role; saved metadata is not trusted. The old persisted `menuKey` no longer controls active navigation. +- Navigation history retains its per-account, path-only format. System states are filtered from reads and writes; visible shortcuts still intersect saved paths with authorized menus. +- `useAppRoot`, `appRootRoute`, and `redirectRouterToDashboard` remain only for existing callers. The first two access an inert preference; the last aliases neutral `redirectRouterToWorkspace`. None grants permission, protects a tab, selects a business landing page, or imposes a startup requirement. + +## Verification + +The focused suite `pnpm test:run __test__/router __test__/hooks/useSiderBar.spec.ts __test__/hooks/useAppRoot.spec.ts __test__/layout/navigation-history.spec.ts __test__/layout/preferences.spec.ts __test__/app/workspace-states.spec.tsx` passed 9 files / 80 tests. It covers no-dashboard sources, reserved collisions, login redirects, query/hash restoration, closing the last/root/all tabs, neighbor operations, status exclusion, account removal, role revocation, KeepAlive pruning, logo migration, and safe status actions. Router error tests cover failed business-page and error-page imports without recursion. + +After the final URL-sanitizer and legacy-icon typing adjustment, the affected permission/preferences rerun passed 2 files / 26 tests. `vue-tsc --build`, ESLint with zero warnings, and Prettier checks passed for the routing-owned changes. + +The complementary integration review found and corrected three further boundaries: + +- A superseded lazy import could fail after a newer successful or pending navigation and incorrectly open 500. Error handling now tracks normalized navigation-target identity, including terminal duplicated/aborted attempts, while cancelled old attempts cannot take ownership back. A three-case regression covers newer successful, pending, and duplicate navigation. Errors thrown by a component's leave guard before the tracking guard remain ordinary Router rejections; this conservative case does not claim ownership it cannot establish. +- System-page titles did not follow language changes because no business menu was active. The title watcher now derives the active route's translated metadata. Welcome and 403 title changes are covered. Target-specific tab actions are disabled when a system page has no active target. +- A rejected startup Promise prevented later same-page or microfrontend remount attempts from refetching route configuration. Failed initialization now releases that Promise; successful initialization and guard registration remain shared. The retry/concurrent-initialization regression passed 1/1; this tests Router initialization ownership, not an external Wujie host. + +The final race/title suite passed 2 files / 14 tests; its source changes also passed type checking, lint, and formatting. The integrating agent records full checks and browser evidence in the [combined review](2026-11-quality-review.md). Server-side authorization remains unchanged. A remote configuration failure before application startup still uses the existing boot-error state; the 500 route handles owned navigation failures after Router setup. No deployment or publication was performed. diff --git a/docs/reviews/2026-11-ui.md b/docs/reviews/2026-11-ui.md new file mode 100644 index 00000000..b1182446 --- /dev/null +++ b/docs/reviews/2026-11-ui.md @@ -0,0 +1,67 @@ +# UI refinement review — November 2026 + +## Scope and acceptance + +Review the four existing interface styles, initial startup feedback, and the content loader used by `useSpinning`. Preserve saved preferences, custom primary colors, language, route/loading ownership, and the existing Naive UI configuration contract. Refinement means consistent shapes, clear hierarchy, readable secondary content, restrained elevation, and feedback that cannot be mistaken for a control. + +## Style inventory + +| Style | Intended character | Finding | Resolution | +| -------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Plain | Neutral gray, 2px corners, flat surfaces | Dashboard tiles and shortcut surfaces still used fixed 10–18px corners; shared descriptive text inherited the library's weaker tertiary color. | Route custom surfaces through the active radius tokens and use the secondary text fallback for page descriptions. Keep the preset flat. | +| Naive UI | Native library controls, green accent, compact shapes | The library preset was already unmodified, but custom dashboard corners were inconsistent; `boxShadow1` intended for floating content was reused as a page shadow. The light page-muted color measured below the documented 4.5:1 target. | Preserve the native preset; make custom surfaces follow its shape tokens, omit unconfigured page shadows, and use secondary text for shared page descriptions. | +| Material | Purple tonal surfaces, large cards, capsule buttons | The preset had a coherent shape/color direction, but custom surfaces ignored it and dark surface elevation fell back to a library overlay shadow. | Apply existing shape tokens to custom surfaces and define a restrained dark shadow. Preserve tonal surfaces and 20px cards. | +| Modern | Ray blue, quiet cool canvas, 8px controls and 12px cards | Existing palette, density, and hierarchy were a suitable baseline. Ad hoc corner values and loading treatments weakened consistency. | Retain the established palette and spacing; align custom surfaces and loading feedback. | + +This review does not rename or consolidate the styles. Their differences remain deliberate. A user-selected primary color still overrides the preset and can require its own contrast review. + +## Loading and motion + +| Area | Finding | Resolution | +| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Initial HTML | Existing startup feedback worked before the bundle and preserved retry, but its canvas did not follow the saved style. Brand, label, and progress spacing lacked a consistent visual rhythm. | Add a restrained logo stage and entrance, match each saved preset's canvas/accent, and align the line/label treatment. No runtime dependency, artificial progress percentage, or minimum startup delay. | +| `useSpinning` feedback | An `NSpin` and text enclosed in a bordered/filled capsule looked like a button; routine loads used a live status region. | Replace with an unboxed line and label plus labeled native indeterminate `progress`. Preserve the 120ms anti-flicker timer, immediate remount feedback, scope cleanup, and locale lookup. | +| Reduced motion | Shared theme CSS forced all animation/transition durations to 0.01ms, including infinite animations. | Remove global duration overrides. Keep local route handling; suppress the startup entrance and slow both new loading tracks to 6s. Component-specific motion remains owned by the component review. | +| Forced colors | Progress depended on background colors. | Preserve visible system-color borders for the track and moving segment; avoid relying on shadows or color-only backgrounds. | + +## Chart style packs + +All eight JSON packs were reviewed field by field: categorical colors, canvas, title/subtitle, legend, tooltip, pointer/crosshair labels, category/value/time/log axes, grids, line widths/area opacity, bar radii, and pie separators. Canvas colors match their owning page card surfaces. Explicit business options remain authoritative, following the [ECharts style contract](https://echarts.apache.org/handbook/en/concepts/style/). + +The existing Modern blue/teal/violet sequence and Material purple/tonal sequence were already coherent. Naive keeps its green-led palette. Plain keeps low-saturation categorical hues so separate series remain distinguishable without turning the style into a colorful dashboard. No series palette was changed merely for novelty. + +| Pack | Chart canvas | Label contrast | Lowest data-color contrast | Pointer contrast after review | +| -------------- | ------------ | -------------- | -------------------------- | ----------------------------- | +| Modern light | `#ffffff` | 6.05:1 | 4.19:1 | 3.15:1, unchanged | +| Modern dark | `#172131` | 8.78:1 | 7.45:1 | 3.74:1, unchanged | +| Naive light | `#ffffff` | 12.16:1 | 4.60:1 | 4.22:1, previously 1.31:1 | +| Naive dark | `#18181c` | 12.12:1 | 7.73:1 | 5.56:1, previously 2.18:1 | +| Material light | `#fffaff` | 10.39:1 | 4.79:1 | 3.56:1, unchanged | +| Material dark | `#241e2c` | 11.02:1 | 9.00:1 | 3.90:1, unchanged | +| Plain light | `#ffffff` | 12.16:1 | 4.08:1 | 4.54:1, previously 1.31:1 | +| Plain dark | `#202020` | 11.31:1 | 6.74:1 | 5.37:1, previously 2.20:1 | + +Ratios use sRGB relative luminance after compositing alpha against the actual canvas. Tooltip text is at least 7.74:1 across these packs. Naive/Plain previously used divider colors for interactive pointers; those four packs now distinguish the pointer from the decorative grid. The minimum 3:1 target for meaningful graphical marks follows [W3C non-text contrast guidance](https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html). The measurements are against the chart canvas, not a claim that every overlapping area, adjacent pie slice, or custom chart satisfies accessibility requirements. + +The loading-style audit also reproduced `transparent` becoming `rgba(0,0,0,0.9)` when alpha was replaced. `loadingOptions` now parses once and falls back to the mode's surface when the custom theme has no usable background. It retains selected theme colors and caller overrides without modifying the theme object. + +## Verification + +- Browser follow-up found that an entry dependency could fail before `main.ts` installed its async error handler. An inline capture listener now sends module resource errors and script `ErrorEvent`s to the existing failure/retry UI, ignores image errors, and becomes inert once the splash is removed. It is removed on the next post-mount error and adds no timeout or module dependency. This follows the separate [script-element fetch-error](https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-element) and [module evaluation-error](https://html.spec.whatwg.org/multipage/webappapis.html#run-a-module-script) paths. Vite regenerates bundled module tags, so an `onerror` attribute on the source tag would not cover production output reliably. +- `boot-feedback.spec.ts` passed 4 focused cases for captured module resource failure, script evaluation failure, unrelated image errors, and post-mount cleanup. +- `chart-themes.spec.ts` adds 30 deterministic checks for all eight theme registrations/surfaces, text and data/pointer contrast, loading masks, transparent/invalid backgrounds, and caller overrides. It passed together with the existing chart and startup-feedback regressions: 3 files, 39 tests. +- Focused Vitest run passed: `content-loading.spec.tsx`, `global-provider.spec.ts`, and `preferences.spec.ts` — 3 files, 13 tests. New cases cover delayed feedback, short-operation cancellation, unmount cleanup, native progress labeling, and immediate remount feedback. +- ESLint passed for changed TypeScript/TSX files. Prettier passed for the UI implementation and tests. +- The lead agent visually accepted dashboard consumers in all four styles and both modes, and all eight actual chart palettes/tooltips. ECharts retained the same instance through the switches. The checked flows had no console errors. +- At 390px in English/dark mode, the content loader retained its unboxed label, native progress, 6s reduced-motion sweep, and no horizontal overflow. Forced-colors track/fill borders remained visible. +- A local proxy fixture generated from the actual served startup HTML verified Material dark/English startup at 390px, reduced motion, genuine module-resource failure, and a missing named export in a module dependency. Both failures displayed the alert and Reload action; Reload started a new document. These are controlled failure probes, separate from the real application-flow checks and the final production build/preview. +- Screenshots are stored under `.harness-local/quality-review/screenshots/`. The lead agent owns the final combined build and browser evidence record. +- No device-matrix or assistive-technology certification is claimed. The loader retains native semantics, but real screen-reader testing is separate from DOM assertions. + +## Guidance applied + +- `spinner`: “Without a `value` attribute, it is implicitly indeterminate.” The loading state uses native progress semantics without inventing a completion percentage; a decorative line represents activity. +- `motion`: “Prefer to animate `opacity` and `transform`”. Loading animation uses compositor-friendly transforms; startup entrance uses only opacity and transform. +- `motion`: “DO NOT globally apply `animation-duration: 0.01ms;`”. Reduced motion is handled at the affected animations rather than accelerating infinite effects. +- `accessibility`: “Don't use live regions for interstitial states”. Routine content loading exposes progress semantics without introducing repeated live announcements. +- `color`: “Maintain 4.5:1 for normal text” and “a minimum contrast ratio of 3:1”. Chart palette checks composite alpha before measuring; interactive pointers use a stronger color than decorative dividers. diff --git a/docs/reviews/2026-11-workspace-states.md b/docs/reviews/2026-11-workspace-states.md new file mode 100644 index 00000000..b33fccad --- /dev/null +++ b/docs/reviews/2026-11-workspace-states.md @@ -0,0 +1,25 @@ +# Neutral workspace and status-page UI — November 2026 + +## Scope and ownership + +This UI change accompanies the routing change that removes protected-home and forced-home navigation. The router owns always-available `/welcome`, `/403`, `/404`, and `/500` destinations, system-page exclusions from business tabs/menus, guards, and failed-navigation recovery. This record covers the views, recovery controls, copy, and visual treatment. + +## Findings and changes + +- The previous `PageResult` overrode all caller statuses with 500 while displaying a hardcoded Chinese 404 message. Its two recovery actions both depended on configured home state. The component now renders the supplied status, distinct bilingual 403/404/500 explanations, and a semantic page heading. +- A nested `height: 100vh` ignored shell header/tabs/footer height. Status pages now use the available content-height variable, permit natural overflow when needed, and remain centered without forcing another viewport-sized panel. +- Welcome is an intentional workspace with no active business selection. It uses an existing icon, `AppPageHeader`, semantic surface/radius tokens, and native navigation links. It adds no fabricated activity, counts, or placeholder charts. +- Up to six real menu destinations appear. The current visible, role-filtered menu tree is authoritative; account-scoped recent paths only rank those destinations. Hidden branches, external links, detail-only entries, unresolved parameters, and stale history are excluded. An empty list reports a lack of visible navigation entries rather than falsely claiming the account has no permissions. +- Page state uses typography, spacing, and a single clear recovery hierarchy. All four themes retain their own surfaces and shapes. Links collapse to one column below a 600px content container; long labels wrap. Motion is limited to local hover color transitions and is disabled for reduced motion. + +## Recovery contract + +The neutral action always uses `WELCOME_ROUTE_PATH`. A 500 page shows retry only when the routing utility resolves untrusted `query.from` to an authorized business URL; the query and hash remain intact. Other states may expose a previous-page action when the same utility accepts the history target. These controls use internal router replacement instead of assuming browser history is safe or reloading `/500` into itself. + +Naive Result props and `icon`, `default`, and `footer` slots remain available. Title/description overrides are honored. Custom footer content replaces the default actions rather than being overwritten by the wrapper. + +## Verification + +- `__test__/app/workspace-states.spec.tsx`: 10 tests passed, covering visible-menu/history filtering, removal of unavailable shortcuts, language switching, distinct 403/404/500 rendering, neutral navigation, authorized retry with query/hash, unsafe/system/forbidden retry rejection, and custom copy/slots. +- ESLint passed for all new/changed view code and tests; Prettier formatted the views and locale resources. +- The lead agent owns browser acceptance in desktop/narrow viewports and representative light/dark themes after routing integration stabilizes. The routing agent separately owns guard/tab/source regressions. Unit rendering is not a claim of completed browser acceptance. diff --git a/docs/ui-design.md b/docs/ui-design.md index ff7f3284..30876145 100644 --- a/docs/ui-design.md +++ b/docs/ui-design.md @@ -4,15 +4,70 @@ The template uses restrained blues and neutral colors. Refinement comes from con ## Themes and dimensions -- Prefer semantic variables in `apps/admin/src/styles/design-system.scss` for page backgrounds, cards, dividers, and text. Naive UI theme overrides live in `apps/admin/src/app-config/design-config.ts`. Keep a consistent color scale instead of inventing a separate theme for each page. -- `apps/admin/src/styles/base.scss` is the global style entry point. `design-system.scss` owns theme variables and basic focus styles; `setting.scss` owns layout dimensions. Keep `naive.scss` limited to shared control defaults. Put layout/component-specific rules in the owning directory to avoid affecting nested Naive UI instances. -- Controls generally use 8px radii, cards 12px, and page sections 20–28px spacing. Use accent colors for selection and primary actions; distinguish body text, descriptions, and eyebrow labels by color hierarchy. +- Consume semantic variables from [shared theme.css](../packages/ui/src/theme.css) for page backgrounds, cards, dividers, and text. [theme-presets.ts](../packages/ui/src/theme-presets.ts) owns preset values and their mapping; the admin's modern preset can be customized through `APP_THEME.appNaiveUIThemeOverrides` in [design-config.ts](../apps/admin/src/app-config/design-config.ts). Do not copy a palette into each page. +- `apps/admin/src/styles/entry.ts` imports `base.scss`; `design-system.scss` only bridges to the shared theme stylesheet. `setting.scss` contains legacy compile-time Sass dimensions, not live layout preferences. Keep `naive.scss` limited to shared control defaults. Put layout/component-specific rules in the owning directory to avoid affecting nested Naive UI instances. +- The modern preset uses 8px control radii and 12px card radii. Plain stays square and neutral, Naive retains the library's native controls, and Material uses larger shapes and tonal surfaces. Custom page surfaces use `--r-radius` / `--r-control-radius` so a preset applies beyond library components. Page sections generally use 20–28px spacing. +- Use accent colors for selection and primary actions; distinguish body text, descriptions, and eyebrow labels by color hierarchy. Page descriptions must remain readable: when a preset does not define a body-safe muted color, use the library's secondary text color rather than its weaker tertiary color. - Use subtle dividers between top bars, tab bars, and sidebars rather than layered shadows. A small number of content cards may use two-layer shadows. +- Page surfaces use only the active preset's explicit soft shadow; library overlay shadows are not inherited by ordinary page cards. Naive's floating menus and dialogs retain their native elevation. - Page tabs normally show only their names. Reveal the close button on hover or focus; touch users can close the active tab directly. - The preference drawer uses one or two field columns according to available width. Keep section navigation and reset actions in consistent positions. - When content is maximized, provide an exit control above the content, accessible by button or Esc. - Reuse `AppPageHeader` for page headings: an eyebrow, one main title, a short description, and optional actions. Do not replace page hierarchy with long descriptions or equally prominent card headings. +## Custom CSS contract + +The table below describes consumption, not a second token definition. The linked stylesheet and mapping function remain authoritative for names, values, and fallback behavior. + +| Semantic property | Use | +| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--r-canvas` | Workspace/page background. | +| `--r-surface`, `--r-surface-muted`, `--r-surface-hover` | Primary, secondary, and hovered surfaces. Hover is a derived surface color, not an alpha value. | +| `--r-text`, `--r-text-secondary`, `--r-text-muted` | Main text, supporting text, and quieter descriptions. Muted text remains readable; it is not a disabled-state token. | +| `--r-line`, `--r-control-border` | Quiet structural dividers versus identifiable control boundaries. Do not use the weaker divider as the only boundary for an input or active control. | +| `--r-theme-primary-color`, `--r-theme-primary-fade-color` | Raw primary and primary-hover colors. The historical `fade` name does not guarantee transparency. | +| `--r-primary-text`, `--r-selected-text` | Readable emphasis/selected text. Dark mode deliberately maps these to text colors rather than blindly reusing a user-selected accent. | +| `--r-radius`, `--r-control-radius` | Custom surface and control corners. Surface radius comes from an explicit Card radius or common radius; control radius comes from common radius. Naive component-specific shapes, such as Material capsule buttons, still belong to their theme overrides. | +| `--r-shadow-soft` | Optional page-surface elevation. Only an explicitly configured common shadow is mapped; no configured shadow means `none`, including the native Naive preset. Plain stays flat. | +| `--r-bezier`, `--r-font-mono` | Shared easing and monospaced text stack. | + +`--r-token-*` properties are the provider's mapped inputs. Ordinary page/component styles consume the semantic properties above; they do not replace the mapping, write global palette primitives, or introduce competing `--primary-color` conventions. Add local variables such as `--report-gap` only when the component actually needs an override point. There is no global spacing-token API to invent or assume. + +### Provisioning and scope + +- **Admin pages:** `AppNaiveGlobalProvider` supplies the effective `NConfigProvider` theme; its descendant `AppStyleProvider` reads `useThemeVars()`, maps tokens, and writes them to ``. The setting store merges the selected style/mode with custom primary overrides. Consume these values directly; do not subscribe to settings or call `getComputedStyle()` per render merely to recolor DOM elements. +- **Independent package consumers:** Import `@ray-template/ui/theme.css`, supply `NConfigProvider` with the chosen light/dark preset, and apply `createRayThemeStyle()` plus `.r-theme-scope` and the matching `.r-template--light`/`.r-template--dark` class to the local DOM owner. [ThemeScopeExample.vue](../apps/docs/examples/ThemeScopeExample.vue) is a type-checked, copyable host example using public exports only. [DemoFrame.vue](../apps/docs/examples/DemoFrame.vue) is the current documentation integration. +- **Resolved variables:** `useThemeVars()` reads an ancestor provider, not a provider returned later by the same component. Put a bridge below that provider, as the admin does, or merge the exported Naive base `common` values with the same common overrides, as the independent example does. +- **Local inheritance:** `.r-theme-scope` redefines semantic aliases where local mapped inputs live. Setting only a child `--r-token-*` while inheriting aliases computed at an ancestor can leave those aliases bound to the ancestor's theme. Custom properties follow the [CSS cascade and inheritance rules](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Cascading_variables/Using_custom_properties). +- **Behavior services:** `provideUiServices()` supplies translation, chart mode/theme, icons, or persistence to descendants. It does not install a Naive provider or write CSS. The standalone example supplies only mode/chart behavior; a host adds its own locale/translation and other services as needed. Do not wrap existing admin pages in a partial service provider, which would shadow the application services. +- **Missing providers:** With the shared stylesheet but no mapped inputs, semantic properties fall back to system colors (`Canvas`, `CanvasText`, `Highlight`, `ButtonBorder`), 4px radii, and no shadow. This is a readable fallback, not automatic selection of Modern/Material/Naive/Plain. Without the stylesheet, consumers must import it or provide explicit `var()` fallbacks. Naive components keep their own default behavior when their provider is absent. +- **Teleport:** Vue injection follows component ownership, but CSS inheritance follows the DOM. Custom content teleported outside a local theme scope needs a target inside the scope or an explicitly themed target. A local scope does not recolor the entire document; however, the imported stylesheet also defines root color-scheme and generic focus rules, so it is not a completely isolated stylesheet. + +### Writing and overriding styles + +1. Prefer existing component props/slots and Naive `themeOverrides` before internal selectors. For theme-specific controls use Naive components so density, capsule shapes, disabled states, and focus treatment remain coherent. +2. Put application styles next to their page/component and import them from its entry. Reusable UI styles live with the owning shared component. Use a stable component class (`.r-report`, `.r-report__actions`) or SFC `scoped` styles; scope any necessary `.n-*` override beneath that owner. Avoid broad `button`, `.n-card`, or `.n-input` overrides. +3. Use semantic properties for theme-dependent colors, borders, radii, and shadows. Fixed values remain appropriate for content geometry, optical icon sizing, spacing, breakpoints, and brand/data colors with a documented purpose. Brand assets and ECharts palettes are distinct contracts; CSS `currentColor` is suitable for generic SVG icons, not a replacement for the Canvas chart-theme API. +4. CSS custom properties hold runtime preferences. Sass variables and mixins run at build time; do not use them to implement live color or layout changes. Do not create per-preset selector copies of the same component when token inheritance is sufficient. +5. Respect contrast and focus. Keep border/outline fallbacks for forced colors, do not remove focus indication, and handle reduced motion at the specific transition/animation. Prefer opacity/transform for motion; avoid permanent `will-change` or JS frame loops for simple decoration. + +See the [reader's CSS recipe and host example](../apps/docs/guide/appearance.md#custom-css) for complete markup/styles rather than copying palette definitions into this guide. + +### Layout and responsive sizing + +`AdminShell` owns the live [layout properties](../packages/admin-shell/src/AdminShell.tsx) and [measured dimensions](../packages/admin-shell/src/layout-css-vars.ts): + +| Property | Meaning | +| ---------------------------- | -------------------------------------------------------------------------------------------------- | +| `--layout-content-padding` | Configured content padding. | +| `--layout-content-gutter` | Effective padding at the content container, including narrow-screen reduction. | +| `--layout-content-max-width` | Configured fixed maximum or `100%` for fluid content. Let the shell apply it. | +| `--layout-content-height` | Available vertical budget after measured header, tabs, and footer; maximized content overrides it. | + +Flow pages use natural height. A workspace that needs independent internal scrolling may use `calc(var(--layout-content-height, 100dvh) - 2 * var(--layout-content-gutter, 16px))`, then Flex/Grid with `min-block-size: 0` and an actual scroll owner. Prefer parent-provided height for components outside the shell. Do not add another `100vh` page inside the workspace or subtract guessed header/tab sizes. + +Use `minmax(0, 1fr)`, `min-inline-size: 0`, logical sizing/spacing, and content-container queries where available width matters. A query container belongs on an ancestor; use `container-type: inline-size`, not unnecessary size containment that collapses intrinsic height. Breakpoints are explicit content decisions, not invented theme variables: `var()` cannot be used as a media/container query threshold. Avoid treating the legacy `--layout-content-width` (currently measured from the header) as the definitive child width; use normal parent layout instead. + ## Page composition - Limit dashboard and explanatory demo content to 1360px and center it. Business tables continue to honor fluid/fixed-width layout preferences; do not narrow them globally. @@ -21,6 +76,13 @@ The template uses restrained blues and neutral colors. Refinement comes from con - Reuse Naive UI and template components before adding small layout structures. Do not invent statistics for visual effect. Read the dashboard version from the actual package configuration and derive shortcuts from visible menus. - Preserve distinct uses of shared components. For example, resource links remain compact on login pages and cards on the dashboard; visual consistency must not break existing page constraints. +## Loading feedback + +- Keep the startup splash self-contained in `apps/admin/index.html`: it must render before the application bundle, use the saved preset and color mode, and retain the bilingual failure/retry state. Animate only opacity and transforms; do not delay application mounting to make an animation visible. +- Content loading uses a thin indeterminate line and an unboxed label. It is feedback rather than an action; avoid borders, filled capsules, or button-like padding around the label. Preserve the 120ms delay for transient operations and immediate feedback while content is remounted. +- Use a labeled native `progress` element without a fabricated percentage. Routine intermediate loading does not need a live-region announcement. Decorative tracks remain hidden from assistive technology. +- Handle reduced motion at each animation: suppress the startup entrance and slow indeterminate movement to a gentle cycle. Do not force every animation to `0.01ms`, which can accelerate infinite effects. Keep system-color borders for progress tracks in forced-colors mode. + ## Verification Choose affected pages and dimensions using [Harness browser verification](../harness/README.md#browser-verification): desktop and 390px widths for layout changes, light/dark themes for color changes, Chinese/English for copy changes, and wrapping for changes to long code or button layouts. Local changes do not trigger a site-wide or all-dimensions matrix. Choose default body-text colors for at least 4.5:1 contrast and control boundaries such as inputs for at least 3:1. User-selected primary colors still need checking in their actual combinations. diff --git a/harness/context/layout.md b/harness/context/layout.md index 3fd82344..f4d20da8 100644 --- a/harness/context/layout.md +++ b/harness/context/layout.md @@ -4,7 +4,7 @@ Use this topic for providers, navigation layouts, page caching, the settings dra | Question | Read first | Follow through | | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Initial rendering, Wujie mounting, and global services | [Application bootstrap](../../apps/admin/src/main.ts), [App provider composition](../../apps/admin/src/App.tsx) | [Application providers](../../apps/admin/src/app-components/provider), [shared UI service interfaces](../../packages/ui/src/services.ts), [post-startup template checks](../../apps/admin/src/__ray-template/index.ts) | +| Initial rendering, Wujie mounting, and global services | [Application bootstrap](../../apps/admin/src/main.ts), [App provider composition](../../apps/admin/src/App.tsx) | [Application providers](../../apps/admin/src/app-components/provider), [shared UI service interfaces](../../packages/ui/src/services.ts), [development diagnostics](../../apps/admin/src/doctor/index.ts) | | Sidebar, top navigation, tabs, and search | [Application layout adapter](../../apps/admin/src/layout/index.tsx), [application navigation hook](../../apps/admin/src/hooks/template/useAppNavigation.ts) | [Shared AdminShell](../../packages/admin-shell/src/AdminShell.tsx), [host layout components](../../apps/admin/src/layout/components), [slot contract](../../apps/admin/src/layout/README.md) | | Content area, loading, navigation, and KeepAlive | [Host content slot](../../apps/admin/src/layout/default/ContentWrapper/index.tsx), [host transition adapter](../../apps/admin/src/components/RTransitionComponent) | [Shared transitions and cached rendering](../../packages/admin-shell/src/RouteTransition.vue), [cache allowlist](../../apps/admin/src/store/modules/keep-alive/index.ts), [page request cancellation](api.md) | | Layout preferences, JSON import/export, and transient state | [Settings store](../../apps/admin/src/store/modules/setting/index.ts), [preference-file validation](../../apps/admin/src/store/modules/setting/preference-file.ts), [runtime store](../../apps/admin/src/store/modules/runtime/index.ts) | [Host settings drawer](../../apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.tsx), [shared layout settings](../../packages/admin-shell/src/LayoutSettings.tsx), [reader guide](../../apps/docs/guide/layout.md) | diff --git a/harness/context/ui.md b/harness/context/ui.md index 159e63b1..c008f040 100644 --- a/harness/context/ui.md +++ b/harness/context/ui.md @@ -12,6 +12,8 @@ Use this topic when adding or changing pages, shared UI, themes, bilingual copy, The application's `@/components` and some hook/directive paths retain compatibility exports. Follow exports into the owning shared package before fixing common behavior. Inject host-specific services instead of referencing application aliases from shared packages. Add both Chinese and English for new interface copy. +For custom CSS, follow the [semantic-token and scope contract](../../docs/ui-design.md#custom-css), then use the [reader recipe](../../apps/docs/guide/appearance.md#custom-css) or [independent-host example](../../apps/docs/examples/ThemeScopeExample.vue). The authoritative token definitions remain in [theme.css](../../packages/ui/src/theme.css) and its [mapping](../../packages/ui/src/theme-presets.ts); do not copy preset palettes into page styles. + Before adding a component, check existing capabilities using the [Harness reuse conventions](../README.md#engineering-conventions). For full-height content and independent scrolling, start with [TablePro height styles](../../packages/ui/src/RTablePro/src/index.scss), [layout height variables](../../packages/admin-shell/src/layout-css-vars.ts), and the [user management page](../../apps/admin/src/views/user-management/index.tsx). `RTablePro autoHeight` uses `--r-table-height` to fill its host. Naive UI's `NCard contentScrollable` and `NScrollbar` handle scrolling; the parent uses Flex/Grid and `min-block-size: 0` to provide a definite height that can shrink. Targeted verification: for small fixes, run the relevant [component](../../__test__/components), [hook](../../__test__/hooks), or [cross-package consumer](../../__test__/workspace/consumer.spec.tsx) test file. Use `pnpm harness verify ui` for scope-level regression coverage; it runs Vitest without launching a browser. For visible effects or interactions, choose pages and dimensions using [Harness browser verification](../README.md#browser-verification). diff --git a/packages/composables/src/element.ts b/packages/composables/src/element.ts index cbe7412f..fa60f46c 100644 --- a/packages/composables/src/element.ts +++ b/packages/composables/src/element.ts @@ -184,7 +184,7 @@ export const removeStyle = ( * @param defaultColor 默认颜色值 * * @description - * 转换 rgb/hex/hsl 颜色;已有 rgba/hsla 会更新 alpha,四位和八位 hex 保留自带透明度。 + * 转换逗号分隔的 rgb/hsl 和 hex 颜色;rgba/hsla 会更新 alpha,四位和八位 hex 保留自带透明度。 * 无法识别时返回默认色或原始值。 */ export const colorToRgba = ( diff --git a/packages/composables/src/useDayjs.ts b/packages/composables/src/useDayjs.ts index a9c93427..1a96a155 100644 --- a/packages/composables/src/useDayjs.ts +++ b/packages/composables/src/useDayjs.ts @@ -22,9 +22,15 @@ export interface StartAndEndOfDay { const defaultDayjsFormat = 'YYYY-MM-DD HH:mm:ss' /** + * + * @param locales 应用语言键到 Day.js locale 的映射 + * @param fallback 未知语言键使用的 Day.js locale + * @param legacyGlobalLocale 是否兼容应用共享的 Day.js 全局语言 * * @description * 日期格式化使用本地时区;兼容模式沿用 Day.js 全局语言。 + * + * @returns 日期格式化、比较、范围与语言设置方法。 */ export const createDayjsTools = ( locales: Record, diff --git a/packages/composables/src/useDomToImage.ts b/packages/composables/src/useDomToImage.ts index e29548e0..c0c18fa0 100644 --- a/packages/composables/src/useDomToImage.ts +++ b/packages/composables/src/useDomToImage.ts @@ -1,33 +1,28 @@ -import { - toBlob, - toCanvas, - toJpeg, - toPixelData, - toPng, - toSvg, -} from 'html-to-image' +import type * as HtmlToImage from 'html-to-image' import type { BasicTarget, TargetType } from './types' import { unrefElement } from './vue/unref-element' // html-to-image 方法 const domToImageMethods = { - svg: toSvg, - png: toPng, - jpeg: toJpeg, - blob: toBlob, - pixelData: toPixelData, - canvas: toCanvas, + svg: 'toSvg', + png: 'toPng', + jpeg: 'toJpeg', + blob: 'toBlob', + pixelData: 'toPixelData', + canvas: 'toCanvas', } as const // 获取 html-to-image Options -type HtmlToImageOptions = Partial[1]>> +type HtmlToImageOptions = Partial< + NonNullable[1]> +> // 获取 html-to-image 方法 keys type DomToImageMethodKeys = keyof typeof domToImageMethods // 获取 html-to-image 方法返回值 type DomToImageReturnType = Awaited< - ReturnType<(typeof domToImageMethods)[ImageType]> + ReturnType<(typeof HtmlToImage)[(typeof domToImageMethods)[ImageType]]> > // 自定义拓展 Options @@ -62,6 +57,7 @@ export type UseDomToImageOptions< * * @description * 本次 create 的格式覆盖默认配置,缺省为 JPEG;created 可能收到不同格式的结果。 + * 渲染库在首次创建时按需加载,未使用截图的页面不必下载它。 * * @returns create 方法,其 Promise 结果类型跟随所选格式。 */ @@ -102,7 +98,8 @@ export const useDomToImage = < throw new Error('[useDomToImage]: target element is undefined.') const imageTypeKey = imageType ?? _imageType ?? 'jpeg' - const result = await domToImageMethods[imageTypeKey]( + const renderers = await import('html-to-image') + const result = await renderers[domToImageMethods[imageTypeKey]]( element, imageOptions, ) diff --git a/packages/composables/src/useElementFullscreen.ts b/packages/composables/src/useElementFullscreen.ts index 2128398e..77412cf4 100644 --- a/packages/composables/src/useElementFullscreen.ts +++ b/packages/composables/src/useElementFullscreen.ts @@ -48,9 +48,17 @@ export const useElementFullscreen = ( } = options ?? {} const isFullscreen = ref(false) + let disposed = false let frame: number | undefined let restore: (() => void) | undefined + /** + * + * @description + * 恢复进入前的样式并取消待执行动画帧;尚未进入时不操作。 + * + * @throws beforeExit 抛错时保留全屏;exit 回调的错误在样式恢复后传播。 + */ const exit = () => { if (!restore) return @@ -59,7 +67,16 @@ export const useElementFullscreen = ( onExit?.() } + /** + * + * @description + * 解析当前目标并进入 CSS 全屏;目标无效、已被占用或作用域已销毁时忽略。 + * + * @throws 前置回调或目标 getter 的错误会中止进入;enter 回调的错误在进入后传播。 + */ const enter = () => { + if (disposed) return + const element = unrefElement(target) if (!(element instanceof HTMLElement) || activeElements.has(element)) return @@ -130,12 +147,19 @@ export const useElementFullscreen = ( onEnter?.() } + /** + * + * @description + * 按当前实例状态调用 enter 或 exit,遵循对应回调与异常规则。 + */ const toggleFullscreen = () => { if (isFullscreen.value) exit() else enter() } effectDispose(() => { + disposed = true + if (!restore) return // 作用域销毁必须释放样式和动画帧,不允许前置回调取消。 diff --git a/packages/composables/src/usePagination.ts b/packages/composables/src/usePagination.ts index eaaa96f0..eca1611d 100644 --- a/packages/composables/src/usePagination.ts +++ b/packages/composables/src/usePagination.ts @@ -77,11 +77,17 @@ export const usePagination = ( 'onUpdate:page-size', 'onUpdate:pageSize', ]), + // 配置可通过返回的引用修改,默认候选不能跨实例共享可变数组。 + pageSizes: options?.pageSizes ?? [...DEFAULT_OPTIONS.pageSizes!], ...paginationMethods, })) // 分页配置 const paginationRef = ref(mergedOptions.value) + /** + * + * @returns 当前总条数;未设置时返回 0。 + */ const getItemCount = () => paginationRef.value.itemCount ?? 0 /** @@ -95,6 +101,10 @@ export const usePagination = ( paginationRef.value.itemCount = itemCount } + /** + * + * @returns 当前页码,初始默认值为 1。 + */ const getPage = () => paginationRef.value.page as number /** @@ -108,6 +118,10 @@ export const usePagination = ( paginationMethods.onUpdatePage(page) } + /** + * + * @returns 当前每页条数,初始默认值为 10。 + */ const getPageSize = () => paginationRef.value.pageSize as number /** @@ -121,6 +135,10 @@ export const usePagination = ( paginationMethods.onUpdatePageSize(pageSize) } + /** + * + * @returns 当前响应式配置本身;不创建快照,修改会影响当前实例。 + */ const getPagination = () => paginationRef.value as UsePaginationOptions /** @@ -143,7 +161,8 @@ export const usePagination = ( * 页码恢复为 1,每页条数取第一个选项的值;选项为空时使用 10。 */ const resetPagination = () => { - const { pageSizes, pageChange, pageSizeChange } = mergedOptions.value + const { pageChange, pageSizeChange } = mergedOptions.value + const { pageSizes } = paginationRef.value paginationRef.value.page = DEFAULT_OPTIONS.page const firstSize = pageSizes?.[0] diff --git a/packages/icons/ICON-SOURCES.md b/packages/icons/ICON-SOURCES.md index ccf22403..e612c590 100644 --- a/packages/icons/ICON-SOURCES.md +++ b/packages/icons/ICON-SOURCES.md @@ -6,64 +6,66 @@ 品牌标识沿用仓库已有的 SVG。不要将品牌标识与这批通用线性图标的来源或许可混用。 -| 图标路径 | 含义 | Iconfont ID | -| ------------------------- | ---------------- | ----------- | -| `action/adjustment` | 调节与密度 | 43971755 | -| `action/close` | 关闭 | 43971715 | -| `action/close_left` | 关闭左侧标签 | 43963762 | -| `action/close_other` | 关闭其他标签 | 43971709 | -| `action/close_right` | 关闭右侧标签 | 43963796 | -| `action/draggable` | 拖动 | 43970567 | -| `action/fullscreen` | 进入全屏 | 43970519 | -| `action/fullscreen_fold` | 退出全屏 | 43970505 | -| `action/lock` | 锁定 | 43970578 | -| `action/more` | 更多操作 | 43971752 | -| `action/mouse` | 鼠标与浏览器交互 | 43963496 | -| `action/out` | 退出 | 43963748 | -| `action/print` | 打印 | 43963390 | -| `action/reload` | 刷新与重试 | 43971771 | -| `action/search` | 搜索 | 43971773 | -| `action/setting` | 设置 | 43971792 | -| `action/shared` | 分享 | 43963969 | -| `action/add` | 新增 | 43971721 | -| `action/copy` | 复制 | 44587183 | -| `action/delete` | 删除 | 43970563 | -| `action/download` | 下载与导出 | 43963755 | -| `action/edit` | 编辑 | 43970366 | -| `action/filter` | 筛选 | 43970546 | -| `action/link` | 链接 | 43970476 | -| `action/upload` | 上传与导入 | 43963752 | -| `directional/enter` | 回车键 | 43963418 | -| `directional/expanded` | 下箭头与展开 | 43963753 | -| `directional/left_arrow` | 左箭头 | 43963808 | -| `directional/resize_h` | 水平调宽 | 43970706 | -| `directional/right_arrow` | 右箭头 | 43963720 | -| `directional/row_end` | 固定到末列 | 43970709 | -| `directional/row_head` | 固定到首列 | 43970682 | -| `navigation/dashboard` | 工作台 | 43970703 | -| `navigation/echart` | 图表与统计 | 43964136 | -| `navigation/menu` | 菜单 | 43971756 | -| `navigation/other` | 通用页面 | 43971760 | -| `navigation/rely` | 依赖关系 | 43963954 | -| `navigation/table` | 表格 | 43964166 | -| `navigation/appearance` | 外观与风格 | 43967447 | -| `navigation/barcode` | 条码 | 43967617 | -| `navigation/components` | 组件 | 43970685 | -| `navigation/database` | 缓存与数据 | 43964067 | -| `navigation/document` | 文档 | 43968045 | -| `navigation/flow` | 流程与层级 | 43963967 | -| `navigation/form` | 表单 | 43970427 | -| `navigation/icons` | 图标与资源 | 43970516 | -| `navigation/layout` | 页面布局 | 43970373 | -| `navigation/qr_code` | 二维码 | 43967582 | -| `navigation/routing` | 路由 | 43963960 | -| `navigation/window` | 窗口与嵌入页面 | 44567174 | -| `status/error` | 错误 | 43971705 | -| `status/question` | 帮助 | 43971699 | -| `status/success` | 成功 | 43971707 | -| `status/warning` | 注意 | 43971723 | -| `system/dark` | 深色模式 | 43964184 | -| `system/language` | 语言与翻译 | 43963919 | -| `system/light` | 浅色模式 | 43964181 | -| `system/system_os` | 跟随系统 | 43963546 | -| `system/watermark` | 水印与背景 | 43970747 | +| 图标路径 | 含义 | Iconfont ID | +| ------------------------- | ------------------ | ----------- | +| `action/adjustment` | 调节与密度 | 43971755 | +| `action/close` | 关闭 | 43971715 | +| `action/close_left` | 关闭左侧标签 | 43963762 | +| `action/close_other` | 关闭其他标签 | 43971709 | +| `action/close_right` | 关闭右侧标签 | 43963796 | +| `action/draggable` | 拖动 | 43970567 | +| `action/fullscreen` | 进入全屏 | 43970519 | +| `action/fullscreen_fold` | 退出全屏 | 43970505 | +| `action/lock` | 锁定 | 43970578 | +| `action/more` | 更多操作 | 43971752 | +| `action/mouse` | 鼠标与浏览器交互 | 43963496 | +| `action/out` | 退出 | 43963748 | +| `action/print` | 打印 | 43963390 | +| `action/reload` | 刷新与重试 | 43971771 | +| `action/search` | 搜索 | 43971773 | +| `action/setting` | 设置 | 43971792 | +| `action/shared` | 分享 | 43963969 | +| `action/add` | 新增 | 43971721 | +| `action/copy` | 复制 | 44587183 | +| `action/copy-image` | 截取区域并复制 PNG | 43970501 | +| `action/external-link` | 在外部页面打开 | 43971751 | +| `action/delete` | 删除 | 43970563 | +| `action/download` | 下载与导出 | 43963755 | +| `action/edit` | 编辑 | 43970366 | +| `action/filter` | 筛选 | 43970546 | +| `action/link` | 链接 | 43970476 | +| `action/upload` | 上传与导入 | 43963752 | +| `directional/enter` | 回车键 | 43963418 | +| `directional/expanded` | 下箭头与展开 | 43963753 | +| `directional/left_arrow` | 左箭头 | 43963808 | +| `directional/resize_h` | 水平调宽 | 43970706 | +| `directional/right_arrow` | 右箭头 | 43963720 | +| `directional/row_end` | 固定到末列 | 43970709 | +| `directional/row_head` | 固定到首列 | 43970682 | +| `navigation/dashboard` | 工作台 | 43970703 | +| `navigation/echart` | 图表与统计 | 43964136 | +| `navigation/menu` | 菜单 | 43971756 | +| `navigation/other` | 通用页面 | 43971760 | +| `navigation/rely` | 依赖关系 | 43963954 | +| `navigation/table` | 表格 | 43963947 | +| `navigation/appearance` | 外观与风格 | 43967447 | +| `navigation/barcode` | 条码 | 43967617 | +| `navigation/components` | 组件 | 43970685 | +| `navigation/database` | 缓存与数据 | 43964067 | +| `navigation/document` | 文档 | 43968045 | +| `navigation/flow` | 流程与层级 | 43963967 | +| `navigation/form` | 表单 | 43970427 | +| `navigation/icons` | 图标与资源 | 43970516 | +| `navigation/layout` | 页面布局 | 43970373 | +| `navigation/qr_code` | 二维码 | 43967582 | +| `navigation/routing` | 路由 | 43963960 | +| `navigation/window` | 窗口与嵌入页面 | 44567174 | +| `status/error` | 错误 | 43971709 | +| `status/question` | 帮助 | 43971699 | +| `status/success` | 成功 | 43971726 | +| `status/warning` | 注意 | 43971723 | +| `system/dark` | 深色模式 | 43964184 | +| `system/language` | 语言与翻译 | 43963919 | +| `system/light` | 浅色模式 | 43964181 | +| `system/system_os` | 跟随系统 | 43963546 | +| `system/watermark` | 水印与背景 | 43970747 | diff --git a/packages/icons/src/A_README.md b/packages/icons/src/A_README.md index cecb045f..c2c022ba 100644 --- a/packages/icons/src/A_README.md +++ b/packages/icons/src/A_README.md @@ -31,6 +31,8 @@ For ordinary buttons, `` uses the default 20 px bo See the [source and license inventory](../ICON-SOURCES.md). Legacy Excel export, Office, and login illustration icons were retired. Historical route/menu reads migrate them to download, table, and generic-page icons respectively. +Choose a glyph for the actual interaction: `navigation/table` denotes a data grid, `action/external-link` denotes an external destination, `action/shared` denotes sharing, and `action/copy-image` denotes region capture. Forward navigation uses a right arrow without rotating an expansion chevron. Status glyphs share a circular container and comparable optical size; keep that family coherent when adding states. + ## Generation and injection - Adding, editing, deleting, or moving an SVG causes the development server to check/synchronize `packages/icons/src/manifest.ts`. Adding/removing an entire group restarts the server automatically. diff --git a/packages/icons/src/action/copy-image.svg b/packages/icons/src/action/copy-image.svg new file mode 100644 index 00000000..e4c05184 --- /dev/null +++ b/packages/icons/src/action/copy-image.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/icons/src/action/external-link.svg b/packages/icons/src/action/external-link.svg new file mode 100644 index 00000000..9af92e9b --- /dev/null +++ b/packages/icons/src/action/external-link.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/packages/icons/src/manifest.ts b/packages/icons/src/manifest.ts index 13c2fb95..a1756485 100644 --- a/packages/icons/src/manifest.ts +++ b/packages/icons/src/manifest.ts @@ -8,10 +8,12 @@ export const iconNames = [ 'action/close_other', 'action/close_right', 'action/copy', + 'action/copy-image', 'action/delete', 'action/download', 'action/draggable', 'action/edit', + 'action/external-link', 'action/filter', 'action/fullscreen', 'action/fullscreen_fold', diff --git a/packages/icons/src/navigation/table.svg b/packages/icons/src/navigation/table.svg index ef2b906c..6d6cc2d2 100644 --- a/packages/icons/src/navigation/table.svg +++ b/packages/icons/src/navigation/table.svg @@ -1,7 +1,10 @@ - - - - - + + + + + + + + diff --git a/packages/icons/src/status/error.svg b/packages/icons/src/status/error.svg index 9133d9e3..942ea354 100644 --- a/packages/icons/src/status/error.svg +++ b/packages/icons/src/status/error.svg @@ -1,6 +1,8 @@ - - - - + + + + + + diff --git a/packages/icons/src/status/success.svg b/packages/icons/src/status/success.svg index b5c20370..036425e6 100644 --- a/packages/icons/src/status/success.svg +++ b/packages/icons/src/status/success.svg @@ -1,7 +1,7 @@ - - - - - + + + + + diff --git a/packages/routing/src/contract.ts b/packages/routing/src/contract.ts index edf9a8c9..239c13ec 100644 --- a/packages/routing/src/contract.ts +++ b/packages/routing/src/contract.ts @@ -13,8 +13,13 @@ export interface RouteCatalog { | { name: string; load: NonNullable } | undefined findRouteViewId(loader: unknown): string | undefined - homePath: string + /** + * + * @deprecated 首页不再具有路由校验或默认导航特权,保留字段仅兼容旧调用方。 + */ + homePath?: string managementPath: string + reservedPaths?: readonly string[] reservedNames?: readonly string[] } @@ -24,12 +29,16 @@ export function createRouteContract(catalog: RouteCatalog) { findRouteView, findRouteViewId, managementPath: ROUTE_MANAGEMENT_PATH, - homePath: DEFAULT_HOME_PATH, } = catalog + const reservedPaths = + catalog.reservedPaths?.map((path) => path.toLowerCase()) ?? [] const isReservedPath = (path: string) => path === '/' || path === ROUTE_MANAGEMENT_PATH || - path.startsWith(`${ROUTE_MANAGEMENT_PATH}/`) + path.startsWith(`${ROUTE_MANAGEMENT_PATH}/`) || + reservedPaths.some( + (reserved) => path === reserved || path.startsWith(`${reserved}/`), + ) const reservedNames = new Set( catalog.reservedNames?.map((name) => name.toLowerCase()), ) @@ -74,11 +83,7 @@ export function createRouteContract(catalog: RouteCatalog) { const menuPaths = new Set() const matchPatterns = new Set() - const visit = ( - records: RouteConfigRecord[], - parent = '', - restricted = false, - ) => { + const visit = (records: RouteConfigRecord[], parent = '') => { for (const record of records) { const { name, component, children, alias, redirect, props, meta } = record @@ -126,7 +131,7 @@ export function createRouteContract(catalog: RouteCatalog) { if (path.includes(':')) fail('Use static paths for menu groups.') - visit(children, path, restricted || !!meta.role?.length) + visit(children, path) continue } @@ -163,18 +168,6 @@ export function createRouteContract(catalog: RouteCatalog) { if (isReservedPath(key) || paths.has(key)) fail(`Duplicate or reserved path "${address}".`) - if ( - key === DEFAULT_HOME_PATH && - (address !== path || - path !== DEFAULT_HOME_PATH || - !view || - restricted || - meta.role?.length) - ) - fail( - '/dashboard must be a view accessible to all authenticated roles.', - ) - if (address !== path && (address.includes(':') || path.includes(':'))) fail('Aliases require a static page path.') diff --git a/packages/ui/src/RBarcode/src/Barcode.tsx b/packages/ui/src/RBarcode/src/Barcode.tsx index 293352e0..0dc52457 100644 --- a/packages/ui/src/RBarcode/src/Barcode.tsx +++ b/packages/ui/src/RBarcode/src/Barcode.tsx @@ -2,21 +2,9 @@ import './index.scss' import { completeSize } from '@ray-template/composables/element' import { call } from '@ray-template/composables/vue/call' import { useResizeObserver } from '@vueuse/core' -import type { UseResizeObserverReturn } from '@vueuse/core' import barcode from 'jsbarcode' import { NSpin } from 'naive-ui' -import { - computed, - defineComponent, - nextTick, - onBeforeUnmount, - onMounted, - ref, - useTemplateRef, - watch, - watchEffect, -} from 'vue' -import type { WatchStopHandle } from 'vue' +import { computed, defineComponent, ref, useTemplateRef, watch } from 'vue' import props from './props' export default defineComponent({ @@ -28,7 +16,6 @@ export default defineComponent({ ) const containerRef = useTemplateRef('containerRef') const containerSize = ref({ width: 0, height: 0 }) - let resizeObserverReturn: UseResizeObserverReturn | null const cssVars = computed(() => { let width = completeSize(props.width) @@ -49,8 +36,11 @@ export default defineComponent({ return cssVar }) - let watchStop: WatchStopHandle - + /** + * + * @description + * 在 DOM 更新后重绘当前条码;复用同一观察器,配置变化由 Vue 合并到一次渲染。 + */ const barcodeRender = () => { if (!barcodeRef.value) { return @@ -64,17 +54,12 @@ export default defineComponent({ }) // 如果是响应式模式,根据容器尺寸调整条形码选项 - if (containerSize.value.width > 0) { - if (props.width === 'responsive') { - assignOptions.width = Math.max(1, containerSize.value.width / 100) - } + if (props.width === 'responsive' && containerSize.value.width > 0) { + assignOptions.width = Math.max(1, containerSize.value.width / 100) + } - if (props.height === 'responsive') { - assignOptions.height = Math.max( - 20, - containerSize.value.height * 0.8, - ) - } + if (props.height === 'responsive' && containerSize.value.height > 0) { + assignOptions.height = Math.max(20, containerSize.value.height * 0.8) } barcode( @@ -101,57 +86,33 @@ export default defineComponent({ } } - watchEffect(() => { - if (props.watchText) { - watchStop?.() + useResizeObserver( + () => (props.responsive ? containerRef.value : null), + ([entry]) => { + if (!entry) return - watchStop = watch(() => props.text, barcodeRender) - } else { - watchStop?.() - } + const { width, height } = entry.contentRect + const previous = containerSize.value - // 监听容器尺寸变化 - if (props.responsive) { - resizeObserverReturn?.stop() + if (previous.width !== width || previous.height !== height) + containerSize.value = { width, height } + }, + ) - resizeObserverReturn = useResizeObserver( - containerRef, - (entries: readonly ResizeObserverEntry[]) => { - const entry = entries[0] - - if (entry) { - const { width, height } = entry.contentRect - - containerSize.value = { width, height } - - nextTick(() => { - barcodeRender() - }) - } - }, - ) - } else { - resizeObserverReturn?.stop() - - resizeObserverReturn = null - } - }) - - onMounted(() => { - // 初始化容器尺寸 - if (containerRef.value) { - const rect = containerRef.value.getBoundingClientRect() - - containerSize.value = { width: rect.width, height: rect.height } - } - - nextTick(() => { - barcodeRender() - }) - }) - onBeforeUnmount(() => { - watchStop?.() - }) + watch( + [ + barcodeRef, + () => (props.watchText ? props.text : void 0), + () => props.format, + () => props.options, + () => props.width, + () => props.height, + () => props.responsive, + containerSize, + ], + barcodeRender, + { deep: true, flush: 'post' }, + ) return { barcodeRef, diff --git a/packages/ui/src/RBarcode/src/props.ts b/packages/ui/src/RBarcode/src/props.ts index 6341d98a..2256546f 100644 --- a/packages/ui/src/RBarcode/src/props.ts +++ b/packages/ui/src/RBarcode/src/props.ts @@ -158,7 +158,7 @@ const props = { * @description * 是否启用响应式尺寸,当容器大小变化时自动重新渲染条形码。 * - * 如果启用了该属性,width 和 height 配置项将失效。 + * width 或 height 为 'responsive' 时按容器尺寸计算对应维度,固定尺寸仍然保留。 * * @default false */ diff --git a/packages/ui/src/RChart/src/hooks/useChart.ts b/packages/ui/src/RChart/src/hooks/useChart.ts index 5a5f0027..91d5ba80 100644 --- a/packages/ui/src/RChart/src/hooks/useChart.ts +++ b/packages/ui/src/RChart/src/hooks/useChart.ts @@ -4,30 +4,10 @@ import type { ECharts } from 'echarts/core' /** * * @description - * 获取 RChart 实例。 - * 让你能够便捷的调用相关的一些已封装方法。 + * 通过 RChart 的 onRegister 取得实例及组件拥有的重建、销毁方法。 + * 手动销毁后仍可通过 render 重建;真正的资源释放由组件负责。 * - * @warning - * 值得注意的是,必须手动调用 register 方法,否则不能正常使用。 - * 在使用 相关 hooks 的时候,需要注意生命周期,确保 register 方法已经被调用与表格实例已经被初始化; - * 不要在父组件 create 阶段就去调用 hook,如果需要,请使用 nextTick 包裹。 - * - * @example - * defineComponent({ - * setup() { - * const [register, { ...Hooks }] = useChart() - * - * return { - * register, - * ...Hooks, - * } - * }, - * render() { - * const { register, ...Hooks } = this - * - * return - * }, - * }) + * @returns 注册函数与实例访问、销毁、重建方法 */ const useChart = () => { let echartInst: ECharts @@ -36,7 +16,9 @@ const useChart = () => { /** * - * @param inst echart instance + * @param inst 当前 ECharts 实例 + * @param render 由组件提供的重建入口 + * @param dispose 由组件提供的销毁入口 * * @description * 注册当前 echart 实例,用于使用 useChart hook。 @@ -56,6 +38,9 @@ const useChart = () => { * * 如果未在调用前注册 onRegister 事件,则会抛出异常。 * + * @returns 实例及组件拥有的重建、销毁方法 + * @throws 尚未通过 onRegister 注册时抛错 + * * @example * const [register, { getChartInstance }] = useChart() * @@ -80,6 +65,9 @@ const useChart = () => { * @description * chart 是否已经销毁。 * 如果销毁则返回 true,否则返回 false。 + * + * @returns 最近注册的图表是否已销毁 + * @throws 尚未注册时抛错 */ const isDisposed = () => !!getChartInstance().echartInst?.isDisposed() @@ -87,6 +75,8 @@ const useChart = () => { * * @description * 销毁当前 chart 实例。 + * + * @throws 尚未注册时抛错 */ const dispose = () => getChartInstance().dispose.call(null) @@ -94,6 +84,8 @@ const useChart = () => { * * @description * 渲染当前 chart 实例。 + * + * @throws 尚未注册时抛错 */ const render = () => getChartInstance().render.call(null) diff --git a/packages/ui/src/RChart/src/hooks/useChartProvider.ts b/packages/ui/src/RChart/src/hooks/useChartProvider.ts index 34ac118b..e5927ba2 100644 --- a/packages/ui/src/RChart/src/hooks/useChartProvider.ts +++ b/packages/ui/src/RChart/src/hooks/useChartProvider.ts @@ -8,7 +8,7 @@ export interface ChartProviderOptions { /** * - * @param 配置项 + * @param options 提供给当前后代图表的配置 * * @description * 全局 chart 配置项。 diff --git a/packages/ui/src/RChart/src/themes/README.md b/packages/ui/src/RChart/src/themes/README.md index ef68ef12..9a25788f 100644 --- a/packages/ui/src/RChart/src/themes/README.md +++ b/packages/ui/src/RChart/src/themes/README.md @@ -9,6 +9,12 @@ Four styles live in `modern/`, `naive/`, `material/`, and `plain/`. Each has sep | Material | Purple tones, thicker lines, larger radii, and soft area fills | | Plain | Muted colors, dotted grids, square bars, and shadow-free tooltips | +The chart canvas matches the corresponding Naive UI card surface, including the warm Material and cool Modern dark surfaces. Title/body text, legends, axis labels, tooltip surfaces, and pie separators follow that same palette. Plain keeps low-saturation categorical colors instead of six indistinguishable gray series. The six-color sequences are designed as a set; a custom application primary color does not automatically replace a data series color. + +Use the active pointer color for crosshairs rather than copying the much softer divider/grid color. Naive and Plain need this distinction in both color modes. Text is checked at 4.5:1 and series/pointer marks at 3:1 against the chart canvas; alpha channels are composited first. Decorative area fills and grid lines stay subtle, while the pointer/tooltip communicates values. These checks do not certify every business chart: overlapping marks, color-vision differences, and values conveyed only by decorative grids require chart-specific review. Enable `showAria` for descriptions/decals, and supply accessible data where the visualization requires it. + +`__test__/components/chart-themes.spec.ts` checks all eight registration names, surface mappings, contrast pairs, and loading masks. Loading uses the selected theme's colors; transparent or invalid custom backgrounds fall back to a mode-appropriate surface, and explicit `loadingOptions` still take precedence. + When editing with the [ECharts theme builder](https://echarts.apache.org/zh/theme-builder.html), export JSON to the appropriate directory. The loader registers themes by filename; filenames must be unique even across directories. A light-only theme remains active for both modes. Adding a `-dark.json` variant enables switching with the application theme. Explicit colors/styles in business `options` still take precedence. Legacy `macarons` and `macarons-dark` themes were removed. Pages with hardcoded names can omit `theme` to follow the interface style or use a new theme registration name. diff --git a/packages/ui/src/RChart/src/themes/naive/ray-naive-dark.json b/packages/ui/src/RChart/src/themes/naive/ray-naive-dark.json index f07d02c1..ba8e3e33 100644 --- a/packages/ui/src/RChart/src/themes/naive/ray-naive-dark.json +++ b/packages/ui/src/RChart/src/themes/naive/ray-naive-dark.json @@ -53,11 +53,11 @@ }, "axisPointer": { "lineStyle": { - "color": "rgba(255, 255, 255, 0.24)", + "color": "rgba(255, 255, 255, 0.52)", "type": "solid" }, "crossStyle": { - "color": "rgba(255, 255, 255, 0.24)", + "color": "rgba(255, 255, 255, 0.52)", "type": "solid" }, "label": { diff --git a/packages/ui/src/RChart/src/themes/naive/ray-naive.json b/packages/ui/src/RChart/src/themes/naive/ray-naive.json index 442702e4..9bec3c94 100644 --- a/packages/ui/src/RChart/src/themes/naive/ray-naive.json +++ b/packages/ui/src/RChart/src/themes/naive/ray-naive.json @@ -53,11 +53,11 @@ }, "axisPointer": { "lineStyle": { - "color": "rgb(224, 224, 230)", + "color": "rgb(118, 124, 130)", "type": "solid" }, "crossStyle": { - "color": "rgb(224, 224, 230)", + "color": "rgb(118, 124, 130)", "type": "solid" }, "label": { diff --git a/packages/ui/src/RChart/src/themes/plain/ray-plain-dark.json b/packages/ui/src/RChart/src/themes/plain/ray-plain-dark.json index 97007c3a..c163d36a 100644 --- a/packages/ui/src/RChart/src/themes/plain/ray-plain-dark.json +++ b/packages/ui/src/RChart/src/themes/plain/ray-plain-dark.json @@ -53,11 +53,11 @@ }, "axisPointer": { "lineStyle": { - "color": "rgba(255, 255, 255, 0.24)", + "color": "rgba(255, 255, 255, 0.52)", "type": "dotted" }, "crossStyle": { - "color": "rgba(255, 255, 255, 0.24)", + "color": "rgba(255, 255, 255, 0.52)", "type": "dotted" }, "label": { diff --git a/packages/ui/src/RChart/src/themes/plain/ray-plain.json b/packages/ui/src/RChart/src/themes/plain/ray-plain.json index f744a747..c078e349 100644 --- a/packages/ui/src/RChart/src/themes/plain/ray-plain.json +++ b/packages/ui/src/RChart/src/themes/plain/ray-plain.json @@ -53,11 +53,11 @@ }, "axisPointer": { "lineStyle": { - "color": "rgb(224, 224, 230)", + "color": "#767676", "type": "dotted" }, "crossStyle": { - "color": "rgb(224, 224, 230)", + "color": "#767676", "type": "dotted" }, "label": { diff --git a/packages/ui/src/RChart/src/types.ts b/packages/ui/src/RChart/src/types.ts index 24df5dfc..f84d06e5 100644 --- a/packages/ui/src/RChart/src/types.ts +++ b/packages/ui/src/RChart/src/types.ts @@ -29,6 +29,13 @@ export interface LoadingOptions { export type ChartTheme = string | null +/** + * + * @description + * 保留旧版组件 ref 结构以兼容既有类型引用;当前 RChart 通过 onRegister 提供实例。 + * + * @deprecated 当前调用请使用 UseChartReturn,组件 ref 不实现此旧版结构。 + */ export interface RChartInst { /** * diff --git a/packages/ui/src/RChart/src/utils/get-custom-echart-theme.ts b/packages/ui/src/RChart/src/utils/get-custom-echart-theme.ts index a2728751..8af0d542 100644 --- a/packages/ui/src/RChart/src/utils/get-custom-echart-theme.ts +++ b/packages/ui/src/RChart/src/utils/get-custom-echart-theme.ts @@ -1,5 +1,13 @@ import type { ChartThemeRawArray } from '../types' +/** + * + * @description + * 读取随包构建的主题 JSON,以不含扩展名的文件名作为 ECharts 注册名。 + * + * @returns 可直接注册的主题名称与配置;明暗变体保留各自注册名。 + * @throws 不同目录中的主题文件同名时抛错,避免注册结果受遍历顺序影响。 + */ export const getCustomEchartTheme = (): ChartThemeRawArray[] => { const modules = import.meta.glob( '../themes/**/*.json', diff --git a/packages/ui/src/RChart/src/utils/loading-options.ts b/packages/ui/src/RChart/src/utils/loading-options.ts index f3d0677d..b592ff1b 100644 --- a/packages/ui/src/RChart/src/utils/loading-options.ts +++ b/packages/ui/src/RChart/src/utils/loading-options.ts @@ -1,19 +1,40 @@ import { color } from 'echarts/core' import type { ChartThemeRawArray, LoadingOptions } from '../types' +/** + * + * @param theme 已注册的图表主题;内建或缺失主题可不提供 + * @param dark 当前图表是否使用暗色模式 + * @param text 已翻译的加载文字 + * @param overrides 调用方指定的覆盖字段 + * + * @description + * 从图表主题生成加载层样式;透明或无效背景回退到当前明暗模式的表面色。 + * + * @returns 合并后的 ECharts 加载选项,调用方字段具有最高优先级。 + */ export const loadingOptions = ( theme: ChartThemeRawArray['theme'] | undefined, dark: boolean, text: string, overrides: Partial, ): LoadingOptions => { + const background = + typeof theme?.backgroundColor === 'string' + ? color.parse(theme.backgroundColor) + : void 0 + // transparent 的 RGB 分量为黑色,直接改透明度会在浅色图表上产生黑色遮罩。 + const mask = background?.[3] + ? background + : color.parse(dark ? '#172131' : '#fff')! + + mask[3] = 0.9 + return { text, color: theme?.color?.[0] ?? (dark ? '#aabaff' : '#3b63d9'), textColor: theme?.textStyle?.color ?? (dark ? '#e9eef7' : '#1d2a3e'), - maskColor: - color.modifyAlpha(theme?.backgroundColor, 0.9) ?? - (dark ? 'rgba(23, 33, 49, 0.9)' : 'rgba(255, 255, 255, 0.9)'), + maskColor: color.stringify(mask, 'rgba'), zlevel: 0, fontSize: 12, showSpinner: true, diff --git a/packages/ui/src/RChart/src/utils/set-echart-options.ts b/packages/ui/src/RChart/src/utils/set-echart-options.ts index 565baa80..31e6458b 100644 --- a/packages/ui/src/RChart/src/utils/set-echart-options.ts +++ b/packages/ui/src/RChart/src/utils/set-echart-options.ts @@ -1,9 +1,11 @@ /** - * - * @see https://echarts.apache.org/zh/api.html#echartsInstance.setOption * * @description * 获取 setOptions 方法默认配置规则。 + * + * @returns 每次独立创建的 ECharts 更新配置 + * + * @see https://echarts.apache.org/zh/api.html#echartsInstance.setOption */ export const setEchartOptions = () => ({ notMerge: true, diff --git a/packages/ui/src/RCollapseGrid/src/index.scss b/packages/ui/src/RCollapseGrid/src/index.scss index 03fd5634..54587e28 100644 --- a/packages/ui/src/RCollapseGrid/src/index.scss +++ b/packages/ui/src/RCollapseGrid/src/index.scss @@ -2,12 +2,22 @@ box-sizing: border-box; & .collapse-icon { + padding: 0; + border: 0; + background: none; + color: inherit; + font: inherit; height: 100%; display: flex; align-items: center; cursor: pointer; transition: color 0.3s var(--r-bezier); + &:focus-visible { + outline: 2px solid var(--r-primary-color, currentColor); + outline-offset: 4px; + } + > .collapse-icon--arrow { margin-left: 0.5em; transition: @@ -21,6 +31,13 @@ } } + @media (prefers-reduced-motion: reduce) { + .collapse-icon, + .collapse-icon > .collapse-icon--arrow { + transition: none; + } + } + .r-collapse-grid__suffix--btn { align-self: var(--r-collapse-grid-action-align); } diff --git a/packages/ui/src/RCollapseGrid/src/index.tsx b/packages/ui/src/RCollapseGrid/src/index.tsx index c5094ee4..136b4562 100644 --- a/packages/ui/src/RCollapseGrid/src/index.tsx +++ b/packages/ui/src/RCollapseGrid/src/index.tsx @@ -25,16 +25,21 @@ export default defineComponent({ modelCollapsed.value = !modelCollapsed.value if (onUpdateOpen) { - call(onUpdateOpen, modelCollapsed.value) + call(onUpdateOpen, !modelCollapsed.value) } if (_onUpdateOpen) { - call(_onUpdateOpen, modelCollapsed.value) + call(_onUpdateOpen, !modelCollapsed.value) } } const CollapseIcon = (collapse: boolean) => ( -
+
+ ) watchEffect(() => { @@ -81,8 +86,8 @@ export default defineComponent({ class="r-collapse-grid" {...($props as GridProps)} collapsed={modelCollapsed} - xGap={xGap || 12} - yGap={yGap || 12} + xGap={xGap ?? 12} + yGap={yGap ?? 12} collapsedRows={collapsedRows} > {defaultSlot?.()} diff --git a/packages/ui/src/RCollapseGrid/src/props.ts b/packages/ui/src/RCollapseGrid/src/props.ts index d7ac3cdb..b092b058 100644 --- a/packages/ui/src/RCollapseGrid/src/props.ts +++ b/packages/ui/src/RCollapseGrid/src/props.ts @@ -1,4 +1,4 @@ -import type { AnyFn, MaybeArray } from '@ray-template/utils/types' +import type { MaybeArray } from '@ray-template/utils/types' import { gridProps } from 'naive-ui' import type { PropType } from 'vue' import type { ActionAlignType, CollapseToggleText } from './types' @@ -29,11 +29,8 @@ const props = { open: { /** * - * 是否折叠操作栏 - * - * 默认折叠 - * - * `true` 收起, `false` 展开 + * @description + * 是否展开全部网格行,true 展开,false 收起;更新事件返回展开状态。 */ type: Boolean, default: false, @@ -55,7 +52,7 @@ const props = { * * 卡片边框 * - * 默认 `false` + * 默认 `true` */ type: Boolean, default: true, diff --git a/packages/ui/src/RDraggableCard/DraggableCard.tsx b/packages/ui/src/RDraggableCard/DraggableCard.tsx index 755be1a6..0b38432a 100644 --- a/packages/ui/src/RDraggableCard/DraggableCard.tsx +++ b/packages/ui/src/RDraggableCard/DraggableCard.tsx @@ -2,15 +2,14 @@ import type { PropType } from 'vue' import { computed, defineComponent, - nextTick, - onMounted, + onBeforeUnmount, + onUnmounted, useTemplateRef, - watchEffect, + watch, } from 'vue' import './index.scss' import { completeSize, queryElements } from '@ray-template/composables/element' import { unrefElement } from '@ray-template/composables/vue' -import type { AnyFn } from '@ray-template/utils/types' import type { MaybeElement } from '@vueuse/core' import interact from 'interactjs' import { cardProps, NCard } from 'naive-ui' @@ -44,7 +43,7 @@ const props = { * @default body */ restrictionElement: { - type: [String, HTMLElement, Function, Object] as PropType< + type: [String, Function, Object] as PropType< string | HTMLElement | (() => VNode) | MaybeRefOrGetter >, default: 'body', @@ -150,22 +149,23 @@ export default defineComponent({ } }) let isSetup = false - const cacheProps = { - defaultPosition: props.defaultPosition, - dad: props.dad, - } // 创建 DraggableCard 容器 const createDraggableCardContainer = () => { + if (typeof document === 'undefined') return null + if (!document.getElementById(CONTAINER_ID)) { const container = document.createElement('div') container.id = CONTAINER_ID - document.documentElement.appendChild(container) + container.dataset.rDraggableOwned = '' + document.body.appendChild(container) } + + return document.getElementById(CONTAINER_ID) } - createDraggableCardContainer() + const container = createDraggableCardContainer() // 获取 card, restrictionElement 的 dom 信息 const getDom = () => { @@ -328,41 +328,49 @@ export default defineComponent({ interactInst = null } - // 更新拖拽 - const refreshDraggableWhenPropsChange = (fn: AnyFn) => { - isSetup = false - - fn() - setupDraggable() - } - expose() - watchEffect(() => { - props.dad ? setupDraggable() : resetDraggable() + watch( + [ + cardRef, + () => props.dad, + () => props.defaultPosition, + () => props.padding, + () => props.restrictionElement, + () => props.restrictRectOptions, + ], + (values, previous) => { + // 开关拖拽保留当前位置;定位配置或实际节点替换时重新计算位置。 + if ([0, 2, 3, 4].some((index) => values[index] !== previous[index])) + isSetup = false - if (props.defaultPosition !== cacheProps.defaultPosition) { - refreshDraggableWhenPropsChange(() => { - cacheProps.defaultPosition = props.defaultPosition - }) - } - }) - - onMounted(() => { - nextTick(() => { + resetDraggable() setupDraggable() - }) + }, + { flush: 'post' }, + ) + onBeforeUnmount(resetDraggable) + onUnmounted(() => { + // 多个卡片共用容器,最后一个卸载后再释放组件创建的节点。 + if ( + container?.hasAttribute('data-r-draggable-owned') && + !container.childElementCount + ) + container.remove() }) return { cardRef, CONTAINER_ID, cssVars, + container, } }, render() { const { $attrs, $slots, $props, CONTAINER_ID, cssVars, animation } = this + if (!this.container) return null + return ( {animation ? ( diff --git a/packages/ui/src/RDraggableCard/index.scss b/packages/ui/src/RDraggableCard/index.scss index 278332e7..55351f24 100644 --- a/packages/ui/src/RDraggableCard/index.scss +++ b/packages/ui/src/RDraggableCard/index.scss @@ -17,6 +17,10 @@ .draggable-card-enter-active, .draggable-card-leave-active { transition: opacity 0.3s var(--r-bezier); + + @media (prefers-reduced-motion: reduce) { + transition: none; + } } .draggable-card-enter-from, diff --git a/packages/ui/src/RFlow/src/Flow.tsx b/packages/ui/src/RFlow/src/Flow.tsx index 41b058d7..d233affa 100644 --- a/packages/ui/src/RFlow/src/Flow.tsx +++ b/packages/ui/src/RFlow/src/Flow.tsx @@ -17,9 +17,6 @@ import { useTemplateRef } from 'vue' import props from './props' import type { FlowGraphData, G } from './types' -// 是否首次注册插件 -let isSetup = false - export default defineComponent({ name: 'RFlow', props, @@ -38,48 +35,37 @@ export default defineComponent({ }) // 流程图实例 const logicFlowInstRef = shallowRef() - // 需要禁用的流程图配置项 - const readonlyOptions = { - nodeTextEdit: false, - edgeTextEdit: false, - textEdit: false, - } + let editableConfig: ReturnType | undefined + let keyboardDisabled = false // 默认流程图数据 const defaultGraphData = { nodes: [], edges: [], } - // 注册流程图插件 - const registerExtension = () => { - if (!isSetup) { - props.use?.filter(Boolean).forEach((curr) => LogicFlow.use(curr)) - - isSetup = true - } - } - - // 动态根据 readonly 配置项修改流程图配置 + /** + * + * @param bool 是否启用只读模式 + * + * @description + * 进入只读前保存实例的交互配置,退出时恢复,避免覆盖调用方禁用的编辑项或快捷键。 + */ const updateFlowConfig = (bool: boolean) => { - if (!logicFlowInstRef.value) { - return + const instance = logicFlowInstRef.value + + if (!instance) return + + if (bool) { + editableConfig = instance.getEditConfig() + keyboardDisabled = instance.keyboard.disabled + instance.updateEditConfig({ isSilentMode: true }) + } else if (editableConfig) { + instance.updateEditConfig(editableConfig) + + if (keyboardDisabled) instance.keyboard.disable() + + editableConfig = void 0 } - - const ops = Object.entries(readonlyOptions).reduce( - (acc, [key]) => { - acc[key as keyof typeof acc] = !bool - - return acc - }, - {} as typeof readonlyOptions, - ) - - // 单独处理 isSilentMode 配置项 - Object.assign(readonlyOptions, ops, { - isSilentMode: bool, - adjustNodePosition: !bool, - }) - logicFlowInstRef.value.updateEditConfig(readonlyOptions) } /** @@ -92,14 +78,17 @@ export default defineComponent({ * 会自动忽略 container 属性,即使是配置了。 */ const setupFlowRender = (graphData?: FlowGraphData) => { - registerExtension() - if (!flowDomRef.value) { return } const { options, readonly } = props + // LogicFlow 按 pluginName 去重;后挂载实例仍需注册自己的插件。 + props.use + ?.filter(Boolean) + .forEach((extension) => LogicFlow.use(extension)) + // 初始化流程图实例 logicFlowInstRef.value = new LogicFlow({ container: unref(flowDomRef.value), @@ -112,13 +101,10 @@ export default defineComponent({ updateFlowConfig(readonly) } - watch( - () => props.data, - (data) => { - if (props.watchData && data) - logicFlowInstRef.value?.renderRawData(data as G) - }, - ) + watch([() => props.data, () => props.watchData], ([data, enabled]) => { + if (enabled) + logicFlowInstRef.value?.renderRawData((data ?? defaultGraphData) as G) + }) watch(() => props.readonly, updateFlowConfig) onMounted(() => { diff --git a/packages/ui/src/RFlow/src/constant.ts b/packages/ui/src/RFlow/src/constant.ts index e9210859..0e871e06 100644 --- a/packages/ui/src/RFlow/src/constant.ts +++ b/packages/ui/src/RFlow/src/constant.ts @@ -5,6 +5,8 @@ import type { FlowOptions } from './types' * @description * RFlow 默认初始化流程图配置项。 * 默认,使用组件内置的 container,所以会自动忽略该属性,即使是传递了。 + * + * @returns 当前实例独立的初始化配置及嵌套键盘选项 */ export const getDefaultFlowOptions = (): FlowOptions => { return { diff --git a/packages/ui/src/RFlow/src/hooks/useFlow.ts b/packages/ui/src/RFlow/src/hooks/useFlow.ts index 9a14e241..59383fac 100644 --- a/packages/ui/src/RFlow/src/hooks/useFlow.ts +++ b/packages/ui/src/RFlow/src/hooks/useFlow.ts @@ -1,11 +1,19 @@ import type LogicFlow from '@logicflow/core' +import { onScopeDispose } from 'vue' +/** + * + * @description + * 通过 RFlow 的 onRegister 取得当前实例,实例生命周期由组件负责。 + * + * @returns 注册函数与实例访问方法 + */ export const useFlow = () => { - let flowInst: LogicFlow + let flowInst: LogicFlow | undefined /** * - * @param inst flow instance + * @param inst 当前挂载的 LogicFlow 实例 * * @description * 注册当前 flow 实例,用于使用 useFlow hook。 @@ -13,6 +21,9 @@ export const useFlow = () => { const register = (inst: LogicFlow) => { if (inst) { flowInst = inst + onScopeDispose(() => { + if (flowInst === inst) flowInst = void 0 + }, true) } } @@ -23,6 +34,9 @@ export const useFlow = () => { * * 如果未在调用前注册 onRegister 事件,则会抛出异常。 * + * @returns 当前 LogicFlow 实例 + * @throws 未注册或组件已卸载时抛错 + * * @example * const [register, { getFlowInstance }] = useFlow() * diff --git a/packages/ui/src/RFlow/src/props.ts b/packages/ui/src/RFlow/src/props.ts index af532e72..af8d39c3 100644 --- a/packages/ui/src/RFlow/src/props.ts +++ b/packages/ui/src/RFlow/src/props.ts @@ -83,7 +83,7 @@ const props = { */ options: { type: Object as PropType, - default: getDefaultFlowOptions(), + default: getDefaultFlowOptions, }, /** * diff --git a/packages/ui/src/RForm/src/Form.tsx b/packages/ui/src/RForm/src/Form.tsx index 1b53f666..2b128499 100644 --- a/packages/ui/src/RForm/src/Form.tsx +++ b/packages/ui/src/RForm/src/Form.tsx @@ -1,38 +1,86 @@ import { call } from '@ray-template/composables/vue' -import { useEventListener } from '@vueuse/core' import { NForm, NSpin } from 'naive-ui' -import { computed, defineComponent, onMounted, useTemplateRef } from 'vue' -import type { ShallowRef } from 'vue' +import { + defineComponent, + onBeforeUnmount, + onMounted, + useTemplateRef, +} from 'vue' import props from './props' import type { RFormInst } from './types' export default defineComponent({ name: 'RForm', + inheritAttrs: false, props, setup(props, { expose }) { const formRef = useTemplateRef('formRef') - const currentSubmitFn = computed(() => props.onFinish ?? Promise.resolve) + let submitting = false + let disposed = false - const bindKeydownListener = (e: KeyboardEvent) => { - const keyCode = e.code + onBeforeUnmount(() => { + disposed = true + }) - if (keyCode === 'Enter') { - e.stopPropagation() - e.preventDefault() - - formRef.value?.validate().then(currentSubmitFn.value) - } - } - - if (props.submitWhenEnter) { - useEventListener( - formRef as unknown as ShallowRef, - 'keydown', - bindKeydownListener, - { - capture: true, - }, + /** + * + * @param event 表单内冒泡的键盘事件 + * + * @description + * 仅提交未被输入控件消费的单行 Enter;校验失败保留表单错误,提交异常交给 Vue 错误处理。 + */ + const submitOnEnter = async (event: KeyboardEvent) => { + if ( + !props.submitWhenEnter || + props.loading || + submitting || + event.defaultPrevented || + event.isComposing || + event.repeat || + event.key !== 'Enter' || + event.shiftKey || + event.ctrlKey || + event.altKey || + event.metaKey ) + return + + const target = event.target + + // 组合框的 Enter 用于选项确认,多行输入、按钮和可编辑区域保留原生行为。 + if ( + !(target instanceof HTMLInputElement) || + ![ + 'text', + 'search', + 'email', + 'url', + 'tel', + 'password', + 'number', + ].includes(target.type) || + target.closest('[role="combobox"], [contenteditable="true"]') || + !formRef.value + ) + return + + event.preventDefault() + submitting = true + + try { + let validation + + try { + validation = await formRef.value.validate() + } catch { + // Naive UI 已在字段上展示校验错误,键盘事件不再制造未处理的拒绝。 + return + } + + if (!disposed) await props.onFinish?.(validation) + } finally { + submitting = false + } } onMounted(() => { @@ -48,6 +96,7 @@ export default defineComponent({ return { formRef, + submitOnEnter, } }, render() { @@ -62,7 +111,12 @@ export default defineComponent({ height: 'auto', }} > - + {{ ...$slots, }} diff --git a/packages/ui/src/RForm/src/hooks/useForm.ts b/packages/ui/src/RForm/src/hooks/useForm.ts index 1a67c01b..f6c7fbef 100644 --- a/packages/ui/src/RForm/src/hooks/useForm.ts +++ b/packages/ui/src/RForm/src/hooks/useForm.ts @@ -1,7 +1,7 @@ import type { Recordable } from '@ray-template/utils/types' import { cloneDeep } from 'lodash-es' import type { Ref } from 'vue' -import { ref, shallowRef } from 'vue' +import { onScopeDispose, ref, shallowRef } from 'vue' import type { FormValidateCallback, RFormInst, @@ -10,32 +10,15 @@ import type { } from '../types' /** + * + * @param model 初始模型或每次创建模型的工厂 + * @param rules 校验规则或每次创建规则的工厂 * * @description - * 获取 RForm 实例。 - * 让你能够便捷的调用相关的一些已封装方法。 + * 管理表单模型、规则与实例方法。对象输入深拷贝,工厂自行保证返回独立对象; + * 实例操作必须先通过 RForm 的 onRegister 绑定注册函数。 * - * @warning - * 值得注意的是,必须手动调用 register 方法,否则不能正常使用。 - * 在使用 相关 hooks 的时候,需要注意生命周期,确保 register 方法已经被调用与表格实例已经被初始化; - * 不要在父组件 create 阶段就去调用 hook,如果需要,请使用 nextTick 包裹。 - * - * @example - * defineComponent({ - * setup() { - * const [register, { ...Hooks }] = useForm() - * - * return { - * register, - * ...Hooks, - * } - * }, - * render() { - * const { register, ...Hooks } = this - * - * return - * }, - * }) + * @returns 注册函数、响应式模型与表单操作方法 */ const useForm = < T extends Recordable = Recordable, @@ -47,12 +30,30 @@ const useForm = < const formRef = shallowRef() const formModelRef = ref() + /** + * + * @param inst 挂载后的 Naive UI 表单实例 + * + * @description + * 注册表单,并在所属组件卸载时清理同一实例的引用。 + */ const register = (inst: RFormInst) => { if (inst) { formRef.value = inst + onScopeDispose(() => { + if (formRef.value === inst) formRef.value = void 0 + }, true) } } + /** + * + * @description + * 读取已注册且仍挂载的表单。 + * + * @returns 当前表单实例 + * @throws 未注册或表单已卸载时抛错 + */ const getFormInstance = () => { if (!formRef.value) { throw new Error( @@ -63,7 +64,11 @@ const useForm = < return formRef.value } - // 初始化 formModelRef 的值,根据 model 的类型进行初始化 + /** + * + * @description + * 为当前 Hook 建立初始模型;对象输入深拷贝,工厂结果直接使用。 + */ const initialFormModel = () => { if (typeof model === 'function') { formModelRef.value = model() ?? ({} as T) @@ -73,10 +78,16 @@ const useForm = < } /** + * + * @param callback 校验完成回调 + * @param shouldRuleBeApplied 选择本次需要执行的规则 * * @description * 验证表单,Promise rejection 的返回值类型是 FormValidationError[]。 * + * @returns Naive UI 校验 Promise + * @throws 尚未注册时抛错,校验失败时 Promise 拒绝 + * * @see https://www.naiveui.com/zh-CN/dark/components/form#inline.vue */ const validate = ( @@ -89,6 +100,8 @@ const useForm = < * @description * 还原表单到未验证状态。 * + * @throws 尚未注册或表单已卸载时抛错 + * * @see https://www.naiveui.com/zh-CN/dark/components/form#Form-Methods */ const restoreValidation = () => getFormInstance().restoreValidation.call(null) @@ -137,6 +150,8 @@ const useForm = < * 获取验证表单项的规则。 * * 调用该方法时,需要确保初始化 useForm 方法的时候传入了 rules,否则可能有意想不到的问题发生。 + * + * @returns 工厂返回的规则或初始化规则的深拷贝,未配置时为空对象 */ const formRules = () => { if (typeof rules === 'function') { @@ -150,10 +165,6 @@ const useForm = < * * @param values 需要重置的表单值,该参数会覆盖初始化值 * - * @warning - * 请注意初始化值的问题,如果设置初始化值为 undefined, - * 则会导致 reset 初始化操作失败,必须使用 null 作为初始化的空值。 - * * @description * 重置表单的值,依赖 useForm 传入的初始化值。 * 该方法会将初始化传入的值视为整个表单的初始化绑定值。 @@ -162,7 +173,7 @@ const useForm = < * 所以,最佳的实践应该是初始化 useForm 方法的时候,就应该确定好初始化值。 * 然后,在需要重置表单的时候,直接调用该方法即可。 */ - const reset = (values?: Values & Recordable) => { + const reset = = Partial>(values?: Values) => { formModelRef.value = Object.assign( formModelRef.value as T, formModel(), @@ -183,6 +194,9 @@ const useForm = < * 注意,该方法想要正常运转,需要在定义 rules 时定义唯一 key; * 否则,该逻辑执行会失败。 * + * @returns 匹配规则的校验 Promise + * @throws key 为空、实例不可用时抛错,校验失败时 Promise 拒绝 + * * @example * const [register, { validateTargetField }] = useForm( * { @@ -214,10 +228,11 @@ const useForm = < } /** + * + * @param values 需要浅合并到当前模型的字段,不修改初始模型 * * @description - * 更新表单的值,该方法会覆盖初始化值。 - * 推荐在表单组件中使用该方法,而不是直接修改表单的值,符合函数式的理念。 + * 更新当前模型,保留对象引用和未提供的字段。 * * @example * const [register, { updateFormCondition }] = useForm( @@ -230,7 +245,7 @@ const useForm = < * name: 'John', * }) */ - const updateFormCondition = (values: T & Recordable) => { + const updateFormCondition = (values: Partial) => { formModelRef.value = Object.assign(formModelRef.value as T, values) } diff --git a/packages/ui/src/RForm/src/props.ts b/packages/ui/src/RForm/src/props.ts index 4aadffda..ae757599 100644 --- a/packages/ui/src/RForm/src/props.ts +++ b/packages/ui/src/RForm/src/props.ts @@ -44,12 +44,8 @@ const props = { * 是否在按下回车键时自动触发表单的校验,如果校验成功则会自动触发 onFinish 事件。 * 该功能需要结合 onFinish 属性使用。 * - * 注意,该属性不支持响应式更新,只依赖于初始化传入的值; - * 因为该方法特性的原因,做响应式的更新意义不大。 - * - * 并且该属性启用后,会自动的拦截 Enter 键的默认行为; - * 例如 NSelect, NInput 等官方自带组件的默认快捷键功能,都会被阻止; - * 但是不得不这么做,以避免一些奇奇怪怪的问题。 + * 支持动态切换;仅处理单行输入,保留输入法确认、多行换行、组合框与按钮的原生行为。 + * 校验或提交仍在进行时忽略重复 Enter,loading 时不触发。 * * @default false */ diff --git a/packages/ui/src/RIcon/src/index.scss b/packages/ui/src/RIcon/src/index.scss index fe1cbd53..fd02b3ca 100644 --- a/packages/ui/src/RIcon/src/index.scss +++ b/packages/ui/src/RIcon/src/index.scss @@ -10,7 +10,6 @@ justify-content: center; align-items: center; color: var(--r-icon-color); - transform: translateZ(0); opacity: var(--r-icon-depth); cursor: var(--r-icon-cursor); @@ -26,6 +25,11 @@ stroke-dasharray: var(--r-icon-path-length); stroke-dashoffset: var(--r-icon-path-length); animation: rayIconPathAnimate 2s forwards; + + @media (prefers-reduced-motion: reduce) { + animation: none; + stroke-dashoffset: 0; + } } @keyframes rayIconPathAnimate { diff --git a/packages/ui/src/RIframe/src/Iframe.tsx b/packages/ui/src/RIframe/src/Iframe.tsx index 4f4f2712..214ed531 100644 --- a/packages/ui/src/RIframe/src/Iframe.tsx +++ b/packages/ui/src/RIframe/src/Iframe.tsx @@ -1,4 +1,4 @@ -import { computed, defineComponent, ref } from 'vue' +import { computed, defineComponent, ref, watch } from 'vue' import './index.scss' import { completeSize } from '@ray-template/composables/element' import { call } from '@ray-template/composables/vue' @@ -23,6 +23,13 @@ export default defineComponent({ const iframeRef = useTemplateRef('iframeRef') const spinShow = ref(true) + watch( + () => props.src, + () => { + spinShow.value = true + }, + ) + const iframeLoadSuccess = (e: Event) => { spinShow.value = false @@ -47,6 +54,7 @@ export default defineComponent({ useEventListener(iframeRef, 'error', iframeLoadError) expose({ + iframe: iframeRef, iframeInst: iframeRef, }) diff --git a/packages/ui/src/RIframe/src/types.ts b/packages/ui/src/RIframe/src/types.ts index 61148fdc..f5037557 100644 --- a/packages/ui/src/RIframe/src/types.ts +++ b/packages/ui/src/RIframe/src/types.ts @@ -1,7 +1,8 @@ -import type { Ref } from 'vue' - export interface RIframeInst { - iframe: Ref + /** 组件 ref 自动解包后的原生 iframe,挂载前或卸载后为 null */ + readonly iframe: HTMLIFrameElement | null + /** 保留已有运行时名称,与 iframe 指向同一元素 */ + readonly iframeInst: HTMLIFrameElement | null } export type Lazy = 'lazy' | 'eager' | undefined diff --git a/packages/ui/src/RModal/src/hooks/useModal.ts b/packages/ui/src/RModal/src/hooks/useModal.ts index b2e202c7..4b3986ed 100644 --- a/packages/ui/src/RModal/src/hooks/useModal.ts +++ b/packages/ui/src/RModal/src/hooks/useModal.ts @@ -10,17 +10,28 @@ import { CSS_VARS_KEYS, R_MODAL_CLASS } from '../constant' import type { RModalProps } from '../types' /** + * + * @description + * 保留历史 RModal 命令式入口;新代码应使用 Naive UI 的 useModal 或声明式 RModal。 + * + * @returns 创建弹窗与关闭全部弹窗的方法 * * @deprecated * * @see https://www.naiveui.com/zh-CN/dark/components/modal#useModal-API - * - * @description - * 请使用官方的 `useModal` 方法。 */ const useModal = () => { const { create: naiveCreate, destroyAll: naiveDestroyAll } = useNaiveModal() + /** + * + * @param options Naive UI 弹窗配置及模板尺寸、全屏配置 + * + * @description + * 由 Naive UI 创建并管理弹窗,DOM 就绪后补充模板尺寸样式;提前关闭时跳过补充。 + * + * @returns Naive UI 弹窗响应式句柄 + */ const create = (options: RModalProps) => { const { content, ...rest } = options let contentNode = content diff --git a/packages/ui/src/RModal/src/index.scss b/packages/ui/src/RModal/src/index.scss index ad16e987..1cb4f252 100644 --- a/packages/ui/src/RModal/src/index.scss +++ b/packages/ui/src/RModal/src/index.scss @@ -10,6 +10,8 @@ } .r-modal { + width: var(--r-modal-width); + &.n-card { width: var(--r-modal-card-width); } diff --git a/packages/ui/src/RMoreDropdown/src/MoreDropdown.tsx b/packages/ui/src/RMoreDropdown/src/MoreDropdown.tsx index 9ea16941..adb7b447 100644 --- a/packages/ui/src/RMoreDropdown/src/MoreDropdown.tsx +++ b/packages/ui/src/RMoreDropdown/src/MoreDropdown.tsx @@ -1,25 +1,36 @@ import { renderNode } from '@ray-template/composables/vue' -import { NDropdown } from 'naive-ui' +import { NButton, NDropdown } from 'naive-ui' import type { DropdownProps } from 'naive-ui' import { defineComponent } from 'vue' import { RIcon } from '../../RIcon' +import { useUiServices } from '../../services' import props from './props' export default defineComponent({ name: 'RMoreDropdown', props, + setup() { + return { translate: useUiServices().translate } + }, render() { const { iconSize, cursor, icon } = this const { default: $default } = this.$slots return ( - + {renderNode($default, { - defaultElement: , + defaultElement: ( + + + + ), })} ) diff --git a/packages/ui/src/RMoreDropdown/src/props.ts b/packages/ui/src/RMoreDropdown/src/props.ts index a072391e..2054ab2f 100644 --- a/packages/ui/src/RMoreDropdown/src/props.ts +++ b/packages/ui/src/RMoreDropdown/src/props.ts @@ -4,6 +4,10 @@ import type { PropType } from 'vue' const props = { ...dropdownProps, + placement: { + ...dropdownProps.placement, + default: 'bottom-start', + }, icon: { type: String as PropType, default: 'action/more', @@ -11,6 +15,8 @@ const props = { iconSize: { type: Number, }, + /** 默认图标按钮的可访问名称,自定义触发插槽自行提供名称 */ + triggerLabel: String, cursor: { type: String, default: 'inherit', diff --git a/packages/ui/src/RSegment/src/Segment.tsx b/packages/ui/src/RSegment/src/Segment.tsx index 3f67277c..3dcd65ad 100644 --- a/packages/ui/src/RSegment/src/Segment.tsx +++ b/packages/ui/src/RSegment/src/Segment.tsx @@ -10,17 +10,18 @@ import type { RSegmentOptions } from './types' const iconSegmentTab = (option: RSegmentOptions) => { const { icon, label } = option + const content = typeof label === 'function' ? label() : label if (icon) { return ( {typeof icon === 'function' ? icon() : icon} -
{label}
+
{content}
) } - return label + return content } const popoverSegmentTab = (option: RSegmentOptions) => { @@ -107,7 +108,7 @@ export default defineComponent({ !curr.popover ? iconSegmentTab(curr) : popoverSegmentTab(curr) } disabled={curr.disabled} diff --git a/packages/ui/src/RSegment/src/types.ts b/packages/ui/src/RSegment/src/types.ts index 7ce1616a..31653269 100644 --- a/packages/ui/src/RSegment/src/types.ts +++ b/packages/ui/src/RSegment/src/types.ts @@ -60,6 +60,6 @@ export interface RSegmentOptions { export type RSegmentWidth = number | 'block' | 'fitContent' export interface RSegmentProps extends Omit { - options?: RSegmentOptions + options?: RSegmentOptions[] width?: RSegmentWidth } diff --git a/packages/ui/src/RTablePro/README.md b/packages/ui/src/RTablePro/README.md index fa4edea2..09aac4f9 100644 --- a/packages/ui/src/RTablePro/README.md +++ b/packages/ui/src/RTablePro/README.md @@ -26,7 +26,8 @@ import { RTablePro } from '@/components' - 行标识默认取 `row.id` 或 `row.key`,其他字段使用 `rowKey`。宽表可设置 `scrollX` 和列宽,横向滚动留在表格内部。根列拖动或固定时保留分组的子列。 - `autoHeight` 默认使用当前布局的可用高度,宿主外部使用视口高度;嵌入特定区域时可以用 CSS 变量 `--r-table-height` 覆盖。较短的屏幕保留表格的最小操作高度。 - 只接收最新的请求结果。切换请求源或有效筛选条件会立即清空旧行和总数;切页或修改每页条数会隐藏旧行并保留同一范围的总数。当前页未加载时,实例取数返回空、底层实例返回 `null`,CSV 和打印不会启动。请求失败后显示空态并清空总数,通过宿主 Toast 提醒。可用 `onRequestError` 接收详情、用实例 `reload()` 重试,或显式提供 `error` 插槽接管提示。 -- 需要实例时使用 `shallowRef()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。 +- 需要实例时使用 `shallowRef()`。实例提供 `reload(resetPage?)`、`setPage`、`setPageSize`、`getCurrentPageData`、`downloadCsv`、`print`、`copyImage` 和 `getTableInstance`。额外区域可用 `toolbar`、`tableFooter`、`tableAction` 插槽。 +- 工具栏将业务 `toolbar` 插槽与内置工具分组。`request` 模式提供刷新,列设置、复制图片和全屏保持直接入口;「更多操作」统一收纳密度、斑马纹、边框与 CSV。打印默认隐藏,设置 `showPrint` 后出现在该菜单。`tool={false}` 隐藏全部内置工具,仍保留业务插槽。 ## 注册 Hook @@ -58,11 +59,42 @@ const reloadFromFirstPage = () => reload(true) - 使用 Naive UI 的列 `key`,同一表的列 key 唯一且稳定。勾选状态独立于列定义;列分组会跟随子列,选择列和展开列不会被勾选隐藏。至少保留一个数据列。 - 缓存是按表格标识分隔的本地偏好。只保存隐藏列的 key,启用或切换标识时读一次,用户改动时才写入。新增列默认显示,失效 key 不影响渲染,恢复全部列会清除缓存。不传标识时仅保留实例内状态。需要按账号或租户隔离时,将其标识纳入 key。 - 页面需要接管列顺序、固定位置或 `resizable` 时,可以用 `v-model:columns`;收到的是完整列定义,包含已隐藏的列。显隐始终由列设置维护,固定列仍遵守 Naive UI 的数字列宽约定。 +- 在列设置中固定或取消固定分组时,同步更新该组所有后代的 `fixed`,使表头和表体保持一致;列宽、渲染器、调整宽度等其它配置保持不变。分组固定要求全部叶子列具有数字宽度。本地与受控模式使用相同规则,均不修改调用方的原始列定义。 - 「恢复列布局」恢复根列顺序、固定和调整宽度开关,保留隐藏列;「恢复全部列」只恢复显隐。受控列由调用方提供 `onResetColumnLayout` 并应用自己的初始定义,未提供时不显示恢复布局按钮。 - 不缓存行数据、列定义、回调、列宽、固定或顺序。默认模式用列 key 维护实例内的调整;更新列标题、渲染器等定义不会抹掉用户调整。 +## 复制表格图片 + +默认工具栏提供「复制表格图片」,将当前 `NDataTable` 的表头、行、内部滚动可视区域及原生分页器复制为 PNG。图片不包括 TablePro 标题、搜索区、工具栏、提示区、`tableFooter` 或 `tableAction`。这是表格自身的 DOM 可视盒,不是整张网页的屏幕截图,也不会为复制主动滚动或加载其它页。虚拟滚动只包含已渲染且位于可视盒内的内容;需要完整当前页数据时使用 CSV 或打印。 + +```tsx +const [register, { copyImage }] = useTablePro() + + + +// 直接在用户点击回调里调用,不要先等待其它异步操作。 + void copyImage()}>复制图片 +``` + +`showCopyImage={false}` 隐藏内置按钮,不影响实例或 Hook 的 `copyImage(options?)`。默认分辨率使用设备像素比并限制为最高 2,`copyImageOptions` 和单次参数可覆盖 `pixelRatio`、`backgroundColor`、尺寸、`style`、`filter`、字体及资源请求选项;单次参数优先。输出固定为 PNG,不接收格式、JPEG quality 或渲染生命周期回调。`filter` 处理临时快照中的节点,应按类名或数据属性判断,而不要比较原始 DOM 对象身份。 + +复制成功返回 `true`;加载中、重复调用、未确认的远端数据、取消或失败返回 `false`。组件使用原生 Clipboard API,在点击调用栈内把 PNG Promise 交给 `ClipboardItem`,随后按需加载现有渲染库。需要浏览器支持及 HTTPS/localhost,权限被拒绝时显示对应反馈。独立使用时在表格旁显示状态,宿主可通过 `UiServices.reportSuccess/reportError` 接管。外部图片、字体或受保护的画布可能使渲染失败,可配置资源请求或占位图。 + +快照保留当前滚动位置与固定列;成功、失败、数据替换和卸载均清理临时节点,重复操作不会启动并行截图。取消会阻止尚未就绪的图片交给剪贴板,但无法撤销浏览器已经接受的写入。 + +RIcon 外部精灵图和本地 `#symbol` 会在快照中展开为独立静态 SVG,保留视口尺寸与 `currentColor`,移除导入 ID,避免多行图标互相干扰。只读取同源注册精灵图或公共 `.svg` 文件,不携带凭据、不跟随重定向;每次最多 16 个资源,每个最多 1 MiB,并共用同一取消信号。展开路径支持静态几何和呈现属性,不提供嵌套引用、paint server、样式表或动态 CSS 值(`var/env/attr`)的兼容。 + +快照连接到文档前移除脚本和内联事件属性。`iframe/object/embed/audio/video` 嵌入内容会明确拒绝,避免在临时副本中重新启动活动内容;普通图片与 canvas 仍沿用上述资源策略。 + ## 打印和 CSV +打印入口默认隐藏。业务页面可用 `showPrint` 在「更多操作」中启用打印;实例 `print(options?)` 始终可由业务显式调用。CSV 入口位于同一菜单。 + 内置打印按当前排序、筛选和分页打印**当前页数据和可见列**。使用单独的白底 HTML 表格,跨纸页重复表头;不打印搜索、操作、复选框、展开区、分页或插槽。虚拟滚动不影响取数。需要特殊单元格文本时用 `formatCell`;未配置时沿用 `getCsvCell` 或字段值。自定义 Vue 单元格、树展开状态和合并格不会复刻为打印布局;需要复刻时指定自定义区域。 ```tsx @@ -70,6 +102,7 @@ const reloadFromFirstPage = () => reload(true) columns={columns} data={rows} printTableOptions={{ target: reportRef }} + showPrint /> ``` @@ -79,6 +112,8 @@ CSV 默认导出当前页可见数据列;`keepOriginalData` 使用传入的整 ## Naive UI 的配置边界 +分页配置使用 `TableProPagination`:请将旧 `pagination.onChange` 改为 `onUpdatePage`(或 `onUpdate:page`),将 `pagination.onPageSizeChange` 改为 `onUpdatePageSize`(或 `onUpdate:pageSize`)。TablePro 顶层旧 `onPageChange/onPageSizeChange` 同样迁移到对应更新事件。旧字段不再调用,也不会被继续透传给 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`,由调用方负责切换范围时清空旧数据。本地和手动远端受控模式由调用方在分页回调中更新 `pagination.page/pageSize`;搜索重置和实例操作也会触发同一回调。服务端排序、过滤继续使用 Naive UI 的事件,在调用方将条件传给 `params`,组件不会推断接口字段。页数很大时可配置 `pagination.showQuickJumpDropdown: false`。 在「表格 → 高级搜索」可以切换本地筛选和模拟远端查询,查看日期区间拆分和组织到负责人的联动。配置、值类型和实例方法见[高级搜索参考](../../../../apps/docs/reference/table-pro.md#高级搜索)。在「表格」菜单下也可以查看查询与分页、选择与批量操作、导出与打印三个 Hooks 示例。 diff --git a/packages/ui/src/RTablePro/index.ts b/packages/ui/src/RTablePro/index.ts index 7614abd6..08ad54a8 100644 --- a/packages/ui/src/RTablePro/index.ts +++ b/packages/ui/src/RTablePro/index.ts @@ -18,4 +18,6 @@ export type { TableProSearchValue, TableProSearchValues, TableProPrintOptions, + TableProImageOptions, + TableProPagination, } from './src/types' diff --git a/packages/ui/src/RTablePro/src/TablePanel.tsx b/packages/ui/src/RTablePro/src/TablePanel.tsx index 7afd3581..684dc198 100644 --- a/packages/ui/src/RTablePro/src/TablePanel.tsx +++ b/packages/ui/src/RTablePro/src/TablePanel.tsx @@ -10,17 +10,19 @@ import { } from 'vue' import { useUiServices } from '../../services' import './index.scss' +import { unrefElement } from '@ray-template/composables/vue' import { useElementSize } from '@vueuse/core' import { NDataTable, NDropdown, useThemeVars } from 'naive-ui' -import type { DataTableInst, DataTableProps } from 'naive-ui' +import type { DataTableInst, DataTableProps, DropdownProps } from 'naive-ui' import { useTemplateRef } from 'vue' +import type { ComponentPublicInstance } from 'vue' +import { RIcon } from '../../RIcon' import { useColumnLayout, useColumnVisibility } from './columns' -import AppearanceSettings from './components/AppearanceSettings' import ColumnSettings from './components/ColumnSettings' import Fullscreen from './components/Fullscreen' -import Size from './components/Size' import ToolButton from './components/ToolButton' import { buildTableCsv, downloadTableCsv } from './csv' +import { copyTableImage } from './image' import { useTableLocale } from './locale' import { buildPrintableTable, @@ -29,12 +31,17 @@ import { } from './printing' import { tablePanelProps, toNativeTableProps } from './props' import { config } from './shared' -import type { - PropsComponentPopselectKeys, - TablePanelInst, - TableProRowContext, -} from './types' +import type { TablePanelInst, TableProRowContext } from './types' +/** + * + * @param prop 外部属性读取器 + * + * @description + * 外部值改变前允许面板持有本地覆盖,外部更新后自动回归调用方配置。 + * + * @returns 可写的当前展示值 + */ const useLocalOverride = (prop: () => Value) => { const source = computed(() => ({ value: prop() })) const local = shallowRef<{ source: typeof source.value; value: Value }>() @@ -56,7 +63,7 @@ export default defineComponent({ props: tablePanelProps, setup(props, { attrs, slots, expose }) { const { t } = useTableLocale() - const { columnStorage, reportError } = useUiServices() + const { columnStorage, reportError, reportSuccess } = useUiServices() const theme = useThemeVars() const cardStyle = computed(() => ({ '--r-table-card-surface': theme.value.cardColor, @@ -65,7 +72,9 @@ export default defineComponent({ '--r-table-card-text': theme.value.textColor1, '--r-table-card-muted': theme.value.textColor2, })) - const table = useTemplateRef('dataTable') + const table = useTemplateRef( + 'dataTable', + ) const wrapper = useTemplateRef('wrapper') const responsivePager = computed(() => typeof props.pagination === 'object' && props.pagination.simple == null @@ -99,10 +108,34 @@ export default defineComponent({ columnStorage, ) const printing = ref(false) + const copyingImage = ref(false) + const imageFeedback = shallowRef<{ key: string; error: boolean }>() let pendingPrint: AbortController | undefined + let pendingImage: AbortController | undefined + let disposed = false const cancelPrint = () => pendingPrint?.abort() + const cancelImage = () => pendingImage?.abort() - onBeforeUnmount(cancelPrint) + onBeforeUnmount(() => { + disposed = true + cancelPrint() + cancelImage() + }) + + const reportImageResult = (key: string, error: boolean) => { + const notify = error ? reportError : reportSuccess + + imageFeedback.value = { key, error } + + if (notify) { + try { + notify(t(key)) + imageFeedback.value = void 0 + } catch { + // 宿主消息服务不可用时保留局部反馈,不改变已经完成的剪贴板结果。 + } + } + } provide(config.wrapperKey, wrapper) const size = useLocalOverride(() => props.size) @@ -118,17 +151,81 @@ export default defineComponent({ () => props.data, () => props.rowActionsDisabled, () => props.contextMenuOptions, + () => props.loading, ], - ([data, disabled], [previousData, previouslyDisabled]) => { + ([data, disabled, , loading], [previousData, previouslyDisabled]) => { closeContext() - if (data !== previousData || disabled !== previouslyDisabled) + if (data !== previousData || disabled !== previouslyDisabled) { cancelPrint() + cancelImage() + imageFeedback.value = void 0 + } + + if (loading) cancelImage() }, ) const handle: TablePanelInst = { getTableInstance: () => table.value, + copyImage: async (options) => { + if ( + disposed || + copyingImage.value || + props.loading || + props.rowActionsDisabled + ) + return false + + const target = unrefElement(table) + + if (!(target instanceof HTMLElement)) return false + + const current = new AbortController() + + pendingImage = current + copyingImage.value = true + imageFeedback.value = void 0 + + try { + await copyTableImage( + target, + { + backgroundColor: theme.value.cardColor, + ...props.copyImageOptions, + ...options, + }, + current.signal, + ) + + if (!disposed && !current.signal.aborted) + reportImageResult('copyImageSuccess', false) + + return true + } catch (error) { + const name = error instanceof Error ? error.name : '' + + if (!disposed && !current.signal.aborted) { + if (name === 'AbortError') return false + + reportImageResult( + name === 'NotSupportedError' + ? 'copyImageUnsupported' + : name === 'NotAllowedError' + ? 'copyImagePermission' + : 'copyImageError', + true, + ) + } + + return false + } finally { + if (pendingImage === current) { + pendingImage = void 0 + copyingImage.value = false + } + } + }, downloadCsv: (options) => { if (props.rowActionsDisabled) return @@ -239,9 +336,96 @@ export default defineComponent({ } } - const changeAppearance = (values: PropsComponentPopselectKeys[]) => { - striped.value = values.includes('striped') - bordered.value = values.includes('bordered') + const actionOptions = computed>( + () => [ + { + key: 'density', + label: t('density'), + icon: () => , + children: (['small', 'medium', 'large'] as const).map( + (value, index) => ({ + key: `density:${value}`, + label: t(['compact', 'standard', 'comfortable'][index]), + icon: () => ( + + ), + props: { + role: 'menuitemradio', + 'aria-checked': size.value === value, + }, + }), + ), + }, + ...(['striped', 'bordered'] as const).map((key) => { + const checked = key === 'striped' ? striped.value : bordered.value + + return { + key, + label: t(key), + icon: () => , + props: { role: 'menuitemcheckbox', 'aria-checked': checked }, + } + }), + { key: 'output-divider', type: 'divider' }, + { + key: 'csv', + label: t('csv'), + icon: () => , + disabled: + props.rowActionsDisabled || props.loading || !props.columns.length, + }, + ...(props.showPrint + ? [ + { + key: 'print', + label: t('print'), + icon: () => , + disabled: + props.rowActionsDisabled || props.loading || printing.value, + }, + ] + : []), + ], + ) + + /** + * + * @param key 工具菜单操作键 + * + * @description + * 复用实例导出和打印路径;外观只更新本地覆盖,不改变调用方列或数据。 + */ + const selectAction = async (key: string | number) => { + switch (key) { + case 'density:small': + size.value = 'small' + break + case 'density:medium': + size.value = 'medium' + break + case 'density:large': + size.value = 'large' + break + case 'striped': + striped.value = !striped.value + break + case 'bordered': + bordered.value = !bordered.value + break + case 'csv': + if (!props.loading) handle.downloadCsv() + + break + case 'print': + if (props.showPrint && !(await handle.print())) + reportError?.(t('printError')) + + break + default: + break + } } const nativeProps = computed(() => toNativeTableProps(props)) @@ -297,29 +481,26 @@ export default defineComponent({ ) : null} {showToolbar ? (
- {toolbar?.()} + {toolbar ? ( +
{toolbar()}
+ ) : null} {tool ? ( - <> - { - if (!(await handle.print())) - reportError?.(t('printError')) - }} - /> - { - size.value = value - }} - /> - +
+ {props.reload ? ( + + ) : null} {props.columns.length ? ( ) : null} - - + {props.showCopyImage ? ( + { + void handle.copyImage() + }} + /> + ) : null} + + + + +
) : null}
) : null} ) : null} + {imageFeedback.value ? ( +

+ {t(imageFeedback.value.key)} +

+ ) : null} , }, pagination: { - type: [Boolean, Object] as PropType, + type: [Boolean, Object] as PropType, default: void 0, }, pageSize: { type: Number, default: 10 }, @@ -80,14 +81,23 @@ const props = { export type TableProProps = ExtractPublicPropTypes export interface TableProInst extends TablePanelInst { + /** 远端查询状态;本地数据模式下为 null */ readonly queryState: TableProQueryState | null + /** 重载当前查询,resetPage 为 true 时先回到第一页 */ reload: (resetPage?: boolean) => Promise + /** 切换合法页码,远端模式等待对应请求完成 */ setPage: (page: number) => Promise + /** 修改每页数量并回到第一页 */ setPageSize: (pageSize: number) => Promise + /** 读取当前查询已确认的数据,未就绪时返回空数组 */ getCurrentPageData: () => readonly Readonly>[] + /** 复制当前草稿或已应用搜索值,默认读取草稿 */ getSearchValues: (source?: 'draft' | 'applied') => TableProSearchValues + /** 修改已定义的搜索字段,提交时机由搜索配置决定 */ setSearchValues: (values: TableProSearchValues) => void + /** 校验并提交当前搜索,失效或失败时返回 false */ submitSearch: () => Promise + /** 恢复并提交默认搜索值 */ resetSearch: () => Promise } @@ -231,11 +241,7 @@ export default defineComponent({ page.value = value pager.value.notifyPage(value) - for (const handler of [ - props.onUpdatePage, - props['onUpdate:page'], - props.onPageChange, - ]) + for (const handler of [props.onUpdatePage, props['onUpdate:page']]) if (handler) call(handler, value) return true @@ -315,7 +321,6 @@ export default defineComponent({ pager.value.notifyPageSize(value) for (const handler of [ - props.onPageSizeChange, props.onUpdatePageSize, props['onUpdate:pageSize'], ]) @@ -463,6 +468,10 @@ export default defineComponent({ if (!props.request || activeResult.value) table.value?.downloadCsv(options) }, + copyImage: (options) => + (!props.request || activeResult.value + ? table.value?.copyImage(options) + : void 0) ?? Promise.resolve(false), } expose(instance) @@ -500,6 +509,7 @@ export default defineComponent({ : localRows.value.rows } rowActionsDisabled={!!request && !activeResult.value} + reload={request ? reload : void 0} loading={requestPhase.value === 'loading' || externalLoading} pagination={paginationProps} onUpdatePage={setPage} diff --git a/packages/ui/src/RTablePro/src/columns.ts b/packages/ui/src/RTablePro/src/columns.ts index 02de3b4b..39cf0b61 100644 --- a/packages/ui/src/RTablePro/src/columns.ts +++ b/packages/ui/src/RTablePro/src/columns.ts @@ -10,9 +10,24 @@ export type ColumnLayoutPatch = Partial< Pick > +/** + * + * @param column 数据表列定义 + * + * @returns 是否为带业务键的数据列或分组列 + */ export const hasColumnKey = (column: DataTableColumn): column is KeyedColumn => 'key' in column +/** + * + * @param columns 按展示顺序排列的列定义 + * + * @description + * 展开分组并跳过选择、展开等功能列;保留叶子列对象引用,供导出与可见性逻辑共用。 + * + * @returns 按展示顺序排列的叶子列 + */ export const getLeafColumns = (columns: DataTableColumn[]): LeafColumn[] => columns.flatMap((column) => !hasColumnKey(column) @@ -41,6 +56,43 @@ const applyRootOrder = ( ) } +/** + * + * @param column 要调整的数据列或分组列 + * @param patch 本次布局调整,fixed 显式为 undefined 表示取消固定 + * + * @description + * Naive UI 表体读取叶子列自身的 fixed;分组固定需同步子树,仅传播 fixed,不覆盖子列其它配置。 + * + * @returns 独立的调整结果,未涉及的子树保留原引用 + */ +const applyColumnPatch = ( + column: Column, + patch: ColumnLayoutPatch, +): Column => { + if (!('children' in column) || !Object.hasOwn(patch, 'fixed')) + return { ...column, ...patch } + + return { + ...column, + ...patch, + children: column.children.map((child) => + applyColumnPatch(child, { fixed: patch.fixed }), + ), + } +} + +/** + * + * @param columns 当前完整列定义 + * @param onUpdate 受控模式的完整列更新回调 + * @param onReset 受控模式的重置回调 + * + * @description + * 在受控回调与本地布局补丁间选择单一状态来源,不直接修改输入列。 + * + * @returns 布局后的列及排序、补丁、重置方法 + */ export const useColumnLayout = ( columns: Ref, onUpdate: Ref<((columns: DataTableColumn[]) => void) | undefined>, @@ -60,9 +112,11 @@ export const useColumnLayout = ( if (!adjustments?.size) return arranged return arranged.map((column) => { - const patch = hasColumnKey(column) && adjustments.get(column.key) + if (!hasColumnKey(column)) return column - return patch ? { ...column, ...patch } : column + const patch = adjustments.get(column.key) + + return patch ? applyColumnPatch(column, patch) : column }) }) @@ -79,7 +133,7 @@ export const useColumnLayout = ( onUpdate.value( columns.value.map((column) => hasColumnKey(column) && column.key === key - ? { ...column, ...patch } + ? applyColumnPatch(column, patch) : column, ), ) @@ -124,15 +178,14 @@ const filterColumns = ( if (!('children' in column)) return hidden.has(column.key) ? [] : [column] - const children = column.children.filter((child) => !hidden.has(child.key)) + const children = filterColumns( + column.children, + hidden, + ) as typeof column.children if (!children.length) return [] - return [ - children.length === column.children.length - ? column - : { ...column, children }, - ] + return [children === column.children ? column : { ...column, children }] }) return filtered.length === columns.length && @@ -150,6 +203,17 @@ const isColumnKey = (value: unknown): value is TableColumnKey => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value)) +/** + * + * @param columns 包含隐藏列的完整列定义 + * @param scope 可选持久化标识,空值表示不写入存储 + * @param storage 隐藏列状态存储,浏览器中默认使用 localStorage + * + * @description + * 按叶子列键维护可见性,忽略已删除的键并至少保留一列;未变更的分支复用原对象。 + * + * @returns 可见列、隐藏键与切换、重置方法 + */ export const useColumnVisibility = ( columns: Ref, scope: Ref, diff --git a/packages/ui/src/RTablePro/src/components/AppearanceSettings.tsx b/packages/ui/src/RTablePro/src/components/AppearanceSettings.tsx deleted file mode 100644 index 1f10d48f..00000000 --- a/packages/ui/src/RTablePro/src/components/AppearanceSettings.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { NPopselect } from 'naive-ui' -import { defineComponent } from 'vue' -import { useTableLocale } from '../locale' -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 } = useTableLocale() - 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/packages/ui/src/RTablePro/src/components/ColumnSettings.tsx b/packages/ui/src/RTablePro/src/components/ColumnSettings.tsx index e2263454..40ec9f3e 100644 --- a/packages/ui/src/RTablePro/src/components/ColumnSettings.tsx +++ b/packages/ui/src/RTablePro/src/components/ColumnSettings.tsx @@ -76,7 +76,9 @@ export default defineComponent({ typeof column.title === 'string' ? column.title : String(column.key) const hasWidth = 'children' in column - ? column.children.every((child) => typeof child.width === 'number') + ? getLeafColumns(column.children).every( + (child) => typeof child.width === 'number', + ) : typeof column.width === 'number' return ( diff --git a/packages/ui/src/RTablePro/src/components/Size.tsx b/packages/ui/src/RTablePro/src/components/Size.tsx deleted file mode 100644 index b58b32e3..00000000 --- a/packages/ui/src/RTablePro/src/components/Size.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import { NPopselect } from 'naive-ui' -import type { DataTableProps } from 'naive-ui' -import { defineComponent } from 'vue' -import { useTableLocale } from '../locale' -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 } = useTableLocale() - - return () => ( - { - if (value === 'small' || value === 'medium' || value === 'large') - emit('change', value) - }} - > - - - ) - }, -}) diff --git a/packages/ui/src/RTablePro/src/components/ToolButton.tsx b/packages/ui/src/RTablePro/src/components/ToolButton.tsx index 2f8a331d..95316886 100644 --- a/packages/ui/src/RTablePro/src/components/ToolButton.tsx +++ b/packages/ui/src/RTablePro/src/components/ToolButton.tsx @@ -9,6 +9,7 @@ export default defineComponent({ icon: { type: String as PropType, required: true }, label: { type: String, required: true }, disabled: Boolean, + loading: Boolean, onClick: { type: Function as PropType<(event: MouseEvent) => unknown>, default: void 0, @@ -23,6 +24,7 @@ export default defineComponent({ aria-label={props.label} {...{ title: props.label }} disabled={props.disabled} + loading={props.loading} onClick={props.onClick} > {{ diff --git a/packages/ui/src/RTablePro/src/csv.ts b/packages/ui/src/RTablePro/src/csv.ts index e7a32bf0..7481d3c5 100644 --- a/packages/ui/src/RTablePro/src/csv.ts +++ b/packages/ui/src/RTablePro/src/csv.ts @@ -12,6 +12,18 @@ const encodeCell = (value: unknown) => { return `"${formula ? "'" : ''}${text.replaceAll('"', '""')}"` } +/** + * + * @param columns 当前可见列 + * @param data 要导出的数据快照 + * @param getCell 可选单元格格式化函数 + * @param getHeader 可选表头格式化函数 + * + * @description + * 只导出允许导出的叶子列,统一转义引号并防护文本型公式注入,不修改输入数据。 + * + * @returns 使用 CRLF 换行的 CSV 文本 + */ export const buildTableCsv = ( columns: DataTableColumn[], data: Record[], @@ -44,6 +56,14 @@ export const buildTableCsv = ( ].join('\r\n') } +/** + * + * @param csv 已编码的 CSV 文本 + * @param fileName 下载文件名,缺少 .csv 时补齐 + * + * @description + * 添加 UTF-8 BOM 并触发浏览器下载,随后释放临时链接和对象 URL。 + */ export const downloadTableCsv = (csv: string, fileName = 'data.csv') => { const url = URL.createObjectURL( new Blob(['\uFEFF', csv], { type: 'text/csv;charset=utf-8' }), diff --git a/packages/ui/src/RTablePro/src/en-US.json b/packages/ui/src/RTablePro/src/en-US.json index bb6f7daf..dc4a0f13 100644 --- a/packages/ui/src/RTablePro/src/en-US.json +++ b/packages/ui/src/RTablePro/src/en-US.json @@ -1,4 +1,12 @@ { + "tableControls": "Table controls", + "moreActions": "More actions", + "copyImage": "Copy table image", + "copyingImage": "Copying table image…", + "copyImageSuccess": "Table image copied", + "copyImageUnsupported": "This browser cannot copy PNG images. Use a supported browser over HTTPS or localhost.", + "copyImagePermission": "Clipboard access was denied. Allow clipboard access and try again.", + "copyImageError": "Couldn't copy the table image. Check its images and fonts, then try again.", "httpSource": "Local mock API", "localSource": "Local demo data", "directory": "People directory", diff --git a/packages/ui/src/RTablePro/src/image-svg.ts b/packages/ui/src/RTablePro/src/image-svg.ts new file mode 100644 index 00000000..02a10f6f --- /dev/null +++ b/packages/ui/src/RTablePro/src/image-svg.ts @@ -0,0 +1,307 @@ +import { iconSprites } from '@ray-template/icons/manifest' + +const SVG_NS = 'http://www.w3.org/2000/svg' +const XLINK_NS = 'http://www.w3.org/1999/xlink' +const MAX_SPRITE_BYTES = 1024 * 1024 +const MAX_SPRITE_SOURCES = 16 +const vectorTags = new Set([ + 'svg', + 'symbol', + 'g', + 'path', + 'rect', + 'circle', + 'ellipse', + 'line', + 'polyline', + 'polygon', + 'title', + 'desc', +]) +const presentation = [ + 'color', + 'fill', + 'fill-opacity', + 'fill-rule', + 'stroke', + 'stroke-width', + 'stroke-opacity', + 'stroke-linecap', + 'stroke-linejoin', + 'stroke-miterlimit', + 'stroke-dasharray', + 'stroke-dashoffset', + 'opacity', + 'vector-effect', + 'paint-order', + 'display', + 'visibility', + 'transform', + 'transform-origin', +] +const vectorAttributes = new Set([ + ...presentation, + 'viewBox', + 'preserveAspectRatio', + 'x', + 'y', + 'x1', + 'x2', + 'y1', + 'y2', + 'width', + 'height', + 'cx', + 'cy', + 'r', + 'rx', + 'ry', + 'd', + 'points', + 'pathLength', +]) + +const safeValue = (value: string) => { + // 静态矢量不依赖外部资源或 paint server,避免内联后引入新的请求与 ID 引用。 + if (/(?:url|var|env|attr)\s*\(|\\|\/\*/i.test(value)) + throw new Error( + '[TablePro] Resource-dependent SVG values are not supported in snapshots.', + ) + + return value +} + +/** + * + * @param source 已验证来源的静态 SVG 节点 + * @param document 快照所属文档 + * @param depth 当前矢量嵌套深度 + * + * @description + * 只复制静态几何和呈现属性;不复制 ID、事件、链接或任意样式规则。 + * + * @returns 独立的安全矢量节点 + * @throws 非静态元素、URL 绘制依赖或过深结构出现时抛错 + */ +function copyVector( + source: Element, + document: Document, + depth = 0, +): SVGElement { + if ( + source.namespaceURI !== SVG_NS || + !vectorTags.has(source.localName) || + depth > 32 + ) + throw new Error('[TablePro] Only static SVG vectors can be copied.') + + const node = document.createElementNS( + SVG_NS, + source.localName === 'symbol' ? 'svg' : source.localName, + ) + + for (const attribute of Array.from(source.attributes)) { + if (vectorAttributes.has(attribute.name)) + node.setAttribute(attribute.name, safeValue(attribute.value)) + } + + const style = (source as SVGElement).style + + safeValue(source.getAttribute('style') ?? '') + + for (const property of presentation) { + const value = style?.getPropertyValue(property) + + if (value) node.style.setProperty(property, safeValue(value)) + } + + for (const child of Array.from(source.childNodes)) { + if (child.nodeType === Node.ELEMENT_NODE) + node.append(copyVector(child as Element, document, depth + 1)) + else if (child.nodeType === Node.TEXT_NODE) + node.append(document.createTextNode(child.textContent ?? '')) + } + + return node +} + +/** + * + * @param url 同源公共 SVG 资源地址 + * @param signal 截图取消信号 + * + * @returns 有大小上限的 SVG XML 文档 + * @throws 请求、大小限制或 XML 校验失败时拒绝 + */ +async function fetchSprite(url: string, signal: AbortSignal) { + const response = await fetch(url, { + signal, + credentials: 'omit', + redirect: 'error', + mode: 'same-origin', + cache: 'force-cache', + headers: { Accept: 'image/svg+xml' }, + }) + + if ( + !response.ok || + !response.body || + Number(response.headers.get('content-length')) > MAX_SPRITE_BYTES + ) + throw new Error('[TablePro] The SVG sprite could not be read.') + + const reader = response.body.getReader() + const decoder = new TextDecoder() + const chunks: string[] = [] + let size = 0 + + try { + while (true) { + signal.throwIfAborted() + const { value, done } = await reader.read() + + if (done) break + + size += value.byteLength + + if (size > MAX_SPRITE_BYTES) + throw new Error('[TablePro] The SVG sprite is too large.') + + chunks.push(decoder.decode(value, { stream: true })) + } + } finally { + await reader.cancel().catch(() => {}) + reader.releaseLock() + } + + chunks.push(decoder.decode()) + const source = chunks.join('') + + if ( + / 10_000 + ) + throw new Error( + '[TablePro] The SVG sprite is not a bounded static document.', + ) + + const document = new DOMParser().parseFromString(source, 'image/svg+xml') + + if ( + document.querySelector('parsererror') || + document.documentElement.namespaceURI !== SVG_NS || + document.documentElement.localName !== 'svg' + ) + throw new Error('[TablePro] Invalid SVG sprite document.') + + return document +} + +/** + * + * @param snapshot 已连接但不可交互的截图副本 + * @param signal 截图取消信号 + * + * @description + * 将 RIcon 精灵图和本地 symbol 引用展开为独立静态 SVG,每次截图内合并同源资源请求。 + * 只处理注册精灵图或 .svg 公共文件,不携带凭据或追随重定向;原页面节点保持不变。 + * + * @throws 来源、符号、静态矢量或资源限制不满足时拒绝,不继续生成缺图 PNG + */ +export async function inlineTableSvgUses( + snapshot: HTMLElement, + signal: AbortSignal, +) { + const document = snapshot.ownerDocument + const page = new URL(document.URL) + + page.hash = '' + const registered = new Set( + Object.values(iconSprites).map( + (path) => new URL(path, document.baseURI).href, + ), + ) + const sources = new Map>() + + await Promise.all( + Array.from(snapshot.querySelectorAll('use'), async (use) => { + signal.throwIfAborted() + const href = + use.getAttribute('href') ?? use.getAttributeNS(XLINK_NS, 'href') + + if (!href) return + + const url = new URL(href, document.baseURI) + const id = decodeURIComponent(url.hash.slice(1)) + + url.hash = '' + + if (!id) throw new Error('[TablePro] SVG references require a symbol ID.') + + let source: Document + + if (href.startsWith('#') || url.href === page.href) source = document + else { + if ( + url.origin !== page.origin || + !['http:', 'https:'].includes(url.protocol) || + url.username || + url.password || + (!registered.has(url.href) && + !url.pathname.toLowerCase().endsWith('.svg')) + ) + throw new Error( + '[TablePro] SVG sprites must be same-origin public assets.', + ) + + let request = sources.get(url.href) + + if (!request) { + if (sources.size >= MAX_SPRITE_SOURCES) + throw new Error('[TablePro] Too many SVG sprite sources.') + + request = fetchSprite(url.href, signal) + sources.set(url.href, request) + } + + source = await request + } + + signal.throwIfAborted() + const symbol = source.getElementById(id) + + if (!symbol) throw new Error('[TablePro] The SVG symbol does not exist.') + + const vector = copyVector(symbol, document) + const group = document.createElementNS(SVG_NS, 'g') + const style = document.defaultView!.getComputedStyle(use) + + for (const property of presentation) { + const value = style.getPropertyValue(property) + + if (value) group.style.setProperty(property, safeValue(value)) + } + + const viewport = + vector.localName === 'svg' + ? vector + : document.createElementNS(SVG_NS, 'svg') + + if (viewport !== vector) { + viewport.style.overflow = 'visible' + viewport.append(vector) + } + + for (const name of ['x', 'y', 'width', 'height']) { + const value = use.getAttribute(name) ?? style.getPropertyValue(name) + + if (value && value !== 'auto') viewport.setAttribute(name, value) + else if (name === 'width' || name === 'height') + viewport.setAttribute(name, '100%') + } + + group.append(viewport) + use.replaceWith(group) + }), + ) +} diff --git a/packages/ui/src/RTablePro/src/image.ts b/packages/ui/src/RTablePro/src/image.ts new file mode 100644 index 00000000..095b6045 --- /dev/null +++ b/packages/ui/src/RTablePro/src/image.ts @@ -0,0 +1,333 @@ +import { useDomToImage } from '@ray-template/composables/useDomToImage' +import { inlineTableSvgUses } from './image-svg' +import type { TableProImageOptions } from './types' + +/** + * + * @param target 当前表格根节点 + * + * @description + * 创建不参与页面交互的临时快照,固定可视尺寸并将滚动、sticky 位置转换为静态位移。 + * 先集中读取原节点,再写入快照与校准固定列;不修改原表格的滚动或样式。 + * + * @returns 快照节点及幂等清理方法 + * @throws 节点未连接或没有可见尺寸时抛错 + */ +export function createTableImageSnapshot(target: HTMLElement) { + const view = target.ownerDocument.defaultView + const width = target.offsetWidth + const height = target.offsetHeight + + if (!view || !target.isConnected || width <= 0 || height <= 0) + throw new Error('[TablePro] The table has no visible capture area.') + + const embedded = 'iframe, object, embed, audio, video' + + if (target.matches(embedded) || target.querySelector(embedded)) + throw new Error( + '[TablePro] Embedded media cannot be copied into a table snapshot.', + ) + + const clone = target.cloneNode(true) as HTMLElement + const originals = [target, ...target.querySelectorAll('*')] + const copies = [clone, ...clone.querySelectorAll('*')] + const rootRect = target.getBoundingClientRect() + const rootStyle = view.getComputedStyle(target) + const formOwner = `r-table-image-${crypto.randomUUID()}` + const scrolls: { clone: HTMLElement; left: number; top: number }[] = [] + const sticky: { + clone: HTMLElement + left: number + top: number + transform: string + }[] = [] + const transforms = new Map() + + for (const [index, original] of originals.entries()) { + const copy = copies[index] + + if (copy.localName === 'script') { + copy.remove() + continue + } + + for (const name of copy.getAttributeNames()) { + if (/^on/i.test(name)) copy.removeAttribute(name) + } + + if (original instanceof HTMLElement && copy instanceof HTMLElement) { + const style = view.getComputedStyle(original) + + transforms.set(copy, style.transform === 'none' ? '' : style.transform) + + // 临时控件不参与真实表单或单选分组,也不触发自动聚焦。 + copy.removeAttribute('autofocus') + + if ('form' in copy) { + copy.setAttribute('form', formOwner) + copy.removeAttribute('name') + } + + if (original.scrollLeft || original.scrollTop) + scrolls.push({ + clone: copy, + left: original.scrollLeft, + top: original.scrollTop, + }) + + if (style.position === 'sticky') { + const rect = original.getBoundingClientRect() + + sticky.push({ + clone: copy, + left: rect.left - rootRect.left, + top: rect.top - rootRect.top, + transform: style.transform, + }) + } + } + + if ( + original instanceof HTMLInputElement && + copy instanceof HTMLInputElement + ) { + if (original.type !== 'file') { + copy.value = + original.type === 'password' + ? '•'.repeat(original.value.length) + : original.value + copy.defaultValue = copy.value + } + + copy.checked = original.checked + copy.defaultChecked = original.checked + copy.indeterminate = original.indeterminate + } else if ( + original instanceof HTMLTextAreaElement && + copy instanceof HTMLTextAreaElement + ) { + copy.value = original.value + copy.defaultValue = original.value + } else if ( + original instanceof HTMLOptionElement && + copy instanceof HTMLOptionElement + ) { + copy.selected = original.selected + copy.defaultSelected = original.selected + } else if ( + original instanceof HTMLCanvasElement && + copy instanceof HTMLCanvasElement + ) { + const context = copy.getContext('2d') + + if (!context) throw new Error('[TablePro] Canvas capture is unavailable.') + + context.drawImage(original, 0, 0) + } + } + + // 快照仍放在原父级下,保留作用域样式与主题变量,但固定定位不参与布局或交互。 + for (const name of Array.from(rootStyle)) { + if (name.startsWith('--')) + clone.style.setProperty(name, rootStyle.getPropertyValue(name)) + } + + Object.assign(clone.style, { + position: 'fixed', + left: '0', + top: '-100000px', + margin: '0', + width: `${width}px`, + height: `${height}px`, + boxSizing: 'border-box', + pointerEvents: 'none', + transform: 'none', + }) + clone.inert = true + clone.setAttribute('aria-hidden', 'true') + clone.setAttribute('data-r-table-image-snapshot', '') + + for (const { clone: scroller, left, top } of scrolls) { + scroller.style.overflow = 'hidden' + + for (const child of Array.from(scroller.children)) { + if (child instanceof HTMLElement) + child.style.transform = `translate(${-left}px, ${-top}px) ${transforms.get(child) ?? ''}` + } + } + + for (const item of sticky) { + Object.assign(item.clone.style, { position: 'relative', inset: 'auto' }) + } + + const dispose = () => clone.remove() + + try { + target.parentElement!.append(clone) + const cloneRect = clone.getBoundingClientRect() + const corrections = sticky.map((item) => { + const rect = item.clone.getBoundingClientRect() + + return { + element: item.clone, + x: item.left - (rect.left - cloneRect.left), + y: item.top - (rect.top - cloneRect.top), + transform: + item.clone.style.transform || + (item.transform === 'none' ? '' : item.transform), + } + }) + + const byElement = new Map(corrections.map((item) => [item.element, item])) + + for (const { element, x, y, transform } of corrections) { + let parent = element.parentElement + + while (parent && !byElement.has(parent)) parent = parent.parentElement + + const inherited = parent ? byElement.get(parent) : void 0 + + // 嵌套 sticky 已随父节点移动,只补齐尚未校正的位移。 + element.style.transform = `translate(${x - (inherited?.x ?? 0)}px, ${y - (inherited?.y ?? 0)}px) ${transform}` + } + + return { element: clone, dispose } + } catch (error) { + dispose() + throw error + } +} + +/** + * + * @param target 当前表格根节点,只截取该节点的可视盒 + * @param options PNG 渲染配置,调用时按需加载现有渲染库 + * @param signal 组件拥有的取消信号 + * + * @description + * 在第一次异步等待之前请求剪贴板写入,向 ClipboardItem 提供延迟 PNG,保留浏览器用户激活。 + * 取消时拒绝尚未就绪的图片并清理快照;浏览器已经接受的数据写入无法撤销。 + * + * @throws API 不可用、权限被拒绝、生成失败或尚未就绪时取消会使 Promise 拒绝 + */ +export async function copyTableImage( + target: HTMLElement, + options: TableProImageOptions = {}, + signal?: AbortSignal, +) { + if ( + typeof ClipboardItem === 'undefined' || + typeof navigator === 'undefined' || + typeof navigator.clipboard?.write !== 'function' || + globalThis.isSecureContext === false + ) + throw new DOMException( + 'PNG clipboard writing is unavailable.', + 'NotSupportedError', + ) + + const controller = new AbortController() + const representation = Promise.withResolvers() + const signals = [signal, options.fetchRequestInit?.signal].filter( + (value): value is AbortSignal => !!value, + ) + let snapshot: ReturnType | undefined + let captureTimer: ReturnType | undefined + let active = true + const cancel = () => { + clearTimeout(captureTimer) + controller.abort() + representation.reject( + new DOMException('Table image copy was cancelled.', 'AbortError'), + ) + snapshot?.dispose() + } + + if (signals.some((current) => current.aborted)) + throw new DOMException('Table image copy was cancelled.', 'AbortError') + + for (const current of signals) + current.addEventListener('abort', cancel, { once: true }) + + // 浏览器可能在消费表示数据之前拒绝写入,仍需接住对应图片 Promise 的拒绝。 + void representation.promise.catch(() => {}) + + try { + const writing = navigator.clipboard.write([ + new ClipboardItem({ 'image/png': representation.promise }), + ]) + const result = writing.catch((error: unknown) => { + active = false + clearTimeout(captureTimer) + controller.abort() + representation.reject(error) + snapshot?.dispose() + throw error + }) + + // 写入请求已在点击调用栈内发出,再让出当前任务供忙碌状态绘制,然后开始克隆与按需加载。 + const capture = async () => { + if (!active || controller.signal.aborted) return + + try { + snapshot = createTableImageSnapshot(target) + await inlineTableSvgUses(snapshot.element, controller.signal) + + if (!active || controller.signal.aborted) return + + const { create } = useDomToImage(snapshot.element, { + pixelRatio: Math.min(globalThis.devicePixelRatio || 1, 2), + ...options, + fetchRequestInit: { + ...options.fetchRequestInit, + signal: controller.signal, + }, + style: { + position: 'static', + inset: 'auto', + margin: '0', + transform: 'none', + ...options.style, + }, + imageType: 'blob', + type: 'image/png', + }) + const blob = await create('blob') + + if (!active || controller.signal.aborted) return + + if (!blob || blob.type !== 'image/png' || !blob.size) + throw new Error( + '[TablePro] The PNG renderer returned an empty image.', + ) + + representation.resolve(blob) + } catch (error) { + controller.abort() + representation.reject(error) + } finally { + snapshot?.dispose() + } + } + + captureTimer = setTimeout(() => { + void capture() + }, 0) + + await result + } catch (error) { + representation.reject(error) + + if (signals.some((current) => current.aborted)) + throw new DOMException('Table image copy was cancelled.', 'AbortError') + + throw error + } finally { + active = false + clearTimeout(captureTimer) + + for (const current of signals) current.removeEventListener('abort', cancel) + + snapshot?.dispose() + } +} diff --git a/packages/ui/src/RTablePro/src/index.scss b/packages/ui/src/RTablePro/src/index.scss index cbf6a7a9..18a0d4b2 100644 --- a/packages/ui/src/RTablePro/src/index.scss +++ b/packages/ui/src/RTablePro/src/index.scss @@ -41,10 +41,34 @@ flex-wrap: wrap; align-items: center; justify-content: flex-end; - gap: 6px; + gap: 8px; margin-inline-start: auto; } + &__business-actions, + &__utilities { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + min-inline-size: 0; + } + + &__business-actions { + gap: 8px; + } + + &__utilities--separated { + padding-inline-start: 8px; + border-inline-start: 1px solid var(--r-line, var(--r-table-card-divider)); + } + + &__image-feedback { + margin: 0; + font-size: 13px; + line-height: 1.5; + } + &__heading { min-inline-size: 0; } diff --git a/packages/ui/src/RTablePro/src/locale.ts b/packages/ui/src/RTablePro/src/locale.ts index 136a918e..60b22c0e 100644 --- a/packages/ui/src/RTablePro/src/locale.ts +++ b/packages/ui/src/RTablePro/src/locale.ts @@ -7,6 +7,13 @@ const labelsByLocale = { en: { ...en, fullscreen: 'Full screen', exitFullscreen: 'Exit full screen' }, } +/** + * + * @description + * 优先使用宿主注入的翻译函数,缺失键时回退到表格内置的中文或英文文案。 + * + * @returns 读取最新语言并处理简单参数插值的翻译方法 + */ export function useTableLocale() { const { translate, locale } = useUiServices() diff --git a/packages/ui/src/RTablePro/src/pagination.ts b/packages/ui/src/RTablePro/src/pagination.ts index 76c1c77d..c173ddf7 100644 --- a/packages/ui/src/RTablePro/src/pagination.ts +++ b/packages/ui/src/RTablePro/src/pagination.ts @@ -1,29 +1,33 @@ import { call } from '@ray-template/composables/vue/call' -import type { PaginationProps } from 'naive-ui' +import { omit } from 'lodash-es' +import type { TableProPagination } from './types' -export const splitPaginationOptions = (options: PaginationProps = {}) => { +/** + * + * @param options 调用方分页配置 + * + * @description + * 分离展示配置与当前更新事件;移除旧版 change 字段,避免传入原生组件后重复触发或产生弃用警告。 + * + * @returns 展示参数及页码、页容量通知方法 + */ +export const splitPaginationOptions = (options: TableProPagination = {}) => { const { onUpdatePage, 'onUpdate:page': updatePage, - onChange, onUpdatePageSize, 'onUpdate:pageSize': updatePageSize, - onPageSizeChange, ...view } = options return { - view, + view: omit(view, ['onChange', 'onPageSizeChange']), notifyPage: (page: number) => { - for (const handler of [onChange, onUpdatePage, updatePage]) + for (const handler of [onUpdatePage, updatePage]) if (handler) call(handler, page) }, notifyPageSize: (size: number) => { - for (const handler of [ - onPageSizeChange, - onUpdatePageSize, - updatePageSize, - ]) + for (const handler of [onUpdatePageSize, updatePageSize]) if (handler) call(handler, size) }, } diff --git a/packages/ui/src/RTablePro/src/printing.ts b/packages/ui/src/RTablePro/src/printing.ts index 19bcaa13..a658b877 100644 --- a/packages/ui/src/RTablePro/src/printing.ts +++ b/packages/ui/src/RTablePro/src/printing.ts @@ -29,12 +29,25 @@ const displayText = (value: unknown): string => { : '' } +/** + * + * @param doc 打印表格所属文档 + * @param columns 当前可见列 + * @param rows 当前页数据快照 + * @param options 表头与单元格格式化选项 + * + * @description + * 生成保留分组表头的独立表格,文本通过 textContent 写入,不执行数据中的 HTML。 + * + * @returns 尚未插入文档的表格元素 + */ export const buildPrintableTable = ( doc: Document, columns: DataTableColumn[], rows: Record[], - { formatHeader, formatCell }: TableProPrintOptions = {}, + options: TableProPrintOptions = {}, ) => { + const { formatHeader, formatCell } = options const table = doc.createElement('table') const leaves = getLeafColumns(columns) const header = table.createTHead() @@ -224,6 +237,16 @@ const copyPageStyles = (source: Document, destination: Document) => { return links } +/** + * + * @param options 可选打印目标与样式配置 + * @param defaultTable 未指定目标时创建默认表格的工厂 + * + * @description + * 自定义目标会复制为独立节点,并去除脚本、嵌入内容、内联事件与敏感表单值。 + * + * @returns 可打印节点;目标不存在或不可打印时为 null + */ export const resolvePrintContent = ( options: TableProPrintOptions, defaultTable: () => HTMLElement | null, @@ -235,6 +258,19 @@ export const resolvePrintContent = ( return target instanceof HTMLElement ? cloneRegion(target) : null } +/** + * + * @param content 待插入打印 iframe 的独立内容节点 + * @param options 标题、样式及页面样式继承选项 + * @param signal 可选取消信号,只在调起浏览器打印前取消 + * + * @description + * 在沙箱 iframe 中等待图片、样式与字体(最多 2 秒),再调起浏览器打印。 + * iframe 在打印完成、失败或兜底超时后释放;返回成功只表示已请求打印。 + * + * @returns 是否已调起浏览器打印,提前取消时为 false + * @throws 文档不可用或浏览器打印调用失败时抛错 + */ export const printTableContent = async ( content: HTMLElement, options: TableProPrintOptions, diff --git a/packages/ui/src/RTablePro/src/props.ts b/packages/ui/src/RTablePro/src/props.ts index c4ff44c3..9933ea78 100644 --- a/packages/ui/src/RTablePro/src/props.ts +++ b/packages/ui/src/RTablePro/src/props.ts @@ -2,12 +2,21 @@ import { omit, pick } from 'lodash-es' import { dataTableProps } from 'naive-ui' import type { DataTableColumn, DataTableInst, DropdownOption } from 'naive-ui' import type { ExtractPropTypes, PropType, VNode } from 'vue' -import type { TableProPrintOptions, TableProRowContext } from './types' +import type { + TableProImageOptions, + TableProPrintOptions, + TableProRowContext, +} from './types' const panelControls = { bare: Boolean, autoHeight: Boolean, tool: { type: Boolean, default: true }, + /** 是否在更多操作菜单显示打印,实例 print 方法始终可按需调用 */ + showPrint: Boolean, + /** 是否显示复制表格图片按钮,默认显示;实例 copyImage 方法不受该开关影响 */ + showCopyImage: { type: Boolean, default: true }, + copyImageOptions: Object as PropType, title: [String, Object] as PropType, downloadCsvTableOptions: Object as PropType< Parameters[0] @@ -29,9 +38,11 @@ const panelControls = { } as const export const tablePanelProps = { - ...dataTableProps, + ...omit(dataTableProps, ['onPageChange', 'onPageSizeChange']), ...panelControls, rowActionsDisabled: Boolean, + /** 由查询层提供;手动 data 模式通过自定义工具栏提供刷新 */ + reload: Function as PropType<() => Promise>, } const keysOf = (value: T) => Object.keys(value) as (keyof T)[] @@ -45,9 +56,17 @@ const nativeTableKeys = keysOf( 'striped', 'bordered', 'flexHeight', + 'onPageChange', + 'onPageSizeChange', ]), ) +/** + * + * @param props 表格面板接收的完整属性 + * + * @returns 交给 NDataTable 的原生属性,排除面板拥有的状态和包装参数 + */ export const toNativeTableProps = ( props: ExtractPropTypes, ) => pick(props, nativeTableKeys) @@ -58,16 +77,21 @@ const managedPanelKeys = [ 'remote', 'loading', 'rowActionsDisabled', + 'reload', 'onUpdatePage', 'onUpdate:page', - 'onPageChange', 'onUpdatePageSize', 'onUpdate:pageSize', - 'onPageSizeChange', ] as const const panelKeys = keysOf(omit(tablePanelProps, managedPanelKeys)) +/** + * + * @param props RTablePro 接收的完整属性 + * + * @returns 交给面板的属性,排除查询层负责的数据、分页和事件 + */ export const toPanelProps = < Props extends Pick< ExtractPropTypes, @@ -77,4 +101,4 @@ export const toPanelProps = < props: Props, ) => pick(props, panelKeys) -export default omit(tablePanelProps, ['rowActionsDisabled']) +export default omit(tablePanelProps, ['rowActionsDisabled', 'reload']) diff --git a/packages/ui/src/RTablePro/src/search.ts b/packages/ui/src/RTablePro/src/search.ts index 89a41bb8..6e1fb86b 100644 --- a/packages/ui/src/RTablePro/src/search.ts +++ b/packages/ui/src/RTablePro/src/search.ts @@ -11,18 +11,40 @@ import type { type Row = Readonly> +/** + * + * @param search 搜索配置 + * + * @returns 是否使用兼容的字段数组配置 + */ export function isSearchArray( search: TableProSearchConfig | undefined, ): search is readonly TableProSearchFieldConfig[] { return Array.isArray(search) } +/** + * + * @param search 字段数组、完整配置或禁用标记 + * + * @returns 统一的搜索配置,禁用时为 undefined + */ export function resolveSearchOptions( search: TableProSearchConfig | undefined, ): TableProSearchOptions | undefined { return isSearchArray(search) ? { fields: search } : search || void 0 } +/** + * + * @param options 搜索配置 + * @param columns 完整列定义 + * + * @description + * 优先使用显式字段,否则从叶子列提取;重复键保留首次出现的定义。 + * + * @returns 去重后的搜索字段 + */ export function resolveSearchFields( options: TableProSearchOptions, columns: TableProColumn[], @@ -54,6 +76,15 @@ export function resolveSearchFields( }) } +/** + * + * @param values 扁平搜索值快照 + * + * @description + * 复制字段容器和数组型字段,防止调用方修改内部快照;标量无需深拷贝。 + * + * @returns 独立的搜索值容器 + */ export function copySearchValues( values: Readonly>, ): Record { @@ -65,6 +96,14 @@ export function copySearchValues( ) } +/** + * + * @param field 当前字段定义 + * @param values 当前草稿或已应用值 + * + * @returns 字段是否可见;兼容字段始终可见 + * @throws visible 回调异常原样传播,由表格边界处理 + */ export function isSearchFieldVisible( field: TableProSearchFieldConfig, values: TableProSearchValues, @@ -148,6 +187,13 @@ function sanitizeValue( } } +/** + * + * @param fields 当前字段定义 + * @param values 候选搜索值 + * + * @returns 仅包含已定义字段的值,不匹配字段类型的值归一为 null + */ export function pickSearchValues( fields: readonly TableProSearchFieldConfig[], values: TableProSearchValues, @@ -157,6 +203,13 @@ export function pickSearchValues( ) } +/** + * + * @param fields 当前字段定义 + * @param options 可选初始值配置 + * + * @returns 经字段类型校验的初始草稿,整体初始值覆盖单字段初始值 + */ export function initialSearchValues( fields: readonly TableProSearchFieldConfig[], options: TableProSearchOptions | undefined, @@ -182,6 +235,12 @@ const sameValue = ( left.length === right.length && left.every((value, index) => value === right[index])) +/** + * + * @param fields 当前字段定义 + * + * @returns 从上游字段键到直接依赖字段键的索引,供单次变更遍历复用 + */ export const createSearchDependencies = ( fields: readonly TableProSearchFieldConfig[], ) => { @@ -201,6 +260,18 @@ export const createSearchDependencies = ( return dependents } +/** + * + * @param fields 当前字段定义 + * @param previous 上一次草稿 + * @param patch 本次字段补丁 + * @param dependents 已计算的反向依赖索引 + * + * @description + * 校验补丁并清空受影响的下游字段;本次显式赋值优先,循环依赖不会重复遍历。 + * + * @returns 新草稿;没有实际变化时复用 previous + */ export function patchSearchValues( fields: readonly TableProSearchFieldConfig[], previous: TableProSearchValues, @@ -229,6 +300,13 @@ export function patchSearchValues( return next } +/** + * + * @param field 新字段定义 + * @param previous 旧字段定义 + * + * @returns 字段值形状是否兼容,供动态字段保留草稿时判断 + */ export function sameSearchField( field: TableProSearchFieldConfig, previous: TableProSearchFieldConfig | undefined, @@ -244,6 +322,13 @@ export function sameSearchField( ) } +/** + * + * @param field 新字段定义 + * @param previous 旧字段定义 + * + * @returns 值形状、可见性、取值、匹配与转换回调是否一致 + */ export function sameSearchBehavior( field: TableProSearchFieldConfig, previous: TableProSearchFieldConfig | undefined, @@ -260,11 +345,29 @@ export function sameSearchBehavior( ) } +/** + * + * @param fields 当前字段定义 + * @param values 当前搜索值 + * + * @returns 当前可见的字段,保留输入顺序 + * @throws 可见性回调异常原样传播 + */ export const visibleSearchFields = ( fields: readonly TableProSearchFieldConfig[], values: TableProSearchValues, ) => fields.filter((field) => isSearchFieldVisible(field, values)) +/** + * + * @param fields 本次应用的字段 + * @param values 候选搜索值 + * + * @description + * 校验字段类型、裁剪文本并移除空值;数字 0 和布尔 false 保留。 + * + * @returns 可用于请求或本地过滤的搜索快照 + */ export function normalizeSearchValues( fields: readonly TableProSearchFieldConfig[], values: TableProSearchValues, @@ -286,6 +389,17 @@ export function normalizeSearchValues( ) } +/** + * + * @param fields 搜索字段定义 + * @param values 已校验的搜索值 + * + * @description + * 执行字段转换并移除 page、pageSize 保留键,分页始终由表格状态提供。 + * + * @returns 请求参数对象 + * @throws transform 回调异常原样传播 + */ export function toSearchParams( fields: readonly TableProSearchFieldConfig[], values: TableProSearchValues, @@ -311,6 +425,16 @@ export function toSearchParams( return params } +/** + * + * @param fields 搜索字段定义 + * @param values 已归一化的过滤值 + * + * @description + * 为一次搜索编译匹配函数,预先建立键索引、多选集合及文本关键词,避免逐行重复准备。 + * + * @returns 逐行匹配函数;没有过滤条件时为 null + */ export function createSearchPredicate( fields: readonly TableProSearchFieldConfig[], values: TableProSearchValues, diff --git a/packages/ui/src/RTablePro/src/types.ts b/packages/ui/src/RTablePro/src/types.ts index ec052214..2d13ebef 100644 --- a/packages/ui/src/RTablePro/src/types.ts +++ b/packages/ui/src/RTablePro/src/types.ts @@ -1,4 +1,5 @@ import type { BasicTarget } from '@ray-template/composables/types' +import type { UseDomToImageOptions } from '@ray-template/composables/useDomToImage' import type { CascaderProps, DataTableInst, @@ -8,6 +9,7 @@ import type { FormItemRule, InputNumberProps, InputProps, + PaginationProps, SelectOption, SelectProps, TimePickerProps, @@ -16,6 +18,32 @@ import type { import type { VNodeChild } from 'vue' import type { LeafColumn } from './columns' +/** + * + * @description + * 仅使用 Naive UI 当前的分页更新事件,不再接收旧版 change 别名。 + */ +export type TableProPagination = Omit< + PaginationProps, + 'onChange' | 'onPageSizeChange' +> + +/** + * + * @description + * PNG 渲染选项;截图范围固定为当前表格 DOM,生命周期与剪贴板写入由组件管理。 + */ +export type TableProImageOptions = Omit< + UseDomToImageOptions, + | 'imageType' + | 'type' + | 'quality' + | 'beforeCreate' + | 'created' + | 'createdError' + | 'finally' +> + export interface TableProPrintOptions { target?: BasicTarget title?: string @@ -38,6 +66,8 @@ export interface TablePanelInst { getTableInstance: () => DataTableInst | null print: (options?: TableProPrintOptions) => Promise downloadCsv: DataTableInst['downloadCsv'] + /** 从用户点击事件中调用,复制当前表格区域 PNG;成功写入时返回 true */ + copyImage: (options?: TableProImageOptions) => Promise } export interface TableProParams extends Record { diff --git a/packages/ui/src/RTablePro/src/useTablePro.ts b/packages/ui/src/RTablePro/src/useTablePro.ts index 84767314..71af5b81 100644 --- a/packages/ui/src/RTablePro/src/useTablePro.ts +++ b/packages/ui/src/RTablePro/src/useTablePro.ts @@ -2,9 +2,23 @@ import { computed, onScopeDispose, shallowRef } from 'vue' import type { ComputedRef } from 'vue' import type { TableProInst } from './TablePro' +/** + * + * @description + * 代理 RTablePro 的实例方法与只读查询状态;绑定 onRegister 后使用,卸载时释放注册引用。 + * + * @returns 注册函数、就绪状态与表格操作方法 + */ export const useTablePro = () => { const table = shallowRef() + /** + * + * @param instance 当前挂载的表格实例 + * + * @description + * 替换当前实例,并在该组件作用域销毁时清理引用;旧实例卸载不会清除新实例。 + */ const register = (instance: TableProInst) => { table.value = instance @@ -14,6 +28,11 @@ export const useTablePro = () => { }, true) } + /** + * + * @returns 已注册的表格实例 + * @throws 尚未注册或已卸载时抛错 + */ const getTableProInstance = () => { if (!table.value) { throw new Error( @@ -43,6 +62,7 @@ export const useTablePro = () => { getTableInstance: () => getTableProInstance().getTableInstance(), print: (options) => getTableProInstance().print(options), downloadCsv: (options) => getTableProInstance().downloadCsv(options), + copyImage: (options) => getTableProInstance().copyImage(options), } return [register, actions] as const diff --git a/packages/ui/src/RTablePro/src/useTableRequest.ts b/packages/ui/src/RTablePro/src/useTableRequest.ts index 4430f9a9..426b8ee6 100644 --- a/packages/ui/src/RTablePro/src/useTableRequest.ts +++ b/packages/ui/src/RTablePro/src/useTableRequest.ts @@ -10,6 +10,14 @@ import type { type RequestScope = { request: TableProRequest; filters: TableProParams } type Paging = { page: number; pageSize: number } +/** + * + * @description + * 使用调用方提供的请求、过滤和分页读取器管理远端查询。新请求与卸载会取消旧请求, + * 仅当前查询的结果可以进入状态;错误交给 reportError,不覆盖其他查询的加载状态。 + * + * @returns 重载方法、当前结果、总数、阶段及只读查询状态 + */ export function useTableRequest({ request, filters, @@ -70,6 +78,11 @@ export function useTableRequest({ }) let pending: AbortController | undefined + /** + * + * @description + * 取消前一次请求,以当前参数重新查询;页码越界时回退到当前最后一页继续请求。 + */ const reload = async () => { pending?.abort() const currentScope = scope.value diff --git a/packages/ui/src/RTablePro/src/useTableSearch.ts b/packages/ui/src/RTablePro/src/useTableSearch.ts index 64a7ce8a..2c68492d 100644 --- a/packages/ui/src/RTablePro/src/useTableSearch.ts +++ b/packages/ui/src/RTablePro/src/useTableSearch.ts @@ -13,6 +13,20 @@ import type { TableProSearchValues, } from './types' +/** + * + * @param fields 当前搜索字段的读取器 + * @param options 当前搜索配置的读取器 + * @param validate 支持查询是否仍有效的校验函数 + * @param restoreValidation 清除界面校验反馈 + * @param reportError 报告转换或提交异常并返回失败状态 + * @param commit 提交已确认的草稿快照 + * + * @description + * 持有搜索草稿、字段依赖及防抖计时器;编辑或卸载会使旧校验和延迟提交失效。 + * + * @returns 草稿状态与读取、修改、提交、重置和字段协调方法 + */ export function useTableSearch( fields: () => readonly TableProSearchFieldConfig[], options: () => TableProSearchOptions | undefined, @@ -43,6 +57,13 @@ export function useTableSearch( }, ) + /** + * + * @description + * 校验当前草稿快照,期间有新编辑时放弃旧提交。 + * + * @returns 当前快照是否成功提交 + */ const submit = async () => { cancelPending() const current = revision @@ -60,6 +81,13 @@ export function useTableSearch( } } + /** + * + * @param values 本次更新的字段值 + * + * @description + * 清理类型不匹配的值、重置依赖字段,并按配置安排防抖提交;等值更新保持引用不变。 + */ const setValues = (values: TableProSearchValues) => { const next = patchSearchValues( fields(), @@ -78,6 +106,13 @@ export function useTableSearch( } } + /** + * + * @description + * 取消待执行提交、恢复初始草稿并清除校验,随后提交重置后的快照。 + * + * @returns 提交函数的结果 + */ const reset = () => { cancelPending() draft.value = initialSearchValues(fields(), options()) @@ -86,6 +121,13 @@ export function useTableSearch( return commit(draft.value, 'reset') } + /** + * + * @param retainedKeys 字段定义变化后允许保留草稿的键 + * + * @description + * 取消旧校验与计时器,按最新字段定义补入默认值并移除失效字段。 + */ const reconcile = (retainedKeys: ReadonlySet) => { cancelPending() const defaults = initialSearchValues(fields(), options()) diff --git a/packages/ui/src/RTablePro/src/zh-CN.json b/packages/ui/src/RTablePro/src/zh-CN.json index 7da2f140..37ba6a46 100644 --- a/packages/ui/src/RTablePro/src/zh-CN.json +++ b/packages/ui/src/RTablePro/src/zh-CN.json @@ -1,4 +1,12 @@ { + "tableControls": "表格工具", + "moreActions": "更多操作", + "copyImage": "复制表格图片", + "copyingImage": "正在复制表格图片…", + "copyImageSuccess": "表格图片已复制", + "copyImageUnsupported": "当前浏览器无法复制 PNG 图片,请使用支持此功能的浏览器,并通过 HTTPS 或 localhost 访问。", + "copyImagePermission": "剪贴板访问被拒绝,请允许剪贴板权限后重试。", + "copyImageError": "表格图片复制失败,请检查表格中的图片和字体后重试。", "httpSource": "本地 Mock 接口", "localSource": "本地示例数据", "directory": "人员列表", diff --git a/packages/ui/src/services.ts b/packages/ui/src/services.ts index 6f637aba..caaaf1d2 100644 --- a/packages/ui/src/services.ts +++ b/packages/ui/src/services.ts @@ -10,12 +10,27 @@ export interface UiServices { translate?: (key: string, params?: Record) => string columnStorage?: ReturnType reportError?: (message: string) => void + reportSuccess?: (message: string) => void iconUrl?: (name: IconName, prefix: string) => string } const servicesKey: InjectionKey = Symbol('ray-ui-services') +/** + * + * @param services 宿主提供的翻译、主题、图标与存储适配 + * + * @description + * 在当前组件作用域提供共享 UI 服务,响应式变化由传入的读取函数负责。 + */ export const provideUiServices = (services: UiServices) => provide(servicesKey, services) +/** + * + * @description + * 读取最近的宿主服务;独立组件或无注入上下文时使用空配置,由组件决定回退行为。 + * + * @returns 当前 UI 服务适配 + */ export const useUiServices = () => hasInjectionContext() ? inject(servicesKey, {}) : {} diff --git a/packages/ui/src/theme-presets.ts b/packages/ui/src/theme-presets.ts index c2644f7a..761fa5f9 100644 --- a/packages/ui/src/theme-presets.ts +++ b/packages/ui/src/theme-presets.ts @@ -101,6 +101,15 @@ export type ThemeStyle = (typeof themeStyles)[number] export const DEFAULT_THEME_STYLE: ThemeStyle = 'modern' +/** + * + * @param value 持久化或外部传入的界面风格 + * + * @description + * 保留已支持的风格;历史缓存中的缺失或无效值回退到默认风格。 + * + * @returns 可用于主题预设索引的风格名称。 + */ export const normalizeThemeStyle = (value: unknown): ThemeStyle => themeStyles.find((style) => style === value) ?? DEFAULT_THEME_STYLE @@ -150,6 +159,7 @@ export const themeStyleOverrides: Record = { textColor3: '#b9a9c4', borderColor: '#867791', dividerColor: '#473c52', + boxShadow1: '0 2px 8px rgb(0 0 0 / 16%)', }, Layout: { siderColor: '#241e2c', headerColor: '#241e2c' }, }, @@ -192,6 +202,16 @@ export const themeStyleOverrides: Record = { }, } +/** + * + * @param vars 当前 Naive UI 主题变量 + * @param overrides 当前风格和用户主色的合并配置 + * + * @description + * 将组件主题映射为页面语义变量。页面阴影只采用显式预设,避免继承浮层阴影。 + * + * @returns 供主题容器写入的 CSS 自定义属性。 + */ export const createRayThemeStyle = ( vars: ReturnType['value'], overrides: GlobalThemeOverrides, @@ -206,8 +226,10 @@ export const createRayThemeStyle = ( '--r-token-border': vars.borderColor, '--r-token-text': vars.textColor1, '--r-token-text-secondary': vars.textColor2, - '--r-token-text-muted': vars.textColor3, - '--r-token-shadow': vars.boxShadow1, + // 组件库的弱文本不一定满足正文对比度,页面说明文字回退到次级文本色。 + '--r-token-text-muted': overrides.common?.textColor3 ?? vars.textColor2, + // 页面卡片不能直接继承组件库用于浮层的高强度阴影。 + '--r-token-shadow': overrides.common?.boxShadow1 ?? 'none', '--r-token-radius': typeof overrides.Card?.borderRadius === 'string' ? overrides.Card.borderRadius diff --git a/packages/ui/src/theme.css b/packages/ui/src/theme.css index 8ea73848..0d16e7f6 100644 --- a/packages/ui/src/theme.css +++ b/packages/ui/src/theme.css @@ -64,7 +64,5 @@ .r-layout-full *::before, .r-layout-full *::after { scroll-behavior: auto !important; - animation-duration: 0.01ms !important; - transition-duration: 0.01ms !important; } } diff --git a/packages/utils/src/core/index.ts b/packages/utils/src/core/index.ts index e2aeffdd..c5fd7a9d 100644 --- a/packages/utils/src/core/index.ts +++ b/packages/utils/src/core/index.ts @@ -45,14 +45,19 @@ export const uuid = (length = 16, radix = 62) => { const range = 2 ** 32 const limit = range - (range % radix) - const sample = new Uint32Array(1) + // 小批量复用缓冲区,避免每个字符都跨越一次 Web Crypto 边界。 + const samples = new Uint32Array(Math.min(length, 128)) let result = '' while (result.length < length) { - crypto.getRandomValues(sample) + crypto.getRandomValues(samples) - // 丢弃无法均匀分配到字符集的样本。 - if (sample[0] < limit) result += chars[sample[0] % radix] + for (const sample of samples) { + // 丢弃无法均匀分配到字符集的样本。 + if (sample < limit) result += chars[sample % radix] + + if (result.length === length) break + } } return result diff --git a/packages/utils/src/files/index.ts b/packages/utils/src/files/index.ts index e9e33688..593c177d 100644 --- a/packages/utils/src/files/index.ts +++ b/packages/utils/src/files/index.ts @@ -6,13 +6,23 @@ import type { DownloadAnyFileDataType } from '../types' * * @returns PNG Data URL。 */ -export const arrayBufferToBase64Image = (data: ArrayBuffer) => - 'data:image/png;base64,' + - btoa( - Array.from(new Uint8Array(data), (byte) => String.fromCharCode(byte)).join( - '', - ), - ) +export const arrayBufferToBase64Image = (data: ArrayBuffer) => { + const bytes = new Uint8Array(data) + + // 原生编码避免中间二进制字符串;旧浏览器继续使用分块回退。 + if (typeof bytes.toBase64 === 'function') { + return 'data:image/png;base64,' + bytes.toBase64() + } + + const chunks: string[] = [] + + // 分块限制函数参数个数,也避免为每个字节分配一个字符串数组项。 + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + chunks.push(String.fromCharCode(...bytes.subarray(offset, offset + 0x8000))) + } + + return 'data:image/png;base64,' + btoa(chunks.join('')) +} /** * diff --git a/packages/utils/src/precision.ts b/packages/utils/src/precision.ts index 81e2fbd8..8b795d7e 100644 --- a/packages/utils/src/precision.ts +++ b/packages/utils/src/precision.ts @@ -10,8 +10,15 @@ export interface CurrencyOptions extends Options { type?: OriginalValueType } +/** 以八位小数缩放为 Number 整数;调用方需确保缩放后的金额仍在安全整数范围内。 */ const defaultOptions = { precision: 8, decimal: '.' } +/** + * + * @param value 待判断的值 + * + * @returns 是否为当前 currency.js 构造器创建的实例。 + */ export const isCurrency = (value: unknown): value is currency => value instanceof currency diff --git a/packages/utils/src/storage.ts b/packages/utils/src/storage.ts index 94e570c8..af3a1e59 100644 --- a/packages/utils/src/storage.ts +++ b/packages/utils/src/storage.ts @@ -1,8 +1,24 @@ +/** + * + * @param storage 由宿主提供的同步存储后端 + * @param prefix 直接拼接在每个键前的命名空间 + * + * @description + * 使用 JSON 读写;不缓存副本,读取始终反映存储后端的当前值。 + * + * @returns 不向调用方抛出存储异常的读取、写入和删除方法。 + */ export function createStorage( storage: Pick, prefix = '', ) { return { + /** + * + * @param key 未加前缀的键 + * + * @returns 解析后的 JSON;缺键、内容损坏或存储不可读时返回 null。 + */ get(key: string): unknown { try { return JSON.parse(storage.getItem(prefix + key) ?? 'null') @@ -10,18 +26,35 @@ export function createStorage( return null } }, + /** + * + * @param key 未加前缀的键 + * @param value 可序列化为 JSON 的值 + * + * @description + * 序列化成功后再写入;无法序列化或存储拒绝写入时保留已有值。 + */ set(key: string, value: unknown) { try { - storage.setItem(prefix + key, JSON.stringify(value)) + const serialized = JSON.stringify(value) + + if (serialized !== void 0) storage.setItem(prefix + key, serialized) } catch { - // 存储不可用时保留当前实例的状态。 + // 不覆盖调用方的内存状态,也不删除此前保存的值。 } }, + /** + * + * @param key 未加前缀的键 + * + * @description + * 删除对应键;存储后端拒绝操作时忽略异常。 + */ remove(key: string) { try { storage.removeItem(prefix + key) } catch { - // 存储不可用时保留当前实例的状态。 + // 删除失败时仍允许界面继续使用当前状态。 } }, }