Compare commits

..

No commits in common. "main" and "v5.2.5" have entirely different histories.
main ... v5.2.5

1534 changed files with 14571 additions and 85836 deletions

View File

@ -5,15 +5,3 @@ node_modules
dist
.ai-local
.harness-local
**/node_modules
**/.vitepress/cache
**/.vitepress/dist
**/.env
**/.env.*
!apps/admin/.env.development
!apps/admin/.env.production
!apps/admin/.env.test
**/dist-test
**/src/generated
.pnpm-store

38
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,38 @@
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
open-pull-requests-limit: 5
groups:
vue:
patterns:
[
'vue',
'vue-router',
'pinia',
'pinia-plugin-persistedstate',
'@vue/*',
'@vueuse/*',
]
testing:
patterns: ['vitest', '@vitest/*', 'happy-dom']
lint:
patterns:
[
'eslint*',
'@eslint/*',
'typescript-eslint',
'vue-eslint-parser',
'prettier',
'@ianvs/*',
]
ignore:
# Vue Language Tools 和 typescript-eslint 尚不支持 TypeScript 7。
- dependency-name: typescript
versions: ['>=7']
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly

View File

@ -1,11 +1,11 @@
## Changes and rationale
## 变化与原因
<!-- Describe the observable change and the problem it addresses. -->
<!-- 描述用户能观察到的变化,以及需要这次改动的原因。 -->
## Verification
## 验证
- [ ] Run relevant tests or `pnpm harness verify <scope>` for the affected area. Use `pnpm harness verify all` for integration risk or releases; CI runs `pnpm check`.
- [ ] For visible behavior changes, verify only affected pages, actions, and language/theme/viewport dimensions. Explain when this does not apply.
- [ ] For persistence, permissions, or shared components, check compatibility with existing data and callers.
- [ ] `pnpm harness verify` 或 CI 的 `pnpm check`
- [ ] 涉及页面时,验证对应路由、中文/英文与明暗主题
- [ ] 涉及持久化、权限或公共组件时,检查已有数据与调用方兼容性
<!-- Select the verification scope using harness/README.md. Record actual commands, results, regression cases, and unverified areas. For browser verification, include actions and observations; mark it as not applicable when there is no UI impact. -->
<!-- 写明实际命令、结果、回归用例和未验证部分。浏览器验收附上操作与观察结果。 -->

View File

@ -1,8 +1,8 @@
name: Pages
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
@ -13,42 +13,42 @@ concurrency:
cancel-in-progress: true
jobs:
build:
name: Build admin and documentation
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-24.04
check:
name: Check (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@v7.1.0
with:
node-version-file: .nvmrc
- uses: pnpm/action-setup@v6.1.1
- uses: pnpm/action-setup@v6.1.0
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build admin and documentation
run: pnpm pages:build
env:
RAY_TEMPLATE_SITE_ORIGIN: ${{ github.repository == 'XiaoDaiGua-Ray/ray-template' && 'https://xiaodaigua-ray.github.io' || vars.RAY_TEMPLATE_SITE_ORIGIN }}
RAY_TEMPLATE_SOURCE_REF: ${{ github.sha }}
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v5.0.0
with:
path: dist/pages
include-hidden-files: true
- name: Validate harness, typecheck, lint, format, test and build
run: pnpm check
deploy:
name: Deploy to GitHub Pages
needs: build
runs-on: ubuntu-24.04
name: Deploy main to dist branch
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: check
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
contents: write
steps:
- name: Publish Pages artifact
id: deployment
uses: actions/deploy-pages@v5.0.1
- uses: actions/checkout@v7.0.1
- uses: actions/setup-node@v7.1.0
with:
node-version-file: .nvmrc
- uses: pnpm/action-setup@v6.1.0
- run: pnpm install --frozen-lockfile
- run: pnpm build
env:
RAY_TEMPLATE_SITE_ORIGIN: ${{ github.repository == 'XiaoDaiGua-Ray/ray-template' && 'https://xiaodaigua-ray.github.io' || vars.RAY_TEMPLATE_SITE_ORIGIN }}
- uses: JamesIves/github-pages-deploy-action@v4.9.0
with:
branch: dist
folder: dist/production

View File

@ -1,141 +0,0 @@
name: Source distributions
on:
workflow_dispatch:
inputs:
sync_frontend:
description: Update the generated frontend branch from main
type: boolean
default: false
release_tag:
description: Attach assets to the existing release for this tag (optional)
type: string
permissions:
contents: read
defaults:
run:
shell: bash
concurrency:
group: source-distributions
cancel-in-progress: false
jobs:
verify:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 30
outputs:
source: ${{ steps.source.outputs.commit }}
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- name: Select the source revision
id: source
env:
RELEASE_TAG: ${{ inputs.release_tag }}
SYNC_FRONTEND: ${{ inputs.sync_frontend }}
run: |
if [[ -n "$RELEASE_TAG" ]]; then
[[ "$SYNC_FRONTEND" == false ]] || { echo "Run branch sync and release attachment separately."; exit 1; }
[[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([.-][a-zA-Z0-9.-]+)?$ ]]
source=$(git rev-parse --verify "refs/tags/$RELEASE_TAG^{commit}")
git merge-base --is-ancestor "$source" "$GITHUB_SHA"
git checkout --detach "$source"
[[ "v$(node -p 'require("./package.json").version')" == "$RELEASE_TAG" ]]
fi
echo "commit=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
- uses: actions/setup-node@v7.1.0
with:
node-version-file: .nvmrc
- uses: pnpm/action-setup@v6.1.1
- name: Export both source distributions
env:
HUSKY: '0'
run: |
pnpm install --frozen-lockfile
pnpm dist:frontend
pnpm dist:fullstack
cd dist/distributions
sha256sum ray-template-*.tar.gz > SHA256SUMS.txt
- name: Verify independent installations and builds
env:
HUSKY: '0'
run: |
version=$(node -p 'require("./package.json").version')
for edition in frontend fullstack; do
name="ray-template-$edition-$version"
tar -xzf "dist/distributions/$name.tar.gz" -C "$RUNNER_TEMP"
(
cd "$RUNNER_TEMP/$name"
pnpm install --frozen-lockfile
pnpm check
if [[ "$edition" == fullstack ]]; then
node deploy/smoke.mjs
fi
)
done
- uses: actions/upload-artifact@v7
with:
name: source-distributions
path: |
dist/distributions/ray-template-*.tar.gz
dist/distributions/SHA256SUMS.txt
if-no-files-found: error
compression-level: 0
sync-frontend:
if: inputs.sync_frontend && inputs.release_tag == ''
needs: verify
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
- uses: actions/download-artifact@v8
with:
name: source-distributions
path: ${{ runner.temp }}/source-distributions
- name: Update the generated branch
run: |
version=$(node -p 'require("./package.json").version')
name="ray-template-frontend-$version"
artifacts="$RUNNER_TEMP/source-distributions"
(cd "$artifacts" && sha256sum --check SHA256SUMS.txt)
tar -xzf "$artifacts/$name.tar.gz" -C "$RUNNER_TEMP"
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
bash scripts/sync-frontend.sh "$RUNNER_TEMP/$name"
attach-release:
if: inputs.release_tag != '' && !inputs.sync_frontend
needs: verify
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v7.0.1
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/download-artifact@v8
with:
name: source-distributions
path: ${{ runner.temp }}/source-distributions
- name: Attach source archives to the existing release
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.release_tag }}
SOURCE: ${{ needs.verify.outputs.source }}
run: |
[[ "$(git rev-parse --verify "refs/tags/$RELEASE_TAG^{commit}")" == "$SOURCE" ]]
gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json tagName >/dev/null
cd "$RUNNER_TEMP/source-distributions"
sha256sum --check SHA256SUMS.txt
gh release upload "$RELEASE_TAG" ray-template-*.tar.gz SHA256SUMS.txt --repo "$GITHUB_REPOSITORY"

2
.gitignore vendored
View File

@ -34,5 +34,3 @@ coverage/
.env.*.local
.ai-local/
.harness-local/
.pnpm-store/
apps/docs/.vitepress/cache/

View File

@ -1,6 +1,4 @@
dist/*
apps/docs/.vitepress/cache/
apps/docs/.vitepress/dist/
node_modules/*
auto-imports.d.ts
components.d.ts
@ -15,11 +13,6 @@ coverage/
.husky/_/
.ai-local/
.harness-local/
**/dist-test/
apps/server/src/generated/
.pnpm-store/
CHANGELOG.md
packages/icons/src/
packages/ui/src/RChart/src/themes/
packages/demo-data/src/route-catalog.json
src/icons/
src/app-config/echart-themes/

View File

@ -19,12 +19,4 @@ module.exports = {
singleAttributePerLine: false,
bracketSameLine: false,
plugins: ['@ianvs/prettier-plugin-sort-imports'],
overrides: [
{
files: 'apps/server/**/*.ts',
options: {
importOrderParserPlugins: ['typescript', 'decorators-legacy'],
},
},
],
}

View File

@ -2,7 +2,6 @@
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"eslint.enable": true,
"eslint.probe": [],
"eslint.validate": [
"javascript",
"javascriptreact",
@ -89,14 +88,11 @@
"Popselect",
"precommit",
"qrcode",
"rgba",
"sider",
"siderbar",
"snapline",
"stylelint",
"unocss",
"VITE",
"vitepress",
"vueuse",
"WUJIE",
"zlevel"

View File

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

View File

@ -1,16 +1,9 @@
# Ray Template
A Vue 3 + TSX admin template with an admin application, a documentation site, and shared packages.
Vue 3 + TSX 中后台模板。项目协作、定向验证和交付证据统一从 [AI Harness](harness/README.md) 开始。按任务选择上下文,不必通读仓库。
- 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.
- 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.
- Write agent guidance and internal engineering documentation in English. Preserve the intended languages of product copy and reader-facing documentation.
- Follow the [comment style](docs/comment-style.md) when adding or editing comments. Maintain both Chinese and English product copy. For visible behavior changes, use [browser verification](harness/README.md#browser-verification) only for affected pages, actions, and dimensions.
- For custom CSS, follow the [style contract](docs/ui-design.md#custom-css-contract): consume semantic theme tokens and the shell's runtime layout variables so style, color mode, primary color, and layout preferences keep working. Keep provider ownership and scoped overrides explicit.
- Select relevant tests or `pnpm harness verify <scope>` using the [verification scope](harness/README.md#choosing-the-verification-scope). Small changes do not default to full checks or a UI/UX sweep. Use full checks for integration risk, releases, or an explicit request. Pages builds and publishes on main independently of full verification. Within one task, rerun only checks affected by subsequent changes. Report what was and was not verified.
- Establish engineering facts from current source, manifests, and the lockfile. Keep sensitive data out of source, prompts, and evidence. Commits, pushes, and deployments require user authorization.
- `pnpm harness context` 列出任务域。`pnpm harness context <scope>` 给出入口、约定与回归命令。跨模块变更可查 [架构地图](docs/architecture.md)。
- 先看 `git status`,保留已有改动。变更路由、持久化、请求或公共组件时,追踪调用方和现有数据契约。
- 新增或修改注释时遵循 [注释规范](docs/comment-style.md)。页面文案同时维护中英文,页面改动按 Harness 指南验收。
- 完成实现后运行 `pnpm harness verify`。它执行 `pnpm check` 并留存结果。交付说明实际验证及未验证项。
- 使用当前源码、清单和锁文件核对工程事实。敏感数据不进入源码、提示词或证据。提交、推送与部署遵循用户授权。

View File

@ -1,77 +1,4 @@
## 6.0.3
### Feats
- 新增简单标签管理和复杂项目管理示例,展示弹窗编辑、独立详情页、里程碑与草稿保护。官网补齐英文指南和组件参考。
- 四种主题的登录页、图标库和业务面板使用各自的配色和圆角。提高输入框和主按钮的对比度,简化窄屏用户页和表格工具栏。
- 全局搜索提示按回车将打开的页面。面包屑可用键盘操作,工作区支持跳至主内容,并区分内容区最大化与浏览器全屏。
- 根 `package.json` 提供各模块的 Vitest 命令和全量入口 `pnpm test:all`。
### Fixes
- 路由守卫拒绝离开编辑页时保留草稿、标签与缓存。键盘关闭最后一个标签后,焦点回到标签页操作按钮。
- TablePro 在等值查询条件下保留页码,图表在实例就绪后才开始深度监听。用户管理按部门 ID 构建组织树,独立图标宿主按名称加载 SVG,打印引擎随打印示例按需加载。
- 修复不同二进制请求体互相取消的问题。RIframe 将 `sandbox` 和 `referrerpolicy` 交给原生 iframe。
- 全栈初始化先检查 Redis,再执行数据库迁移。切换到外部服务会保存实际连接,Compose 支持设置 `REDIS_KEY_PREFIX`。
### Compatibility
- `pnpm lint:fix <文件路径>` 只修复显式指定的文件。ESLint 自动将内置 `undefined` 的运行时读取改成 `void 0`,类型中的 `undefined` 仍可使用。Markdown 和 JSON 走 Prettier。
- 从 Compose 切换到外部服务时,同时提供 `DATABASE_URL` 和 `REDIS_URL`。已有外部服务配置可更新其中一项。[全栈启动指南](apps/docs/guide/distributions.md)
## 6.0.2
### Feats
- 新增可选的 NestJS 后端,使用 PostgreSQL 保存用户、会话与路由配置,Redis 负责限流与演示数据缓存。提供纯前端和全栈两种独立源码包。
- 全栈管理端支持同源 HttpOnly Cookie 会话、个人资料、改密及管理员设置凭据。角色和路由权限由服务端检查。
- 扩充布局、外观、菜单、水印和通用偏好设置,支持导入导出,并完善窄屏下的工作区和账户操作。
### Fixes
- 修复同一标签退出再登录后菜单为空的问题。导航保留查询参数和锚点,刷新当前页时保留其他标签页的草稿。
- 为账号和路由编辑加上版本检查,避免过期表单覆盖已保存的变更。修复演示模式下多标签写入互相覆盖的问题。
- 菜单、设置和主题选项支持键盘操作。亮色主按钮自动选择可读的文字颜色,内联 SVG 保留描边和填充,路由校验支持嵌套图标路径。
- 修复 TablePro 刷新跳回第一页、表单禁用后仍可提交、响应式条码覆盖固定尺寸,以及内容不同的表单请求互相取消等问题。
- 优化首屏依赖加载,将图表和演示数据延后至需要时加载,并更新 Vue、Vite 和 MSW。
### Compatibility
- 管理端编辑器通过 `If-Match` 提交版本。自有后端实现修订值返回和事务内检查后,可在冲突时返回 HTTP 412 并保留草稿。已有客户端可继续按原协议调用。[接入说明](apps/docs/guide/backend.md)
- 需要刷新整个工作区时,使用 `useSpinning().reloadWorkspace()`。标签栏的刷新按钮只刷新当前页面。[布局 Hooks](apps/docs/reference/hooks/layout.md)
## 6.0.1
### Feats
- 新增用户管理、账户维度的历史记录与收藏,补齐会话、权限、HTTP 契约和 MSW 演示接口。
- 完善朴素、Naive UI、Material、现代化四种界面风格,统一页面圆角、阴影、图标和八套 RChart 明暗主题;优化首屏与内容区加载反馈。
- 新增欢迎工作区与 403、404、500 页面。关闭最后一个或全部业务标签后进入工作区,不再要求或自动注入 dashboard。
- TablePro 新增默认展示的 PNG 剪贴板操作,支持 `showCopyImage`、`copyImageOptions` 和 `copyImage()`;常用操作与更多操作分组,打印改为显式开启。
- 将应用诊断入口整理为开发期 `doctor`,补齐自定义 CSS 的语义变量、主题作用域和运行时布局约定。
### Fixes
- 修复权限变化后的失效标签和缓存、查询参数恢复、过期导航错误抢占新页面,以及初始化失败后无法重试的问题。
- 修复折叠状态反向、条码配置不重绘、拖拽资源清理、Flow 只读配置覆盖、表单重复或过期提交、iframe 加载状态和 Segment 标签渲染等问题。
- 修复嵌套列显隐和分组固定列,截图保留当前滚动视口、固定列及静态 SVG 图标,并处理权限、取消和清理。
- 优化权限查询、随机数批量采样、Base64 编码和截图依赖加载,补齐公开方法契约注释。
### Compatibility
- `useAppRoot` 与 `appRootRoute` 仅保留为废弃的兼容元数据,不再控制默认落点或保护标签;无有效目标时进入 `/welcome`。
- 分页改用 `onUpdatePage` / `onUpdatePageSize` 或对应 `onUpdate:*` 事件;旧的 `onChange`、`onPageChange`、`onPageSizeChange` 不再转发。
- `RCollapseGrid` 的更新事件现在返回真实展开状态,接入时应移除旧的取反处理。
- TablePro 默认隐藏打印,使用 `showPrint` 开启;PNG 复制默认开启,可用 `showCopyImage={false}` 隐藏。复制范围是当前可见表格区域,需要浏览器剪贴板能力和安全上下文。
- v6 与 v5 仍保持版本分界,不提供 v5 的原地升级。
## 6.0.0
- **破坏性版本变更**:Ray Admin、官网文档和共享包改为 Monorepo。v6 不提供 v5 的原地升级,旧版代码保留在 [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5)。详见[版本分界](apps/docs/migration.md)。
- 后台迁到 `apps/admin/`,共享组件、Hooks、指令、图标、路由、请求、布局和工具拆成八个 workspace 包。文档通过公共入口复用同一套能力。
- 增加 TablePro、布局、条码、精度、路由校验、防抖和全屏的页内演示。`pnpm pages:build` 组装 Ray Admin 与官网文档。[v6 架构指南](apps/docs/guide/architecture.md)
## v5 主线后续记录(`legacy/v5`)
## Unreleased(2026-11-02)
### Feats

View File

@ -1,7 +1,8 @@
FROM node:26.13.0-bookworm-slim
WORKDIR /app
RUN npm install --global pnpm@12.16.1
COPY . .
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
RUN HUSKY=0 pnpm install --frozen-lockfile
COPY . .
EXPOSE 9527
CMD ["pnpm", "dev", "--host", "0.0.0.0"]

View File

@ -1,22 +1,22 @@
# Commit conventions
# commit 规范
## Commit message format
## commit message 格式
Use the following `commit message` types:
在提交代码时,`commit message` 遵循以下格式:
- feat: New feature
- fix: Bug fix
- update: Code update
- docs: Documentation
- style: Formatting changes that do not affect runtime behavior
- refactor: Code restructuring that neither adds a feature nor fixes a bug
- test: Additional tests
- chore: Changes to the build process or supporting tools
- revert: Revert a change
- merge: Merge branches
- perf: Optimization, such as performance or user experience improvements
- build: Build changes
- plugin: Plugin updates
- publish: Publication
- feat: 新功能`(feature)`
- fix: 修补 `bug`
- update: 更新代码
- docs: 文档(documentation)
- style: 格式(不影响代码运行的变动)
- refactor: 重构(即不是新增功能,也不是修改bug的代码变动)
- test: 增加测试
- chore: 构建过程或辅助工具的变动
- revert: 撤销
- merge: 合并分支
- perf: 优化相关,比如提升性能、体验
- build: 构建
- plugin: 插件更新
- publish: 发布
Customize the `commit message` format in `commitlint.config.cjs` when needed.
当你需要定制化自己的`commit message`格式时,可以在`commitlint.config.cjs`文件中进行配置。

252
README.md
View File

@ -1,54 +1,50 @@
# Ray Template
# Ray Template · Vue 3 Admin Dashboard Template
**A Vue 3 admin template built for AI-assisted development.**
[简体中文](README.zh-CN.md) · **[Live demo](https://xiaodaigua-ray.github.io/ray-template/)** · **[Documentation](https://xiaodaigua-ray.github.io/ray-template-doc/)** · [Quick start](#quick-start)
Give developers and coding agents the same path through the project: **find the implementation, understand its contracts, reuse existing capabilities, and verify the change.**
Ray Template is an **open-source, ready-to-run frontend template** for admin dashboards, back-office tools, and internal apps. Run the demo to try a workspace with role-based menus and page tabs, then reuse TablePro list pages, workspace layouts, and route modules in your own app.
[简体中文](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)
**Stack**: Vue 3 · TypeScript / TSX · Naive UI · Vue Router · Pinia · Vue I18n · Vite / Rolldown · Axios · Vitest
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's TablePro people directory with search, pagination, column settings, and sidebar navigation](docs/assets/tablepro-preview.jpg)](https://xiaodaigua-ray.github.io/ray-template/)
**Task context and verification commands · 4 visual styles · 5 navigation layouts · 11 TablePro examples**
Sign in with the prefilled form. Open **Tables → Remote search and pagination** to try the list shown above, or **Layout playground** to experiment with the workspace.
[![TablePro in Modern light mode, with search, pagination, automatic height, and toolbar actions](docs/assets/readme/table-modern-light.png)](https://xiaodaigua-ray.github.io/ray-template/#/tables/auto-height)
## Core features
## Why choose Ray Template
### TablePro for simple tables and data-heavy pages
### Engineering context for AI collaboration
Use `RTablePro` with `bare` for a plain table, or add search, pagination, and a toolbar for a full list page. Column definitions, selection, sorting, and custom cells follow Naive UI DataTable.
[AGENTS.md](AGENTS.md) sets the collaboration rules; [llms.txt](llms.txt) maps tasks to source, contracts, examples, and checks. When working on tables, routing, layout, or APIs, read the relevant context and use Harness to run the corresponding checks and save their results.
- **Search and pagination**: Pass local `data` or a `request(params, signal)` function that returns `{ data, total }`. Remote queries accept only the latest result. A failed query keeps existing rows visible and lets users retry.
- **Long lists and column controls**: Fill the available workspace and use virtual scrolling for large lists. Users can show, hide, reorder, or pin columns. Set `columnStateKey` to remember hidden columns across reloads.
- **CSV and printing**: Export or print the current page's visible data columns by default. Point printing at a custom region for documents that need their own layout.
### Applications, documentation, and examples share source
[TablePro API and data contract](src/components/RTablePro/README.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)
### A configurable workspace
### Four styles across the business interface
Switch between sidebar, top, and mixed navigation. Narrow screens use a menu drawer. The workspace supports fixed or fluid width, a pinned header and footer, and a maximized content area. Pinia saves layout preferences. Try changes live in the layout playground or use named slots to replace the header, sidebar, tabs, and footer.
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)
Page tabs keep multiple tasks open, and breadcrumbs show where you are. Find menu items with `⌘/Ctrl + K`, and switch between light and dark themes or English and Simplified Chinese.
### TablePro handles interaction and data state
[Layout playground source](src/views/demo/layout-demo.tsx) · [Layout configuration and slots](src/layout/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)
### Route modules connect pages, menus, and permissions
### One contract from the static demo to your business API
Declare a page in `src/router/modules` to generate its navigation and breadcrumbs. Route metadata controls menu labels and icons, roles, visibility, and `keepAlive`. Detail pages can extend the breadcrumb while keeping the current menu and tab. Role checks cover both menu filtering and direct navigation. Connect your backend to validate sessions and authorize API requests.
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)
[Routing guide](src/router/README.md) · [Nested navigation and caching example](src/router/modules/demo/multi-menu.ts)
### Visual route editing with a validated configuration contract
### Reusable components, composables, and SVG icons
Manage menu order, roles, visibility, and caching through a visual editor or JSON. Tree previews, import/export, JSON Schema, and registered view IDs help maintain the configuration. Both editors use the same route model, with documented integration constraints and permission boundaries. [Routes and menus](apps/admin/src/router/README.md)
<!-- fullstack:start -->
### 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/en/guide/distributions.md)
<!-- fullstack:end -->
- **Components**: Start with `RForm` and `RModal` for forms and dialogs. `RChart` manages ECharts initialization, resizing, and theme changes. The demo also includes LogicFlow diagrams, barcodes, and draggable cards. [Component guide](src/components/README.md)
- **Composables**: Template hooks cover page refresh, content maximization, menu badges, and watermarks. Web hooks demonstrate screenshots, printing, and element fullscreen. The examples include expandable usage code. [Composables and examples](src/hooks/README.md)
- **SVG icons**: Add an SVG to a group under `src/icons` to generate typed names and sprites. Routes and `RIcon` share names such as `navigation/dashboard`. The icon gallery lets you browse by group and copy TSX usage. [SVG icon workflow](src/icons/A_README.md)
## Quick start
Use **Node.js 26.13.0** and **pnpm 12.16.1**, as pinned in the repository.
Use the pinned **Node.js 26.13.0** and **pnpm 12.16.1**. With nvm:
```sh
git clone https://github.com/XiaoDaiGua-Ray/ray-template.git
@ -60,144 +56,92 @@ pnpm install --frozen-lockfile
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/) or use the URL printed by Vite. The prefilled demo sign-in and mock data let you run the template before connecting a backend.
- **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/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/en/guide/backend.md) to configure `VITE_API_BASE_URL` and `VITE_API_MOCK=false`.
## 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.
| 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. |
| 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). |
| 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. |
| 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/`. |
For a TablePro task, read its context first, then select verification for the change:
```sh
pnpm harness context table-pro
pnpm harness verify table-pro
```
You can give a coding agent a request like this and replace the business details:
## Project structure
```text
Read AGENTS.md and llms.txt first, then locate the context for this task.
Add a project list page with name, status, and owner filters and remote pagination.
Check existing TablePro examples, route registration, API contracts, and English/Chinese copy before implementing. Reuse existing capabilities.
Identify the modules that need to change, complete the implementation, and run the relevant checks. Verify visible interactions in a browser.
Report the changes, checks that actually passed, and anything still unverified.
.
├── src/
│ ├── main.ts # Bootstraps the app, router, state, and i18n
│ ├── App.tsx # Root component with global providers and layout
│ ├── views/ # Sign-in, dashboard, business pages, and demos
│ │ └── demo/ # TablePro, layout playground, and hook examples
│ ├── router/
│ │ └── modules/ # Page routes, menu metadata, and roles
│ ├── layout/ # Navigation, page tabs, breadcrumbs, and content
│ ├── components/ # Shared UI exported through @/components
│ ├── app-components/ # App-specific UI and global providers
│ ├── api/ # API functions grouped by feature
│ ├── axios/ # HTTP client, interceptors, and cancellation
│ ├── store/ # Pinia modules and access methods
│ ├── hooks/ # Template, component, and browser composables
│ ├── app-config/ # App, routing, theme, and language settings
│ ├── locales/ # English and Simplified Chinese messages
│ ├── icons/ # Grouped SVG sources and generated manifest
│ ├── styles/ # Global styles, design tokens, and theme overrides
│ ├── directives/ # Global Vue directives
│ ├── types/ # Shared types and declarations
│ ├── utils/ # Shared utility functions
│ └── demo-data/ # Sample data for mock APIs and the static demo
├── mock/ # Mock endpoints for local development
├── public/ # Static assets copied into the build as is
├── vite-helper/ # Build helpers for icons, CDN, and SEO
├── vite.config.ts # Vite entry for development and builds
├── vite.custom.config.ts # Deployment base, dev proxy, and build options
├── tsconfig.json # References the app, Node, and test TS projects
├── package.json # Dependencies, runtime versions, and commands
├── scripts/ # Environment checks and icon generation
├── __test__/ # Vitest suites and test utilities
├── harness/ # Task scopes, targeted checks, and report generation
├── .github/workflows/ # CI checks and GitHub Pages deployment
└── docs/ # Architecture, design, and engineering conventions
```
Here, `llms.txt` is a repository task index that you can explicitly ask an agent to read. Load context by task and confirm behavior against current source and contracts. Harness runs only the commands registered for the selected scope; add type, lint, formatting, and browser checks as the change requires. Use `pnpm check` for full verification. See the [verification rules](harness/README.md#choosing-the-verification-scope).
See the [architecture map](docs/architecture.md) for how these modules work together.
## Everyday admin capabilities
## Build your first business page
| Area | Included |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Users and accounts** | Login, logout, session restoration, and screen lock; organization tree, member search, create/edit/detail flows, account status, roles, profiles, and password forms. |
| **Routes and permissions** | Visual and JSON route editors, menu generation, role-based navigation, action permissions, direct-route guards, and KeepAlive. |
| **Navigation and workspace** | Page tabs, context menus, breadcrumbs, `⌘/Ctrl + K` search, account-scoped recent pages and favorites, content maximization, transitions, and 403/404/500 pages. |
| **Tables and search** | Local data, remote requests, controlled pagination, advanced search, dependent remote options, automatic height, virtual scrolling, saved column visibility, reordering, and pinning. |
| **Forms and dialogs** | `RForm`, `useForm`, and `RModal`, with validation, reset, loading states, and interactive examples. |
| **Visualization and interaction** | ECharts lifecycle and themes, LogicFlow, draggable cards, context menus, screenshots, CSV export, printing, and fullscreen. |
| **Themes and localization** | Four styles, light/dark/system modes, custom primary colors, English and Chinese copy, live preference persistence, and JSON import/export. |
| **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). |
This small people directory uses the template's mock query function. To adapt it for orders or inventory, replace the columns, search fields, and request function.
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.
```tsx
import { getPersonList } from '@/api/demo/mock/person'
import { RTablePro } from '@/components'
import { defineComponent } from 'vue'
## Styles and layouts
| Style | Character |
| ------------ | -------------------------------------------------------------------- |
| **Modern** | The default style: blue accents, balanced spacing, and soft corners. |
| **Naive UI** | Native library controls, proportions, and green accents. |
| **Material** | Tonal surfaces, larger corners, and capsule-shaped buttons. |
| **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/en/guide/layout.md).
<details>
<summary>View the workspace and dark theme previews</summary>
![The workspace in Modern light mode](docs/assets/readme/welcome-modern-light.png)
![The workspace in Modern dark mode](docs/assets/readme/welcome-modern-dark.png)
[![TablePro in Modern dark mode](docs/assets/readme/table-modern-dark.png)](https://xiaodaigua-ray.github.io/ray-template/#/tables/auto-height)
</details>
## Workspaces and source distributions
A **pnpm monorepo** keeps business integration separate from shared capabilities.
| Location | Responsibility |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| [apps/admin](apps/admin) | Pages, sessions, Pinia, route registration, business APIs, and mocks. |
| [apps/docs](apps/docs) | VitePress guides, API references, and interactive examples. |
| [packages](packages) | 10 shared packages: `ui`, `admin-shell`, `composables`, `directives`, `icons`, `http`, `api-contracts`, `demo-data`, `routing`, and `utils`. |
| [harness](harness/README.md) | Task context, verification scopes, check commands, and result reports. |
Shared packages expose public `exports`. Boundary checks cover imports, dependency declarations, runtime environments, and dependency cycles. These packages are used within the workspace and are not separately published to npm. [Architecture map](docs/architecture.md)
**Frontend source:** Run `pnpm dist:frontend` to generate `ray-template-frontend-<version>.tar.gz` and its source directory under `dist/distributions/`. Extract it, then run `pnpm install --frozen-lockfile` and `pnpm dev`. The export includes Admin, documentation, shared packages, and mocks; it excludes local configuration, credentials, build output, and installed dependencies. `distribution.json` records the version, source commit, workspace state, and content digest.
<!-- fullstack:start -->
**Optional fullstack source:** The complete repository also includes [apps/server](apps/server), using NestJS, PostgreSQL, and Redis for sessions, API permissions, users, route configuration, audits, and rate limits. Run `pnpm dist:fullstack` to export the fullstack source for the same version.
After installing dependencies and preparing Docker Compose, run:
```sh
pnpm fullstack:setup
pnpm dev:full
export default defineComponent({
setup() {
return () => (
<RTablePro
columns={[
{ title: 'Name', key: 'name' },
{ title: 'Email', key: 'email' },
]}
request={getPersonList}
search={[{ key: 'name', label: 'Name' }]}
columnStateKey="demo:people"
/>
)
},
})
```
`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.
1. **Build the view.** Add a page in `src/views`. The [remote table example](src/views/demo/tables/remote.tsx) shows sorting, row selection, and toolbar actions.
2. **Connect navigation.** Add a route in `src/router/modules` and give its menu entry English and Simplified Chinese labels. Follow the [routing guide](src/router/README.md) when setting up page caching.
3. **Connect your data.** Define your API in `src/api`, use `src/axios` for interceptors and request cancellation, and connect your real sign-in and session. The people directory uses a mock HTTP endpoint in development and sample data in the static preview. [Request layer guide](src/axios/README.md)
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.
## Checks, builds, and deployment
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#容器启动)
| Command | What it does |
| ----------------------------- | ------------------------------------------------------------------------------------------- |
| `pnpm test:run` | Run the Vitest suite |
| `pnpm check` | Run the same checks as CI, including types, lint, formatting, tests, and a production build |
| `pnpm harness context` | Find entry points and checks for areas such as routing, UI, and APIs |
| `pnpm harness verify` | Run the full check and save a local report, or pass a scope to run targeted checks |
| `pnpm build` / `pnpm preview` | Build into `dist/production` or serve the build locally |
<!-- fullstack:end -->
Use the [architecture map](docs/architecture.md) to find module and configuration entry points. See the [deployment guide](docs/architecture.md#deployment-and-search-discovery) for root or subpath hosting and search metadata. Contributors and coding agents share the instructions in [AGENTS.md](AGENTS.md) and the [AI Harness](harness/README.md).
## Development and verification
[MIT License](LICENSE) · [Changelog](CHANGELOG.md) · [Issues](https://github.com/XiaoDaiGua-Ray/ray-template/issues)
**Vue 3 · TypeScript / TSX · Naive UI · Vite / Rolldown · Pinia · Vue Router · Vue I18n · Axios · MSW · Vitest**
| Command | Purpose |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `pnpm dev` / `pnpm docs:dev` | Develop the admin application or documentation. |
| `pnpm build` / `pnpm preview` | Build or preview the admin application. |
| `pnpm pages:build` | Assemble the admin and documentation into `dist/pages`. |
| `pnpm harness context <scope>` | Read task entry points and relevant check commands. |
| `pnpm harness verify <scope>` | Run checks for the selected scope and save a report. |
| `pnpm harness check` | Validate task indexes, relative file links, and registered verification scopes. |
| `pnpm check` | Run the full checks configured for this source edition: environment, contracts, package boundaries, types, lint, formatting, tests, site builds, and distribution plans. |
<!-- fullstack:start -->
In the complete repository, `pnpm check` also checks server types, tests, and builds. Distribution plan checks validate export structure and dependencies; independent installation, runtime, and deployment environments require their own acceptance checks.
<!-- fullstack:end -->
The **Pages workflow** builds the admin and documentation on every push to `main` and publishes the `dist/pages` artifact to GitHub Pages. It also supports manual publication on `main` and runs independently of cross-platform checks. Read [AGENTS.md](AGENTS.md) and the [Harness verification guide](harness/README.md) before contributing. Default deployment paths are `/ray-template/` for the admin and `/ray-template/docs/` for documentation. See the [deployment guidance](docs/architecture.md#deployment-and-search-discovery) for Pages setup.
## Version boundaries
**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/en/migration.md) before adopting v6.
---
[MIT License](LICENSE) · [Changelog](CHANGELOG.md) · [Report an issue](https://github.com/XiaoDaiGua-Ray/ray-template/issues) · [Contributor guidance](AGENTS.md)
Agents can start with the [LLM entry point](llms.txt) and open only the relevant task scope.

View File

@ -1,54 +1,50 @@
# Ray Template
# Ray Template · Vue 3 中后台管理模板
**面向 AI 协作开发的 Vue 3 中后台模板。**
[English](README.md) · **[在线演示](https://xiaodaigua-ray.github.io/ray-template/)** · **[在线文档](https://xiaodaigua-ray.github.io/ray-template-doc/)** · [快速开始](#快速开始)
让开发者与编码助手沿着同一条路径工作:**找到实现入口,理解模块契约,复用现有能力,验证实际改动。**
Ray Template 是一套**开箱即用的中后台前端模板**,适合搭建管理后台、运营工作台和内部工具。克隆后即可体验带权限菜单和多标签页的工作台,也可以直接把 TablePro 列表页、布局和路由模块用在业务里。
[English](README.md) · **[在线演示](https://xiaodaigua-ray.github.io/ray-template/)** · **[在线文档](https://xiaodaigua-ray.github.io/ray-template/docs/)** · [快速开始](#快速开始) · [与 AI 一起开发](#与-ai-一起开发)
**技术栈**:Vue 3 · TypeScript / TSX · Naive UI · Vue Router · Pinia · Vue I18n · Vite / Rolldown · Axios · Vitest
Ray Template 基于 Vue 3、TypeScript / TSX 和 Naive UI,适合管理后台、运营工作台与内部工具。仓库同时提供可运行的应用、共享组件、交互文档,以及按任务组织的工程上下文。
[![Ray Template 的 TablePro 人员列表,展示查询表单、分页、列设置及侧栏导航](docs/assets/tablepro-preview.jpg)](https://xiaodaigua-ray.github.io/ray-template/)
**任务索引与验证入口 · 4 种完整视觉风格 · 5 种导航布局 · 11 个 TablePro 示例**
用演示页预填的表单登录,在「表格 → 远端查询与分页」可以体验图中的列表,或打开「布局实验室」调整工作台。
[![Modern 浅色风格的 TablePro,展示搜索、分页、自适应高度和工具栏](docs/assets/readme/table-modern-light.png)](https://xiaodaigua-ray.github.io/ray-template/#/tables/auto-height)
## 核心能力
## 为什么选择 Ray Template
### TablePro:从纯表格到业务列表
### 为 AI 协作准备的工程上下文
同一个 `RTablePro` 可以用 `bare` 只渲染表格,也可以接入搜索、分页和工具栏。列定义、行选择、排序和自定义单元格沿用 Naive UI DataTable 的写法。
[AGENTS.md](AGENTS.md) 说明协作约定,[llms.txt](llms.txt) 按任务导航到源码、契约、示例和检查入口。处理表格、路由、布局或接口问题时,可以按范围读取相关上下文,并通过 Harness 执行对应检查、保存结果。
- **查询和分页**:传入本地数据 `data`,或提供返回 `{ data, total }` 的 `request(params, signal)`。远端模式只接收最新请求的结果,失败时保留已有数据并提供重试。
- **长列表和列设置**:表格可填充工作区,配合虚拟滚动;用户可调整列的显示、顺序和固定位置,通过 `columnStateKey` 跨刷新记住隐藏列。
- **导出与打印**:默认导出和打印当前页的可见数据列。报表、单据等独立排版可指定自定义打印区域。
### 应用、文档与示例共用源码
[TablePro 用法与数据契约](src/components/RTablePro/README.md)
后台与文档站消费同一工作区的共享包。交互示例使用真实组件,TablePro 文档引用实际运行的示例源码;修改公共能力时,应用与文档都能参与验证。[查看示例](apps/docs/reference/table-pro-examples.md) · [文档协作约定](docs/docs-handoff.md)
### 应用外壳:适配不同的后台工作方式
### 四种风格覆盖业务界面
侧栏、顶部、混合导航可切换,窄屏自动改用菜单抽屉。工作区支持定宽或铺满、顶栏与页脚固定、内容最大化;用户的布局偏好由 Pinia 保存。可以在布局实验室实时调试,也可以用具名插槽替换顶栏、侧栏、标签栏和页脚。
Modern、Naive UI、Material、Plain 覆盖布局外壳、控件、表格和图表,并分别提供明暗模式。自定义页面通过语义化主题变量继承颜色、圆角与阴影,通过运行时布局变量适应工作区尺寸。[主题接入](apps/docs/guide/appearance.md) · [样式契约](docs/ui-design.md#custom-css-contract)
标签页可在多个页面之间切换,面包屑标示当前位置,用 `⌘/Ctrl + K` 可以查找菜单。全局提供明暗主题和中英文切换。
### TablePro 兼顾交互与数据状态
[布局实验室源码](src/views/demo/layout-demo.tsx) · [布局配置与插槽](src/layout/README.md)
一个表格入口支持本地数据、远程请求和受控分页,并配套高级搜索、列设置、导出、打印与实例 Hooks。请求竞态、取消信号、失败恢复和导出范围都有明确契约与对应回归用例。[11 个在线示例](https://xiaodaigua-ray.github.io/ray-template/docs/reference/table-pro-examples.html) · [组件契约](packages/ui/src/RTablePro/README.md)
### 路由模块:把页面、菜单与权限放在同一处配置
### 从静态演示到业务 API,沿用同一套契约
在 `src/router/modules` 声明页面,模板按路由配置生成菜单和面包屑。路由 `meta` 可以配置菜单文案与图标、角色、显示条件和 `keepAlive`。从列表进入详情时,可以保留当前菜单和标签页,只在面包屑中补充详情层级。角色配置同时用于菜单过滤和直接导航时的守卫。接入业务时,由后端校验会话与接口权限。
开发环境与静态在线演示共用 MSW HTTP Mock,页面通过真实的 API 调用链获取数据。共享 TypeScript 类型、Valibot Schema 与生成的 OpenAPI 3.1 为后端接入提供依据,契约同步由命令检查。[接口契约](packages/api-contracts/README.md) · [后端接入](apps/docs/guide/backend.md)
[路由与菜单约定](src/router/README.md) · [多级菜单与缓存示例](src/router/modules/demo/multi-menu.ts)
### 路由配置既能可视化编辑,也有可校验的契约
### 组件、Hooks 与图标:从可运行的示例里复用
通过可视化编辑器或 JSON 管理菜单顺序、角色、可见性与缓存,结合树预览、导入导出、JSON Schema 和可用页面 ID 维护配置。配置最终落到同一套路由模型,接入约束与权限边界有专门说明。[路由与菜单](apps/admin/src/router/README.md)
<!-- fullstack:start -->
### 同一工程,按需要选择前端或全栈源码
可以导出独立运行的纯前端源码,也可以保留 NestJS、PostgreSQL 与 Redis 的全栈实现。发行脚本按依赖图裁剪工作区、锁文件和专属说明,并记录版本、来源提交与内容摘要。[发行版本与启动方式](apps/docs/guide/distributions.md)
<!-- fullstack:end -->
- **组件**:`RForm` 和 `RModal` 用于表单和弹窗场景,`RChart` 封装 ECharts 实例的初始化、尺寸与主题同步;另有 LogicFlow 流程图、条形码和拖拽卡片示例。[组件入口与约定](src/components/README.md)
- **Hooks**:模板 Hooks 处理页面刷新、内容最大化、菜单标记和水印;Web Hooks 展示截图、打印和元素全屏。交互示例提供可展开的用法代码。[Hooks 示例](src/hooks/README.md)
- **SVG**:把文件放入 `src/icons` 的对应分包即可生成类型提示和雪碧图。路由和 `RIcon` 使用同一套完整名称,例如 `navigation/dashboard`,图标库可按分包查找并复制 TSX 用法。[图标生成与使用](src/icons/A_README.md)
## 快速开始
使用仓库固定的 **Node.js 26.13.0** 和 **pnpm 12.16.1**。
使用仓库固定的 **Node.js 26.13.0** 和 **pnpm 12.16.1**。以下以 nvm 为例:
```sh
git clone https://github.com/XiaoDaiGua-Ray/ray-template.git
@ -60,144 +56,92 @@ pnpm install --frozen-lockfile
pnpm dev
```
打开 [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/),点击 **使用演示账号进入**。还可以切换管理者与只读账号,体验权限差异;前端演示无需数据库或业务后端。
打开 [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/),或使用 Vite 输出的地址。预填的演示账号可直接登录,本地开发无需先搭建业务后端。
- **先看界面**:在「设置」中切换风格与布局,再体验用户管理和 TablePro。
- **开始写业务**:参考[第一个业务页面](apps/docs/guide/first-page.md),复用组件并登记路由与中英文菜单。
- **接入自己的服务**:按[后端接入指南](apps/docs/guide/backend.md)配置 `VITE_API_BASE_URL` 和 `VITE_API_MOCK=false`。
## 与 AI 一起开发
AI 友好体现在日常开发路径中。能够读取仓库并执行命令的编码助手,可以和维护者使用相同的 Markdown 文档、源码入口与验证命令。
| 开发时需要回答的问题 | 工程中的依据 |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 从哪里开始,遵守哪些约定? | [AGENTS.md](AGENTS.md):改动范围、复用、文档同步与验收约定。 |
| 这项任务要读哪些文件? | [llms.txt](llms.txt) → [任务索引](harness/context):实现、调用方、契约和测试入口。 |
| 哪个模块负责,哪些边界不能跨? | [架构地图](docs/architecture.md)、公共 `exports` 与[包边界检查](scripts/check-package-boundaries.mjs)。 |
| 已有能力怎么用,参数和状态有什么约束? | [组件参考](apps/docs/reference/components.md)、[Hooks 参考](apps/docs/reference/hooks.md)、模块 README 与[可运行示例](apps/docs/reference/table-pro-examples.md)。 |
| 接口形状、Mock 与业务请求如何对齐? | [共享 Schema 与 OpenAPI](packages/api-contracts/README.md),通过 `pnpm api:check` 检查生成文件同步。 |
| 改完应该跑什么,实际结果在哪里? | [验证范围](harness/scopes.json)、`pnpm harness verify <scope>`,结果保存在 `.harness-local/runs/`。 |
例如,处理 TablePro 时先查看任务上下文,再按改动范围验证:
```sh
pnpm harness context table-pro
pnpm harness verify table-pro
```
也可以把下面的需求交给编码助手,替换其中的业务内容:
## 工程结构
```text
请先读取 AGENTS.md 和 llms.txt,定位这项任务对应的上下文。
新增一个项目列表页,包含名称、状态和负责人筛选,支持远程分页。
先检查现有 TablePro 示例、路由注册、接口契约与中英文文案,复用已有能力。
说明需要修改的模块后完成实现,执行相关检查;可见交互需要浏览器验证。
交付时列出改动、实际通过的检查和仍未验证的部分。
.
├── src/
│ ├── main.ts # 初始化应用、路由、状态和国际化
│ ├── App.tsx # 根组件,挂载全局 Provider 与布局
│ ├── views/ # 登录页、工作台、业务页面和交互示例
│ │ └── demo/ # TablePro、布局实验室、Hooks 等示例
│ ├── router/
│ │ └── modules/ # 页面路由、菜单元数据与角色配置
│ ├── layout/ # 导航、标签页、面包屑与内容区
│ ├── components/ # 通用组件,统一从 @/components 导入
│ ├── app-components/ # 与应用状态绑定的组件和全局 Provider
│ ├── api/ # 按业务组织的接口函数
│ ├── axios/ # 请求实例、拦截器与取消机制
│ ├── store/ # Pinia 状态模块与访问方法
│ ├── hooks/ # 模板、组件和 Web 相关的组合式函数
│ ├── app-config/ # 应用、路由、主题与语言配置
│ ├── locales/ # 中英文语言包与加载逻辑
│ ├── icons/ # 分包 SVG 源文件与生成清单
│ ├── styles/ # 全局样式、设计变量与主题覆盖
│ ├── directives/ # 全局指令
│ ├── types/ # 共享类型与声明
│ ├── utils/ # 通用工具函数
│ └── demo-data/ # Mock 和静态演示共用的样例数据
├── mock/ # 开发环境 Mock 接口
├── public/ # 构建时原样复制的静态资源
├── vite-helper/ # 图标、CDN 和 SEO 等构建辅助
├── vite.config.ts # Vite 开发与构建入口
├── vite.custom.config.ts # 部署路径、开发代理和构建选项
├── tsconfig.json # 引用应用、Node 与测试的 TS 配置
├── package.json # 依赖、运行时版本与项目命令
├── scripts/ # 环境检查与图标生成
├── __test__/ # Vitest 测试与测试工具
├── harness/ # 任务域说明、定向验证与报告生成
├── .github/workflows/ # CI 检查与 GitHub Pages 部署
└── docs/ # 架构、设计与工程约定
```
`llms.txt` 在这里是仓库任务索引,可显式交给助手阅读。上下文按任务读取,具体行为以当前源码和契约为准。Harness 只执行所选范围注册的命令;类型、Lint、格式与浏览器检查按改动补充,完整检查使用 `pnpm check`。详见[验证规则](harness/README.md#choosing-the-verification-scope)。
模块之间的调用关系见[架构地图](docs/architecture.md)。
## 中后台常用能力
## 从示例改出第一个业务页面
| 能力 | 已有内容 |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **用户与账号** | 登录、退出、会话恢复与锁屏;组织树、成员查询、新增/编辑/详情、账号状态、角色、个人资料与密码表单。 |
| **路由与权限** | 可视化和 JSON 路由编辑、菜单生成、角色导航、操作权限、直接访问守卫与 KeepAlive。 |
| **导航与工作区** | 多标签页、右键操作、面包屑、`⌘/Ctrl + K` 搜索、按账号隔离的最近访问与收藏、内容最大化、页面动效与 403/404/500 页面。 |
| **表格与搜索** | 本地/远程/受控分页,高级搜索与远程候选联动,自适应高度、虚拟滚动、列显隐偏好存储、列顺序调整与固定。 |
| **表单与弹窗** | `RForm`、`useForm`、`RModal`,支持校验、重置、加载状态与交互示例。 |
| **可视化与交互** | ECharts 生命周期和主题管理、LogicFlow、拖拽卡片、右键菜单、截图、CSV 导出、打印与全屏。 |
| **主题与国际化** | 四种风格、明暗与系统模式、自定义主题色、中英文文案、偏好即时保存及 JSON 导入/导出。 |
| **图标与工具** | 带类型提示的 SVG 名称与生成精灵图,二维码、条形码、精度运算、存储、组合式函数与指令。 |
| **工程与集成** | pnpm 工作区、请求取消、类型与包边界检查、Vitest、ESLint / Prettier,以及 [Wujie 子应用启动入口](apps/admin/src/main.ts)。 |
下面是人员列表的最小接入。它使用仓库自带的 Mock 查询函数;换成订单或库存列表时,替换列定义、搜索字段与请求函数即可。
前端权限用于控制页面体验,真实会话与 API 授权由业务后端验证。演示数据的用途和接入边界见[后端接入指南](apps/docs/guide/backend.md)。
```tsx
import { getPersonList } from '@/api/demo/mock/person'
import { RTablePro } from '@/components'
import { defineComponent } from 'vue'
## 风格与布局
| 风格 | 视觉特点 |
| ------------------- | ---------------------------------------- |
| **Modern · 现代化** | 默认风格,蓝色主调、适度留白与柔和圆角。 |
| **Naive UI · 原生** | 保留组件库原生控件、比例与绿色主调。 |
| **Material** | 带色阶的面板、大圆角与胶囊按钮。 |
| **Plain · 朴素** | 中性色、小圆角与平面化界面。 |
**侧边导航 · 顶部导航 · 混合导航 · 右侧导航 · 通栏分组**。支持流式或定宽内容、间距调整、固定顶栏/页脚,窄屏使用菜单抽屉。可以在[在线演示](https://xiaodaigua-ray.github.io/ray-template/)中直接切换,或查看[布局实验室](apps/docs/guide/layout.md)。
<details>
<summary>查看工作台与深色主题预览</summary>
![Modern 浅色工作台](docs/assets/readme/welcome-modern-light.png)
![Modern 深色工作台](docs/assets/readme/welcome-modern-dark.png)
[![Modern 深色 TablePro](docs/assets/readme/table-modern-dark.png)](https://xiaodaigua-ray.github.io/ray-template/#/tables/auto-height)
</details>
## 工作区与源码发行
采用 **pnpm Monorepo**,业务接入与共享能力分别维护。
| 位置 | 职责 |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| [apps/admin](apps/admin) | 页面、会话、Pinia、路由注册、业务 API 与 Mock。 |
| [apps/docs](apps/docs) | VitePress 指南、API 参考与交互示例。 |
| [packages](packages) | 10 个共享包:`ui`、`admin-shell`、`composables`、`directives`、`icons`、`http`、`api-contracts`、`demo-data`、`routing`、`utils`。 |
| [harness](harness/README.md) | 任务上下文、验证范围、检查命令与结果报告。 |
共享包通过公开 `exports` 提供能力,边界检查覆盖导入、依赖声明、运行环境与循环依赖。包随工作区使用,未单独发布到 npm。[查看架构地图](docs/architecture.md)
**纯前端源码**:执行 `pnpm dist:frontend`,在 `dist/distributions/` 生成 `ray-template-frontend-<version>.tar.gz` 及源码目录。解压后运行 `pnpm install --frozen-lockfile` 和 `pnpm dev`。导出包含 Admin、文档、共享包与 Mock,排除本地配置、凭据、构建结果和已安装依赖。`distribution.json` 记录版本、来源提交、工作区状态与内容摘要。
<!-- fullstack:start -->
**可选全栈源码**:完整仓库还包含 [apps/server](apps/server),使用 NestJS、PostgreSQL 与 Redis,实现会话、API 权限、用户、路由配置、审计与限流。执行 `pnpm dist:fullstack` 导出同版本全栈源码。
安装依赖并准备 Docker Compose 后,运行:
```sh
pnpm fullstack:setup
pnpm dev:full
export default defineComponent({
setup() {
return () => (
<RTablePro
columns={[
{ title: '姓名', key: 'name' },
{ title: '邮箱', key: 'email' },
]}
request={getPersonList}
search={[{ key: 'name', label: '姓名' }]}
columnStateKey="demo:people"
/>
)
},
})
```
`setup` 创建私有 `apps/server/.env.local`,启动 PostgreSQL 与 Redis,迁移并初始化管理员。随机生成的管理员密码保存在该文件中;真实后端不接受 Mock 演示密码。已有数据库和 Redis 时使用 `pnpm fullstack:setup --external`,配置方式见[启动指南](apps/docs/guide/distributions.md)。
1. **写页面**。在 `src/views` 新建页面,参考[远端查询示例](src/views/demo/tables/remote.tsx)加入排序、行选择和工具栏。
2. **接入导航**。在 `src/router/modules` 添加路由,给菜单配置中英文文案。页面需要缓存时,参考[路由约定](src/router/README.md)配置路由与组件名称。
3. **替换演示数据**。从 `src/api` 接入业务接口,通过 `src/axios` 统一处理拦截与取消,再接入实际登录和会话。人员列表示例在开发时走 Mock HTTP,静态预览使用本地样例数据。[请求层说明](src/axios/README.md)
也可以运行 `node scripts/fullstack.mjs up`,由 Docker 构建并启动整套服务,宿主机无需预先安装项目依赖,默认入口为 `http://127.0.0.1:8080/ray-template/`。`pnpm fullstack:stop` 停止服务并保留数据卷。
## 检查、构建与部署
[源码发行工作流](.github/workflows/distributions.yaml)提供归档验证、生成 `frontend` 分支和附加已有 Release 资产的手动选项。[容器启动与发布说明](apps/docs/guide/distributions.md#容器启动)
| 命令 | 用途 |
| ----------------------------- | -------------------------------------------------------- |
| `pnpm test:run` | 运行 Vitest 测试 |
| `pnpm check` | 执行 CI 同款检查,包含类型、Lint、格式、测试和生产构建 |
| `pnpm harness context` | 按路由、UI、API 等任务域查找源码入口和验证命令 |
| `pnpm harness verify` | 执行全量检查并保存本地报告,也可以指定任务域进行定向验证 |
| `pnpm build` / `pnpm preview` | 输出到 `dist/production`,或在本机预览构建 |
<!-- fullstack:end -->
二次开发可从[架构地图](docs/architecture.md)定位配置与模块。部署到域名根目录或子路径、为公开站点启用搜索元数据时,参考[部署指南](docs/architecture.md#deployment-and-search-discovery)。人工和 AI 协作共用 [AGENTS.md](AGENTS.md) 与 [AI Harness](harness/README.md)。
## 开发与验证
[MIT 许可证](LICENSE) · [更新日志](CHANGELOG.md) · [问题反馈](https://github.com/XiaoDaiGua-Ray/ray-template/issues)
**Vue 3 · TypeScript / TSX · Naive UI · Vite / Rolldown · Pinia · Vue Router · Vue I18n · Axios · MSW · Vitest**
| 命令 | 用途 |
| ------------------------------ | ---------------------------------------------------------------------------------------------------- |
| `pnpm dev` / `pnpm docs:dev` | 开发后台或文档站。 |
| `pnpm build` / `pnpm preview` | 构建或预览后台。 |
| `pnpm pages:build` | 将后台与文档组装到 `dist/pages`。 |
| `pnpm harness context <scope>` | 读取任务入口与相关检查命令。 |
| `pnpm harness verify <scope>` | 执行选定范围的检查并保存报告。 |
| `pnpm harness check` | 检查任务索引、相对文件链接与验证范围注册。 |
| `pnpm check` | 执行当前源码版本配置的完整检查,包括环境、契约、包边界、类型、Lint、格式、测试、站点构建与发行计划。 |
<!-- fullstack:start -->
完整仓库的 `pnpm check` 还包含服务端类型、测试与构建。发行计划检查验证导出结构与依赖,独立安装、运行和部署环境仍需对应验收。
<!-- fullstack:end -->
**Pages 工作流**在 `main` 每次 push 后构建后台与文档,将 `dist/pages` 产物直接发布到 GitHub Pages。它独立于跨平台检查,也支持在 `main` 手动发布。贡献前阅读 [AGENTS.md](AGENTS.md) 与 [Harness 验证说明](harness/README.md)。默认部署路径为后台 `/ray-template/`、文档 `/ray-template/docs/`,Pages 配置见[部署约定](docs/architecture.md#deployment-and-search-discovery)。
## 版本边界
**v6 启用 Monorepo 架构,不提供 v5 原地升级。** v5 的内部导入、接口、部署配置和浏览器数据不保证兼容。
已有项目可以继续使用 [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) 或 [v5.2.5 标签](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.5)。采用 v6 前请阅读[迁移说明](apps/docs/migration.md)。
---
[MIT License](LICENSE) · [更新记录](CHANGELOG.md) · [反馈问题](https://github.com/XiaoDaiGua-Ray/ray-template/issues) · [贡献约定](AGENTS.md)
AI 助手可从 [LLM 入口](llms.txt) 按任务读取源码和验证命令。

View File

@ -1,8 +0,0 @@
Requirements:
- Review
Additional notes:
1. Complete the tasks above in batches.
2. Proceed confidently with all the changes above. Do what you judge to be reasonable and accurate; you have full authorization for those tasks.

View File

@ -1,52 +0,0 @@
import { AdminApiError } from '@/api/admin/client'
import AccountPasswordForm from '@/app-components/app/AccountPasswordForm'
import { flushPromises, mount } from '@vue/test-utils'
import setupMiniApp from '../utils/setupMiniApp'
it('checks password confirmation, renders the API error and permits a retry', async () => {
const { app } = await setupMiniApp()
const save = vi
.fn<(next: string, current: string) => Promise<void>>()
.mockRejectedValueOnce(
new AdminApiError(
400,
'invalidCurrentPassword',
'invalidCurrentPassword',
),
)
.mockResolvedValueOnce(void 0)
const wrapper = mount(AccountPasswordForm, {
props: { username: 'fixture-user', requireCurrent: true, save },
})
try {
const current = wrapper.get('input[name="currentPassword"]')
const next = wrapper.get('input[name="newPassword"]')
const confirmation = wrapper.get('input[name="confirmPassword"]')
await current.setValue('fixture-old-password')
await next.setValue('fixture-new-password')
await confirmation.setValue('fixture-mismatch')
await wrapper.get('form').trigger('submit')
expect(save).not.toHaveBeenCalled()
expect(wrapper.get('[role="alert"]').text()).toContain('不一致')
await confirmation.setValue('fixture-new-password')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(save).toHaveBeenCalledWith(
'fixture-new-password',
'fixture-old-password',
)
expect(wrapper.get('[role="alert"]').text()).toContain('当前密码不正确')
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(save).toHaveBeenCalledTimes(2)
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
expect((next.element as HTMLInputElement).value).toBe('')
} finally {
wrapper.unmount()
app.unmount()
}
})

View File

@ -1,79 +0,0 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { runInNewContext } from 'node:vm'
const html = readFileSync(
resolve(process.cwd(), 'apps/admin/index.html'),
'utf8',
)
const source = new DOMParser()
.parseFromString(html, 'text/html')
.querySelector('script:not([type])')!.textContent!
describe('pre-bundle startup failure feedback', () => {
let splash: HTMLElement
let listener: EventListener
beforeEach(() => {
splash = document.createElement('div')
splash.id = 'pre-loading-animation'
document.body.append(splash)
const subscribe = vi.spyOn(window, 'addEventListener')
runInNewContext(source, {
window,
document,
localStorage,
HTMLScriptElement,
ErrorEvent,
})
listener = subscribe.mock.calls.find(
([type]) => type === 'error',
)![1] as EventListener
subscribe.mockRestore()
})
afterEach(() => {
window.removeEventListener('error', listener, true)
splash.remove()
vi.restoreAllMocks()
})
it('captures a non-bubbling entry/module-graph load error', () => {
const script = document.createElement('script')
script.type = 'module'
document.body.append(script)
script.dispatchEvent(new Event('error'))
expect(splash.dataset.state).toBe('failed')
script.remove()
})
it('handles parse, link, or evaluation errors reported on the window', () => {
window.dispatchEvent(
new ErrorEvent('error', {
message: 'The requested module does not provide an export',
error: new SyntaxError('Missing export'),
}),
)
expect(splash.dataset.state).toBe('failed')
})
it('does not mistake a decorative image failure for a startup failure', () => {
const image = document.createElement('img')
document.body.append(image)
image.dispatchEvent(new Event('error'))
expect(splash.dataset.state).toBeUndefined()
image.remove()
})
it('stops observing after the mounted application has removed the splash', () => {
const unsubscribe = vi.spyOn(window, 'removeEventListener')
splash.remove()
window.dispatchEvent(new ErrorEvent('error'))
expect(unsubscribe).toHaveBeenCalledWith('error', listener, true)
expect(document.getElementById('pre-loading-animation')).toBeNull()
})
})

View File

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

View File

@ -1,127 +0,0 @@
import { flushPromises, mount } from '@vue/test-utils'
import { nextTick, ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import type { AppMenuOption } from '../../apps/admin/src/types'
import Dashboard from '../../apps/admin/src/views/dashboard'
const menus = ref<AppMenuOption[]>([])
vi.mock('@/store', () => ({
useMenuGetters: () => ({ getMenuOptions: menus }),
}))
vi.mock('@/hooks', () => ({
useI18n: () => ({ t: (key: string) => key }),
}))
const menu = (
path: string,
children?: AppMenuOption[],
show = true,
): AppMenuOption => ({
path,
fullPath: path,
key: path,
name: path,
label: path,
meta: {},
children,
show,
})
const setupDashboard = async () => {
const router = createRouter({
history: createMemoryHistory(),
routes: [
'/dashboard',
'/curd/projects',
'/tables/remote',
'/doc/doc-inside',
'/template-hooks',
'/layout-demo',
'/svg-icons',
].map((path) => ({
path,
component: { render: () => null },
})),
})
await router.push('/dashboard')
const wrapper = mount(Dashboard, { global: { plugins: [router] } })
const links = () => wrapper.findAll('.r-dashboard-shortcut')
return { router, wrapper, links }
}
it('shows declared destinations below visible menu groups and navigates to the chosen page', async () => {
menus.value = [
menu('/examples', [
menu('/hooks', [menu('/template-hooks')]),
menu('/layout-demo'),
menu('/resources', [menu('/svg-icons')]),
]),
menu('/curd', [menu('/curd/projects')]),
menu('/tables', [menu('/tables/remote')]),
menu('/doc/doc-inside'),
]
const { router, wrapper, links } = await setupDashboard()
try {
expect(links().map((link) => link.attributes('href'))).toEqual([
'/curd/projects',
'/tables/remote',
'/doc/doc-inside',
'/template-hooks',
'/layout-demo',
'/svg-icons',
])
await links()[0].trigger('click')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/curd/projects')
} finally {
wrapper.unmount()
}
})
it('prunes hidden ancestors and hidden leaves instead of exposing their destinations', async () => {
menus.value = [
menu('/hidden-root', [menu('/template-hooks')], false),
menu('/visible-root', [
menu('/hidden-nested', [menu('/layout-demo')], false),
menu('/svg-icons'),
]),
]
const { wrapper, links } = await setupDashboard()
try {
expect(links().map((link) => link.attributes('href'))).toEqual([
'/svg-icons',
])
menus.value[1].children![1].show = false
await nextTick()
expect(links()).toHaveLength(0)
expect(wrapper.find('.r-dashboard-shortcuts').exists()).toBe(false)
} finally {
wrapper.unmount()
}
})
it('reacts to the current permitted tree without inventing a default or treating external entries as pages', async () => {
menus.value = [menu('/template-hooks')]
const { router, wrapper, links } = await setupDashboard()
try {
expect(links()).toHaveLength(1)
menus.value = [menu('/unrelated')]
await nextTick()
expect(links()).toHaveLength(0)
expect(router.currentRoute.value.path).toBe('/dashboard')
menus.value = [
{ ...menu('/svg-icons'), meta: { windowOpen: 'https://example.com' } },
]
await nextTick()
expect(links()).toHaveLength(0)
} finally {
wrapper.unmount()
}
})

View File

@ -1,109 +0,0 @@
import { runAppDoctor } from '@/doctor'
import * as localeDiagnostics from '@/doctor/locale-config'
import type { LocaleConfiguration } from '@/doctor/locale-config'
const configuration = vi.hoisted(() => ({
options: [{ key: 'zh-CN' }, { key: 'en-US' }],
defaultLocale: 'zh-CN',
fallbackLocale: 'zh-CN',
dayjsLocales: { 'zh-CN': 'zh-cn', 'en-US': 'en' },
defaultDayjsLocale: 'zh-cn',
}))
vi.mock('../../apps/admin/src/app-config/local-config', () => ({
get LOCAL_OPTIONS() {
return configuration.options
},
get SYSTEM_DEFAULT_LOCAL() {
return configuration.defaultLocale
},
get SYSTEM_FALLBACK_LOCALE() {
return configuration.fallbackLocale
},
get DAYJS_LOCAL_MAP() {
return configuration.dayjsLocales
},
get DEFAULT_DAYJS_LOCAL() {
return configuration.defaultDayjsLocale
},
}))
beforeEach(() => {
configuration.defaultLocale = 'zh-CN'
configuration.fallbackLocale = 'zh-CN'
})
afterEach(() => vi.restoreAllMocks())
it('accepts a consistent immutable locale snapshot without changing it', () => {
const input = Object.freeze({
options: Object.freeze([{ key: 'en-US' }]),
defaultLocale: 'en-US',
fallbackLocale: 'en-US',
dayjsLocales: Object.freeze({ 'en-US': 'en' }),
defaultDayjsLocale: 'en',
})
expect(localeDiagnostics.getLocaleConfigIssues(input)).toEqual([])
expect(input.options).toEqual([{ key: 'en-US' }])
})
it('reports duplicate choices and all independent membership problems together', () => {
const input: LocaleConfiguration = {
...configuration,
options: [{ key: 'en-US' }, { key: 'en-US' }, { key: 'en-US' }],
defaultLocale: 'zh-CN',
fallbackLocale: 'fr-FR',
defaultDayjsLocale: 'fr',
}
const issues = localeDiagnostics.getLocaleConfigIssues(input)
expect(issues).toEqual(
expect.arrayContaining([
'LOCAL_OPTIONS contains duplicate locale "en-US".',
'SYSTEM_DEFAULT_LOCAL "zh-CN" is missing from LOCAL_OPTIONS.',
'SYSTEM_FALLBACK_LOCALE "fr-FR" is missing from LOCAL_OPTIONS.',
'DAYJS_LOCAL_MAP locale "zh-CN" is missing from LOCAL_OPTIONS.',
'DEFAULT_DAYJS_LOCAL "fr" is missing from DAYJS_LOCAL_MAP values.',
]),
)
expect(issues).toHaveLength(5)
})
it('finds a selectable language that has no date-locale mapping', () => {
expect(
localeDiagnostics.getLocaleConfigIssues({
...configuration,
dayjsLocales: { 'zh-CN': 'zh-cn' },
}),
).toEqual(['DAYJS_LOCAL_MAP is missing locale "en-US" from LOCAL_OPTIONS.'])
})
it('reports configuration warnings locally and inspects fresh state on each mount', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
configuration.defaultLocale = 'missing'
expect(() => runAppDoctor()).not.toThrow()
expect(warn).toHaveBeenCalledExactlyOnceWith(
'[Ray Admin doctor] SYSTEM_DEFAULT_LOCAL "missing" is missing from LOCAL_OPTIONS.',
)
configuration.defaultLocale = 'zh-CN'
warn.mockClear()
runAppDoctor()
expect(warn).not.toHaveBeenCalled()
})
it('contains an unexpected diagnostic exception instead of rejecting application startup', () => {
const error = new Error('diagnostic failed')
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(localeDiagnostics, 'getLocaleConfigIssues').mockImplementationOnce(
() => {
throw error
},
)
expect(() => runAppDoctor()).not.toThrow()
expect(warn).toHaveBeenCalledExactlyOnceWith(
'[Ray Admin doctor] Locale diagnostics could not complete.',
error,
)
})

View File

@ -1,40 +1,24 @@
import { mount } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { h, nextTick } from 'vue'
import GlobalProvider from '../../apps/admin/src/app-components/provider/AppNaiveGlobalProvider'
import AppStyleProvider from '../../apps/admin/src/app-components/provider/AppStyleProvider'
import { piniaSettingStore } from '../../apps/admin/src/store/modules/setting'
import { nextTick } from 'vue'
import GlobalProvider from '../../src/app-components/provider/AppNaiveGlobalProvider'
import { piniaSettingStore } from '../../src/store/modules/setting'
it('reuses the global message instance across themes and removes its host on unmount', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const originalChildren = new Set(document.body.children)
const wrapper = mount(GlobalProvider, {
global: { plugins: [pinia] },
slots: { default: () => h(AppStyleProvider) },
})
const wrapper = mount(GlobalProvider, { global: { plugins: [pinia] } })
const message = window.$message
const hosts = () =>
Array.from(document.body.children).filter((el) => !originalChildren.has(el))
try {
expect(hosts()).toHaveLength(1)
const store = piniaSettingStore()
store.updateSettingState('themeStyle', 'material')
store.updateSettingState('appTheme', 'dark')
piniaSettingStore().updateSettingState('_appTheme', true)
await nextTick()
expect(window.$message).toBe(message)
expect(
document.documentElement.style.getPropertyValue('--r-token-primary'),
).toBe('#d6bbff')
expect(
document.documentElement.style.getPropertyValue('--r-token-radius'),
).toBe('20px')
expect(
document.documentElement.classList.contains('r-template--dark'),
).toBe(true)
expect(hosts()).toHaveLength(1)
} finally {
wrapper.unmount()

View File

@ -1,4 +1,4 @@
import { prefixCacheKey } from '../../apps/admin/src/utils/app/prefix-cache-key'
import { prefixCacheKey } from '../../src/utils/app/prefix-cache-key'
describe('prefixCacheKey', () => {
it('should return the key with the default prefix', () => {

View File

@ -1,77 +0,0 @@
import * as demoApi from '@/api/demo/data'
import RouteDemoDetail from '@/views/demo/router-demo/router-demo-detail'
import type { RouteDemoPerson } from '@ray-template/api-contracts/demo'
import { flushPromises, mount } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
const person = (key: number): RouteDemoPerson => ({
key,
name: `Remote person ${key}`,
address: 'Remote address',
phone: '123456',
})
const createDetailRouter = () =>
createRouter({
history: createMemoryHistory(),
routes: [{ path: '/details', component: RouteDemoDetail }],
})
afterEach(() => vi.restoreAllMocks())
it('cancels the previous detail request and ignores its late response after navigation', async () => {
const pending = new Map<
string,
{ resolve: (value: RouteDemoPerson) => void; signal?: AbortSignal }
>()
vi.spyOn(demoApi, 'getRouteDemoPerson').mockImplementation(
(id, signal) =>
new Promise((resolve) => pending.set(id, { resolve, signal })),
)
const router = createDetailRouter()
await router.push('/details?id=0')
const wrapper = mount(RouteDemoDetail, { global: { plugins: [router] } })
try {
await flushPromises()
await router.push('/details?id=1')
await flushPromises()
expect(pending.get('0')?.signal?.aborted).toBe(true)
pending.get('1')!.resolve(person(1))
await flushPromises()
pending.get('0')!.resolve(person(0))
await flushPromises()
expect(wrapper.text()).toContain('Remote person 1')
expect(wrapper.text()).not.toContain('Remote person 0')
} finally {
wrapper.unmount()
}
})
it('retries a failed detail request without showing a local sample record', async () => {
const lookup = vi
.spyOn(demoApi, 'getRouteDemoPerson')
.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce(person(2))
const router = createDetailRouter()
await router.push('/details?id=2')
const wrapper = mount(RouteDemoDetail, { global: { plugins: [router] } })
try {
await flushPromises()
expect(wrapper.text()).not.toContain('Remote person 2')
const retry = wrapper
.findAll('button')
.find((button) => /重试|Retry|retry/.test(button.text()))
expect(retry).toBeDefined()
await retry!.trigger('click')
await flushPromises()
expect(lookup).toHaveBeenCalledTimes(2)
expect(wrapper.text()).toContain('Remote person 2')
} finally {
wrapper.unmount()
}
})

View File

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

View File

@ -1,69 +0,0 @@
import Signing from '@/views/login/components/Signing'
import { flushPromises, mount } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
const { signing, loadRoutes, announceSession } = vi.hoisted(() => ({
signing: vi.fn(),
loadRoutes: vi.fn(),
announceSession: vi.fn(),
}))
vi.mock('@/api/admin/client', () => ({ apiMockEnabled: false }))
vi.mock('@/router', () => ({ loadAccountRoutes: loadRoutes }))
vi.mock('@/store/modules/signing', () => ({
announceAdminSessionChange: announceSession,
}))
vi.mock('@/hooks', () => ({
useI18n: () => ({ t: (key: string) => key }),
}))
vi.mock('@/store', () => ({
useSigningActions: () => ({ signing }),
}))
it('submits the real login form with native credential fields and no demo shortcuts', async () => {
signing.mockResolvedValue(void 0)
loadRoutes.mockResolvedValue(void 0)
const router = createRouter({
history: createMemoryHistory(),
routes: ['/', '/welcome'].map((path) => ({
path,
component: { render: () => null },
})),
})
await router.push('/')
const wrapper = mount(Signing, { global: { plugins: [router] } })
try {
const username = wrapper.get('input[name="username"]')
const password = wrapper.get('input[name="password"]')
expect(username.attributes('autocomplete')).toBe('username')
expect(password.attributes('autocomplete')).toBe('current-password')
expect(password.attributes('type')).toBe('password')
expect(wrapper.text()).not.toMatch(/UseDemo|UseMember|UseManager/u)
await username.setValue('qa-account')
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 flushPromises()
expect(signing).toHaveBeenCalledExactlyOnceWith({
name: 'qa-account',
pwd: 'qa-fixture-password',
})
expect(loadRoutes).toHaveBeenCalledExactlyOnceWith()
expect(signing.mock.invocationCallOrder[0]).toBeLessThan(
loadRoutes.mock.invocationCallOrder[0]!,
)
expect(loadRoutes.mock.invocationCallOrder[0]).toBeLessThan(
announceSession.mock.invocationCallOrder[0]!,
)
expect(router.currentRoute.value.path).toBe('/welcome')
} finally {
wrapper.unmount()
}
})

View File

@ -1,142 +0,0 @@
import * as adminApi from '@/api/admin'
import { AdminApiError } from '@/api/admin/client'
import { userOptionsSchema } from '@/api/admin/contracts'
import { router } from '@/router'
import { piniaSigningStore } from '@/store/modules/signing'
import UserManagement from '@/views/user-management'
import { useUserErrorMessage } from '@/views/user-management/error-message'
import { flushPromises, mount } from '@vue/test-utils'
import { NTree } from 'naive-ui'
import { safeParse } from 'valibot'
import setupMiniApp from '../utils/setupMiniApp'
it('indexes unordered departments in linear work and preserves the tree order', async () => {
const { app } = await setupMiniApp()
let parentReads = 0
const departments = Array.from({ length: 1000 }, (_, index) => ({
id: String(index),
name: `Team ${index}`,
get parentId() {
parentReads++
return index < 2 ? '999' : null
},
}))
vi.spyOn(adminApi, 'getUserOptions').mockResolvedValue({
departments,
roles: [],
})
const wrapper = mount(UserManagement, {
global: {
plugins: [router],
stubs: { RTablePro: true, Tree: true, RIcon: true },
},
})
try {
await flushPromises()
const tree = wrapper.getComponent(NTree)
const children = tree.props('data')![0].children!
expect(children).toHaveLength(998)
expect(children[0].key).toBe('2')
expect(children.at(-1)?.children?.map(({ label }) => label)).toEqual([
'Team 0',
'Team 1',
])
expect(tree.props('defaultExpandedKeys')).toEqual(['', '999'])
expect(parentReads).toBeLessThanOrEqual(departments.length * 2)
} finally {
wrapper.unmount()
app.unmount()
vi.restoreAllMocks()
}
})
it('accepts a deep valid department tree and rejects cycles and missing parents', () => {
const departments = Array.from({ length: 2000 }, (_, index) => ({
id: String(index),
name: String(index),
parentId: index ? String(index - 1) : null,
})).reverse()
const valid = () =>
safeParse(userOptionsSchema, { departments, roles: [] }).success
const root = departments.at(-1)!
expect(valid()).toBe(true)
root.parentId = '1999'
expect(valid()).toBe(false)
root.parentId = 'missing'
expect(valid()).toBe(false)
})
it('keeps the current list and selection context when opening and closing an editor', async () => {
localStorage.clear()
const { app } = await setupMiniApp()
await piniaSigningStore().signing({ name: 'admin', pwd: '123456' })
const fetchUsers = vi.spyOn(adminApi, 'getUsers')
const message = window.$message
window.$message = {
error: vi.fn(),
success: vi.fn(),
} as unknown as Window['$message']
const wrapper = mount(UserManagement, {
attachTo: document.body,
global: {
plugins: [router],
stubs: {
Modal: { inheritAttrs: false, template: '<div><slot /></div>' },
RIcon: { inheritAttrs: false, template: '<span />' },
},
},
})
try {
await vi.waitFor(() => expect(wrapper.text()).toContain('Alex Chen'), {
timeout: 3000,
})
expect(fetchUsers).toHaveBeenCalledTimes(1)
await wrapper
.findAll('button')
.find((button) => button.text().trim() === '新增用户')!
.trigger('click')
await flushPromises()
expect(wrapper.find('input[name="username"]').exists()).toBe(true)
expect(wrapper.text()).toContain('Alex Chen')
expect(fetchUsers).toHaveBeenCalledTimes(1)
await wrapper
.findAll('button')
.find((button) => button.text().trim() === '取消')!
.trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('Alex Chen')
expect(fetchUsers).toHaveBeenCalledTimes(1)
} finally {
wrapper.unmount()
app.unmount()
window.$message = message
localStorage.clear()
vi.restoreAllMocks()
}
})
it('shows localized limit and outage messages and falls back for unknown server errors', async () => {
const { app } = await setupMiniApp()
try {
const message = useUserErrorMessage()
const label = (code: number, key: string) =>
message(new AdminApiError(code, key, key))
expect(label(429, 'tooManyRequests')).toBe('请求过于频繁,请稍后再试。')
expect(label(503, 'serviceUnavailable')).toBe(
'服务暂时不可用,请稍后重试。',
)
expect(label(500, 'unexpectedCode')).toBe('请求失败,请稍后重试。')
} finally {
app.unmount()
}
})

View File

@ -1,267 +0,0 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { flushPromises, mount } from '@vue/test-utils'
import { NResult } from 'naive-ui'
import { h, nextTick, ref } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import type { AppMenuOption } from '../../apps/admin/src/types'
import PageResult from '../../apps/admin/src/views/error/PageResult'
import Welcome from '../../apps/admin/src/views/welcome'
const menus = ref<AppMenuOption[]>([])
const recentPaths = ref<string[]>([])
const locale = ref('en-US')
const messages: Record<
string,
Record<string, Record<string, string>>
> = Object.fromEntries(
['en-US', 'zh-CN'].map((language) => [
language,
JSON.parse(
readFileSync(
resolve(
process.cwd(),
`apps/admin/src/locales/lang/${language}/workspaceStates.json`,
),
'utf8',
),
),
]),
)
vi.mock('@/store', () => ({
useMenuGetters: () => ({ getMenuOptions: menus }),
useNavigationHistoryGetters: () => ({ recentPaths }),
piniaSigningStore: () => ({ signingCallback: { role: 'viewer' } }),
}))
vi.mock('@/hooks', () => ({
useI18n: (namespace?: string) => ({
t: (key: string) => {
if (namespace !== 'workspaceStates') return key
const [section, field] = key.split('.')
return messages[locale.value][section]?.[field] ?? key
},
}),
}))
const menu = (
path: string,
extra: Partial<AppMenuOption> = {},
): AppMenuOption => ({
path,
fullPath: path,
key: path,
name: path,
label: path,
breadcrumbLabel: path,
meta: {},
...extra,
})
const createPageRouter = async (path = '/welcome') => {
const page = { render: () => null }
const router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/welcome', name: 'RWelcome', component: page },
{ path: '/403', name: 'ErrorPage403', component: page },
{ path: '/404', name: 'ErrorPage404', component: page },
{ path: '/500', name: 'ErrorPage500', component: page },
{ path: '/reports', name: 'Reports', component: page },
{ path: '/users', name: 'Users', component: page },
{
path: '/restricted',
name: 'Restricted',
component: page,
meta: { role: ['admin'] },
},
],
})
await router.push(path)
return router
}
beforeEach(() => {
menus.value = []
recentPaths.value = []
locale.value = 'en-US'
})
it('ranks current visible menu entries by recent visits without opening a page', async () => {
menus.value = [
menu('/group', { children: [menu('/reports'), menu('/users')] }),
menu('/hidden', { show: false, children: [menu('/hidden/child')] }),
menu('/restricted', { show: false }),
menu('/external', { meta: { windowOpen: 'https://example.com' } }),
menu('/details/:id'),
]
recentPaths.value = ['/removed', '/restricted', '/users']
const router = await createPageRouter()
const wrapper = mount(Welcome, { global: { plugins: [router] } })
try {
expect(
wrapper
.findAll('.r-welcome__link')
.map((link) => link.attributes('href')),
).toEqual(['/users', '/reports'])
expect(wrapper.findAll('h1')).toHaveLength(1)
expect(router.currentRoute.value.path).toBe('/welcome')
expect(wrapper.text()).not.toContain('/removed')
menus.value = [menu('/reports')]
await nextTick()
expect(
wrapper
.findAll('.r-welcome__link')
.map((link) => link.attributes('href')),
).toEqual(['/reports'])
} finally {
wrapper.unmount()
}
})
it('offers a shortcut from each menu group before repeating a group', async () => {
menus.value = [
menu('/system', {
children: [
menu('/reports'),
menu('/maintenance', { children: [menu('/restricted')] }),
],
}),
menu('/people', { children: [menu('/users')] }),
]
const router = await createPageRouter()
const wrapper = mount(Welcome, { global: { plugins: [router] } })
const links = () =>
wrapper.findAll('.r-welcome__link').map((link) => link.attributes('href'))
try {
expect(links()).toEqual(['/reports', '/users', '/restricted'])
recentPaths.value = ['/restricted']
await nextTick()
expect(links()).toEqual(['/restricted', '/users', '/reports'])
} finally {
wrapper.unmount()
}
})
it('shows an honest no-access state and updates its language', async () => {
const router = await createPageRouter()
const wrapper = mount(Welcome, { global: { plugins: [router] } })
try {
expect(wrapper.find('nav').exists()).toBe(false)
expect(wrapper.text()).toContain(messages['en-US'].welcome.noPagesTitle)
locale.value = 'zh-CN'
await nextTick()
expect(wrapper.text()).toContain(messages['zh-CN'].welcome.noPagesTitle)
expect(wrapper.get('h1').text()).toBe(messages['zh-CN'].welcome.title)
} finally {
wrapper.unmount()
}
})
it.each([
['403', 'forbidden'],
['404', 'notFound'],
['500', 'serverError'],
] as const)(
'renders %s with its own identity and neutral recovery action',
async (status, key) => {
const router = await createPageRouter(`/${status}`)
const wrapper = mount(PageResult, {
props: { status },
global: { plugins: [router] },
})
try {
expect(wrapper.getComponent(NResult).props('status')).toBe(status)
expect(wrapper.get('h1').text()).toBe(messages['en-US'][key].title)
expect(wrapper.get('.error-page__mark').text()).toBe(status)
await wrapper.get('button').trigger('click')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/welcome')
} finally {
wrapper.unmount()
}
},
)
it('retries an authorized failed route with its query and hash intact', async () => {
const router = await createPageRouter(
'/500?from=%2Freports%3Fperiod%3Dweek%23chart',
)
const wrapper = mount(PageResult, {
props: { status: '500' },
global: { plugins: [router] },
})
try {
const retry = wrapper
.findAll('button')
.find((button) => button.text() === messages['en-US'].actions.retry)!
await retry.trigger('click')
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe(
'/reports?period=week#chart',
)
} finally {
wrapper.unmount()
}
})
it.each(['//example.com', '/500', '/restricted'])(
'omits retry for unsafe/unavailable target %s',
async (from) => {
const router = await createPageRouter(
`/500?from=${encodeURIComponent(from)}`,
)
const wrapper = mount(PageResult, {
props: { status: '500' },
global: { plugins: [router] },
})
try {
expect(wrapper.findAll('button').map((button) => button.text())).toEqual([
messages['en-US'].actions.workspace,
])
} finally {
wrapper.unmount()
}
},
)
it('preserves custom title, description, content and footer configuration', async () => {
const router = await createPageRouter('/404')
const wrapper = mount(PageResult, {
props: {
status: '404',
title: 'Custom title',
description: 'Custom explanation',
},
slots: {
default: () => h('p', 'Details'),
footer: () => h('button', 'Custom recovery'),
},
global: { plugins: [router] },
})
try {
expect(wrapper.get('h1').text()).toBe('Custom title')
expect(wrapper.text()).toContain('Custom explanation')
expect(wrapper.text()).toContain('Details')
expect(wrapper.findAll('button').map((button) => button.text())).toEqual([
'Custom recovery',
])
} finally {
wrapper.unmount()
}
})

View File

@ -1,100 +0,0 @@
import { mount } from '@vue/test-utils'
import { NAvatar, NButton, NSpin } from 'naive-ui'
import { nextTick } from 'vue'
import AppAvatar from '../../apps/admin/src/app-components/app/AppAvatar'
import AppGlobalSpin from '../../apps/admin/src/app-components/app/AppGlobalSpin'
import UnlockScreen from '../../apps/admin/src/app-components/app/AppLockScreen/components/UnlockScreen'
vi.mock('@/store', async () => {
const { ref } = await import('vue')
return {
useSigningGetters: () => ({
getSigningCallback: ref({ name: 'Tester', avatar: '' }),
}),
useRuntimeGetters: () => ({ globalSpinning: ref(true) }),
useSettingActions: () => ({ updateSettingState: vi.fn() }),
useSettingGetters: () => ({ getLocaleLanguage: ref('en-US') }),
useSigningActions: () => ({ logout: vi.fn() }),
useLockScreenActions: () => ({ setLocked: vi.fn() }),
useLockScreenGetters: () => ({ getLocked: ref(true) }),
}
})
vi.mock('@/hooks', () => ({
useI18n: () => ({ t: (key: string) => key }),
useDevice: () => ({ isTabletOrSmaller: false }),
}))
it('honors avatar shape, native size, and keyboard focus', () => {
const wrapper = mount(AppAvatar, {
props: {
round: false,
size: 42,
objectFit: 'contain',
color: 'rgb(18, 52, 86)',
},
})
try {
const avatar = wrapper.findComponent(NAvatar)
expect(avatar.props()).toMatchObject({
round: false,
size: 42,
objectFit: 'contain',
})
expect((avatar.element as HTMLElement).style.backgroundColor).toBe(
'rgb(18, 52, 86)',
)
expect(wrapper.findComponent(NButton).props('focusable')).toBe(true)
} finally {
wrapper.unmount()
}
})
it('merges global spin overrides while preserving its owned busy state', () => {
const wrapper = mount(AppGlobalSpin, {
props: { show: false, themeOverrides: { opacitySpinning: '0.7' } },
})
try {
expect(wrapper.findComponent(NSpin).props()).toMatchObject({
show: true,
themeOverrides: { opacitySpinning: '0.7' },
})
} finally {
wrapper.unmount()
}
})
it('updates the lock-screen date at midnight and cancels its minute timer', async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-11-06T23:59:59'))
vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
const wrapper = mount(UnlockScreen, {
global: {
stubs: {
AppAvatar: true,
RForm: { template: '<div><slot /></div>' },
NFormItem: { template: '<div><slot /></div>' },
NInput: true,
NButton: true,
NFlex: { template: '<div><slot /></div>' },
},
},
})
try {
expect(wrapper.text()).toContain('2026-11-06')
await vi.advanceTimersByTimeAsync(1_000)
await nextTick()
expect(wrapper.text()).toContain('2026-11-07')
wrapper.unmount()
expect(vi.getTimerCount()).toBe(0)
} finally {
wrapper.unmount()
vi.restoreAllMocks()
vi.useRealTimers()
}
})

View File

@ -1,39 +0,0 @@
import { APP_CATCH_KEY } from '@/app-config'
import { injectRequestHeaders } from '@/axios/axios-interceptor/request/plugins/request-headers'
import type { RequestInterceptorConfig } from '@/axios/types'
import { setStorage } from '@/utils/cache'
import { AxiosHeaders } from 'axios'
afterEach(() => {
localStorage.clear()
vi.unstubAllEnvs()
})
it('sends Bearer credentials only to the configured API origin and path', () => {
vi.stubEnv('VITE_API_BASE_URL', 'https://api.example.test/v1/')
setStorage(APP_CATCH_KEY.token, 'test-token', 'localStorage')
const config = (url: string): RequestInterceptorConfig => ({
url,
headers: new AxiosHeaders(),
})
const owned = config('https://api.example.test/v1/admin/users')
injectRequestHeaders(owned, '')
expect(owned.headers?.Authorization).toBe('Bearer test-token')
for (const url of [
'https://other.example.test/v1/admin/users',
'https://api.example.test/v10/admin/users',
]) {
const foreign = config(url)
injectRequestHeaders(foreign, '')
expect(foreign.headers?.Authorization).toBeUndefined()
}
const explicit = config('https://api.example.test/v1/admin/users')
explicit.headers = { authorization: 'Bearer supplied-token' }
injectRequestHeaders(explicit, '')
expect(explicit.headers.authorization).toBe('Bearer supplied-token')
})

View File

@ -1,6 +1,6 @@
import { expectTypeOf } from 'vitest'
import request from '../../apps/admin/src/axios/instance'
import type { AppRawRequestConfig } from '../../apps/admin/src/axios/types'
import request from '../../src/axios/instance'
import type { AppRawRequestConfig } from '../../src/axios/types'
const data = { id: 42, name: 'Ray' }
const adapter: AppRawRequestConfig['adapter'] = async (config) => ({

View File

@ -1,4 +1,4 @@
import { arrayBufferToBase64Image } from '../../apps/admin/src/utils/basic'
import { arrayBufferToBase64Image } from '../../src/utils/basic'
describe('arrayBufferToBase64Image', () => {
const arrayBuffer = new ArrayBuffer(8)
@ -16,40 +16,3 @@ describe('arrayBufferToBase64Image', () => {
expect(base64Image.startsWith(base64ImagePrefix)).toBe(true)
})
})
it('preserves byte values across chunk boundaries for a large buffer', () => {
const bytes = Uint8Array.from({ length: 262145 }, (_, index) => index % 256)
expect(arrayBufferToBase64Image(bytes.buffer)).toBe(
'data:image/png;base64,' + Buffer.from(bytes).toString('base64'),
)
expect(arrayBufferToBase64Image(new ArrayBuffer(0))).toBe(
'data:image/png;base64,',
)
})
it('keeps a compatible encoding path when native typed-array Base64 is unavailable', () => {
const descriptor = Object.getOwnPropertyDescriptor(
Uint8Array.prototype,
'toBase64',
)
// eslint-disable-next-line no-extend-native -- 模拟缺少原生 API 的浏览器,finally 恢复描述符。
Object.defineProperty(Uint8Array.prototype, 'toBase64', {
configurable: true,
value: void 0,
})
try {
const bytes = Uint8Array.from({ length: 65539 }, (_, index) => index % 256)
expect(arrayBufferToBase64Image(bytes.buffer)).toBe(
'data:image/png;base64,' + Buffer.from(bytes).toString('base64'),
)
} finally {
if (descriptor)
// eslint-disable-next-line no-extend-native -- 恢复测试前的原生描述符。
Object.defineProperty(Uint8Array.prototype, 'toBase64', descriptor)
else Reflect.deleteProperty(Uint8Array.prototype, 'toBase64')
}
})

View File

@ -1,4 +1,4 @@
import { callWithAsyncErrorHandling } from '../../apps/admin/src/utils/basic'
import { callWithAsyncErrorHandling } from '../../src/utils/basic'
describe('callWithAsyncErrorHandling', () => {
it('should call the function and return the result', async () => {

View File

@ -1,4 +1,4 @@
import { callWithErrorHandling } from '../../apps/admin/src/utils/basic'
import { callWithErrorHandling } from '../../src/utils/basic'
describe('callWithErrorHandling', () => {
it('should call the function and return the result', () => {

View File

@ -1,4 +1,4 @@
import { detectOperatingSystem } from '../../apps/admin/src/utils/basic'
import { detectOperatingSystem } from '../../src/utils/basic'
describe('detectOperatingSystem', () => {
afterEach(() => vi.restoreAllMocks())

View File

@ -1,4 +1,4 @@
import { downloadAnyFile } from '../../apps/admin/src/utils/basic'
import { downloadAnyFile } from '../../src/utils/basic'
describe('downloadAnyFile', () => {
const url = 'blob:test'

View File

@ -1,4 +1,4 @@
import { downloadBase64File } from '../../apps/admin/src/utils/basic'
import { downloadBase64File } from '../../src/utils/basic'
describe('downloadBase64File', () => {
const base64 =

View File

@ -1,4 +1,4 @@
import { equalRouterPath } from '../../apps/admin/src/utils/basic'
import { equalRouterPath } from '../../src/utils/basic'
describe('equalRouterPath', () => {
it('compare paths with parameters', () => {

View File

@ -1,4 +1,4 @@
import { getAppEnvironment } from '../../apps/admin/src/utils/basic'
import { getAppEnvironment } from '../../src/utils/basic'
describe('getAppEnvironment', () => {
it('should return MODE is test', () => {

View File

@ -1,4 +1,4 @@
import { isAsyncFunction } from '../../apps/admin/src/utils/basic'
import { isAsyncFunction } from '../../src/utils/basic'
describe('isAsyncFunction', () => {
it('should return true if the function is async', () => {

View File

@ -1,4 +1,4 @@
import { isPromise } from '../../apps/admin/src/utils/basic'
import { isPromise } from '../../src/utils/basic'
describe('isPromise', () => {
it('should return true if the value is a Promise', () => {

View File

@ -1,4 +1,4 @@
import { isValueType } from '../../apps/admin/src/utils/basic'
import { isValueType } from '../../src/utils/basic'
describe('isValueType', () => {
it('should return true for string', () => {

View File

@ -1,4 +1,4 @@
import { uuid } from '../../apps/admin/src/utils/basic'
import { uuid } from '../../src/utils/basic'
describe('uuid', () => {
it('should return String', () => {
@ -31,26 +31,3 @@ it('enforces the requested radix and rejects invalid bounds', () => {
expect(() => uuid(-1)).toThrow(RangeError)
expect(() => uuid(Infinity)).toThrow(RangeError)
})
it('rejects biased samples while filling identifiers across several batches', () => {
let batch = 0
const random = vi
.spyOn(crypto, 'getRandomValues')
.mockImplementation((samples) => {
const values = samples as Uint32Array
values.fill(batch++ === 0 ? 0xffffffff : 9)
return samples
})
try {
expect(uuid(257, 10)).toBe('9'.repeat(257))
} finally {
random.mockRestore()
}
})
it('supports long identifiers without exceeding the Web Crypto byte quota', () => {
expect(uuid(70000, 10)).toMatch(/^\d{70000}$/)
})

View File

@ -1,33 +0,0 @@
import {
getStorage,
removeStorage,
setStorage,
} from '../../apps/admin/src/utils/cache'
import { useMemoryCache } from '../../apps/admin/src/utils/cache-backend'
it('keeps writes and bulk clears in the documentation example out of the real app storage', () => {
const key = 'ray:example-isolation-test'
localStorage.setItem(key, JSON.stringify('admin local'))
sessionStorage.setItem(key, JSON.stringify('admin session'))
try {
useMemoryCache()
expect(getStorage(key, 'localStorage')).toBeNull()
expect(getStorage(key, 'sessionStorage')).toBeNull()
setStorage(key, 'example local', 'localStorage')
setStorage(key, 'example session', 'sessionStorage')
expect(getStorage(key, 'localStorage')).toBe('example local')
expect(getStorage(key, 'sessionStorage')).toBe('example session')
removeStorage('__all__', 'all')
expect(getStorage(key, 'localStorage')).toBeNull()
expect(getStorage(key, 'sessionStorage')).toBeNull()
expect(localStorage.getItem(key)).toBe(JSON.stringify('admin local'))
expect(sessionStorage.getItem(key)).toBe(JSON.stringify('admin session'))
} finally {
localStorage.removeItem(key)
sessionStorage.removeItem(key)
}
})

View File

@ -3,7 +3,7 @@ import {
hasStorage,
removeStorage,
setStorage,
} from '../../apps/admin/src/utils/cache'
} from '../../src/utils/cache'
describe('cache utils', () => {
const __DEMO__KEY = '__DEMO__KEY'

View File

@ -1,67 +0,0 @@
import { createStorage } from '@ray-template/utils/storage'
it('namespaces JSON values and reads the current backend instead of caching a copy', () => {
const backend = new Map<string, string>()
const storage = createStorage(
{
getItem: (key) => backend.get(key) ?? null,
setItem: (key, value) => {
backend.set(key, value)
},
removeItem: (key) => {
backend.delete(key)
},
},
'table:',
)
storage.set('columns', ['name'])
expect(backend.get('table:columns')).toBe('["name"]')
backend.set('table:columns', '["status"]')
expect(storage.get('columns')).toEqual(['status'])
storage.remove('columns')
expect(storage.get('columns')).toBeNull()
})
it('preserves a saved value when a replacement cannot be serialized', () => {
const setItem = vi.fn()
const storage = createStorage({
getItem: () => '"saved"',
setItem,
removeItem: vi.fn(),
})
const circular: { self?: unknown } = {}
circular.self = circular
for (const value of [void 0, Symbol('value'), () => 1, circular, 1n]) {
storage.set('value', value)
}
expect(setItem).not.toHaveBeenCalled()
expect(storage.get('value')).toBe('saved')
storage.set('value', null)
expect(setItem).toHaveBeenCalledExactlyOnceWith('value', 'null')
})
it('contains unavailable-backend errors and malformed JSON', () => {
const fail = () => {
throw new Error('storage denied')
}
const storage = createStorage({
getItem: fail,
setItem: fail,
removeItem: fail,
})
expect(storage.get('value')).toBeNull()
expect(() => storage.set('value', 1)).not.toThrow()
expect(() => storage.remove('value')).not.toThrow()
expect(
createStorage({
getItem: () => '{bad',
setItem: vi.fn(),
removeItem: vi.fn(),
}).get('value'),
).toBeNull()
})

View File

@ -1,83 +0,0 @@
import { resolve } from 'node:path'
import { flushPromises, mount } from '@vue/test-utils'
import barcode from 'jsbarcode'
import { compile } from 'sass'
import { reactive } from 'vue'
import { RBarcode } from '../../packages/ui/src/RBarcode'
vi.mock('jsbarcode', () => ({ default: vi.fn() }))
beforeEach(() => vi.mocked(barcode).mockClear())
it('keeps the fixed dimension on either responsive axis', async () => {
const style = document.createElement('style')
style.textContent = compile(
resolve('packages/ui/src/RBarcode/src/index.scss'),
).css
document.head.append(style)
const wrapper = mount(RBarcode, {
attachTo: document.body,
props: { text: '123', responsive: true, width: 'responsive', height: 48 },
})
try {
const canvas = wrapper.get('canvas').element
expect(getComputedStyle(canvas).height).toBe('48px')
await wrapper.setProps({ width: 96, height: 'responsive' })
expect(getComputedStyle(canvas).width).toBe('96px')
} finally {
wrapper.unmount()
style.remove()
}
})
it('redraws changed format, options and renderer without changing text', async () => {
const options = reactive({ lineColor: '#123456' })
const wrapper = mount(RBarcode, { props: { text: '123456', options } })
try {
await flushPromises()
expect(barcode).toHaveBeenCalledTimes(1)
await wrapper.setProps({ format: 'CODE39' })
expect(barcode).toHaveBeenLastCalledWith(
expect.any(HTMLCanvasElement),
'123456',
expect.objectContaining({ format: 'CODE39' }),
)
options.lineColor = '#abcdef'
await flushPromises()
expect(barcode).toHaveBeenLastCalledWith(
expect.any(HTMLCanvasElement),
'123456',
expect.objectContaining({ lineColor: '#abcdef' }),
)
await wrapper.setProps({ barcodeRender: 'svg' })
expect(vi.mocked(barcode).mock.lastCall?.[0]).toBe(
wrapper.get('svg').element,
)
} finally {
wrapper.unmount()
}
})
it('honors watchText and resumes with the latest value when enabled', async () => {
const wrapper = mount(RBarcode, { props: { text: '123', watchText: false } })
try {
await flushPromises()
const count = vi.mocked(barcode).mock.calls.length
await wrapper.setProps({ text: '456' })
expect(barcode).toHaveBeenCalledTimes(count)
await wrapper.setProps({ watchText: true })
expect(barcode).toHaveBeenLastCalledWith(
expect.anything(),
'456',
expect.anything(),
)
} finally {
wrapper.unmount()
}
})

View File

@ -1,137 +0,0 @@
import { color } from 'echarts/core'
import { darkTheme, lightTheme } from 'naive-ui'
import { getCustomEchartTheme } from '../../packages/ui/src/RChart/src/utils/get-custom-echart-theme'
import { loadingOptions } from '../../packages/ui/src/RChart/src/utils/loading-options'
import {
themeStyleOverrides,
themeStyles,
} from '../../packages/ui/src/theme-presets'
import { contrast } from '../utils/color-contrast'
const registeredThemes = getCustomEchartTheme()
const themes = new Map(registeredThemes.map(({ name, theme }) => [name, theme]))
const variants = themeStyles.flatMap((style) =>
(['light', 'dark'] as const).map((mode) => ({
style,
mode,
name: `ray-${style}${mode === 'dark' ? '-dark' : ''}`,
})),
)
it('registers every style in both modes with unique deterministic names', () => {
expect(registeredThemes).toHaveLength(themes.size)
expect([...themes.keys()]).toEqual(
expect.arrayContaining(variants.map(({ name }) => name)),
)
})
it.each(variants)(
'$name matches the owning page surface',
({ style, mode, name }) => {
const theme = themes.get(name)!
const common = {
...(mode === 'dark' ? darkTheme : lightTheme).common,
...themeStyleOverrides[style][mode].common,
}
expect(color.parse(theme.backgroundColor)).toEqual(
color.parse(common.cardColor),
)
expect(theme.darkMode).toBe(mode === 'dark')
expect(color.parse(theme.pie.itemStyle.borderColor)).toEqual(
color.parse(common.cardColor),
)
},
)
it.each(variants)(
'$name keeps text, data, and active pointers legible',
({ name }) => {
const theme = themes.get(name)!
const background = theme.backgroundColor
const textColors = [
theme.textStyle.color,
theme.title.textStyle.color,
theme.title.subtextStyle.color,
theme.legend.textStyle.color,
...['categoryAxis', 'valueAxis', 'timeAxis', 'logAxis'].map(
(axis) => theme[axis].axisLabel.color,
),
]
for (const foreground of textColors) {
expect(
contrast(foreground, background),
`${name}: text ${foreground}`,
).toBeGreaterThanOrEqual(4.5)
}
expect(
contrast(
theme.tooltip.textStyle.color,
theme.tooltip.backgroundColor,
background,
),
).toBeGreaterThanOrEqual(4.5)
const pointer = theme.tooltip.axisPointer
expect(
contrast(pointer.label.color, pointer.label.backgroundColor, background),
).toBeGreaterThanOrEqual(4.5)
for (const foreground of [
...theme.color,
pointer.lineStyle.color,
pointer.crossStyle.color,
]) {
expect(
contrast(foreground, background),
`${name}: mark ${foreground}`,
).toBeGreaterThanOrEqual(3)
}
},
)
it.each(variants)(
'$name supplies a matching loading layer without mutating its theme',
({ mode, name }) => {
const theme = themes.get(name)!
const before = JSON.stringify(theme)
const loading = loadingOptions(theme, mode === 'dark', 'Loading', {})
const background = color.parse(theme.backgroundColor)
expect(color.parse(loading.maskColor)).toEqual([
...background.slice(0, 3),
0.9,
])
expect(loading.color).toBe(theme.color[0])
expect(loading.textColor).toBe(theme.textStyle.color)
expect(JSON.stringify(theme)).toBe(before)
},
)
it.each(['transparent', 'rgba(0, 0, 0, 0)', 'invalid', void 0])(
'uses a mode-aware surface for a missing/transparent loading background (%s)',
(backgroundColor) => {
const theme = { backgroundColor }
expect(
color.parse(loadingOptions(theme, false, 'Loading', {}).maskColor),
).toEqual([255, 255, 255, 0.9])
expect(
color.parse(loadingOptions(theme, true, 'Loading', {}).maskColor),
).toEqual([23, 33, 49, 0.9])
},
)
it('preserves caller loading overrides', () => {
const overrides = {
maskColor: 'transparent',
showSpinner: false,
text: 'Preparing',
}
expect(
loadingOptions(themes.get('ray-modern'), false, 'Loading', overrides),
).toMatchObject(overrides)
})

View File

@ -1,309 +0,0 @@
import { flushPromises, mount } from '@vue/test-utils'
import { init } from 'echarts/core'
import type { ECharts } from 'echarts/core'
import { nextTick, reactive, ref } from 'vue'
import { RChart, useChart } from '../../packages/ui/src/RChart'
import { USE_CHART_PROVIDER_KEY } from '../../packages/ui/src/RChart/src/config'
import { provideUiServices } from '../../packages/ui/src/services'
vi.mock('echarts/core', async (importOriginal) => {
const actual = await importOriginal<typeof import('echarts/core')>()
return { ...actual, init: vi.fn() }
})
const charts: ReturnType<typeof fakeChart>[] = []
const fakeChart = (element: HTMLElement) => {
let disposed = false
let option = {}
return {
getDom: () => element,
getOption: () => option,
isDisposed: () => disposed,
dispose: vi.fn(() => {
disposed = true
}),
setOption: vi.fn((next) => {
option = { ...option, ...next }
}),
setTheme: vi.fn(),
resize: vi.fn(),
showLoading: vi.fn(),
hideLoading: vi.fn(),
}
}
beforeEach(() => {
charts.length = 0
vi.mocked(init).mockReset()
vi.mocked(init).mockImplementation((element) => {
const chart = fakeChart(element as HTMLElement)
charts.push(chart)
return chart as unknown as ECharts
})
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('updates the live chart on style and color mode changes and resumes only on render', async () => {
const dark = ref(false)
const style = ref('ray-modern')
const [register, actions] = useChart()
const wrapper = mount({
setup() {
provideUiServices({
dark: () => dark.value,
chartTheme: () => style.value,
})
return () => <RChart intersectionObserver={false} onRegister={register} />
},
})
try {
await flushPromises()
expect(init).toHaveBeenLastCalledWith(
expect.anything(),
'ray-modern',
expect.anything(),
)
expect(actions.getChartInstance().echartInst).toBe(charts[0])
style.value = 'ray-material'
await nextTick()
dark.value = true
await nextTick()
expect(charts[0].setTheme.mock.calls).toEqual([
['ray-material'],
['ray-material-dark'],
])
expect(init).toHaveBeenCalledTimes(1)
expect(actions.isDisposed()).toBe(false)
actions.dispose()
style.value = 'ray-plain'
await flushPromises()
expect(charts[0].dispose).toHaveBeenCalledOnce()
expect(init).toHaveBeenCalledTimes(1)
actions.render()
await flushPromises()
expect(init).toHaveBeenLastCalledWith(
expect.anything(),
'ray-plain-dark',
expect.anything(),
)
expect(actions.getChartInstance().echartInst).toBe(charts[1])
} finally {
wrapper.unmount()
}
})
it('applies options and custom loading before callbacks, and preserves caller ARIA settings', async () => {
const calls: string[] = []
const wrapper = mount(RChart, {
props: {
intersectionObserver: false,
loading: true,
loadingOptions: {
text: 'Collecting data',
color: '#123456',
showSpinner: false,
},
options: {
aria: { label: { description: 'Weekly sales' }, decal: { decals: [] } },
},
showAria: true,
onRegister: () => calls.push('register'),
onSuccess: (chart) => {
expect(chart.getOption()).toMatchObject({ aria: { enabled: true } })
calls.push('success')
},
onFinally: () => calls.push('finally'),
},
})
try {
await flushPromises()
expect(calls).toEqual(['register', 'success', 'finally'])
expect(charts[0].getOption()).toMatchObject({
aria: {
enabled: true,
label: { description: 'Weekly sales' },
decal: { show: true, decals: [] },
},
})
expect(charts[0].showLoading).toHaveBeenCalledWith(
'default',
expect.objectContaining({
text: 'Collecting data',
color: '#123456',
showSpinner: false,
}),
)
charts[0].getDom().setAttribute('aria-label', 'Weekly sales')
await wrapper.setProps({ showAria: false })
expect(charts[0].getDom().hasAttribute('aria-label')).toBe(false)
expect(charts[0].getOption()).toMatchObject({ aria: { enabled: false } })
} finally {
wrapper.unmount()
}
})
it('reports a deferred setOption failure and disposes the partial instance', async () => {
const error = new Error('Invalid option')
const onError = vi.fn()
const onFinally = vi.fn()
const onSuccess = vi.fn()
const onRegister = vi.fn()
const errorHandler = vi.fn()
vi.mocked(init).mockImplementationOnce((element) => {
const chart = fakeChart(element as HTMLElement)
chart.setOption.mockImplementationOnce(() => {
throw error
})
charts.push(chart)
return chart as unknown as ECharts
})
const wrapper = mount(RChart, {
props: {
intersectionObserver: false,
onError,
onFinally,
onRegister,
onSuccess,
},
global: { config: { errorHandler } },
})
try {
await flushPromises()
expect(charts[0].dispose).toHaveBeenCalledOnce()
expect(onError).toHaveBeenCalledOnce()
expect(onFinally).toHaveBeenCalledOnce()
expect(onSuccess).not.toHaveBeenCalled()
expect(onRegister).not.toHaveBeenCalled()
expect(errorHandler.mock.calls[0][0].cause).toBe(error)
} finally {
wrapper.unmount()
}
})
it('defers offscreen initialization, even when the theme changes', async () => {
let visible: () => void = () => {}
const disconnect = vi.fn()
class Observer {
constructor(callback: IntersectionObserverCallback) {
visible = () =>
callback(
[{ isIntersecting: true } as IntersectionObserverEntry],
this as unknown as IntersectionObserver,
)
}
observe() {}
disconnect = disconnect
}
vi.stubGlobal('IntersectionObserver', Observer)
const dark = ref(false)
const value = ref(1)
const readValue = vi.fn(() => value.value)
const options = reactive({
series: [
{
data: [
{
get value() {
return readValue()
},
},
],
},
],
})
const wrapper = mount({
setup() {
provideUiServices({ dark: () => dark.value })
return () => <RChart theme="default" options={options} />
},
})
try {
await flushPromises()
dark.value = true
value.value = 2
await nextTick()
expect(init).not.toHaveBeenCalled()
expect(readValue).not.toHaveBeenCalled()
visible()
await flushPromises()
expect(charts[0].getOption()).toMatchObject({
series: [{ data: [{ value: 2 }] }],
})
expect(disconnect).toHaveBeenCalled()
expect(init).toHaveBeenLastCalledWith(
expect.anything(),
'dark',
expect.anything(),
)
dark.value = false
await nextTick()
expect(charts[0].setTheme).toHaveBeenCalledWith('default')
} finally {
wrapper.unmount()
}
})
it('honors a fixed Provider theme when appearance changes', async () => {
const dark = ref(false)
const wrapper = mount(
{
setup() {
provideUiServices({ dark: () => dark.value })
return () => <RChart intersectionObserver={false} theme="default" />
},
},
{
global: {
provide: { [USE_CHART_PROVIDER_KEY]: { theme: 'ray-naive-dark' } },
},
},
)
try {
await flushPromises()
dark.value = true
await nextTick()
expect(init).toHaveBeenLastCalledWith(
expect.anything(),
'ray-naive-dark',
expect.anything(),
)
expect(charts[0].setTheme).not.toHaveBeenCalled()
} finally {
wrapper.unmount()
}
})

View File

@ -1,37 +0,0 @@
import { mount } from '@vue/test-utils'
import { defineComponent, h, ref, withDirectives } from 'vue'
import disabled from '../../packages/directives/src/modules/disabled'
it('restores a native button and toggles the whole form without changing its children', async () => {
const value = ref(false)
const directive = disabled()
const wrapper = mount(
defineComponent(
() => () =>
h('div', [
withDirectives(h('button'), [[directive, value.value]]),
withDirectives(h('form', [h('input', { disabled: true })]), [
[directive, value.value],
]),
]),
),
)
try {
const button = wrapper.get('button').element
const form = wrapper.get('form').element
expect(button.disabled).toBe(false)
value.value = true
await wrapper.vm.$nextTick()
expect(button.disabled).toBe(true)
expect(form.hasAttribute('inert')).toBe(true)
value.value = false
await wrapper.vm.$nextTick()
expect(button.disabled).toBe(false)
expect(form.hasAttribute('inert')).toBe(false)
expect(wrapper.get('input').element.disabled).toBe(true)
} finally {
wrapper.unmount()
}
})

View File

@ -1,82 +0,0 @@
import { flushPromises, mount } from '@vue/test-utils'
import interact from 'interactjs'
import RDraggableCard from '../../packages/ui/src/RDraggableCard/DraggableCard'
const mocks = vi.hoisted(() => ({
instances: [] as Array<{
draggable: ReturnType<typeof vi.fn>
resizable: ReturnType<typeof vi.fn>
unset: ReturnType<typeof vi.fn>
}>,
}))
vi.mock('interactjs', () => ({
default: Object.assign(
vi.fn(() => {
const instance = {
draggable: vi.fn().mockReturnThis(),
resizable: vi.fn().mockReturnThis(),
unset: vi.fn(),
}
mocks.instances.push(instance)
return instance
}),
{ modifiers: { restrictRect: vi.fn((value) => value) } },
),
}))
beforeEach(() => {
mocks.instances.length = 0
vi.mocked(interact).mockClear()
})
it('uses the rendered body as the drag handle when the card has no title', async () => {
const wrapper = mount(RDraggableCard, { slots: { default: 'Body' } })
try {
await flushPromises()
const { allowFrom } = mocks.instances[0].draggable.mock.calls[0][0]
expect(
document.querySelector('.r-draggable-card')?.querySelector(allowFrom)
?.textContent,
).toContain('Body')
} finally {
wrapper.unmount()
}
})
it('releases drag listeners on disable/unmount and removes only the final shared container', async () => {
const first = mount(RDraggableCard, { props: { title: 'First' } })
const second = mount(RDraggableCard, { props: { title: 'Second' } })
await flushPromises()
expect(interact).toHaveBeenCalledTimes(2)
await first.setProps({ dad: false })
expect(mocks.instances[0].unset).toHaveBeenCalledOnce()
await first.setProps({ dad: true })
expect(interact).toHaveBeenCalledTimes(3)
first.unmount()
expect(mocks.instances[2].unset).toHaveBeenCalledOnce()
expect(document.getElementById('r-draggable-card-container')).not.toBeNull()
second.unmount()
expect(mocks.instances[1].unset).toHaveBeenCalledOnce()
expect(document.getElementById('r-draggable-card-container')).toBeNull()
})
it('repositions and rebinds after boundary changes without keeping the previous interaction', async () => {
const wrapper = mount(RDraggableCard, { props: { title: 'Test' } })
try {
await flushPromises()
await wrapper.setProps({ defaultPosition: { x: 24, y: 36 } })
expect(mocks.instances[0].unset).toHaveBeenCalledOnce()
expect(
document.querySelector<HTMLElement>('.r-draggable-card')?.style.transform,
).toBe('translate(24px, 36px)')
} finally {
wrapper.unmount()
}
})

View File

@ -1,98 +0,0 @@
import LogicFlow from '@logicflow/core'
import { flushPromises, mount } from '@vue/test-utils'
import { RFlow, useFlow } from '../../packages/ui/src/RFlow'
import flowProps from '../../packages/ui/src/RFlow/src/props'
const mocks = vi.hoisted(() => ({
instances: [] as Array<{
render: ReturnType<typeof vi.fn>
renderRawData: ReturnType<typeof vi.fn>
destroy: ReturnType<typeof vi.fn>
updateEditConfig: ReturnType<typeof vi.fn>
keyboard: { disabled: boolean; disable: ReturnType<typeof vi.fn> }
}>,
}))
vi.mock('@logicflow/core', () => {
class FakeFlow {
static use = vi.fn()
render = vi.fn()
renderRawData = vi.fn()
destroy = vi.fn()
updateEditConfig = vi.fn()
keyboard = { disabled: true, disable: vi.fn() }
getEditConfig = () => ({
isSilentMode: false,
textEdit: false,
adjustNodePosition: false,
})
constructor() {
mocks.instances.push(this)
}
}
return { default: FakeFlow }
})
beforeEach(() => {
mocks.instances.length = 0
vi.mocked(LogicFlow.use).mockClear()
})
it('registers later plugin sets, renders initial data, and releases each instance', async () => {
const [register, actions] = useFlow()
const data = { nodes: [{ id: 'start' }], edges: [] }
const plugin = { pluginName: 'later-plugin', install: vi.fn() }
const first = mount(RFlow)
const second = mount(RFlow, {
props: { data, use: [plugin], onRegister: register },
})
expect(LogicFlow.use).toHaveBeenCalledWith(plugin)
expect(mocks.instances[1].render).toHaveBeenCalledWith(data)
expect(actions.getFlowInstance()).toBe(mocks.instances[1])
await second.setProps({ data: void 0 })
expect(mocks.instances[1].renderRawData).toHaveBeenLastCalledWith({
nodes: [],
edges: [],
})
first.unmount()
second.unmount()
await flushPromises()
expect(
mocks.instances.every(
(instance) => instance.destroy.mock.calls.length === 1,
),
).toBe(true)
expect(() => actions.getFlowInstance()).toThrow('flow instance is not ready')
})
it('restores configured editing and keyboard behavior after readonly mode', async () => {
const wrapper = mount(RFlow)
const instance = mocks.instances[0]
try {
expect(instance.updateEditConfig).not.toHaveBeenCalled()
await wrapper.setProps({ readonly: true })
expect(instance.updateEditConfig).toHaveBeenLastCalledWith({
isSilentMode: true,
})
await wrapper.setProps({ readonly: false })
expect(instance.updateEditConfig).toHaveBeenLastCalledWith({
isSilentMode: false,
textEdit: false,
adjustNodePosition: false,
})
expect(instance.keyboard.disable).toHaveBeenCalledOnce()
} finally {
wrapper.unmount()
}
})
it('creates independent nested default options for every instance', () => {
const first = flowProps.options.default()
const second = flowProps.options.default()
expect(first).not.toBe(second)
expect(first.keyboard).not.toBe(second.keyboard)
})

View File

@ -1,43 +0,0 @@
import { darkTheme, lightTheme } from 'naive-ui'
import {
themeStyleOverrides,
themeStyles,
} from '../../packages/ui/src/theme-presets'
import { contrast } from '../utils/color-contrast'
it.each(themeStyles)(
'%s keeps editable fields and primary buttons legible in both modes',
(style) => {
for (const mode of ['light', 'dark'] as const) {
const base = mode === 'light' ? lightTheme : darkTheme
const overrides = themeStyleOverrides[style][mode]
const common = { ...base.common, ...overrides.common }
const input = { ...base.Input.self!(common), ...overrides.Input }
const selection = {
...base.Select.peers!.InternalSelection.self!(common),
...overrides.InternalSelection,
}
const button = { ...base.Button.self!(common), ...overrides.Button }
for (const field of [input, selection]) {
expect(
contrast(field.placeholderColor, field.color, common.cardColor),
).toBeGreaterThanOrEqual(4.5)
expect(
contrast(field.border.replace(/^1px solid /, ''), common.cardColor),
).toBeGreaterThanOrEqual(3)
}
for (const [text, fill] of [
[button.textColorPrimary, button.colorPrimary],
[button.textColorHoverPrimary, button.colorHoverPrimary],
[button.textColorPressedPrimary, button.colorPressedPrimary],
[button.textColorFocusPrimary, button.colorFocusPrimary],
]) {
expect(contrast(text, fill, common.cardColor)).toBeGreaterThanOrEqual(
4.5,
)
}
}
},
)

View File

@ -1,5 +1,5 @@
import { mount } from '@vue/test-utils'
import { RModal } from '../../apps/admin/src/components/RModal/index'
import { RModal } from '../../src/components/RModal/index'
describe('RModal', () => {
it('should execute the onAfterEnter callback', () => {

View File

@ -1,14 +1,11 @@
import { RTablePro } from '@/components/RTablePro'
import { useColumnVisibility } from '@/components/RTablePro/src/columns'
import ColumnSettings from '@/components/RTablePro/src/components/C'
import { prefixCacheKey } from '@/utils/app/prefix-cache-key'
import { mount } from '@vue/test-utils'
import { NDataTable, NTree } from 'naive-ui'
import type { DataTableColumn } from 'naive-ui'
import { effectScope, nextTick, ref, shallowRef } from 'vue'
import {
getLeafColumns,
useColumnVisibility,
} from '../../packages/ui/src/RTablePro/src/columns'
import ColumnSettings from '../../packages/ui/src/RTablePro/src/components/ColumnSettings'
const name = { key: 'name', title: 'Name' }
const email = { key: 'email', title: 'Email' }
@ -23,28 +20,6 @@ afterEach(() => {
columns.value = [selection, group, region]
})
it('filters nested leaves and prunes empty groups while retaining unaffected branches', () => {
const scope = effectScope()
const nested = { key: 'outer', children: [group] }
const source = shallowRef<DataTableColumn[]>([nested, region])
try {
const state = scope.run(() => useColumnVisibility(source, ref()))!
state.setColumnVisible('email', false)
expect(
getLeafColumns(state.visibleColumns.value).map(({ key }) => key),
).toEqual(['name', 'region'])
expect(state.visibleColumns.value[1]).toBe(region)
state.setColumnVisible('name', false)
expect(state.visibleColumns.value).toEqual([region])
state.resetColumns()
expect(state.visibleColumns.value).toBe(source.value)
} finally {
scope.stop()
}
})
it('stores only hidden leaf keys, restores them on mount, and isolates separate keys', () => {
const scope = effectScope()
const second = effectScope()
@ -125,126 +100,6 @@ it('updates visibility without touching storage when no key is configured', () =
}
})
it.each([false, true])(
'pins and unpins every group descendant without mutating source definitions (controlled=%s)',
async (controlled) => {
const renderName = (row: { name: string }) => row.name
const nameColumn = {
...name,
width: 120,
resizable: true,
render: renderName,
}
const emailColumn = {
...email,
width: 180,
resizable: false,
fixed: 'right' as const,
}
const children = [nameColumn, emailColumn]
const nested = { key: 'inner', title: 'Details', children }
const grouped = { key: 'contact', title: 'Contact', children: [nested] }
const unaffected = { ...region, width: 140, fixed: 'right' as const }
const input: DataTableColumn[] = [grouped, unaffected]
for (const value of [
nameColumn,
emailColumn,
children,
nested,
grouped.children,
grouped,
unaffected,
input,
])
Object.freeze(value)
const update = vi.fn()
const wrapper = mount(RTablePro, {
props: {
columns: input,
data: [
{ id: 1, name: 'Alice', email: 'alice@example.test', region: 'West' },
],
scrollX: 440,
...(controlled ? { 'onUpdate:columns': update } : {}),
},
})
try {
const settings = wrapper.getComponent(ColumnSettings)
const table = wrapper.getComponent(NDataTable)
const patch = async (value: {
fixed?: 'left' | 'right'
resizable?: boolean
}) => {
settings.vm.$emit('patchColumn', 'contact', value)
if (controlled)
await wrapper.setProps({ columns: update.mock.lastCall![0] })
else await nextTick()
}
await patch({ resizable: true })
expect(table.props('columns')![0]).toMatchObject({
children: [
{
children: [
{ resizable: true },
{ resizable: false, fixed: 'right' },
],
},
],
})
for (const fixed of ['left', 'right', void 0] as const) {
await patch({ fixed })
const result = table.props('columns')!
const leaves = getLeafColumns(result)
expect(result[0].fixed).toBe(fixed)
expect('children' in result[0] && result[0].children[0].fixed).toBe(
fixed,
)
expect(leaves[0]).toMatchObject({
key: 'name',
width: 120,
resizable: true,
render: renderName,
})
expect(leaves[1]).toMatchObject({
key: 'email',
width: 180,
resizable: false,
})
expect(leaves[0].fixed).toBe(fixed)
expect(leaves[1].fixed).toBe(fixed)
expect(result[1]).toBe(unaffected)
for (const key of ['name', 'email']) {
const cell = wrapper.get(`tbody td[data-col-key="${key}"]`)
if (fixed)
expect(cell.classes()).toContain(`n-data-table-td--fixed-${fixed}`)
else
expect(
cell.classes().some((name) => name.includes('--fixed-')),
).toBe(false)
}
}
expect(nameColumn).not.toHaveProperty('fixed')
expect(emailColumn.fixed).toBe('right')
expect(grouped).not.toHaveProperty('fixed')
expect(nested).not.toHaveProperty('fixed')
expect(grouped.children[0]).toBe(nested)
expect(nested.children).toBe(children)
} finally {
wrapper.unmount()
}
},
)
it('provides the full settings with a frozen plain columns array and keeps adjustments when definitions change', async () => {
const input: DataTableColumn[] = [
selection,
@ -354,49 +209,3 @@ it('lets v-model own the full column definitions without removing hidden columns
wrapper.unmount()
}
})
it('offers keyboard-operable column ordering and resets layout without revealing hidden columns', async () => {
const wrapper = mount(RTablePro, {
props: {
columns: [selection, { ...name, width: 100 }, email, region],
columnStateKey: 'keyboard',
},
global: { stubs: { teleport: true } },
})
try {
const settings = wrapper.getComponent(ColumnSettings)
const native = wrapper.getComponent(NDataTable)
await settings.get('button').trigger('click')
const move = wrapper.get('button[aria-label="Move Email up"]')
expect(move.attributes('type')).toBe('button')
await move.trigger('click')
settings.vm.$emit('patchColumn', 'name', { fixed: 'left', resizable: true })
settings.vm.$emit('toggleColumn', 'region', false)
await nextTick()
expect(native.props('columns')).toEqual([
selection,
email,
{ ...name, width: 100, fixed: 'left', resizable: true },
])
const reset = wrapper
.findAll('button')
.find((button) => button.text() === 'Reset column layout')
expect(reset).toBeDefined()
await reset!.trigger('click')
expect(native.props('columns')).toEqual([
selection,
{ ...name, width: 100 },
email,
])
expect(JSON.parse(localStorage.getItem(cacheKey('keyboard'))!)).toEqual([
'region',
])
} finally {
wrapper.unmount()
}
})

View File

@ -1,9 +1,9 @@
import { RTablePro } from '@/components/RTablePro'
import type { TableProInst } from '@/components/RTablePro'
import { flushPromises, mount } from '@vue/test-utils'
import { buildTableCsv } from '@/components/RTablePro/src/csv'
import * as printing from '@/components/RTablePro/src/printing'
import { mount } from '@vue/test-utils'
import type { DataTableColumn } from 'naive-ui'
import { buildTableCsv } from '../../packages/ui/src/RTablePro/src/csv'
import * as printing from '../../packages/ui/src/RTablePro/src/printing'
afterEach(() => vi.restoreAllMocks())
@ -97,111 +97,3 @@ it('exports group children with correct CSV escaping and neutralizes formula tex
'"Name","Note","Score"\r\n"A, ""B""","\'=2+2","-2"\r\n"Array value","\'=2+2,text","-2"',
)
})
it('copies current form values into custom print content without copying credentials', () => {
const target = document.createElement('section')
target.innerHTML =
'<input value="default"><input type="checkbox"><textarea>old</textarea><select><option>A</option><option>B</option></select><input type="password" value="placeholder">'
target.querySelector('input')!.value = 'edited'
target.querySelector<HTMLInputElement>('[type="checkbox"]')!.checked = true
target.querySelector('textarea')!.value = 'new'
target.querySelector('select')!.value = 'B'
target.querySelector<HTMLInputElement>('[type="password"]')!.value = 'private'
const clone = printing.resolvePrintContent({ target }, () => null)!
expect(clone.querySelector('input')?.value).toBe('edited')
expect(
clone.querySelector<HTMLInputElement>('[type="checkbox"]')?.checked,
).toBe(true)
expect(clone.querySelector('textarea')?.value).toBe('new')
expect(clone.querySelector('select')?.value).toBe('B')
expect(
clone.querySelector<HTMLInputElement>('[type="password"]')?.value,
).toBe('')
expect(
target.querySelector<HTMLInputElement>('[type="password"]')?.value,
).toBe('private')
})
it('shares page styles with a custom print frame and removes it after printing', async () => {
const target = document.createElement('section')
const stylesheet = document.createElement('style')
target.className = 'print-fixture'
stylesheet.textContent = '.print-fixture { color: rebeccapurple; }'
document.head.append(stylesheet)
const append = document.body.append.bind(document.body)
vi.spyOn(document.body, 'append').mockImplementation((...nodes) => {
for (const node of nodes)
if (node instanceof HTMLIFrameElement) node.srcdoc = '<!doctype html>'
append(...nodes)
})
const printDocument = document.implementation.createHTMLDocument()
const printWindow = Object.assign(new EventTarget(), {
focus: vi.fn(),
print: vi.fn(() => {
expect(document.querySelector('iframe')).not.toBeNull()
expect(printDocument.head.textContent).toContain('rebeccapurple')
printWindow.dispatchEvent(new Event('afterprint'))
}),
})
vi.spyOn(HTMLIFrameElement.prototype, 'contentWindow', 'get').mockReturnValue(
printWindow as unknown as Window,
)
vi.spyOn(
HTMLIFrameElement.prototype,
'contentDocument',
'get',
).mockReturnValue(printDocument)
try {
expect(
await printing.printTableContent(target.cloneNode(true) as HTMLElement, {
target,
}),
).toBe(true)
expect(printWindow.print).toHaveBeenCalledOnce()
expect(document.querySelector('iframe')).toBeNull()
} finally {
stylesheet.remove()
document.querySelector('iframe')?.remove()
}
})
it('cancels a print still preparing when the request scope changes', async () => {
const print = vi.spyOn(printing, 'printTableContent').mockImplementation(
(_content, _options, signal) =>
new Promise((resolve) => {
signal?.addEventListener('abort', () => resolve(false), { once: true })
}),
)
const wrapper = mount(RTablePro, {
props: {
columns: [{ key: 'name', title: 'Name' }],
params: { account: 'a' },
request: async ({ account }) => ({
data: [{ id: 1, name: account }],
total: 1,
}),
},
})
try {
await flushPromises()
const table = wrapper.vm as unknown as TableProInst
const preview = table.print()
expect(print).toHaveBeenCalledOnce()
await wrapper.setProps({ params: { account: 'b' } })
expect(print.mock.calls[0][2]?.aborted).toBe(true)
expect(await preview).toBe(false)
} finally {
wrapper.unmount()
}
})

View File

@ -1,161 +0,0 @@
import { iconSprites } from '@ray-template/icons/manifest'
import { inlineTableSvgUses } from '../../packages/ui/src/RTablePro/src/image-svg'
const sprite =
'<svg xmlns="http://www.w3.org/2000/svg"><symbol id="icon-action/copy-image" viewBox="0 0 48 48" fill="none"><g id="shared-group"><path id="shared-path" d="M4 4h40v40H4z" stroke="currentColor" stroke-width="3" onload="throw 1" /></g></symbol></svg>'
const response = (source = sprite) =>
new Response(source, { headers: { 'Content-Type': 'image/svg+xml' } })
afterEach(() => {
document.querySelectorAll('[data-svg-test]').forEach((node) => node.remove())
vi.unstubAllGlobals()
})
it('inlines repeated registered sprites once, retaining viewport/color without copied IDs or source mutations', async () => {
const fetchAsset = vi.fn(async () => response())
vi.stubGlobal('fetch', fetchAsset)
const source = document.createElement('div')
source.setAttribute('data-svg-test', '')
source.innerHTML = `<svg style="color: red; width: 24px; height: 24px"><use href="${iconSprites.action}#icon-action/copy-image" width="24" height="24" /></svg><svg style="color: blue; width: 18px; height: 18px"><use href="${iconSprites.action}#icon-action/copy-image" width="18" height="18" /></svg>`
document.body.append(source)
const clone = source.cloneNode(true) as HTMLElement
document.body.append(clone)
const colors = Array.from(
clone.querySelectorAll('use'),
(use) => getComputedStyle(use).color,
)
await inlineTableSvgUses(clone, new AbortController().signal)
expect(fetchAsset).toHaveBeenCalledOnce()
expect(fetchAsset.mock.calls[0]).toEqual([
new URL(iconSprites.action, document.baseURI).href,
expect.objectContaining({
credentials: 'omit',
redirect: 'error',
mode: 'same-origin',
signal: expect.any(AbortSignal),
}),
])
expect(clone.querySelector('use, [id], [onload]')).toBeNull()
expect(clone.querySelectorAll('path')).toHaveLength(2)
const vectors = clone.querySelectorAll('svg svg')
expect(vectors[0].getAttribute('viewBox')).toBe('0 0 48 48')
expect(vectors[0].getAttribute('width')).toBe('24')
expect(vectors[1].getAttribute('width')).toBe('18')
expect(vectors[0].parentElement!.style.color).toBe(colors[0])
expect(vectors[1].parentElement!.style.color).toBe(colors[1])
expect(clone.querySelector('path')!.getAttribute('stroke')).toBe(
'currentColor',
)
expect(source.querySelectorAll('use')).toHaveLength(2)
expect(source.querySelector('path')).toBeNull()
})
it('resolves local symbols outside the captured region without a fetch', async () => {
const fetchAsset = vi.fn()
vi.stubGlobal('fetch', fetchAsset)
const definitions = document.createElement('div')
definitions.setAttribute('data-svg-test', '')
definitions.innerHTML =
'<svg><symbol id="local-capture-symbol" viewBox="0 0 16 16"><rect id="local-rect" width="16" height="16" fill="currentColor" /></symbol></svg>'
const clone = document.createElement('div')
clone.setAttribute('data-svg-test', '')
clone.innerHTML =
'<svg width="16" height="16"><use href="#local-capture-symbol" /></svg>'
document.body.append(definitions, clone)
await inlineTableSvgUses(clone, new AbortController().signal)
expect(fetchAsset).not.toHaveBeenCalled()
expect(clone.querySelector('rect')).not.toBeNull()
expect(clone.querySelector('use, [id]')).toBeNull()
expect(clone.querySelector('svg svg')!.getAttribute('viewBox')).toBe(
'0 0 16 16',
)
expect(document.getElementById('local-capture-symbol')).not.toBeNull()
})
it.each(['https://outside.example/sprite.svg', '/api/admin/private'])(
'rejects an unrelated source %s without fetching it',
async (url) => {
const fetchAsset = vi.fn()
vi.stubGlobal('fetch', fetchAsset)
const clone = document.createElement('div')
clone.innerHTML = `<svg><use href="${url}#icon" /></svg>`
await expect(
inlineTableSvgUses(clone, new AbortController().signal),
).rejects.toThrow('same-origin public assets')
expect(fetchAsset).not.toHaveBeenCalled()
},
)
it.each([
'<script>window.alert(1)</script>',
'<foreignObject><div xmlns="http://www.w3.org/1999/xhtml">Active HTML</div></foreignObject>',
'<image href="https://outside.example/image.png" />',
'<path fill="url(https://outside.example/paint.svg#paint)" d="M0 0h1" />',
'<path fill="var(--paint)" d="M0 0h1" />',
'<path style="fill: attr(data-paint)" d="M0 0h1" />',
'<path fill="u\\72l(https://outside.example/paint.svg#paint)" d="M0 0h1" />',
])(
'rejects non-static SVG content before inserting it into the snapshot',
async (content) => {
vi.stubGlobal(
'fetch',
vi.fn(async () =>
response(
`<svg xmlns="http://www.w3.org/2000/svg"><symbol id="icon">${content}</symbol></svg>`,
),
),
)
const clone = document.createElement('div')
clone.setAttribute('data-svg-test', '')
clone.innerHTML = '<svg><use href="/public/sprite.svg#icon" /></svg>'
document.body.append(clone)
await expect(
inlineTableSvgUses(clone, new AbortController().signal),
).rejects.toThrow()
expect(clone.querySelector('script, foreignObject, image, path')).toBeNull()
},
)
it('bounds streamed source size and forwards cancellation to sprite fetches', async () => {
const clone = document.createElement('div')
clone.innerHTML = '<svg><use href="/public/sprite.svg#icon" /></svg>'
vi.stubGlobal(
'fetch',
vi.fn(async () => response('x'.repeat(1024 * 1024 + 1))),
)
await expect(
inlineTableSvgUses(clone, new AbortController().signal),
).rejects.toThrow('too large')
const controller = new AbortController()
const fetchAsset = vi.fn(
(_url: string, options: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
options.signal!.addEventListener(
'abort',
() => reject(new DOMException('Cancelled', 'AbortError')),
{ once: true },
)
}),
)
vi.stubGlobal('fetch', fetchAsset)
const pending = inlineTableSvgUses(clone, controller.signal)
controller.abort()
await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
expect(fetchAsset.mock.calls[0][1].signal).toBe(controller.signal)
})

View File

@ -1,412 +0,0 @@
import { flushPromises, mount } from '@vue/test-utils'
import { h } from 'vue'
import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro'
import type {
TableProInst,
TableProResult,
} from '../../packages/ui/src/RTablePro'
import {
copyTableImage,
createTableImageSnapshot,
} from '../../packages/ui/src/RTablePro/src/image'
import { provideUiServices } from '../../packages/ui/src/services'
const renderer = vi.hoisted(() => ({
create: vi.fn(),
options: [] as Record<string, unknown>[],
nodes: [] as HTMLElement[],
}))
vi.mock('@ray-template/composables/useDomToImage', () => ({
useDomToImage: (node: HTMLElement, options: Record<string, unknown>) => {
renderer.nodes.push(node)
renderer.options.push(options)
return { create: renderer.create }
},
}))
class Item {
constructor(readonly data: Record<string, Promise<Blob>>) {}
}
const png = () => new Blob(['png'], { type: 'image/png' })
let write: ReturnType<typeof vi.fn<(items: Item[]) => Promise<void>>>
let originalClipboard: PropertyDescriptor | undefined
const columns = [{ key: 'name', title: 'Name' }]
const data = [{ id: 1, name: 'Ray' }]
const tickCapture = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
beforeEach(() => {
renderer.create.mockReset().mockResolvedValue(png())
renderer.options.length = 0
renderer.nodes.length = 0
write = vi.fn(async ([item]) => {
await item.data['image/png']
})
originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { write },
})
vi.stubGlobal('ClipboardItem', Item)
vi.stubGlobal('isSecureContext', true)
vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(640)
vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(240)
})
afterEach(() => {
document
.querySelectorAll('[data-r-table-image-snapshot]')
.forEach((node) => node.remove())
if (originalClipboard)
Object.defineProperty(navigator, 'clipboard', originalClipboard)
else Reflect.deleteProperty(navigator, 'clipboard')
vi.unstubAllGlobals()
vi.restoreAllMocks()
})
it('requests clipboard writing synchronously and supplies an eventual PNG without retaining its snapshot', async () => {
const target = document.createElement('div')
target.textContent = 'Current table'
document.body.append(target)
try {
const copying = copyTableImage(target, { pixelRatio: 1 })
expect(write).toHaveBeenCalledOnce()
expect(renderer.create).not.toHaveBeenCalled()
expect(write.mock.calls[0][0][0].data['image/png']).toBeInstanceOf(Promise)
await copying
expect(renderer.create).toHaveBeenCalledExactlyOnceWith('blob')
expect(renderer.options[0]).toMatchObject({
imageType: 'blob',
type: 'image/png',
pixelRatio: 1,
})
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
} finally {
target.remove()
}
})
it('preserves scroll viewport and input state in an inert clone without touching the live table', () => {
const target = document.createElement('div')
target.innerHTML =
'<div class="viewport"><div class="rows"><input type="checkbox"><input type="radio" name="snapshot-choice" checked autofocus><textarea>Initial</textarea></div></div>'
const viewport = target.querySelector<HTMLElement>('.viewport')!
viewport.scrollLeft = 80
viewport.scrollTop = 120
target.querySelector<HTMLInputElement>('input')!.checked = true
target.querySelector<HTMLTextAreaElement>('textarea')!.value = 'Current'
target.style.setProperty('--example-color', 'rgb(10, 20, 30)')
document.body.append(target)
const snapshot = createTableImageSnapshot(target)
try {
expect(snapshot.element.inert).toBe(true)
expect(snapshot.element.getAttribute('aria-hidden')).toBe('true')
expect(snapshot.element.style.width).toBe('640px')
expect(snapshot.element.style.height).toBe('240px')
expect(snapshot.element.style.getPropertyValue('--example-color')).toBe(
'rgb(10, 20, 30)',
)
expect(
snapshot.element.querySelector<HTMLElement>('.rows')!.style.transform,
).toContain('translate(-80px, -120px)')
expect(
snapshot.element.querySelector<HTMLInputElement>('input')!.defaultChecked,
).toBe(true)
expect(
snapshot.element.querySelector<HTMLTextAreaElement>('textarea')!.value,
).toBe('Current')
expect(viewport.scrollLeft).toBe(80)
expect(viewport.scrollTop).toBe(120)
expect(target.querySelector<HTMLElement>('.rows')!.style.transform).toBe('')
expect(
target.querySelector<HTMLInputElement>('[type="radio"]')!.checked,
).toBe(true)
expect(snapshot.element.querySelector('[name], [autofocus]')).toBeNull()
} finally {
snapshot.dispose()
target.remove()
}
})
it('removes active event attributes and scripts before connecting a snapshot', () => {
const target = document.createElement('div')
target.innerHTML =
'<span onclick="throw 1">Cell</span><img onload="throw 1" onerror="throw 1"><script type="application/json">{}</script>'
document.body.append(target)
const snapshot = createTableImageSnapshot(target)
try {
expect(
snapshot.element.querySelector('script, [onclick], [onload], [onerror]'),
).toBeNull()
expect(target.querySelector('[onclick]')).not.toBeNull()
expect(target.querySelector('script')).not.toBeNull()
} finally {
snapshot.dispose()
target.remove()
}
})
it.each(['iframe', 'object', 'embed', 'audio', 'video'])(
'rejects %s content before creating a connected clone',
(tag) => {
const target = document.createElement('div')
target.append(document.createElement(tag))
vi.spyOn(target, 'isConnected', 'get').mockReturnValue(true)
const clone = vi.spyOn(target, 'cloneNode')
try {
expect(() => createTableImageSnapshot(target)).toThrow('Embedded media')
expect(clone).not.toHaveBeenCalled()
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
} finally {
target.remove()
}
},
)
it('aborts a pending sprite request on unmount without rasterizing or leaving a snapshot', async () => {
const fetchAsset = vi.fn(
(_url: string, options: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
options.signal!.addEventListener(
'abort',
() => reject(new DOMException('Cancelled', 'AbortError')),
{ once: true },
)
}),
)
vi.stubGlobal('fetch', fetchAsset)
const wrapper = mount(RTablePro, {
attachTo: document.body,
props: {
columns: [
{
key: 'icon',
title: 'Icon',
render: () =>
h('svg', [h('use', { href: '/public/sprite.svg#icon' })]),
},
],
data,
},
})
const copying = (wrapper.vm as unknown as TableProInst).copyImage()
await tickCapture()
expect(fetchAsset).toHaveBeenCalledOnce()
wrapper.unmount()
expect(await copying).toBe(false)
expect(fetchAsset.mock.calls[0][1].signal!.aborted).toBe(true)
expect(renderer.create).not.toHaveBeenCalled()
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
})
it('copies only the native table region and supports configured options and hidden actions through the hook', async () => {
const [register, actions] = useTablePro()
const wrapper = mount(RTablePro, {
attachTo: document.body,
props: {
columns,
data,
title: 'Excluded heading',
onRegister: register,
search: [{ key: 'name', label: 'Excluded search' }],
copyImageOptions: { pixelRatio: 1, backgroundColor: '#ffffff' },
},
slots: {
toolbar: 'Excluded toolbar',
tableFooter: 'Excluded footer',
tableAction: 'Excluded action',
},
})
try {
expect(wrapper.find('[aria-label="Copy table image"]').exists()).toBe(true)
expect(await actions.copyImage({ pixelRatio: 2 })).toBe(true)
const target = renderer.nodes[0]
expect(target.classList.contains('n-data-table')).toBe(true)
expect(target.textContent).toContain('Ray')
expect(target.querySelector('th')).not.toBeNull()
expect(target.querySelector('.n-data-table__pagination')).not.toBeNull()
expect(target.textContent).not.toMatch(/Excluded/)
expect(renderer.options[0]).toMatchObject({
pixelRatio: 2,
backgroundColor: '#ffffff',
})
expect(wrapper.get('[role="status"]').text()).toBe('Table image copied')
await wrapper.setProps({ showCopyImage: false })
expect(wrapper.find('[aria-label="Copy table image"]').exists()).toBe(false)
expect(await actions.copyImage()).toBe(true)
} finally {
wrapper.unmount()
}
})
it('reports unavailable and denied clipboard access without rendering or claiming success', async () => {
const wrapper = mount(RTablePro, {
attachTo: document.body,
props: { columns, data },
})
const instance = wrapper.vm as unknown as TableProInst
try {
vi.stubGlobal('ClipboardItem', void 0)
expect(await instance.copyImage()).toBe(false)
expect(wrapper.get('[role="alert"]').text()).toContain('cannot copy PNG')
expect(write).not.toHaveBeenCalled()
vi.stubGlobal('ClipboardItem', Item)
write.mockRejectedValueOnce(new DOMException('Denied', 'NotAllowedError'))
expect(await instance.copyImage()).toBe(false)
expect(wrapper.get('[role="alert"]').text()).toContain('access was denied')
expect(renderer.create).not.toHaveBeenCalled()
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
} finally {
wrapper.unmount()
}
})
it.each(['reject', 'empty'] as const)(
'cleans up a %s render result and allows a later retry',
async (failure) => {
if (failure === 'reject')
renderer.create.mockRejectedValueOnce(new Error('Image failed'))
else renderer.create.mockResolvedValueOnce(null)
const wrapper = mount(RTablePro, {
attachTo: document.body,
props: { columns, data },
})
const instance = wrapper.vm as unknown as TableProInst
try {
expect(await instance.copyImage()).toBe(false)
expect(wrapper.get('[role="alert"]').text()).toContain("Couldn't copy")
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
expect(await instance.copyImage()).toBe(true)
} finally {
wrapper.unmount()
}
},
)
it('deduplicates an in-flight capture and cancels unfinished clipboard data on unmount', async () => {
const pending = Promise.withResolvers<Blob>()
renderer.create.mockReturnValueOnce(pending.promise)
const success = vi.fn()
const error = vi.fn()
const wrapper = mount(
{
setup() {
provideUiServices({ reportSuccess: success, reportError: error })
return () => h(RTablePro, { columns, data })
},
},
{ attachTo: document.body },
)
const instance = wrapper.getComponent(RTablePro).vm as unknown as TableProInst
const copying = instance.copyImage()
await tickCapture()
expect(renderer.create).toHaveBeenCalledOnce()
expect(await instance.copyImage()).toBe(false)
expect(write).toHaveBeenCalledOnce()
wrapper.unmount()
expect(await copying).toBe(false)
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
pending.resolve(png())
await flushPromises()
expect(success).not.toHaveBeenCalled()
expect(error).not.toHaveBeenCalled()
})
it('does not capture unconfirmed remote results', async () => {
const pending = Promise.withResolvers<TableProResult>()
const wrapper = mount(RTablePro, {
attachTo: document.body,
props: { columns, request: () => pending.promise },
})
try {
expect(await (wrapper.vm as unknown as TableProInst).copyImage()).toBe(
false,
)
expect(write).not.toHaveBeenCalled()
pending.resolve({ data, total: 1 })
await flushPromises()
expect(await (wrapper.vm as unknown as TableProInst).copyImage()).toBe(true)
} finally {
wrapper.unmount()
}
})
it('uses bilingual host feedback and preserves a successful result if the host notifier fails', async () => {
const success = vi.fn(() => {
throw new Error('Notifier unavailable')
})
const wrapper = mount(
{
setup() {
provideUiServices({ locale: () => 'zh-CN', reportSuccess: success })
return () => h(RTablePro, { columns, data })
},
},
{ attachTo: document.body },
)
try {
const instance = wrapper.getComponent(RTablePro)
.vm as unknown as TableProInst
expect(await instance.copyImage()).toBe(true)
expect(success).toHaveBeenCalledExactlyOnceWith('表格图片已复制')
expect(wrapper.get('[role="status"]').text()).toBe('表格图片已复制')
} finally {
wrapper.unmount()
}
})
it('cancels pending capture when the displayed dataset changes', async () => {
const pending = Promise.withResolvers<Blob>()
renderer.create.mockReturnValueOnce(pending.promise)
const wrapper = mount(RTablePro, {
attachTo: document.body,
props: { columns, data },
})
const copying = (wrapper.vm as unknown as TableProInst).copyImage()
try {
await tickCapture()
expect(
document.querySelector('[data-r-table-image-snapshot]'),
).not.toBeNull()
await wrapper.setProps({ data: [{ id: 2, name: 'New query' }] })
expect(await copying).toBe(false)
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
pending.resolve(png())
await flushPromises()
expect(wrapper.find('[role="status"]').exists()).toBe(false)
} finally {
wrapper.unmount()
}
})

View File

@ -1,42 +0,0 @@
import { splitPaginationOptions } from '../../packages/ui/src/RTablePro/src/pagination'
import type { TableProPagination } from '../../packages/ui/src/RTablePro/src/types'
it('uses only current update handlers and removes them from native view props', () => {
const page = vi.fn()
const modelPage = vi.fn()
const size = vi.fn()
const modelSize = vi.fn()
const options: TableProPagination = {
page: 2,
pageSize: 20,
showSizePicker: true,
onUpdatePage: [page],
'onUpdate:page': modelPage,
onUpdatePageSize: size,
'onUpdate:pageSize': [modelSize],
}
const pager = splitPaginationOptions(options)
pager.notifyPage(3)
pager.notifyPageSize(50)
expect(page).toHaveBeenCalledExactlyOnceWith(3)
expect(modelPage).toHaveBeenCalledExactlyOnceWith(3)
expect(size).toHaveBeenCalledExactlyOnceWith(50)
expect(modelSize).toHaveBeenCalledExactlyOnceWith(50)
expect(pager.view).toEqual({ page: 2, pageSize: 20, showSizePicker: true })
})
it('drops obsolete callback keys from untyped runtime configuration', () => {
const onChange = vi.fn()
const onPageSizeChange = vi.fn()
const legacy = { page: 1, onChange, onPageSizeChange }
const pager = splitPaginationOptions(legacy)
pager.notifyPage(2)
pager.notifyPageSize(20)
expect(pager.view).toEqual({ page: 1 })
expect(onChange).not.toHaveBeenCalled()
expect(onPageSizeChange).not.toHaveBeenCalled()
expectTypeOf<TableProPagination>().not.toHaveProperty('onChange')
expectTypeOf<TableProPagination>().not.toHaveProperty('onPageSizeChange')
})

View File

@ -1,936 +0,0 @@
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
import type {
TableProParams,
TableProSearchActions,
TableProSearchOptionContext,
TableProSearchOptions,
} from '@ray-template/ui/table-pro'
import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDatePicker, NGrid, NSelect } from 'naive-ui'
import { defineComponent, h, nextTick, shallowRef } from 'vue'
const columns = [{ key: 'name', title: 'Name' }]
const statusOptions = [
{ label: 'Open', value: 'open' },
{ 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 () => {
const fields: TableProSearchOptions['fields'] = [
{ key: 'created', type: 'dateRange', label: 'Created' },
{ key: 'at', type: 'time', label: 'Time' },
{ key: 'group', type: 'cascader', label: 'Group' },
{ key: 'team', type: 'treeSelect', label: 'Team' },
]
const wrapper = mount(RTablePro, { props: { columns, search: { fields } } })
try {
await nextTick()
const [range, time, ...selections] = wrapper.findAll('.n-form-item')
const endpoints = range.findAll('input')
expect(endpoints.map((input) => input.attributes('aria-label'))).toEqual([
'Created start',
'Created end',
])
expect(range.get('label').attributes('for')).toBe(endpoints[0].element.id)
expect(time.get('input').attributes('aria-labelledby')).toBe(
time.get('label').element.id,
)
for (const field of selections)
expect(field.get('[tabindex="0"]').attributes('aria-labelledby')).toBe(
field.get('label').element.id,
)
} finally {
wrapper.unmount()
}
})
it('matches text, multiple values, dates, zero and false before local pagination', async () => {
const [register, actions] = useTablePro()
const data = [
{
id: 1,
name: 'Other',
status: 'open',
day: '2026-11-02',
amount: 0,
active: false,
},
{
id: 2,
name: 'Notebook',
status: 'closed',
day: '2026-11-04',
amount: 0,
active: false,
},
{
id: 3,
name: 'Notebook XL',
status: 'open',
day: '2026-11-05',
amount: 0,
active: false,
},
{
id: 4,
name: 'Notebook Pro',
status: 'open',
day: '2026-11-03',
amount: 0,
active: true,
},
]
const search = {
fields: [
{ key: 'name', label: 'Name', type: 'text' },
{
key: 'status',
label: 'Status',
type: 'select',
multiple: true,
options: statusOptions,
},
{ key: 'day', label: 'Created', type: 'dateRange' },
{ key: 'amount', label: 'Amount', type: 'number' },
{ key: 'active', label: 'Active', type: 'boolean' },
],
} satisfies TableProSearchOptions
const wrapper = mount(RTablePro, {
props: {
columns,
data,
search,
pageSize: 1,
onRegister: register,
tool: false,
},
})
try {
await actions.setPage(2)
actions.setSearchValues({
name: ' NOTE ',
status: ['open', 'closed'],
day: ['2026-11-02', '2026-11-04'],
amount: 0,
active: false,
})
await nextTick()
expect(wrapper.getComponent(NDataTable).props('data')).toEqual(data)
expect(wrapper.getComponent(NDatePicker).props('formattedValue')).toEqual([
'2026-11-02',
'2026-11-04',
])
expect(await actions.submitSearch()).toBe(true)
await nextTick()
expect(actions.getCurrentPageData()).toEqual([data[1]])
expect(actions.getSearchValues('applied')).toMatchObject({
name: 'NOTE',
amount: 0,
active: false,
})
expect(await actions.resetSearch()).toBe(true)
await nextTick()
expect(actions.getCurrentPageData()).toEqual([data[0]])
} finally {
wrapper.unmount()
}
})
it('serializes remote search once per submit and reuses the applied snapshot when paging', async () => {
const [register, actions] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => ({
data: [],
total: 80,
}))
const search = {
initialValues: { status: ['open'] },
fields: [
{
key: 'status',
label: 'Status',
type: 'select',
multiple: true,
options: statusOptions,
},
{
key: 'createdAt',
label: 'Created',
type: 'dateRange',
transform: ([from, to]) => ({ from, to, page: 99, pageSize: 99 }),
},
{ key: 'name', label: 'Name', type: 'text' },
],
} satisfies TableProSearchOptions
const wrapper = mount(RTablePro, {
props: {
columns,
search,
request,
params: { status: 'external', scope: 'orders', page: 200 },
onRegister: register,
tool: false,
},
})
try {
const initial = { status: ['open'], scope: 'orders', page: 1, pageSize: 10 }
expect(request.mock.lastCall?.[0]).toEqual(initial)
await actions.setPage(3)
const status = ['closed']
actions.setSearchValues({
status,
createdAt: ['2026-11-01', '2026-11-04'],
name: ' ',
})
status.push('open')
expect(request).toHaveBeenCalledTimes(2)
await wrapper.get('form').trigger('submit')
await flushPromises()
const applied = {
status: ['closed'],
from: '2026-11-01',
to: '2026-11-04',
scope: 'orders',
page: 1,
pageSize: 10,
}
expect(request.mock.lastCall?.[0]).toEqual(applied)
expect(wrapper.emitted('search')).toEqual([
[
{
reason: 'submit',
values: {
status: ['closed'],
createdAt: ['2026-11-01', '2026-11-04'],
},
params: { status: ['closed'], from: '2026-11-01', to: '2026-11-04' },
},
],
])
actions.setSearchValues({ status: [] })
await actions.setPage(2)
await actions.reload()
expect(request.mock.calls.slice(-2).map(([params]) => params)).toEqual([
{ ...applied, page: 2 },
{ ...applied, page: 2 },
])
expect(await actions.resetSearch()).toBe(true)
expect(request.mock.lastCall?.[0]).toEqual(initial)
expect(request).toHaveBeenCalledTimes(6)
} finally {
wrapper.unmount()
}
})
it('expands a collapsed field when validation rejects and preserves the last query', async () => {
const [register, actions] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => ({
data: [],
total: 0,
}))
const search: TableProSearchOptions = {
defaultCollapsed: true,
fields: [
{
key: 'status',
label: 'Status',
type: 'select',
options: statusOptions,
},
{
key: 'name',
label: 'Name',
type: 'text',
rules: { required: true, message: 'Enter a name' },
},
],
}
const wrapper = mount(RTablePro, {
props: { columns, search, request, onRegister: register, tool: false },
})
try {
expect(
wrapper.get('button[aria-expanded]').attributes('aria-expanded'),
).toBe('false')
actions.setSearchValues({ name: ' ' })
expect(await actions.submitSearch()).toBe(false)
expect(
wrapper.get('button[aria-expanded]').attributes('aria-expanded'),
).toBe('true')
expect(wrapper.text()).toContain('Enter a name')
expect(request).toHaveBeenCalledTimes(1)
actions.setSearchValues({ name: ' Ray ' })
expect(await actions.submitSearch()).toBe(true)
expect(request.mock.lastCall?.[0]).toEqual({
name: 'Ray',
page: 1,
pageSize: 10,
})
} finally {
wrapper.unmount()
}
})
it('keeps legacy single-select exact matching and lets filters own submission', async () => {
const [register, actions] = useTablePro()
const data = [
{ id: 1, name: 'Original', status: 'open' },
{ id: 2, name: 'Reopened', status: 'reopened' },
]
const props = {
columns,
data,
search: [{ key: 'status', label: 'Status', options: statusOptions }],
onRegister: register,
tool: false,
}
const legacy = mount(RTablePro, { props })
try {
expect(legacy.getComponent(NSelect).props('multiple')).toBeFalsy()
actions.setSearchValues({ status: 'open' })
await legacy.get('form').trigger('submit')
expect(actions.getCurrentPageData()).toEqual([data[0]])
} finally {
legacy.unmount()
}
const custom = mount(RTablePro, {
props,
slots: {
filters: ({
submit,
}: {
submit: (values: Record<string, string | number>) => Promise<void>
}) =>
h(
'button',
{ onClick: () => void submit({ status: 'open' }) },
'Apply',
),
},
})
try {
expect(custom.find('form').exists()).toBe(false)
await custom.get('button').trigger('click')
expect(actions.getCurrentPageData()).toEqual([data[0]])
} finally {
custom.unmount()
}
})
it('delegates manual remote search to the caller and supports custom actions', async () => {
const data = [{ id: 1, name: 'Original' }]
const onSearch = vi.fn()
const search: TableProSearchOptions = {
fields: [{ key: 'name', label: 'Name', type: 'text' }],
renderActions: ({ submit }: TableProSearchActions) =>
h(
'button',
{ type: 'button', onClick: () => void submit() },
'Apply filters',
),
}
const wrapper = mount(RTablePro, {
props: { columns, data, remote: true, search, onSearch, tool: false },
})
try {
await wrapper.get('input').setValue('Different')
await wrapper.get('button').trigger('click')
expect(onSearch).toHaveBeenCalledWith({
reason: 'submit',
values: { name: 'Different' },
params: { name: 'Different' },
})
expect(wrapper.getComponent(NDataTable).props('data')).toEqual(data)
} finally {
wrapper.unmount()
}
})
it('uses explicitly searchable leaf columns and treats explicit fields as authoritative', async () => {
const [register, actions] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => ({
data: [],
total: 10,
}))
const wrapper = mount(RTablePro, {
props: {
columns: [
{ type: 'selection' },
{
key: 'group',
title: 'Group',
search: true,
children: [
{ key: 'name', title: 'Name', search: true },
{
key: 'created',
title: 'Created',
search: {
type: 'dateRange',
transform: ([from, to]) => ({ from, to }),
},
},
],
},
{ key: 'excluded', title: 'Excluded', search: false },
],
search: {},
request,
onRegister: register,
tool: false,
},
})
try {
expect(wrapper.get('form').text()).toContain('Name')
expect(wrapper.get('form').text()).toContain('Created')
expect(wrapper.get('form').text()).not.toMatch(/Group|Excluded/)
actions.setSearchValues({
name: 'Ray',
created: ['2026-11-01', '2026-11-04'],
})
await actions.submitSearch()
expect(request.mock.lastCall?.[0]).toEqual({
name: 'Ray',
from: '2026-11-01',
to: '2026-11-04',
page: 1,
pageSize: 10,
})
await wrapper.setProps({ search: { fields: [] } })
expect(wrapper.find('form').exists()).toBe(false)
expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 })
} finally {
wrapper.unmount()
}
})
it('clears a dependent draft, cancels obsolete options and keeps table requests independent', async () => {
const [register, actions] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => ({
data: [],
total: 40,
}))
const north = Promise.withResolvers<{ label: string; value: string }[]>()
const south = Promise.withResolvers<{ label: string; value: string }[]>()
const loadOptions = vi.fn(({ values }: TableProSearchOptionContext) =>
values.org === 'north' ? north.promise : south.promise,
)
const search: TableProSearchOptions = {
initialValues: { org: 'north', owner: 'n1' },
fields: [
{
type: 'select',
key: 'org',
label: 'Organization',
options: [
{ label: 'North', value: 'north' },
{ label: 'South', value: 'south' },
],
},
{
type: 'select',
key: 'owner',
label: 'Owner',
dependsOn: ['org'],
visible: ({ org }) => org != null,
loadOptions,
},
],
}
const wrapper = mount(RTablePro, {
props: { columns, search, request, onRegister: register, tool: false },
})
try {
const selects = () => wrapper.get('form').findAllComponents(NSelect)
const spinner = 'svg.n-base-loading__icon'
expect(loadOptions).toHaveBeenCalledTimes(1)
expect(selects()[0].find(spinner).exists()).toBe(false)
expect(selects()[1].find(spinner).exists()).toBe(true)
actions.setSearchValues({ org: 'south' })
await nextTick()
expect(actions.getSearchValues().owner).toBeNull()
expect(actions.getSearchValues('applied').owner).toBe('n1')
expect(loadOptions).toHaveBeenCalledTimes(2)
expect(loadOptions.mock.calls[0][0].signal.aborted).toBe(true)
south.resolve([{ label: 'South Owner', value: 's1' }])
await flushPromises()
north.resolve([{ label: 'North Owner', value: 'n1' }])
await flushPromises()
expect(selects()[1].props('options')).toEqual([
{ label: 'South Owner', value: 's1' },
])
expect(selects()[1].find(spinner).exists()).toBe(false)
expect(request).toHaveBeenCalledTimes(1)
actions.setSearchValues({ owner: 's1' })
await actions.submitSearch()
expect(request.mock.lastCall?.[0]).toMatchObject({
org: 'south',
owner: 's1',
})
actions.setSearchValues({ org: null, owner: 's1' })
await actions.submitSearch()
expect(wrapper.get('form').findAllComponents(NSelect)).toHaveLength(1)
expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 })
} finally {
wrapper.unmount()
}
})
it('debounces option keywords and retries failed options without querying the table', async () => {
vi.useFakeTimers()
const request = vi.fn(async () => ({ data: [], total: 0 }))
const loadOptions = vi
.fn(async ({ keyword }: TableProSearchOptionContext) => [
{ label: keyword, value: keyword },
])
.mockRejectedValueOnce(new Error('Unavailable'))
const wrapper = mount(RTablePro, {
props: {
columns,
request,
search: {
fields: [{ type: 'select', key: 'owner', label: 'Owner', loadOptions }],
},
tool: false,
},
})
try {
await vi.advanceTimersByTimeAsync(0)
expect(wrapper.get('[role="status"]').text()).toContain(
"Couldn't load options",
)
const retry = wrapper
.findAll('button')
.find((button) => button.text() === 'Retry')
await retry?.trigger('click')
expect(loadOptions).toHaveBeenCalledTimes(2)
const searchOptions = wrapper.getComponent(NSelect).props('onSearch') as (
value: string,
) => void
searchOptions('r')
await nextTick()
searchOptions('ray')
await nextTick()
await vi.advanceTimersByTimeAsync(249)
expect(loadOptions).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(1)
expect(loadOptions.mock.lastCall?.[0].keyword).toBe('ray')
expect(wrapper.getComponent(NSelect).props('options')).toEqual([
{ label: 'ray', value: 'ray' },
])
expect(request).toHaveBeenCalledTimes(1)
} finally {
wrapper.unmount()
vi.useRealTimers()
}
})
it('debounces table edits and cancels scheduled submits on reset or switching to manual', async () => {
vi.useFakeTimers()
const [register, actions] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => ({
data: [],
total: 0,
}))
const search: TableProSearchOptions = {
submitMode: 'change',
debounce: 50,
fields: [{ type: 'text', key: 'name', label: 'Name' }],
}
const wrapper = mount(RTablePro, {
props: { columns, request, search, onRegister: register, tool: false },
})
try {
actions.setSearchValues({ name: 'R' })
await vi.advanceTimersByTimeAsync(40)
actions.setSearchValues({ name: 'Ray' })
await vi.advanceTimersByTimeAsync(49)
expect(request).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1)
expect(request.mock.lastCall?.[0]).toEqual({
name: 'Ray',
page: 1,
pageSize: 10,
})
actions.setSearchValues({ name: 'Ray' })
await vi.advanceTimersByTimeAsync(50)
expect(request).toHaveBeenCalledTimes(2)
actions.setSearchValues({ name: 'Old' })
await actions.resetSearch()
await vi.advanceTimersByTimeAsync(50)
expect(request).toHaveBeenCalledTimes(3)
expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 })
actions.setSearchValues({ name: 'Manual draft' })
await wrapper.setProps({ search: { ...search, submitMode: 'manual' } })
await vi.advanceTimersByTimeAsync(50)
expect(request).toHaveBeenCalledTimes(3)
expect(actions.getSearchValues().name).toBe('Manual draft')
expect(actions.getSearchValues('applied')).toEqual({})
} finally {
wrapper.unmount()
vi.useRealTimers()
}
})
it('ignores asynchronous validation that finishes after a reset', async () => {
const [register, actions] = useTablePro()
const request = vi.fn(async () => ({ data: [], total: 0 }))
const validation = Promise.withResolvers<void>()
const validator = vi.fn(() => validation.promise)
const search: TableProSearchOptions = {
fields: [
{
type: 'text',
key: 'name',
label: 'Name',
rules: { validator },
},
],
}
const wrapper = mount(RTablePro, {
props: { columns, request, search, onRegister: register, tool: false },
})
try {
actions.setSearchValues({ name: 'Old' })
const submitting = actions.submitSearch()
await flushPromises()
expect(validator).toHaveBeenCalledOnce()
await actions.resetSearch()
validation.reject(new Error('Obsolete validation'))
expect(await submitting).toBe(false)
expect(wrapper.text()).not.toContain('Obsolete validation')
expect(request).toHaveBeenCalledTimes(2)
} finally {
wrapper.unmount()
}
})
it('does not reload when rendering a new pagination object with the same paging state', async () => {
const [register, actions] = useTablePro()
const lastQuery = shallowRef<TableProParams>()
const request = vi.fn(async (params: TableProParams) => {
lastQuery.value = params
return { data: [], total: 30 }
})
const search: TableProSearchOptions = {
fields: [{ type: 'text', key: 'name', label: 'Name' }],
}
const wrapper = mount(
defineComponent({
setup: () => () =>
h('section', [
h(RTablePro, {
columns,
request,
search,
pagination: { pageSizes: [10, 20] },
onRegister: register,
tool: false,
}),
h('pre', JSON.stringify(lastQuery.value)),
]),
}),
)
try {
await flushPromises()
expect(request).toHaveBeenCalledTimes(1)
actions.setSearchValues({ name: 'Ray' })
await actions.submitSearch()
await flushPromises()
expect(request).toHaveBeenCalledTimes(2)
expect(wrapper.get('pre').text()).toBe(
'{"name":"Ray","page":1,"pageSize":10}',
)
} finally {
wrapper.unmount()
}
})
it('notifies the owner when search, reset, and instance methods change controlled paging', async () => {
const [register, table] = useTablePro()
const pager = { page: 2, pageSize: 1 }
const pagination = () => ({
...pager,
'onUpdate:page': updatePage,
'onUpdate:pageSize': updatePageSize,
})
const updatePage = vi.fn((page: number) => {
pager.page = page
void wrapper.setProps({ pagination: pagination() })
})
const updatePageSize = vi.fn((pageSize: number) => {
pager.pageSize = pageSize
void wrapper.setProps({ pagination: pagination() })
})
const search: TableProSearchOptions = {
fields: [{ type: 'text', key: 'name', label: 'Name' }],
}
const data = [
{ id: 1, name: 'Ray' },
{ id: 2, name: 'Ray 2' },
{ id: 3, name: 'Other' },
]
const wrapper = mount(RTablePro, {
props: {
columns,
data,
search,
tool: false,
onRegister: register,
pagination: pagination(),
},
})
try {
table.setSearchValues({ name: 'Ray' })
expect(await table.submitSearch()).toBe(true)
expect(table.getCurrentPageData()).toEqual([data[0]])
await table.setPage(2)
expect(table.getCurrentPageData()).toEqual([data[1]])
await table.setPageSize(2)
expect(table.getCurrentPageData()).toEqual(data.slice(0, 2))
await table.setPage(2)
await table.resetSearch()
expect(updatePage.mock.calls.flat()).toEqual([1, 2, 1, 2, 1])
expect(updatePageSize).toHaveBeenCalledExactlyOnceWith(2)
} finally {
wrapper.unmount()
}
})
it('rebuilds a local search when a compatible field changes its matcher', async () => {
const makeSearch = (matches: () => boolean): TableProSearchOptions => ({
fields: [{ type: 'text', key: 'name', label: 'Name', matches }],
initialValues: { name: 'Ray' },
})
const data = [{ id: 1, name: 'Ray' }]
const [register, table] = useTablePro()
const wrapper = mount(RTablePro, {
props: {
columns,
data,
search: makeSearch(() => true),
tool: false,
onRegister: register,
},
})
try {
expect(table.getCurrentPageData()).toEqual(data)
await wrapper.setProps({ search: makeSearch(() => false) })
expect(table.getSearchValues('applied')).toEqual({ name: 'Ray' })
expect(table.getCurrentPageData()).toEqual([])
} finally {
wrapper.unmount()
}
})
it('reports visibility and row callback errors while preserving the last applied local query', async () => {
const visibility = new Error('Visibility failed')
const matcher = new Error('Matcher failed')
const search: TableProSearchOptions = {
fields: [
{
type: 'text',
key: 'name',
label: 'Name',
visible: (values) => {
if (values.name === 'hidden') throw visibility
return true
},
matches: (cell, value) => {
if (value === 'error') throw matcher
return cell === value
},
},
],
initialValues: { name: 'Ray' },
}
const data = [
{ id: 1, name: 'Ray' },
{ id: 2, name: 'Other' },
]
const [register, table] = useTablePro()
const wrapper = mount(RTablePro, {
props: { columns, data, search, tool: false, onRegister: register },
})
try {
for (const value of ['hidden', 'error']) {
table.setSearchValues({ name: value })
expect(await table.submitSearch()).toBe(false)
await nextTick()
expect(table.getCurrentPageData()).toEqual([data[0]])
expect(table.getSearchValues('applied')).toEqual({ name: 'Ray' })
expect(wrapper.get('[role="alert"]').text()).toContain("Couldn't prepare")
}
expect(wrapper.emitted('search-error')).toEqual([[visibility], [matcher]])
table.setSearchValues({ name: 'Other' })
expect(await table.submitSearch()).toBe(true)
await nextTick()
expect(table.getCurrentPageData()).toEqual([data[1]])
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
} finally {
wrapper.unmount()
}
})
it('reads nested column paths and preserves an explicit search value reader', async () => {
const data = [
{ id: 1, customer: { name: 'Ray' }, nickname: 'Alias' },
{ id: 2, customer: { name: 'Another' }, nickname: 'Ray' },
]
const [register, table] = useTablePro()
const search: TableProSearchOptions = {
fields: [
{ type: 'text', key: 'customer.name', label: 'Customer' },
{
type: 'text',
key: 'alias',
label: 'Alias',
getValue: (row) => row.nickname,
},
],
}
const wrapper = mount(RTablePro, {
props: {
columns: [{ key: 'customer.name', title: 'Customer' }],
data,
search,
tool: false,
onRegister: register,
},
})
try {
table.setSearchValues({ 'customer.name': 'ray', alias: 'alias' })
expect(await table.submitSearch()).toBe(true)
await nextTick()
expect(table.getCurrentPageData()).toEqual([data[0]])
} finally {
wrapper.unmount()
}
})

View File

@ -1,301 +0,0 @@
import { DOMWrapper, flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDropdown } from 'naive-ui'
import type { DropdownOption } from 'naive-ui'
import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro'
import type { TableProRequest } from '../../packages/ui/src/RTablePro'
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
import * as image from '../../packages/ui/src/RTablePro/src/image'
import * as printing from '../../packages/ui/src/RTablePro/src/printing'
const columns = [{ key: 'name', title: 'Name' }]
const data = [{ id: 1, name: 'Ray' }]
afterEach(() => vi.restoreAllMocks())
it.each([void 0, 'small', 'medium', 'large'] as const)(
'checks the effective density before any interaction when size is %s',
(size) => {
const wrapper = mount(RTablePro, { props: { columns, data, size } })
try {
const density = wrapper
.getComponent(NDropdown)
.props('options')
?.find((option) => option.key === 'density') as DropdownOption
const choices = density.children as DropdownOption[]
const expected = size ?? 'medium'
expect(wrapper.getComponent(NDataTable).props('size')).toBe(expected)
expect(
choices
.filter((option) => option.props?.['aria-checked'])
.map((option) => option.key),
).toEqual([`density:${expected}`])
} finally {
wrapper.unmount()
}
},
)
it('hides print by default and groups secondary actions under one menu', async () => {
const wrapper = mount(RTablePro, { props: { columns, data } })
try {
const menu = wrapper.getComponent(NDropdown)
const keys = menu.props('options')?.map((option) => option.key)
expect(keys).toContain('csv')
expect(keys).toContain('density')
expect(keys).not.toContain('print')
expect(wrapper.find('[aria-label="Print table"]').exists()).toBe(false)
expect(
wrapper.get('[aria-label="More actions"]').attributes('aria-haspopup'),
).toBe('menu')
await wrapper.get('[aria-label="More actions"]').trigger('click')
await flushPromises()
expect(document.body.textContent).not.toContain('Print table')
} finally {
wrapper.unmount()
}
})
it('puts image copying in the named menu on narrow panels without pagination', async () => {
let resize: ((width: number) => void) | undefined
vi.stubGlobal(
'ResizeObserver',
class {
constructor(private readonly callback: ResizeObserverCallback) {}
observe(target: Element) {
if (target.matches('.r-table'))
resize = (width) =>
this.callback(
[
{
target,
contentRect: new DOMRect(0, 0, width, 200),
} as ResizeObserverEntry,
],
this,
)
}
disconnect() {}
unobserve() {}
},
)
const wrapper = mount(RTablePro, {
props: { columns, data, pagination: false },
})
try {
await flushPromises()
const menu = wrapper.getComponent(NDropdown)
const copyOption = () =>
menu.props('options')?.find(({ key }) => key === 'copy-image')
expect(resize).toBeTypeOf('function')
resize?.(390)
await flushPromises()
expect(copyOption()).toMatchObject({ label: 'Copy table image' })
await wrapper.setProps({ loading: true })
expect(copyOption()).toMatchObject({ disabled: true })
await wrapper.setProps({ loading: false })
const copy = vi.spyOn(image, 'copyTableImage').mockResolvedValue(void 0)
menu.vm.$emit('select', 'copy-image')
await flushPromises()
expect(copy).toHaveBeenCalledOnce()
expect(wrapper.find('button[aria-label="Copy table image"]').exists()).toBe(
false,
)
await wrapper.setProps({ showCopyImage: false })
expect(copyOption()).toBeUndefined()
await wrapper.setProps({ showCopyImage: true })
resize?.(960)
await flushPromises()
expect(copyOption()).toBeUndefined()
expect(wrapper.find('button[aria-label="Copy table image"]').exists()).toBe(
true,
)
} finally {
wrapper.unmount()
vi.unstubAllGlobals()
}
})
it('opts into menu printing and retains CSV formatting and output options', async () => {
const download = vi
.spyOn(csv, 'downloadTableCsv')
.mockImplementation(() => {})
const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true)
const wrapper = mount(RTablePro, {
props: {
columns,
data,
showPrint: true,
downloadCsvTableOptions: { fileName: 'people' },
printTableOptions: { title: 'People report' },
getCsvCell: (value) => `Person: ${String(value)}`,
},
})
try {
const menu = wrapper.getComponent(NDropdown)
expect(
menu.props('options')?.some((option) => option.key === 'print'),
).toBe(true)
menu.vm.$emit('select', 'csv')
await flushPromises()
expect(download).toHaveBeenCalledExactlyOnceWith(
'"Name"\r\n"Person: Ray"',
'people',
)
menu.vm.$emit('select', 'print')
await flushPromises()
expect(print).toHaveBeenCalledOnce()
expect(print.mock.calls[0][1]).toMatchObject({ title: 'People report' })
await wrapper.setProps({ showPrint: false })
expect(
menu.props('options')?.some((option) => option.key === 'print'),
).toBe(false)
menu.vm.$emit('select', 'print')
await flushPromises()
expect(print).toHaveBeenCalledOnce()
} finally {
wrapper.unmount()
}
})
it('updates density and appearance without changing caller defaults', async () => {
const wrapper = mount(RTablePro, {
props: { columns, data, size: 'medium', striped: false, bordered: true },
})
try {
const menu = wrapper.getComponent(NDropdown)
menu.vm.$emit('select', 'density:small')
menu.vm.$emit('select', 'striped')
menu.vm.$emit('select', 'bordered')
await flushPromises()
expect(wrapper.getComponent(NDataTable).props()).toMatchObject({
size: 'small',
striped: true,
bordered: false,
})
expect(wrapper.props()).toMatchObject({
size: 'medium',
striped: false,
bordered: true,
})
await wrapper.setProps({ size: 'large' })
expect(wrapper.getComponent(NDataTable).props('size')).toBe('large')
await wrapper.setProps({ size: void 0 })
expect(wrapper.getComponent(NDataTable).props('size')).toBe('medium')
const density = menu
.props('options')
?.find((option) => option.key === 'density') as DropdownOption
expect(
(density.children as DropdownOption[])
.filter((option) => option.props?.['aria-checked'])
.map((option) => option.key),
).toEqual(['density:medium'])
} finally {
wrapper.unmount()
}
})
it('keeps appearance icons visible when checked or unchecked', async () => {
const wrapper = mount(RTablePro, {
props: {
columns,
data,
size: 'medium',
striped: false,
bordered: true,
showPrint: true,
},
})
const page = new DOMWrapper(document.body)
const openMenu = async () => {
await wrapper.get('[aria-label="More actions"]').trigger('click')
await vi.dynamicImportSettled()
await flushPromises()
}
const appearanceOption = (label: string) =>
page
.findAll('[role="menuitemcheckbox"]')
.find((option) => option.text().includes(label))!
try {
await openMenu()
for (const label of ['Table density', 'Export CSV', 'Print table']) {
const option = page
.findAll('.n-dropdown-option-body')
.find((option) => option.text().includes(label))!
expect(option.get('svg').html()).toContain('<path')
}
for (const [label, initial] of [
['Striped rows', false],
['Table border', true],
] as const) {
const option = appearanceOption(label)
const icon = option.get('.n-dropdown-option-body__prefix svg').html()
expect(icon).toContain('<path')
expect(option.attributes('aria-checked')).toBe(String(initial))
expect(option.get('.r-table-action-label__check').text()).toBe(
initial ? '✓' : '',
)
await option.trigger('click')
await flushPromises()
await openMenu()
const updated = appearanceOption(label)
expect(updated.attributes('aria-checked')).toBe(String(!initial))
expect(updated.get('.r-table-action-label__check').text()).toBe(
initial ? '' : '✓',
)
expect(updated.get('.n-dropdown-option-body__prefix svg').html()).toBe(
icon,
)
}
} finally {
wrapper.unmount()
}
})
it('refreshes the current remote query and preserves the caller toolbar when tools are disabled', async () => {
const [register, actions] = useTablePro()
const request = vi.fn<TableProRequest>(async () => ({ data, total: 30 }))
const wrapper = mount(RTablePro, {
props: { columns, request, onRegister: register },
slots: { toolbar: 'Business action' },
})
try {
await flushPromises()
expect(request).toHaveBeenCalledOnce()
await actions.setPage(2)
await flushPromises()
await wrapper.get('[aria-label="Refresh"]').trigger('click')
await flushPromises()
expect(request.mock.calls.map(([params]) => params.page)).toEqual([1, 2, 2])
expect(request.mock.lastCall?.[1]).not.toBe(request.mock.calls[1][1])
expect(wrapper.get('.r-table__business-actions').text()).toBe(
'Business action',
)
await wrapper.setProps({ tool: false })
expect(wrapper.find('.r-table__utilities').exists()).toBe(false)
expect(wrapper.get('.r-table__business-actions').text()).toBe(
'Business action',
)
} finally {
wrapper.unmount()
}
})

View File

@ -1,14 +1,11 @@
import { RTablePro, useTablePro } from '@/components/RTablePro'
import { RTablePro } from '@/components/RTablePro'
import type {
TableProInst,
TableProParams,
TableProResult,
} from '@/components/RTablePro'
import { provideUiServices } from '@ray-template/ui/services'
import { flushPromises, mount } from '@vue/test-utils'
import { NDataTable, NDropdown, NPagination } from 'naive-ui'
import { defineComponent, h, reactive } from 'vue'
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
import { NDataTable, NPagination } from 'naive-ui'
const columns = [{ title: 'Name', key: 'name' }]
const response = (name: string, total = 30): TableProResult => ({
@ -16,45 +13,6 @@ const response = (name: string, total = 30): TableProResult => ({
total,
})
it('binds table actions on mount and clears the instance until the table remounts', async () => {
const [
register,
{ isReady, reload, setPage, getTableProInstance, getCurrentPageData },
] = useTablePro()
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const mountTable = () =>
mount(RTablePro, { props: { columns, request, onRegister: register } })
expect(isReady.value).toBe(false)
expect(getTableProInstance).toThrow('Table is not mounted')
const first = mountTable()
const originalInstance = getTableProInstance()
try {
expect(isReady.value).toBe(true)
await setPage(2)
await flushPromises()
expect(request.mock.lastCall?.[0]).toEqual({ page: 2, pageSize: 10 })
expect(getCurrentPageData()).toEqual(response('Alice').data)
} finally {
first.unmount()
}
expect(isReady.value).toBe(false)
expect(getTableProInstance).toThrow('Table is not mounted')
const second = mountTable()
try {
expect(isReady.value).toBe(true)
expect(getTableProInstance()).not.toBe(originalInstance)
await setPage(2)
await reload(true)
expect(request.mock.lastCall?.[0]).toEqual({ page: 1, pageSize: 10 })
} finally {
second.unmount()
}
})
it('loads and paginates once per action, without rewriting the filter object', async () => {
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const filters = { email: '@example.test', page: 99 }
@ -97,34 +55,6 @@ it('loads and paginates once per action, without rewriting the filter object', a
}
})
it('keeps the current page for equivalent filters and reloads after a nested filter changes', async () => {
const filter = reactive({ state: 'active' })
const request = vi.fn(async (_params: TableProParams) => response('Alice'))
const wrapper = mount(RTablePro, {
props: {
columns,
request,
params: { filter: { state: 'active' } },
tool: false,
},
})
try {
await flushPromises()
await (wrapper.vm as unknown as TableProInst).setPage(2)
await wrapper.setProps({ params: { filter } })
await flushPromises()
expect(request.mock.calls.map(([query]) => query.page)).toEqual([1, 2])
filter.state = 'disabled'
await flushPromises()
expect(request.mock.calls.map(([query]) => query.page)).toEqual([1, 2, 1])
expect(request.mock.lastCall?.[0].filter).toEqual({ state: 'disabled' })
} finally {
wrapper.unmount()
}
})
it('ignores stale data even if the loader ignores cancellation', async () => {
const first = Promise.withResolvers<TableProResult>()
const second = Promise.withResolvers<TableProResult>()
@ -139,7 +69,7 @@ it('ignores stale data even if the loader ignores cancellation', async () => {
const next = instance.setPage(2)
expect(request.mock.calls[0][1].aborted).toBe(true)
second.resolve(response('New page', 40))
second.resolve(response('New page'))
await next
first.resolve(response('Old page'))
await flushPromises()
@ -147,276 +77,51 @@ it('ignores stale data even if the loader ignores cancellation', async () => {
expect(wrapper.text()).toContain('New page')
expect(wrapper.text()).not.toContain('Old page')
expect(wrapper.getComponent(NDataTable).props('loading')).toBe(false)
expect(instance.queryState).toMatchObject({
loading: false,
failed: false,
page: 2,
total: 40,
})
} finally {
wrapper.unmount()
}
})
it('exposes read-only query state during load, failure and retry', async () => {
const initial = Promise.withResolvers<TableProResult>()
const failing = Promise.withResolvers<TableProResult>()
const retry = Promise.withResolvers<TableProResult>()
const request = vi
.fn(() => retry.promise)
.mockReturnValueOnce(initial.promise)
.mockReturnValueOnce(failing.promise)
const [register, { queryState, reload, setPageSize }] = useTablePro()
expect(queryState.value).toBeNull()
const wrapper = mount(RTablePro, {
props: { columns, request, onRegister: register, tool: false },
})
try {
expect(queryState.value).toEqual({
loading: true,
failed: false,
page: 1,
pageSize: 10,
total: null,
})
expect(Reflect.set(queryState.value!, 'page', 99)).toBe(false)
initial.resolve(response('Last successful result', 42))
await flushPromises()
expect(queryState.value).toMatchObject({ loading: false, total: 42 })
const next = setPageSize(20)
expect(queryState.value).toMatchObject({
loading: true,
pageSize: 20,
total: 42,
})
failing.reject(new Error('offline'))
await next
expect(queryState.value).toEqual({
loading: false,
failed: true,
page: 1,
pageSize: 20,
total: null,
})
expect(wrapper.text()).not.toContain('Last successful result')
const retrying = reload()
expect(queryState.value).toMatchObject({
loading: true,
failed: false,
total: null,
})
retry.resolve(response('Recovered', 7))
await retrying
expect(queryState.value).toMatchObject({
loading: false,
failed: false,
total: 7,
})
} finally {
wrapper.unmount()
}
expect(queryState.value).toBeNull()
})
it('clears rows and blocks output while a different query scope loads or fails', async () => {
const failed = Promise.withResolvers<TableProResult>()
const request = vi
.fn(async (_params: TableProParams) => response('Account B'))
.mockResolvedValueOnce(response('Account A'))
.mockImplementationOnce(() => failed.promise)
const wrapper = mount(RTablePro, {
props: { columns, request, params: { account: { id: 'a' } } },
})
const table = wrapper.vm as unknown as TableProInst
const download = vi
.spyOn(csv, 'downloadTableCsv')
.mockImplementation(() => {})
try {
await flushPromises()
expect(table.getCurrentPageData()).toEqual(response('Account A').data)
await wrapper.setProps({ params: { account: { id: 'b' } } })
expect(table.queryState).toMatchObject({ loading: true, total: null })
expect(table.getCurrentPageData()).toEqual([])
expect(table.getTableInstance()).toBeNull()
expect(wrapper.getComponent(NDataTable).props('data')).toEqual([])
failed.reject(new Error('offline'))
await flushPromises()
expect(table.queryState).toMatchObject({ failed: true, total: null })
expect(wrapper.text()).not.toContain('Account A')
expect(await table.print()).toBe(false)
table.downloadCsv({ keepOriginalData: true })
expect(download).not.toHaveBeenCalled()
await table.reload()
expect(table.getCurrentPageData()).toEqual(response('Account B').data)
table.downloadCsv()
expect(download).toHaveBeenCalledExactlyOnceWith(
'"Name"\r\n"Account B"',
void 0,
)
} finally {
download.mockRestore()
wrapper.unmount()
}
})
it('clears even same-query rows on failure and when the request source changes', async () => {
const request = vi
.fn(async (_params: TableProParams) => response('Previous source'))
.mockResolvedValueOnce(response('Previous source'))
.mockRejectedValueOnce(new Error('offline'))
const replacement = vi.fn(async () => {
throw new Error('new source offline')
})
const wrapper = mount(RTablePro, { props: { columns, request } })
const table = wrapper.vm as unknown as TableProInst
try {
await flushPromises()
await table.reload()
expect(table.queryState).toMatchObject({ failed: true, total: null })
expect(table.getCurrentPageData()).toEqual([])
await table.reload()
expect(table.getCurrentPageData()).toEqual(response('Previous source').data)
await wrapper.setProps({ request: replacement })
await flushPromises()
expect(table.queryState).toMatchObject({ failed: true, total: null })
expect(table.getCurrentPageData()).toEqual([])
} finally {
wrapper.unmount()
}
})
it('shows a persistent request error with retry while preserving the ordinary empty slot', async () => {
it('shows a retry for a failed request and omits paging fields when pagination is off', async () => {
const request = vi
.fn(async (_params: TableProParams) => response('Recovered', 1))
.mockRejectedValueOnce(new Error('offline'))
const reportError = vi.fn()
const wrapper = mount(
defineComponent({
setup() {
provideUiServices({ reportError })
return () =>
h(
RTablePro,
{ columns, request, pagination: false, tool: false },
{
empty: () => 'Custom empty state',
notice: () => 'Always visible notice',
},
)
},
}),
)
const table = wrapper.getComponent(RTablePro)
const instance = table.vm as unknown as TableProInst
const wrapper = mount(RTablePro, {
props: { columns, request, pagination: false, tool: false },
})
try {
await flushPromises()
expect(table.emitted('request-error')).toHaveLength(1)
expect(reportError).not.toHaveBeenCalled()
expect(table.getComponent(NDataTable).props('pagination')).toBe(false)
expect(table.text()).not.toContain('Custom empty state')
expect(table.text()).toContain('Always visible notice')
expect(table.get('[role="alert"]').text()).toBe("Couldn't load the data")
await table
.findAll('button')
.find((item) => item.text() === 'Retry')!
.trigger('click')
expect(wrapper.emitted('request-error')).toHaveLength(1)
expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false)
await wrapper.get('.n-alert button').trigger('click')
await flushPromises()
expect(request.mock.calls.map(([params]) => params)).toEqual([{}, {}])
expect(table.text()).toContain('Recovered')
expect(instance.queryState).toEqual({
loading: false,
failed: false,
page: null,
pageSize: null,
total: 1,
})
request.mockResolvedValueOnce({ data: [], total: 0 })
await instance.reload()
expect(table.text()).toContain('Custom empty state')
expect(wrapper.find('.n-alert').exists()).toBe(false)
expect(wrapper.text()).toContain('Recovered')
} 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 {
wrapper.unmount()
}
})
it('reads the sorted and filtered local page without a request or custom row key', async () => {
it('can paginate local data without requiring a request or a row key function', async () => {
const data = [
{ id: 3, name: 'Third' },
{ id: 1, name: 'First' },
{ id: 2, name: 'Second' },
]
const wrapper = mount(RTablePro, {
props: {
columns: [{ title: 'Name', key: 'name', sorter: 'default' }],
data,
pageSize: 1,
search: [{ key: 'name', label: 'Name' }],
tool: false,
},
props: { columns, data, pageSize: 1, tool: false },
})
try {
expect(wrapper.getComponent(NDataTable).props('remote')).toBe(false)
expect(wrapper.text()).toContain('First')
expect(wrapper.text()).not.toContain('Second')
const instance = wrapper.vm as unknown as TableProInst
expect(instance.getCurrentPageData()).toEqual([data[0]])
instance.getTableInstance()?.sort('name', 'ascend')
await instance.setPage(2)
expect(wrapper.text()).toContain('Second')
expect(instance.getCurrentPageData()).toEqual([data[2]])
await wrapper.get('input').setValue('ir')
await wrapper.get('form').trigger('submit')
expect(instance.getCurrentPageData()).toEqual([data[1]])
} finally {
wrapper.unmount()
}
@ -431,7 +136,6 @@ it('renders bare data without a toolbar or pagination by default', () => {
expect(wrapper.text()).toContain('Bare row')
expect(wrapper.getComponent(NDataTable).props('pagination')).toBe(false)
expect(wrapper.find('header').exists()).toBe(false)
expect(wrapper.classes()).not.toContain('r-table--card')
} finally {
wrapper.unmount()
}
@ -504,7 +208,6 @@ it('returns to the last available remote page when the total shrinks', async ()
expect(request.mock.calls.map(([params]) => params.page)).toEqual([1, 3, 1])
expect(wrapper.text()).toContain('First page')
expect(instance.queryState).toMatchObject({ page: 1, total: 5 })
} finally {
wrapper.unmount()
}
@ -531,7 +234,6 @@ it('passes native pagination settings and totals through for a manually controll
try {
const pager = wrapper.getComponent(NPagination)
expect((wrapper.vm as unknown as TableProInst).queryState).toBeNull()
expect(pager.props()).toMatchObject({
page: 3,
pageSize: 20,
@ -616,99 +318,3 @@ it('supports an optional title slot for actions without putting controls inside
wrapper.unmount()
}
})
it('provides the row that opened the context menu and discards it after data changes', async () => {
const row = { id: 7, name: 'Alice' }
const option = { key: 'edit', label: 'Edit' }
const select = vi.fn()
const onContextmenu = vi.fn((event: MouseEvent) => event.preventDefault())
const wrapper = mount(RTablePro, {
props: {
columns,
data: [row],
tool: false,
rowProps: () => ({ onContextmenu }),
contextMenuOptions: [option],
onContextMenuClick: select,
},
global: { stubs: { teleport: true } },
})
const menu = wrapper
.findAllComponents(NDropdown)
.find((dropdown) => dropdown.props('trigger') === 'manual')!
try {
const entry = wrapper.get('tbody tr')
await entry.trigger('contextmenu')
expect(onContextmenu).toHaveBeenCalledOnce()
expect(menu.props('show')).toBe(false)
expect(entry.attributes('tabindex')).toBe('0')
await entry.trigger('keydown', { key: 'F10', shiftKey: true })
expect(menu.props('show')).toBe(true)
await wrapper.get('.n-dropdown-option-body').trigger('click')
expect(select).toHaveBeenCalledExactlyOnceWith('edit', option, {
row,
index: 0,
})
await entry.trigger('keydown', { key: 'ContextMenu' })
expect(menu.props('show')).toBe(true)
await wrapper.setProps({ data: [{ id: 8, name: 'Ray' }] })
expect(menu.props('show')).toBe(false)
const closingOption = wrapper.find('.n-dropdown-option-body')
if (closingOption.exists()) await closingOption.trigger('click')
expect(select).toHaveBeenCalledOnce()
} finally {
wrapper.unmount()
}
})
it('keeps panel props and slots out of the native table while forwarding its own API', () => {
const wrapper = mount(RTablePro, {
props: {
columns,
tool: false,
title: 'Panel title',
scrollX: 640,
columnStateKey: 'directory',
},
attrs: { id: 'directory' },
slots: { empty: 'Native empty slot', tableFooter: 'Panel footer' },
})
try {
const native = wrapper.getComponent(NDataTable)
expect(wrapper.attributes('id')).toBe('directory')
expect(wrapper.classes()).toContain('r-table--card')
expect(native.props('scrollX')).toBe(640)
expect(native.attributes('columnstatekey')).toBeUndefined()
expect(native.attributes('id')).toBeUndefined()
expect(native.text()).toContain('Native empty slot')
expect(native.text()).not.toContain('Panel footer')
expect(wrapper.get('.r-table__footer').text()).toBe('Panel footer')
} finally {
wrapper.unmount()
}
})
it('respects a changed density prop without reviving an earlier local choice', async () => {
const wrapper = mount(RTablePro, { props: { columns, size: 'medium' } })
const native = wrapper.getComponent(NDataTable)
try {
wrapper.getComponent(NDropdown).vm.$emit('select', 'density:small')
await wrapper.vm.$nextTick()
expect(native.props('size')).toBe('small')
await wrapper.setProps({ size: 'large' })
expect(native.props('size')).toBe('large')
await wrapper.setProps({ size: 'medium' })
expect(native.props('size')).toBe('medium')
} finally {
wrapper.unmount()
}
})

View File

@ -1,274 +0,0 @@
import { flushPromises, mount } from '@vue/test-utils'
import { NDropdown, NForm, NFormItem, NGrid, NSpin } from 'naive-ui'
import { defineComponent, h, nextTick, ref } from 'vue'
import { RCollapseGrid } from '../../packages/ui/src/RCollapseGrid'
import { RForm, useForm } from '../../packages/ui/src/RForm'
import { RIcon } from '../../packages/ui/src/RIcon'
import { RIframe } from '../../packages/ui/src/RIframe'
import type { RIframeInst } from '../../packages/ui/src/RIframe/src/types'
import { RMoreDropdown } from '../../packages/ui/src/RMoreDropdown'
import { RSegment } from '../../packages/ui/src/RSegment'
it('keeps controlled open state and zero grid gaps consistent', async () => {
const open = ref(false)
const wrapper = mount(
defineComponent(() => () => (
<RCollapseGrid
open={open.value}
onUpdateOpen={(value) => (open.value = value)}
xGap={0}
yGap={0}
/>
)),
)
try {
const button = wrapper.get('button.collapse-icon')
expect(wrapper.findComponent(NGrid).props()).toMatchObject({
xGap: 0,
yGap: 0,
collapsed: true,
})
expect(button.attributes('aria-expanded')).toBe('false')
await button.trigger('click')
expect(open.value).toBe(true)
expect(wrapper.findComponent(NGrid).props('collapsed')).toBe(false)
await button.trigger('click')
expect(open.value).toBe(false)
} finally {
wrapper.unmount()
}
})
it('forwards dropdown placement and renders segment label functions', () => {
const dropdown = mount(RMoreDropdown, {
props: { placement: 'top-end', triggerLabel: 'Row actions' },
})
const segment = mount(RSegment, {
props: {
options: [{ key: 'one', label: () => h('strong', 'Rendered label') }],
},
})
try {
expect(dropdown.findComponent(NDropdown).props('placement')).toBe('top-end')
expect(dropdown.get('button').attributes('aria-label')).toBe('Row actions')
expect(segment.get('strong').text()).toBe('Rendered label')
} finally {
dropdown.unmount()
segment.unmount()
}
})
it('preserves SVG root paint when no sprite service is installed', async () => {
const wrapper = mount(RIcon, { props: { name: 'action/close_all' } })
try {
await vi.dynamicImportSettled()
expect(wrapper.find('svg rect').exists()).toBe(true)
expect(wrapper.get('svg').attributes()).toMatchObject({
fill: 'none',
stroke: 'currentColor',
'stroke-width': '1.8',
})
await wrapper.setProps({ name: 'action/reload' })
await vi.dynamicImportSettled()
expect(wrapper.find('svg rect').exists()).toBe(false)
expect(wrapper.find('svg path').exists()).toBe(true)
} finally {
wrapper.unmount()
}
})
it('moves segment focus past disabled choices and emits each change once', async () => {
const change = vi.fn()
const wrapper = mount(RSegment, {
attachTo: document.body,
props: {
options: [
{ key: 'a', label: 'A' },
{ key: 'b', label: 'B', disabled: true },
{ key: 'c', label: 'C' },
],
onUpdateValue: change,
},
})
try {
const [a, b, c] = wrapper.findAll('[role="radio"]')
expect(a.attributes('tabindex')).toBe('0')
expect(b.attributes('aria-disabled')).toBe('true')
await a.trigger('keydown', { key: 'ArrowRight' })
expect(change.mock.calls).toEqual([['c']])
expect(document.activeElement).toBe(c.element)
expect(c.attributes('aria-checked')).toBe('true')
await c.trigger('keydown', { key: 'Home' })
expect(a.attributes('aria-checked')).toBe('true')
} finally {
wrapper.unmount()
}
})
it('starts iframe loading for every source and exposes the same native element', async () => {
const wrapper = mount(RIframe, {
props: { src: '/one.html', sandbox: '', referrerpolicy: 'no-referrer' },
attrs: { class: 'host-frame' },
})
try {
await nextTick()
const frame = wrapper.get('iframe')
expect(frame.attributes('sandbox')).toBe('')
expect(frame.attributes('referrerpolicy')).toBe('no-referrer')
expect(wrapper.element.classList.contains('host-frame')).toBe(true)
expect(wrapper.element.hasAttribute('sandbox')).toBe(false)
await wrapper.setProps({ sandbox: 'allow-forms' })
expect(frame.attributes('sandbox')).toBe('allow-forms')
await frame.trigger('load')
expect(wrapper.findComponent(NSpin).props('show')).toBe(false)
await wrapper.setProps({ src: '/two.html' })
expect(wrapper.findComponent(NSpin).props('show')).toBe(true)
const instance = wrapper.vm as unknown as RIframeInst
expect(instance.iframe).toBe(frame.element)
expect(instance.iframeInst).toBe(frame.element)
await frame.trigger('error')
expect(wrapper.findComponent(NSpin).props('show')).toBe(false)
} finally {
wrapper.unmount()
}
})
it('submits single-line Enter reactively without consuming IME, multiline, or combobox events', async () => {
const onFinish = vi.fn()
const wrapper = mount(RForm, {
props: { submitWhenEnter: false, onFinish },
slots: {
default: () => [
h('input'),
h('textarea'),
h('input', { role: 'combobox' }),
],
},
})
try {
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
expect(onFinish).not.toHaveBeenCalled()
await wrapper.setProps({ submitWhenEnter: true })
await wrapper.get('textarea').trigger('keydown', { key: 'Enter' })
await wrapper.get('[role="combobox"]').trigger('keydown', { key: 'Enter' })
await wrapper
.get('input')
.trigger('keydown', { key: 'Enter', isComposing: true })
await flushPromises()
expect(onFinish).not.toHaveBeenCalled()
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
await flushPromises()
expect(onFinish).toHaveBeenCalledOnce()
} finally {
wrapper.unmount()
}
})
it('keeps validation failures handled and prevents repeated Enter submissions', async () => {
const pending = Promise.withResolvers<void>()
const onFinish = vi.fn(() => pending.promise)
const wrapper = mount(RForm, {
props: { submitWhenEnter: true, onFinish, model: { name: '' } },
slots: {
default: () =>
h(
NFormItem,
{ path: 'name', rule: { required: true, message: 'Required' } },
() => h('input'),
),
},
})
try {
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
await flushPromises()
expect(onFinish).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('Required')
await wrapper.setProps({ model: { name: 'Ready' } })
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
await flushPromises()
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
await flushPromises()
expect(onFinish).toHaveBeenCalledOnce()
pending.resolve()
await flushPromises()
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
await flushPromises()
expect(onFinish).toHaveBeenCalledTimes(2)
} finally {
wrapper.unmount()
}
})
it('clears registered form instances when their component unmounts', async () => {
const [register, actions] = useForm({ name: 'Initial', enabled: false })
const wrapper = mount(RForm, { props: { onRegister: register } })
expect(actions.getFormInstance().validate).toBe(
wrapper.findComponent(NForm).vm.validate,
)
actions.updateFormCondition({ name: 'Updated' })
expect(actions.formConditionRef.value).toEqual({
name: 'Updated',
enabled: false,
})
actions.reset({ enabled: true })
expect(actions.formConditionRef.value).toEqual({
name: 'Initial',
enabled: true,
})
wrapper.unmount()
await nextTick()
expect(() => actions.getFormInstance()).toThrow('form instance is not ready')
})
it('allows forwarded key handlers to consume Enter before automatic submission', async () => {
const onFinish = vi.fn()
const onKeydown = vi.fn((event: KeyboardEvent) => event.preventDefault())
const wrapper = mount(RForm, {
props: { submitWhenEnter: true, onFinish },
attrs: { onKeydown },
slots: { default: () => h('input') },
})
try {
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
await flushPromises()
expect(onKeydown).toHaveBeenCalledOnce()
expect(onFinish).not.toHaveBeenCalled()
} finally {
wrapper.unmount()
}
})
it('does not submit after its component unmounts during asynchronous validation', async () => {
const validation = Promise.withResolvers<void>()
const onFinish = vi.fn()
const wrapper = mount(RForm, {
props: { submitWhenEnter: true, onFinish, model: { name: 'Ready' } },
slots: {
default: () =>
h(
NFormItem,
{ path: 'name', rule: { validator: () => validation.promise } },
() => h('input'),
),
},
})
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
wrapper.unmount()
validation.resolve()
await flushPromises()
expect(onFinish).not.toHaveBeenCalled()
})

View File

@ -1,479 +0,0 @@
// @vitest-environment node
import { spawnSync } from 'node:child_process'
import {
chmodSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
symlinkSync,
writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { parse, parseAllDocuments, stringify } from 'yaml'
import {
checkDistributions,
exportDistribution,
pruneLockfile,
} from '../../scripts/distributions.mjs'
let fixture: string
const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf8'))
const reference = (version: string) => ({ specifier: version, version })
function write(path: string, value: string | object) {
const target = join(fixture, path)
mkdirSync(dirname(target), { recursive: true })
writeFileSync(
target,
typeof value === 'string' ? value : JSON.stringify(value),
)
}
function lockfile() {
const manager = {
lockfileVersion: '9.0',
importers: {
'.': { packageManagerDependencies: { pnpm: reference('12.0.0') } },
},
packages: { 'pnpm@12.0.0': {}, 'pm-native@1.0.0': {} },
snapshots: {
'pnpm@12.0.0': { optionalDependencies: { 'pm-native': '1.0.0' } },
'pm-native@1.0.0': {},
},
}
const workspace = {
lockfileVersion: '9.0',
settings: { autoInstallPeers: true },
importers: {
'.': { devDependencies: { yaml: reference('2.9.1') } },
'apps/admin': {
dependencies: {
'@ray-template/ui': reference('link:../../packages/ui'),
alias: reference('real-package@1.0.0(peer@2.0.0(nested@3.0.0))'),
},
},
'apps/docs': {
dependencies: {
'@ray-template/ui': reference('link:../../packages/ui'),
},
},
'apps/server': {
dependencies: {
'@ray-template/api-contracts': reference(
'link:../../packages/api-contracts',
),
'@ray-template/server-store': reference(
'link:../../packages/server-store',
),
'@nestjs/core': reference('12.0.0'),
},
},
'packages/ui': {
dependencies: {
'@ray-template/api-contracts': reference('link:../api-contracts'),
vue: reference('3.5.0'),
},
},
'packages/api-contracts': {
dependencies: { valibot: reference('1.5.0') },
},
'packages/server-store': { dependencies: { pg: reference('8.0.0') } },
},
packages: {
'yaml@2.9.1': {},
'vue@3.5.0': {},
'valibot@1.5.0': {},
'real-package@1.0.0': {},
'peer@2.0.0': {},
'nested@3.0.0': {},
'native-optional@1.0.0': {},
'@nestjs/core@12.0.0': {},
'pg@8.0.0': {},
'pg-protocol@1.0.0': {},
'unused@1.0.0': {},
},
snapshots: {
'yaml@2.9.1': {},
'vue@3.5.0': {},
'valibot@1.5.0': {},
'real-package@1.0.0(peer@2.0.0(nested@3.0.0))': {
optionalDependencies: { 'native-optional': '1.0.0' },
},
'peer@2.0.0(nested@3.0.0)': {},
'nested@3.0.0': {},
'native-optional@1.0.0': {},
'@nestjs/core@12.0.0': {},
'pg@8.0.0': { dependencies: { 'pg-protocol': '1.0.0' } },
'pg-protocol@1.0.0': {},
'unused@1.0.0': {},
},
}
return `---\n${stringify(manager)}\n---\n${stringify(workspace)}`
}
beforeEach(() => {
fixture = mkdtempSync(join(tmpdir(), 'ray-distribution-'))
write('package.json', {
name: 'ray-template',
version: '6.0.1',
private: true,
scripts: {
dev: 'vite',
'check:frontend': 'pnpm typecheck && pnpm test:run',
check: 'pnpm check:frontend && pnpm server:check && pnpm dist:check',
setup: 'node scripts/fullstack.mjs setup',
'dev:full': 'node scripts/fullstack.mjs dev',
'server:check': 'pnpm --filter @ray-template/server check',
'dist:frontend': 'node scripts/distributions.mjs frontend',
'dist:fullstack': 'node scripts/distributions.mjs fullstack',
'dist:check': 'node scripts/distributions.mjs --check',
},
devDependencies: { yaml: '2.9.1' },
})
write('apps/admin/package.json', {
name: '@ray-template/admin',
dependencies: {
'@ray-template/ui': 'workspace:*',
alias: 'npm:real-package@1.0.0',
},
})
write('apps/docs/package.json', {
name: '@ray-template/docs',
dependencies: { '@ray-template/ui': 'workspace:*' },
})
write('apps/server/package.json', {
name: '@ray-template/server',
dependencies: {
'@ray-template/api-contracts': 'workspace:*',
'@ray-template/server-store': 'workspace:*',
'@nestjs/core': '12.0.0',
},
})
write('packages/ui/package.json', {
name: '@ray-template/ui',
dependencies: { '@ray-template/api-contracts': 'workspace:*' },
peerDependencies: { vue: '3.5.0' },
})
write('packages/api-contracts/package.json', {
name: '@ray-template/api-contracts',
dependencies: { valibot: '1.5.0' },
})
write('packages/server-store/package.json', {
name: '@ray-template/server-store',
dependencies: { pg: '8.0.0' },
})
write('packages/ui/src/index.ts', 'export const shared = true\n')
write('apps/server/src/main.ts', 'export const server = true\n')
write('apps/admin/src/main.ts', 'export const admin = true\n')
write('scripts/distributions.mjs', '// exporter\n')
write('scripts/fullstack.mjs', '// server launcher\n')
write('deploy/compose.yaml', 'services: {}\n')
write('.github/workflows/ci.yaml', 'name: CI\n')
write('.github/workflows/distributions.yaml', 'name: Distributions\n')
write('.husky/pre-commit', 'pnpm lint-staged\n')
chmodSync(join(fixture, '.husky/pre-commit'), 0o755)
write(
'pnpm-workspace.yaml',
'packages:\n - apps/*\n - packages/*\nverifyDepsBeforeRun: false\n',
)
write('pnpm-lock.yaml', lockfile())
write('harness/scopes.json', {
toolchain: { checks: ['packages:check'] },
server: { checks: ['server:check'] },
})
write('harness/context/server.md', '# Server\n')
write('tsconfig.json', {
references: [
{ path: './tsconfig.app.json' },
{ path: './apps/server/tsconfig.json' },
],
})
write('tsconfig.app.json', '{}\n')
write(
'README.md',
'# Template\n\nFrontend instructions.\n\n<!-- fullstack:start -->\n[Server](apps/server/README.md)\n<!-- fullstack:end -->\n\nShared instructions.\n',
)
})
afterEach(() => {
rmSync(fixture, { recursive: true, force: true })
})
it('exports a real frontend workspace without server files, scripts or dependency graph', async () => {
const sourceManifest = readFileSync(join(fixture, 'package.json'), 'utf8')
const sourceLock = readFileSync(join(fixture, 'pnpm-lock.yaml'), 'utf8')
const { directory, manifest } = await exportDistribution(
fixture,
'frontend',
{
archive: false,
},
)
const exported = readJson(join(directory, 'package.json'))
const locks = parseAllDocuments(
readFileSync(join(directory, 'pnpm-lock.yaml'), 'utf8'),
).map((document) => document.toJS())
expect(exported.scripts).not.toHaveProperty('server:check')
expect(exported.scripts).not.toHaveProperty('setup')
expect(exported.scripts).not.toHaveProperty('dev:full')
expect(exported.scripts).not.toHaveProperty('dist:fullstack')
expect(exported.scripts.check).toBe('pnpm check:frontend && pnpm dist:check')
expect(exported.scripts.dev).toBe('vite')
expect(existsSync(join(directory, 'apps/server'))).toBe(false)
expect(existsSync(join(directory, 'packages/server-store'))).toBe(false)
expect(existsSync(join(directory, 'scripts/fullstack.mjs'))).toBe(false)
expect(existsSync(join(directory, 'deploy'))).toBe(false)
expect(
existsSync(join(directory, '.github/workflows/distributions.yaml')),
).toBe(false)
expect(existsSync(join(directory, '.github/workflows/ci.yaml'))).toBe(true)
expect(readJson(join(directory, 'harness/scopes.json'))).not.toHaveProperty(
'server',
)
expect(readJson(join(directory, 'tsconfig.json')).references).toEqual([
{ path: './tsconfig.app.json' },
])
expect(readFileSync(join(directory, 'README.md'), 'utf8')).toContain(
'Frontend instructions.',
)
expect(readFileSync(join(directory, 'README.md'), 'utf8')).not.toContain(
'[Server]',
)
expect(
parse(readFileSync(join(directory, 'pnpm-workspace.yaml'), 'utf8'))
.packages,
).toEqual([
'apps/admin',
'apps/docs',
'packages/api-contracts',
'packages/ui',
])
expect(locks).toHaveLength(2)
expect(locks[0].snapshots).toHaveProperty('pm-native@1.0.0')
expect(Object.keys(locks[1].snapshots)).toEqual(
expect.arrayContaining([
'real-package@1.0.0(peer@2.0.0(nested@3.0.0))',
'peer@2.0.0(nested@3.0.0)',
'nested@3.0.0',
'native-optional@1.0.0',
]),
)
expect(locks[1].snapshots).not.toHaveProperty('@nestjs/core@12.0.0')
expect(locks[1].snapshots).not.toHaveProperty('pg@8.0.0')
expect(locks[1].packages).not.toHaveProperty('pg-protocol@1.0.0')
expect(locks[1].packages).not.toHaveProperty('unused@1.0.0')
expect(manifest.edition).toBe('frontend')
expect(manifest.contentSha256).toMatch(/^[a-f0-9]{64}$/)
expect(manifest.workspaces).not.toContain('apps/server')
expect(readFileSync(join(fixture, 'package.json'), 'utf8')).toBe(
sourceManifest,
)
expect(readFileSync(join(fixture, 'pnpm-lock.yaml'), 'utf8')).toBe(sourceLock)
if (process.platform !== 'win32') {
expect(statSync(join(directory, '.husky/pre-commit')).mode & 0o777).toBe(
0o755,
)
}
})
it('exports fullstack with its backend and transitive packages', async () => {
const { directory, manifest } = await exportDistribution(
fixture,
'fullstack',
{
archive: false,
},
)
const lock = parseAllDocuments(
readFileSync(join(directory, 'pnpm-lock.yaml'), 'utf8'),
)[1].toJS()
expect(existsSync(join(directory, 'apps/server/src/main.ts'))).toBe(true)
expect(
existsSync(join(directory, 'packages/server-store/package.json')),
).toBe(true)
expect(existsSync(join(directory, 'deploy/compose.yaml'))).toBe(true)
expect(readJson(join(directory, 'package.json')).scripts).toHaveProperty(
'dev:full',
)
expect(lock.snapshots).toHaveProperty('pg-protocol@1.0.0')
expect(manifest.workspaces).toContain('apps/server')
})
it('omits local secrets, unapproved root files and generated output while including new source', async () => {
for (const path of [
'.env',
'.env.local',
'credentials.json',
'.git/config',
'apps/server/.env',
'apps/server/src/generated/client.ts',
'apps/server/dist-test/result.js',
'apps/admin/.env.local',
'apps/admin/node_modules/secret.txt',
'packages/ui/dist/index.js',
'apps/docs/.vitepress/cache/leak.json',
'scripts/private.pem',
'docs/.local/token',
'.husky/_/husky.sh',
])
write(path, 'private data')
write('apps/server/.env.example', 'DATABASE_URL=postgresql://example\n')
write('apps/server/.gitignore', '/src/generated/\n/dist-test/\n/.env.local\n')
write('apps/admin/.env.development', 'VITE_API_MOCK=true\n')
write(
'packages/ui/src/new-uncommitted.ts',
'export const uncommitted = true\n',
)
write('__test__/cache/keep.spec.ts', 'export const regression = true\n')
write('apps/admin/src/utils/cache/index.ts', 'export const storage = true\n')
const { directory } = await exportDistribution(fixture, 'fullstack', {
archive: false,
})
expect(existsSync(join(directory, 'apps/server/.env.example'))).toBe(true)
expect(existsSync(join(directory, 'apps/server/.gitignore'))).toBe(true)
expect(existsSync(join(directory, 'apps/server/src/generated'))).toBe(false)
expect(existsSync(join(directory, 'apps/server/dist-test'))).toBe(false)
expect(existsSync(join(directory, 'apps/admin/.env.development'))).toBe(true)
expect(
existsSync(join(directory, 'packages/ui/src/new-uncommitted.ts')),
).toBe(true)
expect(existsSync(join(directory, '__test__/cache/keep.spec.ts'))).toBe(true)
expect(
existsSync(join(directory, 'apps/admin/src/utils/cache/index.ts')),
).toBe(true)
expect(existsSync(join(directory, 'apps/admin/.env.local'))).toBe(false)
expect(existsSync(join(directory, 'apps/server/.env'))).toBe(false)
expect(existsSync(join(directory, '.env'))).toBe(false)
expect(existsSync(join(directory, 'credentials.json'))).toBe(false)
expect(existsSync(join(directory, '.git'))).toBe(false)
expect(existsSync(join(directory, 'packages/ui/dist'))).toBe(false)
expect(existsSync(join(directory, 'scripts/private.pem'))).toBe(false)
})
it('validates exports read-only and supports frontend-only extracted projects', async () => {
const entries = readdirSync(fixture)
expect(checkDistributions(fixture).map(({ edition }) => edition)).toEqual([
'frontend',
'fullstack',
])
expect(readdirSync(fixture)).toEqual(entries)
const { directory } = await exportDistribution(fixture, 'frontend', {
archive: false,
})
expect(checkDistributions(directory).map(({ edition }) => edition)).toEqual([
'frontend',
])
await expect(
exportDistribution(directory, 'fullstack', { archive: false }),
).rejects.toThrow('Workspace dependency is missing')
})
it('refuses broken dependency graphs and missing lockfile importers', async () => {
write('packages/ui/package.json', {
name: '@ray-template/ui',
dependencies: { '@ray-template/server': 'workspace:*' },
})
expect(() => checkDistributions(fixture)).toThrow(
'Frontend dependency reaches the server',
)
expect(() =>
pruneLockfile(lockfile(), new Set(['.', 'apps/missing'])),
).toThrow('Workspace importer is missing')
expect(() =>
pruneLockfile('lockfileVersion: 6\nimporters: {}', new Set()),
).toThrow('version 9')
})
it('refuses credentials in package-manager config and malformed section markers', async () => {
write('.npmrc', '//registry.npmjs.org/:_authToken=do-not-export\n')
expect(() => checkDistributions(fixture)).toThrow('Credential-bearing .npmrc')
rmSync(join(fixture, '.npmrc'))
write('README.md', '<!-- fullstack:start -->\nMissing end\n')
expect(() => checkDistributions(fixture)).toThrow(
'Unpaired fullstack section marker',
)
})
it('replaces only recognized generated output and keeps artifact content reproducible', async () => {
const output = 'dist/distributions/ray-template-frontend-6.0.1'
write(`${output}/keep.txt`, 'user data')
await expect(
exportDistribution(fixture, 'frontend', { archive: false }),
).rejects.toThrow('unrecognized distribution')
expect(readFileSync(join(fixture, output, 'keep.txt'), 'utf8')).toBe(
'user data',
)
rmSync(join(fixture, output), { recursive: true })
const first = await exportDistribution(fixture, 'frontend', {
archive: false,
})
const second = await exportDistribution(fixture, 'frontend', {
archive: false,
})
expect(first.manifest.contentSha256).toBe(second.manifest.contentSha256)
})
it.skipIf(process.platform === 'win32')(
'rejects existing and dangling output symlinks and source symlinks',
async () => {
const outside = mkdtempSync(join(tmpdir(), 'ray-distribution-outside-'))
try {
symlinkSync(outside, join(fixture, 'dist'), 'dir')
await expect(
exportDistribution(fixture, 'frontend', { archive: false }),
).rejects.toThrow('symlink')
expect(readdirSync(outside)).toEqual([])
rmSync(join(fixture, 'dist'))
mkdirSync(join(fixture, 'dist/distributions'), { recursive: true })
symlinkSync(
join(outside, 'new-file'),
join(fixture, 'dist/distributions/ray-template-frontend-6.0.1.tar.gz'),
)
await expect(exportDistribution(fixture, 'frontend')).rejects.toThrow(
'symlink',
)
expect(existsSync(join(outside, 'new-file'))).toBe(false)
rmSync(join(fixture, 'dist'), { recursive: true })
symlinkSync(
join(fixture, 'package.json'),
join(fixture, 'packages/ui/src/linked.json'),
)
expect(() => checkDistributions(fixture)).toThrow('Source symlinks')
} finally {
rmSync(outside, { recursive: true, force: true })
}
},
)
it('creates a portable archive containing one distribution root and its provenance', async () => {
const { archive } = await exportDistribution(fixture, 'frontend')
const result = spawnSync('tar', ['-tzf', archive!], { encoding: 'utf8' })
expect(result.status).toBe(0)
expect(result.stdout).toContain(
'ray-template-frontend-6.0.1/distribution.json',
)
expect(result.stdout).toContain(
'ray-template-frontend-6.0.1/apps/admin/package.json',
)
expect(result.stdout).not.toContain('apps/server')
})

View File

@ -1,6 +1,6 @@
import { toJpeg } from 'html-to-image'
import print from 'print-js'
import { printDom } from '../../apps/admin/src/utils/dom'
import { printDom } from '../../src/utils/dom'
vi.mock('html-to-image', () => ({
toSvg: vi.fn(),

View File

@ -1,4 +1,4 @@
import { autoPrefixStyle } from '../../apps/admin/src/utils/element'
import { autoPrefixStyle } from '../../src/utils/element'
describe('autoPrefixStyle', () => {
it('should be defined', () => {

View File

@ -1,8 +1,4 @@
import {
hasClass,
removeClass,
setClass,
} from '../../apps/admin/src/utils/element'
import { hasClass, removeClass, setClass } from '../../src/utils/element'
import createRefElement from '../utils/createRefElement'
describe('setClass', () => {

View File

@ -1,4 +1,4 @@
import { colorToRgba } from '../../apps/admin/src/utils/element'
import { colorToRgba } from '../../src/utils/element'
describe('colorToRgba', () => {
it('should be defined', () => {

View File

@ -1,4 +1,4 @@
import { completeSize } from '../../apps/admin/src/utils/element'
import { completeSize } from '../../src/utils/element'
describe('completeSize', () => {
it('should be defined', () => {

View File

@ -1,4 +1,4 @@
import { queryElements } from '../../apps/admin/src/utils/element'
import { queryElements } from '../../src/utils/element'
describe('queryElements', () => {
const div = document.createElement('div')

View File

@ -1,4 +1,4 @@
import { removeStyle, setStyle } from '../../apps/admin/src/utils/element'
import { removeStyle, setStyle } from '../../src/utils/element'
import createRefElement from '../utils/createRefElement'
describe('setStyle', () => {

View File

@ -17,31 +17,26 @@ let fixture: string
beforeEach(() => {
fixture = mkdtempSync(join(tmpdir(), 'ray-harness-'))
mkdirSync(join(fixture, 'harness/context'), { recursive: true })
mkdirSync(join(fixture, 'docs'))
mkdirSync(join(fixture, 'harness'))
mkdirSync(join(fixture, '__test__/demo'), { recursive: true })
copyFileSync(
new URL('../../harness/run.mjs', import.meta.url),
join(fixture, 'harness/run.mjs'),
)
for (const path of [
'AGENTS.md',
'docs/architecture.md',
'docs/docs-handoff.md',
'harness/README.md',
'harness/plan.md',
]) {
writeFileSync(join(fixture, path), '# Fixture\n')
}
writeFileSync(join(fixture, 'llms.txt'), '[Demo](harness/context/demo.md)\n')
writeFileSync(
join(fixture, 'harness/context/demo.md'),
'# Demo\n\nRead [architecture](../../docs/architecture.md#fixture)。\n',
join(fixture, 'harness/scopes.json'),
JSON.stringify({
demo: {
description: 'Demo',
paths: ['harness'],
tests: ['__test__/demo/'],
},
}),
)
writeFileSync(
join(fixture, 'package.json'),
JSON.stringify({ scripts: { 'env:check': 'node -e "process.exit(23)"' } }),
)
writeScope({ tests: ['__test__/demo/'] })
writeScripts({ 'env:check': 'node -e "process.exit(23)"' })
})
afterEach(() => {
@ -55,159 +50,27 @@ function run(...args: string[]) {
})
}
function writeScope(targets: { tests?: string[]; checks?: string[] }) {
writeFileSync(
join(fixture, 'harness/scopes.json'),
JSON.stringify({ demo: { description: 'Demo', ...targets } }),
)
}
it('拒绝没有回归用例的目录', () => {
const result = run('check')
function writeScripts(scripts: Record<string, string>) {
writeFileSync(join(fixture, 'package.json'), JSON.stringify({ scripts }))
}
expect(result.status).toBe(1)
expect(result.stderr).toContain('回归测试路径没有用例:__test__/demo/')
})
function readReport() {
it('子命令失败时停止后续验证,并记录失败状态', () => {
writeFileSync(join(fixture, '__test__/demo/example.spec.ts'), '')
const result = run('verify', 'demo')
const runs = join(fixture, '.harness-local/runs')
const [runDirectory] = readdirSync(runs)
return JSON.parse(
const report = JSON.parse(
readFileSync(join(runs, runDirectory, 'report.json'), 'utf8'),
)
}
it('rejects directories without regression tests', () => {
const result = run('check')
expect(result.status).toBe(1)
expect(result.stderr).toContain(
'regression test path contains no tests: __test__/demo/',
)
})
it('reports the source and broken link when an indexed implementation moves', () => {
writeFileSync(join(fixture, '__test__/demo/example.spec.ts'), '')
expect(run('check').status).toBe(0)
rmSync(join(fixture, 'docs/architecture.md'))
const result = run('check')
expect(result.status).toBe(1)
expect(result.stderr).toContain(
'harness/context/demo.md: invalid relative link: ../../docs/architecture.md#fixture',
)
})
it('rejects registered topics missing from the static entry point', () => {
writeFileSync(join(fixture, '__test__/demo/example.spec.ts'), '')
writeFileSync(join(fixture, 'llms.txt'), '# Empty index\n')
const result = run('check')
expect(result.status).toBe(1)
expect(result.stderr).toContain('llms.txt is missing a valid topic link')
})
it('shows context and runs project checks for scopes without Vitest', () => {
writeScope({ checks: ['docs:check'] })
writeScripts({
'env:check': 'node --version',
'docs:check': 'node -e "console.log(process.cwd())"',
})
expect(run('check').status).toBe(0)
const context = run('context', 'demo')
expect(context.status).toBe(0)
expect(context.stdout).toContain(
'Read [architecture](../../docs/architecture.md#fixture)',
)
expect(context.stdout).toContain('pnpm docs:check')
expect(run('verify', 'demo').status).toBe(0)
expect(readReport()).toMatchObject({
scope: 'demo',
status: 'passed',
steps: [
{ command: 'pnpm env:check', exitCode: 0 },
{ command: 'pnpm docs:check', exitCode: 0 },
],
})
})
it('rejects registering full checks as targeted checks to prevent recursion', () => {
writeScope({ checks: ['check'] })
writeScripts({ check: 'node harness/run.mjs check' })
const result = run('verify', 'demo')
expect(result.status).toBe(1)
expect(result.stderr).toContain('demo: unregistered check command: check')
})
it('stops subsequent checks and records failure when a child command fails', () => {
writeFileSync(join(fixture, '__test__/demo/example.spec.ts'), '')
const result = run('verify', 'demo')
expect(result.status).toBe(23)
expect(readReport()).toMatchObject({
expect(report).toMatchObject({
scope: 'demo',
status: 'failed',
steps: [{ command: 'pnpm env:check', exitCode: 23 }],
})
})
it('runs only registered tests without appending full checks', () => {
writeFileSync(join(fixture, '__test__/demo/example.spec.ts'), '')
writeScripts({
'env:check': 'node --version',
'test:run': 'node -e "process.exit(0)"',
check: 'node -e "process.exit(97)"',
})
expect(run('verify', 'demo').status).toBe(0)
expect(readReport()).toMatchObject({
scope: 'demo',
status: 'passed',
steps: [
{ command: 'pnpm env:check', exitCode: 0 },
{ command: 'pnpm test:run __test__/demo/', exitCode: 0 },
],
})
})
it.each(['api:check', 'icons:check'])(
'stops regressions and records failure when targeted %s finds stale artifacts',
(script) => {
writeFileSync(join(fixture, '__test__/demo/example.spec.ts'), '')
writeScope({ checks: [script], tests: ['__test__/demo/'] })
writeScripts({
'env:check': 'node --version',
[script]: 'node -e "process.exit(23)"',
'test:run': 'node -e "process.exit(97)"',
})
expect(run('verify', 'demo').status).toBe(23)
expect(readReport()).toMatchObject({
scope: 'demo',
status: 'failed',
steps: [
{ command: 'pnpm env:check', exitCode: 0 },
{ command: `pnpm ${script}`, exitCode: 23 },
],
})
},
)
it.each([{ args: [] }, { args: ['all'] }])(
'preserves pnpm check compatibility for the full-check entry point $args',
({ args }) => {
writeScripts({ check: 'node --version' })
expect(run('verify', ...args).status).toBe(0)
expect(readReport()).toMatchObject({
scope: 'all',
status: 'passed',
steps: [{ command: 'pnpm check', exitCode: 0 }],
})
},
)

View File

@ -1,31 +0,0 @@
import { ref } from 'vue'
import { useAccess } from '../../apps/admin/src/hooks/template/useAccess'
const { state } = vi.hoisted(() => ({
state: { permissions: void 0 as unknown },
}))
vi.mock('../../apps/admin/src/store', () => ({
useSigningGetters: () => ({ getPermissions: state.permissions }),
}))
it('preserves all/any semantics and invalidates permission lookups after session changes', () => {
const permissions = ref(['users:read', 'users:write'])
state.permissions = permissions
const access = useAccess()
expect(access.permissions).toBe(permissions)
expect(access.hasPermission('users:read')).toBe(true)
expect(access.hasPermission(['users:read', 'users:write'])).toBe(true)
expect(access.hasPermission(['users:read', 'admin:write'])).toBe(false)
expect(access.hasPermission(['users:read', 'admin:write'], 'any')).toBe(true)
expect(access.hasPermission([])).toBe(true)
expect(access.hasPermission([], 'any')).toBe(false)
permissions.value.splice(1, 1)
expect(access.hasPermission('users:write')).toBe(false)
permissions.value = ['admin:write']
expect(access.hasPermission('users:read')).toBe(false)
expect(access.hasPermission('admin:write')).toBe(true)
})

View File

@ -1,16 +1,16 @@
import { createMemoryHistory, createRouter } from 'vue-router'
import { useAppNavigation } from '../../apps/admin/src/hooks/template/useAppNavigation'
import type { AppMenuOption } from '../../apps/admin/src/types'
import { useAppNavigation } from '../../src/hooks/template/useAppNavigation'
import type { AppMenuOption } from '../../src/types'
const { state, menus } = vi.hoisted(() => ({
state: { router: void 0 as ReturnType<typeof createRouter> | undefined },
menus: [{ fullPath: '/parent', children: [{ fullPath: '/target' }] }],
}))
vi.mock('../../apps/admin/src/hooks/template/useVueRouter', () => ({
vi.mock('../../src/hooks/template/useVueRouter', () => ({
useVueRouter: () => ({ router: state.router }),
}))
vi.mock('../../apps/admin/src/store', () => ({
vi.mock('../../src/store', () => ({
useMenuGetters: () => ({ getMenuOptions: { value: menus } }),
}))
@ -36,15 +36,8 @@ describe('useAppNavigation', () => {
expect(pending).toBeInstanceOf(Promise)
await pending
expect(state.router?.currentRoute.value.path).toBe('/target')
await navigationTo(
{ fullPath: '/items/4?q=one#details' } as AppMenuOption,
{
query: { page: '2' },
},
)
expect(state.router?.currentRoute.value.fullPath).toBe(
'/items/4?q=one&page=2#details',
)
await navigationTo({ fullPath: '/items/4' } as AppMenuOption)
expect(state.router?.currentRoute.value.path).toBe('/items/4')
})
it('resolves a dynamic path and preserves URL query and hash when replacing', async () => {

View File

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

View File

@ -1,11 +1,11 @@
import { useBadge } from '../../apps/admin/src/hooks/template/useBadge'
import type { AppMenuExtraOptions } from '../../apps/admin/src/router/types'
import { depthSearchAppMenu, useMenuGetters } from '../../apps/admin/src/store'
import type { AppMenuOption } from '../../apps/admin/src/types'
import { useBadge } from '../../src/hooks/template/useBadge'
import type { AppMenuExtraOptions } from '../../src/router/types'
import { depthSearchAppMenu, useMenuGetters } from '../../src/store'
import type { AppMenuOption } from '../../src/types'
import setupMiniApp from '../utils/setupMiniApp'
describe('useBadge', async () => {
await setupMiniApp(true)
await setupMiniApp()
const { show, hidden, update } = useBadge()
const { getMenuOptions } = useMenuGetters()

View File

@ -1,4 +1,4 @@
import { useContextmenuCoordinate } from '../../apps/admin/src/hooks/components/useContextmenuCoordinate'
import { useContextmenuCoordinate } from '../../src/hooks/components/useContextmenuCoordinate'
import createRefElement from '../utils/createRefElement'
import renderHook from '../utils/renderHook'

View File

@ -1,6 +1,6 @@
import dayjs from 'dayjs'
import { DEFAULT_DAYJS_LOCAL } from '../../apps/admin/src/app-config'
import { useDayjs } from '../../apps/admin/src/hooks/web/useDayjs'
import { DEFAULT_DAYJS_LOCAL } from '../../src/app-config'
import { useDayjs } from '../../src/hooks/web/useDayjs'
describe('useDayjs', () => {
const {

View File

@ -1,8 +1,19 @@
import { useDevice } from '../../apps/admin/src/hooks/web/useDevice'
import { useDevice } from '../../src/hooks/web/useDevice'
describe('useDevice', () => {
const addEventListenerSpy = vi.spyOn(window, 'addEventListener')
const matchMediaSpy = vi.spyOn(window, 'matchMedia')
const matchMediaSpy = vi
.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(() => {
addEventListenerSpy.mockClear()

View File

@ -1,5 +1,5 @@
import { toBlob, toPng } from 'html-to-image'
import { useDomToImage } from '../../apps/admin/src/hooks/web/useDomToImage'
import { useDomToImage } from '../../src/hooks/web/useDomToImage'
vi.mock('html-to-image', () => ({
toSvg: vi.fn(),

View File

@ -1,4 +1,4 @@
import { useElementFullscreen } from '../../apps/admin/src/hooks/web/useElementFullscreen'
import { useElementFullscreen } from '../../src/hooks/web/useElementFullscreen'
// Happy DOM 验证状态与样式恢复;实际布局和动画仍需在浏览器验收。
describe('useElementFullscreen', () => {
@ -121,9 +121,6 @@ it('restores original style priority and releases ownership even when manual exi
expect(element.style.width).toBe('240px')
expect(element.style.getPropertyPriority('width')).toBe('important')
expect(element.getAttribute('data-element-fullscreen')).toBe('prior')
first.enter()
expect(first.isFullscreen.value).toBe(false)
expect(element.getAttribute('data-element-fullscreen')).toBe('prior')
second.enter()
expect(second.isFullscreen.value).toBe(true)
second.exit()

View File

@ -1,11 +1,12 @@
import { ref } from 'vue'
import type { Ref } from 'vue'
import { useI18n } from '../../apps/admin/src/hooks/web/useI18n'
import { useI18n } from '../../src/hooks/web/useI18n'
const { state } = vi.hoisted(() => ({
state: {
instance: void 0 as
| {
mode: string
global: {
t: (key: string, ...args: unknown[]) => string
locale: Ref<string>
@ -15,7 +16,7 @@ const { state } = vi.hoisted(() => ({
},
}))
vi.mock('../../apps/admin/src/locales', () => ({
vi.mock('../../src/locales', () => ({
get i18n() {
return state.instance
},
@ -23,6 +24,7 @@ vi.mock('../../apps/admin/src/locales', () => ({
beforeEach(() => {
state.instance = {
mode: 'composition',
global: { t: (key) => key, locale: ref('zh-CN') },
}
})
@ -44,12 +46,12 @@ describe('useI18n namespaces', () => {
expect(hook.t('code')).toBe('hooks.code')
expectTypeOf(hook.t('code')).toEqualTypeOf<string>()
state.instance = {
mode: 'composition',
global: { t: (key) => `translated:${key}`, locale: ref('zh-CN') },
}
expect(hook.t('code')).toBe('translated:hooks.code')
hook.locale('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}`
expect(hook.t('code')).toBe('updated:hooks.code')
})
@ -60,7 +62,7 @@ it('forwards interpolation and leaves plain text and route keys untouched', asyn
state.instance!.global.t = native
const { t: translate } = useI18n()
const { t } = await import('../../apps/admin/src/hooks/template/useI18n')
const { t } = await import('../../src/hooks/template/useI18n')
expect(translate('Already readable')).toBe('Already readable')
expect(t('menu.Dashboard')).toBe('menu.Dashboard')

View File

@ -1,11 +1,8 @@
import type { LayoutInst } from 'naive-ui'
import type { Ref } from 'vue'
import {
LAYOUT_CONTENT_REF,
LAYOUT_SIDER_REF,
} from '../../apps/admin/src/app-config'
import { useContentScroll } from '../../apps/admin/src/hooks/template/useContentScroll'
import { useSiderScroll } from '../../apps/admin/src/hooks/template/useSiderScroll'
import { LAYOUT_CONTENT_REF, LAYOUT_SIDER_REF } from '../../src/app-config'
import { useContentScroll } from '../../src/hooks/template/useContentScroll'
import { useSiderScroll } from '../../src/hooks/template/useSiderScroll'
describe.each([
[useContentScroll, LAYOUT_CONTENT_REF],

View File

@ -1,7 +1,7 @@
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { nextTick } from 'vue'
import { useMaximize } from '../../apps/admin/src/hooks/template/useMaximize'
import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime'
import { useMaximize } from '../../src/hooks/template/useMaximize'
import { piniaRuntimeStore } from '../../src/store/modules/runtime'
it('shares maximize state across callers and cancels stale completion callbacks', async () => {
const pinia = createPinia()

View File

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

View File

@ -1,4 +1,4 @@
import { usePagination } from '../../apps/admin/src/hooks/web/usePagination'
import { usePagination } from '../../src/hooks/web/usePagination'
describe('usePagination', () => {
let count = 0
@ -94,25 +94,3 @@ it('resets to the first object page size and reports new values to the current c
expect(api.getCallback()).toBeUndefined()
expect(callback).toHaveBeenCalledOnce()
})
it('keeps mutable default page-size options local to each instance', () => {
const [first] = usePagination()
const [second] = usePagination()
first.value.pageSizes!.splice(0, 1, 5)
expect(second.value.pageSizes).toEqual([10, 20, 50, 100])
expect(usePagination()[0].value.pageSizes).toEqual([10, 20, 50, 100])
})
it('resets using the currently configured page sizes after replacing them', () => {
const [pagination, api] = usePagination()
pagination.value.pageSizes = [{ label: 'Twenty five', value: 25 }]
api.resetPagination()
expect(api.getPageSize()).toBe(25)
pagination.value.pageSizes = []
api.resetPagination()
expect(api.getPageSize()).toBe(10)
})

View File

@ -1,5 +1,5 @@
import print from 'print-js'
import { usePrint } from '../../apps/admin/src/hooks/web/usePrint'
import { usePrint } from '../../src/hooks/web/usePrint'
vi.mock('print-js', () => ({ default: vi.fn() }))

View File

@ -1,452 +1,184 @@
import { APP_CATCH_KEY } from '@/app-config'
import { useSiderBar } from '@/hooks/template/useSiderBar'
import { setupI18n } from '@/locales'
import { permissionRouter } from '@/router/utils/permission'
import { piniaKeepAliveStore } from '@/store/modules/keep-alive'
import { piniaMenuStore } from '@/store/modules/menu'
import { getCatchMenuTagOptions } from '@/store/modules/menu/utils'
import { piniaSettingStore } from '@/store/modules/setting'
import { piniaSigningStore } from '@/store/modules/signing'
import { setStorage } from '@/utils/cache'
import { flushPromises, mount } from '@vue/test-utils'
import type { VueWrapper } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { defineComponent, h } from 'vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import type { Router } from 'vue-router'
import { useAppRoot } from '../../src/hooks/template/useAppRoot'
import { useSiderBar } from '../../src/hooks/template/useSiderBar'
import { useVueRouter } from '../../src/hooks/web/useVueRouter'
import { useMenuActions, useMenuGetters } from '../../src/store'
import type { AppMenuOption, MenuTagOptions } from '../../src/types/modules/app'
import setupMiniApp from '../utils/setupMiniApp'
const state = vi.hoisted(() => ({
router: null as unknown,
routes: [] as unknown[],
}))
describe('useSiderBar', async () => {
await setupMiniApp()
vi.mock('../../apps/admin/src/hooks/template/useVueRouter', () => ({
useVueRouter: () => ({ router: state.router }),
}))
vi.mock('../../apps/admin/src/router/app-route-modules', () => ({
getAppRawRoutes: () => state.routes,
appExpandRoutes: () => state.routes,
}))
const { setMenuTagOptions, resolveOption } = useMenuActions()
const {
close,
closeAll,
closeRight,
closeLeft,
closeOther,
getCurrentTagIndex,
checkCloseRight,
checkCloseLeft,
} = useSiderBar()
let pinia: ReturnType<typeof createPinia>
let router: Router
let wrapper: VueWrapper
let menu: ReturnType<typeof piniaMenuStore>
let actions: ReturnType<typeof useSiderBar>
const updateMenuTagOptions = () => {
const { router } = useVueRouter()
const routes = router.getRoutes() as unknown as AppMenuOption[]
beforeEach(async () => {
localStorage.clear()
sessionStorage.clear()
const component = { render: () => h('div') }
const business = [
{ path: '/reports', name: 'Reports', component, meta: { keepAlive: true } },
{ path: '/orders', name: 'Orders', component, meta: {} },
{
path: '/private',
name: 'Private',
component,
meta: { role: ['admin'], keepAlive: true },
},
]
state.routes = business
router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', name: 'RLogin', component },
{
path: '/welcome',
name: 'RWelcome',
component,
meta: { i18nKey: 'workspaceStates.welcome.title' },
},
{
path: '/403',
name: 'ErrorPage403',
component,
meta: { i18nKey: 'workspaceStates.forbidden.title' },
},
{ path: '/404', name: 'ErrorPage404', component },
{ path: '/500', name: 'ErrorPage500', component },
{ path: '/:catchAll(.*)', name: 'RNotFound', redirect: '/404' },
...business,
],
})
state.router = router
pinia = createPinia()
setActivePinia(pinia)
piniaSigningStore().signingCallback = {
id: 'one',
name: 'Tester',
role: 'admin',
routes.forEach((curr) =>
setMenuTagOptions(
resolveOption({
...curr,
fullPath: curr.path,
}),
true,
),
)
}
setStorage(APP_CATCH_KEY.token, 'token', 'localStorage')
setStorage(APP_CATCH_KEY.appMenuTagOptions, [{ fullPath: '/dashboard' }])
setStorage(APP_CATCH_KEY.appMenuKey, '/dashboard')
permissionRouter(router)
await router.push('/welcome')
wrapper = mount(
defineComponent({
setup() {
menu = piniaMenuStore()
actions = useSiderBar()
return () => h('div')
},
}),
{ global: { plugins: [pinia, router] } },
)
await flushPromises()
})
it('should close target tag', async () => {
updateMenuTagOptions()
afterEach(() => {
wrapper.unmount()
disposePinia(pinia)
router.options.history.destroy()
})
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
const [dashboard] = getMenuOptions.value
const beforeIndex = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === dashboard.fullPath,
)
it('starts with no active business page and never injects a missing cached dashboard', () => {
expect(menu.menuTagOptions).toEqual([])
expect(menu.menuKey).toBeNull()
expect(menu.currentMenuOption).toBeNull()
expect(menu.breadcrumbOptions).toEqual([])
expect(router.currentRoute.value.path).toBe('/welcome')
expect(menu.options.map(({ fullPath }) => fullPath)).toEqual([
'/reports',
'/orders',
'/private',
])
})
close(dashboard.fullPath)
it('closes the final business tab, even when it is the legacy root preference', async () => {
piniaSettingStore().updateSettingState('appRootRoute', {
path: '/reports',
name: 'Reports',
await nextTick()
const afterIndex = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === dashboard.fullPath,
)
expect(beforeIndex).not.toBe(afterIndex)
})
await router.push('/reports?sort=asc#summary')
await flushPromises()
expect(actions.getCurrentTagIndex()).toBe(0)
expect(piniaKeepAliveStore().keepAliveInclude).toEqual(['Reports'])
await actions.close(0)
await flushPromises()
expect(menu.menuTagOptions).toEqual([])
expect(menu.menuKey).toBeNull()
expect(menu.currentMenuOption).toBeNull()
expect(piniaKeepAliveStore().keepAliveInclude).toEqual([])
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('stores one tag per pathname and restores its latest query and hash', async () => {
await router.push('/reports?sort=asc#first')
await router.push('/reports?sort=desc#summary')
await router.push('/orders')
await flushPromises()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/reports?sort=desc#summary',
'/orders',
])
await actions.close('/orders')
await flushPromises()
expect(router.currentRoute.value.fullPath).toBe('/reports?sort=desc#summary')
expect(menu.menuKey).toBe('/reports')
expect(actions.getCurrentTagIndex()).toBe(0)
})
it('should close all tags', async () => {
updateMenuTagOptions()
it('closes left, right and other tabs without protecting any business path', async () => {
for (const path of ['/reports', '/orders', '/private'])
await router.push(path)
const { getMenuTagOptions } = useMenuGetters()
await flushPromises()
expect(actions.checkCloseLeft('/orders')).toBe(true)
expect(actions.checkCloseRight('/orders')).toBe(true)
await actions.closeRight('/orders')
await flushPromises()
expect(router.currentRoute.value.path).toBe('/orders')
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/reports',
'/orders',
])
await actions.closeLeft('/orders')
await router.push('/reports')
await actions.closeOther('/orders')
await flushPromises()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/orders',
])
expect(router.currentRoute.value.path).toBe('/orders')
})
closeAll()
it('closes all tags independently of missing or unauthorized root preferences', async () => {
await router.push('/reports')
await router.push('/orders')
piniaSettingStore().updateSettingState('appRootRoute', {
path: '/deleted-home',
await nextTick()
const afterLength = getMenuTagOptions.value.length
expect(afterLength).toBe(1)
})
await actions.closeAll()
await flushPromises()
expect(menu.menuTagOptions).toEqual([])
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)
it('should close right tags', async () => {
updateMenuTagOptions()
const cachedPages = piniaKeepAliveStore().keepAliveInclude
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
const [dashboard] = getMenuOptions.value
const beforeIndex = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === dashboard.fullPath,
)
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()
expect(!!getMenuTagOptions.value[beforeIndex + 1]).toBe(true)
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')
closeRight(dashboard.fullPath)
const settings = piniaSettingStore()
await nextTick()
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',
])
})
const afterIndex = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === dashboard.fullPath,
)
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)
expect(getMenuTagOptions.value[afterIndex + 1]).toBe(void 0)
})
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')
it('should close left tags', async () => {
updateMenuTagOptions()
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')
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
const [dashboard] = getMenuOptions.value
piniaSettingStore().updateSettingState('menuTagFixed', false)
await actions.close('/orders')
expect(menu.menuTagOptions).toEqual([])
expect(router.currentRoute.value.path).toBe('/welcome')
})
closeLeft(dashboard.fullPath)
it('keeps status routes out of tabs and clears active business navigation', async () => {
await router.push('/reports')
await nextTick()
for (const path of ['/welcome', '/403', '/404', '/500']) {
await router.push(path)
await flushPromises()
expect(menu.currentMenuOption).toBeNull()
expect(menu.menuKey).toBeNull()
expect(menu.breadcrumbOptions).toEqual([])
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/reports',
])
}
})
const afterIndex = getMenuTagOptions.value.findIndex(
(curr) => curr.fullPath === dashboard.fullPath,
)
it('removes shortcuts that lead through or to a route the current role cannot open', async () => {
const shortcuts = [
{ path: '/private-link', redirect: '/private', meta: {} },
{
path: '/admin-link',
redirect: '/reports',
meta: { role: ['admin'] },
},
{ path: '/via-admin', redirect: '/admin-link', meta: {} },
{ path: '/open-link', redirect: '/reports', meta: {} },
]
expect(getMenuTagOptions.value[afterIndex - 1]).toBe(void 0)
})
for (const shortcut of shortcuts) router.addRoute(shortcut)
it('should get current tag index', async () => {
updateMenuTagOptions()
state.routes = [...state.routes, ...shortcuts]
await menu.setupAppMenu()
expect(menu.options.map(({ fullPath }) => fullPath)).toContain('/via-admin')
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
const [dashboard] = getMenuOptions.value
piniaSigningStore().signingCallback.role = 'member'
await flushPromises()
expect(menu.options.map(({ fullPath }) => fullPath)).toEqual([
'/reports',
'/orders',
'/open-link',
])
})
const index = getMenuOptions.value.findIndex(
(curr) => curr.fullPath === dashboard.fullPath,
)
it('closes the 403 view back to an allowed tab without storing a denied tab', async () => {
piniaSigningStore().signingCallback.role = 'member'
await router.push('/reports?sort=desc#summary')
await router.push('/private')
await flushPromises()
expect(getCurrentTagIndex()).toBe(index)
})
expect(router.currentRoute.value.path).toBe('/403')
expect(actions.getCurrentTagIndex()).toBe(-1)
await actions.closeForbiddenPage()
await flushPromises()
it('should close other tags', async () => {
updateMenuTagOptions()
expect(router.currentRoute.value.fullPath).toBe('/reports?sort=desc#summary')
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/reports?sort=desc#summary',
])
})
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
const [dashboard] = getMenuOptions.value
it('closes a directly opened 403 to the workspace with no business tags', async () => {
await router.push('/403')
await actions.closeForbiddenPage()
await flushPromises()
closeOther(dashboard.fullPath)
expect(router.currentRoute.value.path).toBe('/welcome')
expect(menu.menuTagOptions).toEqual([])
})
await nextTick()
it('removes revoked tags and cached views without choosing another active page', async () => {
await router.push('/reports')
await router.push('/private?mode=edit#section')
menu.toggleMenuTagFixed('/private?mode=edit#section')
piniaSigningStore().signingCallback.role = 'member'
await flushPromises()
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
'/reports',
])
expect(piniaKeepAliveStore().keepAliveInclude).toEqual(['Reports'])
expect(menu.currentMenuOption).toBeNull()
expect(router.currentRoute.value.path).toBe('/403')
expect(router.currentRoute.value.query.from).toBe(
'/private?mode=edit#section',
)
})
expect(getMenuTagOptions.value[0].fullPath).toBe(dashboard.fullPath)
expect(getMenuTagOptions.value.length).toBe(1)
})
it('clears account-owned tabs without recreating the still-visible page during logout', async () => {
await router.push('/reports')
piniaSigningStore().signingCallback = {} as never
await flushPromises()
expect(menu.menuTagOptions).toEqual([])
expect(menu.currentMenuOption).toBeNull()
expect(piniaKeepAliveStore().keepAliveInclude).toEqual([])
})
it('check menuTagOptions left or right can close', async () => {
updateMenuTagOptions()
it('updates neutral and status document titles when the language changes', async () => {
await setupI18n(wrapper.vm.$.appContext.app)
const settings = piniaSettingStore()
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
const [f, s] = getMenuOptions.value
settings.updateLocale('zh-CN')
await router.push('/403')
await flushPromises()
expect(document.title).toContain('暂时无法访问此页面')
settings.updateLocale('en-US')
await flushPromises()
expect(document.title).toContain('This page is not available to you')
await router.push('/welcome')
await flushPromises()
expect(document.title).toContain('Ready for your next task')
settings.updateLocale('zh-CN')
await flushPromises()
expect(document.title).toContain('工作区已就绪')
})
closeRight(f.fullPath)
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']
await nextTick()
for (const path of paths) await router.push(path)
const canClose = checkCloseRight(f.fullPath)
if (operation === 'closeLeft') await router.push('/reports')
expect(canClose).toBe(false)
const before = {
paths: menu.menuTagOptions.map((tag) => tag.fullPath),
saved: getCatchMenuTagOptions(),
cached: [...piniaKeepAliveStore().keepAliveInclude],
}
updateMenuTagOptions()
router.beforeEach(() => false)
closeLeft(f.fullPath)
if (operation === 'closeAll') await actions.closeAll()
else if (operation === 'close') await actions.close('/reports')
else
await actions[operation](
operation === 'closeLeft' ? '/private' : '/orders',
await nextTick()
const canCloseLeft = checkCloseLeft(f.fullPath)
expect(canCloseLeft).toBe(false)
updateMenuTagOptions()
expect(checkCloseRight(s.fullPath)).toBe(true)
expect(checkCloseLeft(s.fullPath)).toBe(true)
})
it('keeps existing tags if the configured home route is no longer registered', () => {
updateMenuTagOptions()
const { getMenuTagOptions } = useMenuGetters()
const { getRootRoute, setRootRoute } = useAppRoot()
const currentRoot = { ...getRootRoute.value }
const currentTags = getMenuTagOptions.value.map((item) => item.fullPath)
try {
setRootRoute({ path: '/deleted-home-route' })
closeAll()
expect(getMenuTagOptions.value.map((item) => item.fullPath)).toEqual(
currentTags,
)
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
} finally {
setRootRoute(currentRoot)
}
})
const close = actions.closeAll()
await entered.promise
expect(menu.menuTagOptions).toHaveLength(2)
menu.toggleMenuTagFixed('/orders')
gate.resolve(true)
await close
expect(router.currentRoute.value.path).toBe('/welcome')
expect(menu.menuTagOptions.map((tag) => tag.fullPath)).toEqual(['/orders'])
expect(getCatchMenuTagOptions().map((tag) => tag.fullPath)).toEqual([
'/orders',
])
})

View File

@ -1,6 +1,6 @@
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import { useSpinning } from '../../apps/admin/src/hooks/template/useSpinning'
import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime'
import { useSpinning } from '../../src/hooks/template/useSpinning'
import { piniaRuntimeStore } from '../../src/store/modules/runtime'
describe('useSpinning', () => {
let pinia: ReturnType<typeof createPinia>

View File

@ -1,8 +1,5 @@
import { useTheme } from '../../apps/admin/src/hooks/template/useTheme'
import {
useSettingActions,
useSettingGetters,
} from '../../apps/admin/src/store'
import { useTheme } from '../../src/hooks/template/useTheme'
import { useSettingGetters } from '../../src/store'
import setupMiniApp from '../utils/setupMiniApp'
describe('useTheme', async () => {
@ -49,40 +46,18 @@ describe('useTheme', async () => {
expect(__lightThemeLabel).toBe('Light')
})
it('keeps a reused hook reactive to language and theme changes', () => {
const { updateLocale } = useSettingActions()
const previousLocale = useSettingGetters().getLocaleLanguage.value
try {
darkTheme()
updateLocale('en-US')
expect(getAppTheme().themeI18nLabel).toBe('Dark')
updateLocale('zh-CN')
expect(getAppTheme().themeI18nLabel).toBe('暗色')
lightTheme()
expect(getAppTheme()).toMatchObject({
theme: false,
themeLabel: 'Light',
themeI18nLabel: '明亮',
})
} finally {
updateLocale(previousLocale)
lightTheme()
}
})
it('selects auto mode and applies the system color preference', () => {
const dark = window.matchMedia('(prefers-color-scheme: dark)').matches
const spy = vi
.spyOn(window, 'matchMedia')
.mockReturnValue({ matches: true } as MediaQueryList)
try {
syncSystemTheme()
expect(getAppTheme()).toMatchObject({
theme: dark,
themeLabel: dark ? 'Dark' : 'Light',
})
expect(getAppTheme()).toMatchObject({ theme: true, themeLabel: 'Dark' })
expect(useSettingGetters().getAppThemeStr.value).toBe('auto')
} finally {
lightTheme()
spy.mockRestore()
}
})
})

View File

@ -1,5 +1,5 @@
import { useVueRouter } from '../../apps/admin/src/hooks/web/useVueRouter'
import { router } from '../../apps/admin/src/router'
import { useVueRouter } from '../../src/hooks/web/useVueRouter'
import { router } from '../../src/router'
it('shares the live router outside setup and exposes the current route after navigation', async () => {
const a = useVueRouter()

View File

@ -1,5 +1,5 @@
import { useWatermark } from '../../apps/admin/src/hooks/template/useWatermark'
import { useSettingGetters } from '../../apps/admin/src/store'
import { useWatermark } from '../../src/hooks/template/useWatermark'
import { useSettingGetters } from '../../src/store'
import setupMiniApp from '../utils/setupMiniApp'
describe('useWatermark', async () => {

View File

@ -16,7 +16,7 @@ import { pathToFileURL } from 'node:url'
it('generates usable types and package imports after additions, moves and deletions', () => {
const root = mkdtempSync(join(tmpdir(), 'ray-icon-generation-'))
const script = join(root, 'scripts/icons.mjs')
const manifest = join(root, 'src/manifest.ts')
const manifest = join(root, 'src/icons/manifest.ts')
const run = (...args: string[]) =>
execFileSync(process.execPath, [script, ...args], {
cwd: root,
@ -38,12 +38,12 @@ it('generates usable types and package imports after additions, moves and deleti
try {
mkdirSync(join(root, 'scripts'), { recursive: true })
mkdirSync(join(root, 'src/action'), { recursive: true })
mkdirSync(join(root, 'src/icons/action'), { recursive: true })
symlinkSync(resolve('node_modules'), join(root, 'node_modules'), 'junction')
copyFileSync('packages/icons/scripts/icons.mjs', script)
copyFileSync('scripts/icons.mjs', script)
copyFileSync('.prettierrc.cjs', join(root, '.prettierrc.cjs'))
writeFileSync(join(root, 'package.json'), '{"type":"module"}')
writeFileSync(join(root, 'src/action/first.svg'), '<svg/>')
writeFileSync(join(root, 'src/icons/action/first.svg'), '<svg/>')
run()
run('--check')
expect(read()).toEqual({
@ -51,18 +51,18 @@ it('generates usable types and package imports after additions, moves and deleti
sprites: { action: '/__spritemap-action' },
})
renameSync(
join(root, 'src/action/first.svg'),
join(root, 'src/action/renamed.svg'),
join(root, 'src/icons/action/first.svg'),
join(root, 'src/icons/action/renamed.svg'),
)
run()
expect(read().names).toEqual(['action/renamed'])
mkdirSync(join(root, 'src/business-tools'), { recursive: true })
writeFileSync(join(root, 'src/business-tools/new.svg'), '<svg/>')
mkdirSync(join(root, 'src/icons/business-tools'), { recursive: true })
writeFileSync(join(root, 'src/icons/business-tools/new.svg'), '<svg/>')
expect(() => run('--check')).toThrow()
run()
expect(read().sprites['business-tools']).toBe('/__spritemap-business-tools')
expect(read().names).toContain('business-tools/new')
rmSync(join(root, 'src/action'), { recursive: true })
rmSync(join(root, 'src/icons/action'), { recursive: true })
run()
expect(read()).toEqual({
names: ['business-tools/new'],

View File

@ -2,14 +2,10 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { IconProps } from '../../apps/admin/src/components/RIcon'
import {
iconNames,
isIconName,
resolveIconName,
} from '../../apps/admin/src/icons'
import type { IconName } from '../../apps/admin/src/icons'
import { iconNameFromPath, scanIcons } from '../../scripts/icons.mjs'
import type { IconProps } from '../../src/components/RIcon'
import { iconNames, isIconName, resolveIconName } from '../../src/icons'
import type { IconName } from '../../src/icons'
describe('namespaced icons', () => {
it('keeps the generated registry synchronized and exposes strict component props', () => {
@ -47,9 +43,6 @@ describe('namespaced icons', () => {
it('resolves existing persisted bare names without accepting unknown paths', () => {
expect(resolveIconName('ray')).toBe('logo/ray')
expect(resolveIconName('directional/resize_h')).toBe('directional/resize_h')
expect(isIconName('logo/office')).toBe(false)
expect(resolveIconName('office')).toBe('navigation/table')
expect(resolveIconName('illustration/login_bg')).toBe('navigation/other')
expect(resolveIconName('unknown')).toBeUndefined()
expect(resolveIconName('../ray')).toBeUndefined()
})

View File

@ -1,45 +0,0 @@
import { avatarDropdownClick } from '../../apps/admin/src/layout/components/SiderBar/shared'
const { logout, createDialog, showError, push } = vi.hoisted(() => ({
logout: vi.fn(),
createDialog: vi.fn(),
showError: vi.fn(),
push: vi.fn(),
}))
vi.mock('@/store', () => ({
useSigningActions: () => ({ logout }),
useSettingActions: () => ({ updateSettingState: vi.fn() }),
}))
vi.mock('@/hooks', () => ({ useI18n: () => ({ t: (key: string) => key }) }))
vi.mock('@/router', () => ({ router: { push } }))
beforeEach(() => {
vi.clearAllMocks()
window.$dialog = { create: createDialog } as unknown as typeof window.$dialog
window.$message = { error: showError } as unknown as typeof window.$message
})
it('confirms sign-out with the active primary color before ending the session', async () => {
logout.mockResolvedValue(void 0)
await avatarDropdownClick('logout')
expect(logout).not.toHaveBeenCalled()
const dialog = createDialog.mock.calls[0]![0]
expect(dialog).toMatchObject({
title: 'signOut',
showIcon: false,
positiveButtonProps: { type: 'primary' },
})
expect(await dialog.onPositiveClick()).toBe(true)
expect(logout).toHaveBeenCalledOnce()
})
it('keeps the confirmation open and reports a failed sign-out', async () => {
logout.mockRejectedValue(new Error('offline'))
await avatarDropdownClick('logout')
expect(await createDialog.mock.calls[0]![0].onPositiveClick()).toBe(false)
expect(showError).toHaveBeenCalledWith('signOutFailed')
})

View File

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

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