Compare commits

...

13 Commits
v6.0.2 ... main

Author SHA1 Message Date
XiaoDaiGua-Ray
c3458eef4c
fix(layout): simplify dividers and clarify designer labels 2026-12-02 10:58:42 +08:00
XiaoDaiGua-Ray
33319de653
fix(layout): use Naive UI for the placement selector 2026-12-02 10:20:15 +08:00
XiaoDaiGua-Ray
22dfe441e0
feat(layout): add a composable workspace designer
Add layout registration, visual editing, and source generation.

Preserve embedded pages and wait for asynchronous layout renderers.

Add workspace lint and formatting commands.
2026-12-01 17:34:27 +08:00
XiaoDaiGua-Ray
911c403434
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.
2026-12-01 11:04:13 +08:00
XiaoDaiGua-Ray
d3a2504d37
refactor: migrate deprecated APIs and prefer component hooks 2026-11-27 16:56:57 +08:00
XiaoDaiGua-Ray
d67e64d48c
feat(ui): refine frontend interactions and add CURD examples
Protect route drafts and refine keyboard, responsive, and primary button behavior.

Add CURD workspace examples with tests and bilingual documentation.
2026-11-27 14:51:46 +08:00
XiaoDaiGua-Ray
474d75203c
feat(ui): polish global search and expand icon library 2026-11-27 10:37:14 +08:00
XiaoDaiGua-Ray
b5ccd180ef
docs: add English VitePress documentation 2026-11-19 16:05:56 +08:00
XiaoDaiGua-Ray
9a6851b858
docs: expand v6 monorepo architecture guide 2026-11-19 15:17:29 +08:00
XiaoDaiGua-Ray
edf4794078
feat(menu-tag): add pin icon and drag preview 2026-11-19 14:39:19 +08:00
XiaoDaiGua-Ray
2a4a6182b0
feat: refine tab sorting and breadcrumb icons
Use interact.js for tab dragging, drop detection, and automatic scrolling.

Use the window icon as the breadcrumb fallback.
2026-11-19 14:10:42 +08:00
XiaoDaiGua-Ray
c2019b10e6
feat: enhance menu tags, breadcrumbs, and useMenu
Add configurable tab controls, breadcrumb icons, and interactive useMenu examples.
Batch pointer updates per frame and scope writes to the tab cache.
2026-11-19 12:25:05 +08:00
XiaoDaiGua-Ray
94c2e6cdb6
feat: refine menu tags and CSS tooling
Use native tag styling and close controls, add pill settings, and move the sidebar toggle.

Fix TablePro resize feedback, migrate viewport conversion, and add Zed workspace settings.
2026-11-19 11:33:18 +08:00
503 changed files with 19071 additions and 2208 deletions

View File

@ -2,6 +2,7 @@
"editor.formatOnSave": true, "editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode", "editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.enable": true, "eslint.enable": true,
"eslint.probe": [],
"eslint.validate": [ "eslint.validate": [
"javascript", "javascript",
"javascriptreact", "javascriptreact",

103
.zed/settings.json Normal file
View File

@ -0,0 +1,103 @@
{
"languages": {
"TypeScript": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"TSX": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"JavaScript": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"JSX": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["vtsls", "eslint", "!intl-lens", "..."]
},
"Vue.js": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["!intl-lens", "..."]
},
"JSON": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["!eslint", "..."]
},
"JSONC": {
"language_servers": ["!eslint", "..."]
},
"SCSS": {
"formatter": "prettier",
"format_on_save": "on"
},
"CSS": {
"formatter": "prettier",
"format_on_save": "on"
},
"HTML": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["!intl-lens", "..."]
},
"Markdown": {
"formatter": "prettier",
"format_on_save": "on",
"language_servers": ["!eslint", "..."]
}
},
"lsp": {
"cspell": {
"initialization_options": {
"defaultSettings": {
"words": [
"baomitu",
"bezier",
"Cascader",
"Clickoutside",
"codabar",
"commitmsg",
"crossorigin",
"daterange",
"datetimerange",
"depcheckrc",
"domtoimage",
"echart",
"EDITMSG",
"ianvs",
"iife",
"internalkey",
"jsbarcode",
"linebreak",
"logicflow",
"macarons",
"menutag",
"ndata",
"persistedstate",
"pharmacode",
"Popselect",
"precommit",
"qrcode",
"rgba",
"sider",
"siderbar",
"snapline",
"stylelint",
"unocss",
"VITE",
"vitepress",
"vueuse",
"WUJIE",
"zlevel"
]
}
}
}
}
}

View File

@ -5,6 +5,9 @@ A Vue 3 + TSX admin template with an admin application, a documentation site, an
- To locate an implementation, choose a topic from the [task index](llms.txt) or `pnpm harness context <scope>`. Consult the [architecture map](docs/architecture.md) for changes that cross module boundaries. - To locate an implementation, choose a topic from the [task index](llms.txt) or `pnpm harness context <scope>`. Consult the [architecture map](docs/architecture.md) for changes that cross module boundaries.
- Check `git status` first and preserve existing changes. Trace callers and existing data contracts before changing routing, persistence, requests, or shared components. - Check `git status` first and preserve existing changes. Trace callers and existing data contracts before changing routing, persistence, requests, or shared components.
- 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 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 <file> [...]` 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. - 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. - 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. - 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.

View File

@ -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 ## 6.0.2
### Feats ### Feats

View File

@ -4,7 +4,7 @@
Give developers and coding agents the same path through the project: **find the implementation, understand its contracts, reuse existing capabilities, and verify the change.** Give developers and coding agents the same path through the project: **find the implementation, understand its contracts, reuse existing capabilities, and verify the change.**
[简体中文](README.zh-CN.md) · **[Live demo](https://xiaodaigua-ray.github.io/ray-template/)** · **[Documentation](https://xiaodaigua-ray.github.io/ray-template/docs/)** · [Quick start](#quick-start) · [Develop with AI](#develop-with-ai) [简体中文](README.zh-CN.md) · **[Live demo](https://xiaodaigua-ray.github.io/ray-template/)** · **[Documentation](https://xiaodaigua-ray.github.io/ray-template/docs/en/)** · [Quick start](#quick-start) · [Develop with AI](#develop-with-ai)
Ray Template uses Vue 3, TypeScript / TSX, and Naive UI for admin dashboards, operations consoles, and internal tools. The repository brings together a working application, shared components, interactive documentation, and engineering context organized by task. Ray Template uses Vue 3, TypeScript / TSX, and Naive UI for admin dashboards, operations consoles, and internal tools. The repository brings together a working application, shared components, interactive documentation, and engineering context organized by task.
@ -20,19 +20,19 @@ Ray Template uses Vue 3, TypeScript / TSX, and Naive UI for admin dashboards, op
### Applications, documentation, and examples share source ### Applications, documentation, and examples share source
The admin application and documentation consume the same workspace packages. Interactive examples use real components, and the TablePro documentation includes the source of the examples it runs. Changes to public capabilities can be checked in both the application and documentation. [Explore the examples](apps/docs/reference/table-pro-examples.md) · [Documentation workflow](docs/docs-handoff.md) The admin application and documentation consume the same workspace packages. Interactive examples use real components, and the TablePro documentation includes the source of the examples it runs. Changes to public capabilities can be checked in both the application and documentation. [Explore the examples](apps/docs/en/reference/table-pro-examples.md) · [Documentation workflow](docs/docs-handoff.md)
### Four styles across the business interface ### Four styles across the business interface
Modern, Naive UI, Material, and Plain cover the shell, controls, tables, and charts, each with light and dark modes. Custom pages inherit colors, corners, and shadows through semantic theme tokens, while runtime layout variables adapt them to the workspace. [Theme integration](apps/docs/guide/appearance.md) · [CSS contract](docs/ui-design.md#custom-css-contract) Modern, Naive UI, Material, and Plain cover the shell, controls, tables, and charts, each with light and dark modes. Custom pages inherit colors, corners, and shadows through semantic theme tokens, while runtime layout variables adapt them to the workspace. [Theme integration](apps/docs/en/guide/appearance.md) · [CSS contract](docs/ui-design.md#custom-css-contract)
### TablePro handles interaction and data state ### TablePro handles interaction and data state
One table component supports local data, remote requests, and controlled pagination, with advanced search, column settings, export, printing, and instance hooks. Request races, cancellation signals, failure recovery, and export scope have explicit contracts and regression coverage. [11 runnable examples](https://xiaodaigua-ray.github.io/ray-template/docs/reference/table-pro-examples.html) · [Component contract](packages/ui/src/RTablePro/README.md) One table component supports local data, remote requests, and controlled pagination, with advanced search, column settings, export, printing, and instance hooks. Request races, cancellation signals, failure recovery, and export scope have explicit contracts and regression coverage. [11 runnable examples](https://xiaodaigua-ray.github.io/ray-template/docs/en/reference/table-pro-examples.html) · [Component contract](packages/ui/src/RTablePro/README.md)
### One contract from the static demo to your business API ### One contract from the static demo to your business API
Development and the static hosted demo share MSW HTTP mocks, with pages fetching data through the application's API layer. Shared TypeScript types, Valibot schemas, and generated OpenAPI 3.1 definitions guide backend integration; a dedicated command checks that generated contracts stay in sync. [API contracts](packages/api-contracts/README.md) · [Backend integration](apps/docs/guide/backend.md) Development and the static hosted demo share MSW HTTP mocks, with pages fetching data through the application's API layer. Shared TypeScript types, Valibot schemas, and generated OpenAPI 3.1 definitions guide backend integration; a dedicated command checks that generated contracts stay in sync. [API contracts](packages/api-contracts/README.md) · [Backend integration](apps/docs/en/guide/backend.md)
### Visual route editing with a validated configuration contract ### Visual route editing with a validated configuration contract
@ -42,7 +42,7 @@ Manage menu order, roles, visibility, and caching through a visual editor or JSO
### Choose frontend or fullstack source from one project ### Choose frontend or fullstack source from one project
Export an independently runnable frontend, or include the NestJS, PostgreSQL, and Redis implementation. Distribution scripts use the dependency graph to prune workspaces, the lockfile, and edition-specific documentation, then record the version, source commit, and content digest. [Source distributions and startup](apps/docs/guide/distributions.md) Export an independently runnable frontend, or include the NestJS, PostgreSQL, and Redis implementation. Distribution scripts use the dependency graph to prune workspaces, the lockfile, and edition-specific documentation, then record the version, source commit, and content digest. [Source distributions and startup](apps/docs/en/guide/distributions.md)
<!-- fullstack:end --> <!-- fullstack:end -->
@ -63,19 +63,19 @@ pnpm dev
Open [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/) and click **Continue with demo account**. Switch to manager or read-only accounts to explore permission differences. The frontend demo needs no database or business backend. Open [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/) and click **Continue with demo account**. Switch to manager or read-only accounts to explore permission differences. The frontend demo needs no database or business backend.
- **Try the interface.** Open Settings to change styles and layouts, then explore Users and TablePro. - **Try the interface.** Open Settings to change styles and layouts, then explore Users and TablePro.
- **Build your first page.** Follow the [business page guide](apps/docs/guide/first-page.md), reuse components, and register the route with English and Chinese menu labels. - **Build your first page.** Follow the [business page guide](apps/docs/en/guide/first-page.md), reuse components, and register the route with English and Chinese menu labels.
- **Connect your service.** Follow the [backend integration guide](apps/docs/guide/backend.md) to configure `VITE_API_BASE_URL` and `VITE_API_MOCK=false`. - **Connect your service.** Follow the [backend integration guide](apps/docs/en/guide/backend.md) to configure `VITE_API_BASE_URL` and `VITE_API_MOCK=false`.
## Develop with AI ## Develop with AI
AI support is part of the everyday development workflow. Coding agents that can read the repository and run commands can use the same Markdown documents, source entry points, and verification commands as maintainers. AI support is part of the everyday development workflow. Coding agents that can read the repository and run commands can use the same Markdown documents, source entry points, and verification commands as maintainers.
| Development question | Evidence in the repository | | Development question | Evidence in the repository |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Where should I start, and which conventions apply? | [AGENTS.md](AGENTS.md): scope, reuse, documentation updates, and acceptance rules. | | Where should I start, and which conventions apply? | [AGENTS.md](AGENTS.md): scope, reuse, documentation updates, and acceptance rules. |
| Which files matter for this task? | [llms.txt](llms.txt) → [task context](harness/context): implementations, callers, contracts, and tests. | | Which files matter for this task? | [llms.txt](llms.txt) → [task context](harness/context): implementations, callers, contracts, and tests. |
| Which module owns the behavior, and where are its boundaries? | The [architecture map](docs/architecture.md), public `exports`, and [package boundary checks](scripts/check-package-boundaries.mjs). | | Which module owns the behavior, and where are its boundaries? | The [architecture map](docs/architecture.md), public `exports`, and [package boundary checks](scripts/check-package-boundaries.mjs). |
| How do existing capabilities work, and what do their parameters and states mean? | [Component references](apps/docs/reference/components.md), [hook references](apps/docs/reference/hooks.md), module READMEs, and [runnable examples](apps/docs/reference/table-pro-examples.md). | | How do existing capabilities work, and what do their parameters and states mean? | [Component references](apps/docs/en/reference/components.md), [hook references](apps/docs/en/reference/hooks.md), module READMEs, and [runnable examples](apps/docs/en/reference/table-pro-examples.md). |
| How do mocks and business requests agree on API shapes? | [Shared schemas and OpenAPI](packages/api-contracts/README.md), with `pnpm api:check` checking generated contract synchronization. | | How do mocks and business requests agree on API shapes? | [Shared schemas and OpenAPI](packages/api-contracts/README.md), with `pnpm api:check` checking generated contract synchronization. |
| What should I run after a change, and where are the results? | [Verification scopes](harness/scopes.json) and `pnpm harness verify <scope>`, with reports saved under `.harness-local/runs/`. | | What should I run after a change, and where are the results? | [Verification scopes](harness/scopes.json) and `pnpm harness verify <scope>`, with reports saved under `.harness-local/runs/`. |
@ -112,7 +112,7 @@ Here, `llms.txt` is a repository task index that you can explicitly ask an agent
| **Icons and utilities** | Typed SVG names and generated sprites, QR codes, barcodes, precision arithmetic, storage, composables, and directives. | | **Icons and utilities** | Typed SVG names and generated sprites, QR codes, barcodes, precision arithmetic, storage, composables, and directives. |
| **Engineering and integration** | pnpm workspaces, request cancellation, type and package boundary checks, Vitest, ESLint / Prettier, and a [Wujie sub-application entry point](apps/admin/src/main.ts). | | **Engineering and integration** | pnpm workspaces, request cancellation, type and package boundary checks, Vitest, ESLint / Prettier, and a [Wujie sub-application entry point](apps/admin/src/main.ts). |
Frontend permissions shape the page experience; your backend validates real sessions and API authorization. See the [backend integration guide](apps/docs/guide/backend.md) for demo data and integration boundaries. Frontend permissions shape the page experience; your backend validates real sessions and API authorization. See the [backend integration guide](apps/docs/en/guide/backend.md) for demo data and integration boundaries.
## Styles and layouts ## Styles and layouts
@ -123,7 +123,7 @@ Frontend permissions shape the page experience; your backend validates real sess
| **Material** | Tonal surfaces, larger corners, and capsule-shaped buttons. | | **Material** | Tonal surfaces, larger corners, and capsule-shaped buttons. |
| **Plain** | Neutral colors, small corners, and flat surfaces. | | **Plain** | Neutral colors, small corners, and flat surfaces. |
**Side · Top · Mixed · Right · Split.** Choose fluid or fixed-width content, adjust spacing, and pin the header or footer. Narrow screens use a menu drawer. Switch layouts in the [live demo](https://xiaodaigua-ray.github.io/ray-template/) or explore the [layout playground](apps/docs/guide/layout.md). **Side · Top · Mixed · Right · Split.** Choose fluid or fixed-width content, adjust spacing, and pin the header or footer. Narrow screens use a menu drawer. Switch layouts in the [live demo](https://xiaodaigua-ray.github.io/ray-template/) or explore the [layout playground](apps/docs/en/guide/layout.md).
<details> <details>
<summary>View the workspace and dark theme previews</summary> <summary>View the workspace and dark theme previews</summary>
@ -162,11 +162,11 @@ pnpm fullstack:setup
pnpm dev:full pnpm dev:full
``` ```
`setup` creates the private `apps/server/.env.local`, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. The generated administrator password is stored in that file; mock demo passwords do not authenticate against the server. For existing databases and Redis, use `pnpm fullstack:setup --external` and follow the [startup guide](apps/docs/guide/distributions.md) for configuration. `setup` creates the private `apps/server/.env.local`, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. The generated administrator password is stored in that file; mock demo passwords do not authenticate against the server. For existing databases and Redis, use `pnpm fullstack:setup --external` and follow the [startup guide](apps/docs/en/guide/distributions.md) for configuration.
Alternatively, run `node scripts/fullstack.mjs up` to build and start the entire stack with Docker, without first installing project dependencies on the host. The default entry point is `http://127.0.0.1:8080/ray-template/`. `pnpm fullstack:stop` stops services and retains data volumes. Alternatively, run `node scripts/fullstack.mjs up` to build and start the entire stack with Docker, without first installing project dependencies on the host. The default entry point is `http://127.0.0.1:8080/ray-template/`. `pnpm fullstack:stop` stops services and retains data volumes.
The [source distributions workflow](.github/workflows/distributions.yaml) provides manual options to verify archives, generate the `frontend` branch, and attach assets to an existing Release. [Container startup and release instructions](apps/docs/guide/distributions.md#容器启动) The [source distributions workflow](.github/workflows/distributions.yaml) provides manual options to verify archives, generate the `frontend` branch, and attach assets to an existing Release. [Container startup and release instructions](https://xiaodaigua-ray.github.io/ray-template/docs/en/guide/distributions.html#容器启动)
<!-- fullstack:end --> <!-- fullstack:end -->
@ -196,7 +196,7 @@ The **Pages workflow** builds the admin and documentation on every push to `main
**v6 introduces the monorepo architecture and does not provide an in-place upgrade from v5.** Compatibility with v5 internal imports, APIs, deployment settings, and browser data is not guaranteed. **v6 introduces the monorepo architecture and does not provide an in-place upgrade from v5.** Compatibility with v5 internal imports, APIs, deployment settings, and browser data is not guaranteed.
Existing projects can stay on [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) or the [v5.2.5 tag](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.5). Read the [migration notes](apps/docs/migration.md) before adopting v6. Existing projects can stay on [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) or the [v5.2.5 tag](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.5). Read the [migration notes](apps/docs/en/migration.md) before adopting v6.
--- ---

View File

@ -0,0 +1,45 @@
import { useMemoryCache } from '@/utils/cache-backend'
import {
createProjectDraft,
useProjects,
useTags,
} from '@/views/demo/curd/records'
import { beforeEach, describe, expect, it } from 'vitest'
describe('CURD demo records', () => {
beforeEach(useMemoryCache)
it('loads saved project milestones on a new page and removes them with the project', () => {
const projects = useProjects()
const draft = {
...createProjectDraft(),
name: 'Release review',
owner: 'Demo owner',
milestones: [
{ id: 'review', name: 'Check the release', outcome: 'Sign off' },
],
}
expect(projects.create(draft)).toBeUndefined()
const saved = useProjects()
const id = saved.rows.value.find(({ name }) => name === draft.name)!.id
expect(saved.find(id)).toMatchObject(draft)
expect(saved.update(id, { ...draft, name: 'Atlas portal' })).toBe(
'duplicate',
)
expect(useProjects().find(id)).toMatchObject(draft)
expect(saved.remove(id)).toBeUndefined()
expect(useProjects().find(id)).toBeUndefined()
expect(useProjects().update(id, draft)).toBe('missingRecord')
})
it('keeps an explicitly emptied tag list on reopen', () => {
const tags = useTags()
for (const { id } of tags.rows.value)
expect(tags.remove(id)).toBeUndefined()
expect(useTags().rows.value).toEqual([])
})
})

View File

@ -0,0 +1,60 @@
import { useRouteDraftGuard } from '@/views/route-management/use-draft-guard'
import { flushPromises, mount } from '@vue/test-utils'
import type { DialogOptions } from 'naive-ui'
import { defineComponent, h } from 'vue'
import { createMemoryHistory, createRouter, RouterView } from 'vue-router'
vi.mock('@/hooks', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
vi.mock('@/store', () => ({
useSigningGetters: () => ({ getSigningCallback: { value: { id: 'admin' } } }),
}))
it('keeps a dirty editor across a cancelled URL change and leaves after confirmation', async () => {
const warning = vi.fn((_options: DialogOptions) => ({ destroy: vi.fn() }))
vi.stubGlobal('$dialog', { warning })
const editor = defineComponent({
setup() {
useRouteDraftGuard(
() => true,
() => false,
)
return () => h('div', 'Draft editor')
},
})
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/editor', component: editor },
{ path: '/other', component: { render: () => h('div', 'Other view') } },
],
})
await router.push('/editor')
const wrapper = mount(RouterView, { global: { plugins: [router] } })
try {
const update = router.push('/editor?source=other')
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/editor')
warning.mock.lastCall?.[0].onAfterLeave?.()
await update
expect(router.currentRoute.value.fullPath).toBe('/editor')
const leave = router.push('/other')
await flushPromises()
const options = warning.mock.lastCall?.[0]
options?.onPositiveClick?.(new MouseEvent('click'))
options?.onAfterLeave?.()
await leave
expect(wrapper.text()).toBe('Other view')
expect(warning).toHaveBeenCalledTimes(2)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
}
})

View File

@ -44,6 +44,11 @@ it('submits the real login form with native credential fields and no demo shortc
expect(wrapper.text()).not.toMatch(/UseDemo|UseMember|UseManager/u) expect(wrapper.text()).not.toMatch(/UseDemo|UseMember|UseManager/u)
await username.setValue('qa-account') await username.setValue('qa-account')
await password.setValue('qa-fixture-password') await password.setValue('qa-fixture-password')
await wrapper.get('button[aria-label="ShowPassword"]').trigger('click')
expect(password.attributes('type')).toBe('text')
expect(signing).not.toHaveBeenCalled()
await wrapper.get('button[aria-label="HidePassword"]').trigger('click')
expect(password.attributes('type')).toBe('password')
await wrapper.get('form').trigger('submit') await wrapper.get('form').trigger('submit')
await flushPromises() await flushPromises()
expect(signing).toHaveBeenCalledExactlyOnceWith({ expect(signing).toHaveBeenCalledExactlyOnceWith({

View File

@ -1,12 +1,76 @@
import * as adminApi from '@/api/admin' import * as adminApi from '@/api/admin'
import { AdminApiError } from '@/api/admin/client' import { AdminApiError } from '@/api/admin/client'
import { userOptionsSchema } from '@/api/admin/contracts'
import { router } from '@/router' import { router } from '@/router'
import { piniaSigningStore } from '@/store/modules/signing' import { piniaSigningStore } from '@/store/modules/signing'
import UserManagement from '@/views/user-management' import UserManagement from '@/views/user-management'
import { useUserErrorMessage } from '@/views/user-management/error-message' import { useUserErrorMessage } from '@/views/user-management/error-message'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import { NTree } from 'naive-ui'
import { safeParse } from 'valibot'
import setupMiniApp from '../utils/setupMiniApp' 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 () => { it('keeps the current list and selection context when opening and closing an editor', async () => {
localStorage.clear() localStorage.clear()
const { app } = await setupMiniApp() const { app } = await setupMiniApp()

View File

@ -28,15 +28,25 @@ vi.mock('@/hooks', () => ({
it('honors avatar shape, native size, and keyboard focus', () => { it('honors avatar shape, native size, and keyboard focus', () => {
const wrapper = mount(AppAvatar, { const wrapper = mount(AppAvatar, {
props: { round: false, size: 42, objectFit: 'contain' }, props: {
round: false,
size: 42,
objectFit: 'contain',
color: 'rgb(18, 52, 86)',
},
}) })
try { try {
expect(wrapper.findComponent(NAvatar).props()).toMatchObject({ const avatar = wrapper.findComponent(NAvatar)
expect(avatar.props()).toMatchObject({
round: false, round: false,
size: 42, size: 42,
objectFit: 'contain', objectFit: 'contain',
}) })
expect((avatar.element as HTMLElement).style.backgroundColor).toBe(
'rgb(18, 52, 86)',
)
expect(wrapper.findComponent(NButton).props('focusable')).toBe(true) expect(wrapper.findComponent(NButton).props('focusable')).toBe(true)
} finally { } finally {
wrapper.unmount() wrapper.unmount()

View File

@ -6,6 +6,7 @@ import {
themeStyleOverrides, themeStyleOverrides,
themeStyles, themeStyles,
} from '../../packages/ui/src/theme-presets' } from '../../packages/ui/src/theme-presets'
import { contrast } from '../utils/color-contrast'
const registeredThemes = getCustomEchartTheme() const registeredThemes = getCustomEchartTheme()
const themes = new Map(registeredThemes.map(({ name, theme }) => [name, theme])) 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', () => { it('registers every style in both modes with unique deterministic names', () => {
expect(registeredThemes).toHaveLength(themes.size) expect(registeredThemes).toHaveLength(themes.size)
expect([...themes.keys()]).toEqual( expect([...themes.keys()]).toEqual(

View File

@ -1,7 +1,7 @@
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import { init } from 'echarts/core' import { init } from 'echarts/core'
import type { ECharts } 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 { RChart, useChart } from '../../packages/ui/src/RChart'
import { USE_CHART_PROVIDER_KEY } from '../../packages/ui/src/RChart/src/config' import { USE_CHART_PROVIDER_KEY } from '../../packages/ui/src/RChart/src/config'
import { provideUiServices } from '../../packages/ui/src/services' 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) vi.stubGlobal('IntersectionObserver', Observer)
const dark = ref(false) 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({ const wrapper = mount({
setup() { setup() {
provideUiServices({ dark: () => dark.value }) provideUiServices({ dark: () => dark.value })
return () => <RChart theme="default" /> return () => <RChart theme="default" options={options} />
}, },
}) })
try { try {
await flushPromises() await flushPromises()
dark.value = true dark.value = true
value.value = 2
await nextTick() await nextTick()
expect(init).not.toHaveBeenCalled() expect(init).not.toHaveBeenCalled()
expect(readValue).not.toHaveBeenCalled()
visible() visible()
await flushPromises() await flushPromises()
expect(charts[0].getOption()).toMatchObject({
series: [{ data: [{ value: 2 }] }],
})
expect(disconnect).toHaveBeenCalled() expect(disconnect).toHaveBeenCalled()
expect(init).toHaveBeenLastCalledWith( expect(init).toHaveBeenLastCalledWith(
expect.anything(), expect.anything(),

View File

@ -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,
)
}
}
},
)

View File

@ -6,7 +6,7 @@ import type {
TableProSearchOptions, TableProSearchOptions,
} from '@ray-template/ui/table-pro' } from '@ray-template/ui/table-pro'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDatePicker, NSelect } from 'naive-ui' import { NDataTable, NDatePicker, NGrid, NSelect } from 'naive-ui'
import { defineComponent, h, nextTick, shallowRef } from 'vue' import { defineComponent, h, nextTick, shallowRef } from 'vue'
const columns = [{ key: 'name', title: 'Name' }] const columns = [{ key: 'name', title: 'Name' }]
@ -15,6 +15,93 @@ const statusOptions = [
{ label: 'Closed', value: 'closed' }, { label: 'Closed', value: 'closed' },
] ]
it('applies the latest measured search column count on the next frame', async () => {
let resizeSearch: ((width: number) => void) | undefined
vi.useFakeTimers({
toFake: ['requestAnimationFrame', 'cancelAnimationFrame'],
})
vi.stubGlobal(
'ResizeObserver',
class {
readonly callback: ResizeObserverCallback
constructor(callback: ResizeObserverCallback) {
this.callback = callback
}
observe(target: Element) {
if (target.matches('.r-table-search-shell'))
resizeSearch = (width) =>
this.callback(
[
{
target,
contentRect: new DOMRect(0, 0, width, 200),
} as ResizeObserverEntry,
],
this,
)
}
disconnect() {}
unobserve() {}
},
)
const wrapper = mount(RTablePro, {
props: { columns, search: { fields: [{ key: 'name', label: 'Name' }] } },
})
try {
await nextTick()
const grid = wrapper.getComponent(NGrid)
expect(resizeSearch).toBeTypeOf('function')
expect(grid.props('cols')).toBe(1)
expect(grid.find('button[type="submit"]').exists()).toBe(false)
resizeSearch?.(864)
await nextTick()
expect(grid.props('cols')).toBe(1)
resizeSearch?.(1310)
await nextTick()
expect(grid.props('cols')).toBe(1)
vi.advanceTimersToNextFrame()
await nextTick()
expect(grid.props('cols')).toBe(3)
expect(grid.find('button[type="submit"]').exists()).toBe(true)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
vi.useRealTimers()
}
})
it('follows a measured collapse default until the user chooses a state', async () => {
const fields = [
{ key: 'name', label: 'Name' },
{ key: 'team', label: 'Team' },
]
const wrapper = mount(RTablePro, { props: { columns, search: { fields } } })
try {
const grid = wrapper.getComponent(NGrid)
expect(grid.props('collapsed')).toBe(false)
await wrapper.setProps({ search: { fields, defaultCollapsed: true } })
expect(grid.props('collapsed')).toBe(true)
await wrapper.get('button[aria-expanded="false"]').trigger('click')
await wrapper.setProps({ search: { fields, defaultCollapsed: false } })
await wrapper.setProps({ search: { fields, defaultCollapsed: true } })
expect(grid.props('collapsed')).toBe(false)
} finally {
wrapper.unmount()
}
})
it('labels compound picker triggers and both endpoints of a date range', async () => { it('labels compound picker triggers and both endpoints of a date range', async () => {
const fields: TableProSearchOptions['fields'] = [ const fields: TableProSearchOptions['fields'] = [
{ key: 'created', type: 'dateRange', label: 'Created' }, { key: 'created', type: 'dateRange', label: 'Created' },

View File

@ -4,6 +4,7 @@ import type { DropdownOption } from 'naive-ui'
import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro' import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro'
import type { TableProRequest } 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 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' import * as printing from '../../packages/ui/src/RTablePro/src/printing'
const columns = [{ key: 'name', title: 'Name' }] 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 () => { it('opts into menu printing and retains CSV formatting and output options', async () => {
const download = vi const download = vi
.spyOn(csv, 'downloadTableCsv') .spyOn(csv, 'downloadTableCsv')

View File

@ -7,7 +7,7 @@ import type {
import { provideUiServices } from '@ray-template/ui/services' import { provideUiServices } from '@ray-template/ui/services'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDropdown, NPagination } from 'naive-ui' 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' import * as csv from '../../packages/ui/src/RTablePro/src/csv'
const columns = [{ title: 'Name', key: 'name' }] 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 () => { it('ignores stale data even if the loader ignores cancellation', async () => {
const first = Promise.withResolvers<TableProResult>() const first = Promise.withResolvers<TableProResult>()
const second = Promise.withResolvers<TableProResult>() const second = Promise.withResolvers<TableProResult>()
@ -271,7 +299,7 @@ it('clears even same-query rows on failure and when the request source changes',
} }
}) })
it('shows a toast and the normal empty state without an inline alert, then allows retry', async () => { it('shows a persistent request error with retry while preserving the ordinary empty slot', async () => {
const request = vi const request = vi
.fn(async (_params: TableProParams) => response('Recovered', 1)) .fn(async (_params: TableProParams) => response('Recovered', 1))
.mockRejectedValueOnce(new Error('offline')) .mockRejectedValueOnce(new Error('offline'))
@ -299,14 +327,16 @@ it('shows a toast and the normal empty state without an inline alert, then allow
try { try {
await flushPromises() await flushPromises()
expect(table.emitted('request-error')).toHaveLength(1) expect(table.emitted('request-error')).toHaveLength(1)
expect(reportError).toHaveBeenCalledExactlyOnceWith( expect(reportError).not.toHaveBeenCalled()
"Couldn't load the data",
)
expect(table.getComponent(NDataTable).props('pagination')).toBe(false) expect(table.getComponent(NDataTable).props('pagination')).toBe(false)
expect(table.text()).toContain('Custom empty state') expect(table.text()).not.toContain('Custom empty state')
expect(table.text()).toContain('Always visible notice') expect(table.text()).toContain('Always visible notice')
expect(table.find('.n-alert').exists()).toBe(false) expect(table.get('[role="alert"]').text()).toBe("Couldn't load the data")
await instance.reload() await table
.findAll('button')
.find((item) => item.text() === 'Retry')!
.trigger('click')
await flushPromises()
expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}]) expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}])
expect(table.text()).toContain('Recovered') expect(table.text()).toContain('Recovered')
@ -317,6 +347,42 @@ it('shows a toast and the normal empty state without an inline alert, then allow
pageSize: null, pageSize: null,
total: 1, total: 1,
}) })
request.mockResolvedValueOnce({ data: [], total: 0 })
await instance.reload()
expect(table.text()).toContain('Custom empty state')
} finally {
wrapper.unmount()
}
})
it('offers a filter reset when a successful query returns no matches', async () => {
const request = vi.fn(async ({ name }: TableProParams) =>
name ? { data: [], total: 0 } : response('Member', 1),
)
const wrapper = mount(RTablePro, {
props: {
columns,
request,
pagination: false,
search: [{ key: 'name', label: 'Name' }],
},
})
const table = wrapper.vm as unknown as TableProInst
try {
await flushPromises()
table.setSearchValues({ name: 'missing' })
await table.submitSearch()
expect(wrapper.get('span[role="status"]').text()).toBe(
'No results match the filters',
)
await wrapper
.findAll('button')
.find((item) => item.text() === 'Reset filters')!
.trigger('click')
await flushPromises()
expect(request.mock.lastCall?.[0]).toEqual({})
expect(wrapper.text()).toContain('Member')
} finally { } finally {
wrapper.unmount() wrapper.unmount()
} }

View File

@ -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' } }) const wrapper = mount(RIcon, { props: { name: 'action/close_all' } })
try { 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({ expect(wrapper.get('svg').attributes()).toMatchObject({
fill: 'none', fill: 'none',
stroke: 'currentColor', stroke: 'currentColor',
'stroke-width': '1.8', '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 { } finally {
wrapper.unmount() 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 () => { 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 { try {
await nextTick() await nextTick()
const frame = wrapper.get('iframe') 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') await frame.trigger('load')
expect(wrapper.findComponent(NSpin).props('show')).toBe(false) expect(wrapper.findComponent(NSpin).props('show')).toBe(false)
await wrapper.setProps({ src: '/two.html' }) await wrapper.setProps({ src: '/two.html' })

View File

@ -1,51 +0,0 @@
import { useAppRoot } from '../../apps/admin/src/hooks/template/useAppRoot'
import setupMiniApp from '../utils/setupMiniApp'
describe('useAppRoot', async () => {
await setupMiniApp()
const { setRootRoute } = useAppRoot()
it(`should return '/test' and 'test'`, () => {
setRootRoute({
path: '/test',
name: 'test',
})
const { getRootPath, getRootName } = useAppRoot()
expect(getRootPath.value).toBe('/test')
expect(getRootName.value).toBe('test')
})
it(`should be returned a object like: {path: /test2, name: test2}`, () => {
const baseRootRoute = {
path: '/test2',
name: 'test2',
}
setRootRoute(baseRootRoute)
const { getRootRoute } = useAppRoot()
expect(getRootRoute.value).toEqual(baseRootRoute)
})
it('should update root route when setRootRoute is called', () => {
const baseRootRoute = {
path: '/test3',
name: 'test3',
}
setRootRoute({
path: '/test3',
name: 'test3',
})
const { getRootPath, getRootName, getRootRoute } = useAppRoot()
expect(getRootPath.value).toBe('/test3')
expect(getRootName.value).toBe('test3')
expect(getRootRoute.value).toEqual(baseRootRoute)
})
})

View File

@ -2,18 +2,7 @@ import { useDevice } from '../../apps/admin/src/hooks/web/useDevice'
describe('useDevice', () => { describe('useDevice', () => {
const addEventListenerSpy = vi.spyOn(window, 'addEventListener') const addEventListenerSpy = vi.spyOn(window, 'addEventListener')
const matchMediaSpy = vi const matchMediaSpy = vi.spyOn(window, 'matchMedia')
.spyOn(window, 'matchMedia')
.mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
beforeEach(() => { beforeEach(() => {
addEventListenerSpy.mockClear() addEventListenerSpy.mockClear()

View File

@ -6,7 +6,6 @@ const { state } = vi.hoisted(() => ({
state: { state: {
instance: void 0 as instance: void 0 as
| { | {
mode: string
global: { global: {
t: (key: string, ...args: unknown[]) => string t: (key: string, ...args: unknown[]) => string
locale: Ref<string> locale: Ref<string>
@ -24,7 +23,6 @@ vi.mock('../../apps/admin/src/locales', () => ({
beforeEach(() => { beforeEach(() => {
state.instance = { state.instance = {
mode: 'composition',
global: { t: (key) => key, locale: ref('zh-CN') }, global: { t: (key) => key, locale: ref('zh-CN') },
} }
}) })
@ -46,12 +44,12 @@ describe('useI18n namespaces', () => {
expect(hook.t('code')).toBe('hooks.code') expect(hook.t('code')).toBe('hooks.code')
expectTypeOf(hook.t('code')).toEqualTypeOf<string>() expectTypeOf(hook.t('code')).toEqualTypeOf<string>()
state.instance = { state.instance = {
mode: 'composition',
global: { t: (key) => `translated:${key}`, locale: ref('zh-CN') }, global: { t: (key) => `translated:${key}`, locale: ref('zh-CN') },
} }
expect(hook.t('code')).toBe('translated:hooks.code') expect(hook.t('code')).toBe('translated:hooks.code')
hook.locale('en-US') hook.locale('en-US')
expect(state.instance.global.locale.value).toBe('en-US') expect(state.instance.global.locale.value).toBe('en-US')
expect(document.documentElement.lang).toBe('en-US')
state.instance.global.t = (key) => `updated:${key}` state.instance.global.t = (key) => `updated:${key}`
expect(hook.t('code')).toBe('updated:hooks.code') expect(hook.t('code')).toBe('updated:hooks.code')
}) })

View File

@ -0,0 +1,102 @@
import { useMenu } from '@ray-template/composables/useMenu'
import type { UseMenuOptions } from '@ray-template/composables/useMenu'
import { mount } from '@vue/test-utils'
import { NMenu } from 'naive-ui'
import { defineComponent, nextTick } from 'vue'
const daily = { key: 2, label: 'Daily' }
const options = [
{ key: 'home', label: 'Home' },
{ key: 1, label: 'Reports', children: [daily] },
]
const mountMenu = (initial: UseMenuOptions) => {
const menu = useMenu(initial)
const wrapper = mount(
defineComponent({
setup: () => () => <NMenu ref={menu.menuRef} {...menu.menuProps} />,
}),
)
const select = (label: string) =>
wrapper
.findAll('.n-menu-item-content')
.find((row) => row.text() === label)!
.trigger('click')
return { ...menu, wrapper, select }
}
it('updates controlled selection and expansion before notifying native callbacks', async () => {
const onValue = vi.fn(() => menu.menuProps.value)
const onExpanded = vi.fn(() => menu.menuProps.expandedKeys)
const onExpandedAlias = vi.fn()
const menu = mountMenu({
options,
value: 'home',
expandedKeys: [],
'onUpdate:value': onValue,
onUpdateExpandedKeys: [onExpanded, onExpandedAlias],
})
try {
menu.showOption(2)
await nextTick()
expect(onExpanded).toHaveBeenCalledExactlyOnceWith([1])
expect(onExpanded).toHaveReturnedWith([1])
expect(onExpandedAlias).toHaveBeenCalledExactlyOnceWith([1])
expect(menu.menuProps.value).toBe('home')
await menu.select('Daily')
expect(onValue).toHaveBeenCalledExactlyOnceWith(2, daily)
expect(onValue).toHaveReturnedWith(2)
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
'Daily',
)
} finally {
menu.wrapper.unmount()
}
})
it('keeps native defaults for independently uncontrolled props', async () => {
const menu = mountMenu({
options: [],
defaultValue: 'home',
defaultExpandAll: true,
watchProps: ['defaultExpandedKeys'],
})
try {
menu.menuProps.options = options
await nextTick()
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
'Home',
)
expect(menu.wrapper.get('[aria-expanded="true"]').text()).toContain('Daily')
await menu.select('Daily')
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
'Daily',
)
expect(menu.menuProps.value).toBeUndefined()
expect(menu.menuProps.expandedKeys).toBeUndefined()
} finally {
menu.wrapper.unmount()
}
})
it('delegates instance methods only while the menu is mounted', () => {
const menu = useMenu()
const instance = { showOption: vi.fn(), deriveResponsiveState: vi.fn() }
menu.showOption()
menu.deriveResponsiveState()
menu.menuRef.value = instance
menu.showOption()
menu.deriveResponsiveState()
menu.menuRef.value = null
menu.showOption('home')
menu.deriveResponsiveState()
expect(instance.showOption).toHaveBeenCalledExactlyOnceWith(void 0)
expect(instance.deriveResponsiveState).toHaveBeenCalledExactlyOnceWith()
})

View File

@ -1,10 +1,10 @@
import { APP_CATCH_KEY } from '@/app-config' import { APP_CATCH_KEY } from '@/app-config'
import { useAppRoot } from '@/hooks/template/useAppRoot'
import { useSiderBar } from '@/hooks/template/useSiderBar' import { useSiderBar } from '@/hooks/template/useSiderBar'
import { setupI18n } from '@/locales' import { setupI18n } from '@/locales'
import { permissionRouter } from '@/router/utils/permission' import { permissionRouter } from '@/router/utils/permission'
import { piniaKeepAliveStore } from '@/store/modules/keep-alive' import { piniaKeepAliveStore } from '@/store/modules/keep-alive'
import { piniaMenuStore } from '@/store/modules/menu' import { piniaMenuStore } from '@/store/modules/menu'
import { getCatchMenuTagOptions } from '@/store/modules/menu/utils'
import { piniaSettingStore } from '@/store/modules/setting' import { piniaSettingStore } from '@/store/modules/setting'
import { piniaSigningStore } from '@/store/modules/signing' import { piniaSigningStore } from '@/store/modules/signing'
import { setStorage } from '@/utils/cache' import { setStorage } from '@/utils/cache'
@ -119,7 +119,10 @@ it('starts with no active business page and never injects a missing cached dashb
}) })
it('closes the final business tab, even when it is the legacy root preference', async () => { it('closes the final business tab, even when it is the legacy root preference', async () => {
useAppRoot().setRootRoute({ path: '/reports', name: 'Reports' }) piniaSettingStore().updateSettingState('appRootRoute', {
path: '/reports',
name: 'Reports',
})
await router.push('/reports?sort=asc#summary') await router.push('/reports?sort=asc#summary')
await flushPromises() await flushPromises()
expect(actions.getCurrentTagIndex()).toBe(0) expect(actions.getCurrentTagIndex()).toBe(0)
@ -176,13 +179,99 @@ it('closes left, right and other tabs without protecting any business path', asy
it('closes all tags independently of missing or unauthorized root preferences', async () => { it('closes all tags independently of missing or unauthorized root preferences', async () => {
await router.push('/reports') await router.push('/reports')
await router.push('/orders') await router.push('/orders')
useAppRoot().setRootRoute({ path: '/deleted-home' }) piniaSettingStore().updateSettingState('appRootRoute', {
path: '/deleted-home',
})
await actions.closeAll() await actions.closeAll()
await flushPromises() await flushPromises()
expect(menu.menuTagOptions).toEqual([]) expect(menu.menuTagOptions).toEqual([])
expect(router.currentRoute.value.path).toBe('/welcome') expect(router.currentRoute.value.path).toBe('/welcome')
}) })
it('keeps topped tabs together and restores tab order and flags with the latest URL', async () => {
for (const path of ['/reports', '/orders', '/private'])
await router.push(path)
const cachedPages = piniaKeepAliveStore().keepAliveInclude
menu.toggleMenuTagTop('/private')
menu.toggleMenuTagFixed('/orders')
expect(menu.moveMenuTag('/orders', '/private', 'before')).toBe(false)
expect(menu.moveMenuTag('/orders', '/reports', 'before')).toBe(true)
expect(piniaKeepAliveStore().keepAliveInclude).toBe(cachedPages)
await router.push('/orders?sort=desc#details')
await flushPromises()
menu.menuTagOptions = getCatchMenuTagOptions()
await menu.setupAppMenu()
expect(
menu.menuTagOptions.map(({ fullPath, topped, fixed }) => [
fullPath,
topped,
fixed,
]),
).toEqual([
['/private', true, false],
['/orders?sort=desc#details', false, true],
['/reports', false, false],
])
expect(
menu.options.find((option) => option.fullPath === '/private'),
).not.toHaveProperty('topped')
expect(menu.currentMenuOption?.fullPath).toBe('/orders?sort=desc#details')
const settings = piniaSettingStore()
settings.updateSettingState('menuTagDrag', false)
expect(
menu.moveMenuTag('/reports', '/orders?sort=desc#details', 'before'),
).toBe(false)
settings.updateSettingState('menuTagDrag', true)
settings.updateSettingState('menuTagTop', false)
expect(menu.moveMenuTag('/reports', '/private', 'before')).toBe(true)
settings.updateSettingState('menuTagTop', true)
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/private',
'/reports',
'/orders?sort=desc#details',
])
})
it('preserves fixed tabs through single and bulk closes until protection is disabled', async () => {
for (const path of ['/reports', '/orders', '/private'])
await router.push(path)
menu.toggleMenuTagFixed('/orders')
await actions.close('/orders')
await actions.closeLeft('/private')
expect(actions.checkCloseLeft('/private')).toBe(false)
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
'/private',
])
await actions.closeRight('/orders')
expect(actions.checkCloseRight('/orders')).toBe(false)
expect(router.currentRoute.value.path).toBe('/orders')
await router.push('/reports')
await router.push('/private')
await actions.closeOther('/private')
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
'/private',
])
await actions.closeAll()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
])
expect(router.currentRoute.value.path).toBe('/orders')
piniaSettingStore().updateSettingState('menuTagFixed', false)
await actions.close('/orders')
expect(menu.menuTagOptions).toEqual([])
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('keeps status routes out of tabs and clears active business navigation', async () => { it('keeps status routes out of tabs and clears active business navigation', async () => {
await router.push('/reports') await router.push('/reports')
@ -254,6 +343,7 @@ it('closes a directly opened 403 to the workspace with no business tags', async
it('removes revoked tags and cached views without choosing another active page', async () => { it('removes revoked tags and cached views without choosing another active page', async () => {
await router.push('/reports') await router.push('/reports')
await router.push('/private?mode=edit#section') await router.push('/private?mode=edit#section')
menu.toggleMenuTagFixed('/private?mode=edit#section')
piniaSigningStore().signingCallback.role = 'member' piniaSigningStore().signingCallback.role = 'member'
await flushPromises() await flushPromises()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([ expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
@ -294,3 +384,69 @@ it('updates neutral and status document titles when the language changes', async
await flushPromises() await flushPromises()
expect(document.title).toContain('工作区已就绪') 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<boolean>()
const entered = Promise.withResolvers<void>()
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',
])
})

View File

@ -0,0 +1,194 @@
import Layout from '@/layout'
import { LayoutFrame, LayoutOutlet } from '@/layout/blocks'
import { useLayout } from '@/layout/useLayout'
import { flushPromises, mount } from '@vue/test-utils'
import type { VueWrapper } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { defineAsyncComponent, Fragment, h, nextTick } from 'vue'
import type { Component } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
const loaded = {
render: () => h(LayoutFrame, { class: 'loaded-layout' }),
}
let pinia: ReturnType<typeof createPinia>
let wrapper: VueWrapper
beforeEach(async () => {
pinia = createPinia()
setActivePinia(pinia)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/', component: loaded }],
})
wrapper = mount(Layout, {
attachTo: document.body,
slots: {
default: () => [
h('input', { 'aria-label': 'Draft' }),
h('button', { type: 'button' }, 'Save draft'),
],
},
global: {
plugins: [router, pinia],
stubs: {
AppMenu: true,
LayoutHeader: true,
LayoutFooter: true,
LayoutTabs: true,
TopNavigation: true,
ContentLoading: true,
SettingDrawer: true,
},
},
})
await nextTick()
})
afterEach(() => {
wrapper.unmount()
disposePinia(pinia)
vi.restoreAllMocks()
})
function selectPendingLayout(suspensible = true) {
const gate = Promise.withResolvers<Component>()
const layout = useLayout()
layout.registerLayout({
id: 'deferred',
label: 'Deferred',
component: defineAsyncComponent({
loader: () => gate.promise,
suspensible,
delay: 0,
loadingComponent: { render: () => h('p', { class: 'loading-layout' }) },
}),
})
layout.updateLayout('deferred')
return { layout, gate }
}
it.each([
['shared', loaded],
['freeform', { render: () => h('section', [h(loaded)]) }],
] as const)(
'keeps the old page usable and its latest state in a %s layout',
async (_, component) => {
const previous = wrapper.get('.r-layout-full').element
const field = wrapper.get('input').element
const viewport = () =>
field.closest('.r-layout-content-scroll')!.parentElement!
const save = wrapper.get<HTMLButtonElement>('main button').element
field.focus()
viewport().scrollTop = 150
const { layout, gate } = selectPendingLayout()
await flushPromises()
expect(layout.selectedLayoutId.value).toBe('deferred')
expect(wrapper.get('.r-layout-full').element).toBe(previous)
const draft = wrapper.get('input')
expect(draft.element).toBe(field)
expect(draft.isVisible()).toBe(true)
expect(draft.element.closest('[inert]')).toBeNull()
await draft.setValue('edited while loading')
viewport().scrollTop = 320
save.focus()
gate.resolve(component)
await flushPromises()
expect(wrapper.get('.loaded-layout input').element).toBe(field)
expect(field.value).toBe('edited while loading')
expect(viewport().scrollTop).toBe(320)
expect(document.activeElement).toBe(save)
expect(layout.selectedLayoutId.value).toBe('deferred')
},
)
it('accepts a layout that controls its own async loading state', async () => {
const { layout, gate } = selectPendingLayout(false)
await flushPromises()
expect(wrapper.find('.loading-layout').exists()).toBe(true)
expect(layout.selectedLayoutId.value).toBe('deferred')
gate.resolve(loaded)
await flushPromises()
expect(wrapper.find('.loaded-layout input').exists()).toBe(true)
})
it('restores the last usable layout after a loader rejects', async () => {
const report = vi.spyOn(console, 'error').mockImplementation(() => {})
const error = new Error('Layout module failed to load')
useLayout().updateLayout('right')
await flushPromises()
const { layout, gate } = selectPendingLayout()
await flushPromises()
gate.reject(error)
await flushPromises()
expect(report).toHaveBeenCalledWith(
expect.stringContaining('"deferred"'),
error,
)
expect(layout.selectedLayoutId.value).toBe('right')
expect(wrapper.find('main input').exists()).toBe(true)
})
it.each(['success', 'failure'])(
'ignores a stale loader after switching again (%s)',
async (outcome) => {
const report = vi.spyOn(console, 'error').mockImplementation(() => {})
const { layout, gate } = selectPendingLayout()
await flushPromises()
layout.updateLayout('top')
await nextTick()
if (outcome === 'success') gate.resolve(loaded)
else gate.reject(new Error('Stale layout failed'))
await flushPromises()
expect(layout.selectedLayoutId.value).toBe('top')
expect(wrapper.find('.loaded-layout').exists()).toBe(false)
expect(wrapper.find('main input').exists()).toBe(true)
expect(report).not.toHaveBeenCalled()
},
)
it.each([
['no outlet', () => h('section')],
[
'two embedded outlets',
() => h('section', [h(LayoutOutlet), h(LayoutOutlet)]),
],
['two root frames', () => h(Fragment, [h(LayoutFrame), h(LayoutFrame)])],
] as const)('rejects a resolved layout with %s', async (_, render) => {
const report = vi.spyOn(console, 'error').mockImplementation(() => {})
const { layout, gate } = selectPendingLayout()
await flushPromises()
const field = wrapper.get('input').element
const viewport = () =>
field.closest('.r-layout-content-scroll')!.parentElement!
field.focus()
viewport().scrollTop = 280
gate.resolve({ render })
await flushPromises()
expect(report).toHaveBeenCalledWith(
expect.stringContaining('"deferred"'),
expect.stringContaining('exactly one'),
)
expect(layout.selectedLayoutId.value).toBe('side')
expect(wrapper.get('input').isVisible()).toBe(true)
expect(wrapper.get('input').element).toBe(field)
expect(document.activeElement).toBe(field)
expect(viewport().scrollTop).toBe(280)
})

View File

@ -0,0 +1,110 @@
import Breadcrumb from '@/layout/components/SiderBar/components/Breadcrumb'
import type { AppMenuOption } from '@/types'
import { mount } from '@vue/test-utils'
import { h, nextTick, ref } from 'vue'
import type { Ref } from 'vue'
const state = vi.hoisted(() => ({
select: vi.fn(),
compact: null as unknown as Ref<boolean>,
icons: null as unknown as Ref<boolean>,
fallback: null as unknown as Ref<boolean>,
options: null as unknown as Ref<AppMenuOption[]>,
}))
vi.mock('@/hooks', () => ({
useDevice: () => ({ isTabletOrSmaller: state.compact }),
}))
vi.mock('@/store', () => ({
useMenuActions: () => ({ changeMenuModelValue: state.select }),
useMenuGetters: () => ({ getBreadcrumbOptions: state.options }),
useSettingGetters: () => ({
getBreadcrumbIcon: state.icons,
getBreadcrumbIconFallback: state.fallback,
}),
}))
const option = (path: string, label: string): AppMenuOption => ({
name: label,
path,
key: path,
fullPath: path,
label,
breadcrumbLabel: label,
meta: {},
})
it('displays menu images and defaults to a fallback for the missing icon', async () => {
state.compact = ref(false)
state.icons = ref(true)
state.fallback = ref(true)
state.options = ref([
{
...option('/reports', 'Reports'),
icon: () => h('img', { src: '/report.png', alt: '' }),
},
option('/reports/monthly', 'Monthly'),
])
const wrapper = mount(Breadcrumb)
try {
const iconSelector = '.layout-breadcrumb__icon'
expect(wrapper.get(`${iconSelector} img`).attributes('src')).toBe(
'/report.png',
)
expect(wrapper.findAll(iconSelector)).toHaveLength(2)
state.fallback.value = false
await nextTick()
expect(wrapper.findAll(iconSelector)).toHaveLength(1)
state.compact.value = true
state.fallback.value = true
await nextTick()
expect(wrapper.get('[aria-current="page"]').text()).toBe('Monthly')
expect(wrapper.findAll(iconSelector)).toHaveLength(1)
state.icons.value = false
await nextTick()
expect(wrapper.findAll(iconSelector)).toHaveLength(0)
} finally {
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<HTMLButtonElement>(
'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()
}
})

View File

@ -0,0 +1,183 @@
import Layout from '@/layout'
import { LayoutFrame } from '@/layout/blocks'
import { useLayout } from '@/layout/useLayout'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { defineAsyncComponent, h, nextTick, ref } from 'vue'
import type { Component } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
const freeform = { render: () => h('section', [h(LayoutFrame)]) }
const originalMove = Object.getOwnPropertyDescriptor(
Element.prototype,
'moveBefore',
)
beforeAll(() => {
Object.defineProperty(Element.prototype, 'moveBefore', {
configurable: true,
value: void 0,
})
})
afterAll(() => {
if (originalMove)
Object.defineProperty(Element.prototype, 'moveBefore', originalMove)
else Reflect.deleteProperty(Element.prototype, 'moveBefore')
})
const stubs = {
AppMenu: true,
LayoutHeader: true,
LayoutFooter: true,
LayoutTabs: true,
LayoutHeaderActions: true,
TopNavigation: true,
ContentLoading: true,
SettingDrawer: true,
}
async function workspace(initial = 'side') {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
layout.registerLayout({
id: 'wrapped',
label: 'Wrapped frame',
component: freeform,
})
layout.updateLayout(initial)
const embedded = ref(true)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/', component: freeform }],
})
const wrapper = mount(Layout, {
attachTo: document.body,
slots: {
default: () =>
embedded.value
? h('iframe', { srcdoc: '<input>' })
: h('p', 'Next page'),
},
global: { plugins: [router, pinia], stubs },
})
await flushPromises()
return {
wrapper,
layout,
embedded,
dispose: () => {
wrapper.unmount()
disposePinia(pinia)
},
}
}
it.each([
['side', 'wrapped'],
['wrapped', 'top'],
])(
'keeps the current embed connected when moving from %s to %s requires recreating its document',
async (from, to) => {
const { wrapper, layout, embedded, dispose } = await workspace(from)
try {
const frame = wrapper.get('iframe').element
const original = frame.contentDocument
expect(original).toBeTruthy()
layout.updateLayout(to)
await flushPromises()
expect(layout.selectedLayoutId.value).toBe(to)
expect(wrapper.attributes('data-layout')).toBe(from)
expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(true)
expect(wrapper.get('iframe').element.contentDocument).toBe(original)
layout.updateLayout(from)
await flushPromises()
expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(false)
expect(frame.contentDocument).toBe(original)
layout.updateLayout(to)
await flushPromises()
embedded.value = false
await vi.waitFor(() => expect(wrapper.attributes('data-layout')).toBe(to))
expect(wrapper.get('main p').text()).toBe('Next page')
expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(false)
} finally {
dispose()
}
},
)
it('uses the declared shared frame on a generated layout’s first visit with an iframe', async () => {
const { wrapper, layout, dispose } = await workspace()
try {
const original = wrapper.get('iframe').element.contentDocument
layout.registerLayout({
id: 'generated',
label: 'Generated',
sharedFrame: true,
component: { render: () => h(LayoutFrame, { class: 'generated-frame' }) },
})
layout.updateLayout('generated')
await flushPromises()
expect(wrapper.get('.generated-frame iframe').element).toBe(
wrapper.get('iframe').element,
)
expect(wrapper.get('iframe').element.contentDocument).toBe(original)
expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(false)
} finally {
dispose()
}
})
it.each([
['side', true],
['side', false],
['wrapped', true],
['wrapped', false],
] as const)(
'protects an iframe opened from %s while a freeform async renderer loads (suspensible %s)',
async (from, suspensible) => {
const { wrapper, embedded, layout, dispose } = await workspace(from)
try {
embedded.value = false
await nextTick()
const loader = Promise.withResolvers<Component>()
layout.registerLayout({
id: 'loading-shell',
label: 'Loading',
component: defineAsyncComponent({
loader: () => loader.promise,
suspensible,
delay: 0,
}),
})
layout.updateLayout('loading-shell')
await flushPromises()
embedded.value = true
await nextTick()
const original = wrapper.get('iframe').element.contentDocument
loader.resolve(freeform)
await flushPromises()
expect(wrapper.attributes('data-layout')).toBe(from)
expect(wrapper.get('iframe').isVisible()).toBe(true)
expect(wrapper.get('iframe').element.contentDocument).toBe(original)
embedded.value = false
await vi.waitFor(() =>
expect(wrapper.attributes('data-layout')).toBe('loading-shell'),
)
} finally {
dispose()
}
},
)

View File

@ -86,7 +86,16 @@ it('does not navigate while composing and supports keyboard result focus and Ent
} }
const menu = piniaMenuStore() const menu = piniaMenuStore()
menu.options = [option('/visible', 'Visible page')] menu.options = [
{
...option('/tables', 'Table examples'),
meta: { extra: { label: 'TablePro' } },
children: [
option('/visible', 'Visible page'),
option('/hidden', 'Hidden page', false),
],
},
]
const navigate = vi const navigate = vi
.spyOn(menu, 'changeMenuModelValue') .spyOn(menu, 'changeMenuModelValue')
.mockImplementation(() => void 0) .mockImplementation(() => void 0)
@ -107,8 +116,21 @@ it('does not navigate while composing and supports keyboard result focus and Ent
await flushPromises() await flushPromises()
const input = wrapper.find('input').element as HTMLInputElement const input = wrapper.find('input').element as HTMLInputElement
input.value = 'Visible' expect(document.activeElement).toBe(input)
input.dispatchEvent(new Event('input', { bubbles: true })) 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',
)
await wrapper.get('input').setValue('Table examples')
await flushPromises() await flushPromises()
expect(wrapper.findAll('.global-search__destination')).toHaveLength(1) expect(wrapper.findAll('.global-search__destination')).toHaveLength(1)
input.dispatchEvent( input.dispatchEvent(

View File

@ -0,0 +1,199 @@
import { generateLayoutSource, layoutWriteEndpoint } from '@/layout/designer'
import { flushPromises, mount } from '@vue/test-utils'
vi.mock('@/hooks/template/useI18n', () => ({
useI18n: () => ({
t: (key: string, params?: { row?: number }) =>
typeof params?.row === 'number' ? `${key} ${params.row}` : key,
}),
}))
vi.mock('@/layout/useLayout', () => ({
useLayout: () => ({ layouts: { value: [{ id: 'side' }] } }),
}))
async function mountDesigner(writer: boolean) {
vi.stubGlobal('__LAYOUT_PROJECT_WRITER__', writer)
vi.resetModules()
const { default: Designer } =
await import('@/views/demo/layout-lab/LayoutDesigner')
return mount(Designer, { global: { stubs: { teleport: true } } })
}
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
vi.unstubAllGlobals()
})
it('posts the edited visual design on the local development server and blocks duplicate IDs', async () => {
const post = vi.fn().mockResolvedValue(new Response(null, { status: 201 }))
vi.stubGlobal('fetch', post)
const wrapper = await mountDesigner(true)
try {
const button = wrapper.get('.layout-designer__project button')
expect(button.text()).toBe('generate')
const id = wrapper.get('input[aria-label="id"]')
await id.setValue('side')
expect(button.attributes('disabled')).toBeDefined()
await id.setValue('lab-demo')
const palette = (name: string) => wrapper.get(`[data-palette="${name}"]`)
const tile = (name: string) => wrapper.get(`[data-tile="${name}"]`)
const action = (label: string) => {
const control = wrapper
.findAll('.layout-designer__inspector button')
.find((item) => item.text() === label)
expect.assert(control)
return control
}
const selectRow = async (label: string) => {
const select = wrapper.getComponent({ name: 'Select' })
await select.get('.n-base-selection').trigger('click')
const option = select
.findAll('.n-base-select-option')
.find((item) => item.text() === label)
expect.assert(option)
await option.trigger('click')
}
expect(wrapper.find('[data-tile]').exists()).toBe(false)
expect(wrapper.find('.layout-designer__outlet').exists()).toBe(true)
await palette('actions').trigger('click')
await palette('tabs').trigger('click')
await action('rowUp').trigger('click')
expect(
wrapper
.findAll('[data-region="rows"] [data-tile]')
.map((item) => item.text()),
).toEqual(['tabs', 'actions'])
await tile('actions').trigger('click')
await selectRow('topRow 1')
await action('left').trigger('click')
await selectRow('topRow 1')
await action('rowDown').trigger('click')
expect(
wrapper
.findAll('[data-region="bottomRows"] [data-tile]')
.map((item) => item.text()),
).toEqual(['actions', 'tabs'])
await action('rowUp').trigger('click')
await palette('navigation').trigger('click')
await wrapper
.get('[data-region="bottomRows"] .layout-designer__new-row')
.trigger('click')
await palette('sidebar').trigger('click')
await action('sidebarRight').trigger('click')
await palette('footer').trigger('click')
await action('remove').trigger('click')
expect(wrapper.find('[data-tile="footer"]').exists()).toBe(false)
await palette('footer').trigger('click')
expect(tile('sidebar').element.previousElementSibling).toBe(
wrapper.get('.layout-designer__viewer').element,
)
expect(tile('footer').element.parentElement).toBe(
wrapper.get('.layout-designer__viewer').element,
)
const transfer = { setData: vi.fn(), effectAllowed: '' }
const newRows = wrapper
.findAll('.layout-designer__new-row')
.map((item) => item.element)
const destination = tile('navigation').element
expect(newRows).toHaveLength(2)
await palette('breadcrumb').trigger('dragstart', { dataTransfer: transfer })
expect(
wrapper
.findAll('.layout-designer__new-row')
.every((item, index) => item.element === newRows[index]),
).toBe(true)
expect(tile('navigation').element).toBe(destination)
await tile('navigation').trigger('drop', {
dataTransfer: transfer,
clientX: -10,
})
expect(
wrapper
.findAll('[data-region="bottomRows"] [data-tile]')
.map((item) => item.text()),
).toEqual(['breadcrumb', 'navigation'])
await button.trigger('click')
await flushPromises()
expect(post).toHaveBeenCalledTimes(1)
const [endpoint, request] = post.mock.calls[0]
expect(endpoint).toBe(layoutWriteEndpoint)
expect(request.method).toBe('POST')
expect(request.headers['X-Ray-Layout-Write']).toBe('1')
expect(JSON.parse(request.body)).toMatchObject({
id: 'lab-demo',
rows: [['actions', 'tabs']],
bottomRows: [['breadcrumb', 'navigation']],
sidebar: 'right',
footer: true,
})
expect(
wrapper.get('.layout-designer__project [role="status"]').text(),
).toBe('written')
} finally {
wrapper.unmount()
}
})
it.each([
{ writer: false, embedded: false, development: true },
{ writer: true, embedded: false, development: false },
{ writer: true, embedded: true, development: true },
])(
'downloads without requesting a project write for writer=$writer, development=$development, embedded=$embedded',
async ({ writer, embedded, development }) => {
vi.stubEnv('DEV', development)
if (embedded) vi.stubGlobal('top', {})
const post = vi.fn()
vi.stubGlobal('fetch', post)
const blobUrl = vi
.spyOn(URL, 'createObjectURL')
.mockReturnValue('blob:layout-sample')
let filename = ''
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (
this: HTMLAnchorElement,
) {
filename = this.download
})
const wrapper = await mountDesigner(writer)
try {
const button = wrapper.get('.layout-designer__project button')
expect(button.text()).toBe('download')
await button.trigger('click')
expect(filename).toBe('my-workspace.layout.tsx')
const [blob] = blobUrl.mock.calls[0]
expect.assert(blob instanceof Blob)
expect(await blob.text()).toBe(
generateLayoutSource({
id: 'my-workspace',
label: 'defaultName',
selectable: true,
rows: [],
}),
)
expect(post).not.toHaveBeenCalled()
} finally {
wrapper.unmount()
}
},
)

View File

@ -0,0 +1,138 @@
// @vitest-environment node
import { generateLayoutSource } from '@/layout/designer'
import type { LayoutDesign } from '@/layout/designer'
import * as prettier from 'prettier'
import ts from 'typescript'
it('keeps generated definitions formatted and preserves display names as literal text', async () => {
const path = 'apps/admin/src/layout/definitions/demo.layout.tsx'
const config = await prettier.resolveConfig(path)
const labels = [
'My workspace',
'A'.repeat(80),
'中文布局'.repeat(20),
'Dana\'s "Design" \\ `label` ${name} 👩‍💻',
'Left\u2028right\u00a0edge\u0085end',
'Direction\u2066A\u2069, control\u007f and C1\u009bend',
['Backslashes', '\\'.repeat(3), '`', '${name}', '"', '\ud800'].join(''),
]
const arrangements: LayoutDesign['rows'][] = [
[['tabs']],
[['navigation']],
[['breadcrumb'], ['actions']],
[['actions', 'tabs'], ['navigation']],
[['breadcrumb'], ['actions'], ['tabs'], ['navigation']],
]
for (const [index, label] of labels.entries()) {
const design = {
id: 'a'.repeat(64),
label,
rows: arrangements[index % arrangements.length],
selectable: true,
}
const source = generateLayoutSource(design)
expect(await prettier.format(source, { ...config, filepath: path })).toBe(
source,
)
const file = ts.createSourceFile(
path,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
)
const readLabel = (node: ts.Node): ts.StringLiteralLike | undefined => {
if (
ts.isPropertyAssignment(node) &&
node.name.getText(file) === 'label' &&
ts.isStringLiteralLike(node.initializer)
) {
return node.initializer
}
return node.forEachChild(readLabel)
}
const literal = readLabel(file)
expect.assert(literal)
expect(literal.text).toBe(label)
const normalized =
source.slice(0, literal.getStart(file)) +
'`Baseline`' +
source.slice(literal.end)
expect(normalized).toBe(
generateLayoutSource({ ...design, label: 'Baseline' }),
)
expect(source).not.toMatch(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u)
}
})
it.each(['none', 'left', 'right'] as const)(
'renders only the requested sidebar and footer for %s placement',
async (sidebar) => {
const path = 'apps/admin/src/layout/definitions/demo.layout.tsx'
const config = await prettier.resolveConfig(path)
for (const footer of [false, true]) {
for (const rows of [[], [['tabs']]]) {
const design = {
id: 'layout-demo',
label: 'Layout',
selectable: true,
rows,
sidebar,
footer,
}
const source = generateLayoutSource(design)
expect(
await prettier.format(source, { ...config, filepath: path }),
).toBe(source)
expect(source.includes('header: () =>')).toBe(rows.length > 0)
expect(source.includes('footer: () => <LayoutFooter />')).toBe(footer)
if (sidebar === 'none') {
expect(source).not.toContain('LayoutNavigation')
expect(source).not.toContain('sidebarPlacement')
} else {
expect(source).toContain(`sidebarPlacement="${sidebar}"`)
expect(source).toContain(
sidebar === 'right'
? '<LayoutNavigation end />'
: '<LayoutNavigation />',
)
}
}
}
},
)
it('preserves top and bottom row order in the preview and renderer', async () => {
const path = 'apps/admin/src/layout/definitions/demo.layout.tsx'
const config = await prettier.resolveConfig(path)
const source = generateLayoutSource({
id: 'bottom-layout',
label: 'Bottom',
selectable: true,
rows: [['breadcrumb']],
bottomRows: [['navigation'], ['actions', 'tabs']],
sidebar: 'right',
footer: true,
})
expect(await prettier.format(source, { ...config, filepath: path })).toBe(
source,
)
expect(source).toContain("rows: [['breadcrumb']]")
expect(source).toContain("bottomRows: [['navigation'], ['actions', 'tabs']]")
expect(source).toContain("sidebar: 'right'")
expect(source).toContain('footer: true')
expect(source).toMatch(
/bottom: \(\) => \([\s\S]*<LayoutTopNavigation \/>[\s\S]*<LayoutHeaderActions \/>\s+<LayoutTabs \/>/,
)
})

View File

@ -0,0 +1,88 @@
import {
LayoutSettings,
type LayoutConfig,
type LayoutPreview,
} from '@ray-template/admin-shell'
import { mount } from '@vue/test-utils'
const layout: LayoutConfig = {
mode: 'side',
contentWidth: 'fluid',
contentMaxWidth: 1200,
contentPadding: 16,
fixedHeader: true,
fixedFooter: true,
}
const props = {
layout,
defaults: layout,
translate: (key: string) => key,
}
it('draws the registered rows, sidebar and bottom blocks in reading order', async () => {
const preview: LayoutPreview = {
rows: [['actions', 'breadcrumb']],
bottomRows: [['tabs', 'navigation']],
sidebar: 'right',
}
const onSelect = vi.fn()
const wrapper = mount(LayoutSettings, {
props: {
...props,
update: vi.fn(),
onSelect,
selectedId: 'workspace',
choices: [{ id: 'workspace', label: 'Workspace', preview }],
},
})
try {
const choice = wrapper.get('button[aria-label="Workspace"]')
const diagram = choice.get('.r-layout-preview__main')
const rows = diagram.findAll('.r-layout-preview__row')
expect(choice.attributes('aria-pressed')).toBe('true')
expect(diagram.element.nextElementSibling?.className).toBe(
'r-layout-preview__aside',
)
expect(rows[0].element.firstElementChild?.className).toBe(
'r-layout-preview__actions',
)
expect(rows[1].element.previousElementSibling?.className).toBe(
'r-layout-preview__body',
)
expect(rows[1].element.lastElementChild?.className).toBe(
'r-layout-preview__navigation',
)
expect(diagram.find('.r-layout-preview__footer').exists()).toBe(false)
await choice.trigger('click')
expect(onSelect).toHaveBeenCalledWith('workspace')
} finally {
wrapper.unmount()
}
})
it('retains the built-in mode selector when no registry choices are supplied', async () => {
const update = vi.fn()
const wrapper = mount(LayoutSettings, { props: { ...props, update } })
try {
const button = wrapper.get('button[aria-label="split"]')
expect(
button.findAll('.r-layout-preview > .r-layout-preview__row'),
).toHaveLength(2)
expect(
button
.get('.r-layout-preview__main')
.find('.r-layout-preview__tabs')
.exists(),
).toBe(true)
expect(button.find('.r-layout-preview__footer').exists()).toBe(true)
await button.trigger('click')
expect(update).toHaveBeenCalledWith({ mode: 'split' })
} finally {
wrapper.unmount()
}
})

View File

@ -0,0 +1,271 @@
import { APP_CATCH_KEY } from '@/app-config'
import { collectLayoutDefinitions, discoveredLayouts } from '@/layout/discovery'
import type { LayoutDefinition } from '@/layout/types'
import { useLayout } from '@/layout/useLayout'
import { piniaSettingStore } from '@/store/modules/setting'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { createApp, defineComponent, shallowReactive, watch } from 'vue'
const component = defineComponent({ render: () => null })
const definition = (id: string): LayoutDefinition => ({
id,
label: id,
component,
})
function mountWorkspace() {
const pinia = createPinia().use(piniaPluginPersistedstate)
createApp(component).use(pinia)
setActivePinia(pinia)
const layout = useLayout()
const settings = piniaSettingStore()
return { layout, settings, dispose: () => disposePinia(pinia) }
}
const key = APP_CATCH_KEY.appPiniaSettingStore
beforeEach(() => localStorage.removeItem(key))
afterEach(() => localStorage.removeItem(key))
it('discovers built-ins and custom-top and isolates explicitly registered layouts per application', () => {
const first = mountWorkspace()
const second = mountWorkspace()
try {
expect(first.layout.layouts.value.slice(0, 5).map(({ id }) => id)).toEqual([
'side',
'top',
'mixed',
'right',
'split',
])
expect(
first.layout.layouts.value.some(({ id }) => id === 'custom-top'),
).toBe(true)
first.layout.registerLayout({
...definition('private-workspace'),
autoRegister: false,
})
expect(first.layout.activeLayoutId.value).toBe('side')
expect(first.layout.updateLayout('private-workspace')).toBe(true)
expect(second.layout.updateLayout('private-workspace')).toBe(false)
expect(() => first.layout.registerLayout(definition('side'))).toThrow(
/Duplicate/,
)
expect(() =>
first.layout.registerLayout(definition('invalid/name')),
).toThrow(/ID/)
} finally {
first.dispose()
second.dispose()
}
})
it('retains the active layout when selection closes and prevents entry through code or cache restoration', () => {
const first = mountWorkspace()
const custom = shallowReactive({
...definition('optional'),
selectable: true,
})
first.layout.registerLayout(custom)
expect(first.layout.updateLayout('optional')).toBe(true)
expect(first.layout.activeLayoutId.value).toBe('optional')
custom.selectable = false
expect(first.layout.activeLayoutId.value).toBe('optional')
first.settings.$persist()
const second = mountWorkspace()
try {
second.layout.registerLayout(custom)
expect(second.layout.activeLayoutId.value).toBe('side')
expect(second.layout.updateLayout('optional')).toBe(false)
expect(first.layout.updateLayout('top')).toBe(true)
expect(first.layout.updateLayout('optional')).toBe(false)
expect(first.layout.activeLayoutId.value).toBe('top')
} finally {
first.dispose()
second.dispose()
}
})
it('uses the declared structure for discovered and explicitly registered previews', () => {
const workspace = mountWorkspace()
const preview = {
rows: [['tabs' as const]],
bottomRows: [['actions' as const]],
sidebar: 'right' as const,
footer: true,
}
try {
workspace.layout.registerLayout({ ...definition('test-preview'), preview })
const entries = workspace.layout.layouts.value
const registered = entries.find(({ id }) => id === 'test-preview')!
expect(registered.preview).toMatchObject(preview)
preview.rows[0].pop()
expect(registered.preview?.rows).toEqual([['tabs']])
expect(
entries.find(({ id }) => id === 'custom-top')?.preview?.rows,
).toEqual([['tabs', 'actions'], ['navigation']])
expect(
entries.find(({ id }) => id === 'split')?.preview?.wideHeaderRows,
).toBe(2)
expect(() =>
workspace.layout.registerLayout({
...definition('invalid-span'),
preview: { ...preview, rows: [['tabs']], wideHeaderRows: 2 },
}),
).toThrow()
} finally {
workspace.dispose()
}
})
it('restores a late registration only while its saved ID is still selected', () => {
localStorage.setItem(
key,
JSON.stringify({
customLayoutId: 'late-entry',
layoutConfig: { mode: 'right' },
}),
)
const { layout, settings, dispose } = mountWorkspace()
try {
expect(layout.selectedLayoutId.value).toBe('late-entry')
expect(layout.activeLayoutId.value).toBe('side')
layout.registerLayout(definition('late-entry'))
expect(layout.activeLayoutId.value).toBe('late-entry')
settings.updateSettingState('layoutConfig', { contentPadding: 11 })
expect(layout.activeLayoutId.value).toBe('late-entry')
settings.updateSettingState('layoutConfig', { mode: 'right' })
expect(layout.activeLayoutId.value).toBe('right')
expect(settings.customLayoutId).toBeNull()
} finally {
dispose()
}
localStorage.setItem(key, JSON.stringify({ customLayoutId: 'late-entry' }))
const next = mountWorkspace()
try {
next.layout.updateLayout('top')
next.layout.registerLayout(definition('late-entry'))
expect(next.layout.activeLayoutId.value).toBe('top')
} finally {
next.dispose()
}
})
it('round-trips a custom selection in browser storage and maps preference v1 to its built-in mode', () => {
const first = mountWorkspace()
first.layout.updateLayout('custom-top')
const file = first.settings.exportPreferences()
expect(file.version).toBe(1)
expect(file.preferences.layoutConfig.mode).toBe('top')
expect(file.preferences).not.toHaveProperty('customLayoutId')
first.settings.$persist()
first.dispose()
const next = mountWorkspace()
try {
expect(next.layout.activeLayoutId.value).toBe('custom-top')
next.settings.importPreferences(JSON.stringify(file))
expect(next.layout.activeLayoutId.value).toBe('top')
expect(next.settings.customLayoutId).toBeNull()
} finally {
next.dispose()
}
})
it('reconciles discovered files for a mounted workspace without discarding manual registrations', () => {
const original = discoveredLayouts.value
const workspace = mountWorkspace()
try {
workspace.layout.registerLayout(definition('manual-entry'))
const fresh = new Map(original)
fresh.set('generated-layout', definition('generated-layout'))
discoveredLayouts.value = fresh
expect(workspace.layout.updateLayout('generated-layout')).toBe(true)
expect(workspace.layout.activeLayoutId.value).toBe('generated-layout')
discoveredLayouts.value = original
expect(workspace.layout.updateLayout('generated-layout')).toBe(false)
expect(workspace.layout.activeLayoutId.value).toBe('side')
expect(workspace.layout.updateLayout('manual-entry')).toBe(true)
} finally {
discoveredLayouts.value = original
workspace.dispose()
}
})
it('normalizes malformed cached IDs and keeps synchronous observers on the selected layout', () => {
localStorage.setItem(
key,
JSON.stringify({
customLayoutId: { id: 'broken' },
layoutConfig: { mode: 'mixed' },
}),
)
const workspace = mountWorkspace()
try {
expect(workspace.settings.customLayoutId).toBeNull()
const seen: string[] = []
const stop = watch(
workspace.layout.selectedLayoutId,
(id) => seen.push(id),
{ flush: 'sync' },
)
workspace.layout.updateLayout('custom-top')
workspace.layout.updateLayout('right')
stop()
expect(seen).toEqual(['custom-top', 'right'])
} finally {
workspace.dispose()
}
})
it('skips closed auto-registration and detects duplicate definitions without dropping valid siblings', () => {
const report = vi.spyOn(console, 'error').mockImplementation(() => void 0)
try {
const catalog = collectLayoutDefinitions({
'./definitions/other.layout.ts': definition('side'),
'./definitions/side.layout.ts': {
...definition('side'),
label: 'Built-in',
},
'./definitions/hidden.layout.js': {
...definition('hidden'),
autoRegister: false,
},
'./definitions/closed.layout.tsx': {
...definition('closed'),
selectable: false,
},
})
expect([...catalog.keys()]).toEqual(['side', 'closed'])
expect(catalog.get('side')?.label).toBe('Built-in')
expect(report).toHaveBeenCalledExactlyOnceWith(
'[useLayout] ./definitions/other.layout.ts',
expect.any(Error),
)
} finally {
report.mockRestore()
}
})

View File

@ -0,0 +1,233 @@
// @vitest-environment node
import {
mkdir,
mkdtemp,
readdir,
readFile,
rm,
writeFile,
} from 'node:fs/promises'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Readable } from 'node:stream'
import { createServer } from 'vite'
import type { ViteDevServer } from 'vite'
import {
generateLayoutSource,
layoutDefinitionsDirectory,
layoutWriteEndpoint,
parseLayoutDesign,
} from '../../apps/admin/src/layout/designer'
import { layoutWriterPlugin } from '../../vite-helper/layout-writer'
const design = {
id: 'lab-top',
label: 'Research "A"',
selectable: false,
rows: [['tabs', 'actions'], ['navigation']],
}
it('renders a standalone definition using only the selected bricks in row order', () => {
const source = generateLayoutSource(design)
expect(source).toContain('selectable: false')
expect(source).toContain('autoRegister: true')
expect(source).toContain('sharedFrame: true')
expect(source).not.toContain('LayoutBreadcrumb')
expect(source.match(/<LayoutRow>/g)).toHaveLength(2)
expect(source).toMatch(
/<LayoutTabs \/>\s+<LayoutHeaderActions \/>\s+<\/LayoutRow>\s+<LayoutRow>\s+<LayoutTopNavigation \/>/,
)
expect(source.match(/<LayoutOutlet \/>/g)).toHaveLength(1)
})
it('validates file identifiers, labels, block names and uniqueness before generating code', () => {
for (const invalid of [
{ id: 'lab/test' },
{ id: 'a'.repeat(65) },
{ label: ' ' },
{ source: 'arbitrary text' },
{ rows: [[]] },
{ rows: [['footer']] },
{ rows: [['tabs'], ['tabs']] },
{ bottomRows: [['tabs']] },
{ bottomRows: [['invalid']] },
])
expect(() => parseLayoutDesign({ ...design, ...invalid })).toThrow()
})
type Middleware = (
req: IncomingMessage,
res: ServerResponse,
next: () => void,
) => Promise<void>
function handler(root: string, vite?: ViteDevServer) {
let middleware: Middleware
const configure = layoutWriterPlugin(root).configureServer as (
server: ViteDevServer,
) => void
configure({
environments: vite?.environments ?? {
client: { moduleGraph: { getModuleByUrl: async () => void 0 } },
},
config: vite?.config ?? { mode: 'development', isProduction: false },
middlewares: {
use: (fn: Middleware) => {
middleware = fn
},
},
} as unknown as ViteDevServer)
return async (
data = JSON.stringify(design),
headers: Record<string, string> = {},
peer = '127.0.0.1',
) => {
const req = Object.assign(Readable.from([Buffer.from(data)]), {
socket: { remoteAddress: peer },
url: layoutWriteEndpoint,
method: 'POST',
headers: {
host: 'localhost:9527',
origin: 'http://localhost:9527',
'content-type': 'application/json',
'x-ray-layout-write': '1',
...headers,
},
})
let status = 0
let body = ''
await middleware(
req as unknown as IncomingMessage,
{
writeHead(value: number) {
status = value
},
end(value: string) {
body = value
},
} as ServerResponse,
() => {
throw new Error('unexpected route')
},
)
return { status, ...JSON.parse(body) } as {
status: number
path?: string
error?: string
}
}
}
it.each([
{ mode: 'production', isProduction: false },
{ mode: 'development', isProduction: true },
])(
'omits the file writer when serving a production configuration',
(config) => {
const use = vi.fn()
const configure = layoutWriterPlugin('.').configureServer as (
server: ViteDevServer,
) => void
configure({ config, middlewares: { use } } as unknown as ViteDevServer)
expect(use).not.toHaveBeenCalled()
},
)
it('publishes one complete source file, rejects collisions and restricts local writes', async () => {
const root = await mkdtemp(join(tmpdir(), 'ray-layout-lab-'))
const directory = join(root, layoutDefinitionsDirectory)
const post = handler(root)
try {
await mkdir(directory, { recursive: true })
const restricted: Record<string, string>[] = [
{ origin: 'http://localhost:8000' },
{ origin: '' },
{ 'x-ray-layout-write': '' },
{ 'content-type': 'text/plain' },
]
for (const headers of restricted)
expect((await post(void 0, headers)).status).toBe(403)
expect((await post(void 0, {}, '192.0.2.10')).status).toBe(403)
expect((await post('x'.repeat(8193))).status).toBe(413)
expect((await post(JSON.stringify({ ...design, id: 'a/b' }))).status).toBe(
400,
)
expect(await readdir(directory)).toEqual([])
const results = await Promise.all([post(), post()])
expect(results.map(({ status }) => status).sort()).toEqual([201, 409])
expect(results.find(({ status }) => status === 201)?.path).toBe(
`${layoutDefinitionsDirectory}/lab-top.layout.tsx`,
)
expect(await readdir(directory)).toEqual(['lab-top.layout.tsx'])
expect(await readFile(join(directory, 'lab-top.layout.tsx'), 'utf8')).toBe(
generateLayoutSource(design),
)
await writeFile(join(directory, 'existing.layout.js'), '// user source')
expect(
(await post(JSON.stringify({ ...design, id: 'existing' }))).status,
).toBe(409)
} finally {
await rm(root, { recursive: true, force: true })
}
})
it('refreshes the active Vite glob and sends HMR even with filesystem watching disabled', async () => {
const root = await mkdtemp(join(tmpdir(), 'ray-layout-catalog-'))
const directory = join(root, layoutDefinitionsDirectory)
const source = '/src/layout/discovery.ts'
let vite: ViteDevServer | undefined
try {
await mkdir(directory, { recursive: true })
await writeFile(
join(directory, '..', 'discovery.ts'),
[
"export const layouts = Object.keys(import.meta.glob('./definitions/*.layout.tsx'))",
'if (import.meta.hot) import.meta.hot.accept()',
].join('\n'),
)
vite = await createServer({
configFile: false,
root: join(root, 'apps/admin'),
envFile: false,
logLevel: 'silent',
optimizeDeps: { noDiscovery: true, include: [] },
server: { middlewareMode: true, watch: null, ws: false },
})
const client = vite.environments.client
expect((await client.transformRequest(source))?.code).not.toContain(
'lab-top.layout.tsx',
)
const send = vi.spyOn(client.hot, 'send')
expect((await handler(root, vite)()).status).toBe(201)
expect(send).toHaveBeenCalledWith(
expect.objectContaining({
type: 'update',
updates: [expect.objectContaining({ type: 'js-update', path: source })],
}),
)
expect((await client.transformRequest(source))?.code).toContain(
'lab-top.layout.tsx',
)
} finally {
await vite?.close()
await rm(root, { recursive: true, force: true })
}
})

View File

@ -1,9 +1,10 @@
import { LAYOUT_SIDER_REF } from '@/app-config'
import CustomMenu from '@/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu' import CustomMenu from '@/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu'
import { piniaSettingStore } from '@/store/modules/setting' import { piniaSettingStore } from '@/store/modules/setting'
import { getDefaultSettingConfig } from '@/store/modules/setting/constant' import { getDefaultSettingConfig } from '@/store/modules/setting/constant'
import type { AppMenuOption } from '@/types'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import type { VueWrapper } from '@vue/test-utils' import type { VueWrapper } from '@vue/test-utils'
import type { LayoutInst } from 'naive-ui'
import { NButton } from 'naive-ui' import { NButton } from 'naive-ui'
import { createPinia, disposePinia, setActivePinia } from 'pinia' import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { nextTick, ref } from 'vue' import { nextTick, ref } from 'vue'
@ -12,8 +13,7 @@ import type { Ref } from 'vue'
const state = vi.hoisted(() => ({ const state = vi.hoisted(() => ({
collapsed: null as unknown as Ref<boolean>, collapsed: null as unknown as Ref<boolean>,
smaller: null as unknown as Ref<boolean>, smaller: null as unknown as Ref<boolean>,
options: null as unknown as Ref<AppMenuOption[]>,
menuKey: null as unknown as Ref<string>,
refresh: vi.fn(), refresh: vi.fn(),
collapse: vi.fn(), collapse: vi.fn(),
scroll: vi.fn(), scroll: vi.fn(),
@ -35,8 +35,6 @@ vi.mock('@/store', async () => {
...settings, ...settings,
useMenuGetters: () => ({ useMenuGetters: () => ({
getCollapsed: state.collapsed, getCollapsed: state.collapsed,
getMenuOptions: state.options,
getMenuKey: state.menuKey,
}), }),
useMenuActions: () => ({ useMenuActions: () => ({
setupAppMenu: state.refresh, setupAppMenu: state.refresh,
@ -52,8 +50,9 @@ beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
state.collapsed = ref(false) state.collapsed = ref(false)
state.smaller = ref(false) state.smaller = ref(false)
state.options = ref([]) const sider = LAYOUT_SIDER_REF as Ref<LayoutInst | null>
state.menuKey = ref('/reports')
sider.value = null
state.refresh.mockResolvedValue(void 0) state.refresh.mockResolvedValue(void 0)
vi.stubGlobal('$message', { success: state.success, error: state.error }) vi.stubGlobal('$message', { success: state.success, error: state.error })
pinia = createPinia() pinia = createPinia()
@ -92,40 +91,14 @@ it('applies size presets without replacing menu behavior or layout preferences',
}) })
it('enables sidebar actions only when the active desktop layout has a sidebar', async () => { it('enables sidebar actions only when the active desktop layout has a sidebar', async () => {
const settings = piniaSettingStore() const sider = LAYOUT_SIDER_REF as Ref<LayoutInst | null>
await button('menu.collapse').trigger('click')
expect(state.collapse).toHaveBeenCalledExactlyOnceWith(true)
settings.updateSettingState('layoutConfig', { mode: 'top' })
await nextTick()
expect(button('menu.collapse').props('disabled')).toBe(true) expect(button('menu.collapse').props('disabled')).toBe(true)
expect(button('menu.scrollTop').props('disabled')).toBe(true) expect(button('menu.scrollTop').props('disabled')).toBe(true)
settings.updateSettingState('layoutConfig', { mode: 'mixed' }) sider.value = { scrollTo: state.scroll } as unknown as LayoutInst
await nextTick()
expect(button('menu.collapse').props('disabled')).toBe(true)
state.options.value = [
{
fullPath: '/reports',
path: '/reports',
name: 'Reports',
label: 'Reports',
key: '/reports',
meta: {},
show: true,
children: [
{
fullPath: '/reports/daily',
path: '/reports/daily',
name: 'Daily',
label: 'Daily',
key: '/reports/daily',
meta: {},
show: true,
},
],
},
]
await nextTick() await nextTick()
await button('menu.collapse').trigger('click')
expect(state.collapse).toHaveBeenCalledExactlyOnceWith(true)
expect(button('menu.collapse').props('disabled')).toBe(false) expect(button('menu.collapse').props('disabled')).toBe(false)
await button('menu.scrollTop').trigger('click') await button('menu.scrollTop').trigger('click')
expect(state.scroll).toHaveBeenCalledExactlyOnceWith({ expect(state.scroll).toHaveBeenCalledExactlyOnceWith({

View File

@ -1,8 +1,9 @@
import MenuTag from '@/layout/components/MenuTag' import MenuTag from '@/layout/components/MenuTag'
import type { MenuTagOptions } from '@/types' import type { MenuTagOptions } from '@/types'
import { RIcon } from '@ray-template/ui/icon'
import { flushPromises, mount } from '@vue/test-utils' import { flushPromises, mount } from '@vue/test-utils'
import type { VueWrapper } from '@vue/test-utils' import type { VueWrapper } from '@vue/test-utils'
import { NDropdown } from 'naive-ui' import { NDropdown, NTag } from 'naive-ui'
import { h, nextTick, ref } from 'vue' import { h, nextTick, ref } from 'vue'
import type { Ref } from 'vue' import type { Ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router' import { createMemoryHistory, createRouter } from 'vue-router'
@ -11,8 +12,15 @@ import type { Router } from 'vue-router'
const state = vi.hoisted(() => ({ const state = vi.hoisted(() => ({
tags: null as unknown as Ref<MenuTagOptions[]>, tags: null as unknown as Ref<MenuTagOptions[]>,
active: null as unknown as Ref<MenuTagOptions | null>, active: null as unknown as Ref<MenuTagOptions | null>,
round: null as unknown as Ref<boolean>,
top: null as unknown as Ref<boolean>,
fixed: null as unknown as Ref<boolean>,
drag: null as unknown as Ref<boolean>,
close: vi.fn(), close: vi.fn(),
navigate: vi.fn(), navigate: vi.fn(),
move: vi.fn(),
toggleTop: vi.fn(),
toggleFixed: vi.fn(),
})) }))
vi.mock('@/hooks', () => ({ vi.mock('@/hooks', () => ({
@ -36,8 +44,23 @@ vi.mock('@/store', () => ({
getMenuTagOptions: state.tags, getMenuTagOptions: state.tags,
getCurrentMenuOption: state.active, getCurrentMenuOption: state.active,
}), }),
useMenuActions: () => ({ changeMenuModelValue: state.navigate }), useMenuActions: () => ({
changeMenuModelValue: state.navigate,
isMenuTagTopped: (tag?: MenuTagOptions) =>
state.top.value && tag?.topped === true,
isMenuTagFixed: (tag?: MenuTagOptions) =>
state.fixed.value && tag?.fixed === true,
toggleMenuTagTop: state.toggleTop,
toggleMenuTagFixed: state.toggleFixed,
moveMenuTag: state.move,
}),
useRuntimeGetters: () => ({ globalMainLayoutLoad: ref(true) }), useRuntimeGetters: () => ({ globalMainLayoutLoad: ref(true) }),
useSettingGetters: () => ({
getMenuTagRound: state.round,
getMenuTagTop: state.top,
getMenuTagFixed: state.fixed,
getMenuTagDrag: state.drag,
}),
})) }))
let wrapper: VueWrapper let wrapper: VueWrapper
@ -55,6 +78,10 @@ beforeEach(async () => {
})) as MenuTagOptions[], })) as MenuTagOptions[],
) )
state.active = ref(state.tags.value[0]!) state.active = ref(state.tags.value[0]!)
state.round = ref(false)
state.top = ref(true)
state.fixed = ref(true)
state.drag = ref(true)
router = createRouter({ router = createRouter({
history: createMemoryHistory(), history: createMemoryHistory(),
routes: [ routes: [
@ -69,9 +96,15 @@ beforeEach(async () => {
attachTo: host, attachTo: host,
global: { global: {
plugins: [router], plugins: [router],
mocks: { $t: (key: string) => key }, stubs: { 'transition-group': false },
mocks: {
$t: (key: string, params?: { name: string }) =>
params ? `${key}:${params.name}` : key,
},
}, },
}) })
await import('interactjs')
await flushPromises()
}) })
afterEach(() => { afterEach(() => {
@ -79,6 +112,7 @@ afterEach(() => {
router.options.history.destroy() router.options.history.destroy()
host.remove() host.remove()
outside.remove() outside.remove()
vi.unstubAllGlobals()
}) })
const contextDropdown = () => const contextDropdown = () =>
@ -98,6 +132,32 @@ const mouse = (element: Element, type: string, button: number) => {
) )
} }
const point = (
element: Element,
type: string,
clientX: number,
clientY = 16,
) => {
const event = new PointerEvent(type, {
bubbles: true,
isPrimary: true,
pointerId: 2,
pointerType: 'mouse',
buttons: type === 'pointerup' ? 0 : 1,
clientX,
clientY,
})
Object.defineProperties(event, {
pageX: { value: clientX },
pageY: { value: clientY },
})
element.dispatchEvent(event)
}
const dragPreview = () =>
document.body.querySelector<HTMLElement>('.menu-tag__drag-preview')
const openContextMenu = async (index: number) => { const openContextMenu = async (index: number) => {
const tab = wrapper.findAll('.menu-tag__tab')[index]!.element const tab = wrapper.findAll('.menu-tag__tab')[index]!.element
@ -109,6 +169,80 @@ const openContextMenu = async (index: number) => {
await flushPromises() await flushPromises()
} }
it('closes with the named native tag button without selecting the page', async () => {
const closeButton = wrapper.get(
'button.n-tag__close[aria-label="menuTag.closeNamed:Orders"]',
)
point(closeButton.element, 'pointerdown', 10)
point(closeButton.element, 'pointermove', 40)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(false)
point(closeButton.element, 'pointerup', 40)
await closeButton.trigger('click', { detail: 1 })
expect(state.close).toHaveBeenCalledExactlyOnceWith(1)
expect(state.navigate).not.toHaveBeenCalled()
})
it('updates the native close label when the tag is renamed', async () => {
const closeButton = wrapper.get('.n-tag__close')
expect(closeButton.attributes('aria-label')).toBe(
'menuTag.closeNamed:Reports',
)
state.tags.value[0]!.breadcrumbLabel = 'Summary'
await nextTick()
expect(closeButton.attributes('aria-label')).toBe(
'menuTag.closeNamed:Summary',
)
})
it.each(['button', 'Delete'])(
'restores focus after closing by keyboard (%s)',
async (method) => {
state.close.mockImplementationOnce((index: number) => {
state.tags.value.splice(index, 1)
})
const tab = wrapper.get<HTMLButtonElement>('.menu-tag__tab[title="Orders"]')
const closeButton = wrapper.get<HTMLButtonElement>(
'button.n-tag__close[aria-label="menuTag.closeNamed:Orders"]',
)
if (method === 'Delete') {
tab.element.focus()
await tab.trigger('keydown', { key: 'Delete' })
} else {
closeButton.element.focus()
await closeButton.trigger('click', { detail: 0 })
}
expect(state.close).toHaveBeenCalledExactlyOnceWith(1)
expect(state.navigate).not.toHaveBeenCalled()
expect(document.activeElement?.textContent).toBe('Users')
},
)
it('shares the native border across tabs and highlights the current page', async () => {
const tagTypes = () =>
wrapper.findAllComponents(NTag).map((tag) => tag.props('type'))
expect(tagTypes()).toEqual(['primary', 'default', 'default'])
state.tags.value[0]!.fixed = true
state.active.value = state.tags.value[1]!
await nextTick()
expect(tagTypes()).toEqual(['default', 'primary', 'default'])
expect(wrapper.findAll('.menu-tag__item .n-tag__border')).toHaveLength(3)
})
it('applies the native round style to open tags when the preference changes', async () => {
const tag = wrapper.get('.menu-tag__item')
expect(tag.classes('n-tag--round')).toBe(false)
state.round.value = true
await nextTick()
expect(tag.classes('n-tag--round')).toBe(true)
})
it('keeps the context menu open while repeatedly right-clicking other tags', async () => { it('keeps the context menu open while repeatedly right-clicking other tags', async () => {
for (const index of [0, 1, 2, 0]) { for (const index of [0, 1, 2, 0]) {
await openContextMenu(index) await openContextMenu(index)
@ -122,7 +256,7 @@ it('applies a context command to the most recently right-clicked tag', async ()
await openContextMenu(2) await openContextMenu(2)
const command = [ const command = [
...document.querySelectorAll('.n-dropdown-option-body'), ...document.querySelectorAll('.n-dropdown-option-body__label'),
].find((option) => option.textContent === 'closeCurrent') ].find((option) => option.textContent === 'closeCurrent')
expect(command).toBeDefined() expect(command).toBeDefined()
@ -132,6 +266,275 @@ it('applies a context command to the most recently right-clicked tag', async ()
expect(contextDropdown().props('show')).toBe(false) expect(contextDropdown().props('show')).toBe(false)
}) })
it('keeps context commands tied to the selected page when the order changes', async () => {
await openContextMenu(0)
state.tags.value.reverse()
await nextTick()
const command = Array.from(
document.querySelectorAll('.n-dropdown-option-body__label'),
).find((option) => option.textContent === 'fix')
mouse(command!, 'click', 0)
expect(state.toggleFixed).toHaveBeenCalledExactlyOnceWith('/reports')
})
it('updates tab status and actions while preferences change', async () => {
state.tags.value[0].topped = true
state.tags.value[0].fixed = true
await openContextMenu(0)
const tab = wrapper.get('[data-menu-tag-path="/reports"]')
const actions = () =>
contextDropdown()
.props('options')
?.map((option) => option.key)
const pin = tab.get('.n-tag__icon').getComponent(RIcon)
const label = tab.get('.menu-tag__tab')
expect(tab.find('.n-tag__close').exists()).toBe(false)
expect(pin.props('name')).toBe('action/pin')
expect(pin.attributes('aria-hidden')).toBe('true')
expect(label.attributes('aria-label')).toBe(
'Reports · menuTag.topped · menuTag.fixed',
)
expect(actions()).toEqual(
expect.arrayContaining(['toggleTop', 'toggleFixed']),
)
state.top.value = false
state.fixed.value = false
state.drag.value = false
await nextTick()
expect(tab.find('.n-tag__close').exists()).toBe(true)
expect(tab.find('.n-tag__icon').exists()).toBe(false)
expect(label.attributes('aria-label')).toBeUndefined()
expect(label.attributes('aria-keyshortcuts')).toBeUndefined()
expect(actions()).not.toContain('toggleTop')
expect(actions()).not.toContain('toggleFixed')
})
it('reorders a focused protected tab with Shift and an arrow key', async () => {
state.tags.value[0].fixed = true
await nextTick()
const tab = wrapper.get('[data-menu-tag-path="/reports"]')
const button = tab.get('.menu-tag__tab')
expect(tab.find('.n-tag__close').exists()).toBe(false)
expect(button.attributes('aria-keyshortcuts')).toBe(
'Shift+ArrowLeft Shift+ArrowRight',
)
await button.trigger('keydown', { key: 'ArrowRight' })
expect(state.move).not.toHaveBeenCalled()
await button.trigger('keydown', { key: 'ArrowRight', shiftKey: true })
expect(state.move).toHaveBeenCalledExactlyOnceWith(
'/reports',
'/orders',
'after',
)
expect(state.navigate).not.toHaveBeenCalled()
})
const mockTagRects = (viewportWidth = 300) => {
const row = wrapper.get<HTMLElement>('.menu-tag-wrapper').element
const scroller = row.closest('.n-scrollbar-container')!
const mockRect = (element: Element, measure: () => DOMRect) => {
element.getBoundingClientRect = measure
element.getClientRects = () => [measure()] as unknown as DOMRectList
}
mockRect(scroller, () => new DOMRect(0, 0, viewportWidth, 32))
Object.defineProperties(scroller, {
clientWidth: { value: viewportWidth },
scrollWidth: { value: 300 },
})
mockRect(row, () => new DOMRect(-scroller.scrollLeft, 0, 300, 32))
const tags = wrapper.findAll<HTMLElement>('[data-menu-tag-path]')
tags.forEach(({ element }, index) => {
Object.defineProperties(element, {
offsetLeft: { value: index * 100 },
offsetWidth: { value: 94 },
})
mockRect(
element,
() => new DOMRect(index * 100 - scroller.scrollLeft, 0, 94, 30),
)
})
return { row, scroller, tags }
}
it('reorders from the tab body using the release position and ignores the drag click', async () => {
const { row, tags } = mockTagRects()
const source = tags[0].element
point(source, 'pointerdown', 10)
expect(dragPreview()).toBeNull()
point(tags[1].element, 'pointermove', 180, 22)
const preview = dragPreview()!
expect(preview.parentElement).toBe(row.closest('.menu-tag'))
expect(preview.textContent).toBe(source.textContent)
expect(preview.dataset.menuTagPath).toBeUndefined()
expect(preview.getAttribute('aria-hidden')).toBe('true')
expect(preview.hasAttribute('inert')).toBe(true)
expect(preview.style.transform).toBe('translate3d(170px, 6px, 0)')
point(tags[1].element, 'pointermove', 190, 24)
expect(dragPreview()).toBe(preview)
expect(preview.style.transform).toBe('translate3d(180px, 8px, 0)')
expect(tags[1].attributes('data-menu-tag-drop')).toBe('after')
expect(state.move).not.toHaveBeenCalled()
point(tags[2].element, 'pointerup', 285)
expect(state.move).toHaveBeenCalledExactlyOnceWith(
'/reports',
'/users',
'after',
)
expect(
row.querySelector('[data-menu-tag-drop],[data-menu-tag-dragged]'),
).toBeNull()
expect(dragPreview()).toBeNull()
await tags[0].trigger('click', { detail: 1 })
expect(state.navigate).not.toHaveBeenCalled()
point(source, 'pointerdown', 10)
point(source, 'pointermove', 12)
point(source, 'pointerup', 12)
await tags[0].trigger('click', { detail: 1 })
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(
'/reports',
state.tags.value[0],
)
expect(state.move).toHaveBeenCalledTimes(1)
})
it.each([
{ target: 'outside the horizontal viewport', x: -10, firstTopped: false },
{ target: 'over the other tab group', x: 20, firstTopped: true },
])('rejects a drop $target', async ({ x, firstTopped }) => {
state.tags.value[0]!.topped = firstTopped
await nextTick()
const { row, tags } = mockTagRects()
const source = tags[2].element
const target = firstTopped ? tags[0].element : outside
point(source, 'pointerdown', 240)
point(target, 'pointermove', x)
expect(source.hasAttribute('data-menu-tag-dragged')).toBe(true)
expect(row.querySelector('[data-menu-tag-drop]')).toBeNull()
point(target, 'pointerup', x)
expect(state.move).not.toHaveBeenCalled()
})
it('refreshes the drop marker after a scroll with a stationary pointer', () => {
const { scroller, tags } = mockTagRects(220)
const source = tags[0].element
const requestFrame = vi.fn((_callback: FrameRequestCallback) => 1)
vi.stubGlobal('requestAnimationFrame', requestFrame)
point(source, 'pointerdown', 30)
point(tags[1].element, 'pointermove', 180)
const position = dragPreview()?.style.transform
expect(position).toBe('translate3d(150px, 0px, 0)')
expect(tags[1].attributes('data-menu-tag-drop')).toBe('after')
expect(requestFrame).toHaveBeenCalledTimes(1)
requestFrame.mock.calls[0][0](16)
scroller.scrollLeft = 80
scroller.dispatchEvent(new Event('scroll'))
expect(requestFrame).toHaveBeenCalledTimes(2)
requestFrame.mock.calls[1][0](32)
expect(tags[2].attributes('data-menu-tag-drop')).toBe('after')
expect(dragPreview()?.style.transform).toBe(position)
point(tags[2].element, 'pointerup', 180)
})
it('cancels dragging with Escape and preserves keyboard activation', async () => {
const button = wrapper.get<HTMLButtonElement>(
'[data-menu-tag-path="/orders"] .menu-tag__tab',
)
point(button.element, 'pointerdown', 10)
point(button.element, 'pointermove', 60)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(true)
await button.trigger('keydown', { key: 'Escape' })
expect(dragPreview()).toBeNull()
point(button.element, 'pointerup', 60)
await button.trigger('click', { detail: 0 })
expect(state.navigate).toHaveBeenCalledExactlyOnceWith(
'/orders',
state.tags.value[1],
)
await button.trigger('click', { detail: 1 })
expect(state.move).not.toHaveBeenCalled()
expect(state.navigate).toHaveBeenCalledTimes(1)
})
it.each(['pointercancel', 'disabled'])(
'removes the drag preview when the drag is %s',
async (reason) => {
const { row, tags } = mockTagRects()
const source = tags[0].element
point(source, 'pointerdown', 10)
point(tags[1].element, 'pointermove', 180)
expect(dragPreview()).not.toBeNull()
if (reason === 'pointercancel') point(source, 'pointercancel', 180)
else {
state.drag.value = false
await nextTick()
}
expect(dragPreview()).toBeNull()
expect(
row.querySelector('[data-menu-tag-drop],[data-menu-tag-dragged]'),
).toBeNull()
expect(state.move).not.toHaveBeenCalled()
},
)
it.each([
{ hold: 100, claimed: false },
{ hold: 400, claimed: true },
])(
'claims a horizontal touch after $hold ms: $claimed',
({ hold, claimed }) => {
const button = wrapper.get<HTMLButtonElement>('.menu-tag__tab').element
const start = new PointerEvent('pointerdown', {
bubbles: true,
isPrimary: true,
pointerId: 2,
pointerType: 'touch',
buttons: 1,
clientX: 10,
clientY: 16,
})
const move = new TouchEvent('touchmove', {
bubbles: true,
cancelable: true,
touches: [
new Touch({ identifier: 2, target: button, clientX: 30, clientY: 16 }),
],
})
Object.defineProperty(move, 'timeStamp', { value: start.timeStamp + hold })
button.dispatchEvent(start)
button.dispatchEvent(move)
expect(move.defaultPrevented).toBe(claimed)
expect(wrapper.find('[data-menu-tag-dragged]').exists()).toBe(claimed)
expect(Boolean(dragPreview())).toBe(claimed)
},
)
it.each([0, 2])( it.each([0, 2])(
'dismisses when mouse button %i is clicked outside the tags and menu', 'dismisses when mouse button %i is clicked outside the tags and menu',
async (button) => { async (button) => {
@ -166,3 +569,19 @@ it('dismisses the context menu with Escape after switching tags', async () => {
await nextTick() await nextTick()
expect(contextDropdown().props('show')).toBe(false) 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<HTMLButtonElement>('.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,
)
})

View File

@ -62,8 +62,12 @@ describe('layout preferences', () => {
const store = piniaSettingStore() const store = piniaSettingStore()
expect(store.sideBarLogo?.url).toBe(migrated) expect(store.sideBarLogo?.url).toBe(migrated)
expect(store.appRootRoute.path).toBe('/old-unregistered-home') expect(store.appRootRoute).toEqual({
name: 'Old',
path: '/old-unregistered-home',
})
store.updateSettingState('sideBarLogo', { url: '/dashboard' }) store.updateSettingState('sideBarLogo', { url: '/dashboard' })
store.updateSettingState('appRootRoute', { path: '/saved-home' })
store.$persist() store.$persist()
first.app.unmount() first.app.unmount()
disposePinia(first.pinia) disposePinia(first.pinia)
@ -71,6 +75,10 @@ describe('layout preferences', () => {
try { try {
expect(piniaSettingStore().sideBarLogo?.url).toBe('/dashboard') expect(piniaSettingStore().sideBarLogo?.url).toBe('/dashboard')
expect(piniaSettingStore().appRootRoute).toEqual({
name: 'Old',
path: '/saved-home',
})
expect( expect(
piniaSettingStore().exportPreferences().preferences, piniaSettingStore().exportPreferences().preferences,
).not.toHaveProperty('workspaceLandingMigrated') ).not.toHaveProperty('workspaceLandingMigrated')
@ -132,6 +140,14 @@ describe('layout preferences', () => {
}) })
expect(store.localeLanguage).toBe('en-US') expect(store.localeLanguage).toBe('en-US')
expect(store.menuTagSwitch).toBe(false) expect(store.menuTagSwitch).toBe(false)
expect(store.menuTagRound).toBe(false)
expect(store).toMatchObject({
menuTagTop: true,
menuTagFixed: true,
menuTagDrag: true,
breadcrumbIcon: true,
breadcrumbIconFallback: true,
})
expect(store.menuConfig).toMatchObject({ expect(store.menuConfig).toMatchObject({
iconSize: 20, iconSize: 20,
collapsedIconSize: 22, collapsedIconSize: 22,
@ -186,6 +202,12 @@ describe('layout preferences', () => {
store.updateSettingState('layoutConfig', { mode: 'right' }) store.updateSettingState('layoutConfig', { mode: 'right' })
store.updateSettingState('appTheme', 'dark') store.updateSettingState('appTheme', 'dark')
store.updateSettingState('themeStyle', 'material') store.updateSettingState('themeStyle', 'material')
store.updateSettingState('menuTagRound', true)
store.updateSettingState('menuTagTop', false)
store.updateSettingState('menuTagFixed', false)
store.updateSettingState('menuTagDrag', false)
store.updateSettingState('breadcrumbIcon', false)
store.updateSettingState('breadcrumbIconFallback', false)
store.updateSettingState('watermarkConfig', { content: 'Portable' }) store.updateSettingState('watermarkConfig', { content: 'Portable' })
store.updateSettingState('keepAliveConfig', { store.updateSettingState('keepAliveConfig', {
keepAliveExclude: ['Page'], keepAliveExclude: ['Page'],
@ -195,6 +217,9 @@ describe('layout preferences', () => {
store.updateSettingState('layoutConfig', { mode: 'top' }) store.updateSettingState('layoutConfig', { mode: 'top' })
store.updateSettingState('appTheme', 'light') store.updateSettingState('appTheme', 'light')
store.updateSettingState('menuTagRound', false)
store.updateSettingState('menuTagDrag', true)
store.updateSettingState('breadcrumbIcon', true)
store.updateSettingState('appRootRoute', { path: '/custom-home' }) store.updateSettingState('appRootRoute', { path: '/custom-home' })
store.changePrimaryColor('#000000') store.changePrimaryColor('#000000')
store.updateSettingState('themeStyle', 'plain') store.updateSettingState('themeStyle', 'plain')
@ -202,6 +227,7 @@ describe('layout preferences', () => {
await nextTick() await nextTick()
expect(store.exportPreferences()).toEqual(file) expect(store.exportPreferences()).toEqual(file)
expect(store.menuTagRound).toBe(true)
expect(store._appTheme).toBe(true) expect(store._appTheme).toBe(true)
expect(store.themeOverrides.common?.primaryColor).toBe('#3468db') expect(store.themeOverrides.common?.primaryColor).toBe('#3468db')
expect(store.themeOverrides.Card?.borderRadius).toBe('20px') expect(store.themeOverrides.Card?.borderRadius).toBe('20px')
@ -216,6 +242,12 @@ describe('layout preferences', () => {
layoutConfig: { mode: 'right' }, layoutConfig: { mode: 'right' },
appTheme: 'dark', appTheme: 'dark',
themeStyle: 'material', themeStyle: 'material',
menuTagRound: true,
menuTagTop: false,
menuTagFixed: false,
menuTagDrag: false,
breadcrumbIcon: false,
breadcrumbIconFallback: false,
}) })
} finally { } finally {
app.unmount() app.unmount()
@ -232,12 +264,30 @@ describe('layout preferences', () => {
try { try {
store.updateSettingState('themeStyle', 'material') store.updateSettingState('themeStyle', 'material')
store.updateSettingState('menuTagRound', true)
store.changePrimaryColor('#3468db') store.changePrimaryColor('#3468db')
const { preferences, ...file } = store.exportPreferences() const { preferences, ...file } = store.exportPreferences()
const { themeStyle: _style, ...legacy } = preferences const {
themeStyle: _style,
menuTagRound: _round,
menuTagTop: _top,
menuTagFixed: _fixed,
menuTagDrag: _drag,
breadcrumbIcon: _icon,
breadcrumbIconFallback: _fallback,
...legacy
} = preferences
store.importPreferences(JSON.stringify({ ...file, preferences: legacy })) store.importPreferences(JSON.stringify({ ...file, preferences: legacy }))
expect(store.themeStyle).toBe('modern') expect(store.themeStyle).toBe('modern')
expect(store.menuTagRound).toBe(false)
expect(store.exportPreferences().preferences).toMatchObject({
menuTagTop: true,
menuTagFixed: true,
menuTagDrag: true,
breadcrumbIcon: true,
breadcrumbIconFallback: true,
})
expect(store.themeOverrides.Card?.borderRadius).toBe('12px') expect(store.themeOverrides.Card?.borderRadius).toBe('12px')
expect(store.themeOverrides.common?.primaryColor).toBe('#3468db') expect(store.themeOverrides.common?.primaryColor).toBe('#3468db')
@ -252,7 +302,7 @@ describe('layout preferences', () => {
} }
}) })
it('uses the contrast of each resolved button fill after importing an accent and switching modes', () => { it('keeps light primary buttons white and resolves custom colors across modes', () => {
const pinia = createPinia() const pinia = createPinia()
setActivePinia(pinia) setActivePinia(pinia)
@ -273,10 +323,18 @@ describe('layout preferences', () => {
try { try {
store.changePrimaryColor('#2d8cf0') store.changePrimaryColor('#2d8cf0')
expect(store.themeOverrides.common?.primaryColor).toBe('#2d8cf0')
expect(store.themeOverrides.Button).toMatchObject({ expect(store.themeOverrides.Button).toMatchObject({
colorPrimary: 'rgb(45, 140, 240)', colorPrimary: 'rgb(34, 112, 194)',
textColorPrimary: '#000', colorHoverPrimary: 'rgb(57, 121, 188)',
textColorHoverPrimary: '#000', colorPressedPrimary: 'rgb(31, 106, 184)',
textColorPrimary: '#fff',
textColorHoverPrimary: '#fff',
textColorPressedPrimary: '#fff',
textColorFocusPrimary: '#fff',
borderPrimary: '1px solid rgb(34, 112, 194)',
textColorTextPrimary: 'rgb(34, 112, 194)',
textColorGhostPrimary: 'rgb(34, 112, 194)',
}) })
const primaryColor = 'hsla(0, 0%, 90%, 0.1)' const primaryColor = 'hsla(0, 0%, 90%, 0.1)'
@ -300,7 +358,10 @@ describe('layout preferences', () => {
]) ])
store.updateSettingState('appTheme', 'light') store.updateSettingState('appTheme', 'light')
pixels = [252, 252, 252, 255, 234, 234, 234, 255] pixels = [252, 252, 252, 255, 234, 234, 234, 255]
expect(store.themeOverrides.Button?.textColorPrimary).toBe('#000') expect(store.themeOverrides.Button).toMatchObject({
colorPrimary: 'rgb(111, 111, 111)',
textColorPrimary: '#fff',
})
expect(paints.at(-3)).toBe('#ffffff') expect(paints.at(-3)).toBe('#ffffff')
store.changePrimaryColor() store.changePrimaryColor()
expect(store.themeOverrides.Button?.textColorPrimary).toBeUndefined() expect(store.themeOverrides.Button?.textColorPrimary).toBeUndefined()

View File

@ -1,12 +1,51 @@
import { shallowMount } from '@vue/test-utils' import { flushPromises, mount, shallowMount } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia' import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { h, nextTick } from 'vue' import {
defineComponent,
h,
nextTick,
reactive,
ref,
vShow,
withDirectives,
} from 'vue'
import type { SetupContext } from 'vue'
import { createMemoryHistory, createRouter, RouterView } from 'vue-router'
import { LAYOUT_CONTENT_REF } from '../../apps/admin/src/app-config'
import Layout from '../../apps/admin/src/layout' import Layout from '../../apps/admin/src/layout'
import {
LayoutFrame,
LayoutOutlet,
LayoutTabs,
} from '../../apps/admin/src/layout/blocks'
import type { LayoutDesign } from '../../apps/admin/src/layout/designer'
import { useLayout } from '../../apps/admin/src/layout/useLayout'
import { router } from '../../apps/admin/src/router' import { router } from '../../apps/admin/src/router'
import { piniaKeepAliveStore } from '../../apps/admin/src/store/modules/keep-alive'
import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime' import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime'
import { piniaSettingStore } from '../../apps/admin/src/store/modules/setting' import { piniaSettingStore } from '../../apps/admin/src/store/modules/setting'
import { useLayoutDraftPreview } from '../../apps/admin/src/views/demo/layout-lab/useLayoutDraftPreview'
it('lets a custom header replace the complete default header and top navigation', () => { const liveShell = {
LayoutPresentation: false,
SharedFrame: false,
BuiltinLayout: false,
LayoutFrame: false,
LayoutOutlet: false,
LayoutOutletTarget: false,
RayAdminShell: false,
LayoutContent: {
setup(_: unknown, { expose, slots }: SetupContext) {
expose({ scrollTo: vi.fn() })
return () => h('div', slots.default?.())
},
},
teleport: false,
suspense: false,
}
it('lets a custom header replace the complete default header and top navigation', async () => {
const pinia = createPinia() const pinia = createPinia()
setActivePinia(pinia) setActivePinia(pinia)
@ -14,12 +53,13 @@ it('lets a custom header replace the complete default header and top navigation'
const options = { const options = {
global: { global: {
renderStubDefaultSlot: true, renderStubDefaultSlot: true,
stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, stubs: liveShell,
plugins: [router, pinia], plugins: [router, pinia],
}, },
} }
const standard = shallowMount(Layout, options) const standard = shallowMount(Layout, options)
await nextTick()
expect(standard.find('top-navigation-stub').exists()).toBe(true) expect(standard.find('top-navigation-stub').exists()).toBe(true)
standard.unmount() standard.unmount()
const custom = shallowMount(Layout, { const custom = shallowMount(Layout, {
@ -30,6 +70,7 @@ it('lets a custom header replace the complete default header and top navigation'
}) })
try { try {
await nextTick()
expect(custom.find('[data-test="custom-header"]').exists()).toBe(true) expect(custom.find('[data-test="custom-header"]').exists()).toBe(true)
expect(custom.find('top-navigation-stub').exists()).toBe(false) expect(custom.find('top-navigation-stub').exists()).toBe(false)
} finally { } finally {
@ -44,9 +85,10 @@ it('offers a restore button for custom content and also exits with Escape', asyn
setActivePinia(pinia) setActivePinia(pinia)
const runtime = piniaRuntimeStore() const runtime = piniaRuntimeStore()
const wrapper = shallowMount(Layout, { const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: { global: {
renderStubDefaultSlot: true, renderStubDefaultSlot: true,
stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, stubs: liveShell,
plugins: [router, pinia], plugins: [router, pinia],
}, },
slots: { slots: {
@ -55,9 +97,12 @@ it('offers a restore button for custom content and also exits with Escape', asyn
}) })
try { try {
await nextTick()
expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe( expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe(
false, false,
) )
await wrapper.get('.r-layout-skip').trigger('click')
expect(document.activeElement).toBe(wrapper.get('main').element)
runtime.setRuntimeState('layoutContentMaximize', true) runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick() await nextTick()
expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true) expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true)
@ -74,7 +119,111 @@ it('offers a restore button for custom content and also exits with Escape', asyn
} }
}) })
it('moves the full navigation to the right without adding a second menu', () => { it('keeps rows below content independent of copyright and honors inline tab overrides', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
const settings = piniaSettingStore()
layout.registerLayout({
id: 'bottom-tabs',
label: 'Bottom tabs',
component: {
setup: () => () =>
h(LayoutFrame, null, {
bottom: () => h(LayoutTabs),
footer: () => h('span', 'Copyright'),
}),
},
})
layout.updateLayout('bottom-tabs')
const wrapper = mount(Layout, {
slots: {
default: () => h('article', 'Page'),
tabs: () => h('nav', 'Custom tabs'),
},
global: {
plugins: [router, pinia],
stubs: { SettingDrawer: true },
},
})
try {
await flushPromises()
const footer = () => wrapper.get('.r-layout-footer-region')
expect(footer().get('nav').text()).toBe('Custom tabs')
expect(footer().text()).toContain('Copyright')
settings.updateSettingState('copyrightSwitch', false)
await nextTick()
expect(footer().text()).toBe('Custom tabs')
settings.updateSettingState('menuTagSwitch', false)
await nextTick()
expect(footer().find('nav').exists()).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it('previews changes live and restores the saved workspace on exit or leaving the lab', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
layout.updateLayout('top')
const editing = ref(true)
const draft = reactive<LayoutDesign>({
id: 'untitled',
label: 'Draft',
rows: [],
selectable: true,
})
const lab = {
setup() {
const { togglePreview } = useLayoutDraftPreview(draft)
return () => h('button', { onClick: togglePreview }, 'Try')
},
}
const wrapper = mount(Layout, {
slots: {
default: () => (editing.value ? h(lab) : h('article', 'Next page')),
tabs: () => h('nav', 'Open pages'),
},
global: {
plugins: [router, pinia],
stubs: { LayoutHeader: true, TopNavigation: true, SettingDrawer: true },
},
})
try {
await flushPromises()
const toggle = wrapper.get('main button')
await toggle.trigger('click')
expect(wrapper.attributes('data-layout')).toBe('_preview')
expect(layout.selectedLayoutId.value).toBe('top')
expect(wrapper.find('.r-layout-footer-region').exists()).toBe(false)
draft.bottomRows = [['tabs']]
await nextTick()
expect(wrapper.get('.r-layout-footer-region nav').text()).toBe('Open pages')
await toggle.trigger('click')
expect(wrapper.attributes('data-layout')).toBe('top')
await toggle.trigger('click')
editing.value = false
await nextTick()
expect(wrapper.attributes('data-layout')).toBe('top')
expect(wrapper.get('main article').text()).toBe('Next page')
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it('moves the full navigation to the right without adding a second menu', async () => {
const pinia = createPinia() const pinia = createPinia()
setActivePinia(pinia) setActivePinia(pinia)
@ -82,12 +231,13 @@ it('moves the full navigation to the right without adding a second menu', () =>
const wrapper = shallowMount(Layout, { const wrapper = shallowMount(Layout, {
global: { global: {
renderStubDefaultSlot: true, renderStubDefaultSlot: true,
stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, stubs: liveShell,
plugins: [router, pinia], plugins: [router, pinia],
}, },
}) })
try { try {
await nextTick()
expect(wrapper.get('app-menu-stub').attributes('end')).toBe('true') expect(wrapper.get('app-menu-stub').attributes('end')).toBe('true')
expect(wrapper.find('top-navigation-stub').exists()).toBe(false) expect(wrapper.find('top-navigation-stub').exists()).toBe(false)
} finally { } finally {
@ -95,3 +245,327 @@ it('moves the full navigation to the right without adding a second menu', () =>
disposePinia(pinia) disposePinia(pinia)
} }
}) })
it('keeps the active and cached route instances when switching layout components', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const page = (name: string) =>
defineComponent({
name,
setup() {
const draft = ref('')
return () =>
h('input', {
'aria-label': name,
value: draft.value,
onInput: (event: Event) => {
draft.value = (event.target as HTMLInputElement).value
},
})
},
})
const applicationRouter = createRouter({
history: createMemoryHistory(),
routes: [
{
path: '/',
component: Layout,
children: [
{ path: 'first', name: 'FirstDraft', component: page('FirstDraft') },
{
path: 'second',
name: 'SecondDraft',
component: page('SecondDraft'),
},
],
},
],
})
await applicationRouter.push('/first')
const wrapper = mount(RouterView, {
attachTo: document.body,
global: {
plugins: [applicationRouter, pinia],
stubs: {
AppMenu: true,
LayoutHeader: true,
LayoutFooter: true,
LayoutTabs: true,
TopNavigation: true,
ContentLoading: true,
SettingDrawer: true,
LayoutHeaderActions: true,
},
},
})
try {
piniaKeepAliveStore().keepAliveInclude = ['FirstDraft', 'SecondDraft']
const layout = useLayout()
await flushPromises()
const first = wrapper.get('input')
const sharedMain = wrapper.get('[data-shared-layout-frame] main').element
const sharedOutlet = wrapper.get('main > .r-layout-outlet').element
await first.setValue('retained cache')
await applicationRouter.push('/second')
await nextTick()
const second = wrapper.get('input')
await second.setValue('active draft')
second.element.focus()
const scrollContainer = () =>
wrapper.get('.r-layout-content-scroll').element.parentElement!
scrollContainer().scrollTop = 450
expect(layout.updateLayout('custom-top')).toBe(true)
await nextTick()
expect(wrapper.get('[data-layout]').attributes('data-layout')).toBe(
'custom-top',
)
expect(wrapper.get('input').element).toBe(second.element)
await nextTick()
expect(wrapper.get('main').element).toBe(sharedMain)
expect(document.activeElement).toBe(second.element)
expect(scrollContainer().scrollTop).toBe(450)
expect((second.element as HTMLInputElement).value).toBe('active draft')
await applicationRouter.push('/first')
await nextTick()
expect(wrapper.get('input').element).toBe(first.element)
expect((first.element as HTMLInputElement).value).toBe('retained cache')
layout.registerLayout({
id: 'explicit-outlet',
label: 'Explicit outlet',
component: {
setup: () => () =>
h(LayoutFrame, null, { default: () => h(LayoutOutlet) }),
},
})
expect(layout.updateLayout('explicit-outlet')).toBe(true)
await flushPromises()
expect(wrapper.get('[data-shared-layout-frame] main').element).toBe(
sharedMain,
)
expect(wrapper.get('main > .r-layout-outlet').element).toBe(sharedOutlet)
const runtime = piniaRuntimeStore()
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
expect(layout.updateLayout('side')).toBe(true)
await nextTick()
expect(wrapper.get('input').element).toBe(first.element)
expect(runtime.layoutContentMaximize).toBe(true)
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
expect(runtime.layoutContentMaximize).toBe(false)
} finally {
wrapper.unmount()
applicationRouter.options.history.destroy()
disposePinia(pinia)
}
})
it.each([false, true])(
'keeps the public scroll target and focus on the active embedded outlet (maximized=%s)',
async (maximized) => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
layout.registerLayout({
id: 'wrapped-frame',
label: 'Wrapped frame',
component: {
render: () =>
h('section', { class: 'custom-frame' }, [h(LayoutOutlet)]),
},
})
const wrapper = mount(Layout, {
attachTo: document.body,
slots: { default: () => h('input', { 'aria-label': 'Draft' }) },
global: {
plugins: [router, pinia],
stubs: {
SettingDrawer: true,
LayoutHeader: true,
AppMenu: true,
LayoutTabs: true,
LayoutFooter: true,
ContentLoading: true,
},
},
})
const contentElement = () =>
(LAYOUT_CONTENT_REF.value as { $el?: HTMLElement } | null)?.$el
try {
await flushPromises()
const input = wrapper.get('input').element
const sharedContent = contentElement()
expect(sharedContent?.contains(input)).toBe(true)
piniaRuntimeStore().setRuntimeState('layoutContentMaximize', maximized)
await nextTick()
input.focus()
expect(layout.updateLayout('wrapped-frame')).toBe(true)
await flushPromises()
expect(contentElement()).toBe(
wrapper.get('.custom-frame .r-layout-full__viewer-content').element,
)
expect(contentElement()?.contains(input)).toBe(true)
expect(wrapper.get('[data-shared-layout-frame]').isVisible()).toBe(false)
expect(document.activeElement).toBe(input)
expect(layout.updateLayout('side')).toBe(true)
await flushPromises()
expect(contentElement()).toBe(sharedContent)
expect(contentElement()?.contains(input)).toBe(true)
expect(wrapper.get('[data-shared-layout-frame]').isVisible()).toBe(true)
expect(document.activeElement).toBe(input)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
},
)
it.each(['frame', 'outlet'])(
'keeps v-show on the real layout %s',
async (target) => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
const visible = ref(true)
layout.registerLayout({
id: 'conditional-frame',
label: 'Conditional frame',
component: {
render: () =>
target === 'frame'
? withDirectives(h(LayoutFrame), [[vShow, visible.value]])
: h(LayoutFrame, null, {
default: () =>
withDirectives(h(LayoutOutlet), [[vShow, visible.value]]),
}),
},
})
layout.updateLayout('conditional-frame')
const wrapper = mount(Layout, {
attachTo: document.body,
slots: { default: () => h('article', 'Page') },
global: { plugins: [router, pinia], stubs: { SettingDrawer: true } },
})
try {
await flushPromises()
const region = wrapper.get(
target === 'frame' ? '.r-layout-full' : 'main > .r-layout-outlet',
)
expect(region.isVisible()).toBe(true)
visible.value = false
await nextTick()
expect(region.attributes('style')).toContain('display: none')
expect(region.isVisible()).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
},
)
it('preserves the iframe document and its unsaved input across frame layouts', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: {
plugins: [router, pinia],
renderStubDefaultSlot: true,
stubs: { ...liveShell, CustomTopLayout: false },
},
slots: {
default: () => h('iframe', { title: 'Embedded form', srcdoc: '<input>' }),
},
})
try {
await flushPromises()
const frameDocument = wrapper.get('iframe').element.contentDocument!
const field = frameDocument.querySelector('input')!
field.value = 'unfinished draft'
const layout = useLayout()
for (const id of ['top', 'custom-top', 'mixed', 'split', 'right', 'side']) {
expect(layout.updateLayout(id)).toBe(true)
await flushPromises()
expect(wrapper.attributes('data-layout')).toBe(id)
const current = wrapper.get('iframe').element.contentDocument
expect(current).toBe(frameDocument)
expect(current?.querySelector('input')?.value).toBe('unfinished draft')
}
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it.each([0, 2])(
'restores the last valid layout after a renderer mounts %i outlets',
async (count) => {
const pinia = createPinia()
setActivePinia(pinia)
const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: {
plugins: [router, pinia],
renderStubDefaultSlot: true,
stubs: { ...liveShell, InvalidLayout: false },
},
slots: { default: () => h('input', { 'aria-label': 'Retained' }) },
})
const layout = useLayout()
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
await flushPromises()
const field = wrapper.get('input').element
layout.registerLayout({
id: 'invalid',
label: 'Invalid',
component: {
name: 'InvalidLayout',
render: () =>
h(
'div',
Array.from({ length: count }, () => h(LayoutOutlet)),
),
},
})
layout.updateLayout('invalid')
await nextTick()
await nextTick()
await nextTick()
expect(error).toHaveBeenCalledWith(
expect.stringContaining('"invalid"'),
expect.stringContaining('exactly one'),
)
expect(layout.selectedLayoutId.value).toBe('side')
expect(wrapper.get('input').element).toBe(field)
} finally {
error.mockRestore()
wrapper.unmount()
disposePinia(pinia)
}
},
)

View File

@ -133,17 +133,26 @@ describe('workspace preference shortcuts', () => {
.trigger('click') .trigger('click')
try { try {
const pillToggle = wrapper.get(
'[role="switch"][aria-label="preferences.appearance.menuTagRound"]',
)
expect(pillToggle.attributes('aria-checked')).toBe('false')
await pillToggle.trigger('click')
expect(store.menuTagRound).toBe(true)
await click('appearance.minimal') await click('appearance.minimal')
expect([ expect([
store.breadcrumbSwitch, store.breadcrumbSwitch,
store.menuTagSwitch, store.menuTagSwitch,
store.copyrightSwitch, store.copyrightSwitch,
]).toEqual([false, false, false]) ]).toEqual([false, false, false])
expect(store.menuTagRound).toBe(true)
await click('appearance.reset') await click('appearance.reset')
expect(store.contentTransition).toBe( expect(store.contentTransition).toBe(
getDefaultSettingConfig().contentTransition, getDefaultSettingConfig().contentTransition,
) )
expect(store.menuTagSwitch).toBe(getDefaultSettingConfig().menuTagSwitch) expect(store.menuTagSwitch).toBe(getDefaultSettingConfig().menuTagSwitch)
expect(store.menuTagRound).toBe(false)
expect(store.themeStyle).toBe(getDefaultSettingConfig().themeStyle) expect(store.themeStyle).toBe(getDefaultSettingConfig().themeStyle)
expect(store.primaryColorOverride).toEqual({}) expect(store.primaryColorOverride).toEqual({})
expect(store.appTheme).toBe('auto') expect(store.appTheme).toBe('auto')

View File

@ -6,9 +6,10 @@ import {
setupRouter, setupRouter,
} from '../../apps/admin/src/router' } from '../../apps/admin/src/router'
const { load, register } = vi.hoisted(() => ({ const { load, register, resetScroll } = vi.hoisted(() => ({
load: vi.fn(), load: vi.fn(),
register: vi.fn(), register: vi.fn(),
resetScroll: vi.fn(),
})) }))
vi.mock('../../apps/admin/src/router/config/source', () => ({ vi.mock('../../apps/admin/src/router/config/source', () => ({
@ -31,7 +32,7 @@ vi.mock('../../apps/admin/src/router/app-route-modules', () => ({
getStaticAppRoutes: () => [], getStaticAppRoutes: () => [],
})) }))
vi.mock('../../apps/admin/src/router/utils', () => ({ vi.mock('../../apps/admin/src/router/utils', () => ({
scrollViewToTop: vi.fn(), scrollViewToTop: resetScroll,
vueRouterRegister: register, vueRouterRegister: register,
})) }))
@ -53,6 +54,39 @@ it('loads no business routes before login, then shares a retry and registers gua
expect(register).toHaveBeenCalledOnce() expect(register).toHaveBeenCalledOnce()
} finally { } finally {
clearAccountRoutes() clearAccountRoutes()
router.options.history.destroy() }
})
afterAll(() => {
router.options.history.destroy()
})
it('resets workspace scroll after successful and repeated navigation', async () => {
const removeRoute = router.addRoute({
path: '/scroll-target',
component: { render: () => null },
})
const removeBlockedRoute = router.addRoute({
path: '/scroll-blocked',
component: { render: () => null },
beforeEnter: () => false,
})
try {
resetScroll.mockClear()
await router.push('/scroll-target')
expect(resetScroll).toHaveBeenCalledExactlyOnceWith(
router.currentRoute.value,
)
resetScroll.mockClear()
await router.push('/scroll-blocked')
expect(resetScroll).not.toHaveBeenCalled()
await router.push('/scroll-target')
expect(resetScroll).toHaveBeenCalledExactlyOnceWith(
router.currentRoute.value,
)
} finally {
removeBlockedRoute()
removeRoute()
} }
}) })

View File

@ -5,12 +5,7 @@
* *
* 如果可以操作 DOM,则返回 true,否则返回 false。 * 如果可以操作 DOM,则返回 true,否则返回 false。
*/ */
const canUseDom = () => { const canUseDom = () =>
return !!( typeof window !== 'undefined' && !!window.document?.documentElement
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
)
}
export default canUseDom export default canUseDom

View File

@ -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)
}

View File

@ -6,10 +6,6 @@
* 如果是浏览器环境,则返回 true,否则返回 false。 * 如果是浏览器环境,则返回 true,否则返回 false。
*/ */
const isBrowser = () => const isBrowser = () =>
!!( typeof window !== 'undefined' && !!window.document?.documentElement
typeof window !== 'undefined' &&
window.document &&
window.document.createElement
)
export default isBrowser export default isBrowser

View File

@ -1,5 +1,5 @@
import { setupI18n } from '../../apps/admin/src/locales' 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 { setupStore } from '../../apps/admin/src/store'
import { piniaSigningStore } from '../../apps/admin/src/store/modules/signing' import { piniaSigningStore } from '../../apps/admin/src/store/modules/signing'
import Login from '../../apps/admin/src/views/login' import Login from '../../apps/admin/src/views/login'
@ -26,6 +26,7 @@ const setupMiniApp = async (authenticated = false) => {
) )
await setupRouter(app, authenticated, Login) await setupRouter(app, authenticated, Login)
await router.isReady()
return { return {
app, app,

View File

@ -1,3 +1,5 @@
// @vitest-environment node
import { createHttpClient } from '@ray-template/http' import { createHttpClient } from '@ray-template/http'
import RequestCanceler from '@ray-template/http/RequestCanceler' import RequestCanceler from '@ray-template/http/RequestCanceler'
import type { AppRawRequestConfig } from '@ray-template/http/types' 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) 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 () => { it('isolates pending requests by client and leaves caller-owned signals intact', async () => {
const pending: Array<{ signal: unknown; finish: () => void }> = [] const pending: Array<{ signal: unknown; finish: () => void }> = []
const adapter: AxiosAdapter = (config) => const adapter: AxiosAdapter = (config) =>

View File

@ -0,0 +1,72 @@
// @vitest-environment node
import { spawnSync } from 'node:child_process'
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
let fixture: string
beforeEach(() => {
fixture = mkdtempSync(join(tmpdir(), 'ray-lint-fix-'))
writeFileSync(
join(fixture, 'eslint.config.mjs'),
"export default [{ rules: { 'no-var': 'error', 'no-undef': 'error' } }]\n",
)
})
afterEach(() => rmSync(fixture, { recursive: true, force: true }))
function run(script: string, ...args: string[]) {
const entry = fileURLToPath(
new URL(`../../scripts/${script}.mjs`, import.meta.url),
)
return spawnSync(process.execPath, [entry, ...args], {
cwd: fixture,
encoding: 'utf8',
})
}
it('limits explicit lint fixes to named files and defaults to the workspace', () => {
const selected = join(fixture, 'selected file.mjs')
const sibling = join(fixture, 'sibling.mjs')
writeFileSync(selected, 'var value=1\n')
writeFileSync(sibling, 'var value=1\n')
const scoped = run('lint-fix', '--', selected)
expect(scoped.status, scoped.stderr).toBe(0)
expect(readFileSync(selected, 'utf8')).toBe('let value=1\n')
expect(readFileSync(sibling, 'utf8')).toBe('var value=1\n')
const workspace = run('lint-fix')
expect(workspace.status, workspace.stderr).toBe(0)
expect(readFileSync(sibling, 'utf8')).toBe('let value=1\n')
})
it('formats the selected directory and reports remaining lint errors', () => {
const scope = join(fixture, 'module')
const source = join(scope, 'source.mjs')
const sibling = join(fixture, 'sibling.mjs')
mkdirSync(scope)
writeFileSync(source, 'var value=missing\n')
writeFileSync(sibling, 'var value=1\n')
const result = run('fix', 'module')
expect(result.status, result.stderr).toBe(1)
expect(result.stdout).toContain('no-undef')
expect(readFileSync(source, 'utf8')).toBe('let value = missing;\n')
expect(readFileSync(sibling, 'utf8')).toBe('var value=1\n')
})

View File

@ -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 = <Widget value={undefined} />',
'const element = <Widget value={void 0} />',
],
[
'vue',
'<script setup lang="ts">const value: undefined = undefined</script>',
'<script setup lang="ts">const value: undefined = void 0</script>',
],
[
'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)
})

View File

@ -109,7 +109,7 @@
--boot-line: light-dark(#efeff5, #343438); --boot-line: light-dark(#efeff5, #343438);
--boot-text: light-dark(#333639, #f0f0f0); --boot-text: light-dark(#333639, #f0f0f0);
--boot-muted: light-dark(#666970, #b5b5b8); --boot-muted: light-dark(#666970, #b5b5b8);
--boot-accent: light-dark(#18a058, #63e2b7); --boot-accent: light-dark(#137743, #63e2b7);
--boot-radius: 4px; --boot-radius: 4px;
--boot-shadow: none; --boot-shadow: none;
} }

View File

@ -2,7 +2,7 @@
"name": "@ray-template/admin", "name": "@ray-template/admin",
"private": true, "private": true,
"type": "module", "type": "module",
"version": "6.0.2", "version": "6.0.3",
"dependencies": { "dependencies": {
"@faker-js/faker": "10.6.0", "@faker-js/faker": "10.6.0",
"@logicflow/core": "2.2.5", "@logicflow/core": "2.2.5",

View File

@ -4,6 +4,11 @@ import { avatarProps, NAvatar } from 'naive-ui'
const center = 20 const center = 20
const fontSize = 26 const fontSize = 26
export const accountAvatarProps = {
...avatarProps,
color: String,
}
export const accountAvatarFont = { export const accountAvatarFont = {
fontWeight: 600, fontWeight: 600,
fontFamily: 'system-ui, sans-serif', fontFamily: 'system-ui, sans-serif',
@ -41,7 +46,7 @@ export function measureAccountText(text: string, size: number) {
export default defineComponent({ export default defineComponent({
name: 'AccountAvatar', name: 'AccountAvatar',
props: { props: {
...avatarProps, ...accountAvatarProps,
name: { type: String, default: '' }, name: { type: String, default: '' },
}, },
setup(props) { setup(props) {
@ -83,13 +88,13 @@ export default defineComponent({
} }
return () => { return () => {
const { name: _name, ...avatar } = props const { name: _name, color, ...avatar } = props
return ( return (
<NAvatar <NAvatar
{...avatar} {...avatar}
class="r-account-avatar" class="r-account-avatar"
style={avatar.color ? { backgroundColor: avatar.color } : void 0} style={color ? { backgroundColor: color } : void 0}
renderFallback={ renderFallback={
avatar.renderFallback ?? avatar.renderFallback ??
(avatar.fallbackSrc ? void 0 : renderInitial) (avatar.fallbackSrc ? void 0 : renderInitial)

View File

@ -1,9 +1,10 @@
import { useSigningGetters } from '@/store' import { useSigningGetters } from '@/store'
import { avatarProps, NButton, NFlex } from 'naive-ui' import { NButton, NFlex } from 'naive-ui'
import type { AvatarProps, FlexProps } from 'naive-ui' import type { AvatarProps, FlexProps } from 'naive-ui'
import type { PropType } from 'vue' import type { PropType } from 'vue'
import AccountAvatar, { import AccountAvatar, {
accountAvatarFont, accountAvatarFont,
accountAvatarProps,
accountInitial, accountInitial,
measureAccountText, measureAccountText,
} from './AccountAvatar' } from './AccountAvatar'
@ -13,7 +14,7 @@ const captionSize = 14
const AppAvatar = defineComponent({ const AppAvatar = defineComponent({
name: 'AppAvatar', name: 'AppAvatar',
props: { props: {
...avatarProps, ...accountAvatarProps,
round: { type: Boolean, default: true }, round: { type: Boolean, default: true },
objectFit: { objectFit: {
type: String as PropType<AvatarProps['objectFit']>, type: String as PropType<AvatarProps['objectFit']>,

View File

@ -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.

View File

@ -30,6 +30,7 @@ import type { RouteRecordRaw } from 'vue-router'
const examplePaths = new Set([ const examplePaths = new Set([
'/dashboard', '/dashboard',
'/tables', '/tables',
'/curd',
'/form', '/form',
'/modal-demo', '/modal-demo',
'/echart', '/echart',
@ -39,6 +40,7 @@ const examplePaths = new Set([
'/draggable-card', '/draggable-card',
'/svg-icons', '/svg-icons',
'/directive', '/directive',
'/layout-demo',
'/template-hooks', '/template-hooks',
'/web-hooks', '/web-hooks',
'/multi', '/multi',
@ -135,6 +137,22 @@ async function mountExample() {
if (params.get('theme') === 'dark') darkTheme() if (params.get('theme') === 'dark') darkTheme()
else lightTheme() else lightTheme()
if (window.parent !== window && document.referrer) {
const parentOrigin = new URL(document.referrer).origin
window.addEventListener('message', ({ origin, source, data }) => {
if (
origin !== parentOrigin ||
source !== window.parent ||
data?.type !== 'ray-template:example-theme'
)
return
if (data.theme === 'dark') darkTheme()
else if (data.theme === 'light') lightTheme()
})
}
setAppRouteModules(examples) setAppRouteModules(examples)
const routes = [ const routes = [

View File

@ -11,6 +11,7 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
| template | `useWatermark` | `/template-hooks`: text, show, hide, and toggle | [useWatermark](../../../../__test__/hooks/useWatermark.spec.ts) | | template | `useWatermark` | `/template-hooks`: text, show, hide, and toggle | [useWatermark](../../../../__test__/hooks/useWatermark.spec.ts) |
| template | `useAppNavigation` | `/template-hooks`: full paths, indexes, nested menus, and query | [useAppNavigation](../../../../__test__/hooks/useAppNavigation.spec.ts) | | template | `useAppNavigation` | `/template-hooks`: full paths, indexes, nested menus, and query | [useAppNavigation](../../../../__test__/hooks/useAppNavigation.spec.ts) |
| template | `useSiderBar` | `/template-hooks`: close tabs by path or close left/right/other/all tabs | [useSiderBar](../../../../__test__/hooks/useSiderBar.spec.ts) | | template | `useSiderBar` | `/template-hooks`: close tabs by path or close left/right/other/all tabs | [useSiderBar](../../../../__test__/hooks/useSiderBar.spec.ts) |
| components | `useMenu` | `/template-hooks`: bind an NMenu, change the selection, and reveal a nested option | [useMenu](../../../../__test__/hooks/useMenu.spec.tsx) |
| template | `useContentScroll` | `/template-hooks`: scroll content to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) | | template | `useContentScroll` | `/template-hooks`: scroll content to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) |
| template | `useSiderScroll` | `/template-hooks`: scroll sidebar to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) | | template | `useSiderScroll` | `/template-hooks`: scroll sidebar to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) |
| web | `useDevice` | `/web-hooks`: update breakpoint checks with window size | [useDevice](../../../../__test__/hooks/useDevice.spec.ts) | | web | `useDevice` | `/web-hooks`: update breakpoint checks with window size | [useDevice](../../../../__test__/hooks/useDevice.spec.ts) |
@ -34,12 +35,13 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
- Both scroll hooks can be created during setup and read the layout instance only when invoked. Missing sidebars or unmounted instances are safely ignored. - Both scroll hooks can be created during setup and read the layout instance only when invoked. Missing sidebars or unmounted instances are safely ignored.
- `useMaximize` acts on layout content and shares state across callers. `useElementFullscreen` acts on one arbitrary element and owns per-instance state. Neither calls the browser Fullscreen API. - `useMaximize` acts on layout content and shares state across callers. `useElementFullscreen` acts on one arbitrary element and owns per-instance state. Neither calls the browser Fullscreen API.
- `navigationTo` indexes start at 0. Negative, fractional, non-finite, or out-of-range indexes do not navigate. Full URLs support dynamic parameters, query, and hash; additional query parameters override matching URL parameters. Successful calls return the Router navigation Promise. - `navigationTo` indexes start at 0. Negative, fractional, non-finite, or out-of-range indexes do not navigate. Full URLs support dynamic parameters, query, and hash; additional query parameters override matching URL parameters. Successful calls return the Router navigation Promise.
- Bind `useMenu().menuRef` and `menuProps` to `NMenu`. Provide `value` or `expandedKeys` to keep that state in the hook. Omit an input to use the corresponding Naive UI defaults. Replace option arrays for shallow reactivity. The hook is available from `@/hooks` and `@ray-template/composables/useMenu`.
- `useDomToImage` return types follow the default format or the current `create(format)` call. Failures reject with Error. `finally` also runs when the target is missing, so its argument may be empty. The `created` callback receives results from runtime format overrides as well; its argument is a union of actual output types and must be narrowed first. - `useDomToImage` return types follow the default format or the current `create(format)` call. Failures reject with Error. `finally` also runs when the target is missing, so its argument may be empty. The `created` callback receives results from runtime format overrides as well; its argument is a union of actual output types and must be narrowed first.
- `useI18n('hooks').t('code')` and `.t('hooks.code')` address the same translation key. Switch application locales with `useSettingActions().updateLocale` to keep dates and component-library locales synchronized. - `useI18n('hooks').t('code')` and `.t('hooks.code')` address the same translation key. Switch application locales with `useSettingActions().updateLocale` to keep dates and component-library locales synchronized.
- Development HMR reuses the internationalization instance. Translation methods created before initialization read the current instance at invocation rather than permanently retaining the fallback that returns raw keys. - Development HMR reuses the internationalization instance. Translation methods created before initialization read the current instance at invocation rather than permanently retaining the fallback that returns raw keys.
- `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. - `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. - `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. - 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. 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.

View File

@ -1,2 +1,3 @@
export * from './useContextmenuCoordinate' export * from './useContextmenuCoordinate'
export * from './useMenu'
export * from './usePagination' export * from './usePagination'

View File

@ -0,0 +1 @@
export * from '@ray-template/composables/useMenu'

View File

@ -1,5 +1,13 @@
import { useSettingActions, useSettingGetters } from '@/store' import { useSettingActions, useSettingGetters } from '@/store'
import type { AppRootRoute } from '@/store/modules/setting/types' import type { AppRootRoute } from '@/store/modules/setting/types'
import type { ComputedRef } from 'vue'
export type UseAppRootReturnType = {
getRootRoute: ComputedRef<AppRootRoute>
getRootPath: ComputedRef<string>
getRootName: ComputedRef<string>
setRootRoute: (route: Partial<AppRootRoute>) => void
}
/** /**
* *
@ -9,7 +17,7 @@ import type { AppRootRoute } from '@/store/modules/setting/types'
* @returns 历史首页偏好的响应式引用和合并更新方法。 * @returns 历史首页偏好的响应式引用和合并更新方法。
* @deprecated 仅兼容旧设置;使用 Router 显式导航,空工作区统一为 /welcome。 * @deprecated 仅兼容旧设置;使用 Router 显式导航,空工作区统一为 /welcome。
*/ */
export function useAppRoot() { export function useAppRoot(): UseAppRootReturnType {
const { getAppRootRoute } = useSettingGetters() const { getAppRootRoute } = useSettingGetters()
const { updateSettingState } = useSettingActions() const { updateSettingState } = useSettingActions()
@ -38,5 +46,3 @@ export function useAppRoot() {
setRootRoute, setRootRoute,
} }
} }
export type UseAppRootReturnType = ReturnType<typeof useAppRoot>

View File

@ -1,8 +1,7 @@
import { i18n } from '@/locales' import { i18n } from '@/locales'
import type { I18n } from 'vue-i18n'
export interface OverrideUseI18nReturnType extends Partial< export interface OverrideUseI18nReturnType extends Partial<
Omit<I18n['global'], 't' | 'locale'> Omit<NonNullable<typeof i18n>['global'], 't' | 'locale'>
> { > {
t: <T extends string = string>(key: string, ...args: unknown[]) => T t: <T extends string = string>(key: string, ...args: unknown[]) => T
locale: (lang: string) => void locale: (lang: string) => void
@ -70,14 +69,7 @@ export const useI18n = (namespace?: string): OverrideUseI18nReturnType => {
if (!instance) return if (!instance) return
if (instance.mode === 'legacy') {
instance.global.locale = lang
} else if (isRef(instance.global.locale)) {
instance.global.locale.value = lang instance.global.locale.value = lang
} else {
instance.global.locale = lang
}
document.documentElement.lang = lang document.documentElement.lang = lang
} }

View File

@ -7,15 +7,23 @@ import { useVueRouter } from './useVueRouter'
export type CloseMenuTag = Key | MenuTagOptions export type CloseMenuTag = Key | MenuTagOptions
/** /**
*
* @returns 标签页检查与关闭方法;状态由共享菜单 Store 持有。
*/
export function useSiderBar() {
const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters()
const { router } = useVueRouter()
const { setMenuTagOptions, isMenuTagFixed } = useMenuActions()
const canClose = (tag: MenuTagOptions) => !isMenuTagFixed(tag)
/**
* *
* @param target 标签页对象、索引或路径 * @param target 标签页对象、索引或路径
* @param fn 用于日志的调用方方法名 * @param fn 用于日志的调用方方法名
* *
* @returns 当前标签列表中的对象和索引,找不到时返回 undefined。 * @returns 当前标签列表中的对象和索引,找不到时返回 undefined。
*/ */
const normalMenuTagOption = (target: CloseMenuTag, fn: string) => { const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
const { getMenuTagOptions } = useMenuGetters()
const tags = getMenuTagOptions.value const tags = getMenuTagOptions.value
const index = const index =
typeof target === 'number' typeof target === 'number'
@ -33,17 +41,42 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
} }
return { option: tags[index], index } return { option: tags[index], index }
} }
/** const closeTags = (
* candidates: MenuTagOptions[],
* @returns 标签页检查与关闭方法;状态由共享菜单 Store 持有。 destination?: string,
*/ replace = false,
export function useSiderBar() { ) => {
const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters() const closing = new Set(candidates.filter(canClose))
const { router } = useVueRouter() const commit = () => {
const { changeMenuModelValue, spliceMenTagOptions, setMenuTagOptions } = // 守卫等待期间,其他调用方可以打开、固定或替换标签;只移除本次选定且仍可关闭的项。
useMenuActions() 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
})
}
/** /**
* *
@ -64,14 +97,12 @@ export function useSiderBar() {
const checkCloseRight = (target: CloseMenuTag) => { const checkCloseRight = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'checkCloseRight') const normal = normalMenuTagOption(target, 'checkCloseRight')
if (normal) { return (
const { index } = normal !!normal &&
const length = getMenuTagOptions.value.length - 1 getMenuTagOptions.value.some(
(tag, index) => index > normal.index && canClose(tag),
return !(index >= length) )
} )
return false
} }
/** /**
@ -83,7 +114,12 @@ export function useSiderBar() {
const checkCloseLeft = (target: CloseMenuTag) => { const checkCloseLeft = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'checkCloseLeft') const normal = normalMenuTagOption(target, 'checkCloseLeft')
return !!normal && normal.index > 0 return (
!!normal &&
getMenuTagOptions.value.some(
(tag, index) => index < normal.index && canClose(tag),
)
)
} }
/** /**
@ -91,41 +127,48 @@ export function useSiderBar() {
* @param target 要关闭的标签对象、索引或路径 * @param target 要关闭的标签对象、索引或路径
* *
* @description * @description
* 所有业务标签都可关闭;关闭最后一项进入空工作区,其余激活项切换到相邻标签。 * 固定的标签会保留;关闭最后一项进入空工作区,关闭激活项时切换到相邻标签。
* *
* @returns 需要跳转时返回 Router 导航结果。 * @returns 需要跳转时返回 Router 导航结果。
*/ */
const close = (target: CloseMenuTag) => { const close = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'close') const normal = normalMenuTagOption(target, 'close')
if (normal) { if (normal && canClose(normal.option)) {
const { index, option } = normal const { index, option } = normal
const active = option.fullPath === getCurrentMenuOption.value?.fullPath const active = option.fullPath === getCurrentMenuOption.value?.fullPath
spliceMenTagOptions(index) const tags = getMenuTagOptions.value
if (!getMenuTagOptions.value.length) if (tags.length === 1)
return router.replace(WELCOME_ROUTE_PATH) return closeTags([option], WELCOME_ROUTE_PATH, true)
if (active) { return closeTags(
const tag = getMenuTagOptions.value[Math.max(0, index - 1)] [option],
active ? (tags[index - 1] ?? tags[index + 1]).fullPath : void 0,
return tag && changeMenuModelValue(tag.fullPath, tag) )
}
} }
} }
/** /**
* *
* @description * @description
* 清空所有业务标签及其缓存,然后进入空工作区;不依赖任何业务首页。 * 关闭未固定的标签;优先保留当前页面,再尝试第一个固定标签或空工作区。
* *
* @returns Router 导航结果。 * @returns Router 导航结果。
*/ */
const closeAll = () => { const closeAll = () => {
setMenuTagOptions([], false) const current = getCurrentMenuOption.value?.fullPath
const tags = getMenuTagOptions.value
const fixed = tags.filter(isMenuTagFixed)
return router.replace(WELCOME_ROUTE_PATH) return closeTags(
tags,
fixed.some((tag) => tag.fullPath === current)
? void 0
: (fixed[0]?.fullPath ?? WELCOME_ROUTE_PATH),
true,
)
} }
const closeForbiddenPage = () => { const closeForbiddenPage = () => {
@ -148,20 +191,22 @@ export function useSiderBar() {
* @param target 要保留的边界标签对象、索引或路径 * @param target 要保留的边界标签对象、索引或路径
* *
* @description * @description
* 关闭右侧标签;激活项被移除时切换到边界标签。 * 关闭右侧未固定的标签;激活项被移除时切换到边界标签。
*/ */
const closeRight = (target: CloseMenuTag) => { const closeRight = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'closeRight') const normal = normalMenuTagOption(target, 'closeRight')
if (normal) { if (normal) {
const { option, index } = normal const { option, index } = normal
const spliceLength = getMenuTagOptions.value.length - index // 待删除长度
const currentIndex = getCurrentTagIndex() const currentIndex = getCurrentTagIndex()
const current = getMenuTagOptions.value[currentIndex]
spliceMenTagOptions(index + 1, spliceLength) return closeTags(
getMenuTagOptions.value.slice(index + 1),
if (currentIndex > index) current && currentIndex > index && canClose(current)
return changeMenuModelValue(option.fullPath, option) ? option.fullPath
: void 0,
)
} }
} }
@ -170,7 +215,7 @@ export function useSiderBar() {
* @param target 要保留的边界标签对象、索引或路径 * @param target 要保留的边界标签对象、索引或路径
* *
* @description * @description
* 关闭左侧标签;激活项被移除时切换到边界标签。 * 关闭左侧未固定的标签;激活项被移除时切换到边界标签。
*/ */
const closeLeft = (target: CloseMenuTag) => { const closeLeft = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'closeLeft') const normal = normalMenuTagOption(target, 'closeLeft')
@ -178,11 +223,14 @@ export function useSiderBar() {
if (normal) { if (normal) {
const { option, index } = normal const { option, index } = normal
const currentIndex = getCurrentTagIndex() const currentIndex = getCurrentTagIndex()
const current = getMenuTagOptions.value[currentIndex]
spliceMenTagOptions(0, index) return closeTags(
getMenuTagOptions.value.slice(0, index),
if (currentIndex >= 0 && currentIndex < index) current && currentIndex < index && canClose(current)
return changeMenuModelValue(option.fullPath, option) ? option.fullPath
: void 0,
)
} }
} }
@ -191,7 +239,7 @@ export function useSiderBar() {
* @param target 要保留的标签对象、索引或路径 * @param target 要保留的标签对象、索引或路径
* *
* @description * @description
* 仅保留并激活目标标签;目标无效时不操作。 * 保留目标与所有固定标签,并激活目标。
*/ */
const closeOther = (target: CloseMenuTag) => { const closeOther = (target: CloseMenuTag) => {
const normal = normalMenuTagOption(target, 'closeOther') const normal = normalMenuTagOption(target, 'closeOther')
@ -199,10 +247,12 @@ export function useSiderBar() {
if (normal) { if (normal) {
const { option } = normal const { option } = normal
setMenuTagOptions(option, false) return closeTags(
getMenuTagOptions.value.filter((tag) => tag !== option),
if (getCurrentMenuOption.value?.fullPath !== option.fullPath) getCurrentMenuOption.value?.fullPath === option.fullPath
return changeMenuModelValue(option.fullPath, option) ? void 0
: option.fullPath,
)
} }
} }

View File

@ -18,6 +18,22 @@
Interactions draw on [Vben layout preferences](https://doc.vben.pro/en/guide/essentials/settings.html), reusing existing Naive UI components without a second layout framework. Interactions draw on [Vben layout preferences](https://doc.vben.pro/en/guide/essentials/settings.html), reusing existing Naive UI components without a second layout framework.
## Layout definitions and the designer
The authenticated workspace loads `useLayout` from `@/layout/api`. Each Pinia instance owns its registry. Put a default-exported `LayoutDefinition` in `apps/admin/src/layout/definitions/<id>.layout.tsx` (JS, JSX and TS entries are also supported). Use a stable lowercase kebab-case ID. Definitions can contain their renderer or import it from a sibling module. The five built-in definitions share navigation and frame components. The `custom-top` example composes tabs and header actions in one row above top navigation.
Use `registerLayout(definition)` for an explicitly installed module and `updateLayout(id)` to select a registered layout. Both `autoRegister` and `selectable` default to true. A definition with `autoRegister: false` requires explicit registration. The picker and programmatic selection respect `selectable`. The saved custom ID and the built-in fallback mode serve desktop restoration and v1 preference-file portability respectively. Updating only spacing or width preserves the selected definition.
Provide an optional `preview` to describe the settings thumbnail. For example, `{ rows: [['breadcrumb', 'actions']], bottomRows: [['tabs']], sidebar: 'right', footer: true }` places the breadcrumb and actions above the content and tabs below it. Rows also support `navigation`. Use `sidebar` to place navigation on the left or right, or set it to `none`. Set `wideHeaderRows` to the number of leading rows that span both the content and the sidebar. A definition without preview metadata uses its built-in fallback thumbnail. The designer generates this metadata from the same arrangement as its TSX renderer.
Compose renderers with `LayoutFrame`, `LayoutRow`, `LayoutTabs`, `LayoutHeaderActions`, `LayoutBreadcrumb`, `LayoutTopNavigation` and `LayoutFooter` from `@/layout/blocks`. A frame provides the page outlet by default. When composing your own content region, render exactly one `LayoutOutlet`. The application host keeps routed pages and their cache mounted as presentation changes. The compact breakpoint uses the full-menu drawer.
Built-in and generated layouts declare `sharedFrame: true` because their root is always a direct `LayoutFrame` with its standard page outlet. Omit this flag for layouts with an outer DOM wrapper, local providers or a custom content region. A frame or outlet with a template ref, directive, transition or scoped root style also needs its own DOM node. Browsers with state-preserving DOM moves can transfer an active iframe to a different outlet immediately. On other browsers the host keeps the visible layout and its iframe until the embedded content closes or the page reloads, then applies the most recent selection. An ordinary route change can release the iframe. Layouts sharing the existing frame can switch immediately. An encapsulated web component with a closed shadow root can mark its host with `data-layout-preserve-embed` while its embedded document is active.
The lab generates a TSX definition from rows above and below the routed page, sidebar placement and an optional footer. The frame's `bottom` slot hosts rows below the page regardless of copyright visibility. Desktop users can try the draft around the current page and keep editing. Ending the preview or leaving the lab restores the selected layout.
Opening the lab as a top-level page on the loopback Vite development server enables create-only writes to the definitions directory. Production, remote and embedded previews download the same source. The writer validates a declarative draft and generates the source on the server. Discovery imports matching modules before applying registration flags, so review external TSX as executable project source before placing it in this directory. Changes to deployed layout definitions take effect in the next build.
## Configuration and extension ## Configuration and extension
```tsx ```tsx
@ -34,7 +50,7 @@ updateSettingState('layoutConfig', {
Configuration belongs to the `setting` store and retains its persistence key. Historical caches receive defaults and normalized ranges without clearing user preferences. `src/store/modules/setting/constant.ts` owns defaults. Restoring the default layout resets only `layoutConfig`. Configuration belongs to the `setting` store and retains its persistence key. Historical caches receive defaults and normalized ranges without clearing user preferences. `src/store/modules/setting/constant.ts` owns defaults. Restoring the default layout resets only `layoutConfig`.
The settings drawer keeps its five layout previews in one row, scrolling horizontally if needed. Bottom controls export layout, appearance, menu, watermark, and general preferences as `ray-template-preferences.json`, or import the same format. Files must pass version/field validation before applying in the current browser; no reload is required. Login, lock-screen, route configuration, and page-cache data are excluded. The settings drawer lists the registered layouts and marks unavailable choices as disabled. Bottom controls export layout, appearance, menu, watermark, and general preferences as `ray-template-preferences.json`, or import the same format. Files must pass version/field validation before applying in the current browser; no reload is required. Login, lock-screen, route configuration, and page-cache data are excluded.
Use named slots to replace regions: Use named slots to replace regions:
@ -56,4 +72,4 @@ Layout scroll references remain `LAYOUT_CONTENT_REF` for content and `LAYOUT_SID
## Style ownership ## Style ownership
`index.scss` owns the shell, content scrolling, and maximization. Top navigation, menus, tabs, and loading-state styles stay with their components. The settings drawer and layout lab share `LayoutSettings` and `LayoutSettings.scss`. Thumbnails within square option cards indicate navigation placement; text below explains menu behavior. Card groups reserve space for keyboard focus outlines, and `aria-pressed` represents selection. `index.scss` owns the shell, content scrolling, and maximization. Top navigation, menus, tabs, and loading-state styles stay with their components. The settings drawer and layout lab share `LayoutSettings` and `LayoutSettings.scss`. Responsive option cards show the registered layout structure. Long names wrap and expand the card height. Card groups reserve space for keyboard focus outlines, and `aria-pressed` represents selection.

View File

@ -0,0 +1,3 @@
export { useLayout } from './useLayout'
export type { LayoutDefinition } from './types'
export * from './blocks'

View File

@ -0,0 +1,11 @@
import { useSettingGetters } from '@/store'
import Breadcrumb from '../components/SiderBar/components/Breadcrumb'
export default defineComponent({
name: 'LayoutBreadcrumb',
setup() {
const { getBreadcrumbSwitch } = useSettingGetters()
return () => getBreadcrumbSwitch.value && <Breadcrumb />
},
})

View File

@ -0,0 +1,11 @@
import { useSettingGetters } from '@/store'
import FooterWrapper from '../default/FooterWrapper'
export default defineComponent({
name: 'LayoutFooter',
setup() {
const { getCopyrightSwitch } = useSettingGetters()
return () => getCopyrightSwitch.value && <FooterWrapper />
},
})

View File

@ -0,0 +1,155 @@
import { LAYOUT_CONTENT_REF } from '@/app-config'
import { useI18n, useMaximize } from '@/hooks'
import { useRuntimeGetters, useSettingGetters } from '@/store'
import { AdminShell } from '@ray-template/admin-shell'
import type { PropType, VNode } from 'vue'
import ContentLoading from '../default/ContentWrapper/ContentLoading'
import { layoutFrameKey, layoutHostKey } from '../host-context'
import LayoutPresentation from '../renderers/LayoutPresentation'
import LayoutOutlet from './LayoutOutlet'
import OutletTarget from './OutletTarget'
// ref、指令、过渡与作用域样式依赖原节点上的 DOM 绑定。
function hasDomBindings(node: VNode) {
return !!(node.ref || node.dirs || node.transition || node.scopeId)
}
export default defineComponent({
name: 'LayoutFrame',
inheritAttrs: false,
props: {
sidebarPlacement: {
type: String as PropType<'left' | 'right'>,
default: 'left',
},
wideHeader: Boolean,
embedded: Boolean,
},
setup(props, { attrs, slots }) {
const instance = getCurrentInstance()!
const ancestor = instance.parent
// 渲染器的局部 provide 应继续由原组件树传递。
const inheritsHostProviders =
!!ancestor &&
'provides' in ancestor &&
!!ancestor.provides &&
typeof ancestor.provides === 'object' &&
Object.hasOwn(ancestor.provides, layoutHostKey)
provide(layoutFrameKey, true)
const { getLayoutConfig, getMenuTagSwitch, getCopyrightSwitch } =
useSettingGetters()
const {
globalMainLayoutLoad,
layoutContentSpinning,
layoutContentMaximize,
layoutContentMaximizeStyle,
} = useRuntimeGetters()
const host = inject(layoutHostKey)
const { maximize } = useMaximize()
const { t } = useI18n('layout')
const marker = useTemplateRef<HTMLElement>('marker')
const inline = ref(false)
const sharedVNode = shallowRef<VNode>()
const sharedRenderer = () => sharedVNode.value!
const release = () => {
if (host?.sharedFrame.value === sharedRenderer)
host.sharedFrame.value = void 0
}
const placeFrame = () => {
const element = marker.value
if (!host || !element) {
release()
return
}
// Fragment 可能有多个顶层区域;只有单一根节点可提升,避免吞掉兄弟出口。
let owner = ancestor
while (owner && owner.type !== LayoutPresentation) owner = owner.parent
if (
element.parentElement === host.frameRoot.value &&
owner?.subTree.el === element &&
(!host.sharedFrame.value || host.sharedFrame.value === sharedRenderer)
)
host.sharedFrame.value = sharedRenderer
else {
inline.value = true
release()
}
}
onMounted(placeFrame)
onUpdated(placeFrame)
onBeforeUnmount(release)
const renderShell = (content: (() => VNode | VNode[]) | undefined) => {
const overrides = host?.slots
const footer =
slots.footer && getCopyrightSwitch.value
? (overrides?.footer ?? slots.footer)
: void 0
return (
<AdminShell
{...attrs}
class={[attrs.class, props.embedded && 'r-layout-embedded']}
layout={getLayoutConfig.value}
sidebarPlacement={slots.sidebar ? props.sidebarPlacement : 'none'}
wideHeader={props.wideHeader}
showTabs={!!slots.tabs && getMenuTagSwitch.value}
showFooter={!!slots.bottom || !!footer}
busy={
!overrides?.default &&
(!globalMainLayoutLoad.value || layoutContentSpinning.value)
}
maximized={layoutContentMaximize.value}
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restoreOnUnmount={false}
restore={() => maximize(false)}
skipContentLabel={t('skipToContent')}
restoreLabel={t('restore')}
>
{{
header: overrides?.header ?? slots.header,
sidebar: overrides?.sidebar ?? slots.sidebar,
tabs: overrides?.tabs ?? slots.tabs,
footer: () => [slots.bottom?.(), footer?.()],
default: content ?? (() => <OutletTarget />),
loading: overrides?.default ? void 0 : () => <ContentLoading />,
}}
</AdminShell>
)
}
return () => {
if (
!host ||
props.embedded ||
inline.value ||
!inheritsHostProviders ||
hasDomBindings(instance.vnode)
)
return renderShell(slots.default)
const children = slots.default?.()
const child = children?.length === 1 ? children[0] : void 0
if (
children &&
(child?.type !== LayoutOutlet || child.props || hasDomBindings(child))
)
return renderShell(() => children)
// 只有宿主的直接子节点能复用滚动容器;带原生外层的布局保留自身位置。
sharedVNode.value = renderShell(void 0)
return <span ref="marker" hidden aria-hidden="true" />
}
},
})

View File

@ -0,0 +1,26 @@
import { useElementSize } from '@vueuse/core'
import { layoutFrameKey } from '../host-context'
import LayoutFrame from './LayoutFrame'
import OutletTarget from './OutletTarget'
export default defineComponent({
name: 'LayoutOutlet',
setup() {
if (inject(layoutFrameKey, false)) return () => <OutletTarget />
const frame = useTemplateRef<InstanceType<typeof LayoutFrame>>('frame')
const { height } = useElementSize(frame)
return () => (
<LayoutFrame
ref="frame"
embedded
style={
height.value
? { '--layout-content-height': `${height.value}px` }
: void 0
}
/>
)
},
})

View File

@ -0,0 +1,6 @@
export default defineComponent({
name: 'LayoutRow',
setup(_, { slots }) {
return () => <div class="r-layout-row">{slots.default?.()}</div>
},
})

View File

@ -0,0 +1,13 @@
import { useSettingGetters } from '@/store'
import MenuTag from '../components/MenuTag'
import { layoutHostKey } from '../host-context'
export default defineComponent({
name: 'LayoutTabs',
setup() {
const { getMenuTagSwitch } = useSettingGetters()
const host = inject(layoutHostKey)
return () => getMenuTagSwitch.value && (host?.slots.tabs?.() ?? <MenuTag />)
},
})

View File

@ -0,0 +1,18 @@
import { layoutHostKey } from '../host-context'
export default defineComponent({
name: 'LayoutOutletTarget',
setup() {
const host = inject(layoutHostKey)
if (!host)
throw new Error('LayoutOutlet requires the application layout host.')
const element = useTemplateRef<HTMLDivElement>('element')
onMounted(() => host.addOutlet(element.value!))
onBeforeUnmount(() => host.removeOutlet(element.value!))
return () => <div ref="element" class="r-layout-outlet" />
},
})

View File

@ -0,0 +1,65 @@
import { AdminShell } from '@ray-template/admin-shell'
import type { LayoutConfig } from '@ray-template/admin-shell'
import { cloneVNode } from 'vue'
import type { PropType } from 'vue'
import { layoutFrameKey, layoutHostKey } from '../host-context'
import OutletTarget from './OutletTarget'
export default defineComponent({
name: 'SharedFrame',
props: {
onFailure: {
type: Function as PropType<(error: unknown) => void>,
required: true,
},
},
setup(props) {
const host = inject(layoutHostKey)!
provide(layoutFrameKey, true)
let lastLayout: LayoutConfig | undefined
let mountedRenderer: typeof host.sharedFrame.value
const markReady = () => {
mountedRenderer = host.sharedFrame.value
}
onMounted(markReady)
onUpdated(markReady)
onErrorCaptured((error) => {
if (!host.sharedFrame.value || mountedRenderer === host.sharedFrame.value)
return
props.onFailure(error)
return false
})
return () => {
const render = host.sharedFrame.value
if (render) {
const frame = render()
lastLayout = frame.props!.layout as LayoutConfig
return cloneVNode(frame, { 'data-shared-layout-frame': '' })
}
if (!lastLayout) return null
// 验证候选布局期间保留同一内容节点,回退时 iframe 的浏览上下文仍在。
return h(
AdminShell,
{
layout: lastLayout,
'data-shared-layout-frame': '',
style: { display: 'none' },
inert: true,
sidebarPlacement: 'none',
restoreOnUnmount: false,
},
{ default: () => <OutletTarget /> },
)
}
},
})

View File

@ -0,0 +1,88 @@
.r-layout-host {
position: fixed;
inset: 0;
display: grid;
grid-template: minmax(0, 1fr) / minmax(0, 1fr);
}
.r-layout-outlet {
display: contents;
}
.r-layout-switch-notice {
position: fixed;
z-index: 4;
inset-inline: 1rem;
inset-block-end: 1rem;
width: fit-content;
max-width: calc(100% - 2rem);
margin: 0 auto;
padding: 8px 14px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface);
color: var(--r-text);
box-shadow: var(--r-shadow-soft);
pointer-events: none;
}
.r-layout-embedded.r-layout-full {
position: relative;
inset: auto;
block-size: 100%;
min-block-size: 0;
}
.r-layout-row {
display: flex;
align-items: center;
min-inline-size: 0;
padding-inline: $layoutRouterViewContainer;
background: var(--r-surface);
color: var(--r-text);
> * {
flex: 1 1 0;
min-inline-size: 0;
}
> .layout-header__actions {
flex: none;
margin-inline-start: auto;
}
> .menu-tag {
--ray-shell-tab-gutter: 0px;
border: 0;
}
&:has(> *) {
min-block-size: $layoutHeaderHeight;
}
}
:is(.r-layout-header-region, .r-layout-footer-region, .r-layout-row)
> .r-layout-top-navigation,
.r-layout-footer-region > .menu-tag {
border-block-end: 0;
}
.r-layout-header-region:has(
> :is(.layout-header, .r-layout-top-navigation),
> .r-layout-row > *
):not(
:has(
+ .r-layout-tabs-region > *,
+ .r-layout-full__body .r-layout-tabs-region > *
)
) {
border-block-end: 1px solid var(--r-line);
}
.r-layout-footer-region:has(
> .r-layout-row > *,
> .menu-tag,
> .r-layout-top-navigation
) {
border-block-start: 1px solid var(--r-line);
}

View File

@ -0,0 +1,13 @@
import './index.scss'
export { default as LayoutFrame } from './LayoutFrame'
export { default as LayoutOutlet } from './LayoutOutlet'
export { default as LayoutHeader } from '../components/SiderBar'
export { default as LayoutHeaderActions } from '../components/SiderBar/HeaderActions'
export { default as LayoutBreadcrumb } from './LayoutBreadcrumb'
export { default as LayoutTopNavigation } from '../components/TopNavigation'
export { default as LayoutNavigation } from '../components/Menu'
export { default as LayoutTabs } from './LayoutTabs'
export { default as LayoutFooter } from './LayoutFooter'
export { default as LayoutRow } from './LayoutRow'

View File

@ -1,23 +1,59 @@
import { useI18n } from '@/hooks' import { useI18n } from '@/hooks'
import { useSettingActions, useSettingGetters } from '@/store' import { useSettingActions, useSettingGetters } from '@/store'
import { getDefaultSettingConfig } from '@/store/modules/setting/constant' import { getDefaultSettingConfig } from '@/store/modules/setting/constant'
import { LayoutSettings } from '@ray-template/admin-shell' import { LAYOUT_MODES, LayoutSettings } from '@ray-template/admin-shell'
import { layoutHostKey } from '../host-context'
import { useLayout } from '../useLayout'
export default defineComponent({ export default defineComponent({
name: 'LayoutSettings', name: 'LayoutSettings',
props: { showDescription: Boolean }, props: { showDescription: Boolean },
setup(props) { setup(props) {
const { t } = useI18n('layout') const { t } = useI18n('layout')
const { getLayoutConfig } = useSettingGetters() const { layouts, activeLayoutId, updateLayout } = useLayout()
const { getLayoutConfig, getLocaleLanguage } = useSettingGetters()
const { updateSettingState } = useSettingActions() const { updateSettingState } = useSettingActions()
const host = inject(layoutHostKey, null)
return () => ( return () => (
<LayoutSettings <LayoutSettings
showDescription={props.showDescription} showDescription={props.showDescription}
selectionNotice={
host?.deferredFromId.value ? t('deferredForEmbed') : void 0
}
selectedId={
host?.deferredFromId.value ??
(host?.draftRenderer.value ? '' : activeLayoutId.value)
}
onSelect={(id) => {
if (updateLayout(id) && host) host.draftRenderer.value = void 0
}}
choices={layouts.value.map((definition) => {
const mode = LAYOUT_MODES.find((id) => id === definition.id)
const label =
typeof definition.label === 'string'
? definition.label
: definition.label[
getLocaleLanguage.value === 'zh-CN' ? 'zh-CN' : 'en-US'
]
return {
id: definition.id,
label,
preview:
definition.preview ?? mode ?? definition.fallbackMode ?? 'side',
disabled: definition.selectable === false,
hint: mode ? t(`modeHint.${mode}`) : void 0,
}
})}
layout={getLayoutConfig.value} layout={getLayoutConfig.value}
defaults={getDefaultSettingConfig().layoutConfig} defaults={getDefaultSettingConfig().layoutConfig}
translate={t} translate={t}
update={(value) => updateSettingState('layoutConfig', value)} update={(value) => {
updateSettingState('layoutConfig', value)
if (value.mode && host) host.draftRenderer.value = void 0
}}
/> />
) )
}, },

View File

@ -28,8 +28,6 @@
.r-menu__logo { .r-menu__logo {
color: inherit; color: inherit;
border-block-end: 1px solid var(--r-line);
border-block-end-color: color-mix(in srgb, currentColor 15%, transparent);
} }
.n-menu-item-content { .n-menu-item-content {
@ -78,7 +76,6 @@
flex: 1; flex: 1;
min-inline-size: 0; min-inline-size: 0;
padding-inline: 16px 8px; padding-inline: 16px 8px;
border-block-end: 0;
} }
.app-menu__close { .app-menu__close {

View File

@ -11,12 +11,14 @@ import {
} from '@/store' } from '@/store'
import type { AppMenuOption, NaiveMenuOptions } from '@/types' import type { AppMenuOption, NaiveMenuOptions } from '@/types'
import { useMenuKeyboard } from '@ray-template/admin-shell' import { useMenuKeyboard } from '@ray-template/admin-shell'
import { useMenu } from '@ray-template/composables/useMenu'
import { RIcon } from '@ray-template/ui/icon' import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDrawer, NLayoutContent, NLayoutSider, NMenu } from 'naive-ui' import { NButton, NDrawer, NLayoutContent, NLayoutSider, NMenu } from 'naive-ui'
import type { MenuInst } from 'naive-ui'
import type { PropType } from 'vue' import type { PropType } from 'vue'
import SiderBarLogo from './components/SiderBarLogo' import SiderBarLogo from './components/SiderBarLogo'
const triggerStyle = { top: 'max(24px, calc(50% - 240px))' }
export default defineComponent({ export default defineComponent({
name: 'AppMenu', name: 'AppMenu',
props: { props: {
@ -26,12 +28,12 @@ export default defineComponent({
inert: Boolean, inert: Boolean,
}, },
setup(props) { setup(props) {
const menuRef = shallowRef<MenuInst | null>(null) const { menuRef, showOption } = useMenu()
const { changeMenuModelValue, collapsedMenu } = useMenuActions() const { changeMenuModelValue, collapsedMenu } = useMenuActions()
const { t } = useI18n('layout') const { t } = useI18n('layout')
const { getAppTheme, getMenuConfig } = useSettingGetters() const { getAppTheme, getMenuConfig } = useSettingGetters()
const { getMenuOptions, getCollapsed, getMenuKey } = useMenuGetters() const { getMenuOptions, getCollapsed, getMenuKey } = useMenuGetters()
const { globalDrawerValue } = useRuntimeGetters() const { globalDrawerValue, layoutContentMaximize } = useRuntimeGetters()
const { setRuntimeState } = useRuntimeActions() const { setRuntimeState } = useRuntimeActions()
const { isTabletOrSmaller, width } = useDevice({ const { isTabletOrSmaller, width } = useDevice({
observer: (isSmaller) => { observer: (isSmaller) => {
@ -54,8 +56,7 @@ export default defineComponent({
async () => { async () => {
await nextTick() await nextTick()
if (getMenuKey.value != null) if (getMenuKey.value != null) showOption(String(getMenuKey.value))
menuRef.value?.showOption(String(getMenuKey.value))
positionSelectedMenuItem() positionSelectedMenuItem()
}, },
@ -70,8 +71,10 @@ export default defineComponent({
const basicMenu = () => ( const basicMenu = () => (
<NLayoutSider <NLayoutSider
class={['app-menu__sider', { 'app-menu__sider--end': props.end }]} class={['app-menu__sider', { 'app-menu__sider--end': props.end }]}
{...{ inert: props.inert }} {...{ inert: props.inert || layoutContentMaximize.value }}
showTrigger={!isTabletOrSmaller.value} showTrigger={!isTabletOrSmaller.value}
triggerStyle={triggerStyle}
collapsedTriggerStyle={triggerStyle}
collapseMode={getMenuConfig.value.collapsedMode} collapseMode={getMenuConfig.value.collapsedMode}
collapsedWidth={getMenuConfig.value.collapsedWidth} collapsedWidth={getMenuConfig.value.collapsedWidth}
onUpdateCollapsed={collapsedMenu} onUpdateCollapsed={collapsedMenu}

View File

@ -4,3 +4,83 @@
border: 1px solid var(--r-line); border: 1px solid var(--r-line);
border-radius: var(--r-radius); border-radius: var(--r-radius);
} }
.menu-tag-wrapper {
position: relative;
padding-inline: 4px;
}
.menu-tag-wrapper[data-menu-tag-sortable] .menu-tag__item {
-webkit-touch-callout: none;
-webkit-user-select: none;
user-select: none;
}
.menu-tag__top-icon {
rotate: 180deg;
}
.menu-tag-wrapper--dragging,
.menu-tag-wrapper--dragging :is(.menu-tag__item:hover, .menu-tag__tab) {
cursor: grabbing;
}
.menu-tag__item[data-menu-tag-dragged] {
opacity: 0.55;
}
.menu-tag__item.menu-tag__drag-preview {
position: fixed;
inset: 0 auto auto 0;
z-index: 4;
background-color: var(--r-surface);
background-image: linear-gradient(var(--n-color), var(--n-color));
box-shadow: var(--r-shadow-soft);
pointer-events: none;
transition: none;
}
.menu-tag__item[data-menu-tag-drop]::after {
position: absolute;
inset-block: 0;
z-index: 5;
inline-size: 2px;
border-radius: var(--r-control-radius);
background: var(--r-theme-primary-color);
pointer-events: none;
content: '';
}
.menu-tag__item[data-menu-tag-drop='before']::after {
inset-inline-start: -4px;
}
.menu-tag__item[data-menu-tag-drop='after']::after {
inset-inline-end: -4px;
}
.menu-tag-move {
transition: transform 150ms var(--r-bezier);
}
.menu-tag__status {
position: absolute;
inline-size: 1px;
block-size: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
@media (forced-colors: active) {
.menu-tag__item[data-menu-tag-drop]::after {
background: Highlight;
forced-color-adjust: none;
}
}
@media (prefers-reduced-motion: reduce) {
.menu-tag-move {
transition: none;
}
}

View File

@ -1,15 +1,25 @@
import './index.scss' import './index.scss'
import { useI18n, useMaximize, useSiderBar, useSpinning } from '@/hooks' import { useI18n, useMaximize, useSiderBar, useSpinning } from '@/hooks'
import { FORBIDDEN_ROUTE_PATH } from '@/router/constant' import { FORBIDDEN_ROUTE_PATH } from '@/router/constant'
import { useMenuActions, useMenuGetters, useRuntimeGetters } from '@/store' import {
useMenuActions,
useMenuGetters,
useRuntimeGetters,
useSettingGetters,
} from '@/store'
import type { AppMenuOption, MenuTagOptions } from '@/types' import type { AppMenuOption, MenuTagOptions } from '@/types'
import { ShellTab } from '@ray-template/admin-shell' import { ShellTab } from '@ray-template/admin-shell'
import { RIcon } from '@ray-template/ui/icon' import { RIcon } from '@ray-template/ui/icon'
import { RMoreDropdown } from '@ray-template/ui/more-dropdown' import { RMoreDropdown } from '@ray-template/ui/more-dropdown'
import { usePreferredReducedMotion, useResizeObserver } from '@vueuse/core' import {
import { NDropdown, NFlex, NLayoutHeader, NScrollbar } from 'naive-ui' usePreferredReducedMotion,
useResizeObserver,
useTimeoutFn,
} from '@vueuse/core'
import { NDropdown, NFlex, NScrollbar } from 'naive-ui'
import type { ScrollbarInst } from 'naive-ui' import type { ScrollbarInst } from 'naive-ui'
import { useTemplateRef } from 'vue' import { TransitionGroup, useTemplateRef } from 'vue'
import { useTagReorder } from './use-tag-reorder'
const Chevron = ({ direction }: { direction: 'left' | 'right' }) => ( const Chevron = ({ direction }: { direction: 'left' | 'right' }) => (
<RIcon <RIcon
@ -25,14 +35,25 @@ export default defineComponent({
const scrollRef = useTemplateRef<ScrollbarInst | null>('scrollRef') const scrollRef = useTemplateRef<ScrollbarInst | null>('scrollRef')
const tagsRef = useTemplateRef<HTMLElement>('tags') const tagsRef = useTemplateRef<HTMLElement>('tags')
const actionsButton = useTemplateRef<HTMLButtonElement>('actionsButton') const actionsButton = useTemplateRef<HTMLButtonElement>('actionsButton')
const statusRef = useTemplateRef<HTMLSpanElement>('reorderStatus')
const route = useRoute() const route = useRoute()
const showingForbidden = computed(() => route.path === FORBIDDEN_ROUTE_PATH) const showingForbidden = computed(() => route.path === FORBIDDEN_ROUTE_PATH)
const { t } = useI18n('menuTag') const { t } = useI18n('menuTag')
const { t: translate } = useI18n()
const { getCurrentMenuOption, getMenuTagOptions } = useMenuGetters() const { getCurrentMenuOption, getMenuTagOptions } = useMenuGetters()
const { getMenuTagRound, getMenuTagTop, getMenuTagFixed, getMenuTagDrag } =
useSettingGetters()
const getMenuKey = computed( const getMenuKey = computed(
() => getCurrentMenuOption.value?.fullPath ?? null, () => getCurrentMenuOption.value?.fullPath ?? null,
) )
const { changeMenuModelValue } = useMenuActions() const {
changeMenuModelValue,
isMenuTagTopped,
isMenuTagFixed,
toggleMenuTagTop,
toggleMenuTagFixed,
moveMenuTag,
} = useMenuActions()
const { maximize } = useMaximize() const { maximize } = useMaximize()
const { reload } = useSpinning() const { reload } = useSpinning()
const { const {
@ -45,8 +66,15 @@ export default defineComponent({
checkCloseLeft, checkCloseLeft,
checkCloseRight, checkCloseRight,
} = useSiderBar() } = useSiderBar()
// 当前右键标签页索引位置 const contextPath = ref<string>()
const currentContextmenuIndex = ref(-1) const currentContextmenuIndex = computed(() =>
getMenuTagOptions.value.findIndex(
({ fullPath }) => fullPath === contextPath.value,
),
)
const contextTag = computed(
() => getMenuTagOptions.value[currentContextmenuIndex.value],
)
const closeStatus = async (restoreFocus: boolean) => { const closeStatus = async (restoreFocus: boolean) => {
const navigation = closeForbiddenPage() const navigation = closeForbiddenPage()
@ -67,13 +95,13 @@ export default defineComponent({
key: 'closeCurrentPage', key: 'closeCurrentPage',
disabled: disabled:
!(showingForbidden.value && currentContextmenuIndex.value === -1) && !(showingForbidden.value && currentContextmenuIndex.value === -1) &&
!canClose(getMenuTagOptions.value[currentContextmenuIndex.value]), !canClose(contextTag.value),
icon: () => <RIcon name="action/close" size="1em" />, icon: () => <RIcon name="action/close" size="1em" />,
}, },
{ {
label: t('maximize'), label: t('maximize'),
key: 'maximizeLayoutContent', key: 'maximizeLayoutContent',
icon: () => <RIcon name="action/fullscreen" size="1em" />, icon: () => <RIcon name="action/maximize-workspace" size="1em" />,
}, },
{ {
label: t('reload'), label: t('reload'),
@ -83,9 +111,37 @@ export default defineComponent({
{ {
label: t('newWindow'), label: t('newWindow'),
key: 'windowOpenTab', key: 'windowOpenTab',
disabled: !getMenuTagOptions.value[currentContextmenuIndex.value], disabled: !contextTag.value,
icon: () => <RIcon name="navigation/window" size="1em" />, icon: () => <RIcon name="navigation/window" size="1em" />,
}, },
...(getMenuTagTop.value
? [
{
label: t(isMenuTagTopped(contextTag.value) ? 'untop' : 'top'),
key: 'toggleTop',
disabled: !contextTag.value,
icon: () => (
<RIcon
name="directional/expanded"
size="1em"
customClassName="menu-tag__top-icon"
/>
),
},
]
: []),
...(getMenuTagFixed.value
? [
{
label: t(isMenuTagFixed(contextTag.value) ? 'unfix' : 'fix'),
key: 'toggleFixed',
disabled: !contextTag.value,
icon: () => (
<RIcon name="action/pin" size="1em" aria-hidden="true" />
),
},
]
: []),
{ {
type: 'divider', type: 'divider',
key: 'd1', key: 'd1',
@ -94,16 +150,14 @@ export default defineComponent({
label: t('closeLeft'), label: t('closeLeft'),
key: 'closeLeft', key: 'closeLeft',
disabled: disabled:
!getMenuTagOptions.value[currentContextmenuIndex.value] || !contextTag.value || !checkCloseLeft(currentContextmenuIndex.value),
!checkCloseLeft(currentContextmenuIndex.value),
icon: () => <RIcon name="action/close_left" size="1em" />, icon: () => <RIcon name="action/close_left" size="1em" />,
}, },
{ {
label: t('closeRight'), label: t('closeRight'),
key: 'closeRight', key: 'closeRight',
disabled: disabled:
!getMenuTagOptions.value[currentContextmenuIndex.value] || !contextTag.value || !checkCloseRight(currentContextmenuIndex.value),
!checkCloseRight(currentContextmenuIndex.value),
icon: () => <RIcon name="action/close_right" size="1em" />, icon: () => <RIcon name="action/close_right" size="1em" />,
}, },
{ {
@ -114,15 +168,17 @@ export default defineComponent({
label: t('closeOther'), label: t('closeOther'),
key: 'closeOther', key: 'closeOther',
disabled: disabled:
getMenuTagOptions.value.length < 2 || !contextTag.value ||
!getMenuTagOptions.value[currentContextmenuIndex.value], !getMenuTagOptions.value.some(
(tag) => tag !== contextTag.value && canClose(tag),
),
icon: () => <RIcon name="action/close_other" size="1em" />, icon: () => <RIcon name="action/close_other" size="1em" />,
}, },
{ {
label: t('closeAll'), label: t('closeAll'),
key: 'closeAll', key: 'closeAll',
icon: () => <RIcon name="action/close_all" size="1em" />, icon: () => <RIcon name="action/close_all" size="1em" />,
disabled: getMenuTagOptions.value.length === 0, disabled: !getMenuTagOptions.value.some(canClose),
}, },
]) ])
const actionMap = { const actionMap = {
@ -133,7 +189,7 @@ export default defineComponent({
closeCurrentMenuTag(currentContextmenuIndex.value) closeCurrentMenuTag(currentContextmenuIndex.value)
}, },
reloadCurrentPage: async () => { reloadCurrentPage: async () => {
const option = getMenuTagOptions.value[currentContextmenuIndex.value] const option = contextTag.value
if (option && route.fullPath !== option.fullPath) { if (option && route.fullPath !== option.fullPath) {
await changeMenuModelValue(option.fullPath, option) await changeMenuModelValue(option.fullPath, option)
@ -155,8 +211,26 @@ export default defineComponent({
closeOther: () => { closeOther: () => {
$closeOther(currentContextmenuIndex.value) $closeOther(currentContextmenuIndex.value)
}, },
toggleTop: () => {
const option = contextTag.value
if (!option || !toggleMenuTagTop(option.fullPath)) return
void nextTick(() => {
const tag = Array.from(tagsRef.value?.children ?? []).find(
(element): element is HTMLElement =>
element instanceof HTMLElement &&
element.dataset.menuTagPath === option.fullPath,
)
if (tag) revealTag(tag)
})
},
toggleFixed: () => {
if (contextTag.value) toggleMenuTagFixed(contextTag.value.fullPath)
},
windowOpenTab: () => { windowOpenTab: () => {
const option = getMenuTagOptions.value[currentContextmenuIndex.value] const option = contextTag.value
if (!option?.fullPath) { if (!option?.fullPath) {
return return
@ -170,7 +244,7 @@ export default defineComponent({
window.open(path, '_blank', 'noopener') window.open(path, '_blank', 'noopener')
}, },
maximizeLayoutContent: () => { maximizeLayoutContent: () => {
const option = getMenuTagOptions.value[currentContextmenuIndex.value] const option = contextTag.value
maximize(true) maximize(true)
option && menuTagClick(option) option && menuTagClick(option)
@ -183,26 +257,42 @@ export default defineComponent({
actionDropdownShow: false, actionDropdownShow: false,
}) })
const globalMainLayoutLoad = useRuntimeGetters().globalMainLayoutLoad const globalMainLayoutLoad = useRuntimeGetters().globalMainLayoutLoad
const canClose = (option?: MenuTagOptions) => !!option const canClose = (option?: MenuTagOptions) =>
!!option && !isMenuTagFixed(option)
const tagLabel = (tag: MenuTagOptions) =>
tag.meta.i18nKey
? 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] const option = getMenuTagOptions.value[index]
if (!option || !canClose(option)) return if (!option || !canClose(option)) return
const focusIndex = const wasActive = option.fullPath === getMenuKey.value
option.fullPath === getMenuKey.value ? Math.max(0, index - 1) : index const failure = await close(index)
close(index) if (
failure ||
!restoreFocus ||
getMenuTagOptions.value.some((tag) => tag.fullPath === option.fullPath)
)
return
if (restoreFocus) { await nextTick()
void nextTick(() => {
const tabs = const tabs =
tagsRef.value?.querySelectorAll<HTMLButtonElement>('.menu-tag__tab') tagsRef.value?.querySelectorAll<HTMLButtonElement>('.menu-tag__tab')
const adjacent = tabs?.[Math.min(index, tabs.length - 1)]
const focus =
(wasActive
? tagsRef.value?.querySelector<HTMLButtonElement>(
'.menu-tag__tab[aria-current="page"]',
)
: adjacent) ??
adjacent ??
actionsButton.value
tabs?.[Math.min(focusIndex, tabs.length - 1)]?.focus() focus?.focus()
})
}
} }
// 菜单标签点击更新当前菜单激活项 // 菜单标签点击更新当前菜单激活项
@ -217,6 +307,61 @@ export default defineComponent({
) )
const scrollState = reactive({ left: false, right: false }) const scrollState = reactive({ left: false, right: false })
const reducedMotion = usePreferredReducedMotion() const reducedMotion = usePreferredReducedMotion()
const revealTag = (tag: HTMLElement) => {
const element = scroller.value
if (!element) return
const start = tag.offsetLeft
const end = start + tag.offsetWidth
const left = element.scrollLeft
const right = left + element.clientWidth
if (start < left || tag.offsetWidth >= element.clientWidth)
element.scrollLeft = start
else if (end > right) element.scrollLeft = end - element.clientWidth
}
const { start: scheduleAnnouncement } = useTimeoutFn(
(message: string) => {
if (statusRef.value) statusRef.value.textContent = message
},
500,
{ immediate: false },
)
const announce = (message: string) => {
if (statusRef.value) statusRef.value.textContent = ''
scheduleAnnouncement(message)
}
const moveTagWithKey = useTagReorder(
getMenuTagDrag,
tagsRef,
scroller,
(path, target, button) => {
if (!moveMenuTag(path, target.path, target.placement)) return
const position = getMenuTagOptions.value.findIndex(
(tag) => tag.fullPath === path,
)
const option = getMenuTagOptions.value[position]
const wasFocused = document.activeElement === button
void nextTick(() => {
const tag = button.closest<HTMLElement>('[data-menu-tag-path]')
if (!tag?.isConnected) return
revealTag(tag)
if (wasFocused) button.focus({ preventScroll: true })
announce(
t('moved', { name: tagLabel(option), position: position + 1 }),
)
})
},
() => announce(t('moveCanceled')),
)
const syncScroll = () => { const syncScroll = () => {
const element = scroller.value const element = scroller.value
@ -252,12 +397,10 @@ export default defineComponent({
return fn?.() return fn?.()
} }
// 右键点击标签页 const menuTagContextMenu = (path: string, e: MouseEvent) => {
// 缓存当前点击标签页索引值(用于关闭左或者右侧标签页操作)
const menuTagContextMenu = (idx: number, e: MouseEvent) => {
e.preventDefault() e.preventDefault()
currentContextmenuIndex.value = idx contextPath.value = path
actionState.x = e.clientX actionState.x = e.clientX
actionState.y = e.clientY actionState.y = e.clientY
actionState.actionDropdownShow = true actionState.actionDropdownShow = true
@ -276,10 +419,8 @@ export default defineComponent({
actionState.actionDropdownShow = false actionState.actionDropdownShow = false
} }
const setCurrentContextmenuIndex = () => { const selectActiveContext = () => {
currentContextmenuIndex.value = getMenuTagOptions.value.findIndex( contextPath.value = getMenuKey.value ?? void 0
({ fullPath }) => fullPath === getMenuKey.value,
)
} }
const positionMenuTag = () => { const positionMenuTag = () => {
@ -305,7 +446,12 @@ export default defineComponent({
} }
watch( watch(
[getMenuKey, () => getMenuTagOptions.value.length, tagsRef], [
getMenuKey,
() => getMenuTagOptions.value.length,
getMenuTagRound,
tagsRef,
],
positionMenuTag, positionMenuTag,
{ flush: 'post' }, { flush: 'post' },
) )
@ -314,7 +460,12 @@ export default defineComponent({
return { return {
getMenuTagOptions, getMenuTagOptions,
canClose, getMenuTagRound,
getMenuTagDrag,
isMenuTagTopped,
isMenuTagFixed,
moveTagWithKey,
tagLabel,
closeCurrentMenuTag, closeCurrentMenuTag,
getMenuKey, getMenuKey,
menuTagClick, menuTagClick,
@ -330,7 +481,7 @@ export default defineComponent({
actionState, actionState,
menuTagContextMenu, menuTagContextMenu,
dismissContextMenu, dismissContextMenu,
setCurrentContextmenuIndex, selectActiveContext,
maximize, maximize,
reload, reload,
globalMainLayoutLoad, globalMainLayoutLoad,
@ -339,7 +490,6 @@ export default defineComponent({
render() { render() {
const { getMenuTagOptions, globalMainLayoutLoad } = this const { getMenuTagOptions, globalMainLayoutLoad } = this
const { const {
canClose,
closeCurrentMenuTag, closeCurrentMenuTag,
$t, $t,
menuTagClick, menuTagClick,
@ -349,7 +499,6 @@ export default defineComponent({
} = this } = this
return ( return (
<NLayoutHeader>
<div class="menu-tag"> <div class="menu-tag">
<NDropdown <NDropdown
class="menu-tag__dropdown" class="menu-tag__dropdown"
@ -393,34 +542,68 @@ export default defineComponent({
<div <div
ref="tags" ref="tags"
class="menu-tag-wrapper" class="menu-tag-wrapper"
data-menu-tag-sortable={this.getMenuTagDrag ? '' : void 0}
role="group" role="group"
aria-label={$t('menuTag.pages')} aria-label={$t('menuTag.pages')}
onKeydown={this.moveTagWithKey}
> >
<TransitionGroup name="menu-tag" css={false}>
{getMenuTagOptions.map((curr, idx) => { {getMenuTagOptions.map((curr, idx) => {
const active = curr.fullPath === this.getMenuKey const active = curr.fullPath === this.getMenuKey
const label = curr.meta.i18nKey const label = this.tagLabel(curr)
? $t(curr.meta.i18nKey) const topped = this.isMenuTagTopped(curr)
: curr.breadcrumbLabel || curr.fullPath const fixed = this.isMenuTagFixed(curr)
const topLabel = topped ? $t('menuTag.topped') : ''
const fixedLabel = fixed ? $t('menuTag.fixed') : ''
return ( return (
<ShellTab <ShellTab
key={curr.fullPath} key={curr.fullPath}
label={label} label={label}
active={active} active={active}
data-menu-tag-path={curr.fullPath}
data-menu-tag-top={topped ? '' : void 0}
statusLabel={
topLabel && fixedLabel
? `${topLabel} · ${fixedLabel}`
: topLabel || fixedLabel
}
round={this.getMenuTagRound}
keyShortcuts={
this.getMenuTagDrag
? 'Shift+ArrowLeft Shift+ArrowRight'
: void 0
}
select={() => menuTagClick(curr)} select={() => menuTagClick(curr)}
closeLabel={$t('menuTag.closeNamed', { name: label })} closeLabel={$t('menuTag.closeNamed', { name: label })}
close={ close={
canClose(curr) !fixed
? (restoreFocus) => ? (restoreFocus) =>
closeCurrentMenuTag(idx, restoreFocus) closeCurrentMenuTag(idx, restoreFocus)
: void 0 : void 0
} }
contextMenu={(event) => menuTagContextMenu(idx, event)} contextMenu={(event) =>
menuTagContextMenu(curr.fullPath, event)
}
>
{{
prefix: fixed
? () => (
<RIcon
name="action/pin"
size={14}
aria-hidden="true"
/> />
) )
: void 0,
}}
</ShellTab>
)
})} })}
</TransitionGroup>
</div> </div>
</NScrollbar> </NScrollbar>
<span ref="reorderStatus" class="menu-tag__status" role="status" />
<button <button
type="button" type="button"
class="menu-tag__control menu-tag__control--scroll" class="menu-tag__control menu-tag__control--scroll"
@ -450,7 +633,7 @@ export default defineComponent({
title={$t('layout.maximize')} title={$t('layout.maximize')}
onClick={() => this.maximize(true)} onClick={() => this.maximize(true)}
> >
<RIcon name="action/fullscreen" size={16} /> <RIcon name="action/maximize-workspace" size={16} />
</button> </button>
<button <button
type="button" type="button"
@ -481,7 +664,7 @@ export default defineComponent({
class="menu-tag__control" class="menu-tag__control"
aria-label={$t('menuTag.actions')} aria-label={$t('menuTag.actions')}
title={$t('menuTag.actions')} title={$t('menuTag.actions')}
onClick={this.setCurrentContextmenuIndex} onClick={this.selectActiveContext}
> >
<RIcon name="action/more" size={16} /> <RIcon name="action/more" size={16} />
</button> </button>
@ -489,7 +672,6 @@ export default defineComponent({
</div> </div>
</NFlex> </NFlex>
</div> </div>
</NLayoutHeader>
) )
}, },
}) })

View File

@ -0,0 +1,481 @@
import { useEventListener } from '@vueuse/core'
import { watch } from 'vue'
import type { Ref } from 'vue'
type InteractApi = typeof import('interactjs').default
type Placement = 'before' | 'after'
type ClientPosition = Pick<PointerEvent, 'clientX' | 'clientY'>
const TAB_SELECTOR = '[data-menu-tag-path]'
const CLOSE_SELECTOR = '.n-tag__close'
const DRAG_SLOP = 5
const TOUCH_HOLD_DELAY = 280
interface DropTarget {
path: string
placement: Placement
}
interface DropMarker {
tab: HTMLElement
placement: Placement
}
interface Press {
down: PointerEvent
pointer: Interact.PointerEvent
row: HTMLElement
tab: HTMLElement
button: HTMLButtonElement
path: string
offsetX: number
offsetY: number
}
interface Drag {
preview: HTMLElement
restoreDropMode: () => void
release?: PointerEvent
}
let activeTagDrags = 0
let previousDynamicDrop = false
const retainDynamicDrop = (interact: InteractApi) => {
// dynamicDrop 由同一个 interact.js 实例共享,最后一次标签拖动结束时恢复。
if (activeTagDrags === 0) {
previousDynamicDrop = interact.dynamicDrop() === true
interact.dynamicDrop(true)
}
activeTagDrags++
return () => {
activeTagDrags--
if (activeTagDrags === 0) interact.dynamicDrop(previousDynamicDrop)
}
}
export function useTagReorder(
enabled: Ref<boolean>,
list: Ref<HTMLElement | null>,
scroller: Ref<HTMLElement | null | undefined>,
move: (path: string, target: DropTarget, button: HTMLButtonElement) => void,
announceCancellation: () => void,
) {
let press: Press | undefined
let drag: Drag | undefined
let marker: DropMarker | undefined
let frame: number | undefined
let suppressPointerClick = false
const mark = (target?: DropMarker) => {
if (target?.tab === marker?.tab && target?.placement === marker?.placement)
return
marker?.tab.removeAttribute('data-menu-tag-drop')
target?.tab.setAttribute('data-menu-tag-drop', target.placement)
marker = target
}
const finish = () => {
press?.row.classList.remove('menu-tag-wrapper--dragging')
press?.tab.removeAttribute('data-menu-tag-dragged')
mark()
if (frame !== void 0) cancelAnimationFrame(frame)
frame = void 0
drag?.preview.remove()
drag?.restoreDropMode()
drag = void 0
press = void 0
}
const cancel = () => {
if (drag) {
press?.pointer.interaction.stop()
announceCancellation()
}
finish()
}
const refreshDrop = () => {
if (!drag || frame !== void 0) return
frame = requestAnimationFrame(() => {
frame = void 0
// 跳过同坐标的优化,让滚动后的落区重新参与检测。
press?.pointer.interaction.move({ skipModifiers: 1 })
})
}
const movePreview = ({ clientX, clientY }: ClientPosition) => {
if (!press || !drag) return
const x = clientX - press.offsetX
const y = clientY - press.offsetY
drag.preview.style.transform = `translate3d(${x}px, ${y}px, 0)`
}
const start = ({ pointer, tab }: Press, position: ClientPosition) => {
pointer.interaction.start({ name: 'drag' }, pointer.interactable, tab)
movePreview(position)
}
const startWithPointer = (event: PointerEvent) => {
const current = press
if (
!current ||
drag ||
event.pointerId !== current.down.pointerId ||
event.pointerType === 'touch'
)
return
const x = Math.abs(event.clientX - current.down.clientX)
const y = Math.abs(event.clientY - current.down.clientY)
if (Math.max(x, y) >= DRAG_SLOP) start(current, event)
}
const trackTouch = (event: TouchEvent) => {
const current = press
if (current?.down.pointerType !== 'touch') return
if (!event.cancelable || event.touches.length !== 1) {
cancel()
return
}
if (!drag) {
const touch = event.touches[0]
const x = Math.abs(touch.clientX - current.down.clientX)
const y = Math.abs(touch.clientY - current.down.clientY)
if (Math.max(x, y) < DRAG_SLOP) return
if (
event.timeStamp - current.down.timeStamp < TOUCH_HOLD_DELAY ||
y > x
) {
finish()
return
}
start(current, touch)
}
// 普通滑动保持原生滚动,长按启动拖动后才接管触摸。
if (drag) event.preventDefault()
}
const bind = (
interact: InteractApi,
row: HTMLElement,
viewport: HTMLElement,
) => {
const previewHost = row.closest('.menu-tag')
if (!previewHost) return
const zoneRect = (element: Element) => {
const visible = interact.getElementRect(viewport)
const origin = interact.getElementRect(row)?.left
if (!visible || origin === void 0)
return { left: 0, right: 0, top: 0, bottom: 0 }
const previous = element.previousElementSibling
const next = element.nextElementSibling
// 落区延伸到两侧相邻标签的边缘,使标签间的插入线也可以落下。
return {
left:
previous instanceof HTMLElement
? Math.max(
visible.left,
origin + previous.offsetLeft + previous.offsetWidth,
)
: visible.left,
right:
next instanceof HTMLElement
? Math.min(visible.right, origin + next.offsetLeft)
: visible.right,
top: visible.top,
bottom: visible.bottom,
}
}
const placementAt = (
event: Interact.DropEvent,
x: number,
): DropMarker | undefined => {
const { target: tab, relatedTarget: source } = event
if (!(tab instanceof HTMLElement)) return
const middle =
row.getBoundingClientRect().left + tab.offsetLeft + tab.offsetWidth / 2
const placement = x < middle ? 'before' : 'after'
const neighbor =
placement === 'before'
? tab.previousElementSibling
: tab.nextElementSibling
if (neighbor !== source) return { tab, placement }
}
const interactable = interact(TAB_SELECTOR, { context: row })
.styleCursor(false)
.preventDefault('never')
.rectChecker(zoneRect)
.draggable({
manualStart: true,
ignoreFrom: CLOSE_SELECTOR,
autoScroll: { container: viewport, margin: 36, speed: 450 },
listeners: {
start: () => {
if (!press) return
const preview = press.tab.cloneNode(true) as HTMLElement
preview.classList.add('menu-tag__drag-preview')
preview.removeAttribute('data-menu-tag-path')
preview.setAttribute('aria-hidden', 'true')
preview.setAttribute('inert', '')
// 副本浮在滚动区外,原标签继续占位并参与落点判定。
previewHost.append(preview)
drag = { preview, restoreDropMode: retainDynamicDrop(interact) }
suppressPointerClick = true
row.classList.add('menu-tag-wrapper--dragging')
press.tab.setAttribute('data-menu-tag-dragged', '')
refreshDrop()
},
move: movePreview,
end: finish,
},
})
.dropzone({
accept: ({ draggableElement }) =>
draggableElement.parentElement === row,
overlap: 'pointer',
checker: (
event: Interact.DragEvent,
_native,
over,
_zone,
target,
_from,
source,
) => {
if (
!drag ||
target.hasAttribute('data-menu-tag-top') !==
source.hasAttribute('data-menu-tag-top')
)
return false
if (event.type !== 'dragend') return over
const released = drag.release
if (!released) return false
if (
released.clientX === event.clientX &&
released.clientY === event.clientY
)
return over
// 1.10.28 的 dragend 坐标取自上一条 dragmove。松手坐标可能已变化。
const rect = zoneRect(target)
return (
released.pageX > rect.left &&
released.pageX < rect.right &&
released.pageY > rect.top &&
released.pageY < rect.bottom
)
},
ondropmove: (event: Interact.DropEvent) =>
mark(placementAt(event, event.dragEvent.clientX)),
ondragleave: () => mark(),
ondrop: (event: Interact.DropEvent) => {
const released = drag?.release
if (!press || !released) return
const marker = placementAt(event, released.clientX)
const path = marker?.tab.dataset.menuTagPath
if (marker && path)
move(
press.path,
{ path, placement: marker.placement },
press.button,
)
},
})
.pointerEvents({ ignoreFrom: CLOSE_SELECTOR })
.on('down', (pointer: Interact.PointerEvent) => {
const event = pointer.originalEvent
const tab = pointer.currentTarget
if (
press ||
!(event instanceof PointerEvent) ||
!event.isPrimary ||
event.button !== 0 ||
!(tab instanceof HTMLElement) ||
tab.parentElement !== row
)
return
const path = tab.dataset.menuTagPath
const button = tab.querySelector<HTMLButtonElement>('.menu-tag__tab')
if (!path || !button) return
const { left, top } = tab.getBoundingClientRect()
press = {
down: event,
pointer,
row,
tab,
button,
path,
offsetX: event.clientX - left,
offsetY: event.clientY - top,
}
})
return () => {
cancel()
interactable.unset()
}
}
watch(
[enabled, list, scroller],
([allowed, row, viewport], _, onCleanup) => {
if (!allowed || !row || !viewport) return
let disposed = false
let unbind: (() => void) | undefined
onCleanup(() => {
disposed = true
unbind?.()
})
void import('interactjs').then(({ default: interact }) => {
if (!disposed) unbind = bind(interact, row, viewport)
})
},
{ immediate: true, flush: 'post' },
)
useEventListener('pointermove', startWithPointer, {
capture: true,
passive: true,
})
useEventListener(
'pointerup',
(event) => {
if (press?.down.pointerId !== event.pointerId) return
if (drag) drag.release = event
else finish()
},
{ capture: true },
)
useEventListener(
'pointercancel',
(event) => {
if (press?.down.pointerId === event.pointerId) cancel()
},
{ capture: true },
)
useEventListener(list, 'touchmove', trackTouch, { passive: false })
useEventListener(scroller, 'scroll', refreshDrop, { passive: true })
useEventListener(list, 'pointerdown', (event) => {
if (!drag && event.isPrimary && event.button === 0)
suppressPointerClick = false
})
useEventListener(
list,
'click',
(event) => {
if (!suppressPointerClick || event.detail === 0) return
suppressPointerClick = false
event.preventDefault()
event.stopPropagation()
},
{ capture: true },
)
useEventListener(
list,
'contextmenu',
(event) => {
if (press?.down.pointerType !== 'touch') return
event.preventDefault()
event.stopPropagation()
},
{ capture: true },
)
useEventListener(
'keydown',
(event) => {
if (event.key !== 'Escape' || !press) return
event.preventDefault()
cancel()
},
{ capture: true },
)
return (event: KeyboardEvent) => {
if (
!enabled.value ||
drag ||
!event.shiftKey ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.isComposing ||
(event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')
)
return
const button = event.target
if (
!(button instanceof HTMLButtonElement) ||
!button.classList.contains('menu-tag__tab')
)
return
event.preventDefault()
const item = button.closest<HTMLElement>(TAB_SELECTOR)
const placement = event.key === 'ArrowLeft' ? 'before' : 'after'
const neighbor =
placement === 'before'
? item?.previousElementSibling
: item?.nextElementSibling
const path = item?.dataset.menuTagPath
const target =
neighbor instanceof HTMLElement ? neighbor.dataset.menuTagPath : void 0
if (path && target) move(path, { path: target, placement }, button)
}
}

View File

@ -1,130 +1,244 @@
.global-search.n-card { .global-search.n-card {
inline-size: min(650px, calc(100dvw - 24px)); --search-gutter: 20px;
max-block-size: calc(100dvh - 24px); --search-top: min(56px, 8dvh);
margin: 12px auto auto; --search-scrollbar-gutter: 8px;
border-radius: var(--r-radius); --search-focus: color-mix(
in srgb,
var(--r-theme-primary-color) 50%,
var(--r-text)
);
.n-card__content { inline-size: min(620px, calc(100dvw - 24px));
min-block-size: 0; max-block-size: calc(100dvh - var(--search-top) - 12px);
overflow: auto; margin: var(--search-top) auto auto;
border-radius: var(--r-radius);
box-shadow: var(--r-shadow-soft);
> .n-card-header {
gap: 16px;
padding: 10px var(--search-gutter);
} }
.n-card__action { > .n-card__content {
padding: 12px 20px; display: flex;
flex-direction: column;
min-block-size: 0;
padding: 0 var(--search-gutter);
}
> .n-card__action {
flex-shrink: 0;
padding: 8px var(--search-gutter);
border-block-start: 1px solid var(--r-line);
border-end-start-radius: inherit;
border-end-end-radius: inherit;
background: var(--r-surface-muted);
} }
} }
.global-search__header,
.global-search__group-heading,
.global-search__item, .global-search__item,
.global-search__help { .global-search__help {
display: flex; display: flex;
align-items: center; align-items: center;
} }
.global-search__header, .global-search__title {
.global-search__group-heading { color: var(--r-text);
justify-content: space-between; font-size: 16px;
font-weight: 600;
} }
.global-search__header {
gap: 16px;
}
.global-search__group {
margin-top: 20px;
}
.global-search__group-heading {
min-height: 28px;
margin-bottom: 8px;
h2 { .global-search__input {
font-size: 13px; flex-shrink: 0;
font-weight: 500;
color: var(--r-text-secondary);
}
} }
.global-search__results.n-scrollbar {
flex: 0 1 auto;
inline-size: auto;
block-size: auto;
min-block-size: 0;
max-block-size: 400px;
margin-block: 14px 12px;
margin-inline-end: calc(-1 * var(--search-scrollbar-gutter));
}
.global-search__results-content {
padding-inline-end: var(--search-scrollbar-gutter);
}
.global-search__group + .global-search__group {
margin-block-start: 16px;
}
.global-search__group-heading {
margin: 0 0 5px;
padding-inline: 8px;
color: var(--r-text-secondary);
font-size: 12px;
font-weight: 600;
}
.global-search__list {
display: grid;
gap: 4px;
margin: 0;
padding: 0;
list-style: none;
}
.global-search__item { .global-search__item {
gap: 4px; gap: 4px;
border: 1px solid var(--r-line); min-inline-size: 0;
padding-inline-end: 4px;
border-radius: var(--r-control-radius); border-radius: var(--r-control-radius);
margin-block: 6px;
padding-inline-end: 8px;
&:hover, @media (hover: hover) {
&:focus-within { &:hover {
background: var(--r-surface-hover); background: var(--r-surface-hover);
} }
}
&[data-enter-target],
&:has(> .global-search__destination:focus-visible) {
background: color-mix(
in srgb,
var(--r-theme-primary-color) 9%,
var(--r-surface)
);
outline: 2px solid var(--search-focus);
outline-offset: -2px;
> .global-search__destination {
outline: none;
}
.global-search__page-icon {
color: var(--search-focus);
background: color-mix(
in srgb,
var(--r-theme-primary-color) 15%,
var(--r-surface)
);
}
}
&:has(> .global-search__destination:active) {
background: color-mix(in srgb, var(--r-text) 12%, var(--r-surface));
}
} }
.global-search__destination { .global-search__destination {
display: flex; display: flex;
flex: 1; flex: 1;
align-items: center; align-items: center;
gap: 12px; gap: 10px;
min-width: 0; min-inline-size: 0;
min-height: 46px; min-block-size: 44px;
padding: 10px 12px; padding: 6px 8px;
border: 0; border: 0;
border-radius: var(--r-control-radius); border-radius: var(--r-control-radius);
background: transparent; background: transparent;
color: var(--r-text); color: var(--r-text);
text-align: start; text-align: start;
cursor: pointer; cursor: pointer;
line-height: 1.5; font-weight: 500;
line-height: 1.4;
}
> span { .global-search__destination,
.global-search__close.n-button,
.global-search__favorite.n-button,
.global-search__clear.n-button {
&:focus-visible {
outline: 2px solid var(--search-focus);
outline-offset: -2px;
}
}
.global-search__close,
.global-search__favorite,
.global-search__clear {
flex-shrink: 0;
}
.global-search__page-icon {
display: grid;
flex-shrink: 0;
place-items: center;
inline-size: 32px;
block-size: 32px;
border-radius: var(--r-control-radius);
background: var(--r-surface-muted);
color: var(--r-text-secondary);
}
.global-search__page-label {
overflow-wrap: anywhere; overflow-wrap: anywhere;
}
.r-icon {
flex-shrink: 0;
color: var(--r-theme-primary-color);
}
} }
.global-search__favorite {
flex-shrink: 0; .global-search__external {
font-size: 20px; color: var(--r-text-muted);
} }
.global-search__empty { .global-search__empty {
padding: 36px 12px; display: grid;
justify-items: center;
gap: 10px;
margin: 0;
padding: 28px 12px;
text-align: center; text-align: center;
color: var(--r-text-secondary); color: var(--r-text-secondary);
} }
.global-search__hint { .global-search__hint {
margin-top: 12px; margin: 10px 0 0;
color: var(--r-text-secondary); color: var(--r-text-secondary);
} }
.global-search__help { .global-search__help {
flex-wrap: wrap; flex-wrap: wrap;
gap: 16px; gap: 6px 14px;
min-block-size: 30px;
font-size: 12px; font-size: 12px;
color: var(--r-text-secondary); color: var(--r-text-secondary);
}
.global-search__shortcut {
display: inline-flex;
align-items: center;
gap: 4px;
white-space: nowrap;
kbd { kbd {
padding: 2px 5px; display: inline-grid;
place-items: center;
min-inline-size: 20px;
min-block-size: 20px;
padding-inline: 4px;
border: 1px solid var(--r-line); border: 1px solid var(--r-line);
border-radius: 4px; border-radius: var(--r-control-radius);
background: var(--r-surface);
font-family: var(--r-font-mono);
} }
} }
.global-search__results { .global-search__clear {
max-block-size: min(440px, calc(100dvh - 230px)); margin-inline-start: auto;
} }
@media (max-width: 768px) { @media (max-width: 768px) {
.global-search.n-card { .global-search.n-card {
.n-card-header { --search-gutter: 14px;
padding: 12px 16px; --search-top: 12px;
}
.n-card__content { > .n-card__action:not(:has(.global-search__clear)) {
padding-inline: 16px; display: none;
}
.n-card__action {
padding: 12px 16px;
} }
} }
.global-search__header > .n-button, .global-search__close.n-button,
.global-search__favorite { .global-search__favorite.n-button,
.global-search__clear.n-button {
min-inline-size: 44px; min-inline-size: 44px;
min-block-size: 44px; min-block-size: 44px;
} }
@ -132,14 +246,19 @@
.global-search__shortcut { .global-search__shortcut {
display: none; display: none;
} }
.global-search__help:has(> :not(.global-search__shortcut)) {
justify-content: flex-end;
}
} }
@media (min-width: 769px) { @media (forced-colors: active) {
.global-search.n-card { .global-search.n-card {
margin-block-start: min(60px, 8dvh); --search-focus: Highlight;
} }
} }
.global-search__enter-hint {
position: absolute;
inline-size: 1px;
block-size: 1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}

View File

@ -19,6 +19,7 @@ export default defineComponent({
emits: ['update:show'], emits: ['update:show'],
setup(props, { emit }) { setup(props, { emit }) {
const { t } = useI18n('navigationSearch') const { t } = useI18n('navigationSearch')
const { t: translate } = useI18n()
const { changeMenuModelValue } = useMenuActions() const { changeMenuModelValue } = useMenuActions()
const { getMenuOptions } = useMenuGetters() const { getMenuOptions } = useMenuGetters()
const { recentPaths, favoritePaths, storageUnavailable } = const { recentPaths, favoritePaths, storageUnavailable } =
@ -27,6 +28,8 @@ export default defineComponent({
useNavigationHistoryActions() useNavigationHistoryActions()
const input = shallowRef<InputInst>() const input = shallowRef<InputInst>()
const inputId = useId() const inputId = useId()
const enterHintId = useId()
const inputFocused = ref(false)
const searchValue = ref('') const searchValue = ref('')
const activeIndex = ref(0) const activeIndex = ref(0)
const rowButtons = new Map<string, HTMLButtonElement>() const rowButtons = new Map<string, HTMLButtonElement>()
@ -43,13 +46,27 @@ export default defineComponent({
}, },
}) })
const visibleLeaves = computed(() => { const visibleLeaves = computed(() => {
const leaves: AppMenuOption[] = [] const leaves: { option: AppMenuOption; searchText: string }[] = []
const visit = (items: AppMenuOption[]) => { const visit = (items: AppMenuOption[], trail = '') => {
for (const item of items) { for (const item of items) {
if (item.show === false) continue if (item.show === false) continue
if (item.children?.length) visit(item.children) const badge = item.meta.extra
else leaves.push(item) const badgeText =
badge?.show === false
? ''
: badge?.i18nLabel
? translate(badge.i18nLabel)
: (badge?.label ?? '')
const labels =
`${trail} ${item.breadcrumbLabel ?? ''} ${badgeText}`.trim()
if (item.children?.length) visit(item.children, labels)
else
leaves.push({
option: item,
searchText: labels.toLocaleLowerCase(),
})
} }
} }
@ -58,7 +75,10 @@ export default defineComponent({
return leaves return leaves
}) })
const menuByPath = computed( const menuByPath = computed(
() => new Map(visibleLeaves.value.map((item) => [item.fullPath, item])), () =>
new Map(
visibleLeaves.value.map(({ option }) => [option.fullPath, option]),
),
) )
const savedOptions = (paths: readonly string[]) => const savedOptions = (paths: readonly string[]) =>
paths.flatMap((path) => { paths.flatMap((path) => {
@ -73,9 +93,9 @@ export default defineComponent({
return [ return [
{ {
key: 'results', key: 'results',
options: visibleLeaves.value.filter((item) => options: visibleLeaves.value
item.breadcrumbLabel?.toLocaleLowerCase().includes(term), .filter(({ searchText }) => searchText.includes(term))
), .map(({ option }) => option),
}, },
] ]
@ -95,6 +115,10 @@ export default defineComponent({
groups.value.flatMap((group) => group.options), groups.value.flatMap((group) => group.options),
) )
const enterTarget = computed(() =>
inputFocused.value ? options.value[activeIndex.value] : void 0,
)
watch(options, () => { watch(options, () => {
activeIndex.value = 0 activeIndex.value = 0
}) })
@ -104,6 +128,13 @@ export default defineComponent({
if (show) resetSearch() if (show) resetSearch()
}, },
) )
watch(
[() => props.show, input],
([show, field]) => {
if (show) field?.focus()
},
{ flush: 'post' },
)
const openPage = async (option: AppMenuOption) => { const openPage = async (option: AppMenuOption) => {
// 从当前菜单重新解析,缓存里的旧路径不能绕过权限或路由来源变化。 // 从当前菜单重新解析,缓存里的旧路径不能绕过权限或路由来源变化。
@ -167,7 +198,7 @@ export default defineComponent({
onUpdateShow={(value) => { onUpdateShow={(value) => {
modelShow.value = value modelShow.value = value
}} }}
onAfterEnter={() => input.value?.focus()} autoFocus={false}
transformOrigin="center" transformOrigin="center"
displayDirective="if" displayDirective="if"
> >
@ -179,25 +210,34 @@ export default defineComponent({
> >
{{ {{
header: () => ( header: () => (
<div class="global-search__header"> <label class="global-search__title" for={inputId}>
<label for={inputId}>{t('title')}</label> {t('title')}
</label>
),
'header-extra': () => (
<NButton <NButton
quaternary quaternary
circle
size="small" size="small"
class="global-search__close"
aria-label={t('close')} aria-label={t('close')}
onClick={() => { onClick={() => {
modelShow.value = false modelShow.value = false
}} }}
> >
<RIcon name="action/close" /> <RIcon name="action/close" size={16} />
</NButton> </NButton>
</div>
), ),
default: () => ( default: () => (
<> <>
<NInput <NInput
ref={input} ref={input}
class="global-search__input"
size="large" size="large"
themeOverrides={{
color: 'var(--r-surface-muted)',
colorFocus: 'var(--r-surface)',
}}
value={searchValue.value} value={searchValue.value}
onUpdateValue={(value) => { onUpdateValue={(value) => {
searchValue.value = value searchValue.value = value
@ -206,27 +246,48 @@ export default defineComponent({
inputProps={{ inputProps={{
id: inputId, id: inputId,
name: 'page-search', name: 'page-search',
'aria-describedby': enterHintId,
autocapitalize: 'off', autocapitalize: 'off',
spellcheck: false, spellcheck: false,
}} }}
onFocus={() => {
inputFocused.value = true
}}
onBlur={() => {
inputFocused.value = false
}}
onKeydown={(event) => moveResult(event, true)} onKeydown={(event) => moveResult(event, true)}
clearable clearable
> >
{{ prefix: () => <RIcon name="action/search" /> }} {{ prefix: () => <RIcon name="action/search" size={18} /> }}
</NInput> </NInput>
<span
id={enterHintId}
class="global-search__enter-hint"
role="status"
>
{enterTarget.value
? t('enterTarget', {
title: enterTarget.value.breadcrumbLabel,
})
: ''}
</span>
{storageUnavailable.value && ( {storageUnavailable.value && (
<p class="global-search__hint" role="status"> <p class="global-search__hint" role="status">
{t('storageUnavailable')} {t('storageUnavailable')}
</p> </p>
)} )}
<NScrollbar class="global-search__results"> <NScrollbar
class="global-search__results"
contentClass="global-search__results-content"
>
{options.value.length ? ( {options.value.length ? (
groups.value.map((group) => ( groups.value.map((group) => (
<section class="global-search__group" key={group.key}> <section class="global-search__group" key={group.key}>
<div class="global-search__group-heading"> <h2 class="global-search__group-heading">
<h2>{t(group.key)}</h2> {t(group.key)}
</div> </h2>
<ul role="list"> <ul class="global-search__list" role="list">
{group.options.map((option) => { {group.options.map((option) => {
const favorite = favoritePaths.value.includes( const favorite = favoritePaths.value.includes(
option.fullPath, option.fullPath,
@ -236,6 +297,9 @@ export default defineComponent({
<li <li
key={option.fullPath} key={option.fullPath}
class="global-search__item" class="global-search__item"
data-enter-target={
enterTarget.value === option ? '' : void 0
}
> >
<button <button
type="button" type="button"
@ -252,15 +316,23 @@ export default defineComponent({
onKeydown={(event) => moveResult(event)} onKeydown={(event) => moveResult(event)}
onClick={() => void openPage(option)} onClick={() => void openPage(option)}
> >
{typeof option.meta.icon === 'string' && <span class="global-search__page-icon">
option.meta.icon ? ( <RIcon
<RIcon name={option.meta.icon} size={20} /> name={
) : ( typeof option.meta.icon === 'string' &&
<RIcon name="navigation/menu" size={20} /> option.meta.icon
)} ? option.meta.icon
<span>{option.breadcrumbLabel}</span> : 'navigation/menu'
}
size={18}
/>
</span>
<span class="global-search__page-label">
{option.breadcrumbLabel}
</span>
{option.meta.windowOpen && ( {option.meta.windowOpen && (
<RIcon <RIcon
class="global-search__external"
name="action/external-link" name="action/external-link"
size={14} size={14}
/> />
@ -268,6 +340,7 @@ export default defineComponent({
</button> </button>
<NButton <NButton
quaternary quaternary
circle
size="small" size="small"
class="global-search__favorite" class="global-search__favorite"
type={favorite ? 'primary' : 'default'} type={favorite ? 'primary' : 'default'}
@ -278,9 +351,14 @@ export default defineComponent({
)} )}
onClick={() => toggle(option.fullPath)} onClick={() => toggle(option.fullPath)}
> >
<span aria-hidden="true"> <RIcon
{favorite ? '★' : '☆'} name={
</span> favorite
? 'action/star-filled'
: 'action/star'
}
size={18}
/>
</NButton> </NButton>
</li> </li>
) )
@ -289,8 +367,11 @@ export default defineComponent({
</section> </section>
)) ))
) : ( ) : (
<p class="global-search__empty"> <p class="global-search__empty" role="status">
<RIcon name="action/search" size={24} />
<span>
{t(searchValue.value.trim() ? 'noResults' : 'empty')} {t(searchValue.value.trim() ? 'noResults' : 'empty')}
</span>
</p> </p>
)} )}
</NScrollbar> </NScrollbar>
@ -308,7 +389,15 @@ export default defineComponent({
<kbd>Esc</kbd> {t('close')} <kbd>Esc</kbd> {t('close')}
</span> </span>
{recentPaths.value.length > 0 && ( {recentPaths.value.length > 0 && (
<NButton text size="tiny" onClick={clearRecent}> <NButton
class="global-search__clear"
quaternary
size="small"
onClick={() => {
clearRecent()
input.value?.focus()
}}
>
{t('clearRecent')} {t('clearRecent')}
</NButton> </NButton>
)} )}

View File

@ -0,0 +1,209 @@
import './index.scss'
import AppAvatar from '@/app-components/app/AppAvatar'
import { LOCAL_OPTIONS } from '@/app-config'
import { useDevice, useI18n } from '@/hooks'
import { useSettingActions, useSigningGetters } from '@/store'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex } from 'naive-ui'
import type { PropType } from 'vue'
import { useFullscreen } from 'vue-hooks-plus'
import { layoutHostKey } from '../../host-context'
import GlobalSearch from '../Search/GlobalSearch'
import GlobalSearchButton from '../Search/GlobalSearchButton'
import {
avatarDropdownClick,
createAvatarOptions,
createRightIconOptions,
} from './shared'
import type { IconEventMapOptions } from './type'
export default defineComponent({
name: 'LayoutHeaderActions',
props: {
onOpenSettings: { type: Function as PropType<() => void>, default: void 0 },
},
setup(props) {
// 获取 setting 相关值
const { updateLocale, updateSettingState } = useSettingActions()
const { t } = useI18n()
// 获取全屏相关方法
const [isFullscreen, { toggleFullscreen, isEnabled }] = useFullscreen(
document.getElementsByTagName('html')[0],
)
const host = inject(layoutHostKey, null)
const accountMenuShown = ref(false)
const { getSigningCallback } = useSigningGetters()
// 是否展示全局搜索
const globalSearchShown = ref(false)
// 当前是否为平板或者更小的设备
const { isTabletOrSmaller } = useDevice()
/**
*
* @description
* 顶部右边提示框操作栏。
*/
const rightTooltipIconOptions = computed(() =>
createRightIconOptions({
isFullscreen,
isTabletOrSmaller,
}),
)
const iconEventMap: IconEventMapOptions = {
search: () => {
globalSearchShown.value = true
},
setting: () => (props.onOpenSettings ?? host?.openSettings)?.(),
github: () => {
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
},
fullscreen: () => {
if (!isEnabled) {
window.$message.warning(t('globalMessage.isEnabledFullscreen'))
}
toggleFullscreen()
},
lock: () => {
updateSettingState('lockScreenSwitch', true)
},
}
const toolIconClick = (key: keyof typeof iconEventMap) => {
iconEventMap[key]?.()
}
return {
t,
isFullscreen,
rightTooltipIconOptions,
toolIconClick,
updateLocale,
globalSearchShown,
isTabletOrSmaller,
accountMenuShown,
getSigningCallback,
}
},
render() {
const { rightTooltipIconOptions, toolIconClick, updateLocale } = this
return (
<>
<GlobalSearch v-model:show={this.globalSearchShown} />
<NFlex
class="layout-header__actions"
justify="end"
align="center"
size={[4, 0]}
wrap={false}
>
{this.isTabletOrSmaller ? (
<NButton
quaternary
class="override-button__layout"
aria-label={this.t<string>('headerTooltip.Search')}
onClick={() => {
this.globalSearchShown = true
}}
>
<RIcon name="action/search" size={20} />
</NButton>
) : (
<GlobalSearchButton
onClick={(e) => {
e.stopPropagation()
this.globalSearchShown = true
}}
/>
)}
{rightTooltipIconOptions.map((curr) => (
<NButton
class={[
'override-button__layout',
{ 'layout-header__settings': curr.eventKey === 'setting' },
]}
quaternary
size="medium"
key={curr.eventKey ?? curr.name}
aria-label={this.t<string>(
curr.eventKey === 'setting'
? 'headerTooltip.Setting'
: curr.eventKey === 'github'
? 'headerTooltip.Github'
: this.isFullscreen
? 'headerTooltip.CancelFullScreen'
: 'headerTooltip.FullScreen',
)}
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)}
>
<RIcon name={curr.name} size={20} />
</NButton>
))}
<NDropdown
options={LOCAL_OPTIONS}
onSelect={(key: string | number) => updateLocale(String(key))}
trigger="click"
>
<NButton
quaternary
aria-label={this.t<string>('layout.language')}
class="override-button__layout"
>
<RIcon name="system/language" size={20} />
</NButton>
</NDropdown>
<NDropdown
class="layout-account-menu"
placement="bottom-end"
show={this.accountMenuShown}
onUpdateShow={(show) => {
this.accountMenuShown = show
}}
options={[
{
key: 'identity',
type: 'render',
render: () => (
<div class="layout-account-menu__identity">
<span>{this.t('account.eyebrow')}</span>
<strong>{this.getSigningCallback.name}</strong>
</div>
),
},
{ key: 'identity-divider', type: 'divider' },
...createAvatarOptions(this.t),
]}
onSelect={(key) => void avatarDropdownClick(key)}
trigger="click"
>
<AppAvatar
avatarSize={30}
cursor="pointer"
aria-label={this.t<string>('account.menu', {
name: this.getSigningCallback.name,
})}
aria-haspopup="menu"
aria-expanded={this.accountMenuShown}
spaceSize={[8, 0]}
class={[
'layout-header__account',
{ 'is-open': this.accountMenuShown },
]}
>
{{
suffix: () => (
<RIcon
class="layout-header__account-chevron"
name="directional/expanded"
size={14}
/>
),
}}
</AppAvatar>
</NDropdown>
</NFlex>
</>
)
},
})

View File

@ -20,15 +20,64 @@
} }
.layout-breadcrumb, .layout-breadcrumb,
.layout-breadcrumb__current { .layout-breadcrumb__item {
min-inline-size: 0; min-inline-size: 0;
} }
.layout-breadcrumb__item {
display: inline-flex;
align-items: center;
gap: 5px;
max-inline-size: 100%;
}
.layout-breadcrumb__icon {
display: inline-flex;
flex: none;
place-items: center;
inline-size: 1em;
block-size: 1em;
img {
inline-size: 100%;
block-size: 100%;
object-fit: contain;
}
}
.layout-breadcrumb__current { .layout-breadcrumb__current {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 15px; font-size: 15px;
font-weight: 600; font-weight: 600;
color: var(--r-text); color: var(--r-text);
} }
.layout-breadcrumb__current .layout-breadcrumb__label {
min-inline-size: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.layout-breadcrumb__trigger {
display: inline-flex;
align-items: center;
gap: 4px;
max-inline-size: 100%;
padding: 2px 4px;
border: 0;
border-radius: var(--r-control-radius);
color: var(--r-text-secondary);
background: transparent;
font: inherit;
cursor: pointer;
&:hover,
&[aria-expanded='true'] {
color: var(--r-text);
background: var(--r-surface-hover);
}
&:focus-visible {
outline: 2px solid var(--r-theme-primary-color);
}
}

View File

@ -1,7 +1,8 @@
import './index.scss' import './index.scss'
import { useDevice } from '@/hooks' import { useDevice } from '@/hooks'
import { useMenuActions, useMenuGetters } from '@/store' import { useMenuActions, useMenuGetters, useSettingGetters } from '@/store'
import type { AppMenuOption } from '@/types' import type { AppMenuOption } from '@/types'
import { RIcon } from '@ray-template/ui/icon'
import { NBreadcrumb, NBreadcrumbItem, NDropdown } from 'naive-ui' import { NBreadcrumb, NBreadcrumbItem, NDropdown } from 'naive-ui'
import type { DropdownOption } from 'naive-ui' import type { DropdownOption } from 'naive-ui'
import { TransitionGroup } from 'vue' import { TransitionGroup } from 'vue'
@ -11,75 +12,130 @@ export default defineComponent({
setup() { setup() {
const { changeMenuModelValue } = useMenuActions() const { changeMenuModelValue } = useMenuActions()
const { getBreadcrumbOptions } = useMenuGetters() const { getBreadcrumbOptions } = useMenuGetters()
const { getBreadcrumbIcon, getBreadcrumbIconFallback } = useSettingGetters()
const { isTabletOrSmaller } = useDevice() const { isTabletOrSmaller } = useDevice()
const expanded = ref<string>()
const setExpanded = (path: string, open: boolean) => {
if (open) expanded.value = path
else if (expanded.value === path) expanded.value = void 0
}
const dropdownSelect = (key: string | number, option: DropdownOption) => { const dropdownSelect = (key: string | number, option: DropdownOption) => {
expanded.value = void 0
changeMenuModelValue(key, option as unknown as AppMenuOption) changeMenuModelValue(key, option as unknown as AppMenuOption)
} }
/** const renderIcon = (option: Pick<AppMenuOption, 'icon'>) => {
* if (!getBreadcrumbIcon.value) return null
* @param option bread option
*
* 点击面包屑,如果包含子集,则允许点击更新页面
*/
const breadcrumbItemClick = (option: AppMenuOption) => {
if (!option.children?.length) {
const { meta = {} } = option
if (!meta.sameLevel) { const icon =
changeMenuModelValue(option.fullPath, option) option.icon?.() ??
} (getBreadcrumbIconFallback.value ? (
} <RIcon name="navigation/window" size="1em" />
} ) : null)
return { return (
getBreadcrumbOptions, icon && (
dropdownSelect, <span class="layout-breadcrumb__icon" aria-hidden="true">
breadcrumbItemClick, {icon}
isTabletOrSmaller,
}
},
render() {
const { isTabletOrSmaller, getBreadcrumbOptions } = this
const { dropdownSelect, breadcrumbItemClick } = this
return isTabletOrSmaller ? (
<span class="layout-breadcrumb__current" aria-current="page">
{getBreadcrumbOptions.at(-1)?.breadcrumbLabel}
</span> </span>
) : ( )
<NBreadcrumb class="layout-breadcrumb"> )
<TransitionGroup tag="li" name="breadcrumb" appear> }
{getBreadcrumbOptions.map((curr) => (
<NBreadcrumbItem const renderLabel = (
key={curr.fullPath} option: AppMenuOption,
onClick={breadcrumbItemClick.bind(this, curr)} current: boolean,
compact = false,
) => (
<span
class={[
'layout-breadcrumb__item',
{ 'layout-breadcrumb__current': compact },
]}
aria-current={current ? 'page' : void 0}
> >
{renderIcon(option)}
<span class="layout-breadcrumb__label">
{!compact && typeof option.label === 'function'
? option.label()
: option.breadcrumbLabel}
</span>
</span>
)
return () => {
const trail = getBreadcrumbOptions.value
const current = trail.at(-1)
if (isTabletOrSmaller.value)
return current && renderLabel(current, true, true)
return (
<NBreadcrumb class="layout-breadcrumb">
<TransitionGroup name="breadcrumb" appear>
{trail.map((option) => (
<NBreadcrumbItem key={option.fullPath} clickable={false}>
{option.children && option.children.length > 1 ? (
<NDropdown <NDropdown
trigger="hover"
show={expanded.value === option.fullPath}
onUpdateShow={(show) => setExpanded(option.fullPath, show)}
labelField="breadcrumbLabel" labelField="breadcrumbLabel"
keyField="fullPath" keyField="fullPath"
options={ options={option.children}
curr.children && curr.children?.length > 1 renderIcon={renderIcon}
? curr.children onSelect={dropdownSelect}
: []
}
onSelect={dropdownSelect.bind(this)}
> >
{{ <button
default: () => ( type="button"
<span> class="layout-breadcrumb__trigger"
{curr.label && typeof curr.label === 'function' aria-haspopup="menu"
? curr.label() aria-expanded={expanded.value === option.fullPath}
: curr.breadcrumbLabel} onClick={() =>
</span> setExpanded(
), option.fullPath,
expanded.value !== option.fullPath,
)
}
onKeydown={(event) => {
if (event.key === 'Tab')
setExpanded(option.fullPath, false)
if (
event.key === 'ArrowDown' &&
expanded.value !== option.fullPath
) {
event.preventDefault()
event.stopPropagation()
setExpanded(option.fullPath, true)
}
}} }}
>
{renderLabel(option, option === current)}
<RIcon name="directional/expanded" size="0.85em" />
</button>
</NDropdown> </NDropdown>
) : option !== current &&
!option.children?.length &&
!option.meta.sameLevel ? (
<button
type="button"
class="layout-breadcrumb__trigger"
onClick={() =>
changeMenuModelValue(option.fullPath, option)
}
>
{renderLabel(option, false)}
</button>
) : (
renderLabel(option, option === current)
)}
</NBreadcrumbItem> </NBreadcrumbItem>
))} ))}
</TransitionGroup> </TransitionGroup>
</NBreadcrumb> </NBreadcrumb>
) )
}
}, },
}) })

View File

@ -1,7 +1,7 @@
import { useI18n, useTheme } from '@/hooks' import { useI18n, useTheme } from '@/hooks'
import { useSettingGetters } from '@/store' import { useSettingGetters } from '@/store'
import { RIcon } from '@ray-template/ui/icon' import { RIcon } from '@ray-template/ui/icon'
import { NSwitch, NTooltip } from 'naive-ui' import { NFlex, NSwitch } from 'naive-ui'
export default defineComponent({ export default defineComponent({
name: 'ThemeSwitch', name: 'ThemeSwitch',
@ -11,9 +11,7 @@ export default defineComponent({
const { lightTheme, darkTheme } = useTheme() const { lightTheme, darkTheme } = useTheme()
return () => ( return () => (
<NTooltip> <NFlex align="center" wrap={false} size={6}>
{{
trigger: () => (
<NSwitch <NSwitch
value={getAppTheme.value} value={getAppTheme.value}
aria-label={t('theme.darkMode')} aria-label={t('theme.darkMode')}
@ -22,14 +20,12 @@ export default defineComponent({
{{ {{
'checked-icon': () => <RIcon name="system/dark" size={14} />, 'checked-icon': () => <RIcon name="system/dark" size={14} />,
'unchecked-icon': () => <RIcon name="system/light" size={14} />, 'unchecked-icon': () => <RIcon name="system/light" size={14} />,
checked: () => t('theme.dark'),
unchecked: () => t('theme.light'),
}} }}
</NSwitch> </NSwitch>
), <span aria-hidden="true">
default: () => t(getAppTheme.value ? 'theme.dark' : 'theme.light'), {t(getAppTheme.value ? 'theme.dark' : 'theme.light')}
}} </span>
</NTooltip> </NFlex>
) )
}, },
}) })

View File

@ -7,7 +7,6 @@ import type { SettingState } from '@/store/modules/setting/types'
import { downloadAnyFile } from '@/utils/files' import { downloadAnyFile } from '@/utils/files'
import { navigateHorizontalChoice } from '@ray-template/composables/element' import { navigateHorizontalChoice } from '@ray-template/composables/element'
import { RIcon } from '@ray-template/ui/icon' import { RIcon } from '@ray-template/ui/icon'
import { useModal } from '@ray-template/ui/modal'
import { cloneDeep, forIn } from 'lodash-es' import { cloneDeep, forIn } from 'lodash-es'
import { import {
drawerProps, drawerProps,
@ -16,6 +15,7 @@ import {
NDrawerContent, NDrawerContent,
NTab, NTab,
NTabs, NTabs,
useModal,
} from 'naive-ui' } from 'naive-ui'
import Appearance from './segment-views/Appearance' import Appearance from './segment-views/Appearance'
import Common from './segment-views/Common' import Common from './segment-views/Common'
@ -113,7 +113,7 @@ export default defineComponent({
content: t('resetDescription'), content: t('resetDescription'),
positiveText: t('reset'), positiveText: t('reset'),
negativeText: t('cancel'), negativeText: t('cancel'),
dialogWidth: 'min(420px, calc(100vw - 32px))', style: { width: 'min(420px, calc(100vw - 32px))' },
onPositiveClick: () => { onPositiveClick: () => {
forIn(cloneDeep(getDefaultSettingConfig()), (value, key) => { forIn(cloneDeep(getDefaultSettingConfig()), (value, key) => {
updateSettingState(key as keyof SettingState, value) updateSettingState(key as keyof SettingState, value)

View File

@ -38,7 +38,13 @@ export default defineComponent({
getDrawerPlacement, getDrawerPlacement,
getContentTransition, getContentTransition,
getMenuTagSwitch, getMenuTagSwitch,
getMenuTagRound,
getMenuTagTop,
getMenuTagFixed,
getMenuTagDrag,
getBreadcrumbSwitch, getBreadcrumbSwitch,
getBreadcrumbIcon,
getBreadcrumbIconFallback,
getCopyrightSwitch, getCopyrightSwitch,
getColorWeakness, getColorWeakness,
} = useSettingGetters() } = useSettingGetters()
@ -78,7 +84,13 @@ export default defineComponent({
}) })
const switches = [ const switches = [
['breadcrumbSwitch', getBreadcrumbSwitch], ['breadcrumbSwitch', getBreadcrumbSwitch],
['breadcrumbIcon', getBreadcrumbIcon],
['breadcrumbIconFallback', getBreadcrumbIconFallback],
['menuTagSwitch', getMenuTagSwitch], ['menuTagSwitch', getMenuTagSwitch],
['menuTagRound', getMenuTagRound],
['menuTagTop', getMenuTagTop],
['menuTagFixed', getMenuTagFixed],
['menuTagDrag', getMenuTagDrag],
['copyrightSwitch', getCopyrightSwitch], ['copyrightSwitch', getCopyrightSwitch],
['colorWeakness', getColorWeakness], ['colorWeakness', getColorWeakness],
] as const ] as const

View File

@ -1,5 +1,5 @@
import { LAYOUT_SIDER_REF } from '@/app-config'
import { useDevice, useI18n, useSiderScroll } from '@/hooks' import { useDevice, useI18n, useSiderScroll } from '@/hooks'
import { findMenuRoot } from '@/layout/navigation'
import { import {
useMenuActions, useMenuActions,
useMenuGetters, useMenuGetters,
@ -52,28 +52,17 @@ export default defineComponent({
name: 'SegmentViewsCustomMenu', name: 'SegmentViewsCustomMenu',
setup() { setup() {
const { t } = useI18n('preferences') const { t } = useI18n('preferences')
const { getMenuConfig, getLayoutConfig } = useSettingGetters() const { getMenuConfig } = useSettingGetters()
const { getCollapsed, getMenuOptions, getMenuKey } = useMenuGetters() const { getCollapsed } = useMenuGetters()
const { updateSettingState } = useSettingActions() const { updateSettingState } = useSettingActions()
const { setupAppMenu, collapsedMenu } = useMenuActions() const { setupAppMenu, collapsedMenu } = useMenuActions()
const { isTabletOrSmaller } = useDevice() const { isTabletOrSmaller } = useDevice()
const scrollSider = useSiderScroll() const scrollSider = useSiderScroll()
const refreshing = ref(false) const refreshing = ref(false)
const id = useId() const id = useId()
const hasDesktopSidebar = computed(() => { const hasDesktopSidebar = computed(
if (isTabletOrSmaller.value) return false () => !isTabletOrSmaller.value && !!LAYOUT_SIDER_REF.value,
)
const { mode } = getLayoutConfig.value
if (mode === 'side' || mode === 'right') return true
if (mode === 'top') return false
return !!findMenuRoot(
getMenuOptions.value,
String(getMenuKey.value),
)?.children?.some((option) => option.show !== false)
})
const refreshMenu = async () => { const refreshMenu = async () => {
if (refreshing.value) return if (refreshing.value) return

View File

@ -3,7 +3,6 @@
padding-inline: $layoutRouterViewContainer; padding-inline: $layoutRouterViewContainer;
display: flex; display: flex;
align-items: center; align-items: center;
border-block-end: 1px solid var(--r-line);
> .layout-header__method { > .layout-header__method {
inline-size: 100%; inline-size: 100%;
@ -20,13 +19,16 @@
&__actions { &__actions {
flex-shrink: 0; flex-shrink: 0;
} }
}
.layout-header,
.r-layout-row {
.n-breadcrumb { .n-breadcrumb {
font-size: 13px; font-size: 13px;
} }
.override-button__layout, .override-button__layout,
&__menu-toggle { .layout-header__menu-toggle {
inline-size: 36px; inline-size: 36px;
padding: 0; padding: 0;
border-radius: var(--r-control-radius); border-radius: var(--r-control-radius);
@ -51,7 +53,7 @@
} }
} }
&__account { .layout-header__account {
block-size: 40px; block-size: 40px;
margin-inline-start: 8px; margin-inline-start: 8px;
padding-inline: 8px; padding-inline: 8px;
@ -67,12 +69,12 @@
} }
} }
&__account-chevron { .layout-header__account-chevron {
color: var(--r-text-muted); color: var(--r-text-muted);
transition: transform 160ms ease; transition: transform 160ms ease;
} }
&__account.is-open &__account-chevron { .layout-header__account.is-open .layout-header__account-chevron {
transform: rotate(180deg); transform: rotate(180deg);
} }
} }
@ -110,14 +112,14 @@
} }
.override-button__layout, .override-button__layout,
&__menu-toggle, .layout-header__menu-toggle,
&__account { .layout-header__account {
inline-size: 44px; inline-size: 44px;
block-size: 44px; block-size: 44px;
padding: 0; padding: 0;
} }
&__account { .layout-header__account {
margin-inline-start: 0; margin-inline-start: 0;
.r-app-avatar__name, .r-app-avatar__name,

View File

@ -1,136 +1,25 @@
import { useRuntimeActions, useRuntimeGetters } from '@/store'
import './index.scss' import './index.scss'
import AppAvatar from '@/app-components/app/AppAvatar'
import { LOCAL_OPTIONS } from '@/app-config'
import { useDevice, useI18n } from '@/hooks' import { useDevice, useI18n } from '@/hooks'
import { import { useRuntimeActions, useRuntimeGetters } from '@/store'
useSettingActions,
useSettingGetters,
useSigningGetters,
} from '@/store'
import { RIcon } from '@ray-template/ui/icon' import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex, NLayoutHeader } from 'naive-ui' import { NButton, NFlex, NLayoutHeader } from 'naive-ui'
import { useFullscreen } from 'vue-hooks-plus' import type { PropType } from 'vue'
import { import LayoutBreadcrumb from '../../blocks/LayoutBreadcrumb'
Breadcrumb, import HeaderActions from './HeaderActions'
GlobalSearch,
GlobalSearchButton,
SettingDrawer,
TooltipIcon,
} from './components'
import {
avatarDropdownClick,
createAvatarOptions,
createLeftIconOptions,
createRightIconOptions,
} from './shared'
import type { IconEventMapOptions } from './type'
export default defineComponent({ export default defineComponent({
name: 'AppSiderBar', name: 'LayoutHeader',
setup() { props: {
// 获取 setting 相关值 onOpenSettings: { type: Function as PropType<() => void>, default: void 0 },
const { updateLocale, updateSettingState } = useSettingActions() },
const { t } = useI18n() setup(props, { slots }) {
// 获取全屏相关方法 const { t } = useI18n('layout')
const [isFullscreen, { toggleFullscreen, isEnabled }] = useFullscreen(
document.getElementsByTagName('html')[0],
)
// 获取设置相关方法
const { getDrawerPlacement, getBreadcrumbSwitch } = useSettingGetters()
// 是否显示设置抽屉
const showSettings = ref(false)
const accountMenuShown = ref(false)
const { getSigningCallback } = useSigningGetters()
// 是否展示全局搜索
const globalSearchShown = ref(false)
// 当前是否为平板或者更小的设备
const { isTabletOrSmaller } = useDevice() const { isTabletOrSmaller } = useDevice()
// 获取全局 drawer 的值 const { globalDrawerValue } = useRuntimeGetters()
const globalDrawerValue = useRuntimeGetters().globalDrawerValue const { setRuntimeState } = useRuntimeActions()
/** return () => (
*
* @description
* 顶部左边操作栏。
*/
const leftIconOptions = computed(() =>
createLeftIconOptions({
isFullscreen,
isTabletOrSmaller,
}),
)
/**
*
* @description
* 顶部右边提示框操作栏。
*/
const rightTooltipIconOptions = computed(() =>
createRightIconOptions({
isFullscreen,
isTabletOrSmaller,
}),
)
const iconEventMap: IconEventMapOptions = {
search: () => {
globalSearchShown.value = true
},
setting: () => {
showSettings.value = true
},
github: () => {
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
},
fullscreen: () => {
if (!isEnabled) {
window.$message.warning(t('globalMessage.isEnabledFullscreen'))
}
toggleFullscreen()
},
lock: () => {
updateSettingState('lockScreenSwitch', true)
},
menu: () => {
useRuntimeActions().setRuntimeState(
'globalDrawerValue',
!globalDrawerValue.value,
)
},
}
const toolIconClick = (key: keyof typeof iconEventMap) => {
iconEventMap[key]?.()
}
return {
t,
isFullscreen,
leftIconOptions,
rightTooltipIconOptions,
toolIconClick,
showSettings,
updateLocale,
getDrawerPlacement,
getBreadcrumbSwitch,
globalSearchShown,
isTabletOrSmaller,
accountMenuShown,
getSigningCallback,
}
},
render() {
const {
rightTooltipIconOptions,
leftIconOptions,
getDrawerPlacement,
getBreadcrumbSwitch,
} = this
const { toolIconClick, updateLocale } = this
return (
<NLayoutHeader class="layout-header"> <NLayoutHeader class="layout-header">
<GlobalSearch v-model:show={this.globalSearchShown} />
<NFlex <NFlex
class="layout-header__method" class="layout-header__method"
align="center" align="center"
@ -140,143 +29,29 @@ export default defineComponent({
<NFlex <NFlex
class="layout-header__navigation" class="layout-header__navigation"
align="center" align="center"
size={this.isTabletOrSmaller ? 4 : 12} size={isTabletOrSmaller.value ? 4 : 12}
wrap={false} wrap={false}
> >
{leftIconOptions.map((curr) => ( {isTabletOrSmaller.value && (
<NButton <NButton
quaternary quaternary
class="layout-header__menu-toggle" class="layout-header__menu-toggle"
key={curr.name} aria-label={t('toggleMenu')}
aria-label={this.t<string>('layout.toggleMenu')} onClick={() =>
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)} setRuntimeState('globalDrawerValue', !globalDrawerValue.value)
>
<TooltipIcon
iconName={curr.name}
tooltipText={
isRef(curr.tooltip) ? curr.tooltip.value : curr.tooltip
} }
customClassName={curr.iconClass} >
/> <RIcon name="navigation/menu" size={18} />
</NButton> </NButton>
))} )}
{getBreadcrumbSwitch ? <Breadcrumb /> : null} {slots.default ? slots.default() : <LayoutBreadcrumb />}
</NFlex> </NFlex>
<NFlex {slots.actions ? (
class="layout-header__actions" slots.actions()
justify="end"
align="center"
size={[4, 0]}
wrap={false}
>
{this.isTabletOrSmaller ? (
<NButton
quaternary
class="override-button__layout"
aria-label={this.t<string>('headerTooltip.Search')}
onClick={() => {
this.globalSearchShown = true
}}
>
<RIcon name="action/search" size={20} />
</NButton>
) : ( ) : (
<GlobalSearchButton <HeaderActions onOpenSettings={props.onOpenSettings} />
onClick={(e) => {
e.stopPropagation()
this.globalSearchShown = true
}}
/>
)} )}
{rightTooltipIconOptions.map((curr) => (
<NButton
class="override-button__layout"
quaternary
size="medium"
key={curr.eventKey ?? curr.name}
aria-label={this.t<string>(
curr.eventKey === 'setting'
? 'headerTooltip.Setting'
: curr.eventKey === 'github'
? 'headerTooltip.Github'
: this.isFullscreen
? 'headerTooltip.CancelFullScreen'
: 'headerTooltip.FullScreen',
)}
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)}
>
<RIcon name={curr.name} size={20} />
</NButton>
))}
<NDropdown
options={LOCAL_OPTIONS}
onSelect={(key: string | number) => updateLocale(String(key))}
trigger="click"
>
<NButton
quaternary
aria-label={this.t<string>('layout.language')}
class="override-button__layout"
>
<RIcon name="system/language" size={20} />
</NButton>
</NDropdown>
<NDropdown
class="layout-account-menu"
placement="bottom-end"
show={this.accountMenuShown}
onUpdateShow={(show) => {
this.accountMenuShown = show
}}
options={[
{
key: 'identity',
type: 'render',
render: () => (
<div class="layout-account-menu__identity">
<span>{this.t('account.eyebrow')}</span>
<strong>{this.getSigningCallback.name}</strong>
</div>
),
},
{ key: 'identity-divider', type: 'divider' },
...createAvatarOptions(this.t),
]}
onSelect={(key) => void avatarDropdownClick(key)}
trigger="click"
>
<AppAvatar
avatarSize={30}
cursor="pointer"
aria-label={this.t<string>('account.menu', {
name: this.getSigningCallback.name,
})}
aria-haspopup="menu"
aria-expanded={this.accountMenuShown}
spaceSize={[8, 0]}
class={[
'layout-header__account',
{ 'is-open': this.accountMenuShown },
]}
>
{{
suffix: () => (
<RIcon
class="layout-header__account-chevron"
name="directional/expanded"
size={14}
/>
),
}}
</AppAvatar>
</NDropdown>
</NFlex> </NFlex>
</NFlex>
<SettingDrawer
v-model:show={this.showSettings}
placement={getDrawerPlacement}
/>
</NLayoutHeader> </NLayoutHeader>
) )
}, },

View File

@ -5,20 +5,18 @@ import SiderBarLogo from '../Menu/components/SiderBarLogo'
export default defineComponent({ export default defineComponent({
name: 'TopNavigation', name: 'TopNavigation',
setup() { props: { grouped: Boolean },
setup(props) {
const { t } = useI18n() const { t } = useI18n()
const { getMenuOptions, getMenuKey } = useMenuGetters() const { getMenuOptions, getMenuKey } = useMenuGetters()
const { getLayoutConfig, getMenuConfig } = useSettingGetters() const { getMenuConfig } = useSettingGetters()
const { changeMenuModelValue } = useMenuActions() const { changeMenuModelValue } = useMenuActions()
return () => ( return () => (
<ShellTopNavigation <ShellTopNavigation
items={getMenuOptions.value} items={getMenuOptions.value}
active={getMenuKey.value} active={getMenuKey.value}
grouped={ grouped={props.grouped}
getLayoutConfig.value.mode === 'mixed' ||
getLayoutConfig.value.mode === 'split'
}
label={t('layout.navigation')} label={t('layout.navigation')}
iconSize={getMenuConfig.value.iconSize} iconSize={getMenuConfig.value.iconSize}
select={(option) => changeMenuModelValue(option.fullPath, option)} select={(option) => changeMenuModelValue(option.fullPath, option)}

View File

@ -3,7 +3,6 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
border-top: 1px solid var(--r-line);
background: var(--r-surface); background: var(--r-surface);
color: var(--r-text-muted); color: var(--r-text-muted);
font-size: 12px; font-size: 12px;

View File

@ -1,15 +1,16 @@
import SiderBar from '@/layout/components/SiderBar' import SiderBar from '@/layout/components/SiderBar'
import { NFlex } from 'naive-ui' import { NFlex } from 'naive-ui'
import type { PropType } from 'vue'
export default defineComponent({ export default defineComponent({
name: 'LayoutHeaderWrapper', name: 'LayoutHeaderWrapper',
setup() { props: {
return {} onOpenSettings: { type: Function as PropType<() => void>, required: true },
}, },
render() { render() {
return ( return (
<NFlex size={[0, 0]}> <NFlex size={[0, 0]}>
<SiderBar /> <SiderBar onOpenSettings={this.onOpenSettings} />
</NFlex> </NFlex>
) )
}, },

View File

@ -0,0 +1,19 @@
import { builtinLayoutPreviews } from '@ray-template/admin-shell'
import type { LayoutMode } from '@ray-template/admin-shell'
import { createBuiltinLayout } from './renderers/BuiltinLayout'
import type { LayoutDefinition } from './types'
export function defineBuiltinLayout(
id: LayoutMode,
label: LayoutDefinition['label'],
regions: Parameters<typeof createBuiltinLayout>[0],
): LayoutDefinition {
return {
id,
label,
component: createBuiltinLayout(regions),
sharedFrame: true,
preview: builtinLayoutPreviews[id],
fallbackMode: id,
}
}

View File

@ -0,0 +1,15 @@
import CustomTopLayout from '../renderers/CustomTopLayout'
import type { LayoutDefinition } from '../types'
export default {
id: 'custom-top',
label: { 'zh-CN': '双行顶部', 'en-US': 'Two-row top' },
component: CustomTopLayout,
sharedFrame: true,
preview: {
rows: [['tabs', 'actions'], ['navigation']],
sidebar: 'none',
footer: true,
},
fallbackMode: 'top',
} satisfies LayoutDefinition

View File

@ -0,0 +1,10 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'mixed',
{ 'zh-CN': '混合导航', 'en-US': 'Mixed' },
{
topNavigation: 'groups',
sidebar: 'children',
},
)

View File

@ -0,0 +1,7 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'right',
{ 'zh-CN': '右侧导航', 'en-US': 'Right sidebar' },
{ sidebar: 'right' },
)

View File

@ -0,0 +1,7 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'side',
{ 'zh-CN': '侧边导航', 'en-US': 'Sidebar' },
{ sidebar: 'left' },
)

View File

@ -0,0 +1,11 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'split',
{ 'zh-CN': '通栏分组', 'en-US': 'Wide top' },
{
topNavigation: 'groups',
sidebar: 'children',
wideHeader: true,
},
)

View File

@ -0,0 +1,7 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'top',
{ 'zh-CN': '顶部导航', 'en-US': 'Top' },
{ topNavigation: 'all' },
)

View File

@ -0,0 +1,176 @@
import * as v from 'valibot'
import { layoutIdMaxLength, layoutIdPattern } from './id.ts'
import { layoutBlocks, layoutRowsSchema, sidebarSchema } from './preview.ts'
export const layoutDefinitionsDirectory = 'apps/admin/src/layout/definitions'
export const layoutWriteEndpoint = '/__ray-layout-lab/write'
export { layoutBlocks }
export type LayoutBlock = (typeof layoutBlocks)[number]
const idSchema = v.pipe(
v.string(),
v.maxLength(layoutIdMaxLength),
v.regex(layoutIdPattern),
)
const layoutDesignSchema = v.pipe(
v.strictObject({
id: idSchema,
label: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80)),
selectable: v.boolean(),
autoRegister: v.optional(v.boolean(), true),
sidebar: v.optional(sidebarSchema, 'none'),
footer: v.optional(v.boolean(), false),
rows: layoutRowsSchema,
bottomRows: v.optional(layoutRowsSchema, []),
}),
v.check(({ rows, bottomRows }) => {
const blocks = [...rows.flat(), ...bottomRows.flat()]
return new Set(blocks).size === blocks.length
}),
)
export type LayoutDesign = v.InferInput<typeof layoutDesignSchema>
const components = {
actions: 'LayoutHeaderActions',
breadcrumb: 'LayoutBreadcrumb',
navigation: 'LayoutTopNavigation',
tabs: 'LayoutTabs',
} satisfies Record<LayoutBlock, string>
export function layoutFileName(id: string) {
return `${v.parse(idSchema, id)}.layout.tsx`
}
export function parseLayoutDesign(input: unknown) {
return v.parse(layoutDesignSchema, input)
}
function labelLiteral(value: string) {
// 模板字符串在长名称与宽字符下都保持单行;插值符号和不可见字符需要显式转义。
const escaped = JSON.stringify(value)
.slice(1, -1)
.replaceAll('\\"', '"')
.replaceAll('`', '\\`')
.replaceAll('${', '\\${')
.replace(
/[^\S ]|[\p{Cc}\p{Cf}]/gu,
(char) => `\\u{${char.codePointAt(0)!.toString(16)}}`,
)
return '`' + escaped + '`'
}
export function generateLayoutSource(input: unknown): string {
const design = parseLayoutDesign(input)
const placedBlocks = [...design.rows.flat(), ...design.bottomRows.flat()]
const imports = [
'LayoutFrame',
'LayoutOutlet',
...(placedBlocks.length ? ['LayoutRow'] : []),
...(design.sidebar === 'none' ? [] : ['LayoutNavigation']),
...(design.footer ? ['LayoutFooter'] : []),
...placedBlocks.map((block) => components[block]),
].sort()
const symbols = imports.join(', ')
const compactImport = `import { ${symbols} } from '@/layout/blocks'`
const blockImport =
compactImport.length <= 80
? compactImport
: `import {\n${imports.map((item) => ` ${item},`).join('\n')}\n} from '@/layout/blocks'`
const name =
design.id
.split('-')
.map((part) => part[0].toUpperCase() + part.slice(1))
.join('') + 'Layout'
const slots: string[] = []
const rowRegions = [
['header', design.rows],
['bottom', design.bottomRows],
] as const
for (const [region, rows] of rowRegions) {
if (!rows.length) continue
const markup = rows
.map((row) =>
[
' <LayoutRow>',
...row.map((block) => ` <${components[block]} />`),
' </LayoutRow>',
].join('\n'),
)
.join('\n')
slots.push(` ${region}: () => (
<>
${markup}
</>
),`)
}
let frameAttributes = ''
let fallbackMode = 'top'
if (design.sidebar !== 'none') {
frameAttributes = ` sidebarPlacement="${design.sidebar}"`
fallbackMode = design.sidebar === 'right' ? 'right' : 'side'
const end = design.sidebar === 'right' ? ' end' : ''
slots.push(` sidebar: () => <LayoutNavigation${end} />,`)
}
if (design.footer) slots.push(' footer: () => <LayoutFooter />,')
slots.push(' default: () => <LayoutOutlet />,')
const rowLiteral = (rows: LayoutBlock[][]) => {
const lines = rows.map((row) => {
const blocks = row.map((block) => `'${block}'`)
return `[${blocks.join(', ')}]`
})
return `[${lines.join(', ')}]`
}
const preview = [
` rows: ${rowLiteral(design.rows)},`,
...(design.bottomRows.length
? [` bottomRows: ${rowLiteral(design.bottomRows)},`]
: []),
` sidebar: '${design.sidebar}',`,
` footer: ${design.footer},`,
].join('\n')
return `${blockImport}
import type { LayoutDefinition } from '@/layout/types'
import { defineComponent } from 'vue'
export default {
id: '${design.id}',
label: ${labelLiteral(design.label)},
selectable: ${design.selectable},
autoRegister: ${design.autoRegister},
sharedFrame: true,
fallbackMode: '${fallbackMode}',
preview: {
${preview}
},
component: defineComponent({
name: '${name}',
setup() {
return () => (
<LayoutFrame${frameAttributes}>
{{
${slots.join('\n')}
}}
</LayoutFrame>
)
},
}),
} satisfies LayoutDefinition
`
}

View File

@ -0,0 +1,103 @@
import { LAYOUT_MODES } from '@ray-template/admin-shell'
import { shallowRef, toRaw } from 'vue'
import type { ShallowRef } from 'vue'
import { isLayoutId } from './id'
import { readLayoutPreview } from './preview'
import type { LayoutDefinition } from './types'
const validText = (value: unknown) =>
typeof value === 'string' && value.trim().length > 0
export function layoutEntry(definition: LayoutDefinition): LayoutDefinition {
if (!isLayoutId(definition?.id)) throw new TypeError('Invalid layout ID')
const { id, label, component, fallbackMode, autoRegister, selectable } =
definition
if (
!validText(label) &&
!(
typeof label === 'object' &&
label &&
validText(label['zh-CN']) &&
validText(label['en-US'])
)
)
throw new TypeError(`Invalid label for layout "${id}"`)
if (
!component ||
(typeof component !== 'object' && typeof component !== 'function') ||
(fallbackMode !== void 0 && !LAYOUT_MODES.includes(fallbackMode)) ||
(autoRegister !== void 0 && typeof autoRegister !== 'boolean') ||
(definition.sharedFrame !== void 0 &&
typeof definition.sharedFrame !== 'boolean') ||
(selectable !== void 0 && typeof selectable !== 'boolean')
)
throw new TypeError(`Invalid layout definition "${id}"`)
return Object.freeze({
id,
label: typeof label === 'string' ? label : Object.freeze({ ...label }),
component: toRaw(component),
sharedFrame: definition.sharedFrame,
preview:
definition.preview === void 0
? void 0
: readLayoutPreview(definition.preview),
fallbackMode,
autoRegister,
get selectable() {
return definition.selectable
},
})
}
export function collectLayoutDefinitions(
modules: Record<string, LayoutDefinition>,
) {
const builtins = LAYOUT_MODES.map((id) => `./definitions/${id}.layout.ts`)
const paths = [
...builtins.filter((path) => Object.hasOwn(modules, path)),
...Object.keys(modules).filter((path) => !builtins.includes(path)),
]
const catalog = new Map<string, LayoutDefinition>()
for (const path of paths) {
const definition = modules[path]
if (definition?.autoRegister === false) continue
try {
const entry = layoutEntry(definition)
if (catalog.has(entry.id))
throw new Error(`Duplicate layout ID "${entry.id}"`)
catalog.set(entry.id, entry)
} catch (error) {
console.error(`[useLayout] ${path}`, error)
}
}
return catalog
}
const catalog = collectLayoutDefinitions(
import.meta.glob<LayoutDefinition>('./definitions/*.layout.{js,ts,jsx,tsx}', {
eager: true,
import: 'default',
}),
)
// 文件增删会重载本模块。保留 ref,使现有 Pinia 实例和实验室无需重新挂载。
export const discoveredLayouts: ShallowRef<
ReadonlyMap<string, LayoutDefinition>
> = import.meta.hot?.data.discoveredLayouts ?? shallowRef(catalog)
discoveredLayouts.value = catalog
if (import.meta.hot) {
import.meta.hot.data.discoveredLayouts = discoveredLayouts
import.meta.hot.accept()
}

View File

@ -0,0 +1,25 @@
import type {
Component,
InjectionKey,
Ref,
ShallowRef,
Slots,
VNode,
} from 'vue'
export type SharedFrameRenderer = () => VNode
export interface LayoutHost {
frameRoot: Readonly<Ref<HTMLElement | null>>
sharedFrame: ShallowRef<SharedFrameRenderer | undefined>
slots: Slots
draftRenderer: ShallowRef<Component | undefined>
deferredFromId: Readonly<Ref<string | undefined>>
openSettings: () => void
addOutlet: (outlet: HTMLElement) => void
removeOutlet: (outlet: HTMLElement) => void
}
export const layoutHostKey: InjectionKey<LayoutHost> = Symbol('LayoutHost')
export const layoutFrameKey: InjectionKey<boolean> = Symbol('LayoutFrame')

View File

@ -0,0 +1,10 @@
export const layoutIdPattern = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
export const layoutIdMaxLength = 64
export function isLayoutId(value: unknown): value is string {
return (
typeof value === 'string' &&
value.length <= layoutIdMaxLength &&
layoutIdPattern.test(value)
)
}

View File

@ -1,95 +1,325 @@
import { apiMockEnabled } from '@/api/admin/client' import { apiMockEnabled } from '@/api/admin/client'
import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar' import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar'
import UnlockScreen from '@/app-components/app/AppLockScreen/components/UnlockScreen' import UnlockScreen from '@/app-components/app/AppLockScreen/components/UnlockScreen'
import { LAYOUT_CONTENT_REF } from '@/app-config'
import { useDevice, useI18n, useMaximize } from '@/hooks' import { useDevice, useI18n, useMaximize } from '@/hooks'
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store' import { useSettingGetters } from '@/store'
import { AdminShell } from '@ray-template/admin-shell' import { LAYOUT_MODES } from '@ray-template/admin-shell'
import Menu from './components/Menu' import { Suspense, Teleport } from 'vue'
import TopNavigation from './components/TopNavigation' import type { Component } from 'vue'
import { import SharedFrame from './blocks/SharedFrame'
ContentWrapper, import SettingDrawer from './components/SiderBar/components/SettingDrawer'
FeatureWrapper, import ContentWrapper from './default/ContentWrapper'
FooterWrapper, import { layoutHostKey } from './host-context'
HeaderWrapper, import type { SharedFrameRenderer } from './host-context'
} from './default' import CompactLayout from './renderers/BuiltinLayout'
import ContentLoading from './default/ContentWrapper/ContentLoading' import LayoutPresentation, {
import { findMenuRoot } from './navigation' ignoreAbandonedLayoutErrors,
} from './renderers/LayoutPresentation'
import { useDeferredLayout } from './useDeferredLayout'
import { useLayout } from './useLayout'
export default defineComponent({ export default defineComponent({
name: 'RLayout', name: 'RLayout',
setup(_, { slots }) { inheritAttrs: false,
const { getMenuTagSwitch, getCopyrightSwitch, getLayoutConfig } = setup(_, { attrs, slots }) {
useSettingGetters() ignoreAbandonedLayoutErrors()
const { getMenuOptions, getMenuKey } = useMenuGetters() const { activeLayout, layouts, updateLayout } = useLayout()
const { const { getDrawerPlacement } = useSettingGetters()
globalMainLayoutLoad, const { isTabletOrSmaller } = useDevice()
layoutContentSpinning,
layoutContentMaximize,
layoutContentMaximizeStyle,
} = useRuntimeGetters()
const { maximize } = useMaximize() const { maximize } = useMaximize()
const { t } = useI18n('layout') const { t } = useI18n('layout')
const { isTabletOrSmaller } = useDevice()
const { getLockAppScreen } = useAppLockScreen() const { getLockAppScreen } = useAppLockScreen()
const mode = computed(() => const locked = computed(() => apiMockEnabled && getLockAppScreen())
isTabletOrSmaller.value ? 'side' : getLayoutConfig.value.mode, const settingsShown = ref(false)
const root = useTemplateRef<HTMLElement>('root')
const parking = useTemplateRef<HTMLElement>('parking')
const sharedFrame = shallowRef<SharedFrameRenderer>()
let settingsTrigger: HTMLElement | null = null
const openSettings = () => {
settingsTrigger =
document.activeElement instanceof HTMLElement
? document.activeElement
: null
settingsShown.value = true
}
const restoreSettingsFocus = () => {
const trigger =
settingsTrigger?.isConnected && settingsTrigger !== document.body
? settingsTrigger
: root.value?.querySelector<HTMLElement>('.layout-header__settings')
trigger?.focus({ preventScroll: true })
settingsTrigger = null
}
const emergency = ref(false)
const draftRenderer = shallowRef<Component>()
const compact = computed(() => isTabletOrSmaller.value || emergency.value)
const renderer = computed(() =>
compact.value
? CompactLayout
: (draftRenderer.value ?? activeLayout.value.component),
) )
const mixedChildren = computed( const requestedId = computed(() =>
() => compact.value
findMenuRoot( ? 'side'
getMenuOptions.value, : draftRenderer.value
String(getMenuKey.value), ? '_preview'
)?.children?.filter((option) => option.show !== false) ?? [], : activeLayout.value.id,
) )
const requested = computed(() => ({
id: requestedId.value,
renderer: renderer.value,
shared:
compact.value ||
!!draftRenderer.value ||
activeLayout.value.sharedFrame === true,
key: Symbol('LayoutPresentation'),
}))
let mountedPresentation: symbol | undefined
const outlets = new Set<HTMLElement>()
const target = shallowRef<HTMLElement>()
const page = document.createElement('div')
const { presentation, deferred, reconcile, guardPending, markMounted } =
useDeferredLayout(requested, page)
const renderedId = computed(() => presentation.value.id)
page.className = 'r-layout-outlet'
const placePage = (parent: HTMLElement) => {
if (page.parentElement === parent) return
if (page.isConnected && parent.isConnected && parent.moveBefore)
parent.moveBefore(page, null)
else parent.appendChild(page)
}
const rejected = new Set<string>()
let lastGood = 'side'
let disposed = false
let pending = false
let pendingFocus: HTMLElement | null = null
let pendingScroll:
{ container: HTMLElement; left: number; top: number } | undefined
const scrollContainer = () =>
target.value?.closest('.r-layout-content-scroll')?.parentElement
const capturePagePosition = () => {
if (
disposed ||
locked.value ||
!page.isConnected ||
!target.value?.contains(page)
)
return
const focused = document.activeElement
const container = scrollContainer()
if (focused instanceof HTMLElement && page.contains(focused))
pendingFocus = focused
if (!pendingScroll && container)
pendingScroll = {
container,
left: container.scrollLeft,
top: container.scrollTop,
}
}
const rejectLayout = (id: string, error: unknown) => {
if (disposed || locked.value || renderedId.value !== id || compact.value)
return
console.error(`[useLayout] Layout "${id}" could not be rendered.`, error)
if (draftRenderer.value) {
draftRenderer.value = void 0
return
}
rejected.add(id)
const fallback = [lastGood, ...LAYOUT_MODES].find(
(candidate) =>
!rejected.has(candidate) &&
layouts.value.some(
(item) => item.id === candidate && item.selectable !== false,
),
)
if (fallback) updateLayout(fallback)
else emergency.value = true
}
const checkOutlets = () => {
if (pending || disposed) return
pending = true
void nextTick(() => {
pending = false
if (
disposed ||
locked.value ||
mountedPresentation !== presentation.value.key
)
return
const activeOutlets = [...outlets].filter(
(outlet) =>
sharedFrame.value || !outlet.closest('[data-shared-layout-frame]'),
)
if (activeOutlets.length !== 1) {
rejectLayout(
renderedId.value,
'A layout must mount exactly one LayoutOutlet.',
)
return
}
const outlet = activeOutlets[0]
placePage(outlet)
target.value = outlet
markMounted()
if (!compact.value && !draftRenderer.value) {
lastGood = renderedId.value
rejected.clear()
}
if (pendingScroll) {
const container = scrollContainer()
if (container && container !== pendingScroll.container) {
container.scrollLeft = pendingScroll.left
container.scrollTop = pendingScroll.top
}
pendingScroll = void 0
}
if (
pendingFocus?.isConnected &&
(document.activeElement === document.body ||
document.activeElement ===
outlet
.closest('.r-layout-content-viewport')
?.querySelector(':scope > .r-layout-content-restore__button'))
)
pendingFocus.focus({ preventScroll: true })
pendingFocus = null
})
}
provide(layoutHostKey, {
frameRoot: root,
sharedFrame,
deferredFromId: computed(() =>
deferred.value ? renderedId.value : void 0,
),
slots,
draftRenderer,
openSettings,
addOutlet: (element) => {
outlets.add(element)
checkOutlets()
},
removeOutlet: (element) => {
if (
!disposed &&
!locked.value &&
page.parentElement === element &&
parking.value
) {
capturePagePosition()
placePage(parking.value)
}
outlets.delete(element)
checkOutlets()
},
})
watch(
activeLayout,
() => {
emergency.value = false
draftRenderer.value = void 0
},
{ flush: 'sync' },
)
watch(locked, (value) => {
if (value) {
mountedPresentation = void 0
maximize(false)
settingsShown.value = false
pendingScroll = void 0
pendingFocus = null
target.value = void 0
void nextTick(reconcile)
}
})
onBeforeUnmount(() => {
disposed = true
maximize(false)
})
return () => { return () => {
if (apiMockEnabled && getLockAppScreen()) return <UnlockScreen /> if (locked.value) return <UnlockScreen {...attrs} />
const grouped = mode.value === 'mixed' || mode.value === 'split' const attempt = presentation.value
const id = attempt.id
return ( return (
<AdminShell <div ref="root" class="r-layout-host" data-layout={id}>
layout={getLayoutConfig.value} <Suspense onPending={guardPending}>
mode={mode.value} <LayoutPresentation
groupedSidebar={mixedChildren.value.length > 0} {...attrs}
showTabs={getMenuTagSwitch.value} key={attempt.key}
showFooter={getCopyrightSwitch.value} renderer={attempt.renderer}
busy={ onVnodeBeforeUnmount={() => {
!slots.default && if (mountedPresentation === attempt.key) capturePagePosition()
(!globalMainLayoutLoad.value || layoutContentSpinning.value)
}
maximized={layoutContentMaximize.value}
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restore={() => maximize(false)}
restoreLabel={t('restore')}
>
{{
header:
slots.header ??
(() => (
<>
<HeaderWrapper />
{mode.value === 'top' || grouped ? <TopNavigation /> : null}
</>
)),
sidebar:
slots.sidebar ??
(() => (
<Menu
options={grouped ? mixedChildren.value : void 0}
showLogo={!grouped}
end={mode.value === 'right'}
inert={layoutContentMaximize.value}
/>
)),
tabs: slots.tabs ?? (() => <FeatureWrapper />),
footer: slots.footer ?? (() => <FooterWrapper />),
default: slots.default ?? (() => <ContentWrapper />),
loading: slots.default ? void 0 : () => <ContentLoading />,
}} }}
</AdminShell> onReady={() => {
if (attempt !== presentation.value) return
mountedPresentation = attempt.key
checkOutlets()
}}
onFailure={(error) => {
void nextTick(() => {
if (attempt === presentation.value) rejectLayout(id, error)
})
}}
/>
</Suspense>
<SharedFrame
onFailure={(error: unknown) => {
void nextTick(() => {
if (attempt === presentation.value) rejectLayout(id, error)
})
}}
/>
<div hidden ref="parking" />
{deferred.value && (
<p class="r-layout-switch-notice" role="status">
{t('deferredForEmbed')}
</p>
)}
{target.value && (
<Teleport to={page}>
{slots.default ? slots.default() : <ContentWrapper />}
</Teleport>
)}
{!slots.header && (
<SettingDrawer
v-model:show={settingsShown.value}
placement={getDrawerPlacement.value}
onAfterLeave={restoreSettingsFocus}
/>
)}
</div>
) )
} }
}, },

Some files were not shown because too many files have changed in this diff Show More