mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-12-02 09:43:38 +08:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
911c403434 | ||
|
|
d3a2504d37 | ||
|
|
d67e64d48c | ||
|
|
474d75203c | ||
|
|
b5ccd180ef | ||
|
|
9a6851b858 | ||
|
|
edf4794078 | ||
|
|
2a4a6182b0 | ||
|
|
c2019b10e6 | ||
|
|
94c2e6cdb6 |
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@ -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
103
.zed/settings.json
Normal 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"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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.
|
||||||
|
|||||||
21
CHANGELOG.md
21
CHANGELOG.md
@ -1,3 +1,24 @@
|
|||||||
|
## 6.0.3
|
||||||
|
|
||||||
|
### Feats
|
||||||
|
|
||||||
|
- 新增简单标签管理和复杂项目管理示例,展示弹窗编辑、独立详情页、里程碑与草稿保护。官网补齐英文指南和组件参考。
|
||||||
|
- 四种主题的登录页、图标库和业务面板使用各自的配色和圆角。提高输入框和主按钮的对比度,简化窄屏用户页和表格工具栏。
|
||||||
|
- 全局搜索提示按回车将打开的页面。面包屑可用键盘操作,工作区支持跳至主内容,并区分内容区最大化与浏览器全屏。
|
||||||
|
- 根 `package.json` 提供各模块的 Vitest 命令和全量入口 `pnpm test:all`。
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- 路由守卫拒绝离开编辑页时保留草稿、标签与缓存。键盘关闭最后一个标签后,焦点回到标签页操作按钮。
|
||||||
|
- TablePro 在等值查询条件下保留页码,图表在实例就绪后才开始深度监听。用户管理按部门 ID 构建组织树,独立图标宿主按名称加载 SVG,打印引擎随打印示例按需加载。
|
||||||
|
- 修复不同二进制请求体互相取消的问题。RIframe 将 `sandbox` 和 `referrerpolicy` 交给原生 iframe。
|
||||||
|
- 全栈初始化先检查 Redis,再执行数据库迁移。切换到外部服务会保存实际连接,Compose 支持设置 `REDIS_KEY_PREFIX`。
|
||||||
|
|
||||||
|
### Compatibility
|
||||||
|
|
||||||
|
- `pnpm lint:fix <文件路径>` 只修复显式指定的文件。ESLint 自动将内置 `undefined` 的运行时读取改成 `void 0`,类型中的 `undefined` 仍可使用。Markdown 和 JSON 走 Prettier。
|
||||||
|
- 从 Compose 切换到外部服务时,同时提供 `DATABASE_URL` 和 `REDIS_URL`。已有外部服务配置可更新其中一项。[全栈启动指南](apps/docs/guide/distributions.md)
|
||||||
|
|
||||||
## 6.0.2
|
## 6.0.2
|
||||||
|
|
||||||
### Feats
|
### Feats
|
||||||
|
|||||||
30
README.md
30
README.md
@ -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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
45
__test__/app/curd-demo-records.spec.ts
Normal file
45
__test__/app/curd-demo-records.spec.ts
Normal 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([])
|
||||||
|
})
|
||||||
|
})
|
||||||
60
__test__/app/route-draft-guard.spec.ts
Normal file
60
__test__/app/route-draft-guard.spec.ts
Normal 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()
|
||||||
|
}
|
||||||
|
})
|
||||||
@ -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({
|
||||||
|
|||||||
@ -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()
|
||||||
|
|||||||
@ -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()
|
||||||
|
|||||||
@ -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(
|
||||||
|
|||||||
@ -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(),
|
||||||
|
|||||||
43
__test__/components/form-themes.spec.ts
Normal file
43
__test__/components/form-themes.spec.ts
Normal 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,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
@ -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' },
|
||||||
|
|||||||
@ -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')
|
||||||
|
|||||||
@ -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()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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' })
|
||||||
|
|||||||
@ -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)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@ -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()
|
||||||
|
|||||||
@ -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')
|
||||||
})
|
})
|
||||||
|
|||||||
102
__test__/hooks/useMenu.spec.tsx
Normal file
102
__test__/hooks/useMenu.spec.tsx
Normal 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()
|
||||||
|
})
|
||||||
@ -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',
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|||||||
110
__test__/layout/breadcrumb.spec.tsx
Normal file
110
__test__/layout/breadcrumb.spec.tsx
Normal 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()
|
||||||
|
}
|
||||||
|
})
|
||||||
@ -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(
|
||||||
|
|||||||
@ -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,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|||||||
@ -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()
|
||||||
|
|||||||
@ -44,6 +44,7 @@ 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: { RayAdminShell: false, NLayout: false, NLayoutContent: false },
|
||||||
@ -58,6 +59,8 @@ it('offers a restore button for custom content and also exits with Escape', asyn
|
|||||||
expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe(
|
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)
|
||||||
|
|||||||
@ -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')
|
||||||
|
|||||||
@ -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()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@ -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
|
||||||
|
|||||||
36
__test__/utils/color-contrast.ts
Normal file
36
__test__/utils/color-contrast.ts
Normal 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)
|
||||||
|
}
|
||||||
@ -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
|
||||||
|
|||||||
@ -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,
|
||||||
|
|||||||
@ -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) =>
|
||||||
|
|||||||
85
__test__/workspace/no-undefined.spec.ts
Normal file
85
__test__/workspace/no-undefined.spec.ts
Normal 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)
|
||||||
|
})
|
||||||
@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -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",
|
||||||
|
|||||||
@ -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)
|
||||||
|
|||||||
@ -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']>,
|
||||||
|
|||||||
@ -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.
|
||||||
|
|||||||
@ -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',
|
||||||
@ -135,6 +136,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 = [
|
||||||
|
|||||||
@ -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.
|
||||||
|
|||||||
@ -1,2 +1,3 @@
|
|||||||
export * from './useContextmenuCoordinate'
|
export * from './useContextmenuCoordinate'
|
||||||
|
export * from './useMenu'
|
||||||
export * from './usePagination'
|
export * from './usePagination'
|
||||||
|
|||||||
1
apps/admin/src/hooks/components/useMenu.ts
Normal file
1
apps/admin/src/hooks/components/useMenu.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from '@ray-template/composables/useMenu'
|
||||||
@ -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>
|
|
||||||
|
|||||||
@ -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
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,16 @@ 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 标签页对象、索引或路径
|
||||||
@ -14,8 +24,6 @@ export type CloseMenuTag = Key | MenuTagOptions
|
|||||||
* @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'
|
||||||
@ -35,15 +43,40 @@ 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,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -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,7 +28,7 @@ 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()
|
||||||
@ -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()
|
||||||
},
|
},
|
||||||
@ -72,6 +73,8 @@ export default defineComponent({
|
|||||||
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 }}
|
||||||
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}
|
||||||
|
|||||||
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -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 {
|
||||||
|
usePreferredReducedMotion,
|
||||||
|
useResizeObserver,
|
||||||
|
useTimeoutFn,
|
||||||
|
} from '@vueuse/core'
|
||||||
import { NDropdown, NFlex, NLayoutHeader, NScrollbar } from 'naive-ui'
|
import { NDropdown, NFlex, NLayoutHeader, 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,
|
||||||
@ -393,34 +543,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 +634,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 +665,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>
|
||||||
|
|||||||
481
apps/admin/src/layout/components/MenuTag/use-tag-reorder.ts
Normal file
481
apps/admin/src/layout/components/MenuTag/use-tag-reorder.ts
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -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;
|
||||||
|
--search-focus: color-mix(
|
||||||
|
in srgb,
|
||||||
|
var(--r-theme-primary-color) 50%,
|
||||||
|
var(--r-text)
|
||||||
|
);
|
||||||
|
|
||||||
|
inline-size: min(620px, calc(100dvw - 24px));
|
||||||
|
max-block-size: calc(100dvh - var(--search-top) - 12px);
|
||||||
|
margin: var(--search-top) auto auto;
|
||||||
border-radius: var(--r-radius);
|
border-radius: var(--r-radius);
|
||||||
|
box-shadow: var(--r-shadow-soft);
|
||||||
|
|
||||||
.n-card__content {
|
> .n-card-header {
|
||||||
|
gap: 16px;
|
||||||
|
padding: 10px var(--search-gutter);
|
||||||
|
}
|
||||||
|
|
||||||
|
> .n-card__content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
min-block-size: 0;
|
min-block-size: 0;
|
||||||
overflow: auto;
|
padding: 0 var(--search-gutter);
|
||||||
}
|
}
|
||||||
|
|
||||||
.n-card__action {
|
> .n-card__action {
|
||||||
padding: 12px 20px;
|
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;
|
}
|
||||||
|
|
||||||
|
.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);
|
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;
|
.global-search__external {
|
||||||
color: var(--r-theme-primary-color);
|
color: var(--r-text-muted);
|
||||||
}
|
|
||||||
}
|
|
||||||
.global-search__favorite {
|
|
||||||
flex-shrink: 0;
|
|
||||||
font-size: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.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;
|
||||||
|
}
|
||||||
|
|||||||
@ -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>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -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>
|
||||||
)
|
)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@ -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>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@ -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)
|
||||||
|
|||||||
@ -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
|
||||||
|
|||||||
@ -10,12 +10,12 @@ import {
|
|||||||
} from '@/store'
|
} 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, NDropdown, NFlex, NLayoutHeader } from 'naive-ui'
|
||||||
|
import type { PropType } from 'vue'
|
||||||
import { useFullscreen } from 'vue-hooks-plus'
|
import { useFullscreen } from 'vue-hooks-plus'
|
||||||
import {
|
import {
|
||||||
Breadcrumb,
|
Breadcrumb,
|
||||||
GlobalSearch,
|
GlobalSearch,
|
||||||
GlobalSearchButton,
|
GlobalSearchButton,
|
||||||
SettingDrawer,
|
|
||||||
TooltipIcon,
|
TooltipIcon,
|
||||||
} from './components'
|
} from './components'
|
||||||
import {
|
import {
|
||||||
@ -28,7 +28,10 @@ import type { IconEventMapOptions } from './type'
|
|||||||
|
|
||||||
export default defineComponent({
|
export default defineComponent({
|
||||||
name: 'AppSiderBar',
|
name: 'AppSiderBar',
|
||||||
setup() {
|
props: {
|
||||||
|
onOpenSettings: { type: Function as PropType<() => void>, required: true },
|
||||||
|
},
|
||||||
|
setup(props) {
|
||||||
// 获取 setting 相关值
|
// 获取 setting 相关值
|
||||||
const { updateLocale, updateSettingState } = useSettingActions()
|
const { updateLocale, updateSettingState } = useSettingActions()
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
@ -37,9 +40,7 @@ export default defineComponent({
|
|||||||
document.getElementsByTagName('html')[0],
|
document.getElementsByTagName('html')[0],
|
||||||
)
|
)
|
||||||
// 获取设置相关方法
|
// 获取设置相关方法
|
||||||
const { getDrawerPlacement, getBreadcrumbSwitch } = useSettingGetters()
|
const { getBreadcrumbSwitch } = useSettingGetters()
|
||||||
// 是否显示设置抽屉
|
|
||||||
const showSettings = ref(false)
|
|
||||||
const accountMenuShown = ref(false)
|
const accountMenuShown = ref(false)
|
||||||
const { getSigningCallback } = useSigningGetters()
|
const { getSigningCallback } = useSigningGetters()
|
||||||
// 是否展示全局搜索
|
// 是否展示全局搜索
|
||||||
@ -75,9 +76,7 @@ export default defineComponent({
|
|||||||
search: () => {
|
search: () => {
|
||||||
globalSearchShown.value = true
|
globalSearchShown.value = true
|
||||||
},
|
},
|
||||||
setting: () => {
|
setting: props.onOpenSettings,
|
||||||
showSettings.value = true
|
|
||||||
},
|
|
||||||
github: () => {
|
github: () => {
|
||||||
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
|
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
|
||||||
},
|
},
|
||||||
@ -109,9 +108,7 @@ export default defineComponent({
|
|||||||
leftIconOptions,
|
leftIconOptions,
|
||||||
rightTooltipIconOptions,
|
rightTooltipIconOptions,
|
||||||
toolIconClick,
|
toolIconClick,
|
||||||
showSettings,
|
|
||||||
updateLocale,
|
updateLocale,
|
||||||
getDrawerPlacement,
|
|
||||||
getBreadcrumbSwitch,
|
getBreadcrumbSwitch,
|
||||||
globalSearchShown,
|
globalSearchShown,
|
||||||
isTabletOrSmaller,
|
isTabletOrSmaller,
|
||||||
@ -120,12 +117,8 @@ export default defineComponent({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
render() {
|
render() {
|
||||||
const {
|
const { rightTooltipIconOptions, leftIconOptions, getBreadcrumbSwitch } =
|
||||||
rightTooltipIconOptions,
|
this
|
||||||
leftIconOptions,
|
|
||||||
getDrawerPlacement,
|
|
||||||
getBreadcrumbSwitch,
|
|
||||||
} = this
|
|
||||||
const { toolIconClick, updateLocale } = this
|
const { toolIconClick, updateLocale } = this
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -191,7 +184,10 @@ export default defineComponent({
|
|||||||
)}
|
)}
|
||||||
{rightTooltipIconOptions.map((curr) => (
|
{rightTooltipIconOptions.map((curr) => (
|
||||||
<NButton
|
<NButton
|
||||||
class="override-button__layout"
|
class={[
|
||||||
|
'override-button__layout',
|
||||||
|
{ 'layout-header__settings': curr.eventKey === 'setting' },
|
||||||
|
]}
|
||||||
quaternary
|
quaternary
|
||||||
size="medium"
|
size="medium"
|
||||||
key={curr.eventKey ?? curr.name}
|
key={curr.eventKey ?? curr.name}
|
||||||
@ -273,10 +269,6 @@ export default defineComponent({
|
|||||||
</NDropdown>
|
</NDropdown>
|
||||||
</NFlex>
|
</NFlex>
|
||||||
</NFlex>
|
</NFlex>
|
||||||
<SettingDrawer
|
|
||||||
v-model:show={this.showSettings}
|
|
||||||
placement={getDrawerPlacement}
|
|
||||||
/>
|
|
||||||
</NLayoutHeader>
|
</NLayoutHeader>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@ -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>
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|||||||
@ -6,6 +6,7 @@ import { useDevice, useI18n, useMaximize } from '@/hooks'
|
|||||||
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store'
|
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store'
|
||||||
import { AdminShell } from '@ray-template/admin-shell'
|
import { AdminShell } from '@ray-template/admin-shell'
|
||||||
import Menu from './components/Menu'
|
import Menu from './components/Menu'
|
||||||
|
import SettingDrawer from './components/SiderBar/components/SettingDrawer'
|
||||||
import TopNavigation from './components/TopNavigation'
|
import TopNavigation from './components/TopNavigation'
|
||||||
import {
|
import {
|
||||||
ContentWrapper,
|
ContentWrapper,
|
||||||
@ -18,9 +19,14 @@ import { findMenuRoot } from './navigation'
|
|||||||
|
|
||||||
export default defineComponent({
|
export default defineComponent({
|
||||||
name: 'RLayout',
|
name: 'RLayout',
|
||||||
setup(_, { slots }) {
|
inheritAttrs: false,
|
||||||
const { getMenuTagSwitch, getCopyrightSwitch, getLayoutConfig } =
|
setup(_, { attrs, slots }) {
|
||||||
useSettingGetters()
|
const {
|
||||||
|
getMenuTagSwitch,
|
||||||
|
getCopyrightSwitch,
|
||||||
|
getLayoutConfig,
|
||||||
|
getDrawerPlacement,
|
||||||
|
} = useSettingGetters()
|
||||||
const { getMenuOptions, getMenuKey } = useMenuGetters()
|
const { getMenuOptions, getMenuKey } = useMenuGetters()
|
||||||
const {
|
const {
|
||||||
globalMainLayoutLoad,
|
globalMainLayoutLoad,
|
||||||
@ -32,6 +38,24 @@ export default defineComponent({
|
|||||||
const { t } = useI18n('layout')
|
const { t } = useI18n('layout')
|
||||||
const { isTabletOrSmaller } = useDevice()
|
const { isTabletOrSmaller } = useDevice()
|
||||||
const { getLockAppScreen } = useAppLockScreen()
|
const { getLockAppScreen } = useAppLockScreen()
|
||||||
|
const locked = computed(() => apiMockEnabled && getLockAppScreen())
|
||||||
|
const settingsShown = ref(false)
|
||||||
|
const shell = useTemplateRef<InstanceType<typeof AdminShell>>('shell')
|
||||||
|
const openSettings = () => {
|
||||||
|
settingsShown.value = true
|
||||||
|
}
|
||||||
|
const restoreSettingsFocus = () => {
|
||||||
|
const root = shell.value?.$el
|
||||||
|
|
||||||
|
if (root instanceof HTMLElement)
|
||||||
|
root
|
||||||
|
.querySelector<HTMLButtonElement>('.layout-header__settings')
|
||||||
|
?.focus({ preventScroll: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(locked, (value) => {
|
||||||
|
if (value) settingsShown.value = false
|
||||||
|
})
|
||||||
const mode = computed(() =>
|
const mode = computed(() =>
|
||||||
isTabletOrSmaller.value ? 'side' : getLayoutConfig.value.mode,
|
isTabletOrSmaller.value ? 'side' : getLayoutConfig.value.mode,
|
||||||
)
|
)
|
||||||
@ -44,12 +68,15 @@ export default defineComponent({
|
|||||||
)
|
)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (apiMockEnabled && getLockAppScreen()) return <UnlockScreen />
|
if (locked.value) return <UnlockScreen {...attrs} />
|
||||||
|
|
||||||
const grouped = mode.value === 'mixed' || mode.value === 'split'
|
const grouped = mode.value === 'mixed' || mode.value === 'split'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
<>
|
||||||
<AdminShell
|
<AdminShell
|
||||||
|
{...attrs}
|
||||||
|
ref="shell"
|
||||||
layout={getLayoutConfig.value}
|
layout={getLayoutConfig.value}
|
||||||
mode={mode.value}
|
mode={mode.value}
|
||||||
groupedSidebar={mixedChildren.value.length > 0}
|
groupedSidebar={mixedChildren.value.length > 0}
|
||||||
@ -63,6 +90,7 @@ export default defineComponent({
|
|||||||
maximizedStyle={layoutContentMaximizeStyle.value}
|
maximizedStyle={layoutContentMaximizeStyle.value}
|
||||||
contentRef={LAYOUT_CONTENT_REF}
|
contentRef={LAYOUT_CONTENT_REF}
|
||||||
restore={() => maximize(false)}
|
restore={() => maximize(false)}
|
||||||
|
skipContentLabel={t('skipToContent')}
|
||||||
restoreLabel={t('restore')}
|
restoreLabel={t('restore')}
|
||||||
>
|
>
|
||||||
{{
|
{{
|
||||||
@ -70,7 +98,7 @@ export default defineComponent({
|
|||||||
slots.header ??
|
slots.header ??
|
||||||
(() => (
|
(() => (
|
||||||
<>
|
<>
|
||||||
<HeaderWrapper />
|
<HeaderWrapper onOpenSettings={openSettings} />
|
||||||
{mode.value === 'top' || grouped ? <TopNavigation /> : null}
|
{mode.value === 'top' || grouped ? <TopNavigation /> : null}
|
||||||
</>
|
</>
|
||||||
)),
|
)),
|
||||||
@ -90,6 +118,14 @@ export default defineComponent({
|
|||||||
loading: slots.default ? void 0 : () => <ContentLoading />,
|
loading: slots.default ? void 0 : () => <ContentLoading />,
|
||||||
}}
|
}}
|
||||||
</AdminShell>
|
</AdminShell>
|
||||||
|
{!slots.header && (
|
||||||
|
<SettingDrawer
|
||||||
|
v-model:show={settingsShown.value}
|
||||||
|
placement={getDrawerPlacement.value}
|
||||||
|
onAfterLeave={restoreSettingsFocus}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@ -2,11 +2,12 @@ import { LOCAL_OPTIONS, SYSTEM_FALLBACK_LOCALE } from '@/app-config'
|
|||||||
import { getAppDefaultLanguage, getAppLocalMessages } from '@/locales/utils'
|
import { getAppDefaultLanguage, getAppLocalMessages } from '@/locales/utils'
|
||||||
import type { App } from 'vue'
|
import type { App } from 'vue'
|
||||||
import { createI18n } from 'vue-i18n'
|
import { createI18n } from 'vue-i18n'
|
||||||
import type { I18n, I18nOptions } from 'vue-i18n'
|
import type { I18nOptions } from 'vue-i18n'
|
||||||
|
|
||||||
|
type AppI18n = ReturnType<typeof createI18nOptions>
|
||||||
|
|
||||||
/** 已安装的国际化实例;热更新期间保留同一个实例。 */
|
/** 已安装的国际化实例;热更新期间保留同一个实例。 */
|
||||||
export let i18n: I18n | undefined = import.meta.hot?.data.i18n as
|
export let i18n = import.meta.hot?.data.i18n as AppI18n | undefined
|
||||||
I18n | undefined
|
|
||||||
|
|
||||||
if (import.meta.hot) {
|
if (import.meta.hot) {
|
||||||
import.meta.hot.dispose((data) => {
|
import.meta.hot.dispose((data) => {
|
||||||
@ -30,8 +31,6 @@ const createI18nOptions = () => {
|
|||||||
legacy: false,
|
legacy: false,
|
||||||
locale,
|
locale,
|
||||||
messages: messages as unknown as I18nOptions['messages'],
|
messages: messages as unknown as I18nOptions['messages'],
|
||||||
sync: true,
|
|
||||||
silentFallbackWarn: true,
|
|
||||||
fallbackLocale: SYSTEM_FALLBACK_LOCALE,
|
fallbackLocale: SYSTEM_FALLBACK_LOCALE,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
61
apps/admin/src/locales/lang/en-US/curd.json
Normal file
61
apps/admin/src/locales/lang/en-US/curd.json
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"tagsTitle": "Tags",
|
||||||
|
"tagsIntro": "Create and edit tags in a modal. Select a tag name to view its notes in a drawer.",
|
||||||
|
"projectsTitle": "Projects",
|
||||||
|
"projectsIntro": "Filter projects by name and status. Open a project page to view or edit its details and milestones.",
|
||||||
|
"name": "Name",
|
||||||
|
"tagNote": "Notes",
|
||||||
|
"projectName": "Project name",
|
||||||
|
"owner": "Owner",
|
||||||
|
"status": "Status",
|
||||||
|
"planned": "Planned",
|
||||||
|
"active": "In progress",
|
||||||
|
"completed": "Completed",
|
||||||
|
"summary": "Project summary",
|
||||||
|
"overview": "Overview",
|
||||||
|
"milestones": "Milestones",
|
||||||
|
"milestoneName": "Milestone name",
|
||||||
|
"milestoneOutcome": "Expected outcome",
|
||||||
|
"milestoneNumber": "Milestone {number}",
|
||||||
|
"removeMilestoneNumber": "Remove milestone {number}",
|
||||||
|
"addMilestone": "Add milestone",
|
||||||
|
"removeMilestone": "Remove",
|
||||||
|
"noMilestones": "No milestones yet",
|
||||||
|
"actions": "Actions",
|
||||||
|
"search": "Search",
|
||||||
|
"clearFilters": "Clear filters",
|
||||||
|
"noTags": "No tags yet",
|
||||||
|
"noProjects": "No projects yet",
|
||||||
|
"noMatches": "No projects match these filters",
|
||||||
|
"create": "Create",
|
||||||
|
"createTag": "Create tag",
|
||||||
|
"editTag": "Edit tag",
|
||||||
|
"tagDetail": "Tag details",
|
||||||
|
"createProject": "Create project",
|
||||||
|
"editProject": "Edit {name}",
|
||||||
|
"projectDetail": "Project details",
|
||||||
|
"editorIntro": "Add project information and any milestones. Save to apply your changes.",
|
||||||
|
"backToProjects": "Back to projects",
|
||||||
|
"edit": "Edit",
|
||||||
|
"saveChanges": "Save changes",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"close": "Close",
|
||||||
|
"delete": "Delete",
|
||||||
|
"deleteTitle": "Confirm deletion",
|
||||||
|
"deleteTag": "Delete “{name}”? This action is permanent.",
|
||||||
|
"deleteProject": "Delete “{name}” and all its milestones? This action is permanent.",
|
||||||
|
"saved": "Saved",
|
||||||
|
"deleted": "Deleted",
|
||||||
|
"nameRequired": "Enter a name",
|
||||||
|
"ownerRequired": "Enter an owner",
|
||||||
|
"milestoneRequired": "Enter a milestone name",
|
||||||
|
"checkFields": "Review the indicated fields and try again.",
|
||||||
|
"duplicate": "This name is already in use. Choose a different name.",
|
||||||
|
"saveFailed": "Could not write the example data to this browser. Try again.",
|
||||||
|
"missingRecord": "Record unavailable",
|
||||||
|
"missingHelp": "The project may have been deleted or may belong to another demo session.",
|
||||||
|
"discardTitle": "Discard unsaved changes?",
|
||||||
|
"discardMessage": "Your edits will be lost when you leave.",
|
||||||
|
"discard": "Discard changes",
|
||||||
|
"keepEditing": "Keep editing"
|
||||||
|
}
|
||||||
@ -32,6 +32,8 @@
|
|||||||
"profile": "Profile",
|
"profile": "Profile",
|
||||||
"name": "Name",
|
"name": "Name",
|
||||||
"age": "Age",
|
"age": "Age",
|
||||||
|
"decreaseAge": "Decrease age",
|
||||||
|
"increaseAge": "Increase age",
|
||||||
"date": "Date of birth",
|
"date": "Date of birth",
|
||||||
"gender": "Gender",
|
"gender": "Gender",
|
||||||
"female": "Female",
|
"female": "Female",
|
||||||
|
|||||||
@ -22,7 +22,15 @@
|
|||||||
"closeLeft": "Close tabs on the left",
|
"closeLeft": "Close tabs on the left",
|
||||||
"closeRight": "Close tabs on the right",
|
"closeRight": "Close tabs on the right",
|
||||||
"closeCurrent": "Close current tab",
|
"closeCurrent": "Close current tab",
|
||||||
"closeAll": "Close all and open workspace",
|
"closeAll": "Close all tabs",
|
||||||
|
"menuExample": "Menu hook example",
|
||||||
|
"menuOverview": "Overview",
|
||||||
|
"menuReports": "Reports",
|
||||||
|
"menuDaily": "Daily report",
|
||||||
|
"menuMonthly": "Monthly report",
|
||||||
|
"menuReveal": "Reveal monthly report",
|
||||||
|
"menuClear": "Clear selection",
|
||||||
|
"menuState": "Selected {selected} · Expanded {expanded}",
|
||||||
"contentTop": "Scroll content to top",
|
"contentTop": "Scroll content to top",
|
||||||
"content300": "Scroll content to 300 px",
|
"content300": "Scroll content to 300 px",
|
||||||
"siderTop": "Scroll sidebar to top",
|
"siderTop": "Scroll sidebar to top",
|
||||||
@ -55,6 +63,7 @@
|
|||||||
"useWatermark": "Update the global watermark and control visibility. An empty string keeps the previous text.",
|
"useWatermark": "Update the global watermark and control visibility. An empty string keeps the previous text.",
|
||||||
"useAppNavigation": "Navigate by menu object, full path or zero-based top-level index. Returns an awaitable navigation result.",
|
"useAppNavigation": "Navigate by menu object, full path or zero-based top-level index. Returns an awaitable navigation result.",
|
||||||
"useSiderBar": "Close tabs and their neighbors by path, index or tab object.",
|
"useSiderBar": "Close tabs and their neighbors by path, index or tab object.",
|
||||||
|
"useMenu": "Manage NMenu selection and expanded groups. Reveal a menu item through the component instance.",
|
||||||
"useContentScroll": "Obtain a scroll function in setup. Each call resolves the current layout instance.",
|
"useContentScroll": "Obtain a scroll function in setup. Each call resolves the current layout instance.",
|
||||||
"useSiderScroll": "Scroll the current sidebar. Safely does nothing when top navigation has no sidebar.",
|
"useSiderScroll": "Scroll the current sidebar. Safely does nothing when top navigation has no sidebar.",
|
||||||
"useDevice": "Observe viewport size and apply a custom tablet breakpoint. Resize the window to see changes.",
|
"useDevice": "Observe viewport size and apply a custom tablet breakpoint. Resize the window to see changes.",
|
||||||
|
|||||||
@ -24,6 +24,7 @@
|
|||||||
"current": "Current configuration",
|
"current": "Current configuration",
|
||||||
"extension": "Extend the layout",
|
"extension": "Extend the layout",
|
||||||
"slots": "Use header, sidebar, tabs, footer and default content slots. Update the Pinia configuration to switch layouts.",
|
"slots": "Use header, sidebar, tabs, footer and default content slots. Update the Pinia configuration to switch layouts.",
|
||||||
|
"skipToContent": "Skip to main content",
|
||||||
"navigation": "Main navigation",
|
"navigation": "Main navigation",
|
||||||
"maximize": "Maximize content",
|
"maximize": "Maximize content",
|
||||||
"restore": "Restore content size (Esc)",
|
"restore": "Restore content size (Esc)",
|
||||||
|
|||||||
@ -4,6 +4,12 @@
|
|||||||
"CacheDemo": "Cache Utils Demo",
|
"CacheDemo": "Cache Utils Demo",
|
||||||
"CalculatePrecision": "Precision",
|
"CalculatePrecision": "Precision",
|
||||||
"ContextMenu": "Right Click Menu",
|
"ContextMenu": "Right Click Menu",
|
||||||
|
"CurdExamples": "CURD examples",
|
||||||
|
"CurdTags": "Tags · Simple",
|
||||||
|
"CurdProjects": "Projects · Complex",
|
||||||
|
"CurdProjectCreate": "Create project",
|
||||||
|
"CurdProjectDetail": "Project details",
|
||||||
|
"CurdProjectEdit": "Edit project",
|
||||||
"Dashboard": "Home",
|
"Dashboard": "Home",
|
||||||
"DemoComponents": "Component examples",
|
"DemoComponents": "Component examples",
|
||||||
"DemoAssets": "Icons and codes",
|
"DemoAssets": "Icons and codes",
|
||||||
|
|||||||
@ -9,6 +9,14 @@
|
|||||||
"maximize": "Maximize page",
|
"maximize": "Maximize page",
|
||||||
"reload": "Reload page",
|
"reload": "Reload page",
|
||||||
"newWindow": "Open in new window",
|
"newWindow": "Open in new window",
|
||||||
|
"top": "Move to front",
|
||||||
|
"untop": "Remove from front group",
|
||||||
|
"topped": "At the front",
|
||||||
|
"fix": "Protect tab",
|
||||||
|
"unfix": "Unprotect tab",
|
||||||
|
"fixed": "Protected",
|
||||||
|
"moved": "{name} moved to position {position}",
|
||||||
|
"moveCanceled": "Tab reordering canceled",
|
||||||
"scrollLeft": "Scroll tabs left",
|
"scrollLeft": "Scroll tabs left",
|
||||||
"scrollRight": "Scroll tabs right",
|
"scrollRight": "Scroll tabs right",
|
||||||
"actions": "Tab actions"
|
"actions": "Tab actions"
|
||||||
|
|||||||
@ -11,6 +11,7 @@
|
|||||||
"empty": "Search for a page and use the star to save a favorite.",
|
"empty": "Search for a page and use the star to save a favorite.",
|
||||||
"storageUnavailable": "Your browser cannot save history right now. It remains available for this visit.",
|
"storageUnavailable": "Your browser cannot save history right now. It remains available for this visit.",
|
||||||
"move": "Move",
|
"move": "Move",
|
||||||
|
"enterTarget": "Enter opens {title}",
|
||||||
"open": "Open",
|
"open": "Open",
|
||||||
"close": "Close"
|
"close": "Close"
|
||||||
}
|
}
|
||||||
|
|||||||
@ -42,7 +42,13 @@
|
|||||||
"placement": "Drawer position",
|
"placement": "Drawer position",
|
||||||
"display": "Interface display",
|
"display": "Interface display",
|
||||||
"breadcrumbSwitch": "Breadcrumbs",
|
"breadcrumbSwitch": "Breadcrumbs",
|
||||||
|
"breadcrumbIcon": "Show breadcrumb icons",
|
||||||
|
"breadcrumbIconFallback": "Use a fallback for missing icons",
|
||||||
"menuTagSwitch": "Page tabs",
|
"menuTagSwitch": "Page tabs",
|
||||||
|
"menuTagRound": "Pill-shaped page tabs",
|
||||||
|
"menuTagTop": "Allow moving tabs to the front",
|
||||||
|
"menuTagFixed": "Allow protecting tabs",
|
||||||
|
"menuTagDrag": "Allow dragging to reorder tabs",
|
||||||
"copyrightSwitch": "Footer",
|
"copyrightSwitch": "Footer",
|
||||||
"colorWeakness": "Color vision mode",
|
"colorWeakness": "Color vision mode",
|
||||||
"displayHint": "Show or hide breadcrumbs, page tabs, and the footer together, or adjust each below.",
|
"displayHint": "Show or hide breadcrumbs, page tabs, and the footer together, or adjust each below.",
|
||||||
|
|||||||
@ -22,6 +22,8 @@
|
|||||||
"valid": "Valid · {count} records",
|
"valid": "Valid · {count} records",
|
||||||
"editHint": "Validate to preview the route tree.",
|
"editHint": "Validate to preview the route tree.",
|
||||||
"invalid": "Configuration validation failed",
|
"invalid": "Configuration validation failed",
|
||||||
|
"jsonSyntax": "Invalid JSON. Check the double quotes, commas, and matching brackets.",
|
||||||
|
"jsonSyntaxAt": "Invalid JSON near line {line}, column {column}. Check the double quotes, commas, and brackets there.",
|
||||||
"contract": "Input and output contract",
|
"contract": "Input and output contract",
|
||||||
"contractHint": "Give the schema and view catalog to AI or backend developers. API responses, imports and exports use the same format.",
|
"contractHint": "Give the schema and view catalog to AI or backend developers. API responses, imports and exports use the same format.",
|
||||||
"views": "View catalog",
|
"views": "View catalog",
|
||||||
@ -42,7 +44,10 @@
|
|||||||
"validateDraft": "Validate",
|
"validateDraft": "Validate",
|
||||||
"draftValid": "Configuration is valid",
|
"draftValid": "Configuration is valid",
|
||||||
"resetDraft": "Reload configuration",
|
"resetDraft": "Reload configuration",
|
||||||
"resetConfirm": "Discard your draft changes and reload the saved configuration?",
|
"discardTitle": "Unsaved route draft",
|
||||||
|
"discardPrompt": "Continuing discards these changes. Return to the editor to keep working or export the draft.",
|
||||||
|
"keepEditing": "Keep editing",
|
||||||
|
"discardChanges": "Discard changes",
|
||||||
"addRoot": "Add top-level item",
|
"addRoot": "Add top-level item",
|
||||||
"addChild": "Add child item",
|
"addChild": "Add child item",
|
||||||
"editNode": "Edit menu item",
|
"editNode": "Edit menu item",
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"title": "User management",
|
"title": "User management",
|
||||||
"descriptionMock": "Manage members by organization. The online demo uses Mock APIs, with data saved in this browser.",
|
"descriptionMock": "Manage members by organization. The online demo uses Mock APIs, with data saved in this browser.",
|
||||||
|
"descriptionMockCompact": "Demo data is saved in this browser.",
|
||||||
"descriptionServer": "Manage member profiles, roles and account status by organization.",
|
"descriptionServer": "Manage member profiles, roles and account status by organization.",
|
||||||
"organization": "Organization",
|
"organization": "Organization",
|
||||||
"createUser": "Add user",
|
"createUser": "Add user",
|
||||||
@ -50,6 +51,7 @@
|
|||||||
"optionsFailed": "Could not load organizations and roles",
|
"optionsFailed": "Could not load organizations and roles",
|
||||||
"retry": "Retry",
|
"retry": "Retry",
|
||||||
"viewNamed": "View details for {name}",
|
"viewNamed": "View details for {name}",
|
||||||
|
"moreNamed": "More actions for {name}",
|
||||||
"editNamed": "Edit {name}",
|
"editNamed": "Edit {name}",
|
||||||
"deleteNamed": "Delete {name}",
|
"deleteNamed": "Delete {name}",
|
||||||
"enableNamed": "Enable {name}",
|
"enableNamed": "Enable {name}",
|
||||||
|
|||||||
@ -2,12 +2,15 @@
|
|||||||
"Register": "Register",
|
"Register": "Register",
|
||||||
"PageTitle": "Sign in - Ray Admin",
|
"PageTitle": "Sign in - Ray Admin",
|
||||||
"Signing": "Sign in",
|
"Signing": "Sign in",
|
||||||
|
"SignInMethods": "Sign-in options",
|
||||||
"QRCodeSigning": "QR code",
|
"QRCodeSigning": "QR code",
|
||||||
"NamePlaceholder": "please enter user name",
|
"NamePlaceholder": "please enter user name",
|
||||||
"PasswordPlaceholder": "please enter password",
|
"PasswordPlaceholder": "please enter password",
|
||||||
"Login": "Sign in",
|
"Login": "Sign in",
|
||||||
"Name": "User Name",
|
"Name": "User Name",
|
||||||
"Password": "User Password",
|
"Password": "User Password",
|
||||||
|
"ShowPassword": "Show password",
|
||||||
|
"HidePassword": "Hide password",
|
||||||
"RayTemplate": "Build your next admin dashboard",
|
"RayTemplate": "Build your next admin dashboard",
|
||||||
"TemplateDescription": "Open-source Vue 3 admin dashboard template with TypeScript and Naive UI.",
|
"TemplateDescription": "Open-source Vue 3 admin dashboard template with TypeScript and Naive UI.",
|
||||||
"OtherSignInOptions": "More sign-in examples",
|
"OtherSignInOptions": "More sign-in examples",
|
||||||
|
|||||||
61
apps/admin/src/locales/lang/zh-CN/curd.json
Normal file
61
apps/admin/src/locales/lang/zh-CN/curd.json
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
{
|
||||||
|
"tagsTitle": "标签管理",
|
||||||
|
"tagsIntro": "用弹窗创建或编辑标签。点击标签名称,在抽屉里查看备注。",
|
||||||
|
"projectsTitle": "项目管理",
|
||||||
|
"projectsIntro": "按名称和状态筛选项目。打开独立页面查看详情,或编辑项目与里程碑。",
|
||||||
|
"name": "名称",
|
||||||
|
"tagNote": "备注",
|
||||||
|
"projectName": "项目名称",
|
||||||
|
"owner": "负责人",
|
||||||
|
"status": "状态",
|
||||||
|
"planned": "计划中",
|
||||||
|
"active": "进行中",
|
||||||
|
"completed": "已完成",
|
||||||
|
"summary": "项目说明",
|
||||||
|
"overview": "基本信息",
|
||||||
|
"milestones": "里程碑",
|
||||||
|
"milestoneName": "里程碑名称",
|
||||||
|
"milestoneOutcome": "预期成果",
|
||||||
|
"milestoneNumber": "里程碑 {number}",
|
||||||
|
"removeMilestoneNumber": "移除里程碑 {number}",
|
||||||
|
"addMilestone": "添加里程碑",
|
||||||
|
"removeMilestone": "移除",
|
||||||
|
"noMilestones": "暂无里程碑",
|
||||||
|
"actions": "操作",
|
||||||
|
"search": "查询",
|
||||||
|
"clearFilters": "清除筛选",
|
||||||
|
"noTags": "暂无标签",
|
||||||
|
"noProjects": "暂无项目",
|
||||||
|
"noMatches": "没有符合筛选条件的项目",
|
||||||
|
"create": "创建",
|
||||||
|
"createTag": "新增标签",
|
||||||
|
"editTag": "编辑标签",
|
||||||
|
"tagDetail": "标签详情",
|
||||||
|
"createProject": "新增项目",
|
||||||
|
"editProject": "编辑项目「{name}」",
|
||||||
|
"projectDetail": "项目详情",
|
||||||
|
"editorIntro": "填写项目信息,并按需添加里程碑。保存后才会应用这些变更。",
|
||||||
|
"backToProjects": "返回项目列表",
|
||||||
|
"edit": "编辑",
|
||||||
|
"saveChanges": "保存更改",
|
||||||
|
"cancel": "取消",
|
||||||
|
"close": "关闭",
|
||||||
|
"delete": "删除",
|
||||||
|
"deleteTitle": "确认删除",
|
||||||
|
"deleteTag": "确定删除标签「{name}」?此操作无法撤销。",
|
||||||
|
"deleteProject": "确定删除项目「{name}」及其全部里程碑?此操作无法撤销。",
|
||||||
|
"saved": "已保存",
|
||||||
|
"deleted": "已删除",
|
||||||
|
"nameRequired": "请输入名称",
|
||||||
|
"ownerRequired": "请输入负责人",
|
||||||
|
"milestoneRequired": "请输入里程碑名称",
|
||||||
|
"checkFields": "请检查有提示的字段后重新提交。",
|
||||||
|
"duplicate": "此名称已被使用,请换一个名称。",
|
||||||
|
"saveFailed": "无法写入当前浏览器的演示数据,请重试。",
|
||||||
|
"missingRecord": "找不到这条记录",
|
||||||
|
"missingHelp": "该项目可能已删除,或属于另一个演示会话。",
|
||||||
|
"discardTitle": "放弃未保存的更改?",
|
||||||
|
"discardMessage": "离开后,本次编辑的内容将丢失。",
|
||||||
|
"discard": "放弃更改",
|
||||||
|
"keepEditing": "继续编辑"
|
||||||
|
}
|
||||||
@ -32,6 +32,8 @@
|
|||||||
"profile": "档案",
|
"profile": "档案",
|
||||||
"name": "姓名",
|
"name": "姓名",
|
||||||
"age": "年龄",
|
"age": "年龄",
|
||||||
|
"decreaseAge": "减少年龄",
|
||||||
|
"increaseAge": "增加年龄",
|
||||||
"date": "出生日期",
|
"date": "出生日期",
|
||||||
"gender": "性别",
|
"gender": "性别",
|
||||||
"female": "女",
|
"female": "女",
|
||||||
|
|||||||
@ -22,7 +22,15 @@
|
|||||||
"closeLeft": "关闭左侧标签",
|
"closeLeft": "关闭左侧标签",
|
||||||
"closeRight": "关闭右侧标签",
|
"closeRight": "关闭右侧标签",
|
||||||
"closeCurrent": "关闭当前标签",
|
"closeCurrent": "关闭当前标签",
|
||||||
"closeAll": "关闭全部并进入工作区",
|
"closeAll": "关闭全部",
|
||||||
|
"menuExample": "菜单 Hook 示例",
|
||||||
|
"menuOverview": "概览",
|
||||||
|
"menuReports": "报表",
|
||||||
|
"menuDaily": "日报",
|
||||||
|
"menuMonthly": "月报",
|
||||||
|
"menuReveal": "展开月报所在菜单",
|
||||||
|
"menuClear": "清除选中项",
|
||||||
|
"menuState": "选中 {selected} · 展开 {expanded}",
|
||||||
"contentTop": "内容滚动到顶部",
|
"contentTop": "内容滚动到顶部",
|
||||||
"content300": "内容滚动到 300px",
|
"content300": "内容滚动到 300px",
|
||||||
"siderTop": "侧栏滚动到顶部",
|
"siderTop": "侧栏滚动到顶部",
|
||||||
@ -55,6 +63,7 @@
|
|||||||
"useWatermark": "更新全局水印文本并控制显示。空字符串沿用上一次内容。",
|
"useWatermark": "更新全局水印文本并控制显示。空字符串沿用上一次内容。",
|
||||||
"useAppNavigation": "支持菜单对象、完整路径和从 0 开始的一级菜单索引,返回可等待的导航结果。",
|
"useAppNavigation": "支持菜单对象、完整路径和从 0 开始的一级菜单索引,返回可等待的导航结果。",
|
||||||
"useSiderBar": "按路径、索引或标签对象关闭指定标签及其相邻标签。",
|
"useSiderBar": "按路径、索引或标签对象关闭指定标签及其相邻标签。",
|
||||||
|
"useMenu": "管理 NMenu 的选中项和展开项,并通过实例方法展开指定菜单。",
|
||||||
"useContentScroll": "在 setup 中获取滚动方法,执行时使用当前布局实例。",
|
"useContentScroll": "在 setup 中获取滚动方法,执行时使用当前布局实例。",
|
||||||
"useSiderScroll": "滚动当前侧栏;顶部导航没有侧栏,调用时会安全忽略。",
|
"useSiderScroll": "滚动当前侧栏;顶部导航没有侧栏,调用时会安全忽略。",
|
||||||
"useDevice": "观察窗口尺寸并按自定义断点判断是否为平板或更小设备。缩放窗口查看结果。",
|
"useDevice": "观察窗口尺寸并按自定义断点判断是否为平板或更小设备。缩放窗口查看结果。",
|
||||||
|
|||||||
@ -24,6 +24,7 @@
|
|||||||
"current": "当前布局配置",
|
"current": "当前布局配置",
|
||||||
"extension": "扩展布局",
|
"extension": "扩展布局",
|
||||||
"slots": "布局提供 header、sidebar、tabs、footer 和默认内容插槽。通过 Pinia 更新配置即可切换布局。",
|
"slots": "布局提供 header、sidebar、tabs、footer 和默认内容插槽。通过 Pinia 更新配置即可切换布局。",
|
||||||
|
"skipToContent": "跳至主内容",
|
||||||
"navigation": "主导航",
|
"navigation": "主导航",
|
||||||
"maximize": "最大化内容区域",
|
"maximize": "最大化内容区域",
|
||||||
"restore": "退出内容最大化(Esc)",
|
"restore": "退出内容最大化(Esc)",
|
||||||
|
|||||||
@ -4,6 +4,12 @@
|
|||||||
"CacheDemo": "缓存工具函数",
|
"CacheDemo": "缓存工具函数",
|
||||||
"CalculatePrecision": "数字精度",
|
"CalculatePrecision": "数字精度",
|
||||||
"ContextMenu": "右键菜单",
|
"ContextMenu": "右键菜单",
|
||||||
|
"CurdExamples": "CURD 示例",
|
||||||
|
"CurdTags": "标签管理 · 简单",
|
||||||
|
"CurdProjects": "项目管理 · 复杂",
|
||||||
|
"CurdProjectCreate": "新增项目",
|
||||||
|
"CurdProjectDetail": "项目详情",
|
||||||
|
"CurdProjectEdit": "编辑项目",
|
||||||
"Dashboard": "首页",
|
"Dashboard": "首页",
|
||||||
"DemoComponents": "组件示例",
|
"DemoComponents": "组件示例",
|
||||||
"DemoAssets": "图标与编码",
|
"DemoAssets": "图标与编码",
|
||||||
|
|||||||
@ -9,6 +9,14 @@
|
|||||||
"maximize": "最大化当前页面",
|
"maximize": "最大化当前页面",
|
||||||
"reload": "刷新当前页面",
|
"reload": "刷新当前页面",
|
||||||
"newWindow": "新窗口打开",
|
"newWindow": "新窗口打开",
|
||||||
|
"top": "置顶标签页",
|
||||||
|
"untop": "取消置顶",
|
||||||
|
"topped": "已置顶",
|
||||||
|
"fix": "固定标签页",
|
||||||
|
"unfix": "取消固定",
|
||||||
|
"fixed": "已固定",
|
||||||
|
"moved": "{name} 已移至第 {position} 位",
|
||||||
|
"moveCanceled": "已取消标签页排序",
|
||||||
"scrollLeft": "向左滚动标签页",
|
"scrollLeft": "向左滚动标签页",
|
||||||
"scrollRight": "向右滚动标签页",
|
"scrollRight": "向右滚动标签页",
|
||||||
"actions": "标签页操作"
|
"actions": "标签页操作"
|
||||||
|
|||||||
@ -11,6 +11,7 @@
|
|||||||
"empty": "搜索页面,并点击星标收藏常用入口。",
|
"empty": "搜索页面,并点击星标收藏常用入口。",
|
||||||
"storageUnavailable": "浏览器暂时无法保存记录,本次访问中仍可使用。",
|
"storageUnavailable": "浏览器暂时无法保存记录,本次访问中仍可使用。",
|
||||||
"move": "切换",
|
"move": "切换",
|
||||||
|
"enterTarget": "按回车打开{title}",
|
||||||
"open": "打开",
|
"open": "打开",
|
||||||
"close": "关闭"
|
"close": "关闭"
|
||||||
}
|
}
|
||||||
|
|||||||
@ -42,7 +42,13 @@
|
|||||||
"placement": "设置抽屉位置",
|
"placement": "设置抽屉位置",
|
||||||
"display": "界面显示",
|
"display": "界面显示",
|
||||||
"breadcrumbSwitch": "面包屑导航",
|
"breadcrumbSwitch": "面包屑导航",
|
||||||
|
"breadcrumbIcon": "显示面包屑图标",
|
||||||
|
"breadcrumbIconFallback": "缺少图标时显示占位图标",
|
||||||
"menuTagSwitch": "页面标签",
|
"menuTagSwitch": "页面标签",
|
||||||
|
"menuTagRound": "胶囊形页面标签",
|
||||||
|
"menuTagTop": "允许置顶标签",
|
||||||
|
"menuTagFixed": "允许固定标签",
|
||||||
|
"menuTagDrag": "允许拖拽排序标签",
|
||||||
"copyrightSwitch": "页脚信息",
|
"copyrightSwitch": "页脚信息",
|
||||||
"colorWeakness": "色弱模式",
|
"colorWeakness": "色弱模式",
|
||||||
"displayHint": "批量调整面包屑、页面标签和页脚,也可继续逐项设置。",
|
"displayHint": "批量调整面包屑、页面标签和页脚,也可继续逐项设置。",
|
||||||
|
|||||||
@ -22,6 +22,8 @@
|
|||||||
"valid": "校验通过 · {count} 项",
|
"valid": "校验通过 · {count} 项",
|
||||||
"editHint": "校验后可查看配置树。",
|
"editHint": "校验后可查看配置树。",
|
||||||
"invalid": "配置校验失败",
|
"invalid": "配置校验失败",
|
||||||
|
"jsonSyntax": "JSON 格式有误。请检查双引号、逗号和括号是否配对。",
|
||||||
|
"jsonSyntaxAt": "第 {line} 行、第 {column} 列附近的 JSON 格式有误。请检查该处的双引号、逗号和括号。",
|
||||||
"contract": "输入与输出契约",
|
"contract": "输入与输出契约",
|
||||||
"contractHint": "将 Schema 与可用页面清单交给 AI 或后台开发者。接口响应、导入文件和导出文件使用同一格式。",
|
"contractHint": "将 Schema 与可用页面清单交给 AI 或后台开发者。接口响应、导入文件和导出文件使用同一格式。",
|
||||||
"views": "可用页面清单",
|
"views": "可用页面清单",
|
||||||
@ -42,7 +44,10 @@
|
|||||||
"validateDraft": "校验配置",
|
"validateDraft": "校验配置",
|
||||||
"draftValid": "校验通过",
|
"draftValid": "校验通过",
|
||||||
"resetDraft": "重新读取配置",
|
"resetDraft": "重新读取配置",
|
||||||
"resetConfirm": "放弃草稿改动,重新读取已保存的配置?",
|
"discardTitle": "路由草稿尚未保存",
|
||||||
|
"discardPrompt": "继续会放弃本次修改。你可以返回编辑器继续修改或导出草稿。",
|
||||||
|
"keepEditing": "继续编辑",
|
||||||
|
"discardChanges": "放弃修改",
|
||||||
"addRoot": "添加一级菜单",
|
"addRoot": "添加一级菜单",
|
||||||
"addChild": "添加子菜单",
|
"addChild": "添加子菜单",
|
||||||
"editNode": "编辑菜单项",
|
"editNode": "编辑菜单项",
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"title": "用户管理",
|
"title": "用户管理",
|
||||||
"descriptionMock": "按组织管理成员资料与状态。在线演示通过 Mock 接口读写,数据保存在当前浏览器。",
|
"descriptionMock": "按组织管理成员资料与状态。在线演示通过 Mock 接口读写,数据保存在当前浏览器。",
|
||||||
|
"descriptionMockCompact": "演示数据保存在当前浏览器。",
|
||||||
"descriptionServer": "按组织管理成员资料、角色与账号状态。",
|
"descriptionServer": "按组织管理成员资料、角色与账号状态。",
|
||||||
"organization": "组织架构",
|
"organization": "组织架构",
|
||||||
"createUser": "新增用户",
|
"createUser": "新增用户",
|
||||||
@ -50,6 +51,7 @@
|
|||||||
"optionsFailed": "组织和角色加载失败",
|
"optionsFailed": "组织和角色加载失败",
|
||||||
"retry": "重试",
|
"retry": "重试",
|
||||||
"viewNamed": "查看 {name} 的详情",
|
"viewNamed": "查看 {name} 的详情",
|
||||||
|
"moreNamed": "{name} 的更多操作",
|
||||||
"editNamed": "编辑 {name}",
|
"editNamed": "编辑 {name}",
|
||||||
"deleteNamed": "删除 {name}",
|
"deleteNamed": "删除 {name}",
|
||||||
"enableNamed": "启用 {name}",
|
"enableNamed": "启用 {name}",
|
||||||
|
|||||||
@ -2,13 +2,16 @@
|
|||||||
"Register": "注册",
|
"Register": "注册",
|
||||||
"PageTitle": "登录 - Ray Admin",
|
"PageTitle": "登录 - Ray Admin",
|
||||||
"Signing": "登录",
|
"Signing": "登录",
|
||||||
|
"SignInMethods": "登录方式",
|
||||||
"QRCodeSigning": "二维码",
|
"QRCodeSigning": "二维码",
|
||||||
"NamePlaceholder": "请输入用户名",
|
"NamePlaceholder": "请输入用户名",
|
||||||
"PasswordPlaceholder": "请输入密码",
|
"PasswordPlaceholder": "请输入密码",
|
||||||
"Login": "登录",
|
"Login": "登录",
|
||||||
"Name": "用户名",
|
"Name": "用户名",
|
||||||
"Password": "密码",
|
"Password": "密码",
|
||||||
"RayTemplate": "构建你的中后台管理系统",
|
"ShowPassword": "显示密码",
|
||||||
|
"HidePassword": "隐藏密码",
|
||||||
|
"RayTemplate": "构建你的\n中后台管理系统",
|
||||||
"TemplateDescription": "基于 Vue 3、TypeScript 和 Naive UI 的开源中后台管理模板。",
|
"TemplateDescription": "基于 Vue 3、TypeScript 和 Naive UI 的开源中后台管理模板。",
|
||||||
"OtherSignInOptions": "其他登录方式示例",
|
"OtherSignInOptions": "其他登录方式示例",
|
||||||
"Resources": "项目资源",
|
"Resources": "项目资源",
|
||||||
|
|||||||
@ -20,6 +20,26 @@ const views = {
|
|||||||
load: () => import('@/views/demo/context-menu/index'),
|
load: () => import('@/views/demo/context-menu/index'),
|
||||||
name: 'ContextMenuDemo',
|
name: 'ContextMenuDemo',
|
||||||
},
|
},
|
||||||
|
'demo/curd/tags': {
|
||||||
|
load: () => import('@/views/demo/curd/tags'),
|
||||||
|
name: 'CurdTags',
|
||||||
|
},
|
||||||
|
'demo/curd/projects': {
|
||||||
|
load: () => import('@/views/demo/curd/projects'),
|
||||||
|
name: 'CurdProjects',
|
||||||
|
},
|
||||||
|
'demo/curd/project-create': {
|
||||||
|
load: () => import('@/views/demo/curd/project-create'),
|
||||||
|
name: 'CurdProjectCreate',
|
||||||
|
},
|
||||||
|
'demo/curd/project-detail': {
|
||||||
|
load: () => import('@/views/demo/curd/project-detail'),
|
||||||
|
name: 'CurdProjectDetail',
|
||||||
|
},
|
||||||
|
'demo/curd/project-edit': {
|
||||||
|
load: () => import('@/views/demo/curd/project-edit'),
|
||||||
|
name: 'CurdProjectEdit',
|
||||||
|
},
|
||||||
'demo/directive': {
|
'demo/directive': {
|
||||||
load: () => import('@/views/demo/directive/index'),
|
load: () => import('@/views/demo/directive/index'),
|
||||||
name: 'RDirective',
|
name: 'RDirective',
|
||||||
|
|||||||
@ -1,5 +1,11 @@
|
|||||||
|
import { nextTick } from 'vue'
|
||||||
import type { App, Component } from 'vue'
|
import type { App, Component } from 'vue'
|
||||||
import { createRouter, createWebHashHistory } from 'vue-router'
|
import {
|
||||||
|
createRouter,
|
||||||
|
createWebHashHistory,
|
||||||
|
isNavigationFailure,
|
||||||
|
NavigationFailureType,
|
||||||
|
} from 'vue-router'
|
||||||
import { getStaticAppRoutes, setAppRouteModules } from './app-route-modules'
|
import { getStaticAppRoutes, setAppRouteModules } from './app-route-modules'
|
||||||
import { loadRouteConfig, resetRouteSource } from './config/source'
|
import { loadRouteConfig, resetRouteSource } from './config/source'
|
||||||
import {
|
import {
|
||||||
@ -13,9 +19,20 @@ import { scrollViewToTop, vueRouterRegister } from './utils'
|
|||||||
export const router = createRouter({
|
export const router = createRouter({
|
||||||
history: createWebHashHistory(),
|
history: createWebHashHistory(),
|
||||||
routes: [],
|
routes: [],
|
||||||
scrollBehavior: (to) => {
|
})
|
||||||
scrollViewToTop(to)
|
|
||||||
},
|
// 工作区使用独立的内容滚动容器,关闭浏览器对文档的自动滚动恢复。
|
||||||
|
if ('scrollRestoration' in window.history)
|
||||||
|
window.history.scrollRestoration = 'manual'
|
||||||
|
|
||||||
|
router.afterEach((to, from, failure) => {
|
||||||
|
if (
|
||||||
|
failure &&
|
||||||
|
!isNavigationFailure(failure, NavigationFailureType.duplicated)
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
void nextTick(() => scrollViewToTop(failure ? from : to))
|
||||||
})
|
})
|
||||||
|
|
||||||
let pending: Promise<void> | undefined
|
let pending: Promise<void> | undefined
|
||||||
|
|||||||
@ -93,8 +93,9 @@ See the [layout guide](../layout/README.md) for usage and slots.
|
|||||||
## Menu synchronization
|
## Menu synchronization
|
||||||
|
|
||||||
- Build menu trees and path indexes when roles change or during explicit refresh. Do not mutate original module routes. After navigation, synchronize tabs and breadcrumbs from Vue Router's matched records.
|
- Build menu trees and path indexes when roles change or during explicit refresh. Do not mutate original module routes. After navigation, synchronize tabs and breadcrumbs from Vue Router's matched records.
|
||||||
- No business root is mandatory or protected. System states (`/welcome`, `/403`, `/404`, `/500`) have no active business menu, breadcrumb, or tab. Never fabricate an active tab from cached selection or the first visible menu.
|
- System states (`/welcome`, `/403`, `/404`, `/500`) have no active business menu, breadcrumb, or tab. Derive the active tab from the actual route.
|
||||||
- Preserve existing cache keys and tab-list structure. Restore historical tabs using registered routes and roles, ignoring deleted or inaccessible routes. Write the session cache only when the tab list changes.
|
- Preserve existing cache keys and tab-list structure. Restore historical tabs using registered routes and roles, ignoring deleted or inaccessible routes. Write the session cache only when the tab list changes.
|
||||||
|
- Store tab order and optional `topped` and `fixed` flags in the ordered tab list. Topped tabs form the leading group while the preference is enabled. The close actions in `useSiderBar` preserve fixed tabs while their preference is enabled. Role or account reconciliation still prunes unavailable tabs.
|
||||||
- Keep one tag per concrete pathname and preserve its latest query/hash in `fullPath`; keep the sidebar's `menuKey` canonical. Derive menu selection from Router rather than a persisted key.
|
- Keep one tag per concrete pathname and preserve its latest query/hash in `fullPath`; keep the sidebar's `menuKey` canonical. Derive menu selection from Router rather than a persisted key.
|
||||||
- Update KeepAlive in recent-access order, deduplicate, trim to its limit, and prune closed or revoked tab names. Merge themes only when the effective theme changes; observe color-weakness mode and document titles independently.
|
- Update KeepAlive in recent-access order, deduplicate, trim to its limit, and prune closed or revoked tab names. Merge themes only when the effective theme changes; observe color-weakness mode and document titles independently.
|
||||||
|
|
||||||
|
|||||||
@ -63,6 +63,11 @@ export const useMenuActions = () => {
|
|||||||
collapsedMenu,
|
collapsedMenu,
|
||||||
spliceMenTagOptions,
|
spliceMenTagOptions,
|
||||||
setMenuTagOptions,
|
setMenuTagOptions,
|
||||||
|
isMenuTagTopped,
|
||||||
|
isMenuTagFixed,
|
||||||
|
toggleMenuTagTop,
|
||||||
|
toggleMenuTagFixed,
|
||||||
|
moveMenuTag,
|
||||||
resolveOption,
|
resolveOption,
|
||||||
updateMenuState,
|
updateMenuState,
|
||||||
setupAppMenu,
|
setupAppMenu,
|
||||||
@ -73,6 +78,11 @@ export const useMenuActions = () => {
|
|||||||
collapsedMenu,
|
collapsedMenu,
|
||||||
spliceMenTagOptions,
|
spliceMenTagOptions,
|
||||||
setMenuTagOptions,
|
setMenuTagOptions,
|
||||||
|
isMenuTagTopped,
|
||||||
|
isMenuTagFixed,
|
||||||
|
toggleMenuTagTop,
|
||||||
|
toggleMenuTagFixed,
|
||||||
|
moveMenuTag,
|
||||||
resolveOption,
|
resolveOption,
|
||||||
updateMenuState,
|
updateMenuState,
|
||||||
setupAppMenu,
|
setupAppMenu,
|
||||||
|
|||||||
@ -38,12 +38,20 @@ export const useSettingGetters = () => {
|
|||||||
* 获取菜单标签开关。
|
* 获取菜单标签开关。
|
||||||
*/
|
*/
|
||||||
const getMenuTagSwitch = computed(() => variable.menuTagSwitch)
|
const getMenuTagSwitch = computed(() => variable.menuTagSwitch)
|
||||||
|
const getMenuTagRound = computed(() => variable.menuTagRound)
|
||||||
|
const getMenuTagTop = computed(() => variable.menuTagTop)
|
||||||
|
const getMenuTagFixed = computed(() => variable.menuTagFixed)
|
||||||
|
const getMenuTagDrag = computed(() => variable.menuTagDrag)
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @description
|
* @description
|
||||||
* 获取面包屑开关。
|
* 获取面包屑开关。
|
||||||
*/
|
*/
|
||||||
const getBreadcrumbSwitch = computed(() => variable.breadcrumbSwitch)
|
const getBreadcrumbSwitch = computed(() => variable.breadcrumbSwitch)
|
||||||
|
const getBreadcrumbIcon = computed(() => variable.breadcrumbIcon)
|
||||||
|
const getBreadcrumbIconFallback = computed(
|
||||||
|
() => variable.breadcrumbIconFallback,
|
||||||
|
)
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @description
|
* @description
|
||||||
@ -132,7 +140,13 @@ export const useSettingGetters = () => {
|
|||||||
getThemeStyle,
|
getThemeStyle,
|
||||||
getAppTheme,
|
getAppTheme,
|
||||||
getMenuTagSwitch,
|
getMenuTagSwitch,
|
||||||
|
getMenuTagRound,
|
||||||
|
getMenuTagTop,
|
||||||
|
getMenuTagFixed,
|
||||||
|
getMenuTagDrag,
|
||||||
getBreadcrumbSwitch,
|
getBreadcrumbSwitch,
|
||||||
|
getBreadcrumbIcon,
|
||||||
|
getBreadcrumbIconFallback,
|
||||||
getLocaleLanguage,
|
getLocaleLanguage,
|
||||||
getLockScreenSwitch,
|
getLockScreenSwitch,
|
||||||
getCopyrightSwitch,
|
getCopyrightSwitch,
|
||||||
|
|||||||
@ -19,6 +19,7 @@ import { pick } from 'lodash-es'
|
|||||||
import { NEllipsis } from 'naive-ui'
|
import { NEllipsis } from 'naive-ui'
|
||||||
import type { LocationQuery } from 'vue-router'
|
import type { LocationQuery } from 'vue-router'
|
||||||
import { piniaNavigationHistoryStore } from '../navigation-history'
|
import { piniaNavigationHistoryStore } from '../navigation-history'
|
||||||
|
import { piniaSettingStore } from '../setting'
|
||||||
import { piniaSigningStore } from '../signing'
|
import { piniaSigningStore } from '../signing'
|
||||||
import { pickRouteRecordNormalizedConstant } from './constant'
|
import { pickRouteRecordNormalizedConstant } from './constant'
|
||||||
import {
|
import {
|
||||||
@ -67,16 +68,14 @@ export const piniaMenuStore = defineStore(
|
|||||||
breadcrumbOptions: [], // 面包屑菜单
|
breadcrumbOptions: [], // 面包屑菜单
|
||||||
currentMenuOption: null, // 当前激活菜单项
|
currentMenuOption: null, // 当前激活菜单项
|
||||||
})
|
})
|
||||||
|
const settings = piniaSettingStore()
|
||||||
const signing = piniaSigningStore()
|
const signing = piniaSigningStore()
|
||||||
const navigationHistory = piniaNavigationHistoryStore()
|
const navigationHistory = piniaNavigationHistoryStore()
|
||||||
const menuIndex = new Map<
|
const menuIndex = new Map<
|
||||||
string,
|
string,
|
||||||
{ option: AppMenuOption; parentPath: string }
|
{ option: AppMenuOption; parentPath: string }
|
||||||
>()
|
>()
|
||||||
const cacheTags = () => {
|
const persistTags = () => {
|
||||||
retainKeepAliveInclude(
|
|
||||||
new Set(menuState.menuTagOptions.map(({ name }) => name)),
|
|
||||||
)
|
|
||||||
setStorage(
|
setStorage(
|
||||||
APP_CATCH_KEY.appMenuTagOptions,
|
APP_CATCH_KEY.appMenuTagOptions,
|
||||||
menuState.menuTagOptions.map(
|
menuState.menuTagOptions.map(
|
||||||
@ -89,20 +88,119 @@ export const piniaMenuStore = defineStore(
|
|||||||
breadcrumbLabel,
|
breadcrumbLabel,
|
||||||
fullPath,
|
fullPath,
|
||||||
closeable,
|
closeable,
|
||||||
|
topped,
|
||||||
|
fixed,
|
||||||
}) => ({
|
}) => ({
|
||||||
name,
|
name,
|
||||||
key,
|
key,
|
||||||
path,
|
path,
|
||||||
show,
|
show,
|
||||||
meta,
|
meta: {
|
||||||
|
...meta,
|
||||||
|
icon: typeof meta.icon === 'string' ? meta.icon : void 0,
|
||||||
|
extra: meta.extra && {
|
||||||
|
...meta.extra,
|
||||||
|
icon:
|
||||||
|
typeof meta.extra.icon === 'string'
|
||||||
|
? meta.extra.icon
|
||||||
|
: void 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
breadcrumbLabel,
|
breadcrumbLabel,
|
||||||
fullPath,
|
fullPath,
|
||||||
closeable,
|
closeable,
|
||||||
|
topped,
|
||||||
|
fixed,
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const syncOpenTags = () => {
|
||||||
|
retainKeepAliveInclude(
|
||||||
|
new Set(menuState.menuTagOptions.map(({ name }) => name)),
|
||||||
|
)
|
||||||
|
persistTags()
|
||||||
|
}
|
||||||
|
|
||||||
|
const isMenuTagTopped = (tag?: MenuTagOptions) =>
|
||||||
|
settings.menuTagTop && tag?.topped === true
|
||||||
|
|
||||||
|
const isMenuTagFixed = (tag?: MenuTagOptions) =>
|
||||||
|
settings.menuTagFixed && tag?.fixed === true
|
||||||
|
|
||||||
|
const orderMenuTags = (tags: MenuTagOptions[]) =>
|
||||||
|
settings.menuTagTop
|
||||||
|
? [
|
||||||
|
...tags.filter(isMenuTagTopped),
|
||||||
|
...tags.filter((tag) => !isMenuTagTopped(tag)),
|
||||||
|
]
|
||||||
|
: tags
|
||||||
|
|
||||||
|
const toggleMenuTagTop = (fullPath: string) => {
|
||||||
|
if (!settings.menuTagTop) return false
|
||||||
|
|
||||||
|
const tags = [...menuState.menuTagOptions]
|
||||||
|
const index = tags.findIndex((tag) => tag.fullPath === fullPath)
|
||||||
|
|
||||||
|
if (index < 0) return false
|
||||||
|
|
||||||
|
const [tag] = tags.splice(index, 1)
|
||||||
|
const topped = !tag.topped
|
||||||
|
const firstRegular = tags.findIndex((tag) => !isMenuTagTopped(tag))
|
||||||
|
const insert = topped ? 0 : firstRegular < 0 ? tags.length : firstRegular
|
||||||
|
|
||||||
|
tags.splice(insert, 0, { ...tag, topped })
|
||||||
|
menuState.menuTagOptions = tags
|
||||||
|
persistTags()
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggleMenuTagFixed = (fullPath: string) => {
|
||||||
|
if (!settings.menuTagFixed) return
|
||||||
|
|
||||||
|
const tags = menuState.menuTagOptions
|
||||||
|
const index = tags.findIndex((tag) => tag.fullPath === fullPath)
|
||||||
|
|
||||||
|
if (index < 0) return
|
||||||
|
|
||||||
|
tags[index] = { ...tags[index], fixed: !tags[index].fixed }
|
||||||
|
persistTags()
|
||||||
|
}
|
||||||
|
|
||||||
|
const moveMenuTag = (
|
||||||
|
fullPath: string,
|
||||||
|
targetPath: string,
|
||||||
|
placement: 'before' | 'after',
|
||||||
|
) => {
|
||||||
|
if (!settings.menuTagDrag) return false
|
||||||
|
|
||||||
|
const tags = [...menuState.menuTagOptions]
|
||||||
|
const from = tags.findIndex((tag) => tag.fullPath === fullPath)
|
||||||
|
const to = tags.findIndex((tag) => tag.fullPath === targetPath)
|
||||||
|
|
||||||
|
if (
|
||||||
|
from < 0 ||
|
||||||
|
to < 0 ||
|
||||||
|
from === to ||
|
||||||
|
isMenuTagTopped(tags[from]) !== isMenuTagTopped(tags[to])
|
||||||
|
)
|
||||||
|
return false
|
||||||
|
|
||||||
|
const insert = to + Number(placement === 'after') - Number(from < to)
|
||||||
|
|
||||||
|
if (from === insert) return false
|
||||||
|
|
||||||
|
const [tag] = tags.splice(from, 1)
|
||||||
|
|
||||||
|
tags.splice(insert, 0, tag)
|
||||||
|
menuState.menuTagOptions = tags
|
||||||
|
persistTags()
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
const clearActiveMenu = () => {
|
const clearActiveMenu = () => {
|
||||||
menuState.menuKey = null
|
menuState.menuKey = null
|
||||||
menuState.currentMenuOption = null
|
menuState.currentMenuOption = null
|
||||||
@ -206,11 +304,11 @@ export const piniaMenuStore = defineStore(
|
|||||||
!option.meta.windowOpen,
|
!option.meta.windowOpen,
|
||||||
)
|
)
|
||||||
|
|
||||||
isAppend
|
menuState.menuTagOptions = orderMenuTags(
|
||||||
? menuState.menuTagOptions.push(...arr)
|
isAppend ? [...menuState.menuTagOptions, ...arr] : arr,
|
||||||
: (menuState.menuTagOptions = arr)
|
)
|
||||||
|
|
||||||
cacheTags()
|
syncOpenTags()
|
||||||
|
|
||||||
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
||||||
}
|
}
|
||||||
@ -237,12 +335,14 @@ export const piniaMenuStore = defineStore(
|
|||||||
|
|
||||||
if (tagIndex < 0) {
|
if (tagIndex < 0) {
|
||||||
menuState.menuTagOptions.push(option)
|
menuState.menuTagOptions.push(option)
|
||||||
cacheTags()
|
syncOpenTags()
|
||||||
} else if (
|
} else if (
|
||||||
menuState.menuTagOptions[tagIndex].fullPath !== option.fullPath
|
menuState.menuTagOptions[tagIndex].fullPath !== option.fullPath
|
||||||
) {
|
) {
|
||||||
menuState.menuTagOptions[tagIndex] = option
|
const { topped, fixed } = menuState.menuTagOptions[tagIndex]
|
||||||
cacheTags()
|
|
||||||
|
menuState.menuTagOptions[tagIndex] = { ...option, topped, fixed }
|
||||||
|
syncOpenTags()
|
||||||
}
|
}
|
||||||
|
|
||||||
setBreadcrumbOptions(option.key)
|
setBreadcrumbOptions(option.key)
|
||||||
@ -372,22 +472,25 @@ export const piniaMenuStore = defineStore(
|
|||||||
menuState.currentMenuOption = null
|
menuState.currentMenuOption = null
|
||||||
menuState.breadcrumbOptions = []
|
menuState.breadcrumbOptions = []
|
||||||
|
|
||||||
const restoredTags = menuState.menuTagOptions.flatMap(({ fullPath }) => {
|
const restoredTags = menuState.menuTagOptions.flatMap(
|
||||||
if (typeof fullPath !== 'string' || !fullPath.startsWith('/')) return []
|
({ fullPath, topped, fixed }) => {
|
||||||
|
if (typeof fullPath !== 'string' || !fullPath.startsWith('/'))
|
||||||
|
return []
|
||||||
|
|
||||||
const option = optionForRoute(resolve(fullPath))
|
const option = optionForRoute(resolve(fullPath))
|
||||||
|
|
||||||
return option && !option.meta.sameLevel && !option.meta.windowOpen
|
return option && !option.meta.sameLevel && !option.meta.windowOpen
|
||||||
? [option]
|
? [{ ...option, topped: topped === true, fixed: fixed === true }]
|
||||||
: []
|
: []
|
||||||
})
|
},
|
||||||
|
)
|
||||||
|
|
||||||
menuState.menuTagOptions = [
|
menuState.menuTagOptions = orderMenuTags([
|
||||||
...new Map(
|
...new Map(
|
||||||
restoredTags.map((option) => [resolve(option.fullPath).path, option]),
|
restoredTags.map((option) => [resolve(option.fullPath).path, option]),
|
||||||
).values(),
|
).values(),
|
||||||
]
|
])
|
||||||
cacheTags()
|
syncOpenTags()
|
||||||
|
|
||||||
const active = optionForRoute(route)
|
const active = optionForRoute(route)
|
||||||
|
|
||||||
@ -426,13 +529,29 @@ export const piniaMenuStore = defineStore(
|
|||||||
const spliceMenTagOptions = (idx: number, length = 1) => {
|
const spliceMenTagOptions = (idx: number, length = 1) => {
|
||||||
const r = menuState.menuTagOptions.splice(idx, length)
|
const r = menuState.menuTagOptions.splice(idx, length)
|
||||||
|
|
||||||
cacheTags()
|
syncOpenTags()
|
||||||
|
|
||||||
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
||||||
|
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => settings.menuTagTop,
|
||||||
|
(enabled) => {
|
||||||
|
if (!enabled) return
|
||||||
|
|
||||||
|
const current = menuState.menuTagOptions
|
||||||
|
const ordered = orderMenuTags(current)
|
||||||
|
|
||||||
|
if (ordered.every((tag, index) => tag === current[index])) return
|
||||||
|
|
||||||
|
menuState.menuTagOptions = ordered
|
||||||
|
persistTags()
|
||||||
|
},
|
||||||
|
{ flush: 'sync' },
|
||||||
|
)
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
[
|
[
|
||||||
() => signing.signingCallback.role,
|
() => signing.signingCallback.role,
|
||||||
@ -446,7 +565,7 @@ export const piniaMenuStore = defineStore(
|
|||||||
if (!current[1]) {
|
if (!current[1]) {
|
||||||
menuState.options = []
|
menuState.options = []
|
||||||
menuIndex.clear()
|
menuIndex.clear()
|
||||||
cacheTags()
|
syncOpenTags()
|
||||||
clearActiveMenu()
|
clearActiveMenu()
|
||||||
|
|
||||||
return
|
return
|
||||||
@ -488,6 +607,11 @@ export const piniaMenuStore = defineStore(
|
|||||||
collapsedMenu,
|
collapsedMenu,
|
||||||
spliceMenTagOptions,
|
spliceMenTagOptions,
|
||||||
setMenuTagOptions,
|
setMenuTagOptions,
|
||||||
|
isMenuTagTopped,
|
||||||
|
isMenuTagFixed,
|
||||||
|
toggleMenuTagTop,
|
||||||
|
toggleMenuTagFixed,
|
||||||
|
moveMenuTag,
|
||||||
resolveOption,
|
resolveOption,
|
||||||
updateMenuState,
|
updateMenuState,
|
||||||
setupAppMenu,
|
setupAppMenu,
|
||||||
|
|||||||
@ -1,12 +1,17 @@
|
|||||||
import { APP_CATCH_KEY } from '@/app-config'
|
import { APP_CATCH_KEY } from '@/app-config'
|
||||||
import { useI18n } from '@/hooks'
|
import { useI18n } from '@/hooks'
|
||||||
import { resolveIconName } from '@/icons'
|
import { resolveIconName } from '@/icons'
|
||||||
import type { AppMenuKey, AppMenuOption } from '@/types/modules/app'
|
import type {
|
||||||
|
AppMenuKey,
|
||||||
|
AppMenuOption,
|
||||||
|
MenuTagOptions,
|
||||||
|
} from '@/types/modules/app'
|
||||||
import { getStorage } from '@/utils/cache'
|
import { getStorage } from '@/utils/cache'
|
||||||
import { isValueType } from '@/utils/core'
|
import { isValueType } from '@/utils/core'
|
||||||
import { RIcon } from '@ray-template/ui/icon'
|
import { RIcon } from '@ray-template/ui/icon'
|
||||||
import { NTag } from 'naive-ui'
|
import { NTag } from 'naive-ui'
|
||||||
import type { TagProps } from 'naive-ui'
|
import type { TagProps } from 'naive-ui'
|
||||||
|
import { cloneVNode } from 'vue'
|
||||||
import { piniaSettingStore } from '../setting'
|
import { piniaSettingStore } from '../setting'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -148,7 +153,7 @@ export const createMenuIcon = (option: AppMenuOption) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isValueType<object>(icon, 'Object')) {
|
if (isValueType<object>(icon, 'Object')) {
|
||||||
return () => icon
|
return () => cloneVNode(icon)
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = resolveIconName(icon)
|
const name = resolveIconName(icon)
|
||||||
@ -228,7 +233,7 @@ export const getCatchMenuKey = () => {
|
|||||||
* @returns 获取缓存的菜单标签页
|
* @returns 获取缓存的菜单标签页
|
||||||
*/
|
*/
|
||||||
export const getCatchMenuTagOptions = () => {
|
export const getCatchMenuTagOptions = () => {
|
||||||
const cached = getStorage<AppMenuOption[]>(
|
const cached = getStorage<MenuTagOptions[]>(
|
||||||
APP_CATCH_KEY.appMenuTagOptions,
|
APP_CATCH_KEY.appMenuTagOptions,
|
||||||
'sessionStorage',
|
'sessionStorage',
|
||||||
)
|
)
|
||||||
|
|||||||
@ -10,7 +10,13 @@ type OmitKeys =
|
|||||||
| 'keepAliveConfig'
|
| 'keepAliveConfig'
|
||||||
| 'menuConfig'
|
| 'menuConfig'
|
||||||
| 'menuTagSwitch'
|
| 'menuTagSwitch'
|
||||||
|
| 'menuTagRound'
|
||||||
|
| 'menuTagTop'
|
||||||
|
| 'menuTagFixed'
|
||||||
|
| 'menuTagDrag'
|
||||||
| 'breadcrumbSwitch'
|
| 'breadcrumbSwitch'
|
||||||
|
| 'breadcrumbIcon'
|
||||||
|
| 'breadcrumbIconFallback'
|
||||||
| 'copyrightSwitch'
|
| 'copyrightSwitch'
|
||||||
| 'drawerPlacement'
|
| 'drawerPlacement'
|
||||||
| 'colorWeakness'
|
| 'colorWeakness'
|
||||||
@ -57,8 +63,14 @@ const defaultSettingConfig: Readonly<Config> = {
|
|||||||
},
|
},
|
||||||
// 多标签页开关
|
// 多标签页开关
|
||||||
menuTagSwitch: true,
|
menuTagSwitch: true,
|
||||||
|
menuTagRound: false,
|
||||||
|
menuTagTop: true,
|
||||||
|
menuTagFixed: true,
|
||||||
|
menuTagDrag: true,
|
||||||
// 面包屑开关
|
// 面包屑开关
|
||||||
breadcrumbSwitch: true,
|
breadcrumbSwitch: true,
|
||||||
|
breadcrumbIcon: true,
|
||||||
|
breadcrumbIconFallback: true,
|
||||||
// 底部区域开关
|
// 底部区域开关
|
||||||
copyrightSwitch: true,
|
copyrightSwitch: true,
|
||||||
// 默认设置出现位置
|
// 默认设置出现位置
|
||||||
|
|||||||
@ -106,6 +106,7 @@ export const piniaSettingStore = defineStore(
|
|||||||
accent.primaryColor,
|
accent.primaryColor,
|
||||||
accent.primaryColorHover ?? accent.primaryColor,
|
accent.primaryColorHover ?? accent.primaryColor,
|
||||||
surface,
|
surface,
|
||||||
|
mode,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
|||||||
@ -61,7 +61,13 @@ const preferences = v.strictObject({
|
|||||||
),
|
),
|
||||||
drawerPlacement: v.picklist(['left', 'right']),
|
drawerPlacement: v.picklist(['left', 'right']),
|
||||||
breadcrumbSwitch: flag,
|
breadcrumbSwitch: flag,
|
||||||
|
breadcrumbIcon: v.optional(flag, true),
|
||||||
|
breadcrumbIconFallback: v.optional(flag, true),
|
||||||
menuTagSwitch: flag,
|
menuTagSwitch: flag,
|
||||||
|
menuTagRound: v.optional(flag, false),
|
||||||
|
menuTagTop: v.optional(flag, true),
|
||||||
|
menuTagFixed: v.optional(flag, true),
|
||||||
|
menuTagDrag: v.optional(flag, true),
|
||||||
copyrightSwitch: flag,
|
copyrightSwitch: flag,
|
||||||
colorWeakness: flag,
|
colorWeakness: flag,
|
||||||
menuConfig: v.strictObject({
|
menuConfig: v.strictObject({
|
||||||
|
|||||||
@ -3,15 +3,17 @@
|
|||||||
* @param primary 用户选择的主色
|
* @param primary 用户选择的主色
|
||||||
* @param hover 悬停与聚焦状态的主色
|
* @param hover 悬停与聚焦状态的主色
|
||||||
* @param surface 当前风格和明暗模式的卡片底色
|
* @param surface 当前风格和明暗模式的卡片底色
|
||||||
|
* @param mode 当前明暗模式
|
||||||
*
|
*
|
||||||
* @description
|
* @description
|
||||||
* 用浏览器解析 CSS 颜色,并把半透明填充合成在主题底色上。按钮使用同一不透明色,
|
* 在主题底色上解析自定义主色。浅色实心按钮沿用白字,需要时加深填充色;
|
||||||
* 使文字对比度不受按钮下方实际页面内容影响。
|
* 深色按钮按实际填充色选取对比度更高的文字色。
|
||||||
*/
|
*/
|
||||||
export function primaryButtonColors(
|
export function primaryButtonColors(
|
||||||
primary: string,
|
primary: string,
|
||||||
hover: string,
|
hover: string,
|
||||||
surface: string,
|
surface: string,
|
||||||
|
mode: 'light' | 'dark',
|
||||||
) {
|
) {
|
||||||
const canvas = document.createElement('canvas')
|
const canvas = document.createElement('canvas')
|
||||||
|
|
||||||
@ -30,35 +32,71 @@ export function primaryButtonColors(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const pixels = context.getImageData(0, 0, 2, 1).data
|
const pixels = context.getImageData(0, 0, 2, 1).data
|
||||||
const colors = (index: number) => {
|
const colors = (index: number, whiteTextContrast?: number) => {
|
||||||
const rgb = Array.from(pixels.slice(index, index + 3))
|
const rgb = Array.from(pixels.slice(index, index + 3))
|
||||||
const [r, g, b] = rgb.map((byte) => {
|
const channels = rgb.map((byte) => {
|
||||||
const channel = byte / 255
|
const channel = byte / 255
|
||||||
|
|
||||||
return channel <= 0.04045
|
return channel <= 0.04045
|
||||||
? channel / 12.92
|
? channel / 12.92
|
||||||
: ((channel + 0.055) / 1.055) ** 2.4
|
: ((channel + 0.055) / 1.055) ** 2.4
|
||||||
})
|
})
|
||||||
|
const [r, g, b] = channels
|
||||||
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
|
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||||
const blackContrast = (luminance + 0.05) / 0.05
|
const blackContrast = (luminance + 0.05) / 0.05
|
||||||
const whiteContrast = 1.05 / (luminance + 0.05)
|
const whiteContrast = 1.05 / (luminance + 0.05)
|
||||||
|
let fill = rgb
|
||||||
|
|
||||||
|
if (whiteTextContrast !== void 0 && whiteContrast < whiteTextContrast) {
|
||||||
|
const scale = (1.05 / whiteTextContrast - 0.05) / luminance
|
||||||
|
|
||||||
|
fill = channels.map((channel) => {
|
||||||
|
const linear = channel * scale
|
||||||
|
const srgb =
|
||||||
|
linear <= 0.0031308
|
||||||
|
? linear * 12.92
|
||||||
|
: 1.055 * linear ** (1 / 2.4) - 0.055
|
||||||
|
|
||||||
|
return Math.floor(srgb * 255)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
fill: `rgb(${rgb.join(', ')})`,
|
fill: `rgb(${fill.join(', ')})`,
|
||||||
text: blackContrast >= whiteContrast ? '#000' : '#fff',
|
text:
|
||||||
|
whiteTextContrast !== void 0 || whiteContrast > blackContrast
|
||||||
|
? '#fff'
|
||||||
|
: '#000',
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const normal = colors(0)
|
// 默认态预留对比度余量,让悬停提亮后仍满足白字可读性。
|
||||||
const active = colors(4)
|
const light = mode === 'light'
|
||||||
|
const normal = colors(0, light ? 5 : void 0)
|
||||||
|
const active = colors(4, light ? 4.5 : void 0)
|
||||||
|
const pressed = light ? colors(0, 5.5) : normal
|
||||||
|
|
||||||
return {
|
return {
|
||||||
colorPrimary: normal.fill,
|
colorPrimary: normal.fill,
|
||||||
colorPressedPrimary: normal.fill,
|
colorPressedPrimary: pressed.fill,
|
||||||
colorHoverPrimary: active.fill,
|
colorHoverPrimary: active.fill,
|
||||||
colorFocusPrimary: active.fill,
|
colorFocusPrimary: active.fill,
|
||||||
textColorPrimary: normal.text,
|
textColorPrimary: normal.text,
|
||||||
textColorPressedPrimary: normal.text,
|
textColorPressedPrimary: pressed.text,
|
||||||
textColorHoverPrimary: active.text,
|
textColorHoverPrimary: active.text,
|
||||||
textColorFocusPrimary: active.text,
|
textColorFocusPrimary: active.text,
|
||||||
|
...(light && {
|
||||||
|
borderPrimary: `1px solid ${normal.fill}`,
|
||||||
|
borderHoverPrimary: `1px solid ${active.fill}`,
|
||||||
|
borderPressedPrimary: `1px solid ${pressed.fill}`,
|
||||||
|
borderFocusPrimary: `1px solid ${active.fill}`,
|
||||||
|
textColorGhostPrimary: normal.fill,
|
||||||
|
textColorGhostHoverPrimary: active.fill,
|
||||||
|
textColorGhostPressedPrimary: pressed.fill,
|
||||||
|
textColorGhostFocusPrimary: active.fill,
|
||||||
|
textColorTextPrimary: normal.fill,
|
||||||
|
textColorTextHoverPrimary: active.fill,
|
||||||
|
textColorTextPressedPrimary: pressed.fill,
|
||||||
|
textColorTextFocusPrimary: active.fill,
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -37,7 +37,13 @@ export interface SettingState {
|
|||||||
appTheme: 'dark' | 'light' | 'auto'
|
appTheme: 'dark' | 'light' | 'auto'
|
||||||
_appTheme: boolean
|
_appTheme: boolean
|
||||||
menuTagSwitch: boolean
|
menuTagSwitch: boolean
|
||||||
|
menuTagRound: boolean
|
||||||
|
menuTagTop: boolean
|
||||||
|
menuTagFixed: boolean
|
||||||
|
menuTagDrag: boolean
|
||||||
breadcrumbSwitch: boolean
|
breadcrumbSwitch: boolean
|
||||||
|
breadcrumbIcon: boolean
|
||||||
|
breadcrumbIconFallback: boolean
|
||||||
localeLanguage: string
|
localeLanguage: string
|
||||||
lockScreenSwitch: boolean
|
lockScreenSwitch: boolean
|
||||||
watermarkSwitch: boolean
|
watermarkSwitch: boolean
|
||||||
|
|||||||
@ -80,17 +80,6 @@ export default defineComponent({
|
|||||||
<RIcon name="logo/ray" size={44} />
|
<RIcon name="logo/ray" size={44} />
|
||||||
</span>
|
</span>
|
||||||
</AppPageHeader>
|
</AppPageHeader>
|
||||||
<div class="r-dashboard-stack">
|
|
||||||
{stack.map((item) => (
|
|
||||||
<article key={item.name} class="r-dashboard-stack__item">
|
|
||||||
<span>{item.name}</span>
|
|
||||||
<strong>{item.version}</strong>
|
|
||||||
<small>
|
|
||||||
{item.name === 'Pinia' ? text('stateManagement') : item.detail}
|
|
||||||
</small>
|
|
||||||
</article>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{shortcuts.value.length ? (
|
{shortcuts.value.length ? (
|
||||||
<section aria-labelledby={shortcutsTitle}>
|
<section aria-labelledby={shortcutsTitle}>
|
||||||
<h2 id={shortcutsTitle} class="r-dashboard__section-title">
|
<h2 id={shortcutsTitle} class="r-dashboard__section-title">
|
||||||
@ -120,6 +109,17 @@ export default defineComponent({
|
|||||||
</nav>
|
</nav>
|
||||||
</section>
|
</section>
|
||||||
) : null}
|
) : null}
|
||||||
|
<div class="r-dashboard-stack">
|
||||||
|
{stack.map((item) => (
|
||||||
|
<article key={item.name} class="r-dashboard-stack__item">
|
||||||
|
<span>{item.name}</span>
|
||||||
|
<strong>{item.version}</strong>
|
||||||
|
<small>
|
||||||
|
{item.name === 'Pinia' ? text('stateManagement') : item.detail}
|
||||||
|
</small>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
<div class="r-dashboard-info">
|
<div class="r-dashboard-info">
|
||||||
<NCard title={text('project')}>
|
<NCard title={text('project')}>
|
||||||
<p class="r-dashboard-info__intro">{text('projectDescription')}</p>
|
<p class="r-dashboard-info__intro">{text('projectDescription')}</p>
|
||||||
|
|||||||
@ -12,7 +12,7 @@
|
|||||||
.r-showcase-meta {
|
.r-showcase-meta {
|
||||||
padding: 7px 12px;
|
padding: 7px 12px;
|
||||||
border: 1px solid var(--r-line);
|
border: 1px solid var(--r-line);
|
||||||
border-radius: 8px;
|
border-radius: var(--r-control-radius);
|
||||||
color: var(--r-text-secondary);
|
color: var(--r-text-secondary);
|
||||||
background: var(--r-surface);
|
background: var(--r-surface);
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
@ -27,6 +27,15 @@
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.r-demo-control-label {
|
||||||
|
position: absolute;
|
||||||
|
inline-size: 1px;
|
||||||
|
block-size: 1px;
|
||||||
|
overflow: hidden;
|
||||||
|
clip-path: inset(50%);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
.r-demo-section-heading {
|
.r-demo-section-heading {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@ -137,7 +146,7 @@
|
|||||||
min-height: 150px;
|
min-height: 150px;
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
border: 1px solid var(--r-line);
|
border: 1px solid var(--r-line);
|
||||||
border-radius: 10px;
|
border-radius: var(--r-radius);
|
||||||
background: #fff;
|
background: #fff;
|
||||||
color: #182436;
|
color: #182436;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
@ -153,7 +162,7 @@
|
|||||||
gap: 6px;
|
gap: 6px;
|
||||||
padding: 12px 14px;
|
padding: 12px 14px;
|
||||||
border: 1px solid var(--r-line);
|
border: 1px solid var(--r-line);
|
||||||
border-radius: 8px;
|
border-radius: var(--r-radius);
|
||||||
background: var(--r-surface-muted);
|
background: var(--r-surface-muted);
|
||||||
color: var(--r-text);
|
color: var(--r-text);
|
||||||
|
|
||||||
@ -183,7 +192,7 @@
|
|||||||
min-height: 112px;
|
min-height: 112px;
|
||||||
display: grid;
|
display: grid;
|
||||||
place-items: center;
|
place-items: center;
|
||||||
border-radius: 8px;
|
border-radius: var(--r-radius);
|
||||||
background: var(--r-canvas);
|
background: var(--r-canvas);
|
||||||
|
|
||||||
span {
|
span {
|
||||||
@ -191,7 +200,7 @@
|
|||||||
block-size: 68px;
|
block-size: 68px;
|
||||||
border: 1px solid var(--r-control-border);
|
border: 1px solid var(--r-control-border);
|
||||||
border-block-start: 10px solid var(--r-theme-primary-color);
|
border-block-start: 10px solid var(--r-theme-primary-color);
|
||||||
border-radius: 5px;
|
border-radius: var(--r-radius);
|
||||||
background: var(--r-surface);
|
background: var(--r-surface);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -218,5 +227,5 @@
|
|||||||
min-width: 0;
|
min-width: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
border: 1px solid var(--r-line);
|
border: 1px solid var(--r-line);
|
||||||
border-radius: 8px;
|
border-radius: var(--r-radius);
|
||||||
}
|
}
|
||||||
|
|||||||
58
apps/admin/src/views/demo/curd/ProjectDescription.tsx
Normal file
58
apps/admin/src/views/demo/curd/ProjectDescription.tsx
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import { useI18n } from '@/hooks/template/useI18n'
|
||||||
|
import {
|
||||||
|
NCard,
|
||||||
|
NDescriptions,
|
||||||
|
NDescriptionsItem,
|
||||||
|
NFlex,
|
||||||
|
NList,
|
||||||
|
NListItem,
|
||||||
|
NText,
|
||||||
|
} from 'naive-ui'
|
||||||
|
import type { PropType } from 'vue'
|
||||||
|
import type { Project } from './records'
|
||||||
|
|
||||||
|
export default defineComponent({
|
||||||
|
name: 'ProjectDescription',
|
||||||
|
props: {
|
||||||
|
project: { type: Object as PropType<Project>, required: true },
|
||||||
|
},
|
||||||
|
setup(props) {
|
||||||
|
const { t } = useI18n('curd')
|
||||||
|
|
||||||
|
return () => (
|
||||||
|
<NFlex vertical size={20}>
|
||||||
|
<NCard title={t('overview')}>
|
||||||
|
<NDescriptions column={1} labelPlacement="left">
|
||||||
|
<NDescriptionsItem label={t('owner')}>
|
||||||
|
{props.project.owner}
|
||||||
|
</NDescriptionsItem>
|
||||||
|
<NDescriptionsItem label={t('status')}>
|
||||||
|
{t(props.project.status)}
|
||||||
|
</NDescriptionsItem>
|
||||||
|
<NDescriptionsItem label={t('summary')}>
|
||||||
|
{props.project.summary || '—'}
|
||||||
|
</NDescriptionsItem>
|
||||||
|
</NDescriptions>
|
||||||
|
</NCard>
|
||||||
|
<NCard title={t('milestones')}>
|
||||||
|
{props.project.milestones.length ? (
|
||||||
|
<NList>
|
||||||
|
{props.project.milestones.map((milestone) => (
|
||||||
|
<NListItem key={milestone.id}>
|
||||||
|
<NFlex vertical size={4} style={{ overflowWrap: 'anywhere' }}>
|
||||||
|
<strong>{milestone.name}</strong>
|
||||||
|
{milestone.outcome && (
|
||||||
|
<NText depth={2}>{milestone.outcome}</NText>
|
||||||
|
)}
|
||||||
|
</NFlex>
|
||||||
|
</NListItem>
|
||||||
|
))}
|
||||||
|
</NList>
|
||||||
|
) : (
|
||||||
|
<NText depth={2}>{t('noMilestones')}</NText>
|
||||||
|
)}
|
||||||
|
</NCard>
|
||||||
|
</NFlex>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
258
apps/admin/src/views/demo/curd/ProjectEditor.tsx
Normal file
258
apps/admin/src/views/demo/curd/ProjectEditor.tsx
Normal file
@ -0,0 +1,258 @@
|
|||||||
|
import './project-editor.scss'
|
||||||
|
import { useI18n } from '@/hooks/template/useI18n'
|
||||||
|
import { useRuntimeGetters } from '@/store/hooks/useRuntimeStore'
|
||||||
|
import { RForm } from '@ray-template/ui/form'
|
||||||
|
import { uuid } from '@ray-template/utils/core'
|
||||||
|
import { cloneDeep } from 'lodash-es'
|
||||||
|
import {
|
||||||
|
NButton,
|
||||||
|
NCard,
|
||||||
|
NFlex,
|
||||||
|
NFormItem,
|
||||||
|
NFormItemGi,
|
||||||
|
NGrid,
|
||||||
|
NInput,
|
||||||
|
NList,
|
||||||
|
NListItem,
|
||||||
|
NRadio,
|
||||||
|
NRadioGroup,
|
||||||
|
NText,
|
||||||
|
useMessage,
|
||||||
|
} from 'naive-ui'
|
||||||
|
import type { PropType } from 'vue'
|
||||||
|
import type { RouteLocationNormalizedLoaded } from 'vue-router'
|
||||||
|
import DemoPage from '../components/DemoPage'
|
||||||
|
import { useCurdEditor } from './interactions'
|
||||||
|
import type { WriteResult } from './interactions'
|
||||||
|
import { projectStatuses } from './records'
|
||||||
|
import type { ProjectDraft } from './records'
|
||||||
|
|
||||||
|
let reloadingDraft:
|
||||||
|
| {
|
||||||
|
route: RouteLocationNormalizedLoaded
|
||||||
|
draft: ProjectDraft
|
||||||
|
}
|
||||||
|
| undefined
|
||||||
|
|
||||||
|
export default defineComponent({
|
||||||
|
name: 'ProjectEditor',
|
||||||
|
props: {
|
||||||
|
title: { type: String, required: true },
|
||||||
|
submitLabel: { type: String, required: true },
|
||||||
|
initial: { type: Object as PropType<ProjectDraft>, required: true },
|
||||||
|
save: {
|
||||||
|
type: Function as PropType<(draft: ProjectDraft) => WriteResult>,
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
onReturn: { type: Function as PropType<() => void>, required: true },
|
||||||
|
},
|
||||||
|
setup(props) {
|
||||||
|
const { t } = useI18n('curd')
|
||||||
|
const message = useMessage()
|
||||||
|
const router = useRouter()
|
||||||
|
const mountedRoute = router.currentRoute.value
|
||||||
|
const { globalMainLayoutLoad } = useRuntimeGetters()
|
||||||
|
const id = useId()
|
||||||
|
const field = (name: string) => `${id}-${name}`
|
||||||
|
const editor = useCurdEditor(props.initial, props.save, () => {
|
||||||
|
message.success(t('saved'))
|
||||||
|
props.onReturn()
|
||||||
|
})
|
||||||
|
const { draft } = editor
|
||||||
|
|
||||||
|
if (reloadingDraft?.route === mountedRoute)
|
||||||
|
draft.value = reloadingDraft.draft
|
||||||
|
|
||||||
|
reloadingDraft = void 0
|
||||||
|
|
||||||
|
onBeforeRouteLeave(editor.canLeave)
|
||||||
|
onBeforeRouteUpdate(editor.canLeave)
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
// 工作区刷新会重挂载当前路由;仅同一次路由访问可接回草稿。
|
||||||
|
if (
|
||||||
|
!globalMainLayoutLoad.value &&
|
||||||
|
router.currentRoute.value === mountedRoute &&
|
||||||
|
editor.dirty.value
|
||||||
|
)
|
||||||
|
reloadingDraft = { route: mountedRoute, draft: cloneDeep(draft.value) }
|
||||||
|
})
|
||||||
|
|
||||||
|
const required = (key: string) => ({
|
||||||
|
required: true,
|
||||||
|
whitespace: true,
|
||||||
|
trigger: 'blur',
|
||||||
|
message: t(key),
|
||||||
|
})
|
||||||
|
const focusMilestone = (milestoneId?: string) => {
|
||||||
|
void nextTick(() => {
|
||||||
|
const target = milestoneId ? field(milestoneId) : field('add-milestone')
|
||||||
|
|
||||||
|
document.getElementById(target)?.focus()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const addMilestone = () => {
|
||||||
|
const id = uuid()
|
||||||
|
|
||||||
|
draft.value.milestones.push({ id, name: '', outcome: '' })
|
||||||
|
focusMilestone(id)
|
||||||
|
}
|
||||||
|
const removeMilestone = (index: number) => {
|
||||||
|
draft.value.milestones.splice(index, 1)
|
||||||
|
focusMilestone(
|
||||||
|
draft.value.milestones[index]?.id ?? draft.value.milestones.at(-1)?.id,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return () => (
|
||||||
|
<DemoPage title={props.title} description={t('editorIntro')}>
|
||||||
|
<RForm {...editor.formProps} model={draft.value} labelPlacement="top">
|
||||||
|
<NFlex vertical size={20}>
|
||||||
|
{editor.errorNotice()}
|
||||||
|
<NCard title={t('overview')}>
|
||||||
|
<NGrid cols="1 560:2" responsive="self" xGap={16}>
|
||||||
|
<NFormItemGi
|
||||||
|
label={t('projectName')}
|
||||||
|
labelProps={{ for: field('name') }}
|
||||||
|
path="name"
|
||||||
|
rule={required('nameRequired')}
|
||||||
|
>
|
||||||
|
<NInput
|
||||||
|
v-model:value={draft.value.name}
|
||||||
|
inputProps={{ id: field('name'), required: true }}
|
||||||
|
maxlength={80}
|
||||||
|
/>
|
||||||
|
</NFormItemGi>
|
||||||
|
<NFormItemGi
|
||||||
|
label={t('owner')}
|
||||||
|
labelProps={{ for: field('owner') }}
|
||||||
|
path="owner"
|
||||||
|
rule={required('ownerRequired')}
|
||||||
|
>
|
||||||
|
<NInput
|
||||||
|
v-model:value={draft.value.owner}
|
||||||
|
inputProps={{ id: field('owner'), required: true }}
|
||||||
|
maxlength={60}
|
||||||
|
/>
|
||||||
|
</NFormItemGi>
|
||||||
|
</NGrid>
|
||||||
|
<NFormItem
|
||||||
|
label={t('status')}
|
||||||
|
labelProps={{ id: field('status') }}
|
||||||
|
>
|
||||||
|
<NRadioGroup
|
||||||
|
v-model:value={draft.value.status}
|
||||||
|
{...{
|
||||||
|
role: 'radiogroup',
|
||||||
|
'aria-labelledby': field('status'),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<NFlex>
|
||||||
|
{projectStatuses.map((status) => (
|
||||||
|
<NRadio key={status} value={status}>
|
||||||
|
{t(status)}
|
||||||
|
</NRadio>
|
||||||
|
))}
|
||||||
|
</NFlex>
|
||||||
|
</NRadioGroup>
|
||||||
|
</NFormItem>
|
||||||
|
<NFormItem
|
||||||
|
label={t('summary')}
|
||||||
|
labelProps={{ for: field('summary') }}
|
||||||
|
>
|
||||||
|
<NInput
|
||||||
|
class="curd-project-editor__summary"
|
||||||
|
v-model:value={draft.value.summary}
|
||||||
|
inputProps={{ id: field('summary') }}
|
||||||
|
type="textarea"
|
||||||
|
maxlength={500}
|
||||||
|
autosize
|
||||||
|
/>
|
||||||
|
</NFormItem>
|
||||||
|
</NCard>
|
||||||
|
<NCard title={t('milestones')}>
|
||||||
|
{{
|
||||||
|
'header-extra': () => (
|
||||||
|
<NButton
|
||||||
|
{...{ id: field('add-milestone') }}
|
||||||
|
size="small"
|
||||||
|
onClick={addMilestone}
|
||||||
|
>
|
||||||
|
{t('addMilestone')}
|
||||||
|
</NButton>
|
||||||
|
),
|
||||||
|
default: () =>
|
||||||
|
draft.value.milestones.length ? (
|
||||||
|
<NList>
|
||||||
|
{draft.value.milestones.map((milestone, index) => (
|
||||||
|
<NListItem key={milestone.id}>
|
||||||
|
<NFlex justify="space-between" align="center">
|
||||||
|
<strong>
|
||||||
|
{t('milestoneNumber', { number: index + 1 })}
|
||||||
|
</strong>
|
||||||
|
<NButton
|
||||||
|
text
|
||||||
|
aria-label={t('removeMilestoneNumber', {
|
||||||
|
number: index + 1,
|
||||||
|
})}
|
||||||
|
onClick={() => removeMilestone(index)}
|
||||||
|
>
|
||||||
|
{t('removeMilestone')}
|
||||||
|
</NButton>
|
||||||
|
</NFlex>
|
||||||
|
<NGrid cols="1 560:2" responsive="self" xGap={16}>
|
||||||
|
<NFormItemGi
|
||||||
|
label={t('milestoneName')}
|
||||||
|
labelProps={{ for: field(milestone.id) }}
|
||||||
|
path={`milestones.${index}.name`}
|
||||||
|
rule={required('milestoneRequired')}
|
||||||
|
>
|
||||||
|
<NInput
|
||||||
|
v-model:value={milestone.name}
|
||||||
|
inputProps={{
|
||||||
|
id: field(milestone.id),
|
||||||
|
required: true,
|
||||||
|
}}
|
||||||
|
maxlength={80}
|
||||||
|
/>
|
||||||
|
</NFormItemGi>
|
||||||
|
<NFormItemGi
|
||||||
|
label={t('milestoneOutcome')}
|
||||||
|
labelProps={{
|
||||||
|
for: field(`${milestone.id}-outcome`),
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<NInput
|
||||||
|
v-model:value={milestone.outcome}
|
||||||
|
inputProps={{
|
||||||
|
id: field(`${milestone.id}-outcome`),
|
||||||
|
}}
|
||||||
|
maxlength={120}
|
||||||
|
/>
|
||||||
|
</NFormItemGi>
|
||||||
|
</NGrid>
|
||||||
|
</NListItem>
|
||||||
|
))}
|
||||||
|
</NList>
|
||||||
|
) : (
|
||||||
|
<NText depth={2}>{t('noMilestones')}</NText>
|
||||||
|
),
|
||||||
|
}}
|
||||||
|
</NCard>
|
||||||
|
<NFlex justify="end">
|
||||||
|
<NButton disabled={editor.saving.value} onClick={props.onReturn}>
|
||||||
|
{t('cancel')}
|
||||||
|
</NButton>
|
||||||
|
<NButton
|
||||||
|
type="primary"
|
||||||
|
attrType="submit"
|
||||||
|
loading={editor.saving.value}
|
||||||
|
>
|
||||||
|
{props.submitLabel}
|
||||||
|
</NButton>
|
||||||
|
</NFlex>
|
||||||
|
</NFlex>
|
||||||
|
</RForm>
|
||||||
|
</DemoPage>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
})
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user