From 911c4034349060cd46dd4320d6fa3d1f4c318658 Mon Sep 17 00:00:00 2001 From: XiaoDaiGua-Ray <51957438+XiaoDaiGua-Ray@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:04:13 +0800 Subject: [PATCH] feat: refine admin workflows for v6.0.3 Improve theme consistency, keyboard navigation, and reusable frontend components. Harden fullstack initialization and expose scoped lint and Vitest commands. --- .vscode/settings.json | 1 + .zed/settings.json | 9 +- AGENTS.md | 1 + CHANGELOG.md | 21 +++ __test__/app/user-management.spec.ts | 64 +++++++ __test__/components/chart-themes.spec.ts | 32 +--- __test__/components/chart.spec.tsx | 24 ++- __test__/components/form-themes.spec.ts | 43 +++++ __test__/components/table-pro-search.spec.ts | 2 + .../components/table-pro-toolbar.spec.tsx | 65 +++++++ __test__/components/table-pro.spec.ts | 30 ++- .../components/wrapper-contracts.spec.tsx | 18 +- __test__/hooks/useSiderBar.spec.ts | 66 +++++++ __test__/layout/breadcrumb.spec.tsx | 39 +++- __test__/layout/global-search.spec.ts | 7 + __test__/layout/menu-tag.spec.tsx | 20 +- __test__/layout/slots.spec.ts | 3 + __test__/utils/color-contrast.ts | 36 ++++ __test__/utils/setupMiniApp.ts | 3 +- __test__/workspace/http-client.spec.ts | 52 ++++++ __test__/workspace/no-undefined.spec.ts | 85 +++++++++ apps/admin/index.html | 2 +- apps/admin/package.json | 2 +- apps/admin/src/axios/README.md | 2 +- apps/admin/src/hooks/README.md | 2 +- apps/admin/src/hooks/template/useSiderBar.ts | 173 +++++++++++------- .../src/layout/components/MenuTag/index.tsx | 37 ++-- .../components/MenuTag/use-tag-reorder.ts | 21 +-- .../components/Search/GlobalSearch/index.scss | 10 + .../components/Search/GlobalSearch/index.tsx | 27 +++ .../SiderBar/components/Breadcrumb/index.scss | 24 +++ .../SiderBar/components/Breadcrumb/index.tsx | 73 +++++--- apps/admin/src/layout/index.tsx | 1 + apps/admin/src/locales/lang/en-US/layout.json | 1 + .../locales/lang/en-US/navigationSearch.json | 1 + .../locales/lang/en-US/userManagement.json | 1 + apps/admin/src/locales/lang/zh-CN/layout.json | 1 + .../locales/lang/zh-CN/navigationSearch.json | 1 + .../locales/lang/zh-CN/userManagement.json | 1 + .../locales/lang/zh-CN/views/login/index.json | 2 +- apps/admin/src/views/dashboard/index.tsx | 22 +-- .../src/views/demo/components/index.scss | 12 +- .../src/views/demo/curd/ProjectEditor.tsx | 4 +- .../src/views/demo/curd/project-editor.scss | 5 + apps/admin/src/views/demo/hooks/index.scss | 8 +- .../demo/rely/views/rely-about/index.scss | 2 +- .../admin/src/views/demo/svg-icons/index.scss | 15 +- apps/admin/src/views/login/index.scss | 42 ++++- apps/admin/src/views/login/index.tsx | 6 +- .../src/views/route-management/index.scss | 4 +- .../src/views/user-management/index.scss | 26 ++- .../admin/src/views/user-management/index.tsx | 133 +++++++++----- apps/docs/en/guide/appearance.md | 12 +- apps/docs/en/guide/distributions.md | 4 +- apps/docs/en/guide/layout.md | 4 +- apps/docs/en/guide/requests.md | 2 +- apps/docs/en/guide/tooling.md | 6 + apps/docs/en/reference/components/iframe.md | 19 +- apps/docs/en/reference/icons.md | 2 + apps/docs/en/reference/source.md | 2 +- apps/docs/en/reference/table-pro.md | 3 +- apps/docs/guide/appearance.md | 12 +- apps/docs/guide/distributions.md | 4 +- apps/docs/guide/layout.md | 4 +- apps/docs/guide/requests.md | 2 +- apps/docs/guide/tooling.md | 6 + apps/docs/package.json | 2 +- apps/docs/reference/components/iframe.md | 19 +- apps/docs/reference/icons.md | 2 + apps/docs/reference/source.md | 2 +- apps/docs/reference/table-pro.md | 3 +- apps/server/package.json | 2 +- apps/server/scripts/check-redis.mjs | 29 +++ apps/server/test/integration.test.ts | 119 ++++++++++++ deploy/compose.yaml | 1 + deploy/smoke.mjs | 3 +- docs/toolchain-upgrade.md | 6 + eslint.config.mjs | 4 +- harness/README.md | 2 +- harness/context/toolchain.md | 4 + harness/scopes.json | 6 +- package.json | 30 ++- packages/admin-shell/src/AdminShell.tsx | 19 +- packages/admin-shell/src/shell.scss | 19 ++ packages/api-contracts/src/admin.ts | 12 +- packages/composables/package.json | 4 + packages/demo-data/src/route-catalog.json | 2 + packages/http/src/RequestCanceler.ts | 76 +++++--- packages/icons/ICON-SOURCES.md | 2 +- packages/icons/package.json | 3 +- .../icons/src/action/maximize-workspace.svg | 4 + .../icons/src/action/restore-workspace.svg | 4 + packages/icons/src/assets.ts | 19 +- packages/icons/src/load-asset.ts | 24 +++ packages/icons/src/manifest.ts | 2 + packages/icons/src/parse-asset.ts | 18 ++ packages/ui/src/RChart/src/Chart.tsx | 4 +- packages/ui/src/RIcon/src/Icon.tsx | 33 +++- packages/ui/src/RIframe/src/Iframe.tsx | 2 + packages/ui/src/RIframe/src/props.ts | 2 + packages/ui/src/RTablePro/README.md | 2 +- packages/ui/src/RTablePro/src/TablePanel.tsx | 38 ++-- packages/ui/src/RTablePro/src/TablePro.tsx | 26 ++- .../src/RTablePro/src/components/Search.tsx | 29 ++- packages/ui/src/RTablePro/src/index.scss | 8 + .../ui/src/RTablePro/src/useTableRequest.ts | 6 +- packages/ui/src/theme-presets.ts | 43 ++++- scripts/eslint-rules/no-undefined.mjs | 139 ++++++++++++++ scripts/fullstack.mjs | 136 +++++++++++--- scripts/lint-fix.mjs | 38 ++++ 110 files changed, 1886 insertions(+), 426 deletions(-) create mode 100644 __test__/components/form-themes.spec.ts create mode 100644 __test__/utils/color-contrast.ts create mode 100644 __test__/workspace/no-undefined.spec.ts create mode 100644 apps/admin/src/views/demo/curd/project-editor.scss create mode 100644 apps/server/scripts/check-redis.mjs create mode 100644 packages/icons/src/action/maximize-workspace.svg create mode 100644 packages/icons/src/action/restore-workspace.svg create mode 100644 packages/icons/src/load-asset.ts create mode 100644 packages/icons/src/parse-asset.ts create mode 100644 scripts/eslint-rules/no-undefined.mjs create mode 100644 scripts/lint-fix.mjs diff --git a/.vscode/settings.json b/.vscode/settings.json index ba0a1133..149b90a1 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,6 +2,7 @@ "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "eslint.enable": true, + "eslint.probe": [], "eslint.validate": [ "javascript", "javascriptreact", diff --git a/.zed/settings.json b/.zed/settings.json index 9f14ace2..c28a74bc 100644 --- a/.zed/settings.json +++ b/.zed/settings.json @@ -27,7 +27,11 @@ }, "JSON": { "formatter": "prettier", - "format_on_save": "on" + "format_on_save": "on", + "language_servers": ["!eslint", "..."] + }, + "JSONC": { + "language_servers": ["!eslint", "..."] }, "SCSS": { "formatter": "prettier", @@ -44,7 +48,8 @@ }, "Markdown": { "formatter": "prettier", - "format_on_save": "on" + "format_on_save": "on", + "language_servers": ["!eslint", "..."] } }, "lsp": { diff --git a/AGENTS.md b/AGENTS.md index cec2d24b..36cee97a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,6 +7,7 @@ A Vue 3 + TSX admin template with an admin application, a documentation site, an - Prefer feature entry points for runtime imports. Follow the [runtime import boundaries](harness/README.md#runtime-import-boundaries) when adding exports or changing what loads at startup or on demand. - Prefer supported component hooks for imperative actions. Bind the hook's registration callback when required and call its returned actions. Follow the [component action conventions](docs/curd-conventions.md#component-actions) for tables, forms, and modals. - Use `void 0` for an undefined runtime value and `undefined` in type annotations. Use the recommended replacements for APIs marked `@deprecated`. +- Apply ESLint fixes with `pnpm lint:fix [...]` on explicitly named files. Use Prettier for Markdown and JSON. - 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. diff --git a/CHANGELOG.md b/CHANGELOG.md index b66a9daa..e7e4700e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,24 @@ +## 6.0.3 + +### Feats + +- 新增简单标签管理和复杂项目管理示例,展示弹窗编辑、独立详情页、里程碑与草稿保护。官网补齐英文指南和组件参考。 +- 四种主题的登录页、图标库和业务面板使用各自的配色和圆角。提高输入框和主按钮的对比度,简化窄屏用户页和表格工具栏。 +- 全局搜索提示按回车将打开的页面。面包屑可用键盘操作,工作区支持跳至主内容,并区分内容区最大化与浏览器全屏。 +- 根 `package.json` 提供各模块的 Vitest 命令和全量入口 `pnpm test:all`。 + +### Fixes + +- 路由守卫拒绝离开编辑页时保留草稿、标签与缓存。键盘关闭最后一个标签后,焦点回到标签页操作按钮。 +- TablePro 在等值查询条件下保留页码,图表在实例就绪后才开始深度监听。用户管理按部门 ID 构建组织树,独立图标宿主按名称加载 SVG,打印引擎随打印示例按需加载。 +- 修复不同二进制请求体互相取消的问题。RIframe 将 `sandbox` 和 `referrerpolicy` 交给原生 iframe。 +- 全栈初始化先检查 Redis,再执行数据库迁移。切换到外部服务会保存实际连接,Compose 支持设置 `REDIS_KEY_PREFIX`。 + +### Compatibility + +- `pnpm lint:fix <文件路径>` 只修复显式指定的文件。ESLint 自动将内置 `undefined` 的运行时读取改成 `void 0`,类型中的 `undefined` 仍可使用。Markdown 和 JSON 走 Prettier。 +- 从 Compose 切换到外部服务时,同时提供 `DATABASE_URL` 和 `REDIS_URL`。已有外部服务配置可更新其中一项。[全栈启动指南](apps/docs/guide/distributions.md) + ## 6.0.2 ### Feats diff --git a/__test__/app/user-management.spec.ts b/__test__/app/user-management.spec.ts index 952fc7da..38c51eb9 100644 --- a/__test__/app/user-management.spec.ts +++ b/__test__/app/user-management.spec.ts @@ -1,12 +1,76 @@ import * as adminApi from '@/api/admin' import { AdminApiError } from '@/api/admin/client' +import { userOptionsSchema } from '@/api/admin/contracts' import { router } from '@/router' import { piniaSigningStore } from '@/store/modules/signing' import UserManagement from '@/views/user-management' import { useUserErrorMessage } from '@/views/user-management/error-message' import { flushPromises, mount } from '@vue/test-utils' +import { NTree } from 'naive-ui' +import { safeParse } from 'valibot' import setupMiniApp from '../utils/setupMiniApp' +it('indexes unordered departments in linear work and preserves the tree order', async () => { + const { app } = await setupMiniApp() + let parentReads = 0 + const departments = Array.from({ length: 1000 }, (_, index) => ({ + id: String(index), + name: `Team ${index}`, + get parentId() { + parentReads++ + + return index < 2 ? '999' : null + }, + })) + + vi.spyOn(adminApi, 'getUserOptions').mockResolvedValue({ + departments, + roles: [], + }) + const wrapper = mount(UserManagement, { + global: { + plugins: [router], + stubs: { RTablePro: true, Tree: true, RIcon: true }, + }, + }) + + try { + await flushPromises() + const tree = wrapper.getComponent(NTree) + const children = tree.props('data')![0].children! + + expect(children).toHaveLength(998) + expect(children[0].key).toBe('2') + expect(children.at(-1)?.children?.map(({ label }) => label)).toEqual([ + 'Team 0', + 'Team 1', + ]) + expect(tree.props('defaultExpandedKeys')).toEqual(['', '999']) + expect(parentReads).toBeLessThanOrEqual(departments.length * 2) + } finally { + wrapper.unmount() + app.unmount() + vi.restoreAllMocks() + } +}) + +it('accepts a deep valid department tree and rejects cycles and missing parents', () => { + const departments = Array.from({ length: 2000 }, (_, index) => ({ + id: String(index), + name: String(index), + parentId: index ? String(index - 1) : null, + })).reverse() + const valid = () => + safeParse(userOptionsSchema, { departments, roles: [] }).success + const root = departments.at(-1)! + + expect(valid()).toBe(true) + root.parentId = '1999' + expect(valid()).toBe(false) + root.parentId = 'missing' + expect(valid()).toBe(false) +}) + it('keeps the current list and selection context when opening and closing an editor', async () => { localStorage.clear() const { app } = await setupMiniApp() diff --git a/__test__/components/chart-themes.spec.ts b/__test__/components/chart-themes.spec.ts index 319008a2..92b18ce1 100644 --- a/__test__/components/chart-themes.spec.ts +++ b/__test__/components/chart-themes.spec.ts @@ -6,6 +6,7 @@ import { themeStyleOverrides, themeStyles, } from '../../packages/ui/src/theme-presets' +import { contrast } from '../utils/color-contrast' const registeredThemes = getCustomEchartTheme() const themes = new Map(registeredThemes.map(({ name, theme }) => [name, theme])) @@ -17,37 +18,6 @@ const variants = themeStyles.flatMap((style) => })), ) -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( diff --git a/__test__/components/chart.spec.tsx b/__test__/components/chart.spec.tsx index e3f10ea4..9c62770b 100644 --- a/__test__/components/chart.spec.tsx +++ b/__test__/components/chart.spec.tsx @@ -1,7 +1,7 @@ import { flushPromises, mount } from '@vue/test-utils' import { init } from 'echarts/core' import type { ECharts } from 'echarts/core' -import { nextTick, ref } from 'vue' +import { nextTick, reactive, ref } from 'vue' import { RChart, useChart } from '../../packages/ui/src/RChart' import { USE_CHART_PROVIDER_KEY } from '../../packages/ui/src/RChart/src/config' import { provideUiServices } from '../../packages/ui/src/services' @@ -223,24 +223,44 @@ it('defers offscreen initialization, even when the theme changes', async () => { vi.stubGlobal('IntersectionObserver', Observer) const dark = ref(false) + const value = ref(1) + const readValue = vi.fn(() => value.value) + const options = reactive({ + series: [ + { + data: [ + { + get value() { + return readValue() + }, + }, + ], + }, + ], + }) const wrapper = mount({ setup() { provideUiServices({ dark: () => dark.value }) - return () => + return () => }, }) try { await flushPromises() dark.value = true + value.value = 2 await nextTick() expect(init).not.toHaveBeenCalled() + expect(readValue).not.toHaveBeenCalled() visible() await flushPromises() + expect(charts[0].getOption()).toMatchObject({ + series: [{ data: [{ value: 2 }] }], + }) expect(disconnect).toHaveBeenCalled() expect(init).toHaveBeenLastCalledWith( expect.anything(), diff --git a/__test__/components/form-themes.spec.ts b/__test__/components/form-themes.spec.ts new file mode 100644 index 00000000..42415895 --- /dev/null +++ b/__test__/components/form-themes.spec.ts @@ -0,0 +1,43 @@ +import { darkTheme, lightTheme } from 'naive-ui' +import { + themeStyleOverrides, + themeStyles, +} from '../../packages/ui/src/theme-presets' +import { contrast } from '../utils/color-contrast' + +it.each(themeStyles)( + '%s keeps editable fields and primary buttons legible in both modes', + (style) => { + for (const mode of ['light', 'dark'] as const) { + const base = mode === 'light' ? lightTheme : darkTheme + const overrides = themeStyleOverrides[style][mode] + const common = { ...base.common, ...overrides.common } + const input = { ...base.Input.self!(common), ...overrides.Input } + const selection = { + ...base.Select.peers!.InternalSelection.self!(common), + ...overrides.InternalSelection, + } + const button = { ...base.Button.self!(common), ...overrides.Button } + + for (const field of [input, selection]) { + expect( + contrast(field.placeholderColor, field.color, common.cardColor), + ).toBeGreaterThanOrEqual(4.5) + expect( + contrast(field.border.replace(/^1px solid /, ''), common.cardColor), + ).toBeGreaterThanOrEqual(3) + } + + for (const [text, fill] of [ + [button.textColorPrimary, button.colorPrimary], + [button.textColorHoverPrimary, button.colorHoverPrimary], + [button.textColorPressedPrimary, button.colorPressedPrimary], + [button.textColorFocusPrimary, button.colorFocusPrimary], + ]) { + expect(contrast(text, fill, common.cardColor)).toBeGreaterThanOrEqual( + 4.5, + ) + } + } + }, +) diff --git a/__test__/components/table-pro-search.spec.ts b/__test__/components/table-pro-search.spec.ts index 60db203d..283f2bae 100644 --- a/__test__/components/table-pro-search.spec.ts +++ b/__test__/components/table-pro-search.spec.ts @@ -59,6 +59,7 @@ it('applies the latest measured search column count on the next frame', async () expect(resizeSearch).toBeTypeOf('function') expect(grid.props('cols')).toBe(1) + expect(grid.find('button[type="submit"]').exists()).toBe(false) resizeSearch?.(864) await nextTick() @@ -71,6 +72,7 @@ it('applies the latest measured search column count on the next frame', async () vi.advanceTimersToNextFrame() await nextTick() expect(grid.props('cols')).toBe(3) + expect(grid.find('button[type="submit"]').exists()).toBe(true) } finally { wrapper.unmount() vi.unstubAllGlobals() diff --git a/__test__/components/table-pro-toolbar.spec.tsx b/__test__/components/table-pro-toolbar.spec.tsx index ae7f7632..f9696dfd 100644 --- a/__test__/components/table-pro-toolbar.spec.tsx +++ b/__test__/components/table-pro-toolbar.spec.tsx @@ -4,6 +4,7 @@ import type { DropdownOption } from 'naive-ui' import { RTablePro, useTablePro } 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 image from '../../packages/ui/src/RTablePro/src/image' import * as printing from '../../packages/ui/src/RTablePro/src/printing' const columns = [{ key: 'name', title: 'Name' }] @@ -58,6 +59,70 @@ it('hides print by default and groups secondary actions under one menu', async ( } }) +it('puts image copying in the named menu on narrow panels without pagination', async () => { + let resize: ((width: number) => void) | undefined + + vi.stubGlobal( + 'ResizeObserver', + class { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element) { + if (target.matches('.r-table')) + resize = (width) => + this.callback( + [ + { + target, + contentRect: new DOMRect(0, 0, width, 200), + } as ResizeObserverEntry, + ], + this, + ) + } + disconnect() {} + unobserve() {} + }, + ) + const wrapper = mount(RTablePro, { + props: { columns, data, pagination: false }, + }) + + try { + await flushPromises() + const menu = wrapper.getComponent(NDropdown) + const copyOption = () => + menu.props('options')?.find(({ key }) => key === 'copy-image') + + expect(resize).toBeTypeOf('function') + resize?.(390) + await flushPromises() + expect(copyOption()).toMatchObject({ label: 'Copy table image' }) + await wrapper.setProps({ loading: true }) + expect(copyOption()).toMatchObject({ disabled: true }) + await wrapper.setProps({ loading: false }) + const copy = vi.spyOn(image, 'copyTableImage').mockResolvedValue(void 0) + + menu.vm.$emit('select', 'copy-image') + await flushPromises() + expect(copy).toHaveBeenCalledOnce() + expect(wrapper.find('button[aria-label="Copy table image"]').exists()).toBe( + false, + ) + await wrapper.setProps({ showCopyImage: false }) + expect(copyOption()).toBeUndefined() + await wrapper.setProps({ showCopyImage: true }) + resize?.(960) + await flushPromises() + expect(copyOption()).toBeUndefined() + expect(wrapper.find('button[aria-label="Copy table image"]').exists()).toBe( + true, + ) + } finally { + wrapper.unmount() + vi.unstubAllGlobals() + } +}) + it('opts into menu printing and retains CSV formatting and output options', async () => { const download = vi .spyOn(csv, 'downloadTableCsv') diff --git a/__test__/components/table-pro.spec.ts b/__test__/components/table-pro.spec.ts index 14c79f22..b9ee9f32 100644 --- a/__test__/components/table-pro.spec.ts +++ b/__test__/components/table-pro.spec.ts @@ -7,7 +7,7 @@ import type { 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 { defineComponent, h, reactive } from 'vue' import * as csv from '../../packages/ui/src/RTablePro/src/csv' const columns = [{ title: 'Name', key: 'name' }] @@ -97,6 +97,34 @@ it('loads and paginates once per action, without rewriting the filter object', a } }) +it('keeps the current page for equivalent filters and reloads after a nested filter changes', async () => { + const filter = reactive({ state: 'active' }) + const request = vi.fn(async (_params: TableProParams) => response('Alice')) + const wrapper = mount(RTablePro, { + props: { + columns, + request, + params: { filter: { state: 'active' } }, + tool: false, + }, + }) + + try { + await flushPromises() + await (wrapper.vm as unknown as TableProInst).setPage(2) + await wrapper.setProps({ params: { filter } }) + await flushPromises() + expect(request.mock.calls.map(([query]) => query.page)).toEqual([1, 2]) + + filter.state = 'disabled' + await flushPromises() + expect(request.mock.calls.map(([query]) => query.page)).toEqual([1, 2, 1]) + expect(request.mock.lastCall?.[0].filter).toEqual({ state: 'disabled' }) + } finally { + wrapper.unmount() + } +}) + it('ignores stale data even if the loader ignores cancellation', async () => { const first = Promise.withResolvers() const second = Promise.withResolvers() diff --git a/__test__/components/wrapper-contracts.spec.tsx b/__test__/components/wrapper-contracts.spec.tsx index 292166c0..f3aec078 100644 --- a/__test__/components/wrapper-contracts.spec.tsx +++ b/__test__/components/wrapper-contracts.spec.tsx @@ -65,12 +65,17 @@ it('preserves SVG root paint when no sprite service is installed', async () => { const wrapper = mount(RIcon, { props: { name: 'action/close_all' } }) try { - await vi.waitFor(() => expect(wrapper.find('svg rect').exists()).toBe(true)) + await vi.dynamicImportSettled() + expect(wrapper.find('svg rect').exists()).toBe(true) expect(wrapper.get('svg').attributes()).toMatchObject({ fill: 'none', stroke: 'currentColor', 'stroke-width': '1.8', }) + await wrapper.setProps({ name: 'action/reload' }) + await vi.dynamicImportSettled() + expect(wrapper.find('svg rect').exists()).toBe(false) + expect(wrapper.find('svg path').exists()).toBe(true) } finally { wrapper.unmount() } @@ -107,12 +112,21 @@ it('moves segment focus past disabled choices and emits each change once', async }) it('starts iframe loading for every source and exposes the same native element', async () => { - const wrapper = mount(RIframe, { props: { src: '/one.html' } }) + const wrapper = mount(RIframe, { + props: { src: '/one.html', sandbox: '', referrerpolicy: 'no-referrer' }, + attrs: { class: 'host-frame' }, + }) try { await nextTick() const frame = wrapper.get('iframe') + expect(frame.attributes('sandbox')).toBe('') + expect(frame.attributes('referrerpolicy')).toBe('no-referrer') + expect(wrapper.element.classList.contains('host-frame')).toBe(true) + expect(wrapper.element.hasAttribute('sandbox')).toBe(false) + await wrapper.setProps({ sandbox: 'allow-forms' }) + expect(frame.attributes('sandbox')).toBe('allow-forms') await frame.trigger('load') expect(wrapper.findComponent(NSpin).props('show')).toBe(false) await wrapper.setProps({ src: '/two.html' }) diff --git a/__test__/hooks/useSiderBar.spec.ts b/__test__/hooks/useSiderBar.spec.ts index 16ef62f7..5b6770d6 100644 --- a/__test__/hooks/useSiderBar.spec.ts +++ b/__test__/hooks/useSiderBar.spec.ts @@ -384,3 +384,69 @@ it('updates neutral and status document titles when the language changes', async await flushPromises() expect(document.title).toContain('工作区已就绪') }) + +it.each([ + 'close', + 'closeAll', + 'closeOther', + 'closeRight', + 'closeLeft', +] as const)( + 'preserves active, cached and saved tags when the guard declines %s', + async (operation) => { + const paths = + operation === 'closeLeft' + ? ['/orders', '/reports', '/private'] + : ['/orders', '/private', '/reports'] + + for (const path of paths) await router.push(path) + + if (operation === 'closeLeft') await router.push('/reports') + + const before = { + paths: menu.menuTagOptions.map((tag) => tag.fullPath), + saved: getCatchMenuTagOptions(), + cached: [...piniaKeepAliveStore().keepAliveInclude], + } + + router.beforeEach(() => false) + + if (operation === 'closeAll') await actions.closeAll() + else if (operation === 'close') await actions.close('/reports') + else + await actions[operation]( + operation === 'closeLeft' ? '/private' : '/orders', + ) + + expect(router.currentRoute.value.path).toBe('/reports') + expect(menu.menuKey).toBe('/reports') + expect(menu.menuTagOptions.map((tag) => tag.fullPath)).toEqual(before.paths) + expect(getCatchMenuTagOptions()).toEqual(before.saved) + expect(piniaKeepAliveStore().keepAliveInclude).toEqual(before.cached) + }, +) + +it('preserves a tab fixed while the close-all navigation is waiting', async () => { + await router.push('/orders') + await router.push('/reports') + const gate = Promise.withResolvers() + const entered = Promise.withResolvers() + + router.beforeEach(() => { + entered.resolve() + + return gate.promise + }) + const close = actions.closeAll() + + await entered.promise + expect(menu.menuTagOptions).toHaveLength(2) + menu.toggleMenuTagFixed('/orders') + gate.resolve(true) + await close + expect(router.currentRoute.value.path).toBe('/welcome') + expect(menu.menuTagOptions.map((tag) => tag.fullPath)).toEqual(['/orders']) + expect(getCatchMenuTagOptions().map((tag) => tag.fullPath)).toEqual([ + '/orders', + ]) +}) diff --git a/__test__/layout/breadcrumb.spec.tsx b/__test__/layout/breadcrumb.spec.tsx index ba471d63..d28131a4 100644 --- a/__test__/layout/breadcrumb.spec.tsx +++ b/__test__/layout/breadcrumb.spec.tsx @@ -5,6 +5,7 @@ import { h, nextTick, ref } from 'vue' import type { Ref } from 'vue' const state = vi.hoisted(() => ({ + select: vi.fn(), compact: null as unknown as Ref, icons: null as unknown as Ref, fallback: null as unknown as Ref, @@ -16,7 +17,7 @@ vi.mock('@/hooks', () => ({ })) vi.mock('@/store', () => ({ - useMenuActions: () => ({ changeMenuModelValue: vi.fn() }), + useMenuActions: () => ({ changeMenuModelValue: state.select }), useMenuGetters: () => ({ getBreadcrumbOptions: state.options }), useSettingGetters: () => ({ getBreadcrumbIcon: state.icons, @@ -71,3 +72,39 @@ it('displays menu images and defaults to a fallback for the missing icon', async wrapper.unmount() } }) + +it('opens sibling pages from the keyboard and closes after selection', async () => { + state.compact = ref(false) + state.icons = ref(false) + state.fallback = ref(false) + const monthly = option('/reports/monthly', 'Monthly') + + state.options = ref([ + { + ...option('/reports', 'Reports'), + children: [monthly, option('/reports/yearly', 'Yearly')], + }, + monthly, + ]) + const wrapper = mount(Breadcrumb, { attachTo: document.body }) + + try { + const trigger = wrapper.get( + 'button[aria-haspopup="menu"]', + ) + + trigger.element.focus() + await trigger.trigger('keydown', { key: 'ArrowDown' }) + expect(trigger.attributes('aria-expanded')).toBe('true') + await trigger.trigger('keydown', { key: 'ArrowDown' }) + await trigger.trigger('keydown', { key: 'Enter' }) + expect(state.select).toHaveBeenCalledWith( + '/reports/monthly', + expect.objectContaining({ fullPath: '/reports/monthly' }), + ) + expect(trigger.attributes('aria-expanded')).toBe('false') + expect(document.activeElement).toBe(trigger.element) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/layout/global-search.spec.ts b/__test__/layout/global-search.spec.ts index 9ce57c73..39d6652c 100644 --- a/__test__/layout/global-search.spec.ts +++ b/__test__/layout/global-search.spec.ts @@ -120,6 +120,13 @@ it('does not navigate while composing and supports keyboard result focus and Ent await wrapper.get('input').setValue('tablepro') await flushPromises() expect(wrapper.findAll('.global-search__destination')).toHaveLength(1) + expect( + wrapper.get('[data-enter-target] .global-search__destination').text(), + ).toBe('Visible page') + expect( + document.getElementById(input.getAttribute('aria-describedby')!) + ?.textContent, + ).toContain('Visible page') expect(wrapper.get('.global-search__destination').text()).toBe( 'Visible page', ) diff --git a/__test__/layout/menu-tag.spec.tsx b/__test__/layout/menu-tag.spec.tsx index 61c3b9c5..3bfc4109 100644 --- a/__test__/layout/menu-tag.spec.tsx +++ b/__test__/layout/menu-tag.spec.tsx @@ -256,7 +256,7 @@ it('applies a context command to the most recently right-clicked tag', async () await openContextMenu(2) const command = [ - ...document.querySelectorAll('.n-dropdown-option-body'), + ...document.querySelectorAll('.n-dropdown-option-body__label'), ].find((option) => option.textContent === 'closeCurrent') expect(command).toBeDefined() @@ -271,7 +271,7 @@ it('keeps context commands tied to the selected page when the order changes', as state.tags.value.reverse() await nextTick() const command = Array.from( - document.querySelectorAll('.n-dropdown-option-body'), + document.querySelectorAll('.n-dropdown-option-body__label'), ).find((option) => option.textContent === 'fix') mouse(command!, 'click', 0) @@ -569,3 +569,19 @@ it('dismisses the context menu with Escape after switching tags', async () => { await nextTick() expect(contextDropdown().props('show')).toBe(false) }) + +it('returns focus to tab actions after keyboard closing the final page', async () => { + state.tags.value.splice(1) + await nextTick() + state.close.mockImplementationOnce((index) => { + state.tags.value.splice(index, 1) + }) + const tab = wrapper.get('.menu-tag__tab') + + tab.element.focus() + await tab.trigger('keydown', { key: 'Delete' }) + await flushPromises() + expect(document.activeElement).toBe( + wrapper.get('button[aria-label="menuTag.actions"]').element, + ) +}) diff --git a/__test__/layout/slots.spec.ts b/__test__/layout/slots.spec.ts index 5d2c8298..cec7dc9d 100644 --- a/__test__/layout/slots.spec.ts +++ b/__test__/layout/slots.spec.ts @@ -44,6 +44,7 @@ it('offers a restore button for custom content and also exits with Escape', asyn setActivePinia(pinia) const runtime = piniaRuntimeStore() const wrapper = shallowMount(Layout, { + attachTo: document.body, global: { renderStubDefaultSlot: true, stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, @@ -58,6 +59,8 @@ it('offers a restore button for custom content and also exits with Escape', asyn expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe( false, ) + await wrapper.get('.r-layout-skip').trigger('click') + expect(document.activeElement).toBe(wrapper.get('main').element) runtime.setRuntimeState('layoutContentMaximize', true) await nextTick() expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true) diff --git a/__test__/utils/color-contrast.ts b/__test__/utils/color-contrast.ts new file mode 100644 index 00000000..572bf402 --- /dev/null +++ b/__test__/utils/color-contrast.ts @@ -0,0 +1,36 @@ +import { color } from 'echarts/core' + +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, + ) + +export 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) +} diff --git a/__test__/utils/setupMiniApp.ts b/__test__/utils/setupMiniApp.ts index 7668de34..39915ff2 100644 --- a/__test__/utils/setupMiniApp.ts +++ b/__test__/utils/setupMiniApp.ts @@ -1,5 +1,5 @@ import { setupI18n } from '../../apps/admin/src/locales' -import { setupRouter } from '../../apps/admin/src/router' +import { router, setupRouter } from '../../apps/admin/src/router' import { setupStore } from '../../apps/admin/src/store' import { piniaSigningStore } from '../../apps/admin/src/store/modules/signing' import Login from '../../apps/admin/src/views/login' @@ -26,6 +26,7 @@ const setupMiniApp = async (authenticated = false) => { ) await setupRouter(app, authenticated, Login) + await router.isReady() return { app, diff --git a/__test__/workspace/http-client.spec.ts b/__test__/workspace/http-client.spec.ts index 1bf404eb..280f4c9c 100644 --- a/__test__/workspace/http-client.spec.ts +++ b/__test__/workspace/http-client.spec.ts @@ -1,3 +1,5 @@ +// @vitest-environment node + import { createHttpClient } from '@ray-template/http' import RequestCanceler from '@ray-template/http/RequestCanceler' import type { AppRawRequestConfig } from '@ray-template/http/types' @@ -44,6 +46,56 @@ it('compares repeated form fields, URL parameters and uploaded file identity whe expect(anotherFile.aborted).toBe(true) }) +it('keeps independent binary uploads pending and cancels repeats of the same instance', async () => { + const pending: Array<() => void> = [] + const adapter: AxiosAdapter = (config) => + new Promise((resolve, reject) => { + pending.push(() => + resolve({ + data: 'ok', + status: 200, + statusText: 'OK', + headers: {}, + config, + }), + ) + config.signal?.addEventListener?.('abort', () => + reject(new AxiosError('aborted', 'ERR_CANCELED', config)), + ) + }) + const { request, canceler } = createHttpClient({ axios: { adapter } }) + const upload = (data: unknown) => + request.post('/binary', data).catch((error: AxiosError) => error.code) + const bodies = [ + new Blob(['a']), + new Blob(['b']), + new File(['a'], 'same.bin'), + new File(['b'], 'same.bin'), + new Uint8Array([1]).buffer, + new Uint8Array([2]).buffer, + new Uint8Array([1]), + new Uint8Array([1]), + new DataView(new ArrayBuffer(1)), + new DataView(new ArrayBuffer(1)), + new ReadableStream(), + new ReadableStream(), + ] + const uploads = bodies.map(upload) + + await vi.waitFor(() => expect(pending).toHaveLength(bodies.length)) + expect(canceler.getPendingCount()).toBe(bodies.length) + const repeated = upload(bodies[0]) + + await vi.waitFor(() => expect(pending).toHaveLength(bodies.length + 1)) + expect(await uploads[0]).toBe('ERR_CANCELED') + expect(canceler.getPendingCount()).toBe(bodies.length) + pending.forEach((finish) => finish()) + expect(await Promise.all([...uploads.slice(1), repeated])).toEqual( + bodies.map(() => 'ok'), + ) + expect(canceler.getPendingCount()).toBe(0) +}) + it('isolates pending requests by client and leaves caller-owned signals intact', async () => { const pending: Array<{ signal: unknown; finish: () => void }> = [] const adapter: AxiosAdapter = (config) => diff --git a/__test__/workspace/no-undefined.spec.ts b/__test__/workspace/no-undefined.spec.ts new file mode 100644 index 00000000..aa70beb0 --- /dev/null +++ b/__test__/workspace/no-undefined.spec.ts @@ -0,0 +1,85 @@ +// @vitest-environment node + +import { ESLint } from 'eslint' + +const ruleId = 'ray-template/no-undefined' +const eslint = new ESLint({ + fix: true, + ruleFilter: (rule) => rule.ruleId === ruleId, + overrideConfig: { languageOptions: { parserOptions: { project: false } } }, +}) + +async function lint(source: string, extension = 'ts') { + const [result] = await eslint.lintText(source, { + filePath: `__test__/workspace/fixture.${extension}`, + }) + + expect(result.fatalErrorCount, result.messages[0]?.message).toBe(0) + + return { code: result.output ?? source, messages: result.messages } +} + +it.each([ + [ + 'ts', + 'let value: string | undefined = undefined\nvalue = undefined\nuse(undefined)\nvalue === undefined', + 'let value: string | undefined = void 0\nvalue = void 0\nuse(void 0)\nvalue === void 0', + ], + [ + 'ts', + 'const options = { value: undefined, undefined }', + 'const options = { value: void 0, undefined: void 0 }', + ], + [ + 'tsx', + 'const element = ', + 'const element = ', + ], + [ + 'vue', + '', + '', + ], + [ + 'mjs', + 'const result = []\nundefined?.method()', + 'const result = []\n;(void 0)?.method()', + ], + [ + 'mjs', + 'if (enabled) undefined?.method()', + 'if (enabled) (void 0)?.method()', + ], + [ + 'mjs', + 'const power = undefined ** 2\nconst result = new (undefined)()', + 'const power = (void 0) ** 2\nconst result = new (void 0)()', + ], +])('fixes runtime reads in %s from %s', async (extension, source, expected) => { + expect(await lint(source, extension)).toEqual({ + code: expected, + messages: [], + }) +}) + +it('preserves type keywords, type queries, literal keys, and member names', async () => { + const source = + 'type Value = typeof undefined | undefined\n({ undefined: obj.undefined })' + + expect(await lint(source)).toEqual({ code: source, messages: [] }) +}) + +it.each([ + ['mjs', 'function read(undefined) { return undefined }'], + ['mjs', 'undefined = 42'], + ['cjs', 'delete undefined'], + ['cjs', 'function read() { eval("var undefined = 42"); return undefined }'], +])('reports unsafe replacements in %s from %s', async (extension, source) => { + const { code, messages } = await lint(source, extension) + + expect(code).toBe(source) + expect(messages.length).toBeGreaterThan(0) + expect( + messages.every((message) => message.ruleId === ruleId && !message.fix), + ).toBe(true) +}) diff --git a/apps/admin/index.html b/apps/admin/index.html index 8fceb775..1d573f4e 100644 --- a/apps/admin/index.html +++ b/apps/admin/index.html @@ -109,7 +109,7 @@ --boot-line: light-dark(#efeff5, #343438); --boot-text: light-dark(#333639, #f0f0f0); --boot-muted: light-dark(#666970, #b5b5b8); - --boot-accent: light-dark(#18a058, #63e2b7); + --boot-accent: light-dark(#137743, #63e2b7); --boot-radius: 4px; --boot-shadow: none; } diff --git a/apps/admin/package.json b/apps/admin/package.json index 872e7501..7eb89f99 100644 --- a/apps/admin/package.json +++ b/apps/admin/package.json @@ -2,7 +2,7 @@ "name": "@ray-template/admin", "private": true, "type": "module", - "version": "6.0.2", + "version": "6.0.3", "dependencies": { "@faker-js/faker": "10.6.0", "@logicflow/core": "2.2.5", diff --git a/apps/admin/src/axios/README.md b/apps/admin/src/axios/README.md index 9e4eb072..6218028f 100644 --- a/apps/admin/src/axios/README.md +++ b/apps/admin/src/axios/README.md @@ -20,4 +20,4 @@ const loadOrders = (signal: AbortSignal) => }) ``` -The canceller compares encoded URLSearchParams and ordered FormData entries, including file identity. Passing a signal or setting `cancelConfig.cancel` to `false` opts out of default cancellation. The person list demonstrates [forwarding TablePro's signal](../api/demo/mock/person.ts). `useRequest` wraps the same instance and must run within an active Vue effect scope. +The canceller compares encoded URLSearchParams and ordered FormData entries, including file identity. Raw files, blobs, array buffers, typed-array or DataView bodies, and readable streams are identified by instance. Reuse the same instance to replace an earlier pending upload. Passing a signal or setting `cancelConfig.cancel` to `false` opts out of default cancellation. The person list demonstrates [forwarding TablePro's signal](../api/demo/mock/person.ts). `useRequest` wraps the same instance and must run within an active Vue effect scope. diff --git a/apps/admin/src/hooks/README.md b/apps/admin/src/hooks/README.md index 824b3a36..d12f7075 100644 --- a/apps/admin/src/hooks/README.md +++ b/apps/admin/src/hooks/README.md @@ -42,6 +42,6 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r - `usePagination` resets to the first option in the current `pagination.value.pageSizes` and supports Naive UI object options. Default option arrays are isolated between instances. Calling `setCallback()` removes the default callback. - `useDomToImage` loads the rendering library on the first `create` call; import failures use the same error and cleanup callbacks as renderer failures. - A disposed `useElementFullscreen` instance cannot enter again; create a fresh instance in a live scope when a target is remounted. -- `usePrint` unwraps its target when called. DOM targets print as HTML by default. Blob images and binary PDFs are converted first; callers can await the returned Promise. +- `usePrint` unwraps its target when called. DOM targets print as HTML by default. Blob images and binary PDFs are converted first; callers can await the returned Promise. The composables package marks its entry point and the Day.js locale registration as side-effectful so that unused hook re-exports do not load the print engine. Screenshots and printing depend on real browsers. Happy DOM tests verify state and error handling; they do not replace native print-dialog or physical-output acceptance. diff --git a/apps/admin/src/hooks/template/useSiderBar.ts b/apps/admin/src/hooks/template/useSiderBar.ts index b3e86685..7165956f 100644 --- a/apps/admin/src/hooks/template/useSiderBar.ts +++ b/apps/admin/src/hooks/template/useSiderBar.ts @@ -6,35 +6,6 @@ import { useVueRouter } from './useVueRouter' export type CloseMenuTag = Key | MenuTagOptions -/** - * - * @param target 标签页对象、索引或路径 - * @param fn 用于日志的调用方方法名 - * - * @returns 当前标签列表中的对象和索引,找不到时返回 undefined。 - */ -const normalMenuTagOption = (target: CloseMenuTag, fn: string) => { - const { getMenuTagOptions } = useMenuGetters() - - const tags = getMenuTagOptions.value - const index = - typeof target === 'number' - ? target - : tags.findIndex( - (tag) => - tag.fullPath === - (typeof target === 'string' ? target : target.fullPath), - ) - - if (!Number.isInteger(index) || index < 0 || index >= tags.length) { - console.warn(`[${fn}]: Could not find menu tag.`) - - return - } - - return { option: tags[index], index } -} - /** * * @returns 标签页检查与关闭方法;状态由共享菜单 Store 持有。 @@ -42,23 +13,69 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => { export function useSiderBar() { const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters() const { router } = useVueRouter() - const { - changeMenuModelValue, - spliceMenTagOptions, - setMenuTagOptions, - isMenuTagFixed, - } = useMenuActions() - + const { setMenuTagOptions, isMenuTagFixed } = useMenuActions() const canClose = (tag: MenuTagOptions) => !isMenuTagFixed(tag) - const closeWhere = (matches: (index: number) => boolean) => { - const current = getMenuTagOptions.value - const remaining = current.filter( - (tag, index) => !matches(index) || !canClose(tag), - ) - if (remaining.length !== current.length) setMenuTagOptions(remaining, false) + /** + * + * @param target 标签页对象、索引或路径 + * @param fn 用于日志的调用方方法名 + * + * @returns 当前标签列表中的对象和索引,找不到时返回 undefined。 + */ + const normalMenuTagOption = (target: CloseMenuTag, fn: string) => { + const tags = getMenuTagOptions.value + const index = + typeof target === 'number' + ? target + : tags.findIndex( + (tag) => + tag.fullPath === + (typeof target === 'string' ? target : target.fullPath), + ) - return remaining + if (!Number.isInteger(index) || index < 0 || index >= tags.length) { + console.warn(`[${fn}]: Could not find menu tag.`) + + return + } + + return { option: tags[index], index } + } + + const closeTags = ( + candidates: MenuTagOptions[], + destination?: string, + replace = false, + ) => { + const closing = new Set(candidates.filter(canClose)) + const commit = () => { + // 守卫等待期间,其他调用方可以打开、固定或替换标签;只移除本次选定且仍可关闭的项。 + const current = getMenuTagOptions.value + const remaining = current.filter( + (tag) => !closing.has(tag) || !canClose(tag), + ) + + if (remaining.length !== current.length) + setMenuTagOptions(remaining, false) + } + + if (!destination || router.currentRoute.value.fullPath === destination) { + commit() + + return + } + + const navigation = replace + ? router.replace(destination) + : router.push(destination) + + return navigation.then((failure) => { + if (!failure && router.currentRoute.value.fullPath === destination) + commit() + + return failure + }) } /** @@ -81,7 +98,10 @@ export function useSiderBar() { const normal = normalMenuTagOption(target, 'checkCloseRight') return ( - !!normal && getMenuTagOptions.value.slice(normal.index + 1).some(canClose) + !!normal && + getMenuTagOptions.value.some( + (tag, index) => index > normal.index && canClose(tag), + ) ) } @@ -95,7 +115,10 @@ export function useSiderBar() { const normal = normalMenuTagOption(target, 'checkCloseLeft') return ( - !!normal && getMenuTagOptions.value.slice(0, normal.index).some(canClose) + !!normal && + getMenuTagOptions.value.some( + (tag, index) => index < normal.index && canClose(tag), + ) ) } @@ -115,16 +138,15 @@ export function useSiderBar() { const { index, option } = normal const active = option.fullPath === getCurrentMenuOption.value?.fullPath - spliceMenTagOptions(index) + const tags = getMenuTagOptions.value - if (!getMenuTagOptions.value.length) - return router.replace(WELCOME_ROUTE_PATH) + if (tags.length === 1) + return closeTags([option], WELCOME_ROUTE_PATH, true) - if (active) { - const tag = getMenuTagOptions.value[Math.max(0, index - 1)] - - return tag && changeMenuModelValue(tag.fullPath, tag) - } + return closeTags( + [option], + active ? (tags[index - 1] ?? tags[index + 1]).fullPath : void 0, + ) } } @@ -137,11 +159,16 @@ export function useSiderBar() { */ const closeAll = () => { const current = getCurrentMenuOption.value?.fullPath - const remaining = closeWhere(() => true) + const tags = getMenuTagOptions.value + const fixed = tags.filter(isMenuTagFixed) - if (remaining.some((tag) => tag.fullPath === current)) return - - return router.replace(remaining[0]?.fullPath ?? WELCOME_ROUTE_PATH) + return closeTags( + tags, + fixed.some((tag) => tag.fullPath === current) + ? void 0 + : (fixed[0]?.fullPath ?? WELCOME_ROUTE_PATH), + true, + ) } const closeForbiddenPage = () => { @@ -174,10 +201,12 @@ export function useSiderBar() { const currentIndex = getCurrentTagIndex() const current = getMenuTagOptions.value[currentIndex] - closeWhere((tagIndex) => tagIndex > index) - - if (currentIndex > index && canClose(current)) - return changeMenuModelValue(option.fullPath, option) + return closeTags( + getMenuTagOptions.value.slice(index + 1), + current && currentIndex > index && canClose(current) + ? option.fullPath + : void 0, + ) } } @@ -196,10 +225,12 @@ export function useSiderBar() { const currentIndex = getCurrentTagIndex() const current = getMenuTagOptions.value[currentIndex] - closeWhere((tagIndex) => tagIndex < index) - - if (currentIndex >= 0 && currentIndex < index && canClose(current)) - return changeMenuModelValue(option.fullPath, option) + return closeTags( + getMenuTagOptions.value.slice(0, index), + current && currentIndex < index && canClose(current) + ? option.fullPath + : void 0, + ) } } @@ -214,12 +245,14 @@ export function useSiderBar() { const normal = normalMenuTagOption(target, 'closeOther') if (normal) { - const { option, index } = normal + const { option } = normal - closeWhere((tagIndex) => tagIndex !== index) - - if (getCurrentMenuOption.value?.fullPath !== option.fullPath) - return changeMenuModelValue(option.fullPath, option) + return closeTags( + getMenuTagOptions.value.filter((tag) => tag !== option), + getCurrentMenuOption.value?.fullPath === option.fullPath + ? void 0 + : option.fullPath, + ) } } diff --git a/apps/admin/src/layout/components/MenuTag/index.tsx b/apps/admin/src/layout/components/MenuTag/index.tsx index 0dceace8..b9fec55c 100644 --- a/apps/admin/src/layout/components/MenuTag/index.tsx +++ b/apps/admin/src/layout/components/MenuTag/index.tsx @@ -101,7 +101,7 @@ export default defineComponent({ { label: t('maximize'), key: 'maximizeLayoutContent', - icon: () => , + icon: () => , }, { label: t('reload'), @@ -264,24 +264,35 @@ export default defineComponent({ ? translate(tag.meta.i18nKey) : tag.breadcrumbLabel || tag.fullPath - const closeCurrentMenuTag = (index: number, restoreFocus = false) => { + const closeCurrentMenuTag = async (index: number, restoreFocus = false) => { const option = getMenuTagOptions.value[index] if (!option || !canClose(option)) return - const focusIndex = - option.fullPath === getMenuKey.value ? Math.max(0, index - 1) : index + const wasActive = option.fullPath === getMenuKey.value + const failure = await close(index) - close(index) + if ( + failure || + !restoreFocus || + getMenuTagOptions.value.some((tag) => tag.fullPath === option.fullPath) + ) + return - if (restoreFocus) { - void nextTick(() => { - const tabs = - tagsRef.value?.querySelectorAll('.menu-tag__tab') + await nextTick() + const tabs = + tagsRef.value?.querySelectorAll('.menu-tag__tab') + const adjacent = tabs?.[Math.min(index, tabs.length - 1)] + const focus = + (wasActive + ? tagsRef.value?.querySelector( + '.menu-tag__tab[aria-current="page"]', + ) + : adjacent) ?? + adjacent ?? + actionsButton.value - tabs?.[Math.min(focusIndex, tabs.length - 1)]?.focus() - }) - } + focus?.focus() } // 菜单标签点击更新当前菜单激活项 @@ -623,7 +634,7 @@ export default defineComponent({ title={$t('layout.maximize')} onClick={() => this.maximize(true)} > - + + ) : option !== current && + !option.children?.length && + !option.meta.sameLevel ? ( + ) : ( renderLabel(option, option === current) )} diff --git a/apps/admin/src/layout/index.tsx b/apps/admin/src/layout/index.tsx index 87c3807d..53a49520 100644 --- a/apps/admin/src/layout/index.tsx +++ b/apps/admin/src/layout/index.tsx @@ -90,6 +90,7 @@ export default defineComponent({ maximizedStyle={layoutContentMaximizeStyle.value} contentRef={LAYOUT_CONTENT_REF} restore={() => maximize(false)} + skipContentLabel={t('skipToContent')} restoreLabel={t('restore')} > {{ diff --git a/apps/admin/src/locales/lang/en-US/layout.json b/apps/admin/src/locales/lang/en-US/layout.json index 1cffa06c..4e481653 100644 --- a/apps/admin/src/locales/lang/en-US/layout.json +++ b/apps/admin/src/locales/lang/en-US/layout.json @@ -24,6 +24,7 @@ "current": "Current configuration", "extension": "Extend the layout", "slots": "Use header, sidebar, tabs, footer and default content slots. Update the Pinia configuration to switch layouts.", + "skipToContent": "Skip to main content", "navigation": "Main navigation", "maximize": "Maximize content", "restore": "Restore content size (Esc)", diff --git a/apps/admin/src/locales/lang/en-US/navigationSearch.json b/apps/admin/src/locales/lang/en-US/navigationSearch.json index 093c7d22..d72d1871 100644 --- a/apps/admin/src/locales/lang/en-US/navigationSearch.json +++ b/apps/admin/src/locales/lang/en-US/navigationSearch.json @@ -11,6 +11,7 @@ "empty": "Search for a page and use the star to save a favorite.", "storageUnavailable": "Your browser cannot save history right now. It remains available for this visit.", "move": "Move", + "enterTarget": "Enter opens {title}", "open": "Open", "close": "Close" } diff --git a/apps/admin/src/locales/lang/en-US/userManagement.json b/apps/admin/src/locales/lang/en-US/userManagement.json index 9d4894e1..a5254cd7 100644 --- a/apps/admin/src/locales/lang/en-US/userManagement.json +++ b/apps/admin/src/locales/lang/en-US/userManagement.json @@ -1,6 +1,7 @@ { "title": "User management", "descriptionMock": "Manage members by organization. The online demo uses Mock APIs, with data saved in this browser.", + "descriptionMockCompact": "Demo data is saved in this browser.", "descriptionServer": "Manage member profiles, roles and account status by organization.", "organization": "Organization", "createUser": "Add user", diff --git a/apps/admin/src/locales/lang/zh-CN/layout.json b/apps/admin/src/locales/lang/zh-CN/layout.json index b8f92083..e1f7a5e5 100644 --- a/apps/admin/src/locales/lang/zh-CN/layout.json +++ b/apps/admin/src/locales/lang/zh-CN/layout.json @@ -24,6 +24,7 @@ "current": "当前布局配置", "extension": "扩展布局", "slots": "布局提供 header、sidebar、tabs、footer 和默认内容插槽。通过 Pinia 更新配置即可切换布局。", + "skipToContent": "跳至主内容", "navigation": "主导航", "maximize": "最大化内容区域", "restore": "退出内容最大化(Esc)", diff --git a/apps/admin/src/locales/lang/zh-CN/navigationSearch.json b/apps/admin/src/locales/lang/zh-CN/navigationSearch.json index 30c3eccc..371f79e7 100644 --- a/apps/admin/src/locales/lang/zh-CN/navigationSearch.json +++ b/apps/admin/src/locales/lang/zh-CN/navigationSearch.json @@ -11,6 +11,7 @@ "empty": "搜索页面,并点击星标收藏常用入口。", "storageUnavailable": "浏览器暂时无法保存记录,本次访问中仍可使用。", "move": "切换", + "enterTarget": "按回车打开{title}", "open": "打开", "close": "关闭" } diff --git a/apps/admin/src/locales/lang/zh-CN/userManagement.json b/apps/admin/src/locales/lang/zh-CN/userManagement.json index 0311a940..2cff98e0 100644 --- a/apps/admin/src/locales/lang/zh-CN/userManagement.json +++ b/apps/admin/src/locales/lang/zh-CN/userManagement.json @@ -1,6 +1,7 @@ { "title": "用户管理", "descriptionMock": "按组织管理成员资料与状态。在线演示通过 Mock 接口读写,数据保存在当前浏览器。", + "descriptionMockCompact": "演示数据保存在当前浏览器。", "descriptionServer": "按组织管理成员资料、角色与账号状态。", "organization": "组织架构", "createUser": "新增用户", diff --git a/apps/admin/src/locales/lang/zh-CN/views/login/index.json b/apps/admin/src/locales/lang/zh-CN/views/login/index.json index 9c0f2cc9..05ab212f 100644 --- a/apps/admin/src/locales/lang/zh-CN/views/login/index.json +++ b/apps/admin/src/locales/lang/zh-CN/views/login/index.json @@ -11,7 +11,7 @@ "Password": "密码", "ShowPassword": "显示密码", "HidePassword": "隐藏密码", - "RayTemplate": "构建你的中后台管理系统", + "RayTemplate": "构建你的\n中后台管理系统", "TemplateDescription": "基于 Vue 3、TypeScript 和 Naive UI 的开源中后台管理模板。", "OtherSignInOptions": "其他登录方式示例", "Resources": "项目资源", diff --git a/apps/admin/src/views/dashboard/index.tsx b/apps/admin/src/views/dashboard/index.tsx index 97a14324..c9c6e1d4 100644 --- a/apps/admin/src/views/dashboard/index.tsx +++ b/apps/admin/src/views/dashboard/index.tsx @@ -80,17 +80,6 @@ export default defineComponent({ -
- {stack.map((item) => ( -
- {item.name} - {item.version} - - {item.name === 'Pinia' ? text('stateManagement') : item.detail} - -
- ))} -
{shortcuts.value.length ? (

@@ -120,6 +109,17 @@ export default defineComponent({

) : null} +
+ {stack.map((item) => ( +
+ {item.name} + {item.version} + + {item.name === 'Pinia' ? text('stateManagement') : item.detail} + +
+ ))} +

{text('projectDescription')}

diff --git a/apps/admin/src/views/demo/components/index.scss b/apps/admin/src/views/demo/components/index.scss index adcb1d79..27ab85ca 100644 --- a/apps/admin/src/views/demo/components/index.scss +++ b/apps/admin/src/views/demo/components/index.scss @@ -12,7 +12,7 @@ .r-showcase-meta { padding: 7px 12px; border: 1px solid var(--r-line); - border-radius: 8px; + border-radius: var(--r-control-radius); color: var(--r-text-secondary); background: var(--r-surface); font-size: 12px; @@ -146,7 +146,7 @@ min-height: 150px; padding: 12px; border: 1px solid var(--r-line); - border-radius: 10px; + border-radius: var(--r-radius); background: #fff; color: #182436; overflow: auto; @@ -162,7 +162,7 @@ gap: 6px; padding: 12px 14px; border: 1px solid var(--r-line); - border-radius: 8px; + border-radius: var(--r-radius); background: var(--r-surface-muted); color: var(--r-text); @@ -192,7 +192,7 @@ min-height: 112px; display: grid; place-items: center; - border-radius: 8px; + border-radius: var(--r-radius); background: var(--r-canvas); span { @@ -200,7 +200,7 @@ block-size: 68px; border: 1px solid var(--r-control-border); border-block-start: 10px solid var(--r-theme-primary-color); - border-radius: 5px; + border-radius: var(--r-radius); background: var(--r-surface); } @@ -227,5 +227,5 @@ min-width: 0; overflow: hidden; border: 1px solid var(--r-line); - border-radius: 8px; + border-radius: var(--r-radius); } diff --git a/apps/admin/src/views/demo/curd/ProjectEditor.tsx b/apps/admin/src/views/demo/curd/ProjectEditor.tsx index 75a2c7a1..68566767 100644 --- a/apps/admin/src/views/demo/curd/ProjectEditor.tsx +++ b/apps/admin/src/views/demo/curd/ProjectEditor.tsx @@ -1,3 +1,4 @@ +import './project-editor.scss' import { useI18n } from '@/hooks/template/useI18n' import { useRuntimeGetters } from '@/store/hooks/useRuntimeStore' import { RForm } from '@ray-template/ui/form' @@ -159,11 +160,12 @@ export default defineComponent({ labelProps={{ for: field('summary') }} >
diff --git a/apps/admin/src/views/demo/curd/project-editor.scss b/apps/admin/src/views/demo/curd/project-editor.scss new file mode 100644 index 00000000..7b1630c9 --- /dev/null +++ b/apps/admin/src/views/demo/curd/project-editor.scss @@ -0,0 +1,5 @@ +// 在 Naive UI 首次测量镜像之前设好行数边界,避免观察回调再次改变父容器高度。 +.curd-project-editor__summary .n-input__textarea-mirror { + min-block-size: calc(2lh + 2 * var(--n-padding-vertical)); + max-block-size: calc(6lh + 2 * var(--n-padding-vertical)); +} diff --git a/apps/admin/src/views/demo/hooks/index.scss b/apps/admin/src/views/demo/hooks/index.scss index 1b838711..eb5bdfa5 100644 --- a/apps/admin/src/views/demo/hooks/index.scss +++ b/apps/admin/src/views/demo/hooks/index.scss @@ -2,7 +2,7 @@ margin: 0; padding: 16px 18px; border: 1px solid var(--r-line); - border-radius: 8px; + border-radius: var(--r-radius); color: var(--r-text-secondary); background: var(--r-surface-muted); white-space: pre-wrap; @@ -39,7 +39,7 @@ width: 30px; height: 30px; flex-shrink: 0; - border-radius: 8px; + border-radius: var(--r-control-radius); color: var(--r-text-secondary); background: var(--r-surface-muted); font-family: Georgia, serif; @@ -73,7 +73,7 @@ margin: 0 24px 20px; padding: 16px; border: 1px solid var(--r-line); - border-radius: 8px; + border-radius: var(--r-radius); background: var(--r-surface-muted); &__label { @@ -147,7 +147,7 @@ position: relative; padding: 28px; border: 1px solid var(--r-line); - border-radius: 12px; + border-radius: var(--r-radius); background: var(--r-surface); color: var(--r-text); box-shadow: var(--r-shadow-soft); diff --git a/apps/admin/src/views/demo/rely/views/rely-about/index.scss b/apps/admin/src/views/demo/rely/views/rely-about/index.scss index 650c679d..d7b96c59 100644 --- a/apps/admin/src/views/demo/rely/views/rely-about/index.scss +++ b/apps/admin/src/views/demo/rely/views/rely-about/index.scss @@ -19,7 +19,7 @@ gap: 8px; padding: 10px; border: 1px solid var(--r-line); - border-radius: 8px; + border-radius: var(--r-control-radius); background: var(--r-surface-muted); overflow-wrap: anywhere; } diff --git a/apps/admin/src/views/demo/svg-icons/index.scss b/apps/admin/src/views/demo/svg-icons/index.scss index e07bb14c..9bac08e3 100644 --- a/apps/admin/src/views/demo/svg-icons/index.scss +++ b/apps/admin/src/views/demo/svg-icons/index.scss @@ -40,7 +40,7 @@ place-items: center; min-width: 22px; height: 20px; - border-radius: 5px; + border-radius: var(--r-control-radius); color: var(--r-text-muted); background: var(--r-surface-muted); font-size: 10px; @@ -64,8 +64,8 @@ justify-content: center; align-items: center; border: 1px solid var(--r-line); - border-radius: 9px; - color: var(--r-text-secondary); + border-radius: var(--r-control-radius); + color: var(--r-text); background: var(--r-surface-muted); cursor: pointer; transition: @@ -73,17 +73,18 @@ border-color 0.18s ease; > span:last-child { + color: var(--r-text-secondary); font-family: var(--r-font-mono); - font-size: 10px; + font-size: 12px; overflow-wrap: anywhere; } - &:hover { + &:hover, + &:focus-visible { border-color: var(--r-control-border); background: var(--r-surface); - color: var(--r-text); } &:focus-visible { - outline: 2px solid var(--r-theme-primary-color); + outline: 2px solid var(--r-text); outline-offset: 2px; } } diff --git a/apps/admin/src/views/login/index.scss b/apps/admin/src/views/login/index.scss index 621df94e..75cf9604 100644 --- a/apps/admin/src/views/login/index.scss +++ b/apps/admin/src/views/login/index.scss @@ -39,7 +39,7 @@ grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); grid-template-areas: 'story panel'; border: 1px solid var(--r-line); - border-radius: 20px; + border-radius: var(--r-radius); overflow: clip; background: var(--r-surface); box-shadow: var(--r-shadow-soft); @@ -57,12 +57,11 @@ flex-direction: column; justify-content: space-between; gap: 44px; - color: #f1f7ff; - background: - radial-gradient(ellipse at 95% 88%, #204c7e, transparent 64%), #132743; + color: var(--r-text); + background-color: var(--r-surface-muted); .login__eyebrow { - color: #9ce7ff; + color: var(--login-story-secondary, var(--r-text-secondary)); } h2 { @@ -74,13 +73,28 @@ text-wrap: balance; } + h2:lang(zh) { + max-width: none; + white-space: pre-line; + word-break: keep-all; + overflow-wrap: anywhere; + } + h2 + p { max-width: 36ch; - color: #c6d7eb; + color: var(--login-story-secondary, var(--r-text-secondary)); line-height: 1.75; } } + &--modern &__story { + background-image: radial-gradient( + ellipse at 95% 88%, + color-mix(in srgb, var(--r-theme-primary-color) 24%, transparent), + transparent 66% + ); + } + &__stack { display: flex; flex-wrap: wrap; @@ -90,8 +104,8 @@ margin: 24px 0 0; li { - border: 1px solid #6983a3; - border-radius: 100px; + border: 1px solid color-mix(in srgb, currentColor 45%, transparent); + border-radius: var(--r-control-radius); padding: 5px 12px; font-size: 12px; } @@ -107,7 +121,7 @@ background: repeating-radial-gradient( circle, transparent 0 29px, - rgb(156 231 255 / 20%) 30px 31px + color-mix(in srgb, currentColor 15%, transparent) 30px 31px ); } @@ -154,6 +168,16 @@ } } +.r-template--light .login--modern .login__story { + --login-story-secondary: color-mix( + in srgb, + var(--r-surface) 84%, + var(--r-text) + ); + color: var(--r-surface); + background-color: var(--r-text); +} + @media (max-width: 760px) { .login { &__grid { diff --git a/apps/admin/src/views/login/index.tsx b/apps/admin/src/views/login/index.tsx index d7668772..49131d42 100644 --- a/apps/admin/src/views/login/index.tsx +++ b/apps/admin/src/views/login/index.tsx @@ -4,7 +4,7 @@ import AppShareLink from '@/app-components/app/AppShareLink' import { LOCAL_OPTIONS } from '@/app-config' import { useI18n } from '@/hooks' import ThemeSwitch from '@/layout/components/SiderBar/components/SettingDrawer/components/ThemeSwitch' -import { useSettingActions } from '@/store' +import { useSettingActions, useSettingGetters } from '@/store' import { navigateHorizontalChoice } from '@ray-template/composables/element' import { RIcon } from '@ray-template/ui/icon' import { NButton, NDropdown, NFlex, NTab, NTabs } from 'naive-ui' @@ -23,6 +23,7 @@ export default defineComponent({ name: 'RLogin', setup() { const { updateLocale } = useSettingActions() + const { getThemeStyle } = useSettingGetters() const { t } = useI18n('views.login.index') const tabsValue = ref('signing') const tabsId = useId() @@ -33,6 +34,7 @@ export default defineComponent({ return { updateLocale, + getThemeStyle, tabsValue, tabsId, copyright: __APP_CFG__.layout.copyright, @@ -43,7 +45,7 @@ export default defineComponent({ const copy = (key: string) => $t(`views.login.index.${key}`) return ( -
+
diff --git a/packages/ui/src/RTablePro/src/index.scss b/packages/ui/src/RTablePro/src/index.scss index 07e496e2..1aee81ff 100644 --- a/packages/ui/src/RTablePro/src/index.scss +++ b/packages/ui/src/RTablePro/src/index.scss @@ -160,6 +160,14 @@ } } +.r-table-search__inline-actions { + align-self: end; + + .r-table-search__actions { + justify-content: flex-start; + } +} + .r-table-search__item { min-inline-size: 0; diff --git a/packages/ui/src/RTablePro/src/useTableRequest.ts b/packages/ui/src/RTablePro/src/useTableRequest.ts index 426b8ee6..ed847cbc 100644 --- a/packages/ui/src/RTablePro/src/useTableRequest.ts +++ b/packages/ui/src/RTablePro/src/useTableRequest.ts @@ -42,14 +42,12 @@ export function useTableRequest({ if (!load) return + // 只有某一来源的快照确实改变才合并;搜索字段可覆盖同名外部参数。 const values = filters() - delete values.page - delete values.pageSize - return previous?.request === load && isEqual(previous.filters, values) ? previous - : { request: load, filters: cloneDeep(values) } + : { request: load, filters: values } }) const scopedResult = computed(() => diff --git a/packages/ui/src/theme-presets.ts b/packages/ui/src/theme-presets.ts index 761fa5f9..816af188 100644 --- a/packages/ui/src/theme-presets.ts +++ b/packages/ui/src/theme-presets.ts @@ -7,6 +7,15 @@ export const rayPrimaryColor = { type ThemePalette = Record<'light' | 'dark', GlobalThemeOverrides> +// 深色输入和选择器默认使用透明边框,需显式采用当前风格的控件边界色。 +const darkFields = ( + common: NonNullable & { borderColor: string }, +) => ({ + common, + Input: { border: `1px solid ${common.borderColor}` }, + InternalSelection: { border: `1px solid ${common.borderColor}` }, +}) + const modernComponents = { Card: { borderRadius: '12px', @@ -21,7 +30,7 @@ const modernComponents = { export const rayThemeOverrides = { dark: { ...modernComponents, - common: { + ...darkFields({ borderRadius: '8px', fontWeightStrong: '600', lineHeight: '1.6', @@ -44,7 +53,7 @@ export const rayThemeOverrides = { primaryColorPressed: '#96a9fa', primaryColorSuppl: '#aabaff', boxShadow1: '0 1px 2px rgb(0 0 0 / 10%), 0 8px 24px rgb(0 0 0 / 10%)', - }, + }), Layout: { siderColor: '#172131', headerColor: '#172131' }, }, light: { @@ -68,7 +77,7 @@ export const rayThemeOverrides = { dividerColor: '#e4e9f1', hoverColor: 'rgba(82, 100, 124, 0.06)', primaryColor: rayPrimaryColor.primaryColor, - primaryColorHover: '#4b70df', + primaryColorHover: '#486cda', primaryColorPressed: '#2b50be', primaryColorSuppl: rayPrimaryColor.primaryColor, boxShadow1: '0 1px 2px rgb(25 43 74 / 3%), 0 6px 20px rgb(25 43 74 / 3%)', @@ -114,7 +123,19 @@ export const normalizeThemeStyle = (value: unknown): ThemeStyle => themeStyles.find((style) => style === value) ?? DEFAULT_THEME_STYLE export const themeStyleOverrides: Record = { - naive: { light: {}, dark: {} }, + naive: { + light: { + common: { + primaryColor: '#137743', + primaryColorHover: '#16824a', + primaryColorPressed: '#0f6538', + primaryColorSuppl: '#137743', + placeholderColor: '#676b70', + borderColor: '#878a90', + }, + }, + dark: darkFields({ borderColor: '#858991', placeholderColor: '#adb1b8' }), + }, modern: rayThemeOverrides, material: { light: { @@ -134,6 +155,7 @@ export const themeStyleOverrides: Record = { textColor1: '#201a29', textColor2: '#433a50', textColor3: '#61566c', + placeholderColor: '#61566c', borderColor: '#8c8199', dividerColor: '#e1d8ea', boxShadow1: '0 2px 6px rgb(46 31 65 / 14%)', @@ -142,7 +164,7 @@ export const themeStyleOverrides: Record = { }, dark: { ...materialComponents, - common: { + ...darkFields({ primaryColor: '#d6bbff', primaryColorHover: '#e4d1ff', primaryColorPressed: '#bf9ff1', @@ -157,10 +179,11 @@ export const themeStyleOverrides: Record = { textColor1: '#f1e7fa', textColor2: '#ded0e8', textColor3: '#b9a9c4', + placeholderColor: '#b9a9c4', borderColor: '#867791', dividerColor: '#473c52', boxShadow1: '0 2px 8px rgb(0 0 0 / 16%)', - }, + }), Layout: { siderColor: '#241e2c', headerColor: '#241e2c' }, }, }, @@ -175,6 +198,8 @@ export const themeStyleOverrides: Record = { borderRadius: '2px', bodyColor: '#f5f5f5', actionColor: '#eeeeee', + placeholderColor: '#686868', + borderColor: '#858585', boxShadow1: 'none', boxShadow2: 'none', boxShadow3: 'none', @@ -182,7 +207,7 @@ export const themeStyleOverrides: Record = { }, dark: { ...plainComponents, - common: { + ...darkFields({ primaryColor: '#d5d5d5', primaryColorHover: '#ededed', primaryColorPressed: '#bdbdbd', @@ -193,10 +218,12 @@ export const themeStyleOverrides: Record = { popoverColor: '#252525', modalColor: '#252525', actionColor: '#2b2b2b', + placeholderColor: '#b1b1b1', + borderColor: '#888888', boxShadow1: 'none', boxShadow2: 'none', boxShadow3: 'none', - }, + }), Layout: { siderColor: '#202020', headerColor: '#202020' }, }, }, diff --git a/scripts/eslint-rules/no-undefined.mjs b/scripts/eslint-rules/no-undefined.mjs new file mode 100644 index 00000000..e0ee84c7 --- /dev/null +++ b/scripts/eslint-rules/no-undefined.mjs @@ -0,0 +1,139 @@ +const statementLists = new Set([ + 'Program', + 'BlockStatement', + 'StaticBlock', + 'SwitchCase', + 'TSModuleBlock', +]) + +function needsParentheses(node) { + const { parent } = node + + switch (parent.type) { + case 'CallExpression': + case 'NewExpression': + return parent.callee === node + case 'MemberExpression': + return parent.object === node + case 'TaggedTemplateExpression': + return parent.tag === node + case 'BinaryExpression': + return parent.operator === '**' && parent.left === node + case 'ClassDeclaration': + case 'ClassExpression': + return parent.superClass === node + case 'Decorator': + case 'TSInstantiationExpression': + case 'TSNonNullExpression': + return true + default: + return false + } +} + +function replacementText(sourceCode, node) { + if (node.parent.type === 'Property' && node.parent.shorthand) + return `${sourceCode.getText(node)}: void 0` + + if (!needsParentheses(node)) return 'void 0' + + const before = sourceCode.getTokenBefore(node) + + if (before?.value === '(' && sourceCode.getTokenAfter(node)?.value === ')') + return 'void 0' + + // 补上的左括号可能被解析为上一条表达式的函数调用。 + const startsStatement = sourceCode + .getAncestors(node) + .some( + (ancestor) => + ancestor.type === 'ExpressionStatement' && + ancestor.range[0] === node.range[0] && + statementLists.has(ancestor.parent.type), + ) + + return startsStatement && before && ![';', '{', ':'].includes(before.value) + ? ';(void 0)' + : '(void 0)' +} + +export default { + meta: { + type: 'suggestion', + fixable: 'code', + schema: [], + messages: { + useVoidZero: 'Use void 0 for the runtime undefined value.', + unexpectedUndefined: 'Unexpected use of undefined as an identifier.', + }, + }, + create(context) { + const { sourceCode } = context + const evalScopes = new Set() + const canFix = (reference) => { + const { identifier } = reference + const { parent } = identifier + + if ( + identifier.type !== 'Identifier' || + !reference.isReadOnly() || + parent.type === 'ExportSpecifier' || + (parent.type === 'UnaryExpression' && parent.operator === 'delete') + ) + return false + + for (let scope = reference.from; scope; scope = scope.upper) { + if (scope.type === 'with' || evalScopes.has(scope)) return false + } + + return true + } + + return { + 'CallExpression[callee.type="Identifier"][callee.name="eval"]'(node) { + // 保守处理直接 eval 可能在运行时引入的局部绑定。 + if (!node.optional) + evalScopes.add(sourceCode.getScope(node).variableScope) + }, + 'Program:exit'(program) { + const globalScope = sourceCode.getScope(program) + + for (const scope of sourceCode.scopeManager.scopes) { + const variable = scope.set.get('undefined') + + if (!variable) continue + + for (const { name } of variable.defs) + context.report({ node: name, messageId: 'unexpectedUndefined' }) + + for (const reference of variable.references) { + const node = reference.identifier + + if ( + reference.init || + reference.isValueReference === false || + node.parent.type === 'TSTypeQuery' || + node.parent.type === 'TSQualifiedName' + ) + continue + + if ( + scope === globalScope && + !variable.defs.length && + canFix(reference) + ) { + context.report({ + node, + messageId: 'useVoidZero', + fix: (fixer) => + fixer.replaceText(node, replacementText(sourceCode, node)), + }) + } else { + context.report({ node, messageId: 'unexpectedUndefined' }) + } + } + } + }, + } + }, +} diff --git a/scripts/fullstack.mjs b/scripts/fullstack.mjs index e75e5191..eba4ec7e 100644 --- a/scripts/fullstack.mjs +++ b/scripts/fullstack.mjs @@ -1,16 +1,16 @@ import { spawn } from 'node:child_process' import { randomBytes } from 'node:crypto' import { - appendFileSync, - chmodSync, existsSync, readFileSync, + renameSync, + rmSync, writeFileSync, } from 'node:fs' import { createServer } from 'node:net' import { setTimeout as delay } from 'node:timers/promises' import { fileURLToPath } from 'node:url' -import { parseEnv } from 'node:util' +import { isDeepStrictEqual, parseEnv } from 'node:util' const root = fileURLToPath(new URL('../', import.meta.url)) const envFile = new URL('../apps/server/.env.local', import.meta.url) @@ -60,6 +60,63 @@ function configuration() { return { ...parseEnv(readFileSync(envFile, 'utf8')), ...process.env } } +function envEntry(key, value) { + for (const quote of ['"', "'", '']) { + const line = `${key}=${quote}${value}${quote}` + const parsed = parseEnv(line) + + if (Object.keys(parsed).length === 1 && parsed[key] === value) return line + } + + throw new Error( + `${key} cannot be saved in .env.local. Use a dotenv-compatible value.`, + ) +} + +function updateSettings(source, saved, changes) { + const missing = new Set(Object.keys(changes)) + const lines = source.split('\n').map((line) => { + const key = /^\s*(?:export\s+)?(\w+)\s*=/u.exec(line)?.[1] + + if (!Object.hasOwn(changes, key)) return line + + missing.delete(key) + + return envEntry(key, changes[key]) + }) + + for (const key of missing) lines.push(envEntry(key, changes[key])) + + const content = lines.join('\n').replace(/\n?$/u, '\n') + + if (!isDeepStrictEqual({ ...parseEnv(content) }, { ...saved, ...changes })) + throw new Error( + 'Update the connection settings in apps/server/.env.local explicitly.', + ) + + const temporary = new URL( + `.env.setup-${randomBytes(8).toString('hex')}.local`, + envFile, + ) + + writeFileSync(temporary, content, { flag: 'wx', mode: 0o600 }) + + try { + if (readFileSync(envFile, 'utf8') !== source) + throw new Error( + 'Configuration changed during setup. Retry using the saved settings.', + ) + + renameSync(temporary, envFile) + } finally { + rmSync(temporary, { force: true }) + } +} + +function checkRedis(env) { + return run(process.execPath, ['apps/server/scripts/check-redis.mjs'], env) +} + function compose(env) { const project = env.RAY_COMPOSE_PROJECT ?? 'ray-template' @@ -267,10 +324,42 @@ try { if (action === 'setup' || action === 'up') { const external = flags.includes('--external') - if (!existsSync(envFile)) { - if (external && (!process.env.DATABASE_URL || !process.env.REDIS_URL)) - throw new Error('External setup requires DATABASE_URL and REDIS_URL.') + const source = existsSync(envFile) ? readFileSync(envFile, 'utf8') : null + const saved = parseEnv(source ?? '') + const changes = {} + const connectionKeys = ['DATABASE_URL', 'REDIS_URL'] + + if (action === 'setup' && !external) { + for (const key of connectionKeys) + if (process.env[key] !== void 0 && process.env[key] !== saved[key]) + throw new Error( + `${key} differs from the saved Compose settings. Use fullstack:setup --external with both connection URLs for external services.`, + ) + } + + if (external) { + const switching = saved.RAY_FULLSTACK_SERVICES === 'compose' + + for (const key of connectionKeys) { + const requested = process.env[key] + const target = switching ? requested : (requested ?? saved[key]) + + if (!target) + throw new Error( + 'External setup requires both DATABASE_URL and REDIS_URL.', + ) + + if (saved[key] !== target) changes[key] = target + } + + if (saved.RAY_FULLSTACK_SERVICES !== 'external') + changes.RAY_FULLSTACK_SERVICES = 'external' + + await checkRedis({ ...saved, ...process.env, ...changes }) + } + + if (source === null) { const password = randomBytes(24).toString('base64url') const redisPassword = randomBytes(24).toString('base64url') const postgresPort = portFrom(process.env, 'POSTGRES_PORT', '5432') @@ -289,6 +378,9 @@ try { POSTGRES_PORT: postgresPort, REDIS_PASSWORD: redisPassword, REDIS_PORT: redisPort, + ...(process.env.REDIS_KEY_PREFIX && { + REDIS_KEY_PREFIX: process.env.REDIS_KEY_PREFIX, + }), APP_PORT: portFrom(process.env, 'APP_PORT', '8080'), APP_PROXY_NETWORK: process.env.APP_PROXY_NETWORK || '172.30.67', DATABASE_URL: external @@ -304,14 +396,15 @@ try { CORS_ORIGINS: devOrigins(adminPort).join(','), TRUST_PROXY: 'false', DEMO_ENABLED: 'true', - JWT_SECRET: randomBytes(32).toString('base64url'), + JWT_SECRET: + process.env.JWT_SECRET ?? randomBytes(32).toString('base64url'), } // 配置只创建一次,避免重复初始化覆盖用户配置和已修改的凭据。 writeFileSync( envFile, Object.entries(values) - .map(([key, value]) => `${key}=${JSON.stringify(value)}`) + .map(([key, value]) => envEntry(key, value)) .join('\n') + '\n', { flag: 'wx', mode: 0o600 }, ) @@ -319,21 +412,15 @@ try { 'Created apps/server/.env.local. Initial administrator credentials are stored there; keep this file private.', ) } else { - const saved = parseEnv(readFileSync(envFile, 'utf8')) - const additions = [] - - // 升级时只补缺少的字段,保留已有连接和管理员配置。 if (!('JWT_SECRET' in saved)) - additions.push(`JWT_SECRET=${randomBytes(32).toString('base64url')}`) + changes.JWT_SECRET = + process.env.JWT_SECRET ?? randomBytes(32).toString('base64url') - if (external && !('RAY_FULLSTACK_SERVICES' in saved)) - additions.push('RAY_FULLSTACK_SERVICES=external') - - if (additions.length) { - if (process.platform !== 'win32') chmodSync(envFile, 0o600) - - appendFileSync(envFile, `\n${additions.join('\n')}\n`) - console.log('Updated apps/server/.env.local for this version.') + if (Object.keys(changes).length) { + updateSettings(source, saved, changes) + console.log( + `Updated apps/server/.env.local (${Object.keys(changes).join(', ')}).`, + ) } } @@ -366,15 +453,14 @@ try { `Fullstack services ready at http://127.0.0.1:${port}/ray-template/.`, ) } else { - if (external && (!env.DATABASE_URL || !env.REDIS_URL)) - throw new Error('External setup requires DATABASE_URL and REDIS_URL.') - - if (!external) + if (!external) { await run( 'docker', [...compose(env), 'up', '-d', '--wait', 'postgres', 'redis'], env, ) + await checkRedis(env) + } await run(pnpm, ['server:db:migrate'], env) await run(pnpm, ['server:db:seed'], env) diff --git a/scripts/lint-fix.mjs b/scripts/lint-fix.mjs new file mode 100644 index 00000000..bb785500 --- /dev/null +++ b/scripts/lint-fix.mjs @@ -0,0 +1,38 @@ +import { statSync } from 'node:fs' + +const files = process.argv.slice(process.argv[2] === '--' ? 3 : 2) + +if (files.length === 0) { + console.error('Usage: pnpm lint:fix [ ...]') + process.exit(1) +} + +const invalidFile = files.find( + (file) => !statSync(file, { throwIfNoEntry: false })?.isFile(), +) + +if (invalidFile !== void 0) { + console.error(`Expected an existing file path: ${invalidFile}`) + process.exit(1) +} + +const { ESLint } = await import('eslint') +const eslint = new ESLint({ fix: true, globInputPaths: false }) +const lintableFiles = [] + +for (const file of files) { + if (!(await eslint.isPathIgnored(file))) lintableFiles.push(file) +} + +if (lintableFiles.length > 0) { + const results = await eslint.lintFiles(lintableFiles) + const formatter = await eslint.loadFormatter() + + await ESLint.outputFixes(results) + process.stdout.write(await formatter.format(results)) + + if ( + results.some(({ errorCount, warningCount }) => errorCount || warningCount) + ) + process.exitCode = 1 +}