docs: add English VitePress documentation

This commit is contained in:
XiaoDaiGua-Ray 2026-11-19 16:05:56 +08:00
parent 9a6851b858
commit b5ccd180ef
No known key found for this signature in database
64 changed files with 3941 additions and 208 deletions

View File

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

View File

@ -1,19 +1,72 @@
import vueJsx from '@vitejs/plugin-vue-jsx'
import { defineConfig, postcssIsolateStyles } from 'vitepress'
import { writeLegacyRedirects } from './legacy.mts'
import { sidebar } from './sidebar.mts'
import { createSidebar } from './sidebar.mts'
import { demo, repository, version } from './source.mts'
const base = '/ray-template/docs/'
const requestedRef = process.env.RAY_TEMPLATE_SOURCE_REF ?? ''
const sourceRef = /^[0-9a-f]{40}$/.test(requestedRef) ? requestedRef : 'main'
function createNav(english: boolean) {
const prefix = english ? '/en' : ''
return [
{
text: english ? 'Guide' : '指南',
link: prefix + '/guide/start',
activeMatch: '^' + prefix + '/guide/',
},
{
text: english ? 'Architecture' : '架构',
link: prefix + '/guide/architecture',
},
{ text: english ? 'Migration' : '版本分界', link: prefix + '/migration' },
{
text: english ? 'API Reference' : 'API 参考',
link: prefix + '/reference/',
activeMatch: '^' + prefix + '/reference/',
},
{ text: 'Ray Admin', link: demo },
]
}
export default defineConfig({
base,
title: 'Ray Template',
titleTemplate: ':title · Ray Template 文档',
description: `Ray Template ${version} 的 Monorepo 架构、版本分界、组件与交互示例。`,
lang: 'zh-CN',
locales: {
root: {
label: '简体中文',
themeConfig: {
nav: createNav(false),
sidebar: createSidebar(false),
outline: { label: '本页目录', level: [2, 3] },
skipToContentLabel: '跳转到正文',
docFooter: { prev: '上一页', next: '下一页' },
returnToTopLabel: '回到顶部',
sidebarMenuLabel: '文档目录',
darkModeSwitchLabel: '主题',
lightModeSwitchTitle: '切换到浅色',
darkModeSwitchTitle: '切换到深色',
langMenuLabel: '切换语言',
footer: { copyright: '© 2022–至今 Ray · MIT License' },
},
},
en: {
label: 'English',
lang: 'en-US',
titleTemplate: ':title · Ray Template Docs',
description: `Architecture, migration, components, and interactive examples for Ray Template ${version}.`,
themeConfig: {
nav: createNav(true),
sidebar: createSidebar(true),
footer: { copyright: '© 2022–present Ray · MIT License' },
},
},
},
srcExclude: ['README.md', 'AGENTS.md'],
vite: {
plugins: [vueJsx()],
@ -39,47 +92,29 @@ export default defineConfig({
themeConfig: {
logo: { src: '/ray-mark.svg', alt: '' },
siteTitle: 'Ray Template',
nav: [
{ text: '指南', link: '/guide/start', activeMatch: '^/guide/' },
{ text: '架构', link: '/guide/architecture' },
{ text: '版本分界', link: '/migration' },
{
text: 'API 参考',
link: '/reference/',
activeMatch: '^/reference/',
},
{ text: 'Ray Admin', link: demo },
],
sidebar,
outline: { label: '本页目录', level: [2, 3] },
outline: { level: [2, 3] },
search: {
provider: 'local',
options: {
translations: {
button: { buttonText: '搜索文档', buttonAriaLabel: '搜索文档' },
modal: {
noResultsText: '未找到相关内容',
resetButtonTitle: '清除搜索',
footer: {
selectText: '打开',
navigateText: '切换',
closeText: '关闭',
locales: {
root: {
translations: {
button: { buttonText: '搜索文档', buttonAriaLabel: '搜索文档' },
modal: {
noResultsText: '未找到相关内容',
resetButtonTitle: '清除搜索',
footer: {
selectText: '打开',
navigateText: '切换',
closeText: '关闭',
},
},
},
},
},
},
},
skipToContentLabel: '跳转到正文',
docFooter: { prev: '上一页', next: '下一页' },
returnToTopLabel: '回到顶部',
sidebarMenuLabel: '文档目录',
darkModeSwitchLabel: '主题',
lightModeSwitchTitle: '切换到浅色',
darkModeSwitchTitle: '切换到深色',
socialLinks: [{ icon: 'github', link: repository }],
footer: {
copyright: '© 2022–至今 Ray · MIT License',
},
},
markdown: {
config(md) {
@ -88,6 +123,11 @@ export default defineConfig({
md.renderer.rules.link_open = (tokens, index, options, env, renderer) => {
const token = tokens[index]
const href = token.attrGet('href')
const label = token.attrGet('aria-label')
if (token.attrGet('class') === 'header-anchor' && label) {
token.attrSet('aria-label', label.replace(/\s+\{#[^}]+\}(?="$)/u, ''))
}
for (const kind of ['blob', 'tree']) {
const prefix = `${repository}/${kind}/main`

View File

@ -1,96 +1,204 @@
import type { DefaultTheme } from 'vitepress'
const entry = (text: string, link: string): DefaultTheme.SidebarItem => ({
text,
link,
})
export function createSidebar(english: boolean): DefaultTheme.Sidebar {
const prefix = english ? '/en' : ''
const label = (zh: string, en: string) => (english ? en : zh)
const entry = (
zh: string,
en: string,
path: string,
): DefaultTheme.SidebarItem => ({
text: label(zh, en),
link: prefix + path,
})
const guide = [
{
text: '入门',
items: [
entry('快速开始', '/guide/start'),
entry('发行版本与快速启动', '/guide/distributions'),
entry('v6 Monorepo 架构', '/guide/architecture'),
entry('v5 与 v6 的版本分界', '/migration'),
entry('第一个业务页面', '/guide/first-page'),
],
},
{
text: '开发指南',
items: [
entry('路由、菜单与权限', '/guide/routing'),
entry('应用布局与状态', '/guide/layout'),
entry('接口、取消与 Mock', '/guide/requests'),
entry('服务端接入与标准契约', '/guide/backend'),
entry('主题与国际化', '/guide/appearance'),
entry('工程检查与部署', '/guide/tooling'),
],
},
entry('API 参考', '/reference/'),
]
const guide = [
{
text: label('入门', 'Get started'),
items: [
entry('快速开始', 'Quick start', '/guide/start'),
entry(
'发行版本与快速启动',
'Source distributions',
'/guide/distributions',
),
entry(
'v6 Monorepo 架构',
'v6 Monorepo Architecture',
'/guide/architecture',
),
entry('v5 与 v6 的版本分界', 'Moving from v5 to v6', '/migration'),
entry(
'第一个业务页面',
'Your first business page',
'/guide/first-page',
),
],
},
{
text: label('开发指南', 'Development'),
items: [
entry(
'路由、菜单与权限',
'Routes, menus, and permissions',
'/guide/routing',
),
entry('应用布局与状态', 'Layout and state', '/guide/layout'),
entry(
'接口、取消与 Mock',
'Requests, cancellation, and mocks',
'/guide/requests',
),
entry('服务端接入与标准契约', 'Backend integration', '/guide/backend'),
entry('主题与国际化', 'Themes and localization', '/guide/appearance'),
entry('工程检查与部署', 'Checks and deployment', '/guide/tooling'),
],
},
entry('API 参考', 'API Reference', '/reference/'),
]
const reference = [
entry('API 参考总览', '/reference/'),
{
...entry('组件', '/reference/components'),
collapsed: true,
items: [
entry('TablePro', '/reference/table-pro'),
entry('TablePro 在线示例', '/reference/table-pro-examples'),
entry('RForm 与 useForm', '/reference/components/form'),
entry('RModal', '/reference/components/modal'),
entry('RChart 与 useChart', '/reference/components/chart'),
entry('RFlow 与 useFlow', '/reference/components/flow'),
entry('RCollapseGrid', '/reference/components/collapse-grid'),
entry('RSegment', '/reference/components/segment'),
entry('RMoreDropdown', '/reference/components/more-dropdown'),
entry('RIframe', '/reference/components/iframe'),
entry('RBarcode', '/reference/components/barcode'),
entry('RDraggableCard', '/reference/components/draggable-card'),
entry('RTransitionComponent', '/reference/components/route-transition'),
entry('RIcon 与 SVG 图标', '/reference/icons'),
entry('二维码', '/reference/components/qr-code'),
entry('应用组件与 Provider', '/reference/components/app'),
],
},
{
...entry('Hooks', '/reference/hooks'),
collapsed: true,
items: [
entry('导航与菜单', '/reference/hooks/navigation'),
entry('布局与滚动', '/reference/hooks/layout'),
entry('主题、语言和水印', '/reference/hooks/appearance'),
entry('分页与右键菜单', '/reference/hooks/interaction'),
entry('窗口、全屏和日期', '/reference/hooks/browser'),
entry('DOM 截图与打印', '/reference/hooks/output'),
],
},
entry('指令', '/reference/directives'),
{
...entry('Store', '/reference/store'),
collapsed: true,
items: [
entry('Setting', '/reference/store/setting'),
entry('Menu 与 KeepAlive', '/reference/store/navigation'),
entry('Runtime 与 Lock Screen', '/reference/store/runtime'),
entry('Signing', '/reference/store/signing'),
],
},
{
...entry('工具函数', '/reference/utils'),
collapsed: true,
items: [
entry('基础、日期和数值', '/reference/utils/core'),
entry('缓存与兼容加密', '/reference/utils/storage'),
entry('Vue 与浏览器工具', '/reference/utils/browser'),
],
},
entry('应用配置', '/reference/configuration'),
entry('文档与源码版本', '/reference/source'),
]
const reference = [
entry('API 参考总览', 'API Reference Overview', '/reference/'),
{
...entry('组件', 'Components', '/reference/components'),
collapsed: true,
items: [
entry('TablePro', 'TablePro', '/reference/table-pro'),
entry(
'TablePro 在线示例',
'TablePro Live Examples',
'/reference/table-pro-examples',
),
entry(
'RForm 与 useForm',
'RForm and useForm',
'/reference/components/form',
),
entry('RModal', 'RModal', '/reference/components/modal'),
entry(
'RChart 与 useChart',
'RChart and useChart',
'/reference/components/chart',
),
entry(
'RFlow 与 useFlow',
'RFlow and useFlow',
'/reference/components/flow',
),
entry(
'RCollapseGrid',
'RCollapseGrid',
'/reference/components/collapse-grid',
),
entry('RSegment', 'RSegment', '/reference/components/segment'),
entry(
'RMoreDropdown',
'RMoreDropdown',
'/reference/components/more-dropdown',
),
entry('RIframe', 'RIframe', '/reference/components/iframe'),
entry('RBarcode', 'RBarcode', '/reference/components/barcode'),
entry(
'RDraggableCard',
'RDraggableCard',
'/reference/components/draggable-card',
),
entry(
'RTransitionComponent',
'RTransitionComponent',
'/reference/components/route-transition',
),
entry('RIcon 与 SVG 图标', 'RIcon and SVG Icons', '/reference/icons'),
entry('二维码', 'QR Codes', '/reference/components/qr-code'),
entry(
'应用组件与 Provider',
'App Components and Providers',
'/reference/components/app',
),
],
},
{
...entry('Hooks', 'Hooks', '/reference/hooks'),
collapsed: true,
items: [
entry(
'导航与菜单',
'Navigation and Menus',
'/reference/hooks/navigation',
),
entry('布局与滚动', 'Layout and Scrolling', '/reference/hooks/layout'),
entry(
'主题、语言和水印',
'Themes, Language, and Watermarks',
'/reference/hooks/appearance',
),
entry(
'分页与右键菜单',
'Pagination and Context Menus',
'/reference/hooks/interaction',
),
entry(
'窗口、全屏和日期',
'Viewport, Fullscreen, and Dates',
'/reference/hooks/browser',
),
entry(
'DOM 截图与打印',
'DOM Capture and Printing',
'/reference/hooks/output',
),
],
},
entry('指令', 'Directives', '/reference/directives'),
{
...entry('Store', 'Stores', '/reference/store'),
collapsed: true,
items: [
entry('Setting', 'Settings', '/reference/store/setting'),
entry(
'Menu 与 KeepAlive',
'Menu and KeepAlive',
'/reference/store/navigation',
),
entry(
'Runtime 与 Lock Screen',
'Runtime and Lock Screen',
'/reference/store/runtime',
),
entry('Signing', 'Signing', '/reference/store/signing'),
],
},
{
...entry('工具函数', 'Utilities', '/reference/utils'),
collapsed: true,
items: [
entry(
'基础、日期和数值',
'Core, Dates, and Numbers',
'/reference/utils/core',
),
entry(
'缓存与兼容加密',
'Storage and Legacy Encryption',
'/reference/utils/storage',
),
entry(
'Vue 与浏览器工具',
'Vue and Browser Utilities',
'/reference/utils/browser',
),
],
},
entry('应用配置', 'Application Configuration', '/reference/configuration'),
entry(
'文档与源码版本',
'Documentation and Source Versions',
'/reference/source',
),
]
export const sidebar: DefaultTheme.Sidebar = {
'/reference/': reference,
'/': guide,
return {
[prefix + '/reference/']: reference,
[prefix + '/']: guide,
}
}

View File

@ -4,21 +4,26 @@
<div>
<h1>Ray Template</h1>
<p class="ray-lead">
v{{ version }} 将 Ray
Admin、官网文档和共享包放在同一个工作区。可在文档里直接体验真实组件。
v{{ version }}
{{
label(
'将 Ray Admin、官网文档和共享包放在同一个工作区。可在文档里直接体验真实组件。',
'puts Ray Admin, the documentation site, and shared packages in one workspace. Try the components directly in the docs.',
)
}}
</p>
<div class="ray-actions">
<a class="ray-start" :href="withBase('/guide/start.html')"
>快速开始</a
>
<a class="ray-migrate" :href="withBase('/migration.html')"
>v5 与 v6 的版本分界</a
>
<a class="ray-start" :href="docsLink('/guide/start.html')">
{{ label('快速开始', 'Quick start') }}
</a>
<a class="ray-migrate" :href="docsLink('/migration.html')">
{{ label('v5 与 v6 的版本分界', 'Moving from v5 to v6') }}
</a>
</div>
</div>
<section class="ray-map" aria-labelledby="ray-map-title">
<h2 id="ray-map-title">v6 工作区</h2>
<h2 id="ray-map-title">{{ label('v6 工作区', 'v6 workspace') }}</h2>
<svg class="ray-orbit" viewBox="0 0 200 200" aria-hidden="true">
<circle cx="100" cy="100" r="65" />
<circle cx="100" cy="100" r="89" stroke-dasharray="3 6" />
@ -27,7 +32,7 @@
</svg>
<ul>
<li v-for="module in modules" :key="module.href">
<a :href="withBase(module.href)">
<a :href="docsLink(module.href)">
<span>{{ module.title }}</span>
<code>{{ module.name }}</code>
</a>
@ -37,12 +42,12 @@
</header>
<section class="ray-paths" aria-labelledby="ray-paths-title">
<h2 id="ray-paths-title">常用文档</h2>
<h2 id="ray-paths-title">{{ label('常用文档', 'Popular guides') }}</h2>
<ul>
<li v-for="(card, index) in cards" :key="card.href">
<a
class="ray-path"
:href="withBase(card.href)"
:href="docsLink(card.href)"
:aria-labelledby="`ray-path-title-${index}`"
:aria-describedby="`ray-path-summary-${index}`"
>
@ -67,18 +72,30 @@
<section class="ray-showcase" aria-labelledby="ray-showcase-title">
<div>
<h2 id="ray-showcase-title">TablePro 自适应高度</h2>
<p>表格填满可用高度,数据在表内滚动。</p>
<h2 id="ray-showcase-title">
{{ label('TablePro 自适应高度', 'TablePro with automatic height') }}
</h2>
<p>
{{
label(
'表格填满可用高度,数据在表内滚动。',
'The table fills the available height and scrolls its rows internally.',
)
}}
</p>
<div class="ray-showcase-links">
<a :href="withBase('/reference/table-pro.html')">TablePro 用法</a>
<a :href="docsLink('/reference/table-pro.html')">
{{ label('TablePro 用法', 'TablePro reference') }}
</a>
<a
:href="
withBase(
docsLink(
'/reference/table-pro-examples.html#自适应高度与虚拟滚动',
)
"
>在线示例</a
>
{{ label('在线示例', 'Live example') }}
</a>
</div>
</div>
<img
@ -86,40 +103,68 @@
width="1440"
height="820"
loading="lazy"
alt="TablePro 自适应高度示例,虚拟滚动已开启,分页位于表格底部"
:alt="
label(
'TablePro 自适应高度示例,虚拟滚动已开启,分页位于表格底部',
'TablePro with automatic height, virtual scrolling, and a paginator at the bottom',
)
"
/>
</section>
</main>
</template>
<script setup lang="ts">
import { withBase } from 'vitepress'
import { useData, withBase } from 'vitepress'
import { computed } from 'vue'
import { version } from '../source.mts'
const modules = [
{ title: 'Ray Admin', name: 'apps/admin', href: '/guide/layout.html' },
{ title: '共享包', name: 'packages', href: '/guide/architecture.html' },
{ title: '页内交互', name: 'apps/docs', href: '/reference/table-pro.html' },
]
const { localeIndex } = useData()
const english = computed(() => localeIndex.value === 'en')
const label = (zh: string, en: string) => (english.value ? en : zh)
const docsLink = (path: string) => withBase((english.value ? '/en' : '') + path)
const cards = [
const modules = computed(() => [
{ title: 'Ray Admin', name: 'apps/admin', href: '/guide/layout.html' },
{
title: '第一个业务页面',
summary: '添加订单列表、路由和菜单。',
title: label('共享包', 'Shared packages'),
name: 'packages',
href: '/guide/architecture.html',
},
{
title: label('页内交互', 'Inline demos'),
name: 'apps/docs',
href: '/reference/table-pro.html',
},
])
const cards = computed(() => [
{
title: label('第一个业务页面', 'Your first business page'),
summary: label(
'添加订单列表、路由和菜单。',
'Add an order list, a route, and a menu entry.',
),
href: '/guide/first-page.html',
icon: 'M6 3.5h8l4 4v13H6z M14 3.5v4h4 M9 12h6 M9 16h6',
},
{
title: '组件与 Hooks',
summary: '查找表单、弹窗和常用组合式函数。',
title: label('组件与 Hooks', 'Components and hooks'),
summary: label(
'查找表单、弹窗和常用组合式函数。',
'Find forms, dialogs, and commonly used composables.',
),
href: '/reference/components.html',
icon: 'M3.5 3.5h7v7h-7z M13.5 3.5h7v7h-7z M3.5 13.5h7v7h-7z M13.5 13.5h7v7h-7z',
},
{
title: '构建与部署',
summary: '检查项目并部署到站点子路径。',
title: label('构建与部署', 'Build and deploy'),
summary: label(
'检查项目并部署到站点子路径。',
'Check the project and deploy it under a site subpath.',
),
href: '/guide/tooling.html',
icon: 'M4 8.5h16v11H4z M4 8.5l3-4h10l3 4 M12 16v-4 M10 14l2-2 2 2',
},
]
])
</script>

View File

@ -9,25 +9,28 @@ export default {
extends: DefaultTheme,
Layout: defineComponent({
setup() {
const { page } = useData()
const { localeIndex, page } = useData()
return () =>
h(DefaultTheme.Layout, null, {
'doc-before': () => {
const path = page.value.relativePath
const english = localeIndex.value === 'en'
const prefix = english ? '/en' : ''
const path = page.value.relativePath.replace(/^en\//, '')
const section = path.startsWith('guide/')
? '开发指南'
? { zh: '开发指南', en: 'Development guide' }
: path.startsWith('reference/')
? '参考'
: '版本迁移'
? { zh: '参考', en: 'Reference' }
: { zh: '版本迁移', en: 'Migration' }
return h('div', { class: 'ray-doc-meta' }, [
h('span', section),
h('span', english ? section.en : section.zh),
path !== 'reference/source.md'
? h('a', { href: withBase('/reference/source.html') }, [
'版本 ',
h('code', version),
])
? h(
'a',
{ href: withBase(prefix + '/reference/source.html') },
[english ? 'Version ' : '版本 ', h('code', version)],
)
: null,
])
},

View File

@ -15,13 +15,16 @@ pnpm docs:check
pnpm docs:preview
```
Open `/ray-template/docs/` at the address printed in the terminal. `pnpm docs:check` checks example types, internal links, and the production build. Output goes to `apps/docs/.vitepress/dist`. `pnpm check` includes this check. For production deployment, run `pnpm pages:build` from the root; it generates documentation under `dist/pages/docs`. Setting `RAY_TEMPLATE_SITE_ORIGIN` also generates `dist/legacy-docs` for redirects from the previous documentation site.
Open `/ray-template/docs/` for Simplified Chinese or `/ray-template/docs/en/` for English at the address printed in the terminal. `pnpm docs:check` checks example types, internal links, and the production build. Output goes to `apps/docs/.vitepress/dist`. `pnpm check` includes this check. For production deployment, run `pnpm pages:build` from the root. It generates documentation under `dist/pages/docs`. Setting `RAY_TEMPLATE_SITE_ORIGIN` also generates `dist/legacy-docs` for redirects from the previous documentation site.
- `guide/`: Getting started, development, and deployment tasks.
- `migration.md`: Previous and current usage, compatibility boundaries, and verification methods.
- `reference/`: API references for components, hooks, stores, directives, utilities, and configuration.
- `examples/`: Vue source for interactive examples; Markdown displays code from those same files.
- `.vitepress/`: Theme, navigation, and legacy path mappings. Production builds generate redirect pages for preserved legacy relative paths.
- `en/`: English pages at the same relative paths as their Chinese counterparts.
Update both languages when changing public behavior or examples. Keep the same section IDs across locales so VitePress can switch languages without losing the current section. Use explicit IDs in English when translated headings would generate a different slug. Keep existing Chinese URLs and anchors stable. Both locales use the same runnable examples and source includes.
When application changes affect public APIs, update the corresponding documentation and examples. Examples use public workspace package entry points. Shell previews have their own in-memory router and example menus. Follow the [documentation workflow](../../docs/docs-handoff.md#update-workflow) to check affected content. Verify navigation, search, themes, narrow layouts, legacy paths, and interactions only when they change; use production previews for production paths and release verification.

View File

@ -0,0 +1,158 @@
# Themes and localization {#主题与国际化}
## Themes and styles {#主题与样式}
Switch styles under **Preferences → Appearance → Interface style**. Style is independent of light, dark, and system mode. Changes apply immediately, survive refresh, and are included in preference import and export.
| Style | Appearance |
| ---------------- | --------------------------------------------------------------------------------- |
| Naive UI default | Uses the component library's native tokens. |
| Modern | The default style. Ray blue, subdued backgrounds, moderate radii, and whitespace. |
| Material | Purple tones, larger radii, pill-shaped buttons, and layered surfaces. |
| Plain | Neutral gray, small radii, and flat surfaces. |
A manually selected primary color takes precedence over a preset and is retained when switching styles. Use **Use preset color** to restore the active preset's color. Solid buttons with a custom primary color choose black or white text for the actual fill of each interaction state. A translucent fill is composited over the current card background. New users, restored defaults, and legacy settings without a style use Modern. An explicitly chosen style survives refresh and import.
### Where styles live {#样式放在哪里}
- Use [Naive UI theme overrides](https://github.com/tusen-ai/naive-ui/blob/main/demo/pages/docs/customize-theme/enUS/index.md) for component colors, radii, density, and shadows. The four presets are defined in `packages/ui/src/theme-presets.ts`. `APP_THEME.appNaiveUIThemeOverrides` is the app-level entry point for the Modern style. Overrides combine the active preset, light or dark mode, and the user's primary color. Pages and discrete messages, notifications, and dialogs share the resulting configuration.
- Custom navigation, tabs, and workspace surfaces use the `--r-*` semantic variables from `packages/ui/src/theme.css`. Admin maps the resolved `useThemeVars()` values to the root element. Docs examples scope the same mapping to their containers. Use these variables so custom elements follow the component theme.
- Custom cards and controls use `--r-radius` and `--r-control-radius`, respectively. Use readable body-level contrast for page descriptions. Page shadows use explicit soft shadows from the preset, while Naive UI overlays retain their native styles.
- Global Sass contains resets, utilities, and legacy form-width conventions. Component SCSS handles layout, scrolling, and interaction. When a suitable component API is unavailable, scope any internal selectors under your own class. Keep theme colors out of global `.n-*` rules and use semantic variables for theme switching.
- Startup styles are inline in `apps/admin/index.html`. They show the brand and a thin progress indicator before the app mounts and read the saved style and color mode. The app appears when startup completes. A failure shows a localized message and retry button. Reduced motion disables the entrance animation and slows the progress line. ECharts themes and page options control chart colors.
`vite.custom.config.ts` injects global Sass helpers. CSS Modules expose class names in camelCase.
## Custom CSS that follows live settings {#custom-css}
`AppNaiveGlobalProvider` supplies component themes within Admin. `AppStyleProvider` maps resolved colors and dimensions to `<html>`. Pages can use semantic variables directly to follow all four styles, light and dark mode, and custom primary colors.
The variables are implemented in [theme.css](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/theme.css) and [createRayThemeStyle](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/theme-presets.ts).
| Use | Variables |
| ------------------------------------------------------------ | --------------------------------------------------------------------- |
| Page background, cards, subdued surfaces, and hover surfaces | `--r-canvas`, `--r-surface`, `--r-surface-muted`, `--r-surface-hover` |
| Body, supporting, and subdued text | `--r-text`, `--r-text-secondary`, `--r-text-muted` |
| Structural dividers and visible control borders | `--r-line`, `--r-control-border` |
| Primary color and its hover value | `--r-theme-primary-color`, `--r-theme-primary-fade-color` |
| Readable accent and selected text | `--r-primary-text`, `--r-selected-text` |
| Card radius, control radius, and soft shadow | `--r-radius`, `--r-control-radius`, `--r-shadow-soft` |
| Easing and monospace font | `--r-bezier`, `--r-font-mono` |
Despite its historical name, `fade-color` maps to the primary hover color, which may be opaque. In dark mode, accent and selected text use a color chosen for contrast and may differ from the user's primary color. `--r-radius` uses the Card radius when available, while `--r-control-radius` takes the common radius. Naive UI controls component-specific shapes such as Material pill buttons. Without an explicit page shadow, the value is `none`. Overlay shadows remain on overlays.
### Style custom markup {#自有结构的写法}
Use `NCard` for ordinary cards. For custom markup, follow the SFC below and pass the title, description, and button label from the caller to use its translations.
```vue
<template>
<section class="report-panel">
<header class="report-panel__heading">
<h2>{{ title }}</h2>
<NButton type="primary" @click="emit('refresh')">{{
actionLabel
}}</NButton>
</header>
<p v-if="description" class="report-panel__description">
{{ description }}
</p>
<div class="report-panel__content"><slot /></div>
</section>
</template>
<script setup lang="ts">
import { NButton } from 'naive-ui'
defineProps<{ title: string; description?: string; actionLabel: string }>()
const emit = defineEmits<{ refresh: [] }>()
</script>
<style scoped>
.report-panel {
container-type: inline-size;
min-inline-size: 0;
padding: 1.25rem;
border: 1px solid var(--r-line, ButtonBorder);
border-radius: var(--r-radius, 4px);
color: var(--r-text, CanvasText);
background: var(--r-surface, Canvas);
}
.report-panel__heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.report-panel__heading h2 {
margin: 0;
font-size: 1rem;
font-weight: 600;
}
.report-panel__description {
margin-block: 0.75rem 0;
color: var(--r-text-secondary, CanvasText);
line-height: 1.7;
}
.report-panel__content {
min-inline-size: 0;
margin-block-start: 1rem;
}
@container (max-width: 32rem) {
.report-panel__heading {
align-items: flex-start;
flex-direction: column;
}
}
</style>
```
TSX uses the same classes and CSS. Keep styles beside the component and load them with `import './index.scss'`. Semantic variables inherit through the DOM and cover the four styles. Define local variables or props for component-specific spacing.
### Use shared components in a standalone project {#在独立项目中使用共享组件}
A standalone host supplies a Naive `NConfigProvider`, a CSS variable scope, and optional behavior services through `provideUiServices`. The provider owns component themes, and the scope owns CSS values. The example uses public exports and is included in docs example type checks. Save it as `ThemeScope.vue` and pass business content in its slot.
::: details Complete standalone host example
<<< @/examples/ThemeScopeExample.vue
:::
Use `theme-style="material"` and `:dark="true"` to choose the style and mode. Merge a custom primary color through `commonOverrides`. For complete interaction colors, set `primaryColor`, `primaryColorHover`, `primaryColorPressed`, and `primaryColorSuppl` together. Inside Admin, use `useSettingActions().changePrimaryColor()` with the existing host. Pass values from storage or JSON through `normalizeThemeStyle()` first.
The example merges the exported Naive light or dark common theme with the same overrides before mapping variables. To read `useThemeVars()`, place the read in a descendant of `NConfigProvider`. Provide your own `UiServices` as needed for translation, icon URLs, or other host behavior. Existing Admin pages should use the application services they already inherit.
A local theme scope needs `.r-theme-scope`, a light or dark class, and the mapped styles. Overriding only `--r-token-*` on a child can leave aliases with values already resolved on an ancestor. See [CSS custom property inheritance](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Cascading_variables/Using_custom_properties). Vue `Teleport` retains Vue injection but uses the target's DOM style inheritance. Teleport custom overlays inside the scope or apply the same theme to the target container.
With `theme.css` alone, variables fall back to system colors such as `Canvas`, `CanvasText`, `Highlight`, and `ButtonBorder`, plus 4 px radii and no shadow. Naive components use their default theme. Import the shared stylesheet or provide explicit `var()` fallbacks. Local mappings are scoped to the container. The shared stylesheet also defines root `color-scheme` and common focus styles.
### Sizing, scrolling, and motion {#尺寸、滚动与动效}
- `AdminShell` provides live content sizing. `--layout-content-padding` is the configured padding, `--layout-content-gutter` is the effective spacing after narrow-screen adjustments, `--layout-content-max-width` is applied by the layout, and `--layout-content-height` is the available height after measuring the header, tabs, and footer. Sass values in `setting.scss` are resolved at build time.
- Let ordinary pages size naturally. Workspaces that require internal scrolling can use `calc(var(--layout-content-height, 100dvh) - 2 * var(--layout-content-gutter, 16px))` and allocate the space with flex or grid, `min-block-size: 0`, and a defined scroll container. For standalone components, prefer a height provided by the parent.
- Use `minmax(0, 1fr)`, `min-inline-size: 0`, and logical properties. Adapt to available content width. Container queries require an ancestor with `container-type: inline-size` and explicit breakpoint lengths. Query conditions cannot use `var()`.
- Use semantic variables for colors, radii, and shadows. Fixed values can express local spacing, optical icon sizes, breakpoints, and intentional brand or data colors. Shared SVGs use `currentColor`, while Canvas chart colors come from themes or chart options.
- Prefer `opacity` and `transform` for motion and handle `prefers-reduced-motion` in the relevant component. Retain keyboard focus outlines and borders or outlines in forced-colors mode.
Prefer props, slots, or `themeOverrides` when customizing Naive components. Scope any necessary internal selectors inside your component class. Check the affected preset, color mode, and narrow layout. Prose-only edits can use source and formatting checks.
For large-screen designs that require proportional scaling, add a matching path rule to `viewportIncludeFiles` in root `postcss.config.cjs`, for example `[/[/\\]large-screen[/\\]/]`. An empty list disables `postcss-px-conversion`. For matching Admin styles, the plugin converts to `vw` using a 1920 px design width. It excludes third-party dependencies, `.ignore` selectors, and rules inside media or container queries.
## Maintain Chinese and English together {#中英文同时维护}
Place page copy in the matching JSON files under `apps/admin/src/locales/lang/zh-CN` and `apps/admin/src/locales/lang/en-US`. Namespaces must be unique within each language. To add a language, also update `apps/admin/src/locales/lang/<locale>.ts` and the application's locale configuration.
```ts
import { useI18n } from '@/hooks'
import { useSettingActions } from '@/store'
import { computed } from 'vue'
const { t } = useI18n('menu')
const orderLabel = computed(() => t('Orders'))
const { updateLocale } = useSettingActions()
updateLocale('en-US')
```
Call `t` in the render function or a computed value when the UI should react to language changes. Switch the application language through `updateLocale` to keep the date and component-library locales in sync.
[Language pack conventions](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/locales/README.md) · [Theme configuration](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/app-config/design-config.ts)

View File

@ -0,0 +1,227 @@
# v6 Monorepo Architecture {#v6-monorepo-架构}
Ray Template v6 puts Ray Admin, the VitePress documentation site, and ten shared packages in one pnpm workspace. Ray Admin owns sign-in, business pages, and application state. The documentation site runs examples from the same component sources. Shared packages expose reusable implementations through public entry points.
## Workspace overview {#工作区总览}
```text
ray-template/
├─ apps/
│ ├─ admin/ Ray Admin
│ │ ├─ index.html Admin entry
│ │ ├─ example.html Demo entry
│ │ └─ src/
│ │ ├─ main.ts Bootstrap
│ │ ├─ App.tsx Providers
│ │ ├─ app-config/ App config
│ │ ├─ app-components/ Host UI
│ │ ├─ locales/ Locales
│ │ ├─ router/ Route guards
│ │ │ └─ config/ Route inputs
│ │ ├─ store/ Pinia state
│ │ │ ├─ modules/ Pinia stores
│ │ │ └─ hooks/ State access
│ │ ├─ layout/ Shell wiring
│ │ ├─ views/ Pages, demos
│ │ ├─ api/ API calls
│ │ │ ├─ admin/ Admin API
│ │ │ └─ demo/ Demo queries
│ │ ├─ axios/ Interceptors
│ │ └─ mocks/ MSW state
│ └─ docs/ VitePress
│ ├─ .vitepress/
│ │ ├─ config.mts Site config
│ │ ├─ sidebar.mts Sidebar
│ │ ├─ legacy.mts Legacy URLs
│ │ └─ theme/ Site theme
│ ├─ guide/ Guides
│ ├─ reference/ API docs
│ ├─ examples/ Vue examples
│ └─ playground/ Layout demo
├─ packages/
│ ├─ admin-shell/ Layout shell
│ ├─ routing/ Navigation
│ ├─ ui/ UI and theme
│ ├─ icons/ SVG icons
│ ├─ http/ HTTP client
│ ├─ api-contracts/ API schemas
│ ├─ demo-data/ Fixtures
│ ├─ composables/ Vue hooks
│ ├─ directives/ Directives
│ └─ utils/ Utilities
├─ harness/ Task checks
└─ pnpm-lock.yaml Lockfile
```
Ray Admin uses all the shared packages shown above. The docs import the packages needed by each example, including UI, layout, and routing. Examples that need the full admin context open an isolated entry in an iframe. Each application declares dependencies in its own `package.json` and uses the workspace lockfile. [Workspace configuration](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/pnpm-workspace.yaml) · [Engineering architecture map](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/docs/architecture.md)
<!-- fullstack:start -->
The full-stack source also includes `apps/server`, which runs independently. [Server architecture](#可选服务端怎样分层)
<!-- fullstack:end -->
## How Ray Admin is assembled {#ray-admin-怎么组装}
### Bootstrap and global services {#启动与全局服务}
```text
index.html → main.ts
↓
Install Pinia and language packs
↓
Restore the session → Set up Vue Router
↓
Install Day.js and directives
↓
Mount App.tsx and global providers
↓
RouterView → Active page
```
Standalone and Wujie sub-app modes use the same plugin setup. Startup restores the session before deciding whether to load account routes. `src/app-config/` supplies theme, route, request, and cache configuration. [Bootstrap entry point](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/main.ts) · [Application configuration](../reference/configuration)
`App.tsx` assembles Naive UI, global styles, the watermark, and loading state. Through `@ray-template/ui/services` it provides theme, translation, icon URLs, notifications, and column preference storage. Shared UI components consume these through `UiServices`, so the docs can run them in their own context. [App source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/App.tsx)
### From route configuration to menus and pages {#从路由配置到菜单和页面}
```text
Built-in JSON / Local / Remote
↓
router/config/source.ts → Select source
↓
api-contracts → Validate structure
↓
routing + config/views.ts
Bind view IDs to page loaders
↓
Vue Router + App guards
├─→ store/menu → Menus, tabs, crumbs
└─→ RLayout → AdminShell → Page
```
- `router/` registers sign-in, status, and current-account routes. Built-in configuration comes from `demo-data`. `router/config/views.ts` registers the loadable `views/` pages. Guards use the verified session and route permissions to decide whether to enter a page. [Routes, menus, and permissions](./routing)
- `store/` keeps state by responsibility. `signing` handles sessions. `menu` derives menus from permissions and syncs tabs and breadcrumbs with the route. `keep-alive` tracks cacheable pages. `setting` persists selected preferences, while `runtime` rebuilds loading, drawer, and maximization state on mount. Store hooks expose state and actions. [Store reference](../reference/store)
- `layout/` adapts the shared shell. `RLayout` supplies layout preferences and slots for navigation and content to `AdminShell`. The default content slot wires request cancellation and page transitions. The transition uses the cache settings and allowlist to render `KeepAlive`. [Layout and state](./layout)
### The path of a business request {#一次业务请求经过哪些层}
```text
views/ or store/
↓
api/admin/ or api/demo/
↓
axios/ App interceptors
↓
@ray-template/http Axios instance
├─→ MSW → mocks/ → Demo fixtures
└─→ HTTP → Configured API
```
`api/` wraps endpoints. The admin client adds session transport and validates responses with `api-contracts`. `axios/` configures request, response, and error interceptors. `http` provides a canceler for each instance and accepts a caller-provided `AbortSignal`. [Requests, cancellation, and mocks](./requests)
Development and the static hosted demo can use the same MSW HTTP mock. `mocks/handlers.ts` implements endpoints. `mocks/database.ts` handles demo sessions, users, and route reads and writes. `demo-data` provides initial fixtures and query utilities. When a real API is connected, the server verifies sessions and authorizes resource access. [Backend integration and the standard API contract](./backend)
## How the docs run components {#文档怎样运行组件}
```text
Documentation page
├─ Render examples/*.vue directly
│ └─ Public entry, e.g. ui/table-pro
└─ Embed through AdminExample.vue
└─ admin/example.html
└─ documentation-example.tsx
└─ Allowed admin demo routes
```
- **Direct examples.** The precision, barcode, and TablePro examples import shared packages. Markdown includes the same `.vue` file used by the runnable example. TablePro receives local rows or a cancelable mock query. The layout playground has a separate preview page and in-memory router. [Precision arithmetic](../reference/utils/core#交互示例) · [Barcode](../reference/components/barcode#交互示例) · [TablePro example](../reference/table-pro#交互示例) · [Live layout playground](./layout#在线布局实验)
- **Embedded admin demos.** `AdminExample.vue` hosts examples that need the admin layout or application context. `example.html` uses its own bootstrap, restricted example routes, and Pinia instance. Ordinary app cache is in memory, and column visibility uses a separate session storage namespace. [Docs source overview](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/docs/README.md)
<!-- fullstack:start -->
## Optional backend layers {#可选服务端怎样分层}
`apps/server/src/main.ts` starts a standalone NestJS HTTP service. `app.ts` installs the business modules, platform middleware, global response interceptor, and exception filter.
```text
Browser request to /api
↓
platform/ ─────────→ Redis
↓ Limits, demo cache
NestJS guards and controllers
├─ auth / users / routes
│ └─ Prisma → PostgreSQL
└─ demo (when enabled)
└─ @ray-template/demo-data
```
- `modules/auth/` handles authentication and sessions and installs the global authorization guard. `modules/users/` handles account management and provides department and role options. `modules/routes/` reads, filters, and saves route configuration. Business modules define and validate HTTP data with `api-contracts`.
- `infrastructure/database.ts` wraps Prisma access. The schema and migrations under `prisma/` define users, credentials, grants, sessions, route configuration, and audit records in PostgreSQL. The database is authoritative for sessions and permissions.
- `platform/` owns Redis, request IDs, logs, security middleware, and health checks. Redis provides rate limits and caches selected reconstructible demo reads. Demo endpoints are enabled by deployment configuration and share `demo-data`.
`apps/server` builds independently and ships in the full-stack source distribution. [Server source overview](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/server/README.md) · [Source distributions and startup](./distributions)
<!-- fullstack:end -->
## Shared package responsibilities {#各包负责什么}
Arrows show direct dependencies from the importing shared package to the package it uses. Names in the diagram stand for `@ray-template/<name>`.
```text
admin-shell
├─→ ui ───────┬─→ composables
│ ├─→ icons
│ └─→ utils
├─→ routing ──┬─→ api-contracts
│ ├─→ icons
│ └─→ utils
├─→ composables
└─→ icons
directives ──┬─→ composables
└─→ utils
composables ───→ utils
http ──────────→ utils
demo-data ─────→ api-contracts
```
`package.json#exports` declares public entry points. Prefer feature imports across workspaces, for example `@ray-template/ui/table-pro` or `@ray-template/utils/precision`. `rayTemplate.runtime` distinguishes `browser`, `server`, and `universal`. `api-contracts` and `demo-data` are universal and can be used by the browser and server. Universal workspaces depend only on other universal workspaces. Applications consume public package entries to assemble features. `pnpm packages:check` validates workspace dependencies, public entries, and cycles. [Package boundary check](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/scripts/check-package-boundaries.mjs)
### UI, layout, and routing {#界面、布局与路由}
- **`@ray-template/admin-shell`** implements layout modes and slot placement in `AdminShell.tsx`. `TopNavigation.tsx`, `ShellTab.tsx`, and `menu-keyboard.ts` support navigation, tabs, and keyboard interaction. `LayoutSettings.tsx` provides layout options and `RouteTransition.vue` handles transitions and cache rendering. The host supplies layout state, menu items, navigation actions, and content. [Shell exports](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/admin-shell/src/index.ts)
- **`@ray-template/routing`** exposes `/contract` to bind host-provided views, reserved paths, and permission rules to serializable config and Vue Router records. It supports exporting records back to JSON. `/expand-routes`, `/order-routes`, and `/navigation` expand and order routes and traverse menu trees. `/schema` and `/json-schema` are compatibility exports backed by `api-contracts`. [Routing exports](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/routing/package.json)
- **`@ray-template/ui`** organizes implementations, types, and styles by component, with entries such as `/table-pro`, `/form`, `/chart`, and `/barcode`. `/theme.css` and `/theme-presets` supply design variables and presets. `/services` connects host themes, translations, notifications, and storage to components. [Component reference](../reference/components)
- **`@ray-template/icons`** groups SVG sources by directory. The generated `/manifest` provides full icon names, types, and group asset URLs. The admin build generates a sprite per group. `RIcon` and route configuration use the same names, such as `navigation/table`. [SVG icons](../reference/icons)
In TablePro, `TablePro.tsx` composes filtering, pagination, queries, and the instance API. `useTableSearch` manages drafts and submitted filters. `useTableRequest` handles remote request status and cancellation. `TablePanel` owns the Naive UI data table, column settings, and tools. The host supplies the query and column preference storage. [TablePro reference](../reference/table-pro) · [Component entry point](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/index.ts)
```text
Submit search / Change page
↓
TablePro → useTableRequest
↓
Host request(params, signal)
↓
Current page data + Filtered total
↓
TablePanel → Naive UI NDataTable
```
### HTTP, contracts, and demo data {#http、契约与演示数据}
- **`@ray-template/http`** exposes `createHttpClient` in `client.ts` to create an independent Axios instance that returns HTTP response bodies. `RequestCanceler` tracks and clears pending requests. The host chooses the base URL, headers, and interceptors. [HTTP client source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/http/src/client.ts)
- **`@ray-template/api-contracts`** defines envelopes, sessions, and admin models under `/admin` and demo queries and responses under `/demo`. `routes.ts` is the route schema source. `/route-validation` validates structure, and `/route-json-schema` and `/openapi` generate editor and API integration descriptions. Frontend, mock, and server consumers share the Valibot contracts. [API contract package](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/api-contracts/README.md)
- **`@ray-template/demo-data`** includes default routes in `routes.json`, initial options, charts, orders, people, and helpers for search, filtering, and pagination. Hosts decide when to enable demos and manage their own sessions and writes. [Demo data package](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/demo-data/README.md)
### Hooks, directives, and utilities {#hooks、指令与工具}
- **`@ray-template/composables`** offers Vue lifecycle and element-reference helpers under `/vue`. Feature hooks have their own entries, including `/useDevice`, `/useElementFullscreen`, `/useDomToImage`, and `/usePrint`. Admin-specific navigation, layout, and state hooks live under `apps/admin/src/hooks/template/`. [Hooks reference](../reference/hooks)
- **`@ray-template/directives`** keeps implementations and types by directive under `src/modules/`. Import entries such as `/copy`, `/debounce`, and `/throttle` as needed. Ray Admin's `src/directives/index.ts` registers the directives it uses. [Directives reference](../reference/directives)
- **`@ray-template/utils`** provides precision arithmetic via `/precision` and object, file, and type helpers via `/core`, `/files`, and `/types`. `/storage` reads and writes namespaced JSON through a host-supplied store. The host chooses the storage location and cache keys. [Utilities reference](../reference/utils)
## Build and deploy {#构建与部署}
`pnpm dev` starts Admin and `pnpm docs:dev` starts the docs. `pnpm build` builds Admin, `pnpm docs:build` builds the docs, and `pnpm pages:build` assembles them under `dist/pages`. The hosted application is at `/ray-template/` and the docs are at `/ray-template/docs/`, with English at `/ray-template/docs/en/`. [Build and deployment guide](./tooling)
For a project based on v5, review the compatibility boundaries and adoption process. [Moving from v5 to v6](../migration)

View File

@ -0,0 +1,195 @@
# Backend integration and the standard API contract {#服务端接入与标准契约}
Sign-in, sessions, user management, and route management use the same HTTP API. [Source distributions and startup](./distributions)
MSW intercepts requests at the network layer in development and in the static hosted demo. Pages and stores go through the API layer. To connect your own backend, keep the pages and call sites and provide a new API address and implementation.
<script setup>
import { withBase } from 'vitepress'
</script>
<a :href="withBase('/contracts/admin-api.json')" target="_blank" rel="noreferrer">Download the OpenAPI 3.1 contract</a>
The contract is generated from the `@ray-template/api-contracts` workspace package and the route schema. It covers request bodies, responses, query parameters, Bearer authentication, and permission codes. Import sign-in and user contracts from `/admin`, demo contracts from `/demo`, and route schemas from `/routes`. `/openapi` exports the OpenAPI generator. `packages/api-contracts/src/routes.ts` is the source of truth for the route schema, and the older routing entry point re-exports it. The package is independent of browser state, so the frontend, mocks, and your backend can share types and runtime validation. It is distributed with the workspace. The existing application paths `api/admin/contracts.ts` and `api/demo/contracts.ts` remain compatible. Run `pnpm api:generate` after changes. `pnpm api:check` checks the generated files against the runtime schemas.
```ts
import type { ApiResponse, UserInput } from '@ray-template/api-contracts/admin'
import { userInputSchema } from '@ray-template/api-contracts/admin'
import type {
DemoOrderQuery,
SearchOptions,
} from '@ray-template/api-contracts/demo'
```
## Connect your service {#接入步骤}
Configure `apps/admin/.env.local` and restart or rebuild the app.
```dotenv
VITE_API_MOCK=false
VITE_API_BASE_URL=https://your-api.example.com/api/
```
A deployment proxy can also forward same-origin `/api/` requests. Setting `VITE_API_BASE_URL` disables mocks by default. Set `VITE_API_MOCK=true` to explicitly re-enable them. The base URL can include a version prefix. Pages use the methods in `api/admin`. `VITE_*` values are bundled for the browser, so use them only for public configuration.
The application waits for the worker before sending mock API requests. Before each API request, it checks an internal health marker. If the browser reclaimed the worker, the same MSW client calls `stop()` and `start()` to restore its listeners and interception state. If recovery fails, the request is blocked and form and demo data remain intact. `GET /admin/mock-health` is internal to mock mode. The worker is served at `/ray-template/mockServiceWorker.js`, with a query parameter for the current MSW version and a scope matching the application base. Serve the script at that path over HTTPS or on localhost. GitHub Pages hosts static files. The worker in a running demo page handles API calls, while opening the API address directly returns 404. In backend mode, requests go straight to the configured service and failures surface to the caller. MSW is pinned to 3.0.4. Installation skips the worker copy step. After upgrading, run `pnpm exec msw init apps/admin/public --save` and verify the contract and browser behavior.
<!-- fullstack:start -->
## Bundled NestJS backend {#配套-nestjs-服务端}
The complete source includes `apps/server`, which implements the same `/api/admin/*` protocol. Existing page-level calls work with it. For local development, use `pnpm fullstack:setup` and `pnpm dev:full`. To use an existing PostgreSQL and Redis instance, run `pnpm fullstack:setup --external`. The generated admin credentials are stored in private `apps/server/.env.local`. Use them to sign in to the real backend. [Full-stack distribution](./distributions#全栈发行包)
PostgreSQL persists users, departments, role grants, sessions, route configuration, and audit records. Normalized unique fields prevent conflicts in usernames and emails that differ only by case. Bulk mutations, account protections, and audit writes run in transactions. Initialization adds missing seed data and preserves existing settings, routes, and accounts on subsequent runs.
The backend uses signed JWTs as session credentials and stores only token digests in PostgreSQL. It derives passwords with randomly salted scrypt. Each request checks the JWT signature and expiry, the stored session, and current permissions. The bundled same-origin Admin uses an HttpOnly cookie. API clients can use Bearer authentication. Sign-out revokes the current session. Disabling an account, changing its role, or changing its password revokes all its sessions.
Create a user record first, then let an authorized administrator set the credential from User Management. Operators can recover credentials with `pnpm server:credential:set`. The bundled `dev:full` and Compose set `VITE_API_AUTH_TRANSPORT=cookie`. For a manual build, pair it with a same-origin proxy and `VITE_API_BASE_URL=/api/`. Enable secure cookies for HTTPS deployments. Cookie-mode requests send `X-Ray-Session: cookie`. Writes must also come from an allowed same-origin page.
Redis rate-limits API calls, sign-in, and password changes across processes and caches reconstructible demo reads. Session and permission checks go to the database. Responses carry `X-Request-Id`. JSON logs record the route template, status, and duration and omit request bodies, query strings, credentials, and raw connection errors. Readiness at `/api/health/ready` checks that the database is initialized and Redis is available. Liveness is at `/api/health/live`.
Configure explicit CORS origins and trusted proxies. Forwarded headers are untrusted by default. Invalid JSON, oversized requests, rate limits, and dependency failures return standard error envelopes. `POST /admin/users/reset` is a mock-only endpoint. A Redis outage returns 503 and protected traffic remains blocked.
`DEMO_ENABLED` defaults to on in development and off in production. When enabled, `/admin/demo/*` serves public fixtures consistent with the mocks. When disabled, the demo endpoints return 404 and runtime routes omit demo views and redirects to them. The stored route configuration remains available to authorized editors.
<!-- fullstack:end -->
## Response envelope {#统一响应}
Successful requests return HTTP 200 with this envelope.
```json
{
"code": 200,
"msg": "OK",
"data": { "items": [], "total": 0 }
}
```
Paginated requests use `page` starting at 1 and `pageSize` from 1 to 100. `data.items` is the current page, and `data.total` is the count after all filters. Filters apply before pagination. Detail and write endpoints put a single object in `data`. Bulk mutations return an affected count such as `{ "affected": 2 }`.
Failures use the corresponding HTTP status and `code` with `data` set to `null`.
```json
{
"code": 409,
"msg": "duplicateUsername",
"data": null,
"error": { "key": "duplicateUsername" }
}
```
Successful reads of user details and full route configuration (`view=editor`) include an opaque `revision`. When saving the same resource, send `If-Match: "<revision>"`. If it changed since the read, the API returns 412 with `editConflict` and the editor retains the draft. Reload and compare changes before resubmitting. Clients can still omit the header for unconditional replacement. A custom backend must return the revision and check it within the write transaction to provide the same concurrency protection.
| Status | Meaning |
| ------ | --------------------------------------------------------------------------------------- |
| 400 | Invalid input |
| 401 | Invalid or expired session |
| 403 | Insufficient permissions |
| 404 | Resource missing |
| 409 | Username or email conflict, or current account is protected |
| 413 | Request body too large |
| 429 | Rate limit exceeded |
| 503 | Storage or dependency temporarily unavailable, including mock database writes that fail |
`error.key` is a stable application error identifier. Optional `error.fields` maps field names to error keys. The API layer converts failures to `AdminApiError`, and User Management translates known keys into Chinese and English. The API layer also validates read responses against their schemas.
## Sign-in, sessions, and permissions {#登录、会话与权限}
| Method and path | Input | Successful data |
| ---------------------------- | ---------------------------------- | --------------------------------------------------------------------------------- |
| `POST /admin/auth/login` | `{ username, password }` | `{ accessToken, expiresAt, user, permissions }`. Cookie mode omits `accessToken`. |
| `GET /admin/auth/session` | Session | `{ user, permissions, expiresAt? }` |
| `POST /admin/auth/logout` | Session | `null` |
| `GET /admin/auth/profile` | Session | Current account profile and department |
| `PATCH /admin/auth/profile` | `{ name, phone }` | Updated current account profile |
| `PATCH /admin/auth/password` | `{ currentPassword, newPassword }` | `null`. Sign in again. |
```json
{
"user": { "id": "u-1", "username": "admin", "name": "Alex", "role": "admin" },
"permissions": [
"users:read",
"users:create",
"users:update",
"routes:read",
"routes:write"
]
}
```
Custom backends use `Authorization: Bearer <accessToken>` by default. The app fetches the session and permissions again on startup. A 401 clears the invalid session, and other errors remain failure states. The route contract uses one `user.role`, while `meta.role` is an array of allowed roles. Permission codes are independent of role names, so the backend can assign them as needed. Users can edit their own name and phone. Manage username, email, role, and department in User Management.
```tsx
import { useAccess } from '@/hooks'
const { hasPermission } = useAccess()
// All permissions are required by default. Pass 'any' as the second argument to require just one.
hasPermission('users:create')
hasPermission(['users:update', 'users:delete'], 'any')
```
The frontend uses permissions for menus, navigation, and action placement. The backend must independently authorize every business request. The mock API also enforces role and account protections on direct requests. The demo accounts `admin` (also `Ray Admin`), `manager`, and `member` all use `123456`. They have full access, user-maintenance access, and read-only access, respectively. Demo passwords and mock tokens are for the live demo.
## User management {#用户管理}
| Method and path | Input | Required permission |
| ---------------------------------- | ------------------------------------------------------------- | ------------------- |
| `GET /admin/users/options` | None | `users:read` |
| `GET /admin/users` | Pagination and `name/username/email/departmentId/role/status` | `users:read` |
| `GET /admin/users/{id}` | Path ID | `users:read` |
| `POST /admin/users` | `UserInput` | `users:create` |
| `PUT /admin/users/{id}` | Complete `UserInput` | `users:update` |
| `POST /admin/users/batch-delete` | `{ ids: string[] }` | `users:delete` |
| `PATCH /admin/users/status` | `{ ids: string[], status }`, with `"enabled"` or `"disabled"` | `users:status` |
| `PUT /admin/users/{id}/credential` | `{ newPassword }` for an account other than the current one | `users:credentials` |
| `POST /admin/users/reset` | None. Demo reset only. | `users:reset` |
```json
{
"username": "alex",
"name": "Alex",
"email": "alex@example.com",
"phone": "",
"departmentId": "engineering",
"role": "member",
"status": "enabled",
"remark": ""
}
```
User responses add a stable `id` and ISO 8601 `createdAt`. Usernames and emails are unique regardless of case. Updates keep the ID and creation time. The options endpoint returns `{ departments: [{ id, parentId, name, labelKey? }], roles: [{ value, label, labelKey?, disabled? }] }`. A department filter includes descendants. The demo uses optional `labelKey` for translations. A custom backend can return labels directly.
The API validates the entire batch before committing it. Users cannot delete or disable their own accounts or change their own roles through the editor. Editing status also requires `users:status`. Managing target accounts and their credentials requires the appropriate permissions, and managers cannot manage administrator accounts. The mock database persists users, routes, and sessions in the current browser. User Management shows the reset action only in mock mode.
## Route management {#路由管理}
After sign-in, `GET /admin/route-config` returns `data: { version: 1, routes: [...] }` for the current session. The server considers parent and child roles, view permissions, and the demo switch. It removes groups without accessible children and redirects without an authorized target. Without `routes:read` or any accessible page, it returns `routes: []`. The shell and profile remain available. A session with `routes:write` can read the full configuration with `GET /admin/route-config?view=editor` and save it with `PUT /admin/route-config`.
Initial menus live in `packages/demo-data/src/routes.json`. In standard API mode, the server's route configuration is authoritative. Runtime routes are registered at sign-in and reloaded after saving. Load failures surface as errors. Direct access to a pruned business route shows 404, and opening the reserved Route Management entry without edit rights shows 403. Business APIs authorize requests independently. Imports, exports, and the API use the same structure. [Route contract](./routing)
`router/config/views.ts` is the frontend allowlist of component IDs. The API returns registered IDs, keeping executable component code in the frontend. The shell reserves sign-in, 404, and the protected Route Management entry. `VITE_ROUTE_CONFIG_URL` remains compatible with older raw JSON read endpoints. Use the standard API base for full read and write support.
## Verify against the live demo {#在线验证}
The demo endpoints use the same standard HTTP contract.
| Method and path | Input | Successful data |
| ----------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `GET /admin/demo/people` | `page/pageSize/name/email/sortAge/fail` | `{ items: Person[], total }` |
| `GET /admin/demo/route-people` | `page/pageSize/name`. Exact name matching preserves old links. | `{ items: RouteDemoPerson[], total }` |
| `GET /admin/demo/route-people/{id}` | Nonnegative integer ID starting at 0 | `RouteDemoPerson`, or 404 when missing |
| `GET /admin/demo/search-options` | `locale` | Status, organization, product category, warehouse, and delivery options |
| `POST /admin/demo/orders/search` | `{ query: DemoOrderQuery, locale, fail? }` | `{ items: DemoOrder[], total }` |
| `POST /admin/demo/owners/search` | `{ orgId, keyword, locale, fail? }` | `{ value, label }[]` |
| `GET /admin/demo/charts` | `refresh` | `DemoCharts` |
| `GET /admin/demo/request` | None | Ticket and city data |
The page size limit is 100. `sortAge` is `ascend` or `descend`. `refresh` and the demo-only `fail` are booleans. Invalid input returns HTTP 400. Shared schemas and OpenAPI define order filter fields, types, date formats, and minimum amounts. `fail=true` simulates a remote failure with HTTP 503.
The search page loads business options from the API. Order responses include warehouse and delivery names directly. If options fail to load, the UI offers a retry. Switching language or leaving the page cancels older requests. Route-demo lists and details also come from the API and support old lookup links by name. Preset scenarios and failure buttons appear only in mock mode.
Open the browser's Network panel. Sign in, open User Management, run a query, create or edit a user, open the details, and save a route to see the corresponding HTTP requests. The hosted demo marks responses as coming from the service worker. It simulates the server protocol on static hosting. When connected to a real backend, the same page requests go to the configured API base.
User Management reuses `RTablePro`, `RForm/useForm`, and Naive UI. On desktop, both panels fill the content area. The organization card uses `contentScrollable`, and the table uses `autoHeight`. On narrow screens the panels stack, and existing scrolling components keep the page usable.

View File

@ -0,0 +1,120 @@
# Source distributions and startup {#发行版本与快速启动}
The same frontend is available as a standalone source export. Admin, the docs, and shared packages keep their workspace dependency boundaries, and mocks and custom backends use the same API contract. The archives contain editable project files. Install dependencies and build before running a deployment.
## Frontend distribution {#纯前端发行包}
Run this command from the repository root.
```sh
pnpm dist:frontend
```
`dist/distributions/` contains `ray-template-frontend-<version>/` and a matching `.tar.gz`. After extracting the archive and entering the source directory, use Node.js 26.13.0 and pnpm 12.16.1.
```sh
pnpm install --frozen-lockfile
pnpm dev
```
Open `/ray-template/` to try sign-in, user management, routes, and other examples through MSW. The frontend edition includes Admin, the docs, all 10 shared packages, and required tools. It runs and builds independently of the backend workspace, database drivers, Redis client, server launcher, and database configuration. Frontend development, builds, and docs run without Docker.
To connect your own backend, configure `VITE_API_BASE_URL` and `VITE_API_MOCK=false`. These values enter the browser bundle, so use them for public configuration only. [Backend integration](./backend)
## Distribution provenance {#发行物追溯}
`distribution.json` in the archive records the following.
- Edition and version.
- Source Git commit and whether the source had uncommitted changes. Exports without Git metadata keep known provenance.
- Included workspaces and source file count.
- SHA-256 digest of the exported content.
The exporter follows the dependency graph, prunes the lockfile, and removes commands and notes specific to omitted features. It excludes `.git`, `node_modules`, local environment files, credentials, build output, and temporary verification evidence. `pnpm dist:check` checks the export plan and dependency integrity. Installation, build, and runtime checks in a clean environment run separately.
Export commands create local source directories and archives.
<!-- fullstack:start -->
## Full-stack distribution {#全栈发行包}
Run this command in the complete repository.
```sh
pnpm dist:fullstack
```
The same output directory contains `ray-template-fullstack-<version>/` and a matching `.tar.gz`. It includes the frontend source plus `apps/server`, database migrations, Redis configuration, and startup tools. The backend uses NestJS 12.3.3, Prisma 7.10.1, PostgreSQL 18, and Redis client 6.3.1. Compose uses Redis 8.2.11. See the distribution manifest and lockfile for pinned versions.
### Local development {#本地开发}
Install dependencies and prepare Docker Compose, then run the following.
```sh
pnpm fullstack:setup
pnpm dev:full
```
The first setup creates private `apps/server/.env.local`, generates database and Redis configuration, a random admin password, and a JWT signing key, starts PostgreSQL and Redis, applies migrations, and initializes the administrator. Read the initial username and password locally and keep them out of Git, uploads, and frontend variables. `123456` is the frontend demo password.
Subsequent setup runs reuse configuration and preserve accounts and database contents. `dev:full` waits for backend readiness before starting the frontend. Vite proxies same-origin `/api/` requests and disables mocks. The default address is `http://127.0.0.1:9527/ray-template/`. Use `ADMIN_DEV_PORT` and `PORT` for frontend and backend ports. Ctrl+C stops the dev process. `pnpm fullstack:stop` stops Compose services and retains data volumes.
### Use existing PostgreSQL and Redis services {#使用已有数据库与-redis}
Provide `DATABASE_URL` and `REDIS_URL` in the process's secure environment, then run the following.
```sh
pnpm fullstack:setup --external
pnpm dev:full
```
`--external` skips starting Docker services and still runs migrations and initialization. It preserves an existing `apps/server/.env.local`. Process variables take precedence. Use a database dedicated to the project, since migration and initialization create or update its schema and data. Manage external services through their own deployment environment.
### Create a real sign-in account {#创建真实登录账号}
After adding a user in User Management, an administrator with `users:credentials` can choose **Set password** for the account. Signed-in users can change their own password from **Profile** in the avatar menu by entering their current password. Changing or resetting the password revokes all sessions for that account. Passwords must be 12–128 characters.
For credential recovery, an operator can supply `CREDENTIAL_USERNAME` and `CREDENTIAL_PASSWORD` in a secure environment and run `pnpm server:credential:set` from a trusted terminal with database access. Re-running setup preserves renamed accounts and existing passwords. Keep credentials out of command lines, terminal transcripts, and AI conversations.
### Service commands and checks {#服务与运行检查}
| Command or endpoint | Purpose |
| ------------------------------ | ---------------------------------------------------------------------------------------- |
| `pnpm server:build` | Generate Prisma Client and build the standalone server. |
| `pnpm server:start` | Start the built server. |
| `pnpm server:check` | Run server type checks and unit/platform tests, then build. |
| `pnpm server:test:integration` | Check real persistence and HTTP behavior using `TEST_DATABASE_URL` and `TEST_REDIS_URL`. |
| `GET /api/health/live` | Process liveness. |
| `GET /api/health/ready` | PostgreSQL and Redis readiness. |
The full stack includes configuration validation, endpoint authorization, session revocation, Redis rate limits, security headers, CORS, request IDs, redacted logs, and audit records. When Redis is unavailable, management requests return 503. Only reconstructible demo reads are cached. Session and permission checks use the database each time.
Production disables demo endpoints by default and removes the corresponding demo routes from the runtime menu. Authorized editors can still manage the full route configuration. Production API failures surface as errors.
### Container startup {#容器启动}
Use Node.js 26.13.0 and a running Docker installation with the Compose v2 plugin. Verify `docker compose version` and `docker info`. From the extracted full-stack source or complete repository root, run the following.
```sh
node scripts/fullstack.mjs up
# With pnpm, you can also run pnpm fullstack:up
```
The command creates private configuration, builds Admin and the API, starts PostgreSQL and Redis, applies migrations and initialization, and prints the local entry point after readiness. The host can build without preinstalled frontend dependencies. The default address is `http://127.0.0.1:8080/ray-template/`. Change it with `APP_PORT`. Stop services with `node scripts/fullstack.mjs stop` to keep the data volumes. For several isolated instances, assign each a distinct `RAY_COMPOSE_PROJECT`, host port, and `APP_PROXY_NETWORK`.
Nginx proxies same-origin `/api/` to the backend. The host port listens on loopback by default. Production disables demo features unless `APP_DEMO_ENABLED=true`. For an external HTTPS entry point, set `APP_ORIGINS` to the actual browser origin and `APP_SESSION_COOKIE_SECURE=true`, and serve `/ray-template/` and `/api/` on the same origin. The example Nginx overwrites forwarded headers. With an outer proxy, configure Nginx real IP to trust only the immediately upstream proxy and check that client-supplied forwarding headers cannot falsify the rate-limit address. If proxy subnets conflict, change `APP_PROXY_NETWORK`, for example to `172.30.68`. For containers using external data services, set correctly encoded `APP_DATABASE_URL` and `APP_REDIS_URL`. For local development with existing services, use `setup --external`.
### Deployment verification for operators and agents {#给部署者和-ai-的验收清单}
1. Verify that the distribution includes `apps/server`, `deploy/compose.yaml`, and `scripts/fullstack.mjs`. Use the container workflow by default, or local development for hot reload. Use a dedicated database and Redis key prefix for existing services. Resolve port conflicts with `APP_PORT` for containers or `ADMIN_DEV_PORT` and `PORT` for local development. Database and Redis port mappings use `POSTGRES_PORT` and `REDIS_PORT`.
2. Prepare PostgreSQL migration permissions, a Redis connection, and private server configuration. Replicas share a `JWT_SECRET` consisting of 32 random bytes encoded as base64url. Use separate keys for different environments. For older workspaces, rerun `setup` or `up` to fill in missing keys. Back up PostgreSQL before migrating. Old tokens require users to sign in again. The initial password is used only when creating the initial account.
3. Check for 200 from `GET /api/health/live` and `GET /api/health/ready`, and for 401 from an unauthenticated `GET /api/admin/route-config`. After sign-in, check User Management, Profile, and Route Management. Set a password for a test account and confirm that a read-only account cannot write. An account with no menu entries should still be able to open Profile.
4. If only liveness passes, inspect Compose `ps -a` and `logs initialize server` for migration, initialization, and connection errors. Use `--env-file apps/server/.env.local -f deploy/compose.yaml --profile app -p <project-name>`. Read redacted logs and keep environment file values private. If the browser still gets 401 after sign-in, check the actual origin, same-origin proxy, and secure cookie setting. For external deployment, also verify HTTPS, backup and restore, and proxy rate limiting.
`node deploy/smoke.mjs` uses an isolated temporary Compose project to check migration, builds, sign-in, routing, CORS, the demo switch, and proxy rate limits. It cleans up only the test resources it creates.
### Generated branches and release assets {#生成分支与-release-资产}
Maintainers can run **Source distributions** manually from `main` in GitHub Actions. By default it verifies and uploads that run's archives. Select `sync_frontend` to rebuild the generated `frontend` branch from the mainline. To attach both source archives and the SHA-256 file to an existing release, supply `release_tag`. The workflow checks the tag version and commit, verifies the archives, and preserves existing assets with the same name.
<!-- fullstack:end -->

View File

@ -0,0 +1,62 @@
# Your first business page {#第一个业务页面}
Start with an order table. Use local data to check the page and menu, then connect a remote query.
## Create the page {#创建页面}
Add this code in `apps/admin/src/views/orders/index.tsx`.
```tsx
import { RTablePro } from '@ray-template/ui/table-pro'
import { defineComponent } from 'vue'
const rows = [{ id: 'ORD-001', customer: 'Demo customer' }]
export default defineComponent({
name: 'Orders',
setup() {
return () => (
<RTablePro
columns={[
{ key: 'id', title: 'Order number' },
{ key: 'customer', title: 'Customer' },
]}
data={rows}
search={[{ key: 'customer', label: 'Customer' }]}
columnStateKey="orders:list"
/>
)
},
})
```
The default row identifier comes from `id` or `key`. Pass `rowKey` to use another field. For a bilingual interface, add the column titles and search prompts to the language packs.
## Add the menu entry {#接入菜单}
Register the component in the `views` allowlist in `apps/admin/src/router/config/views.ts`.
```ts
orders: { load: () => import('@/views/orders'), name: 'Orders' },
```
Add the following record to the initial mock route file `packages/demo-data/src/routes.json`, or return it from your own route API.
```json
{
"path": "/orders",
"name": "Orders",
"component": "orders",
"meta": { "i18nKey": "menu.Orders", "icon": "navigation/table", "order": 20 }
}
```
Add the `Orders` translation to both `menu.json` language files. If the current browser already has a customized route configuration, load the initial configuration in Route Management and save it to the API, or add the record directly in the editor. After reloading, check the menu, the direct URL, and a browser refresh.
User Management under System Management already demonstrates department filtering, remote queries, create and edit flows, details, bulk actions, and API permissions. Use it as a complete example when integrating a feature. [Standard API contract](./backend)
## Connect the API {#接入-api}
Write the order query in `apps/admin/src/api`. Map TablePro pagination and filters to backend fields and replace `data` with `request={loadOrders}`. Return the current page of rows and the filtered total. Follow the [remote TablePro example](../reference/table-pro-examples#远端查询与失败恢复) for sorting, cancellation, and retry.
[TablePro](../reference/table-pro) · [Routes and permissions](./routing) · [Request conventions](./requests)

View File

@ -0,0 +1,80 @@
# Layout and state {#应用布局与状态}
<script setup>
import { withBase } from 'vitepress'
</script>
Open the layout playground or the **Layout** tab in the top bar's Preferences drawer to switch navigation and workspace settings. Desktop modes are side (`side`), top (`top`), mixed (`mixed`), right (`right`), and split (`split`). Mixed mode puts first-level navigation at the top and displays only the active group's children in the sidebar. At widths of 768 px or less, navigation uses a drawer and preserves desktop preferences.
## Live layout playground {#在线布局实验}
Try a different navigation position, pin the header, or change content width. The preview uses Ray Admin's layout and settings components with its own menus and state.
<iframe :src="withBase('/en/playground/shell.html')" title="Ray Admin interactive layout preview" loading="lazy" style="width: 100%; height: 650px; border: 1px solid var(--vp-c-divider); border-radius: 12px;" />
::: details View example source
<<< @/examples/ShellDemo.vue
:::
Press Tab to focus menu items and Enter or Space to expand a group or open a page. Use Up and Down in the sidebar and Left and Right in the top menu. In submenus from the collapsed sidebar or top menu, use the arrow keys to select, Enter to open, and Esc to close.
## Configure the workspace {#配置工作区}
```ts
import { useSettingActions } from '@/store'
const { updateSettingState } = useSettingActions()
updateSettingState('layoutConfig', {
mode: 'mixed',
contentWidth: 'fixed',
contentMaxWidth: 1200,
contentPadding: 24,
})
```
Maximum width ranges from 640 to 2560 px, and padding ranges from 0 to 48 px. The header and footer can stay fixed or scroll with the content. The settings drawer defaults to Comfortable (24 px) and also offers Compact and Centered Reading presets. These presets adjust content width and padding while retaining navigation and fixed-bar settings. The preset area shows the active preset and actual spacing. Manual settings outside the presets show as custom spacing. Existing browser preferences carry forward. Restoring layout defaults applies the new default spacing and resets only `layoutConfig`. Older settings receive defaults for any missing fields.
Content maximization uses `useMaximize`. Close Preferences to see the result. At narrow widths, the exit button floats in the upper-right corner, leaving the content area free. Click the button or press Esc to restore the layout. A refresh resets maximization.
In Appearance, toggle breadcrumbs, tabs, and the footer together. Choose the page transition under **Window and motion**. Enter transitions take 240 ms and exit transitions take 190 ms, with small changes in position and scale. The outgoing page completes its transition before the incoming page enters. A reduced-motion system preference switches pages immediately. Restoring Appearance defaults preserves the current light or dark mode. The watermark panel offers Spaced, Compact, and Horizontal presets, a local preview, and shortcuts to fill in the app title or account nickname. You can adjust the style with the full-page watermark off. Presets preserve text and visibility. Reset buttons affect only the section they belong to.
Under **Preferences → Appearance → Interface display**, enable pill-shaped page tabs to change the tab shape. It defaults to off. The setting survives refresh and is included when exporting or importing preferences.
### Page tabs and breadcrumbs {#页面标签与面包屑}
- Right-click a tab or open its actions menu to move it to the front or protect it. Moving a tab to the front places it at the left edge. Undoing this moves it to the start of the regular tab group. Protected tabs show a pin next to the title, hide the close button, and are protected from individual and bulk closing.
- Drag a tab, or focus it and use Shift + Left or Shift + Right to reorder it. While dragging, a preview follows the pointer and an insertion line marks the drop location. On touch screens, swipe the tab bar to scroll, or hold a tab and drag to reorder. Tabs promoted to the front and regular tabs reorder within their own groups. Order, promotion, and protection survive refresh within the current session.
- Breadcrumbs use the menu icons, including grouped SVG names and image VNodes on code-defined routes. The fallback is an outlined window icon. Narrow screens show the current path item and its icon.
**Preferences → Appearance → Interface display** has five independent switches, all on by default. Turning off tab protection or promotion pauses the effect and retains tab markers. Re-enabling the switch restores the effect. Turning off breadcrumb icons also hides the placeholder. You can turn the placeholder off on its own.
## Menu icons {#菜单图标}
The expanded sidebar, mobile drawer, and top navigation use 20 px icons by default. The collapsed sidebar uses 22 px icons so entries remain identifiable from the glyph. Outline icons react to menu state and light or dark mode. In **Preferences → Menu**, change the icon size or collapsed icon size to apply it immediately. Compact and Comfortable presets adjust width, indentation, and icon size. You can also change collapse behavior, toggle the sidebar, scroll it to the top, or refresh the menu. Layouts without a desktop sidebar disable the sidebar quick actions and retain the configured sizes.
## Replace layout regions {#替换布局区域}
`RLayout` exposes `header`, `sidebar`, `tabs`, `footer`, and `default` slots. Layout mode and visibility settings still apply. For example, the top navigation mode omits the sidebar region. Supply route caching and request cancellation as needed when replacing the `default` content.
## Where state lives {#状态放在哪里}
| State | Entry point | After refresh |
| -------------------------------------------------------- | ----------------------------------------- | -------------------------------------------------------- |
| Loading, mobile drawer, content maximization, and reload | `useRuntimeGetters` / `useRuntimeActions` | New runtime state. |
| Layout, theme, language, and other preferences | `useSettingGetters` / `useSettingActions` | Restores cached preferences and fills missing defaults. |
| Lock screen | Lock Screen Store | Retains the legacy boolean format and syncs across tabs. |
The General panel uses `updateLocale` to keep the UI, component library, and date locale in sync. It also exposes refresh, scroll to top, and cache management. You can adjust the cache limit, and the UI explains the policy. Clearing the cache releases inactive page instances and keeps the current one. Later visits recreate instances according to the cache settings. Refreshing the current page remounts it, so unsaved inputs can be lost. Restoring General defaults resets the dynamic title and cache settings while retaining language, recent pages, and favorites.
Place shared state by responsibility in `apps/admin/src/store/modules` and expose it through store hooks. Choose persisted fields with `pick` or `omit`. Check legacy keys and serialized formats before changing them.
[Layout and slots](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/layout/README.md) · [State and persistence](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/README.md)
[Setting Store](../reference/store/setting) · [Runtime Store](../reference/store/runtime) · [Layout hooks](../reference/hooks/layout)
## Recent pages and favorites {#最近访问和收藏}
Press Ctrl or Command + K on desktop to open search. Search by page name and click a star to add a favorite. With an empty query, it shows favorites and recent pages. Use the arrow keys, Enter, or Tab to operate it. Entries are scoped to the session user ID and restored on refresh. Clearing history keeps favorites. You can also clear the current account's recent pages after confirmation in **Preferences → General**. The cache stores only menu paths. Display resolves them against the current menus, permissions, and translations. On mobile, use the top bar's search button. The navigation drawer has a Close button. A width change preserves the desktop sidebar's collapse preference.
When content should fill the workspace, reuse `--layout-content-height`, `RTablePro autoHeight`, and `--r-table-height`, or Naive UI's `NCard contentScrollable` or `NScrollbar`. Give the parent a definite height. Flex and grid children can use `min-block-size: 0` before hosting internal scrolling. The User Management page scrolls the left and right panels independently on desktop. At narrow widths, the page scrolls vertically, the organization tree has a height limit, and the table retains its own horizontal scrolling.

View File

@ -0,0 +1,76 @@
# Requests, cancellation, and mocks {#接口、取消与-mock}
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
Business code calls functions in `apps/admin/src/api`, which use `request` from `@/axios`. On success, the instance resolves with the response body `T`. On failure, it rejects. The business layer unwraps any additional API envelope. Use an Axios instance that returns the full response when you need raw headers or status codes.
## Interactive example {#交互示例}
<AdminExample path="/axios" title="Send, cancel, and throttle requests" />
::: details View example source
<<< @/../admin/src/views/demo/axios/index.tsx
:::
## Send and cancel requests {#接入请求和取消}
```ts
import { request } from '@/axios'
interface Order {
id: string
customer: string
}
export function loadOrders(
params: Record<string, unknown>,
signal: AbortSignal,
) {
return request<{ data: Order[]; total: number }>({
method: 'get',
url: '/api/orders',
params,
signal,
cancelConfig: { cancel: false },
})
}
```
The default canceler identifies duplicate requests by URL, method, query, and body. It compares the encoded parameter sequence for `URLSearchParams` and the ordered fields, text values, and file instances for `FormData`. The default layout cancels managed requests before the route updates. Callers that supply `signal` or set `cancelConfig.cancel: false` manage cancellation themselves. In the example above, TablePro owns the signal.
## Configuration and interceptors {#配置与拦截器}
- Set `baseURL`, timeouts, and default headers in `apps/admin/src/app-config/request-config.ts`.
- Register plugins in `apps/admin/src/axios/axios-interceptor/{request,response}/provider.ts`. Put request headers, auth responses, and other concerns in the corresponding `plugins`.
- `useRequest` wraps the same client. Call it within an active Vue effect scope.
## Switch from demo to a real service {#从演示切到真实服务}
Development, production preview, and GitHub Pages use the same MSW HTTP mocks. Sign-in, users, routes, people tables, route-demo details, business search options, charts, and request examples all go through the API layer. A service worker under the application base responds in the hosted demo. Table examples with local filtering first fetch data through the API and then sort, paginate, and filter locally. Request and response types and runtime schemas live in `@ray-template/api-contracts`. `@ray-template/http` supplies the transport client.
Set `VITE_API_MOCK=false` and `VITE_API_BASE_URL` to send requests to your own server. See the [backend integration guide](./backend) for request and response formats, error codes, sessions, permissions, and the downloadable OpenAPI definition. Mock changes persist in the current browser. Your backend owns shared data and production sessions.
[Request instance](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/instance.ts) · [Business APIs](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/api/admin/index.ts)
## useRequest and manual execution {#userequest-与手动执行}
Import `useRequest<Response>(fetchOptions, options?)` from `@/axios` to run the given configuration through the template Axios instance. It forwards `options` to vue-hooks-plus, including `manual` and success or error callbacks. Data, errors, loading state, and the execution methods come from the upstream hook. Create it in `setup` or an active effect scope.
```ts
import { useRequest } from '@/axios'
export function useOrderSummary() {
return useRequest<{ total: number }>(
{ url: '/api/orders/summary', method: 'get' },
{ manual: true },
)
}
```
Call `run()` to load manually. The wrapper reads its configuration from `fetchOptions`. For a dynamic service with parameters, import `useHookPlusRequest(service, options?)` from the same entry point and call `request` inside the service. Business code or response interceptors own error notifications. The default interceptors ignore the optional `responseSuccessMessage` and `responseErrorMessage` type fields.
The template injects `Authorization: Bearer <token>` only for the configured API base and preserves caller-provided auth headers. Configure a separate client explicitly for third-party URLs.
[Request hook](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/index.ts) · [Request configuration types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/http/src/types.ts) · [Header injection](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/axios/axios-interceptor/request/plugins/request-headers.ts)

View File

@ -0,0 +1,64 @@
# Routes, menus, and permissions {#路由、菜单与权限}
<script setup>
import RouteConfigDemo from '../../examples/RouteConfigDemo.vue'
</script>
After sign-in, `GET /admin/route-config` returns the routes available to the session, ordered by `meta.order`. Menus and breadcrumbs use the route tree, and Vue Router registers the expanded page records. The initial mock routes live in `packages/demo-data/src/routes.json`. The shell reserves sign-in, profile, and status pages. The default router uses hashes, for example `/ray-template/#/orders`.
## Validate route configuration {#路由配置交互校验}
Change the path, name, or view ID to see the shared validator's result. This example registers the `overview` view.
<RouteConfigDemo />
::: details View example source
<<< @/examples/RouteConfigDemo.vue
:::
## Edit routes and connect the API {#在线编辑与接口接入}
With `routes:write`, the visual and JSON editors load the complete draft from the editor endpoint and save it with `PUT /admin/route-config`. The runtime routes then reload. Mock writes persist in the current browser, and you can switch to a local or built-in configuration. In standard backend mode, the remote configuration is authoritative and load failures surface as errors. If you configured the read-only `VITE_ROUTE_CONFIG_URL`, select the remote source in the JSON editor and enable the remote configuration to resume reading that URL. Save edits to a read-only source locally or export the draft.
The request body is `{ version: 1, routes: [...] }`. Both read and write results are in `data` in the shared `{ code, msg, data }` envelope. `component` must be a registered ID in `router/config/views.ts`. Register the ID for a new frontend page before returning its route from the API. [Standard backend contract](./backend)
## Common metadata {#常用元数据}
| Field | Behavior |
| -------------------------- | -------------------------------------------------------------------------------------------------------- |
| `i18nKey` / `noLocalTitle` | Use a translation key or a literal menu title. |
| `icon` | Use the full group-qualified icon name. Code-defined routes can also supply a VNode. |
| `role` | Applies to menus and guards. Role values must use the same type as the session. |
| `hidden`, `env` | Control menu visibility. Route and API access have their own permission checks. |
| `sameLevel` | A detail page can keep the current menu item and tab, adding its level only to the breadcrumb. |
| `keepAlive` | Makes the page eligible for caching in the content area. |
| `windowOpen` | Opens the configured address when the menu entry is clicked. |
| `ignoreAutoResetScroll` | Allows the page to retain the content area's scroll position. See the scroll utility for details. |
| `extra` | Text, icon, type, and visibility of menu badges. See [useBadge](../reference/hooks/navigation#usebadge). |
Relative child paths inherit the parent path. Built-in examples group routes by purpose and use absolute paths to preserve existing URLs. [Layout and nested route examples](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/demo-data/src/routes.json)
## Sign-in and roles {#登录和角色}
The default sign-in route is `/`. When a user opens a business page without a session, the guard puts the full destination in the sign-in page's `redirect` parameter. After sign-in, it restores only a registered business URL the current role can still access, including its query and hash. Without a valid destination, it opens `/welcome`. For redirect routes, the menu and guard check permissions on the entry, each hop, and the destination. A hidden menu item may still allow direct navigation. In production, validate the session, permissions, and resource ownership on the backend.
## Empty workspace and status pages {#空工作区和状态页}
`/welcome` represents a workspace with no active business route and displays accessible entry points. It is a shell status page, like `/403`, `/404`, and `/500`. These pages stay outside business menus, tabs, history, and page caching. The shell reserves these four paths, their descendants and aliases, and their route names. Local and remote JSON must leave them available to the shell. A custom source may omit `/dashboard` or give it role restrictions.
All business tabs can be closed, including the former home page and the last open tab. Closing the active tab selects an adjacent tab. Closing the last tab or all tabs opens the empty workspace and releases the corresponding KeepAlive instances. Each concrete pathname has one tab. Query or fragment changes update the full address stored with that tab. A role change removes revoked tabs and cached instances without opening another business page automatically.
- `/403` appears for a signed-in user without access to the requested page. Closing the current page from the tab bar returns to the previous accessible page or an open accessible tab, with the workspace as the fallback.
- `/404` indicates a missing destination. `query.from` retains the original target.
- `/500` indicates route resolution or lazy loading failed. Retry is available when `query.from` still exists and is accessible.
Every status page offers a way back to the workspace. Back and Retry validate the destination as an internal, permitted route before using history or query values. `useAppRoot` and the old `appRootRoute` preference still support compatibility reads and writes. The current startup and navigation flow use the workspace behavior above.
## Troubleshoot KeepAlive {#keepalive-排查}
1. Set `meta.keepAlive: true` and give the route a unique `name`.
2. Match the TSX `defineComponent({ name })` or SFC component name to the route name. Check that the lazy-loaded module exports the intended component.
3. Enter from the menu, change some page state, switch to another tab, and return. Also check closing the tab, direct navigation, and reloading. A browser refresh creates new component instances.
4. If you replace the default layout content slot, provide the routing and caching behavior your application needs.
[Route contract](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/router/README.md) · [Guard implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/router/utils/permission.ts)

View File

@ -0,0 +1,36 @@
# Quick start {#快速开始}
This guide uses Ray Template v6. For a v5 project, start with [Moving from v5 to v6](../migration).
The standalone frontend source distribution runs on its own. The full source also includes an optional backend. [Source distributions and startup](./distributions)
## Start the admin workspace {#启动工作台}
Use Node.js 26.13.0 and pnpm 12.16.1. The commands below use nvm.
```sh
git clone https://github.com/XiaoDaiGua-Ray/ray-template.git
cd ray-template
nvm install
nvm use
npm install --global pnpm@12.16.1
pnpm install --frozen-lockfile
pnpm env:check
pnpm dev
```
Open [http://127.0.0.1:9527/ray-template/](http://127.0.0.1:9527/ray-template/). If the port is in use, use the address Vite prints. Sign in with the prefilled form and try the remote query and pagination example under Tables or open the layout playground. You can also use the [live demo](https://xiaodaigua-ray.github.io/ray-template/).
::: warning Demo and production use
The prefilled sign-in form, demo sessions, and mocks illustrate frontend workflows. Connect your own authentication, server-side authorization, and APIs before deploying a production application.
:::
## Start the documentation site {#启动文档}
Run `pnpm docs:dev` in the same workspace. Use the address printed in the terminal and open `/ray-template/docs/en/` to try the TablePro, barcode, and layout examples.
## Related documentation {#相关文档}
[Your first business page](./first-page) · [Moving from v5 to v6](../migration) · [Checks and deployment](./tooling)
[Runtime and dependency manifest](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/package.json) · [Workspace structure and startup](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/docs/architecture.md)

View File

@ -0,0 +1,41 @@
# Checks and deployment {#工程检查与部署}
## Common commands {#常用命令}
| Command | Purpose |
| -------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `pnpm env:check` | Verify the Node and pnpm versions and dependency installation. |
| `pnpm dev` | Synchronize the icon manifest and start Vite. |
| `pnpm harness context` | List task areas. Add `routing`, `table-pro`, or `docs` for implementation and verification pointers. |
| `pnpm harness verify table-pro` | Run targeted tests or project checks for the selected scope. |
| `pnpm harness verify all` | Run full checks and write a local report for integration risk or releases. |
| `pnpm typecheck` | Validate the icon manifest and check types for the application, Node configuration, and tests. |
| `pnpm dev-build` / `pnpm report` | Create a development build or static bundle report. |
| `pnpm build` / `pnpm preview` | Build and preview the admin artifact locally. |
| `pnpm packages:check` | Check public entry points, dependency declarations, and cycles. |
| `pnpm pages:build` | Assemble the admin and docs in `dist/pages`. |
| `pnpm docs:dev` | Start the docs development server. |
| `pnpm docs:check` | Check docs example types and internal links, and build the site. |
| `pnpm docs:preview` | Preview the built documentation site. |
For routine changes, run the relevant test files or `pnpm harness verify <scope>`, then add formatting, ESLint, and type checks as the diff requires. Wording, comment, and maintainer documentation edits can use source review and formatting checks. Run `pnpm harness check` when indexes change. Run full checks once near completion for integration risk such as dependencies, public exports, or build configuration, or when a release or explicit request calls for them. Pages builds independently. The full local entry point is `pnpm check`.
Full checks cover the environment, Harness, API and package boundaries, icon synchronization, types, ESLint, Prettier, Vitest, and both admin and docs builds. `pnpm harness verify` with no scope still runs the full suite. Specify a scope for routine work. Harness saves command results in `.harness-local/runs/`. Browser acceptance runs separately from these commands.
Record browser checks for the affected behavior. Exercise the relevant page for interaction changes, add desktop and narrow widths for layout changes, check light and dark themes for color changes, and check both English and Chinese for copy or localization changes. For shared functionality, choose representative consumers with different usage. Logic, maintainer notes, and prose-only reader documentation can be verified without a browser. Once a check passes, rerun it only if a later change affects it.
## Deploy under a subpath {#部署到子路径}
`pnpm build` outputs `dist/production`. Deploy it at the path configured as `base` in `vite.custom.config.ts`. The default application base is `/ray-template/`. Use `/` to deploy at the domain root. Vite bundles local dependencies by default. If using the optional CDN mode, verify CDN access in the target environment.
Run `pnpm pages:build` for a combined site in `dist/pages`. The hosted admin lives at `/ray-template/`, the v6 docs at `/ray-template/docs/`, and the English docs at `/ray-template/docs/en/`. The Pages workflow builds on Ubuntu 24.04 for each push to `main` and deploys a GitHub Pages artifact. Manual publication from `main` is also available. Set `RAY_TEMPLATE_SOURCE_REF` at build time to pin documentation source links to the release commit. In the repository, choose **GitHub Actions** under **Settings → Pages → Source** and confirm that the `github-pages` deployment environment allows `main`.
For a public production deployment, set `RAY_TEMPLATE_SITE_ORIGIN` to the actual origin, such as `https://example.com`. The base supplies the path. Admin builds default to `noindex` without that setting. The sitemap lists public entry pages. Signed-in hash routes serve application navigation.
## Development conventions {#二次开发约定}
- Use the Vue 3 Composition API with TSX or follow the existing SFC patterns. Reuse existing components and organize declarations by responsibility.
- Generate Vue, Router, and Pinia auto-import declarations through their generators. Use `import type` for types. The application, tests, and Node configuration have separate TypeScript boundaries.
- Prettier manages formatting. ESLint uses flat config. Follow the repository's current commit and comment conventions.
[Build and deployment entry points](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/docs/architecture.md) · [AI Harness](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/harness/README.md) · [Comment style](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/docs/comment-style.md)

11
apps/docs/en/index.md Normal file
View File

@ -0,0 +1,11 @@
---
title: Developer Documentation
layout: home
markdownStyles: false
---
<script setup>
import RayHome from '../.vitepress/theme/RayHome.vue'
</script>
<RayHome />

25
apps/docs/en/migration.md Normal file
View File

@ -0,0 +1,25 @@
# Moving from v5 to v6 {#v5-与-v6-的版本分界}
**Ray Template 6.0.0 starts a new major release line.** v6 reorganizes the admin application, documentation site, and shared packages into a monorepo. In-place upgrades from v5 are unsupported. Review internal import paths, APIs, deployment settings, and browser data before migrating. Existing v5 projects can stay on v5.
| Version | Where to start |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **v6.0.0** | Start new projects from the v6 workspace. See [Quick start](./guide/start) and [v6 Monorepo Architecture](./guide/architecture). |
| **v5** | [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) preserves the complete source before the split. The branch points to `6f095b7` with manifest version `5.2.5`. For a tagged snapshot, use [v5.2.4](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.4). |
## What changed in v6 {#v6-的变更}
| Area | v6 entry points and conventions |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Application structure | The former root `src/`, `mock/`, `public/`, app environment files, and `index.html` moved under `apps/admin/`. Review environment variables, container configuration, and build scripts against the v6 entry points. |
| Components and utilities | Import shared code through each package's public entry points, such as `@ray-template/ui/table-pro`, `@ray-template/composables/useDevice`, and `@ray-template/utils/precision`. Within Ray Admin, `@/` resolves to the application's own `src/`. |
| Component integration | In v6, `RTablePro` accepts either `data` or `request(params, signal)`. `useTablePro` retains `[register, actions]` and `onRegister`. Use the [current API](./reference/table-pro#usetablepro) for requests and instance methods. |
| Routing, permissions, and requests | Shared packages provide route validation, the HTTP client, and the layout. Ray Admin supplies the view registry, session handling, access checks, request headers, themes, and language. |
| Docs and demo | The VitePress site in `apps/docs/` runs examples through public package exports. The hosted admin is at `/ray-template/` and the docs are at `/ray-template/docs/`, with English at `/ray-template/docs/en/`. |
## Adopt v6 in an existing project {#现有项目采用-v6}
1. Start from a new workspace or branch. Keep a way to roll back to your v5 code and deployment. Configure dependencies, environment variables, API endpoints, and CI for v6.
2. Move pages, endpoints, and menus one feature at a time. Review old deep imports, route JSON, and custom interceptors against the [page example](./guide/first-page), [routing conventions](./guide/routing), and [TablePro API](./reference/table-pro).
3. Verify v6 with a separate browser profile or deployment origin. `localStorage` is scoped to the origin, so different paths on the same host share session and preference storage. Existing settings, lock state, cache, and sign-in state require project-specific migration.
4. Check sign-in, permissions, direct navigation, APIs, caching, and deployment paths before switching traffic. Run `pnpm harness verify`. Use `pnpm pages:build` for a combined deployment. [Checks and deployment](./guide/tooling)

View File

@ -0,0 +1,14 @@
---
layout: page
navbar: false
sidebar: false
footer: false
---
<script setup>
import { defineClientComponent } from 'vitepress'
const ShellDemo = defineClientComponent(() => import('../../examples/ShellDemo.vue'))
</script>
<ShellDemo locale="en" />

View File

@ -0,0 +1,25 @@
# Components {#组件}
Import shared components from `@ray-template/ui` or use subpaths such as `/table-pro` and `/barcode`. Inside Ray Admin you can also use `@/components`. The route transition lives in `@ray-template/admin-shell`, and the application supplies current route and cache state. This reference lists props, slots, and events the template adds, overrides, or uses. For inherited functionality, consult the types in the pinned Naive UI dependency.
| Component | Props type | Purpose |
| ----------------------------------------------------- | --------------------------------- | --------------------------------------------------------------------------------------------- |
| [RTablePro](./table-pro) | `TableProProps` | Bare tables, remote queries, automatic height, column settings, export, and optional printing |
| [RForm](./components/form) | `FormProps` | Form loading, validation, reset, and keyboard submission |
| [RModal](./components/modal) | `ModalProps` | Controlled modal, preset widths, and fullscreen cards |
| [RChart](./components/chart) | `ChartProps` | ECharts initialization, themes, and export |
| [RFlow](./components/flow) | `FlowProps` | LogicFlow diagrams and read-only mode |
| [RCollapseGrid](./components/collapse-grid) | `CollapseGridProps` | Collapsible filters with action columns |
| [RSegment](./components/segment) | `SegmentProps` | Segmented options, icons, and tooltips |
| [RMoreDropdown](./components/more-dropdown) | `MoreDropdownProps` | Icon menus and row actions |
| [RIframe](./components/iframe) | `IframeProps` | Embedded pages with loading state |
| [RBarcode](./components/barcode) | `BarcodeProps` | Canvas and SVG barcodes |
| [RDraggableCard](./components/draggable-card) | `DefaultPosition` (position type) | Draggable card and movement boundaries |
| [RTransitionComponent](./components/route-transition) | `TransitionComponentProps` | Route transitions and KeepAlive |
| [RIcon](./icons#ricon-api) | `IconProps` | Typed SVG sprites |
Import [App Components and Providers](./components/app) by file. These use template state, themes, or routing. [QR codes](./components/qr-code) use `vue3-next-qrcode` directly.
Each component directory contains its implementation, styles, and types. Prop definitions such as `formProps`, `modalProps`, and `chartProps` also have named exports. Application code normally uses the component and public prop types. To get a TablePro instance directly, use a component ref. `RForm`, `RChart`, and `RFlow` use their respective `onRegister` contracts.
[Public exports](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/index.ts) · [Component conventions](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/components/README.md) · [Example source](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main/apps/admin/src/views/demo)

View File

@ -0,0 +1,57 @@
# App Components and Providers {#应用组件与-provider}
Use default imports by file, for example `import AppPageHeader from '@/app-components/app/AppPageHeader'`. These components depend on application stores, routing, or the DOM. Integrate them in the [default App mount order](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/App.tsx).
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
## Admin context example {#后台上下文示例}
This preview runs the admin dashboard and layout. Use the Template Hooks entry in the sidebar to change the theme, watermark, layout loading state, and menu state. Version prompts, request cancellation, and other providers belong to application initialization.
<AdminExample path="/dashboard" title="Admin dashboard, layout, and providers" layout />
::: details View the preview entry point and dashboard source
<<< @/../admin/src/documentation-example.tsx
<<< @/../admin/src/views/dashboard/index.tsx
:::
## Page components {#页面组件}
| Component | Configuration and behavior |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AppPageHeader` | `title` is required. `description` defaults to empty, and `eyebrow` defaults to `RAY TEMPLATE`. Place action buttons in the default slot on the right and page content outside the component. |
| `AppShareLink` | `variant: 'compact' \| 'cards'` defaults to `compact`. Text comes from the dashboard messages. The component defines its own links. |
| `AppAvatar` | Reads avatar and name from Signing Store. `avatarSize` and `spaceSize` default to `medium`, and `vertical` defaults to `false`. Avatars are round and use cover sizing. The first character of the name is the fallback. Internally derived `src` and `size` take precedence. |
| `AppGlobalSpin` | Accepts NSpin props and slots. Runtime Store's `globalSpinning` controls visibility and overrides `show`. The layout content spinner is independent. |
| `AppLockScreen` | `setting.lockScreenSwitch` controls the setup dialog. The dialog stays open on backdrop clicks and Esc. After locking, the layout reads Lock Screen Store to render the unlock screen. |
```tsx
import AppPageHeader from '@/app-components/app/AppPageHeader'
import { NButton } from 'naive-ui'
export const renderOrdersHeader = (create: () => void) => (
<AppPageHeader
eyebrow="Inventory"
title="Orders"
description="View and manage sales orders"
>
<NButton type="primary" onClick={create}>
New order
</NButton>
</AppPageHeader>
)
```
## Providers {#provider}
| Provider | Responsibilities and lifecycle |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AppNaiveGlobalProvider` | Wraps the default slot and syncs color mode, theme overrides, UI locale, and date locale. Provides Message, Dialog, Modal, Notification, and LoadingBar contexts and assigns `window.$message`, `$dialog`, `$notification`, and `$loadingBar`. Discrete APIs are available after initialization and released on unmount. Call them after the provider is ready. |
| `AppStyleProvider` | Syncs HTML color-mode classes, CSS primary color, and viewport variables, and ends the startup animation. Use settings actions to change the theme. |
| `AppVersionProvider` | Compares the built version with the cached version at startup. The first startup writes the version. On version change, confirming the prompt signs out and reloads, and canceling closes the prompt. |
| `AppWatermarkProvider` | Renders a full-page Naive UI watermark from preferences. Standalone pages can place `NWatermark` in a local region. |
| `AppRequestCancelerProvider` | Cancels template-managed requests from the route update hook in the default content area. Preserve cancellation as needed when replacing the content slot. |
[App components](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/app-components/README.md) · [Layout settings](../../guide/layout) · [Stores](../store) · [Request cancellation](../../guide/requests)

View File

@ -0,0 +1,54 @@
# RBarcode
<script setup>
import { defineClientComponent } from 'vitepress'
const RBarcodeDemo = defineClientComponent(() => import('../../../examples/RBarcodeDemo.vue'))
</script>
`RBarcode` renders strings as barcodes with JsBarcode. Use the [QR code component](./qr-code) for QR codes.
## Interactive example {#交互示例}
Edit the text or change the symbology to see the barcode and validation feedback. The example loads `RBarcode` directly.
<RBarcodeDemo />
::: details View example source
<<< @/examples/RBarcodeDemo.vue
:::
## Usage {#用法}
```tsx
import { RBarcode } from '@/components'
export const renderOrderBarcode = (orderNo: string) => (
<RBarcode
text={orderNo}
format="CODE128"
barcodeRender="svg"
options={{ displayValue: true, height: 60 }}
onError={(error) => console.error('Invalid barcode format', error)}
/>
)
```
| Prop | Default | Description |
| ------------------ | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `text` | None | Barcode content. Empty or invalid values can fail to render. |
| `format` | `'CODE128'` | Symbology. Overrides `options.format`. |
| `barcodeRender` | `'canvas'` | `canvas` or `svg`. |
| `options` | `{}` | JsBarcode options, for example `displayValue`, `lineColor`, `margin`, and bar width and height. |
| `width` / `height` | `'auto'` | Display dimensions. Numbers are pixels. Set intrinsic bar width and height in `options`. |
| `responsive` | `false` | Observes the container. Use `width="responsive"` or `height="responsive"` for the corresponding dimension to follow its size. |
| `watchText` | `true` | Redraws on text changes. Changes to `format`, `options` (including nested reactive fields), dimensions, or rendering medium also redraw with the same key. |
| `loading` | `false` | Caller-controlled spinner. |
`responsive width="responsive" :height="48"` follows container width and keeps a 48 px height. Give the parent a definite height when using responsive height.
`onSuccess(text, format, options)`, `onError(error)`, and `onFinally()` accept one callback or an array. The success callback receives the original options. Responsive bar dimensions are internal. Rendering errors call `onError` so the caller can notify users or clear an old preview.
Supported formats are `CODE39`, `CODE128` and its `A/B/C` variants, `EAN13/EAN8/EAN5/EAN2`, `UPC`, `ITF14/ITF`, `MSI/MSI10/MSI11/MSI1010/MSI1110`, `pharmacode`, and `codabar`. Validate length and check digits for EAN or UPC. Verify printed barcodes on the intended scanner and at the final dimensions.
[Component implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RBarcode/src/Barcode.tsx) · [Format and option types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RBarcode/src/types.ts)

View File

@ -0,0 +1,74 @@
# RChart and useChart {#rchart-与-usechart}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RChart` takes ECharts options and manages the instance, theme changes, resize observation, and cleanup. Give the container a definite height. `height="100%"` depends on the parent's height. The page owns chart data and series configuration.
```tsx
import { RChart, useChart } from '@/components'
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const [register] = useChart()
return () => (
<RChart
onRegister={register}
preset="card"
title="Orders this week"
height={300}
options={{
xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed'] },
yAxis: { type: 'value' },
series: [{ type: 'bar', data: [12, 19, 14] }],
}}
/>
)
},
})
```
## Interactive example {#交互示例}
<AdminExample path="/echart" title="Render and update a chart" />
::: details View example source
<<< @/../admin/src/views/demo/echart/index.tsx
:::
## Rendering, themes, and updates {#渲染、主题与更新}
| Prop | Default | Description |
| ---------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `options` | `{}` | ECharts options. `showAria` defaults to `false`. The component controls `aria.enabled` and `aria.decal.show` and preserves other ARIA settings. |
| `width` / `height` | `'100%'` | CSS dimensions. Numbers are pixels. |
| `use` | `[]` | Extra ECharts registrations. The built-in registrar covers bar, line, pie, candlestick, scatter, and pictorial bar series, the Canvas renderer, and base modules such as titles, tooltips, grids, datasets, and legends. |
| `intersectionObserver` | `true` | Initializes when the target intersects. Hidden charts may have no instance yet. Starts immediately in browsers without intersection observation. |
| `intersectionObserverTarget` / `intersectionOptions` | Container / `{ threshold: 0.1 }` | Custom observation target and options. |
| `autoResize` / `autoResizeObserverTarget` | `true` / chart container | Throttles resize on container size changes. |
| `watchOptions` / `watchDeep` | `true` / `true` | Watch options and choose deep observation. |
| `watchOptionsThrottleWait` | `500` | Options update throttle interval in milliseconds. |
| `nextTick` | `true` | Await the Vue update before initialization. |
| `setChartOptions` | `{ notMerge: true, lazyUpdate: true, silent: false, replaceMerge: [] }` | ECharts `setOption` controls. |
| `theme` / `autoChangeTheme` | `null` / `true` | Follow the app's four styles and color mode. Pass a registered name for a fixed theme. |
| `loading` / `loadingOptions` | `false` / current chart theme | Show the ECharts loading mask and override selected default styles. |
The default is `ray-modern`, `ray-naive`, `ray-material`, or `ray-plain`, with a `-dark` variant for each. `theme="default"` uses the built-in ECharts theme and follows app color mode when `autoChangeTheme=true`. Another explicit registered theme stays fixed. Set `autoChangeTheme=false` to disable automatic dark variant selection. The older `macarons` and `macarons-dark` themes have been removed.
The eight themes coordinate canvas, text, legend, axes, tooltips, and series colors with the corresponding card surfaces. Modern uses cool tones, Naive starts with green, Material uses purple and soft tones, and Plain uses a subdued categorical palette. Changing the application primary color leaves chart series colors intact. Explicit page options take precedence.
The default loading mask uses the chart palette. Transparent or invalid backgrounds in custom themes fall back to the corresponding light or dark surface to avoid a black mask. Use `loadingOptions` to override the mask, text, or spinner.
Theme switching calls ECharts 6 `setTheme`, keeping the instance and listeners. ECharts rebuilds its option model and can reset legend selection, zoom, and incremental options set in merge mode. Supply the complete `options` to retain these values.
## Card preset and callbacks {#卡片预设和回调}
- `preset="card"` uses Naive UI Card and supports `title` (string or render function), `bordered` (default `true`), and `contentStyle`. Replace the upper-right content with `cardExtra`.
- The default menu includes image download. `downloadOptions` accepts ECharts `getDataURL` options and an optional `filename`. `dropdownOptions` replaces the menu and `onDropdownSelect(key, option)` reports the selection.
- Initialization success calls `onRegister(instance, render, dispose)`, `onSuccess(instance)`, and `onFinally()` in order. Failure disposes the instance, calls `onError()` and `onFinally()`, and reports through Vue error handling. The initial options render synchronously so the registration callback can read the chart. Later updates follow `setChartOptions`.
`useChart()` returns `[register, actions]`. `getChartInstance()` returns `{ echartInst, render, dispose }` and throws before registration. `isDisposed()` checks the underlying instance. `dispose()` releases it and stops observation. `render()` mounts it again. Update an existing chart through `options` or `setOption`. Unmounting cleans up the chart.
[Props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RChart/src/props.ts) · [Implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RChart/src/Chart.tsx) · [useChart](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RChart/src/hooks/useChart.ts)

View File

@ -0,0 +1,71 @@
# RCollapseGrid
<script setup>
import CollapseGridDemo from '../../../examples/CollapseGridDemo.vue'
</script>
Use this component for search forms with several filters. It renders an `NGrid` and requires `NGridItem` children. Configure it with `cols`, `responsive`, `collapsedRows`, `xGap`, and `yGap`. The default gap is 12, and an explicit `0` is preserved.
## Interactive example {#交互示例}
<ClientOnly>
<CollapseGridDemo />
</ClientOnly>
::: details View example source
<<< @/examples/CollapseGridDemo.vue
:::
| Prop | Default | Description |
| -------------------- | ------------------------------------- | ---------------------------------------------------------------------------- |
| `open` | `false` | Expansion state. `true` expands and `false` collapses. |
| `actionSpan` | `1` | Grid columns occupied by the action area. |
| `actionAlign` | `'end'` | CSS alignment for the actions. Use `auto`, `end`, `center`, or `start`. |
| `collapseToggleText` | `['展开', '收起']` (Expand, Collapse) | Order is the label shown when collapsed, then the label shown when expanded. |
| `bordered` | `true` | Outer card border. |
Use `default` for filter fields, `action` for the search action, and `collapse(collapsed)` to replace the toggle. The custom collapse slot receives a boolean. Wire its button to update `open`.
::: tip Controlled state and update events
`onUpdateOpen` and `onUpdate:open` receive the expanded state and work with `v-model:open`. Remove any inversion added for an older reversed event. Binding both listeners invokes each once. The default button supports keyboard activation and exposes state through `aria-expanded`.
:::
```tsx
import { RCollapseGrid } from '@/components'
import { NButton, NGridItem, NInput } from 'naive-ui'
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const open = ref(false)
return () => (
<RCollapseGrid
open={open.value}
cols={3}
collapsedRows={1}
collapseToggleText={['Expand', 'Collapse']}
onUpdateOpen={(value) => {
open.value = value
}}
>
{{
default: () => [
<NGridItem>
<NInput placeholder="Order number" />
</NGridItem>,
<NGridItem>
<NInput placeholder="Customer" />
</NGridItem>,
<NGridItem>
<NInput placeholder="City" />
</NGridItem>,
],
action: () => <NButton type="primary">Search</NButton>,
}}
</RCollapseGrid>
)
},
})
```
[Component implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RCollapseGrid/src/index.tsx) · [Props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RCollapseGrid/src/props.ts)

View File

@ -0,0 +1,44 @@
# RDraggableCard
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
The component uses Naive UI Card and Interact.js. It teleports the card to an application-managed container outside the original parent's layout flow. With a title, drag the header. Otherwise, drag the content. Resizing is outside the component's interaction model.
| Prop | Default | Description |
| --------------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `dad` | `true` | Enables dragging. |
| `restrictionElement` | `'body'` | Movement boundary. Accepts a CSS selector, an element, or a target Vue can unwrap. Selectors use the first match. |
| `restrictRectOptions` | Default boundary, `endOnly: true` | Overrides the Interact.js restriction. |
| `defaultPosition` | `{ x: 0, y: 0 }` | Offset relative to the boundary or a named preset. |
| `padding` | None | `{ x, y }` spacing from the boundary on initial placement. |
| `width` / `zIndex` | `600` / unspecified | Card width and stacking order. |
| `animation` | `false` | Enables the entrance transition. |
Position presets are `top-left`, `top-right`, `bottom-left`, `bottom-right`, `center`, `top-center`, and `bottom-center`. Replacing `defaultPosition`, `padding`, or the boundary reference repositions the card. Toggling `dad` keeps its current position. Drag events and position persistence are internal. Use a selector that exists in the layout and a boundary with a definite size. Drag DOM and interaction initialize after browser mount. Disabling dragging or unmounting releases listeners, and the last card to unmount removes the shared container. The component inherits Card props and slots. Its entrance transition honors reduced motion.
## Interactive example {#交互示例}
<AdminExample path="/draggable-card" title="Drag a card within its movement boundary" />
::: details View example source
<<< @/../admin/src/views/demo/draggable-card.tsx
:::
```tsx
import { RDraggableCard } from '@/components'
export const renderFloatingHelp = () => (
<RDraggableCard
title="Help"
width={320}
defaultPosition="bottom-right"
padding={{ x: 24, y: 24 }}
>
Drag the header to move this card.
</RDraggableCard>
)
```
[Component source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RDraggableCard/DraggableCard.tsx)

View File

@ -0,0 +1,69 @@
# RFlow and useFlow {#rflow-与-useflow}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RFlow` creates LogicFlow in its own DOM container. `FlowGraphData` has optional `nodes` and `edges` arrays. Both `NodeConfig` and `EdgeConfig` require stable IDs, and edge sources and targets must reference existing nodes.
## Interactive example {#交互示例}
<AdminExample path="/flow" title="Flow diagram and read-only mode" />
::: details View example source
<<< @/../admin/src/views/demo/flow-demo.tsx
:::
```tsx
import { RFlow } from '@/components'
import type LogicFlow from '@logicflow/core'
import { defineComponent } from 'vue'
const graph = {
nodes: [
{ id: 'start', type: 'rect', x: 100, y: 90, text: 'Start' },
{ id: 'review', type: 'rect', x: 300, y: 90, text: 'Review' },
],
edges: [
{
id: 'start-review',
type: 'polyline',
sourceNodeId: 'start',
targetNodeId: 'review',
},
],
} satisfies Parameters<LogicFlow['render']>[0]
export default defineComponent({
setup: () => () => (
<RFlow
height={240}
readonly
onRegister={(instance) => instance.render(graph)}
/>
),
})
```
| Prop | Default | Description |
| ---------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `width` / `height` | `'100%'` | Container dimensions. Give it a resolvable height. |
| `data` | None | Renders on mount and when the reference changes. Setting it to `undefined` clears the graph. In-place nested mutation does not redraw it. |
| `watchData` | `true` | Watches the supplied data. Disable it for instance-controlled rendering. |
| `readonly` | `false` | Enables LogicFlow silent mode. Leaving restores the prior interaction and keyboard settings, including anything the caller disabled. |
| `options` | Grid on, `partial: false`, keyboard on | LogicFlow setup for size, background, keyboard, edges, interaction, history, and plugins. The component owns `container`. |
| `use` | None | Registers the component's LogicFlow global plugins before initialization. LogicFlow deduplicates by name. Use `options.plugins` for instance-level plugins. |
| `onRegister(instance)` | None | Provides LogicFlow after mount. Accepts one callback or an array. |
`FlowOptions` groups these fields by purpose.
- Canvas and layout include `width`, `height`, `background`, `grid`, `partial`, `style`, and `overlapMode`.
- Interaction includes `keyboard`, `adjustEdge`, `allowRotate`, `allowResize`, `isSilentMode`, `stopScrollGraph`, `stopZoomGraph`, `stopMoveGraph`, `textEdit`, `textMode`, `edgeTextMode`, `nodeTextMode`, and `guards`.
- Edges and rendering include `edgeType`, `customTrajectory`, `animation`, `history`, `outline`, and `snapline`.
- Extensions include `plugins`, `pluginsOptions`, `disabledPlugins`, `disabledTools`, `idGenerator`, and `edgeGenerator`.
Use `FlowGraphData` for the wrapper's props. For direct calls to `instance.render`, use `Parameters<LogicFlow['render']>[0]` to retain LogicFlow's required node types, coordinates, and connection fields.
`useFlow()` returns `[register, { getFlowInstance }]`. Pass `register` to `onRegister` and supply initial data through `data`. Calling `getFlowInstance()` before registration or after unmount throws. The component destroys the LogicFlow instance on unmount. Use that instance for programmatic editing, imports, and listeners, and clean up external resources you create.
[Implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RFlow/src/Flow.tsx) · [Graph and option types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RFlow/src/types.ts) · [Instance hook](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RFlow/src/hooks/useFlow.ts)

View File

@ -0,0 +1,94 @@
# RForm and useForm {#rform-与-useform}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RForm` wraps Naive UI Form and uses a spinner for submission or loading. Match `NFormItem.path` to the `model` field and update the value from the input.
```tsx
import { RForm, useForm } from '@/components'
import { NButton, NFormItem, NInput } from 'naive-ui'
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const [register, form] = useForm(
{ name: '' },
{
name: {
key: 'name',
required: true,
message: 'Enter a name',
trigger: 'blur',
},
},
)
const rules = form.formRules()
const submit = async () => {
await form.validate()
console.log(form.formConditionRef.value.name)
}
return () => (
<RForm
onRegister={register}
model={form.formConditionRef.value}
rules={rules}
>
<NFormItem label="Name" path="name">
<NInput
value={form.formConditionRef.value.name}
onUpdateValue={(name) => form.updateFormCondition({ name })}
/>
</NFormItem>
<NButton onClick={() => void submit().catch(() => {})}>
Validate and submit
</NButton>
<NButton onClick={() => form.reset()}>Reset</NButton>
</RForm>
)
},
})
```
## Interactive example {#交互示例}
<AdminExample path="/form" title="Validate and reset a form" />
::: details View example source
<<< @/../admin/src/views/demo/form/index.tsx
:::
## Props and events {#属性与事件}
The component inherits public `NForm` props and `onSubmit` and forwards the default slot to `NForm`.
| Prop | Default | Description |
| -------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `loading` | `false` | Caller-controlled outer spinner. |
| `loadingDescription` | None | Loading description. |
| `autocomplete` | `'off'` | Written to the form element on mount. |
| `submitWhenEnter` | `false` | Can be enabled dynamically for single-line input. Successful validation calls `onFinish`. Repeated submissions are ignored while loading or while a prior submission is pending. |
| `onFinish` | None | Called after Enter-triggered validation succeeds. Custom submit buttons should call `validate()` and perform the submission. |
| `onRegister(inst)` | None | Provides the Naive UI Form instance after mount. Accepts a callback or array. |
Enter keeps its native behavior for IME confirmation, multiline input, comboboxes, buttons, modifier keys, and controls that already called `preventDefault()`. The form displays validation failures from keyboard submission. Vue error handling receives exceptions from `onFinish`. Handle rejected `useForm.validate()` promises. Access Form instance methods through the registration hook.
## useForm
`useForm(model?, rules?)` returns `[register, actions]`. Bind `register` to `onRegister`. Initial values and rules can be objects or factories. Objects are deep-cloned. Factory results are used directly, so return a new object each time.
| Return value | Behavior |
| ------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `formConditionRef` | Reactive model for `RForm.model` and input bindings. |
| `formModel()` / `formRules()` | Get fresh initial model and rules. |
| `getFormInstance()` | Get the registered instance. Throws before registration or after unmount. |
| `validate(callback?, shouldRuleBeApplied?)` | Forwards Naive UI validation. Handle rejection on failure. |
| `validateTargetField(key)` | Selects rules by their unique `key`, which can differ from `NFormItem.path`. |
| `restoreValidation()` | Clears validation and retains input. |
| `updateFormCondition(values)` | Shallow-merges the current model and keeps initial values. |
| `reset(values?)` | Merges initial values with overrides and clears validation. Dynamically added fields remain. |
Call instance methods after the form mounts and registers. Declare nullable fields in the initial model and use an empty value appropriate for each input. When updating nested fields, account for the shallow merge.
[Component source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RForm/src/Form.tsx) · [useForm source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RForm/src/hooks/useForm.ts) · [Form example](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/demo/form/index.tsx)

View File

@ -0,0 +1,37 @@
# RIframe
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RIframe` wraps a native iframe and Naive UI Spin. Embed pages that permit it. The embedded page's CSP, framing permissions, and same-origin policy still apply. The `load` event signals a frame load. Verify business content separately where needed.
## Interactive example {#交互示例}
<AdminExample path="/iframe" title="Embedded page and loading state" />
::: details View example source
<<< @/../admin/src/views/demo/iframe/index.tsx
:::
```tsx
import { RIframe } from '@/components'
export const renderReport = (url: string) => (
<RIframe src={url} title="Inventory report" height={460} lazy="eager" />
)
```
| Prop | Default | Description |
| ------------------------------------ | -------- | ------------------------------------------------------------------------------ |
| `src` | Required | iframe URL. If it comes from user input, enforce application-approved origins. |
| `width` / `height` | `'100%'` | CSS dimensions. Percentage heights depend on the parent. |
| `frameborder` | `0` | Template border style value. |
| `iframeWrapperClass` / `iframeClass` | None | Classes for the wrapper and native iframe. |
| `title` / `name` / `allow` | None | Native iframe attributes. Provide `title` for assistive technology. |
| `lazy` | `true` | `true` or `'lazy'` defers loading. `false` or `'eager'` loads eagerly. |
| `customSpinProps` | `{}` | NSpin configuration. Internal state controls `show`. |
`onSuccess(iframe, event)` and `onError(event)` accept a callback or array. Each `src` change shows the spinner until `load` or `error`. The component ref exposes the native element as `iframe` and its compatibility alias `iframeInst`, both `null` before mounting. Vue already unwraps them. Additional slots go to Spin, and the iframe remains the default content.
[Component implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RIframe/src/Iframe.tsx) · [Props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RIframe/src/props.ts)

View File

@ -0,0 +1,64 @@
# RModal and dialogs {#rmodal-与弹窗}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RModal` inherits Naive UI Modal's `show`, `preset`, close events, and slots, then adds preset widths and fullscreen cards. Control declarative modals with `show` and `onUpdateShow` or `v-model:show`.
```tsx
import { RModal } from '@/components'
import { NButton } from 'naive-ui'
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const show = ref(false)
return () => (
<>
<NButton
onClick={() => {
show.value = true
}}
>
View report
</NButton>
<RModal
show={show.value}
onUpdateShow={(value) => {
show.value = value
}}
preset="card"
title="Inventory report"
cardWidth={960}
>
Report contents
</RModal>
</>
)
},
})
```
| Prop | Default | Applies to |
| ------------- | ------- | ----------------------------- |
| `width` | `600` | Width without a preset. |
| `cardWidth` | `600` | Width with `preset="card"`. |
| `dialogWidth` | `446` | Width with `preset="dialog"`. |
| `fullscreen` | `false` | Card preset only. |
Widths accept numbers or CSS dimensions. `fullscreen` stretches the card across the viewport and scrolls overflowing body content. It is a layout mode outside the browser Fullscreen API. Slots such as `default`, `header`, and `footer` are forwarded with their Naive UI preset behavior.
## Interactive example {#交互示例}
<AdminExample path="/modal-demo" title="Declarative and imperative modals" />
::: details View example source
<<< @/../admin/src/views/demo/modal-demo/index.tsx
:::
## Imperative modals {#命令式弹窗}
`useModal()` from `@/components` is deprecated. Legacy integrations can still call `create(options)` and `destroyAll()`. `create` returns a Naive UI modal handle and accepts compatibility options such as `fullscreen`, `width`, `cardWidth`, and `dialogWidth`. New code can import `useModal` from `naive-ui` and call it inside an `NModalProvider`. Use declarative `RModal` for the template's fullscreen styles. The global [Dialog provider](./app) can also confirm destructive actions.
[Component source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RModal/src/Modal.tsx) · [Compatibility hook](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RModal/src/hooks/useModal.ts) · [Regression tests](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/__test__/components/modal.spec.ts)

View File

@ -0,0 +1,52 @@
# RMoreDropdown
<script setup>
import MoreDropdownDemo from '../../../examples/MoreDropdownDemo.vue'
</script>
Wraps `NDropdown` with a default more-actions icon for row actions. `options`, `trigger`, `placement`, `onSelect(key, option)`, and controlled visibility follow Naive UI Dropdown.
## Interactive example {#交互示例}
<ClientOnly>
<MoreDropdownDemo />
</ClientOnly>
::: details View example source
<<< @/examples/MoreDropdownDemo.vue
:::
| Prop | Default | Description |
| -------------- | ---------------------------------------- | ----------------------------------------------- |
| `icon` | `'action/more'` | `IconName` using the full group-qualified path. |
| `iconSize` | RIcon default | Trigger icon size. Omission uses 20 px. |
| `cursor` | `'inherit'` | Inherits the parent control's pointer style. |
| `triggerLabel` | Injected translation or `'More actions'` | Accessible name of the default icon button. |
The default trigger is a keyboard-focusable icon button. `placement` defaults to `'bottom-start'` and can be overridden. The `default` slot replaces the entire trigger. Give a custom native button or `NButton` an accessible name. Stop click propagation as needed in a row so opening the menu does not also navigate.
```tsx
import { RIcon, RMoreDropdown } from '@/components'
import { NButton } from 'naive-ui'
export const renderRowActions = (edit: () => void) => (
<RMoreDropdown
trigger="click"
placement="bottom-end"
options={[{ key: 'edit', label: 'Edit' }]}
onSelect={(key) => {
if (key === 'edit') edit()
}}
>
<NButton
text
aria-label="More actions"
onClick={(event) => event.stopPropagation()}
>
<RIcon name="action/more" />
</NButton>
</RMoreDropdown>
)
```
[Component implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RMoreDropdown/src/MoreDropdown.tsx) · [Props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RMoreDropdown/src/props.ts)

View File

@ -0,0 +1,39 @@
# QR Codes {#二维码}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
Ray Template uses `Vue3NextQrcode` from `vue3-next-qrcode` directly. Its public instance type is `QRCodeInst`. The component demo and QR sign-in placeholder both use it.
## Interactive example {#交互示例}
<AdminExample path="/qrcode" title="QR code options and preview" />
::: details View example source
<<< @/../admin/src/views/demo/qrcode/index.tsx
:::
```tsx
import { NButton } from 'naive-ui'
import { defineComponent, ref } from 'vue'
import { Vue3NextQrcode, type QRCodeInst } from 'vue3-next-qrcode'
export default defineComponent({
setup() {
const qr = ref<QRCodeInst>()
return () => (
<>
<Vue3NextQrcode ref={qr} text="https://example.com/report" />
<NButton onClick={() => qr.value?.downloadQRCode()}>Download</NButton>
</>
)
},
})
```
`text` sets the encoded content and redraws on change by default. Adjust appearance with `logoImage`, `backgroundImage`, `gifBackgroundURL`, `dotScale`, and `colorDark`. Test scannability when adding backgrounds. Remote assets are subject to cross-origin and browser loading restrictions.
`status` displays states such as `loading` and `error`. `onReload` notifies the caller on retry. Call `downloadQRCode()` after the instance mounts. A generated QR code represents data. QR sign-in requires a backend to issue and verify the corresponding credential.
[QR code example](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/demo/qrcode/index.tsx) · [QR sign-in entry point](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/login/components/QRCodeSigning/index.tsx)

View File

@ -0,0 +1,33 @@
# RTransitionComponent
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RTransitionComponent` is the template route outlet. It composes `RouterView`, `Transition`, `Suspense`, and `KeepAlive`. It renders the matched component and keys instances by `route.fullPath`, so query and hash changes can also select another instance.
| Prop | Default | Description |
| -------------------- | ---------- | ------------------------------------------------------------ |
| `transitionPropName` | `'fade'` | Vue Transition class prefix. Match the application's styles. |
| `transitionMode` | `'out-in'` | Vue Transition mode. |
| `transitionAppear` | `true` | Runs the transition on the first mount. |
`setting.keepAliveConfig` controls global enablement, capacity, and excluded names. `KeepAlive.include` comes from the KeepAlive Store. To enter the cache, a page's component name must match its route name. The allowlist is saved in the tab's Session Storage. A browser refresh still creates new component instances. In a custom layout slot, render one outlet at the intended route level to avoid double rendering. Transitioned pages use a single root element.
## Interactive example {#交互示例}
<AdminExample path="/multi/multi-menu-one" title="Route transitions and page caching" layout />
::: details View example source
<<< @/../admin/src/views/demo/multi/views/multi-menu-one/index.tsx
:::
```tsx
import { RTransitionComponent } from '@/components'
export const renderPageOutlet = () => (
<RTransitionComponent transitionPropName="fade" transitionAppear={false} />
)
```
[Component source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/admin-shell/src/RouteTransition.vue) · [Cache Store](../store/navigation#keepalive-store) · [Troubleshoot KeepAlive](../../guide/routing#keepalive-排查)

View File

@ -0,0 +1,51 @@
# RSegment
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
`RSegment` renders options in Naive UI Tabs' `segment` mode. Use `value` and `onUpdateValue` or `v-model:value` to change business state. For an uncontrolled initial value, use `defaultValue`. Render page content from the selected value in the caller.
Assistive technology receives a radio group. Name it with `aria-label`. Tab focuses the selected option. Left and Right move between options and skip disabled items. Home and End select the first and last enabled options.
| Prop | Default | Description |
| ---------------- | ------------------------ | ------------------------------------------------------------------------------- |
| `options` | `[]` | `RSegmentOptions[]`. Each option needs a unique `key`. |
| `width` | `'fitContent'` | `'block'` fills the width. `'fitContent'` sizes to content. Numbers are pixels. |
| `themeOverrides` | Built-in segment spacing | Caller overrides are shallow-merged with built-in settings. |
Each option requires `key: string \| number` and `label` (text, VNode, or a render value). Optional fields include `disabled`, `icon` (VNode or function), `popover` (text or Naive UI Popover options with `label`), and `slots.default`. `displayDirective` exists in the type but is not forwarded to options, so it cannot control panel mounting. The component fixes `type="segment"` and its animation. Tab editing, position, pane styles, and other omitted Tabs props are outside this API.
## Interactive example {#交互示例}
<AdminExample path="/segment" title="Segmented options and width" />
::: details View example source
<<< @/../admin/src/views/demo/segment/index.tsx
:::
```tsx
import { RSegment, type RSegmentOptions } from '@/components'
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const selected = ref<string | number>('day')
const options: RSegmentOptions[] = [
{ key: 'day', label: 'Day', popover: 'View by day' },
{ key: 'week', label: 'Week' },
]
return () => (
<RSegment
options={options}
value={selected.value}
onUpdateValue={(value) => {
selected.value = value
}}
/>
)
},
})
```
[Implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RSegment/src/Segment.tsx) · [Option types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RSegment/src/types.ts) · [Omitted Tabs props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RSegment/src/constant.ts)

View File

@ -0,0 +1,25 @@
# Application Configuration {#应用配置}
The application and documentation site have separate configuration entry points. This page covers `@/app-config`, Vite settings, and runtime preferences in Ray Admin. Saved preferences can override source defaults. Use clean browser storage to verify defaults.
| File | Configuration |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `apps/admin/src/app-config/app-config.ts` | `GLOBAL_CLASS_NAMES` for color-mode classes and CSS variables. `MESSAGE_PROVIDER` defaults to five non-dismissible messages. `LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE` defaults to off. Also defines `APP_GLOBAL_LOADING`, `PRE_LOADING_CONFIG`, `APP_CATCH_KEY`, `APP_CATCH_KEY_PREFIX`, and `CONTENT_TRANSITION_OPTIONS`. |
| `apps/admin/src/app-config/design-config.ts` | `APP_THEME` palette, startup brand blue `#3b63d9`, light and dark Modern overrides, and the default ECharts theme. Four presets live in `packages/ui/src/theme-presets.ts`. |
| `apps/admin/src/app-config/local-config.ts` | `LOCAL_OPTIONS`, `SYSTEM_DEFAULT_LOCAL`, `SYSTEM_FALLBACK_LOCALE`, `DAYJS_LOCAL_MAP`, and `DEFAULT_DAYJS_LOCAL`. The app default and fallback are `zh-CN`. |
| `apps/admin/src/app-config/request-config.ts` | `AXIOS_CONFIG` defaults to a relative same-origin base, a five-second timeout, `withCredentials: false`, and JSON Content-Type. |
| `apps/admin/src/app-config/router-config.ts` | `SETUP_ROUTER_ACTION` enables the loading bar and guard by default. Also defines `WHITE_ROUTES` (name allowlist), `SUPER_ADMIN` (empty by default), `LAYOUT_CONTENT_REF`, and `LAYOUT_SIDER_REF`. |
| `apps/admin/src/app-config/regex-config.ts` | `APP_REGEX` for template CSS sizing rules. |
| `vite.custom.config.ts` | `base`, `server`, `buildOptions(mode)`, `alias`, `cdn`, `copyright`, Sass injection, and startup loading configuration. |
## Choose the configuration entry point {#选择改动入口}
- For defaults for layout, menus, tabs, and cache, see [Setting Store](./store/setting) and `apps/admin/src/store/modules/setting/constant.ts`. Existing users can restore defaults in Preferences to check changes.
- For themes and language, see [Themes and localization](../guide/appearance). Maintain the translation files and Day.js and Naive UI locale mappings together.
- For access control, see [Routes, menus, and permissions](../guide/routing). The allowlist matches case-sensitive route names. The guard handles session state before checking the allowlist and role access.
- For API addresses, auth headers, and failure handling, see [Requests and mocks](../guide/requests). Read the required `VITE_*` variables explicitly in Axios configuration.
- The default application base is `/ray-template/`. After changing it, rebuild and check icons, proxies, and direct navigation. [Checks and deployment](../guide/tooling)
Vite injects `__APP_CFG__` at build time for application metadata, copyright, and the default primary color. The browser can read injected values. Store interactive preferences in Pinia and build settings in Vite configuration.
[Application config source](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main/apps/admin/src/app-config) · [Custom Vite config](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/vite.custom.config.ts)

View File

@ -0,0 +1,131 @@
# Directives {#指令}
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
import DebounceDemo from '../../examples/DebounceDemo.vue'
</script>
`main.ts` calls `setupDirectives(app)`. The registrar finds `packages/directives/src/modules/<name>/index.ts`, calls its default factory, and registers the returned Vue directive under the directory name. Use `v-<name>` directly in an SFC. The implementation files define each directive's binding type.
## Interactive example {#交互示例}
Try copy, throttle, debounce, ellipsis, ripple, and disabled behavior in one example. The smaller debounce example below shows the call count.
<AdminExample path="/directive" title="Six directives in one interactive example" :height="550" />
::: details View the full directives example source
<<< @/../admin/src/views/demo/directive/index.tsx
:::
## v-copy
Bind the string to copy. Changing the binding recreates the ClipboardJS instance, and unmounting destroys it. Ray Admin supplies notifications when registering the directive. Standalone consumers of `createCopyDirective` can supply their own callbacks. Trigger copy from a user click. Convert nonstring values such as numbers explicitly.
```vue
<template>
<button type="button" v-copy="'ORD-001'">Copy order number</button>
</template>
```
[Source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/copy/index.ts)
## v-debounce and v-throttle {#v-debounce-与-v-throttle}
Click the button repeatedly. Debounce calls the handler once after 500 ms without further clicks.
<DebounceDemo />
::: details View example source
<<< @/examples/DebounceDemo.vue
:::
Both directives accept `{ func, trigger?, wait?, options? }`. `func` must be a function and can accept the native event. `trigger` defaults to `'click'`, `wait` to 500 ms, and `options` passes through to the corresponding Lodash method. Debounce handles input after a burst stops. Throttle limits a continuing event rate.
```vue
<script setup lang="ts">
import { ref } from 'vue'
const keyword = ref('')
const requestedKeyword = ref('')
const clicks = ref(0)
const applySearch = () => {
requestedKeyword.value = keyword.value
}
const countClick = () => {
clicks.value += 1
}
</script>
<template>
<input
v-model="keyword"
v-debounce="{ func: applySearch, trigger: 'input', wait: 300 }"
/>
<p>Submitted query: {{ requestedKeyword }}</p>
<button type="button" v-throttle="{ func: countClick, wait: 1000 }">
Clicks: {{ clicks }}
</button>
</template>
```
- `options.leading` and `trailing` control execution at the start and end of the interval. Debounce also supports `maxWait`. The directive reads the binding on mount. For changing data, read reactive values inside the original callback.
- Each bound element has independent timing. Unmounting removes its own listener and queued callback. Change the element's `key` to bind a new interval.
- These directives control how often handlers fire. Manage cancellation, concurrency, and idempotency separately for async requests.
[Debounce source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/debounce/index.ts) · [Throttle source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/throttle/index.ts)
## v-ellipsis
`width` is required. Numbers are pixels and strings can be CSS lengths. `type: 'block'` truncates one line. `type: 'line'` uses the `line` count, with one line as the default. `popoverText: true` writes the current text to the native `title`. Styles are written on mount and update. Switching modes or disabling hover text can leave the previous styles or `title`. For frequent changes, use the UI library's ellipsis component or change the node's `key`.
```vue
<template>
<p v-ellipsis="{ type: 'line', line: 2, width: 240, popoverText: true }">
Longer explanatory text is truncated after two lines.
</p>
</template>
```
[Source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/ellipsis/index.ts)
## v-ripple
Omit the binding or pass `true` to enable, and use `false` to disable. Supply `{ class: '...' }` to style the ripple. `.center` starts it in the center, and `.circle` uses circular geometry. Pointer events draw the visual feedback. The wrapping button owns the interaction semantics.
```vue
<template>
<button type="button" v-ripple.center.circle>View details</button>
</template>
```
[Source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/ripple/index.ts) · [Binding and cleanup](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/ripple/utils.ts)
## v-disabled
Native form controls use the Boolean `disabled` attribute. Forms, containers, and custom control roots use `inert`, removing the subtree from keyboard focus and blocking pointer interaction. Set the binding back to `false` to restore interaction. Prefer the component's own `disabled` prop when available.
[Source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/modules/disabled/index.ts)
## Add a directive {#新增指令}
Put each directive in its own directory and default-export the factory. Use `CustomDirectiveFC<HTMLElement, T>` to type the binding. Read the element in `mounted`, handle changes in `updated`, and release listeners, timers, and third-party instances in `beforeUnmount`. Store per-element resources in a `WeakMap` when bindings are independent.
```ts
import type { CustomDirectiveFC } from '@/directives/types'
const focusWhen: CustomDirectiveFC<HTMLElement, boolean> = () => ({
mounted(el, { value }) {
if (value) el.focus()
},
updated(el, { value, oldValue }) {
if (value && !oldValue) el.focus()
},
})
export default focusWhen
```
Save the example as `packages/directives/src/modules/focus-when/index.ts` and use `v-focus-when`. Use a single lower-case kebab-case directory name. The registrar throws if the default export is missing or is not a function.
[Registration entry point](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/index.ts) · [Directive types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/directives/src/types.ts)

View File

@ -0,0 +1,16 @@
# Hooks
Import public template hooks from `@/hooks`. The hooks tied to components, `useForm`, `useModal`, `useChart`, and `useFlow`, come from `@/components` and are documented with each component. Import `useRequest` from `@/axios`.
| Task | Reference |
| ------------------------------------------------------------ | --------------------------------------------- |
| Build menus, navigate, manage tabs, or add menu badges | [Navigation and menus](./hooks/navigation) |
| Maximize, reload, or scroll the content area | [Layout and scrolling](./hooks/layout) |
| Set themes, language, or watermarks | [Themes and localization](./hooks/appearance) |
| Implement pagination or context menus | [Component interactions](./hooks/interaction) |
| Observe viewport size, fill the viewport, or work with dates | [Viewport and dates](./hooks/browser) |
| Capture or print DOM content | [Capture and printing](./hooks/output) |
Create hooks that subscribe, listen, or register cleanup during `setup()` or within an active Vue effect scope. Capture, print, and fullscreen actions should run after DOM mount or on user interaction. `BasicTarget` accepts elements, refs, or getters. [Vue and DOM targets](./utils/browser#vue-目标解析)
`@/hooks/web/useI18n`, `@/hooks/web/useVueRouter`, and `@/hooks/web/usePagination` remain as compatibility imports. Use `@/hooks` in new application code. [Hook implementation and test index](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/README.md)

View File

@ -0,0 +1,77 @@
# Themes, Language, and Watermark Hooks {#主题、语言和水印-hooks}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
## Interactive example {#交互示例}
<AdminExample path="/template-hooks" title="Themes and watermarks" focus="useTheme,useWatermark" layout />
::: details View example source
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useTheme
`useTheme()` returns these methods. Setting Store and the global provider manage color overrides together.
| Method | Behavior |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
| `lightTheme()` / `darkTheme()` | Select manual light or dark mode and update Naive UI theme overrides. |
| `toggleTheme()` | Select the manual mode opposite the current resolved mode. |
| `syncSystemTheme()` | Read the browser preference and switch to `auto`. Setting Store then follows system changes. |
| `getAppTheme()` | Returns `{ theme, themeLabel, themeI18nLabel }`. `theme: true` means dark. `themeLabel` is the literal `Dark` or `Light`. |
`getAppTheme()` returns a snapshot. Call it in a computed value or render function for UI that follows language or theme. Set a custom primary color with `changePrimaryColor` in [Setting Store](../store/setting).
## useI18n
<AdminExample path="/web-hooks" title="Switch the example language and inspect translations" focus="useI18n" />
::: details View language switching source
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
`useI18n(namespace?)` exposes `t(key, ...args)`, `locale(lang)`, and the Vue I18n global API when initialized. `useI18n('menu').t('Dashboard')` and `useI18n('menu').t('menu.Dashboard')` use the same key. Without a namespace, a bare string is returned as written. Before initialization, `t` returns the resolved key. The same function reads the current instance after initialization.
`@/hooks` also exports a standalone `t(key)` that returns the original key for route metadata and static translation tooling. Change the whole application language with `useSettingActions().updateLocale(lang)` to sync Day.js, the UI library, and persisted settings. Calling `useI18n().locale` directly updates only Vue I18n and the HTML language attribute.
```ts
import { useI18n, useTheme } from '@/hooks'
import { useSettingActions } from '@/store'
import { computed } from 'vue'
export function useAppearanceSettings() {
const { t } = useI18n('menu')
const theme = useTheme()
const { updateLocale } = useSettingActions()
const title = computed(() => t('Dashboard'))
return {
title,
followSystem: theme.syncSystemTheme,
switchToEnglish: () => updateLocale('en-US'),
}
}
```
## useWatermark
`setWatermarkContent(content)` merges new watermark text and ignores an empty string. `showWatermark()`, `hiddenWatermark()`, and `toggleWatermark()` change shared visibility. To hide it, use `hiddenWatermark()`. Update font, rotation, and spacing in Setting Store's `watermarkConfig`. The position of `AppWatermarkProvider` determines its scope.
```ts
import { useWatermark } from '@/hooks'
export function useReportWatermark() {
const { setWatermarkContent, showWatermark, hiddenWatermark } = useWatermark()
return {
enable() {
setWatermarkContent('Internal report')
showWatermark()
},
disable: hiddenWatermark,
}
}
```
[useTheme source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useTheme.ts) · [useI18n source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useI18n.ts) · [useWatermark source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useWatermark.ts)

View File

@ -0,0 +1,83 @@
# Viewport, Fullscreen, and Dates {#窗口、全屏和日期}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
import FullscreenDemo from '../../../examples/FullscreenDemo.vue'
</script>
## Interactive example {#交互示例}
<AdminExample path="/web-hooks" title="Viewport width and date ranges" focus="useDevice,useDayjs" />
::: details View example source
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
## useDevice
`useDevice(options?)` returns `width` and `height` refs and a computed `isTabletOrSmaller` ref. The default test is `width <= 768`. Set a custom breakpoint with `options.media`. Other window size options pass to VueUse `useWindowSize`. `observer(isSmaller, { width, height })` runs once immediately, then when size or breakpoint state changes. This API classifies viewport width. For component container width, use CSS or observe the container.
```ts
import { useDevice } from '@/hooks'
import { computed } from 'vue'
export function useListDensity() {
const { isTabletOrSmaller } = useDevice({ media: 900 })
return computed(() => (isTabletOrSmaller.value ? 'small' : 'medium'))
}
```
## useElementFullscreen
Use the button to make the element fill the viewport and restore its original position.
<FullscreenDemo />
::: details View example source
<<< @/examples/FullscreenDemo.vue
:::
`useElementFullscreen(target, options?)` returns `enter()`, `exit()`, `toggleFullscreen()`, and read-only `isFullscreen`. The target must unwrap to an `HTMLElement`. It fills the viewport through CSS fixed positioning, outside the native Fullscreen API. One instance can control a given element at a time.
| Option | Behavior |
| -------------------------------- | ------------------------------------------------------------------------------------------------------- |
| `beforeEnter` / `beforeExit` | Run before overriding or restoring styles. An exception aborts a manual toggle. |
| `enter` / `exit` | Run after the state changes or styles are restored. `enter` runs independently of animation completion. |
| `zIndex` | Stacking order. Defaults to the order in which elements enter. |
| `backgroundColor` / `transition` | Background and transition. Set `'none'` to disable transition. |
Exiting or unmounting restores original inline styles and cancels pending animation frames. Scope disposal restores styles immediately, then calls `exit`. A disposed instance cannot enter again. Bind `exit()` to Esc or a close button if the interaction needs it.
```ts
import { useElementFullscreen } from '@/hooks'
import { ref } from 'vue'
export function usePanelFullscreen() {
const panel = ref<HTMLElement>()
const controls = useElementFullscreen(panel, { transition: 'none' })
return { panel, ...controls }
}
```
## useDayjs
| Method | Behavior |
| ------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `locale(key)` | Sets the global Day.js locale using the app mapping. Unknown keys fall back to the default locale. |
| `isDayjs(value)` | Checks whether the value is a Day.js object. |
| `format(date, { format }?)` | Formats a date. Default is `YYYY-MM-DD HH:mm:ss`. |
| `getStartAndEndOfDay({ format }?)` | Returns `today`, `startOfDay`, `endOfDay`, and the three corresponding `format…` strings. |
| `daysDiff(date1, date2)` | Whole-day difference `date2 - date1`, which may be negative. |
| `isDateInRange(date, { start, end })` | Checks the open interval `start < date < end`, excluding both endpoints. |
Day boundaries follow the current Day.js environment. When the backend groups by a fixed time zone, pass timestamps in a consistent zone and handle interval boundaries in the business layer. Change UI language through Setting Store to update date localization at the same time.
```ts
import { useDayjs } from '@/hooks'
const day = useDayjs()
export const exportDate = day.format('2026-11-03', { format: 'YYYY-MM-DD' })
export const dayRange = day.getStartAndEndOfDay()
```
[useDevice source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useDevice.ts) · [useElementFullscreen source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useElementFullscreen.ts) · [useDayjs source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useDayjs.ts)

View File

@ -0,0 +1,77 @@
# Pagination and Context Menus {#分页与右键菜单}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
## Interactive example {#交互示例}
<AdminExample path="/web-hooks" title="Pagination and context menus" focus="usePagination,useContextmenuCoordinate" />
::: details View example source
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
## usePagination
`usePagination(callback?, options?)` returns a read-only `[pagination, actions]` tuple. `pagination` is reactive configuration for `NPagination` or `NDataTable`. Defaults are page 1, 10 rows per page, and a page-size control with `[10, 20, 50, 100]`. `options` accepts Pagination props except theme and native update callbacks, and adds `pageChange(page)` and `pageSizeChange(size)`.
| Method | Behavior |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `getPage()` / `setPage(page)` | Read the page, or update it and notify callbacks. |
| `getPageSize()` / `setPageSize(size)` | Updating size resets to page 1 before notifying callbacks. |
| `getItemCount()` / `setItemCount(count)` | Read or write the count. A missing count reads as 0. Setting it leaves request callbacks idle. |
| `getPagination()` | Read the current configuration object. |
| `getCallback()` / `setCallback(callback?)` | Read, replace, or remove the shared callback. |
| `resetPagination()` | Returns to page 1. Uses the first `pageSizes` number or object `value`, or 10 if there are no choices. |
Page and page-size changes update state, call the shared `callback`, and then the corresponding specific callback. Reset reads current `pagination.value.pageSizes` and calls both specific callbacks. Default size arrays are independent per instance. For remote data, issue the request only in the shared callback to avoid duplicate loads. The page owns initial loading, data fetching, and row slicing. `RTablePro` already manages pagination when you pass `request`.
```ts
import { usePagination } from '@/hooks'
export function useOrdersPagination(
load: (page: number, size: number) => void,
) {
const [pagination, actions] = usePagination(
() => load(actions.getPage(), actions.getPageSize()),
{ pageSizes: [10, 20, 50], itemCount: 0 },
)
return { pagination, actions, loadFirstPage: () => actions.setPage(1) }
}
```
## useContextmenuCoordinate
`useContextmenuCoordinate(target, options?)` takes an element, ref, or getter. `options` can be a capture boolean, listener options including `clickOutside(event)`, or a ref or getter for either. The listener uses `passive: false` to suppress the browser context menu.
It returns read-only `x` and `y` viewport coordinates, `show`, `updateShow(value)`, and `stop()`. Right-click closes the old menu first, then writes coordinates and opens the menu on the next Vue update. A regular click or outside click closes it. The outside-click callback runs after closing. Call `updateShow(false)` when selecting an item. `stop()` removes listeners and cancels any queued open. The scope also cleans up on disposal.
```tsx
import { useContextmenuCoordinate } from '@/hooks'
import { NDropdown } from 'naive-ui'
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const area = ref<HTMLElement>()
const { x, y, show, updateShow } = useContextmenuCoordinate(area)
return () => (
<div ref={area}>
Right-click here
<NDropdown
trigger="manual"
x={x.value}
y={y.value}
show={show.value}
options={[{ key: 'details', label: 'Details' }]}
onSelect={() => updateShow(false)}
onClickoutside={() => updateShow(false)}
/>
</div>
)
},
})
```
[usePagination source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/usePagination.ts) · [useContextmenuCoordinate source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useContextmenuCoordinate.ts)

View File

@ -0,0 +1,80 @@
# Layout and Scrolling Hooks {#布局与滚动-hooks}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
These APIs operate on the template's default layout. Check [layout slots and instances](../../guide/layout) before replacing the content or sidebar.
## Interactive example {#交互示例}
<AdminExample path="/template-hooks" title="Content loading, maximization, and scrolling" focus="useMaximize,useSpinning,useContentScroll,useSiderScroll" layout />
::: details View example source
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useMaximize
`useMaximize(defaults?)` returns `isLayoutContentMaximized`, its alias `isFullscreen`, `maximize(full, options?)`, and `toggleFullscreen()`. The page, tab menu, and exit button use the same Pinia state. For a single DOM element, use [useElementFullscreen](./browser#useelementfullscreen).
Per-call `options` override `defaults`. Options include `zIndex` (default 999), `backgroundColor`, `transition`, `scrollToOptions: { left?, top?, behavior? }`, `beforeEnter`, `enter`, `beforeExit`, and `exit`. The before callbacks run first. Completion callbacks run on the next Vue update and are independent of CSS animation completion. Entering can adjust scroll position. For rapid toggles, only the latest state's completion callback runs. Selecting the current state returns immediately.
```ts
import { useMaximize } from '@/hooks'
export function useReportLayout() {
const { isLayoutContentMaximized, maximize } = useMaximize()
const expand = () => maximize(true, { scrollToOptions: { top: 0 } })
return { expand, collapse: () => maximize(false), isLayoutContentMaximized }
}
```
## useSpinning
| Method | Purpose |
| ---------------------------- | ---------------------------------------------------------------------------- |
| `openSpin()` / `closeSpin()` | Toggle content-area loading independently of the app's global spinner. |
| `reload(wait?)` | Remount the current address and keep other tabs' caches. Defaults to 800 ms. |
| `reloadWorkspace(wait?)` | Remount the complete content area and release page instances for all tabs. |
Content loading uses a thin progress bar and text. `openSpin` only shows it after 120 ms to avoid flashes. `reload` displays it immediately. When indicating a pending request, call `openSpin` and pair it with `closeSpin` in `finally`. Reload loses unpersisted state on the current page. For repeated reloads, Runtime Store retains only the most recent restore timer.
```ts
import { useSpinning } from '@/hooks'
export function useLoadWithSpinner() {
const { openSpin, closeSpin } = useSpinning()
return async <T>(load: () => Promise<T>) => {
openSpin()
try {
return await load()
} finally {
closeSpin()
}
}
}
```
## useContentScroll
`useContentScroll()` returns a `scrollTo` function. Pass `(x, y?)` or `{ top, left, behavior }`, for example `scrollContent({ top: 0, behavior: 'smooth' })`. It resolves `LAYOUT_CONTENT_REF` at call time, so it can be created in `setup` and used in an event handler. It is a no-op while the layout is unmounted.
## useSiderScroll
`useSiderScroll()` returns a function with the same signature for `LAYOUT_SIDER_REF`. It is a no-op in top navigation mode or when the sidebar is unmounted. It scrolls the sidebar container and leaves menu selection alone.
```ts
import { useContentScroll, useSiderScroll } from '@/hooks'
export function useScrollShortcuts() {
const scrollContent = useContentScroll()
const scrollSider = useSiderScroll()
return {
toTop: () => scrollContent(0, 0),
toMenuTop: () => scrollSider(0, 0),
}
}
```
[useMaximize source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useMaximize.ts) · [useSpinning source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useSpinning.ts) · [useContentScroll source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useContentScroll.ts) · [useSiderScroll source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useSiderScroll.ts)

View File

@ -0,0 +1,164 @@
# Navigation and Menus {#导航与菜单}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
Import these APIs from `@/hooks`. See the [routing guide](../../guide/routing) for menu sources, permissions, and route records.
## Interactive example {#交互示例}
<AdminExample path="/template-hooks" title="Navigation, tabs, and badges" focus="useAppNavigation,useSiderBar,useBadge" layout />
::: details View example source
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useVueRouter
<AdminExample path="/web-hooks" title="Read the route and update query parameters" focus="useVueRouter" />
::: details View the router example source
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
`useVueRouter()` returns `{ router }`, the template's shared Vue Router instance. Read the current route with `router.currentRoute.value` and use Vue Router's `push`, `replace`, and `back` methods. You can get the instance outside `setup`. Wait for initialization before reading state that depends on route matching.
```ts
import { useVueRouter } from '@/hooks'
export const readQuery = () => useVueRouter().router.currentRoute.value.query
```
## useAppNavigation
`useAppNavigation().navigationTo(target, options?)` accepts these targets.
| Target | Behavior |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Full path string | Resolves through Router and preserves dynamic segments, query, and hash. Returns `undefined` if it matches nothing or only the catch-all route. |
| `AppMenuOption` | Navigates by `fullPath`, preserving parameters and fragments. `query` can override matching query keys. |
| Zero-based integer | Selects an item from the initialized menu. For a parent item, follows first children until it reaches a leaf. |
`NavigationToOptions.isPush` defaults to `true`. Set it to `false` to call `router.replace`. `query` overrides matching parameters in a string path. If navigation starts, the function returns the Router promise. Negative, fractional, nonfinite, and out-of-range indexes are ignored. Route guards still decide the outcome.
```ts
import { useAppNavigation } from '@/hooks'
export function useTableNavigation() {
const { navigationTo } = useAppNavigation()
return () =>
navigationTo('/tables/remote?tab=people', {
isPush: false,
query: { tab: 'orders' },
})
}
```
## useMenu
`useMenu(options?)` wraps Naive UI `NMenu` for standalone menus, local navigation, or selectors. Pass native menu configuration for horizontal or vertical layout, groups, dividers, custom fields, and render functions.
<AdminExample path="/template-hooks" title="Select and expand menu items" focus="useMenu" deferred />
| Return value | Purpose |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `menuRef` | Component ref to bind to `NMenu`. |
| `menuProps` | Shallow reactive props to bind directly. Replace `menuProps.options` when loading options asynchronously. |
| `showOption(key?)` | Expands the ancestors of an item. Omit the key to expand the current selection's ancestors without changing selection. |
| `deriveResponsiveState()` | Recalculates overflow for a horizontal menu with `responsive`. |
When you pass `value` or `expandedKeys`, the hook syncs the prop before invoking the original update callback. `value: null` clears selection, and `expandedKeys: []` collapses every group. When omitted, `NMenu` owns the respective state and uses `defaultValue`, `defaultExpandedKeys`, or `defaultExpandAll`. Instance methods are available after mount. After an async options update, await `nextTick()` for the component to receive the data.
```tsx
import { useMenu } from '@/hooks'
import { NButton, NMenu } from 'naive-ui'
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
const { menuRef, menuProps, showOption } = useMenu({
options: [
{ key: 'overview', label: 'Overview' },
{
key: 'reports',
label: 'Reports',
children: [{ key: 'monthly', label: 'Monthly' }],
},
],
value: 'monthly',
expandedKeys: [],
})
return () => (
<>
<NMenu ref={menuRef} {...menuProps} />
<NButton onClick={() => showOption()}>Expand selection</NButton>
</>
)
},
})
```
`useAppNavigation` and the route menu store manage workspace navigation. Use `useMenu` for standalone menus and `useMenuKeyboard` for workspace menu keyboard behavior. [Naive UI Menu API](https://www.naiveui.com/en-US/components/menu#API)
<span id="useapproot-兼容接口"></span>
## useAppRoot compatibility API {#useapproot}
This deprecated API reads and writes a legacy preference for existing callers. `getRootRoute`, `getRootPath`, and `getRootName` are computed refs, and `setRootRoute({ name?, path? })` merges its fields. Sign-in destinations, tab protection, and closing all tabs follow the current routing behavior. The empty workspace is always `/welcome`, and startup does not validate a home route. Use Router for explicit navigation in new code.
```ts
import { useVueRouter } from '@/hooks'
export function useOpenWorkspace() {
const { router } = useVueRouter()
return () => router.replace('/welcome')
}
```
## useSiderBar
These methods manage workspace tabs. Methods accepting `CloseMenuTag` take a zero-based index, a string matching the tab's `fullPath`, or a tab object.
| Method | Behavior |
| ---------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `getCurrentTagIndex()` | Current tab index, or `-1` if absent. |
| `checkCloseLeft(target)` / `checkCloseRight(target)` | Check for closable tabs in the given direction. |
| `close(target)` | Close an eligible business tab. Closing the active tab selects a neighbor. Closing the last tab opens the empty workspace. |
| `closeLeft(target)` / `closeRight(target)` | Close eligible tabs in the given direction. If the active tab closes, select the target. |
| `closeOther(target)` | Retain the target and protected tabs, and activate the target. |
| `closeAll()` | Close eligible tabs. Prefer the current protected page, then the first protected tab, then `/welcome`. |
Handle unsaved-form confirmation in the business workflow before invoking bulk close methods.
```ts
import { useSiderBar } from '@/hooks'
export function useCloseActiveTag() {
const { close, getCurrentTagIndex } = useSiderBar()
return () => {
const index = getCurrentTagIndex()
if (index >= 0) close(index)
}
}
```
## useBadge
Use a menu `fullPath` or `AppMenuOption` as the target. `show(target, options?)` merges options and shows the badge. `hidden(target)` hides it while retaining options. `update(target, options)` changes only the supplied fields. A badge is added only when the menu is loaded and the item is found.
`AppMenuExtraOptions` supports `label` (string or number), `i18nLabel` (translation key), `icon` (VNode), `type` (Naive UI Tag type), and `show` (visibility). Maintain translations in both packs when using a translation key.
```ts
import { useBadge } from '@/hooks'
export function useUnreadBadge() {
const { show, hidden } = useBadge()
const path = '/tables/remote'
return (count: number) =>
count > 0 ? show(path, { label: count, type: 'info' }) : hidden(path)
}
```
[useMenu](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useMenu.ts) · [useAppNavigation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useAppNavigation.ts) · [useAppRoot](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useAppRoot.ts) · [useSiderBar](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useSiderBar.ts) · [useBadge](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useBadge.ts) · [useVueRouter](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useVueRouter.ts)

View File

@ -0,0 +1,69 @@
# DOM Capture and Printing {#dom-截图与打印}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
## Interactive example {#交互示例}
<AdminExample path="/web-hooks" title="Capture and print DOM content" focus="useDomToImage,usePrint" />
::: details View example source
<<< @/../admin/src/views/demo/hooks/web-hooks.tsx
:::
## useDomToImage
`useDomToImage(target, options?)` returns `create(format?)`. It resolves an element, ref, or getter at call time. The default format is `jpeg`, `options.imageType` sets a different default, and a per-call `format` takes precedence. The promise result depends on the format.
| Format | Return value |
| -------------------- | ------------------- |
| `jpeg`, `png`, `svg` | Data URL string |
| `blob` | `Blob \| null` |
| `canvas` | `HTMLCanvasElement` |
| `pixelData` | `Uint8ClampedArray` |
`options` also accepts html-to-image settings such as `backgroundColor`, `pixelRatio`, and `filter`. `beforeCreate(element)` runs before checking the target and `created(result, element)` runs on success. Its result type covers all formats, so narrow it first. `createdError(error)` receives errors and the promise still rejects with `Error`. `finally(element)` runs every time and can receive an unresolved target. Capture after mount. Cross-origin images and fonts must satisfy browser loading rules.
The renderer loads on the first `create`, so pages without capture avoid downloading it. Load failures also invoke the error and cleanup callbacks above.
```ts
import { useDomToImage } from '@/hooks'
import { ref } from 'vue'
export function useReportImage() {
const report = ref<HTMLElement>()
const { create } = useDomToImage(report, { imageType: 'png', pixelRatio: 2 })
return {
report,
exportPng: () => create(),
exportCanvas: () => create('canvas'),
}
}
```
## usePrint
`usePrint(target, options?)` returns `print()`, which unwraps the target when called. It accepts a DOM target, URL or string, `Blob`, `Uint8ClampedArray`, or an array of objects. `UsePrintOptions` consists of print-js configuration except `printable`.
- DOM targets use `html` by default, and strings use `pdf`. Set `type: 'image'` for image URLs or `type: 'json'` for object arrays. JSON also needs `properties`.
- Image MIME blobs use `image`. Other blobs and byte arrays default to `pdf`. Binary targets become data URLs asynchronously. PDF printing removes the data URL prefix.
- Missing targets and empty strings return immediately. Synchronous branches such as DOM return `void`, and binary conversions return a promise. Use `await print()` to catch conversion errors. A requested print flow leaves physical output to the browser and user.
```ts
import { usePrint } from '@/hooks'
import { ref } from 'vue'
export function useReportPrint() {
const report = ref<HTMLElement>()
const { print } = usePrint(report, {
type: 'html',
documentTitle: 'Inventory report',
})
return { report, print }
}
```
Built-in TablePro printing uses the current page and visible columns. For custom business layouts, see [TablePro printing](../table-pro#打印与-csv).
[useDomToImage source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useDomToImage.ts) · [usePrint source](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/usePrint.ts)

View File

@ -0,0 +1,68 @@
# SVG Icons {#svg-图标}
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
```tsx
import type { IconName } from '@ray-template/icons'
import { RIcon } from '@ray-template/ui/icon'
const name: IconName = 'directional/resize_h'
const renderIcon = () => <RIcon name={name} />
```
`RIcon.name` and route `meta.icon` use the same group-qualified names. For example, `packages/icons/src/business/orders/approved.svg` becomes `business/orders/approved`. Search and copy usage from the SVG Icons demo.
## Interactive example {#交互示例}
The icon library copies TSX by default, such as `<RIcon name="action/search" />`. Select **Vue template** and click an icon to copy `<r-icon name="action/search" />` for a Vue template that imports `RIcon`.
<AdminExample path="/svg-icons" title="Search icons and switch the copied format" />
::: details View example source
<<< @/../admin/src/views/demo/svg-icons/index.tsx
:::
## Add and generate icons {#添加和生成}
1. Choose an existing group such as `action`, `navigation`, or `system`, or create a business group. Start path segments with a letter and use lowercase letters, digits, underscores, or hyphens.
2. Use `currentColor` for monochrome icons and `none` for empty areas. Keep brand colors.
3. The dev server or `pnpm icons:generate` updates `packages/icons/src/manifest.ts`. Verify with `pnpm icons:check` and commit the manifest with the SVGs. Generate the union type from the files.
Production builds generate a separate hashed sprite per top-level group, loaded under the deployment base. Replace bare names in old source. Cached bare names are migrated only if the filename is unique.
[Icon workflow and group map](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/icons/src/A_README.md)
## RIcon API
`@/components` exports `RIcon`, `IconProps`, `iconProps`, `IconName`, and `IconPackage`. `@/icons` also exports the icon types.
| Prop | Default | Description |
| ------------------ | ---------------- | ----------------------------------------------------------------------- |
| `name` | Required | Full group-qualified path. The first segment selects the sprite. |
| `size` | `20` | Base width and height. Numbers are pixels, and CSS sizes are supported. |
| `width` / `height` | `0` / `0` | Override the base dimensions individually. `0` uses `size`. |
| `color` | `'currentColor'` | SVG fill. Brand icons with their own colors may retain them. |
| `prefix` | `'icon'` | Symbol prefix, which must match generation. |
| `customClassName` | None | Extra class for the root. |
| `depth` | `1` | Icon opacity level. |
| `cursor` | `'inherit'` | Inherits the parent control's cursor. |
| `onClick(event)` | None | Accepts a callback or array. |
The inner SVG is hidden from screen readers. For an action, wrap it in a button with an accessible name and preserve keyboard operation and focus.
[RIcon props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RIcon/src/props.ts) · [Sprite reference implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RIcon/src/Icon.tsx)
## Icon sources {#图标来源}
Shared icons come from the [IconPark outline collection on Iconfont](https://www.iconfont.cn/collections/detail?cid=51731). The [source inventory](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/icons/ICON-SOURCES.md) lists names and Iconfont IDs by use. Monochrome icons follow text color. Ray and other brand marks retain their original colors.
Prefer existing icon names. Three retired assets migrate when loading old route configurations.
- `action/export_excel` becomes `action/download`.
- `logo/office` becomes `navigation/table`.
- `illustration/login_bg` becomes `navigation/other`.
Use the new full names in new code.

View File

@ -0,0 +1,15 @@
# API Reference {#api-参考}
The reference is organized by public entry point. Follow the [first-page guide](../guide/first-page) before building a page, and use the sections below to look up individual APIs.
| Area | Covers |
| -------------------------------------------- | ------------------------------------------------------------------------ |
| [Components](./components) | Shared components, props, events, slots, instance methods, and providers |
| [Hooks](./hooks) | Navigation, state, pagination, browser APIs, and side effects |
| [Directives](./directives) | Binding values, modifiers, updates, and teardown |
| [Stores](./store) | State, getters, actions, and persistence |
| [Utilities](./utils) | Types, numbers, DOM, files, and storage |
| [SVG icons](./icons) | Icon paths, type generation, and `RIcon` |
| [Application configuration](./configuration) | Themes, routes, localization, requests, and builds |
Use the [source version listed for this site](./source). Examples assume the Ray Template `@` alias and default application context.

View File

@ -0,0 +1,11 @@
# Documentation and Source Versions {#文档与源码版本}
This site covers **Ray Template 6.0.2**. Ray Admin, the runnable examples, and the shared packages live in the same repository. Inline examples use workspace source at build time. Release builds pin source links to the corresponding commit.
| Version | Source and documentation |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **v6** | [Current Ray Template source](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main) · [Monorepo architecture](../guide/architecture) · [Version boundary and adoption](../migration) |
| **v5** | [legacy/v5](https://github.com/XiaoDaiGua-Ray/ray-template/tree/legacy/v5) is fixed at `6f095b7`. The [v5.2.4 tag](https://github.com/XiaoDaiGua-Ray/ray-template/tree/v5.2.4) is available. |
| **Legacy documentation** | [Original docs repository](https://github.com/XiaoDaiGua-Ray/ray-template-doc) · [Legacy content snapshot](https://github.com/XiaoDaiGua-Ray/ray-template-doc/tree/0cae0e4334b16df22d491401c190360af4819025) |
Source versions, Git tags, and deployments follow separate timelines. Record the exact tag or commit when reproducing a behavior. In issue reports, specify v5 or v6 and include the relevant page or module entry point. [Report an issue](https://github.com/XiaoDaiGua-Ray/ray-template/issues)

View File

@ -0,0 +1,22 @@
# Stores {#store}
Pinia manages cross-page state. Import getters and actions from `@/store`, read refs with `.value`, and use actions for changes. State owned by one component or page can stay in a local ref.
| Store | Access | Persistence |
| ------------------------------------------------ | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| [Setting](./store/setting) | `useSettingGetters` / `useSettingActions` | Local Storage key `piniaSettingStore` excludes the lock configuration dialog. The current language is also stored separately. |
| [Menu](./store/navigation#menu-store) | `useMenuGetters` / `useMenuActions` | Local Storage retains the sidebar's collapsed state. Open tabs use Session Storage. Selection is derived from the current route. |
| [KeepAlive](./store/navigation#keepalive-store) | `useKeepAliveGetters` / `useKeepAliveActions` | Session Storage retains names eligible for caching. |
| [Runtime](./store/runtime#runtime-store) | `useRuntimeGetters` / `useRuntimeActions` | Lives for the current Pinia instance. |
| [Lock Screen](./store/runtime#lock-screen-store) | `useLockScreenGetters` / `useLockScreenActions` | Legacy Local Storage boolean with cross-tab sync. |
| [Signing](./store/signing) | `useSigningGetters` / `useSigningActions` | Profile and permissions live in memory and are restored from the session API. Bearer mode stores the token in Local Storage. |
## Initialization and extension {#初始化与扩展}
`setupStore(app)` installs Pinia and its persistence plugin. Unmount releases the Pinia instance and scope. The template entry point already installs them. Access Menu and Signing from a component's active setup context when using APIs that depend on routing.
Add each store under `apps/admin/src/store/modules` with a unique ID. For persistence, use `pick` or `omit`, a suitable storage area and stable key, and serializable data. Put the accessors under `apps/admin/src/store/hooks` and export them from `apps/admin/src/store/index.ts`. Raw `pinia…Store` exports are available internally. Pages should use hooks to reduce coupling to implementation fields.
Cache keys and JSON formats are data contracts. Consider reads, migration, and fallback for old values before changing keys, fields, or serialization. Keep server secrets out of browser storage.
[Initialization and exports](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/index.ts) · [Store conventions](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/README.md)

View File

@ -0,0 +1,48 @@
# Menu and KeepAlive Stores {#menu-与-keepalive-store}
## Menu Store
Route modules become a menu tree. Menu Store coordinates selection, tabs, breadcrumbs, and navigation. Pages typically use [useAppNavigation](../hooks/navigation#useappnavigation) or [useSiderBar](../hooks/navigation#usesiderbar).
| Getter | Computed value |
| ---------------------- | -------------------------------------------------------------------------------- |
| `getMenuOptions` | Application menu tree and its children. Rendering also considers route metadata. |
| `getBreadcrumbOptions` | Current breadcrumb items. |
| `getMenuKey` | Current menu key, usually a full path. |
| `getMenuTagOptions` | Workspace tabs. |
| `getCurrentMenuOption` | Active menu item, possibly missing initially. |
| `getCollapsed` | Whether the sidebar is collapsed. |
| Action | Behavior |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `setupAppMenu()` | Rebuilds menus, tabs, and titles from known routes and returns `Promise<void>`. The first route synchronization initializes it. |
| `resolveOption(option)` | Converts a route-shaped option into a menu item. Supply the correct `fullPath` for its key and lookup. |
| `changeMenuModelValue(key, option, query?)` | Navigates and syncs state. `meta.windowOpen` opens an external page. `sameLevel` preserves the original menu and tab and extends breadcrumbs. |
| `collapsedMenu(collapsed)` | Updates collapsed state. |
| `setMenuTagOptions(options, isAppend = true)` | Appends or replaces tabs from one item or an array. |
| `spliceMenTagOptions(idx, length = 1)` | Removes tabs by index. The historical spelling is retained. |
| `updateMenuState(key, value, callback?)` | Updates an existing field and shallow-merges plain objects. Use the other actions for coordinated changes. |
`depthSearchAppMenu(options, key)` finds a menu item by full path. Use Router or `navigationTo` to await guards because `changeMenuModelValue` returns no navigation promise. After role changes, keep backend authorization and direct route access in sync with the menu.
`piniaMenuStore` persists `collapsed` in Local Storage. Tabs are stored under `appMenuTagOptions` in Session Storage with their order and optional `topped` and `fixed` flags. Refresh restores only routes that still exist and are accessible. Current route changes update menu selection and breadcrumbs.
## KeepAlive Store
`useKeepAliveGetters().getKeepAliveInclude` is a computed list of cached component names. `useKeepAliveActions()` provides `getKeepAliveInclude()` to read the list and `setKeepAliveInclude(option)` to add names from route options. It processes pages with `meta.keepAlive`. Access moves a name to the newest position, and the list is trimmed to the configured capacity. [RTransitionComponent](../components/route-transition) renders the actual cache.
- Match each route `name` to the page component name so `include` can match it.
- Store names survive refresh in the current tab's Session Storage. Component instances and form state are recreated.
- Configure enablement, excluded names, and capacity in [Setting Store](./setting)'s `keepAliveConfig`. Check nested routes and query changes before testing a return to a cached tab.
```ts
import { useKeepAliveGetters, useMenuGetters } from '@/store'
export function useNavigationSummary() {
const { getMenuKey, getMenuTagOptions } = useMenuGetters()
const { getKeepAliveInclude } = useKeepAliveGetters()
return { getMenuKey, getMenuTagOptions, getKeepAliveInclude }
}
```
[Menu implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/menu/index.ts) · [Menu hooks](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/hooks/useMenuStore.ts) · [KeepAlive implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/keep-alive/index.ts)

View File

@ -0,0 +1,44 @@
# Runtime and Lock Screen Stores {#runtime-与-lock-screen-store}
## Runtime Store
`useRuntimeGetters()` exposes read-only refs. `useRuntimeActions()` returns `setRuntimeState(key, value)` and `reloadContent(wait = 800, path?)`. These UI values live in memory.
| Field | Default | Purpose |
| ------------------------------ | ----------------- | --------------------------------------------------------------------------------- |
| `globalSpinning` | `false` | Global spinner. |
| `globalDrawerValue` | `false` | Narrow-screen menu drawer. |
| `globalMainLayoutLoad` | `true` | Whether the default layout mounts page content. |
| `refreshingPath` | `null` | Full address of the page being refreshed. |
| `layoutContentMaximize` | `false` | Workspace maximization. |
| `layoutContentMaximizeVersion` | `0` | Sequence number used to discard stale maximization callbacks. Managed internally. |
| `layoutContentSpinning` | `false` | Layout content spinner. |
| `layoutContentMaximizeStyle` | `{ zIndex: 999 }` | Maximized stacking order, background, and transition. |
Call `reloadContent` with the current full path to remount that page. Omit the path to release all cached content instances. Only the newest timer is retained, and disposal clears it. Pages can call `useSpinning().reload()` for the active page or `reloadWorkspace()` for the full workspace. Use [useMaximize](../hooks/layout#usemaximize) to retain callbacks and exit handling. Global and content loading are independent.
```ts
import { useRuntimeActions } from '@/store'
export function useGlobalLoading() {
const { setRuntimeState } = useRuntimeActions()
return async <T>(task: () => Promise<T>) => {
setRuntimeState('globalSpinning', true)
try {
return await task()
} finally {
setRuntimeState('globalSpinning', false)
}
}
}
```
Global loading state is Boolean. Coordinate several concurrent requests in the caller before toggling it.
## Lock Screen Store
`useLockScreenGetters().getLocked` reads the actual lock state. `useLockScreenActions().setLocked(value)` writes it. It defaults to `false` and uses the legacy Local Storage Boolean key `isAppLockScreen` with cross-tab sync.
`setting.lockScreenSwitch` controls the lock configuration dialog. The default lock component handles the local passphrase and unlock flow. A business action should open the configuration dialog so the user can set a passphrase before locking. The lock screen hides the local interface independently of server sessions and authorization.
[Runtime implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/runtime/index.ts) · [Lock Screen implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/lock-screen/index.ts) · [Lock flow](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/app-components/app/AppLockScreen/components/LockScreen/index.tsx)

View File

@ -0,0 +1,59 @@
# Setting Store
`useSettingGetters()` returns computed refs. `useSettingActions()` changes preferences and triggers related side effects. Settings are restored after refresh. Use the provided actions so the UI, date locale, and HTML styles stay in sync.
## Getters
| Getter | Field and default behavior |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `getLayoutConfig` | `layoutConfig` for layout mode and workspace dimensions. |
| `getDrawerPlacement` | `drawerPlacement` defaults to `right`. |
| `getPrimaryColorOverride` | Effective Naive UI token overrides from the active style, color mode, and custom primary color. |
| `getThemeStyle` / `getCustomPrimaryColor` | Style and custom primary color. `modern` is the default style. The preset color is used without a manual override. |
| `getAppTheme` / `getAppThemeStr` | `_appTheme` is the resolved dark Boolean. `appTheme` is `light/dark/auto` and starts as `light`. |
| `getLocaleLanguage` | `localeLanguage` uses the saved locale or system default configuration. |
| `getMenuTagSwitch` / `getBreadcrumbSwitch` | `menuTagSwitch` and `breadcrumbSwitch` show tabs and breadcrumbs by default. |
| `getMenuTagTop` / `getMenuTagFixed` / `getMenuTagDrag` | `menuTagTop`, `menuTagFixed`, and `menuTagDrag` enable moving tabs to the front, protecting tabs, and drag reordering by default. |
| `getBreadcrumbIcon` / `getBreadcrumbIconFallback` | `breadcrumbIcon` and `breadcrumbIconFallback` show menu icons and placeholders by default. |
| `getLockScreenSwitch` | `lockScreenSwitch` controls the lock setup dialog. It defaults to off and lives in memory. |
| `getCopyrightSwitch` | `copyrightSwitch` shows the copyright region by default. |
| `getContentTransition` | `contentTransition` defaults to `scale`. |
| `getWatermarkSwitch` / `getWatermarkConfig` | `watermarkSwitch` defaults to off. The configuration covers text, font size, line height, dimensions, offset, spacing, rotation, and `cross`. |
| `getAppRootRoute` | Legacy `appRootRoute` defaults to `{ name: 'Dashboard', path: '/dashboard' }`. |
| `getSideBarLogo` | `sideBarLogo` contains `icon`, `title`, `url`, and `jumpType`. Defaults to `logo/ray` and an internal link to the dashboard. |
| `getKeepAliveConfig` | `keepAliveConfig` is on by default, with room for ten instances and no excluded names. |
| `getMenuConfig` | `menuConfig` covers the sidebar, collapse behavior, icons, accordion behavior, and scrolling. |
| `getColorWeakness` / `getDynamicDocumentTitle` | `colorWeakness` defaults to off and `dynamicDocumentTitle` to on. |
`layoutConfig.mode` accepts `side` (default), `top`, `mixed`, `right`, or `split`. `contentWidth` accepts `fluid` (default) or `fixed`. `contentMaxWidth` defaults to 1200 and is clamped to 640–2560. `contentPadding` defaults to 24 and is clamped to 0–48. `fixedHeader` and `fixedFooter` default to on. Hydrating older settings fills missing fields and normalizes ranges.
`menuConfig` defaults to width 272, collapsed width 64, expanded and top navigation icons of 20 px, collapsed icons of 22 px, and indentation 24. `collapsedMode` defaults to `width`. `transform` moves the sidebar. `accordion`, `inverted`, and `nativeScrollbar` default to off, while `menuSiderBarLogo` defaults to on. `sideBarLogo.jumpType` uses `station` for internal routing and `outsideStation` for external links. Omit `url` to leave the logo without a destination. Old browser data with both icon sizes set to 16 px is migrated to the current icon defaults. Dimensions saved by the current version or present in preference files are retained. Legacy bare icon names are resolved when possible. Use a string icon name for a persisted logo because VNodes are unsuitable for storage.
## Actions
| Method | Behavior |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `updateSettingState(key, value, callback?)` | Updates an existing field. Plain objects are shallow-merged. `layoutConfig` also checks format and ranges. Success invokes the optional callback. |
| `updateLocale(key)` | Updates Vue I18n, Day.js, the stored language, and Pinia. Naive UI receives its locale from Pinia. |
| `changePrimaryColor(value?, alpha = 0.85)` | Overrides the active preset's primary color. Omit the value to restore the preset. |
| `toggleColorWeakness(bool)` | Updates the preference and switches the HTML inversion filter. |
Switch themes with [useTheme](../hooks/appearance#usetheme). [useAppRoot](../hooks/navigation#useapproot) is a compatibility API for legacy preferences. When changing nested settings, pass the complete object at the next level, since merging is shallow.
```ts
import { useSettingActions, useSettingGetters } from '@/store'
export function useCompactWorkspace() {
const { getLayoutConfig } = useSettingGetters()
const { updateSettingState } = useSettingActions()
const apply = () =>
updateSettingState('layoutConfig', {
mode: 'mixed',
contentWidth: 'fixed',
contentMaxWidth: 1200,
})
return { config: getLayoutConfig, apply }
}
```
[Getters and actions](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/hooks/useSettingStore.ts) · [State types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/setting/types.ts) · [Defaults](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/setting/constant.ts) · [Persistence](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/setting/index.ts)

View File

@ -0,0 +1,28 @@
# Signing Store
`useSigningGetters().getSigningCallback` returns the current user, with fields such as `id`, `username`, `name`, `role`, and optional `avatar`. `getPermissions` returns the session's permission codes. Frontend menus and actions use roles and permissions, and the backend independently authorizes business requests.
| Method | Behavior |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `signing({ name, pwd })` | Stores the user and permissions after sign-in and returns `Promise<void>`. Read the profile with getters. The promise rejects on failure. |
| `restoreSession()` | Restores profile and permissions from the session endpoint. A 401 clears the invalid session. Other request errors reach the caller. |
| `clearSigningCallback()` | Clears this app's sign-in and route state, lock state, and cached tabs while keeping the current address. |
| `endSession(redirect?)` | Clears the local session, notifies other tabs, and opens sign-in. The optional redirect can restore the destination at the next sign-in. |
| `logout(redirect?)` | Calls the server's logout endpoint. Success or 401 calls `endSession`. Other errors reach the caller. |
The user profile and permissions live in memory and are retrieved from the session API after refresh. Bearer mode stores the access token in application Local Storage. In cookie mode the browser manages the session credential. Favorites and recent pages are scoped to the account. [Backend contract](../../guide/backend)
```ts
import { useSigningActions, useSigningGetters } from '@/store'
import { computed } from 'vue'
export function useAccountMenu() {
const { getSigningCallback } = useSigningGetters()
const { logout } = useSigningActions()
return { name: computed(() => getSigningCallback.value?.name ?? ''), logout }
}
```
Sign-out removes only this application's session and cache keys. Other application entries in Session Storage on the same origin are retained.
[Signing implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/signing/index.ts) · [Types](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/store/modules/signing/types.ts) · [Sign-in demo](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/views/login/components/Signing/index.tsx) · [Route guard](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/router/utils/permission.ts)

View File

@ -0,0 +1,158 @@
# TablePro Live Examples {#tablepro-在线示例}
Start with a bare table and add queries, pagination, column settings, or printing as needed. These examples use real Ray Admin components and demo data. **Run example** loads each interactive area without sign-in or a business API. On narrow screens, scroll inside the table or open a new tab. Each example includes the source that actually runs.
<script setup>
import AdminExample from '../../examples/AdminExample.vue'
</script>
| Goal | Start here |
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| Display rows you already have | [Bare table and local sorting](#纯表格与本地排序) |
| Use the current page and total returned by an API | [Remote queries and retry](#远端查询与失败恢复) |
| Let a page or query library own data and pagination | [Manual remote pagination](#手动远端分页) |
| Combine filters, validation, and remote options | [Advanced search](#高级搜索) |
| Fill the workspace and handle many columns or rows | [Automatic height and virtual scrolling](#自适应高度与虚拟滚动) · [Column settings and persistence](#列设置与缓存) |
| Customize actions or export print and CSV | [Custom slots and row menu](#自定义插槽与行菜单) · [Printing and CSV](#打印与-csv) |
| Control the table from the page | [Instance methods and hooks](#实例与-hooks) |
## Bare table and local sorting {#纯表格与本地排序}
Click **Age** to cycle through ascending, descending, and default order. The table consumes the ten supplied rows. `bare` hides the title and toolbar and disables pagination by default. `scrollX` preserves column widths in a wide table.
<AdminExample path="/tables/basic" title="Bare table and local sorting" :height="495" deferred />
::: details View the bare table source
<<< ../../../admin/src/views/demo/tables/basic.tsx
:::
## Remote queries and retry {#远端查询与失败恢复}
1. Copy part of a row's name or email into the filter area and submit. The query returns to page 1 and pagination uses the filtered total.
2. Clear the filters, sort by **Age**, and change pages. `onUpdateSorter` maps the sort to `params.sortAge`, which applies to the full result set before pagination.
3. Select rows on two pages. The toolbar shows the total across pages. **More actions → Export CSV** exports visible data columns on the current page.
4. Click **Simulate request failure** to see the old rows clear and an error appear. Click **Refresh** to recover. Forward `request`'s `signal` to the HTTP client for cancellation.
<AdminExample path="/tables/remote" title="Remote queries, server-side sort, and retry" :height="695" deferred />
::: details View the remote query source
<<< ../../../admin/src/views/demo/tables/remote.tsx
:::
## Manual remote pagination {#手动远端分页}
This example simulates an external API with local data and supplies only the current page. Go to page 2 and filter by name. The page returns to 1 and the total changes. Changing page size also returns to page 1.
The page owns `page`, `pageSize`, and `itemCount` and updates them from pagination callbacks and `onSearch`. For an async service, manage loading, cancellation, and errors in that layer. Use `request` from the previous example to let TablePro own these states.
<AdminExample path="/tables/controlled" title="Page-controlled remote pagination and results" :height="670" deferred />
::: details View the controlled pagination source
<<< ../../../admin/src/views/demo/tables/controlled.tsx
:::
## Advanced search {#高级搜索}
Switch between local matching and a mock remote query. After each action, compare the draft, applied filters, transformed parameters, and actual list request.
1. **Combine filters.** Submit multiple statuses and a creation date range. The remote query splits the dates into `createdFrom` and `createdTo`. Page changes reuse the parameters.
2. **Dependencies and cancellation.** Switch quickly between North and South. The owner draft clears and the previous options request is canceled. Search South's options for **Wang**.
3. **Zero and boolean values.** Apply the delivery and amount scenario and expand an order. Follow the product cascader, warehouse tree, delivery control, and datetime field. Confirm `minAmount: 0` and `invoiced: false` are preserved.
4. **Validation and automatic apply.** Submit a one-character keyword and check that existing rows remain. Correct it, enable automatic submission on input, and edit repeatedly to see the debounce.
5. **Recover independent failures.** Fail the owner options or list request once. Retry options at the field, or resubmit the list query.
<AdminExample path="/tables/search" title="Combined filters, remote options, and advanced search" :height="960" deferred />
::: details View the search example, business API, and demo fixtures
<<< ../../../admin/src/views/demo/tables/search.tsx
<<< ../../../admin/src/api/demo/data.ts
<<< ../../../../packages/demo-data/src/orders.ts
:::
## Automatic height and virtual scrolling {#自适应高度与虚拟滚动}
Enable **Virtual rows**, then show the footer and action slots. The list gives the new content room while the paginator stays below the rows. Open the example in a new tab and resize its height. Compare the available space with filters expanded and collapsed. Virtual scrolling reduces the rendered row count. The current page, loaded rows, and export scope are calculated as usual.
<AdminExample path="/tables/auto-height" title="Automatic height, virtual scrolling, and footer slots" :height="640" deferred />
::: details View the automatic height source
<<< ../../../admin/src/views/demo/tables/auto-height.tsx
:::
## Column settings and persistence {#列设置与缓存}
1. Open **Column settings**. Hide **Name** and **Email**. The **Contact details** group disappears once both children are hidden.
2. Drag root columns or use the move buttons. Columns with widths can be pinned to the start or end. Enable resizing, then drag a header edge.
3. Click **Reset column layout** to restore initial order, pinning, and width settings while keeping visibility.
4. Open the example in a new tab, hide a column, and reload that same tab. `columnStateKey` saves visibility in a separate session namespace. Production applications can include the tenant or account ID in the key.
5. Toggle **Include the ID field** to change the column definitions. Data columns and groups use stable keys. Selection columns are outside visible data column settings.
<AdminExample path="/tables/columns" title="Groups, visibility, pinned columns, and widths" :height="680" deferred />
::: details View the column settings source
<<< ../../../admin/src/views/demo/tables/columns.tsx
:::
## Custom slots and row menu {#自定义插槽与行菜单}
Filter by email in the custom form, which submits through `submit(values)` from `filters`. Use the title actions to return to page 1 and set 20 rows per page. Select rows and clear them with the bottom action. Right-click a row to run a sample menu action. The callback receives the row's data.
<AdminExample path="/tables/custom" title="Custom filters, footer, actions, and row context menu" :height="690" deferred />
::: details View the custom slot source
<<< ../../../admin/src/views/demo/tables/custom.tsx
:::
## Copy an image {#复制图片}
Click **Copy table image** in any full table above and paste it into an image-capable chat or document. Try hiding or pinning columns, or scrolling horizontally, before copying. Virtual scrolling captures only the content currently rendered in the visible table area. The copy action is on by default and can be hidden with `showCopyImage={false}`. Printing is off by default.
## Printing and CSV {#打印与-csv}
This example sets `showPrint`. Filter by name or hide a column in Column settings. Choose **More actions → Print table** to preview the current page's visible data columns. **Print a separate summary** previews a custom region supplied via `print({ target })`. Cancel the browser dialog to preview without printing.
<AdminExample path="/tables/printing" title="Print the current page or a custom region" :height="710" deferred />
::: details View printing source and styles
<<< ../../../admin/src/views/demo/tables/printing.tsx
<<< ../../../admin/src/views/demo/tables/printing.scss
:::
To compare both CSV scopes, download the files in [Export, print, and the instance lifecycle](#导出与打印的实例生命周期).
## Instance methods and hooks {#实例与-hooks}
### Query, retry, and pagination {#查询、重试与分页}
Go to page 2 and compare **Refresh current page** with **Refresh from page 1**. Simulate failure and observe `queryState` loading, failure, and totals, then refresh to recover. Submitting a name filter displays the actual request parameters. Change pages rapidly to see the latest request win.
<AdminExample path="/tables/hooks-query" title="Control queries and pagination with useTablePro" :height="810" deferred />
::: details View the query hook source
<<< ../../../admin/src/views/demo/tables/hooks-query.tsx
:::
### Cross-page selection and bulk actions {#跨页选择与批量操作}
Use **Select current page** on two pages, then **Deselect current page**. Only that page's keys are removed. Mark the remaining selected rows and return to the relevant page to check them. Sort rows, then use **Clear sorting** to see how the example calls the underlying method exposed by `getTableInstance()`.
<AdminExample path="/tables/hooks-selection" title="Cross-page selection and bulk marking with useTablePro" :height="790" deferred />
::: details View the selection hook source
<<< ../../../admin/src/views/demo/tables/hooks-selection.tsx
:::
### Export, print, and the instance lifecycle {#导出与打印的实例生命周期}
Download **Export current page as CSV** and **Export all loaded rows as CSV**, then compare the row counts. The latter uses `keepOriginalData` to export the entire supplied batch. In remote mode it does not fetch other pages. Click **Unmount table** to disable the actions, then mount it again to re-register the instance.
<AdminExample path="/tables/hooks-output" title="CSV scopes, printing, and instance mount state" :height="780" deferred />
::: details View the output hook source
<<< ../../../admin/src/views/demo/tables/hooks-output.tsx
:::
[Back to the TablePro API reference](./table-pro)

View File

@ -0,0 +1,238 @@
# TablePro
<script setup>
import { useData } from 'vitepress'
import { defineAsyncComponent } from 'vue'
import AdminExample from '../../examples/AdminExample.vue'
const { isDark, lang } = useData()
const TableProDemo = defineAsyncComponent(() => import('../../examples/TableProDemo.vue'))
</script>
Import `RTablePro` from `@ray-template/ui/table-pro`. Ray Admin can also import it from `@/components`. Columns, selection, sorting, pinning, and virtual scrolling follow Naive UI DataTable. Use `bare` for a plain table, or add search, pagination, and tools as needed.
![Remote people directory with filters, toolbar, visible columns, and pagination](/assets/tablepro-preview.jpg)
## Interactive example {#交互示例}
[Open all live examples](./table-pro-examples) for 11 runnable scenarios with steps, expected behavior, and the source that actually runs.
Switch the data source, filter rows, or change pages. In remote mode, changing pages or resubmitting filters quickly cancels the previous query. After simulating a failure, use the retry button in the table.
<ClientOnly>
<TableProDemo :dark="isDark" :locale="lang.startsWith('en') ? 'en' : 'zh-CN'" />
</ClientOnly>
::: details View example source
<<< @/examples/TableProDemo.vue
:::
## Bare tables and remote queries {#纯表格与远端查询}
```tsx
import { getPersonList } from '@/api/demo/mock/person'
import { RTablePro } from '@/components'
const columns = [
{ title: 'Name', key: 'name' },
{ title: 'Email', key: 'email' },
]
const renderBare = () => <RTablePro bare columns={columns} data={[]} />
const renderRemote = () => (
<RTablePro
columns={columns}
request={getPersonList}
search={[{ key: 'name', label: 'Name' }]}
columnStateKey="demo:people"
/>
)
```
- Remote `request(params, signal)` returns `Promise<{ data, total }>`. The component accepts only the latest result. Changing the source or filter scope clears old rows and the total. Changing the page or page size hides old rows. Until the current page resolves, the instance returns no rows and CSV and printing are unavailable. A failure clears rows and total, shows the empty state, and uses the host toast. Retry with `reload()`. Forward the signal to the HTTP client to cancel the transport.
- Submitting search returns to page 1. Pass external filters in `params`, or use `submit(values)` from the `filters` slot for a custom form. Map sort and filter events into `params` for server-side processing.
- The default is 10 rows per page. Set `pageSize` or `pagination.pageSizes`, or disable pagination with `pagination={false}`. Disabling omits pagination fields. `bare pagination` enables only pagination on a bare table.
- Set the initial page with `pagination.defaultPage`. With `request`, TablePro owns the page, page size, and total. To manage remote data yourself, use `remote + data + pagination` and handle filter scope changes. In controlled mode, update the page and size in their callbacks. Search reset and instance actions invoke the corresponding callbacks.
## Advanced search {#高级搜索}
Start with any of the following scenarios. Compare the draft, applied filters, and request parameters below the table to see when the result changes.
- **Combined filters.** Select several statuses and a creation date range. Switch to mock remote mode, apply the filters, and inspect `createdFrom` and `createdTo`. Change pages to confirm the filters persist.
- **Rapid organization changes.** Load owner options for North and South in quick succession. The owner field clears and the request log shows the North request was canceled. Open the owner menu and search South for **Wang**.
- **Delivery and amount.** Use the product cascader, warehouse tree, minimum amount, invoice state, custom delivery method, and delivery time. Apply the filters and expand a matching order to check delivery details. The request retains `minAmount: 0` and `invoiced: false`.
- **Validation.** Submit a one-character keyword and check the error while the previous rows remain visible. Correct it, switch to automatic apply on input, and edit rapidly to observe the list requests.
Use the recent request controls to fail either the owner lookup or the list once. Retry owner options under the field. For a list failure, submit the query again from the empty state.
<AdminExample path="/tables/search" title="Combined filters, dependent fields, and retry" :height="960" />
::: details View example source
<<< ../../../admin/src/views/demo/tables/search.tsx
:::
### Field configuration {#字段配置}
`search` accepts a legacy field array, a `TableProSearchOptions` object, or `false`. In an array, a field without `type` renders a single-select when it has `options` and a text field otherwise. In object mode, set `fields` explicitly or omit it to infer fields from data columns marked `search: true` or `search: { type, ... }`. Column groups, selection columns, and expand columns are excluded from inference. Column visibility settings leave search fields intact. Explicit `fields` wins, including an empty array. Give each field a unique `key`.
| `type` | Draft and submitted values | Default local matching |
| ---------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------ |
| `text` | String, trimmed on submit | Case-insensitive substring |
| `number`, `boolean` | Number or boolean. Clear a boolean to omit its filter. | Exact |
| `select`, `treeSelect`, `cascader` | String or number. Array with `multiple: true`. | Exact for single selection. Any selected value matches for multiple selection. |
| `date`, `dateRange` | `yyyy-MM-dd` string or pair | Exact day or inclusive range |
| `datetime`, `datetimeRange` | Millisecond timestamp or pair | Exact timestamp or inclusive range |
| `time` | `HH:mm:ss` string | Exact |
| `custom` | String, number, boolean, or array of strings or numbers | Exact for a single value. Any value matches for an array. |
Fields combine with AND. Local matching reads `row[key]` by default. Use `getValue(row)` for nested data or conversions such as timestamps to business dates, and `matches(cell, value, row)` for custom matching. Controls support `placeholder` and typed `fieldProps`. Pass tree-select and cascader options such as nodes and lazy loading through `fieldProps`. Custom controls use `render({ value, setValue, values, inputId, labelId })`. Associate the label with the focusable control.
### Submission and requests {#提交和请求}
- `initialValues` takes precedence over field `initialValue`. Defaults participate in the first query. Reset restores defaults and queries again. With `rules`, the search button and `submitSearch()` validate first and keep the last result on failure. Reset clears validation feedback. Empty values, whitespace-only strings, and empty arrays are omitted. `0` and `false` are retained.
- `transform(value, values)` returns part of the request parameters. For example, a date range can return `{ createdFrom, createdTo }` in place of the original field. Local matching still uses the field value. List requests merge external `params`, transformed search parameters, and the table's `page` and `pageSize` in that order. Submission returns to page 1. Pagination and retry reuse applied filters.
- Errors in `visible`, `transform`, `getValue`, or `matches` trigger `onSearchError` and keep the last valid filters. Local reads support paths such as `customer.name` and prefer `getValue`. When field rules change dynamically, compatible filters are recalculated with the new rules.
- After applying filters, `onSearch` receives `{ values, params, reason }` with `reason` equal to `submit` or `reset`. In manual remote mode, use the event to fetch rows and manage the page and total. Listener exceptions go through Vue event error handling. Applied filters stay in place. The caller owns request error feedback and retry.
- Both the instance and `useTablePro()` expose `getSearchValues('draft' | 'applied')`, `setSearchValues(patch)`, `submitSearch()`, and `resetSearch()`. Reads default to the draft. Submit and reset return `Promise<boolean>` indicating whether filters were applied. Use `submitMode: 'change'` for debounced submission while editing. `debounce` defaults to 300 ms.
### Remote options, dependencies, and layout {#远程选项、联动和布局}
Use `select.loadOptions({ keyword, values, signal })` to fetch options. Pass `signal` to the HTTP client to cancel older requests. A canceled response cannot overwrite newer options even if the transport returns it. Keyword input is debounced by 250 ms by default. Change it with `optionDebounce`. Loading and retrying options is independent of list requests.
`dependsOn: ['orgId']` clears the owner draft when the organization changes and loads owners for the new organization. One `setSearchValues` call can set both organization and owner. Use `visible: ({ orgId }) => orgId != null` to hide and omit the owner filter without an organization. Collapsing changes layout only. Collapsed fields still submit and validate.
Use `defaultCollapsed`, `collapsedRows`, `maxColumns`, and field `span` for layout. Set label position and width with `labelPlacement` and `labelWidth`, and button copy with `searchText` and `resetText`. Extend the buttons with `renderActions` or call `submit`, `reset`, and `setCollapsed` yourself. A custom form can still use `submit(values)` through the higher-priority `filters` slot.
## Layout, tools, and instance methods {#布局、工具与实例}
`autoHeight` fills the available workspace height. For a custom region, set `--r-table-height`. Set column widths and `scrollX` so wide tables scroll inside the table.
```tsx
import { RTablePro, type TableProInst } from '@/components'
import { shallowRef } from 'vue'
const table = shallowRef<TableProInst>()
const reloadFromFirstPage = () => table.value?.reload(true)
const renderTable = () => (
<RTablePro ref={table} columns={[{ title: 'Name', key: 'name' }]} data={[]} />
)
```
The instance also exposes `setPage`, `setPageSize`, `getCurrentPageData`, `downloadCsv`, `print`, `copyImage`, and `getTableInstance`. Extend the table with `title`, `toolbar`, `tableFooter`, or `tableAction`. Use `error` for custom error content.
The toolbar separates application actions from built-in tools. In `request` mode it offers Refresh. Column settings, Copy table image, and fullscreen are direct actions. **More actions** contains density, striped rows, border, and CSV. Stripe and border icons remain visible, with a separate selection mark on the right. Density items use text and a selection mark. The default `size` is `medium` (Standard), shared by the menu and table. `small` selects Compact and `large` selects Comfortable. Use `showPrint` to add Print table. `tool={false}` hides built-in tools and retains the custom `toolbar` slot.
### `useTablePro`
The same package entry exports `useTablePro`. Register the instance with `[register, actions]`.
```tsx
import { RTablePro, useTablePro } from '@ray-template/ui/table-pro'
const [register, { isReady, reload }] = useTablePro()
const renderTable = () => (
<>
<button disabled={!isReady.value} onClick={() => reload(true)}>
Refresh from page 1
</button>
<RTablePro
onRegister={register}
columns={[{ title: 'Name', key: 'name' }]}
/>
</>
)
```
In an SFC, use `<RTablePro @register="register" />`. Call the hook once per table. Registration occurs on mount and clears on unmount. `actions` includes the instance methods, `getTableProInstance()`, and read-only `isReady`. `isReady` indicates instance binding, independent of request status. Calling an instance method before binding throws.
Destructure `queryState` from `actions` and read `queryState.value` reactively for TablePro-managed remote requests. With a component ref, read `table.value?.queryState`.
| Field | Meaning |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `loading` | A `request` is running. The external `loading` prop is separate. |
| `failed` | The current request failed. A retry clears it. Use `onRequestError` for details. |
| `page` / `pageSize` | Current page and page size. Both are `null` when pagination is disabled. |
| `total` | Filtered total from the latest successful result in this query scope. A scope change or failure clears it to `null` until success. |
The `queryState` snapshot and fields are read-only. It is `null` before mount, after unmount, or without `request`, including manual remote mode. Canceled older requests cannot overwrite current query state.
`getCurrentPageData()` reads current-page rows. Local tables apply filters, sort, and pagination. TablePro-managed remote tables return only rows matching the current query and page. Treat these rows as read-only and make business changes through the page's data. Virtual scrolling leaves the data range intact. Replace `runTableRequest` or `runAsyncTableRequest` with `reload` and pass query conditions through `params` or the request function.
[Run the three hook examples](./table-pro-examples#实例与-hooks)
## Column settings and persistence {#列设置与缓存}
Try the [live column settings example](./table-pro-examples#列设置与缓存). Use stable, unique column keys. Column settings control visibility, root column order by drag or move buttons, pinning, and resizability. Group children follow the root column. Set `columnStateKey` to keep hidden columns after refresh. Include the account or tenant identifier in it when needed. The cache stores visibility only. With `v-model:columns`, the caller receives complete definitions including hidden columns. **Reset column layout** preserves visibility. In controlled mode, supply `onResetColumnLayout` to restore your column definitions.
## Copy a table image {#复制表格图片}
**Copy table image** copies the table header, rows, visible internal scroll area, and native paginator as PNG for pasting into a chat or document. The image excludes the title, filters, toolbar, notices, `tableFooter`, and `tableAction`. It preserves current scroll position and pinned columns. Capture is limited to the table's visible DOM box. Virtual scrolling captures rendered rows only and makes no additional page requests.
```tsx
const [register, { copyImage }] = useTablePro()
<RTablePro onRegister={register} columns={columns} data={rows} copyImageOptions={{ pixelRatio: 1 }} />
<NButton onClick={() => void copyImage()}>Copy table image</NButton>
```
`showCopyImage={false}` hides the button. The instance and hook still expose `copyImage(options?)`. Output is PNG. `copyImageOptions` supports `pixelRatio`, background, dimensions, styles, filters, fonts, and resource request options. Call options take precedence. The default device pixel ratio is capped at 2. The filter callback receives temporary snapshot nodes, so match classes or data attributes.
Call directly from a click handler before awaiting another task. Image rendering can be asynchronous, but the clipboard call needs user activation. The implementation passes a `Promise<Blob>` to the native `ClipboardItem` up front. [WebKit Clipboard API](https://webkit.org/blog/10855/async-clipboard-api/)
A successful write returns `true`. Loading, duplicate calls, unconfirmed data, cancellation, and failure return `false`. Use HTTPS or localhost, a browser that supports writing PNG, and clipboard permission. Permission, resource, and rendering failures have feedback. Data replacement or unmount cancels pending rendering and removes temporary nodes. The browser retains writes it already accepted. Cross-origin images, fonts, and protected canvases remain subject to browser policy. Use CSV or print for complete current-page rows.
Same-origin RIcon sprites and local `#symbol` icons are expanded in the snapshot with their static geometry, dimensions, and `currentColor`. Imported IDs are omitted. Fetches are limited to registered same-origin sprites or public `.svg` files, with credentials omitted and redirects rejected. One operation accepts up to 16 files and 1 MiB per file. Nested references, paint servers, stylesheets, and dynamic CSS values are unsupported. Snapshots strip scripts and inline event handlers and reject active `iframe/object/embed/audio/video` elements.
## Printing and CSV {#打印与-csv}
Try the [live print and CSV example](./table-pro-examples#打印与-csv). Both use visible data columns on the current page by default. Printing creates a separate table with current filters and sorting. Vue cells, actions, expanded content, and merged layouts are outside that rendering. For a custom report, set `printTableOptions.target` to an element, ref, or getter. By default it copies host stylesheets, the root theme, and current ordinary form values. Set `includePageStyles: false` to opt out of page styles. A call can supply `title` and dedicated `style`. Use print CSS for layouts that depend on outside ancestors, scripts, or embeds. Password and file values are omitted. Physical printing is handled by the browser.
For CSV, `keepOriginalData` exports the entire batch supplied to the table. It does not fetch other remote pages. Exclude a column with `allowExport: false`. `getCsvCell` and `getCsvHeader` return raw text, and the component escapes CSV fields.
[Full TablePro contract](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/README.md) · [Table examples](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main/apps/admin/src/views/demo/tables) · [What changed in v6](../migration#v6-的变更)
## Props, events, and slots {#props、事件和插槽}
Naive UI DataTable still owns column definitions, selection, expansion, loading, empty states, and virtual scrolling. These options are provided or overridden by TablePro.
| Option | Default or behavior |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bare` | Off. Removes the card appearance and hides the title and toolbar. Pagination is off when omitted. Explicit search and footer slots still work. |
| `autoHeight` | Off. Enables DataTable `flexHeight` when the workspace provides height. |
| `tool` | On. Controls image copying, density, fullscreen, column settings, and appearance. The custom `toolbar` remains available. |
| `title` | String or VNode. A `title` slot takes precedence. |
| `pagination` | On in standard mode. `false` disables it. Objects pass through to Naive UI Pagination. Below 600 px, the default is simple mode. Explicit `simple` takes precedence. |
| `pageSize` | Default 10. `pagination.pageSize` takes first precedence, then `pagination.defaultPageSize`. Remote mode reads `pagination.defaultPage` for its initial page. |
| `request` / `params` | `request` enables TablePro-managed remote data. Deep changes to `params` trigger a new query from page 1. |
| `search` | Supports legacy field arrays, `TableProSearchOptions`, and `false`. [Advanced search](#高级搜索) |
| `rowKey` | Defaults to `row.id ?? row.key`. Supply a stable key if neither exists. |
| `columnStateKey` | Persistence is off by default. Provide a stable identifier to remember hidden columns. |
| `downloadCsvTableOptions` | CSV defaults. The template uses `fileName` and `keepOriginalData`. |
| `onResetColumnLayout` | Controlled column layout reset callback. Update `columns` in the callback. |
| `printTableOptions` | `target`, `title`, `style`, `includePageStyles`, `formatHeader`, and `formatCell`. |
| `showPrint` | `false`. Controls the print item under More actions. `print()` remains callable. |
| `showCopyImage` | `true`. Controls the built-in PNG button. `copyImage()` remains callable. |
| `copyImageOptions` | PNG rendering defaults that `copyImage(options)` can override. [Copy a table image](#复制表格图片) |
| `contextMenuOptions` / `onContextMenuClick` | Row menu items and callback `(key, option, { row, index })`. Open with right-click, Shift+F10, or the Menu key. A row handler can call `preventDefault()`. |
Common events include `onRequestError(error)` (or SFC `@request-error`), `onUpdatePage`, `onUpdatePageSize`, and `onUpdate:columns`. Internal updates and controlled callbacks use the same entry points. For controlled values, update them in the caller. Row selection and sorting follow DataTable events. Put server-side sort parameters in `params`.
Pagination objects use `TableProPagination`. Replace the old `pagination.onChange/onPageSizeChange` and top-level `onPageChange/onPageSizeChange` with `onUpdatePage/onUpdatePageSize` or `onUpdate:page/onUpdate:pageSize`. The native paginator no longer receives the old fields.
| Slot | Parameters and location |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `filters` | Above the table. Receives `{ submit(values) }` for string- or number-keyed filters. Submit returns to page 1. Takes precedence over built-in `search`. |
| `title` / `toolbar` | Left title area and right action area. Both are hidden in `bare` mode. |
| `notice` | Custom notice in normal conditions. |
| `error` | Replaces `notice` after failure if supplied. Receives `{ reload }` and replaces the default toast. |
| `tableFooter` / `tableAction` | Extra regions after DataTable. |
| Other slots | Forwarded to Naive UI DataTable, including loading and empty state. |
`TableProInst.reload(resetPage?)`, `setPage(page)`, and `setPageSize(size)` return `Promise<void>`. Request errors use events, so promise completion alone does not establish business success. `getTableInstance()` may be `null`. `print(options?)` returns `Promise<boolean>` indicating whether a preview was requested. `downloadCsv(options?)` initiates a browser download. `copyImage(options?)` reports whether a PNG was written to the clipboard.
Remote requests merge `params` and applied filters, with the latter taking precedence, then write pagination fields. Disabling pagination removes any supplied `page` and `pageSize`. `total` must be a nonnegative safe integer and `data` an array. If filtering or deletion leaves the current page outside the result range, TablePro moves to the final page and queries it when results exist.
[TablePro Props](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/src/props.ts) · [Remote queries and pagination](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/src/TablePro.tsx) · [Table panel](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/ui/src/RTablePro/src/TablePanel.tsx)

View File

@ -0,0 +1,13 @@
# Utilities {#工具函数}
`@/utils` aggregates public template utilities. Application initialization and lower-level code can use focused entries such as `@/utils/core`, `@/utils/cache`, and `@/utils/files` to avoid importing unrelated dependencies. Legacy `basic.ts` and `c/` remain forwarding entries.
| Topic | APIs |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| [Core, dates, and numbers](./utils/core) | Type checks, PromiseLike, random identifiers, error handling, object updates, date ranges, and fixed-point arithmetic |
| [Storage and legacy encryption](./utils/storage) | Local and Session Storage, prefixes, and legacy AES JSON |
| [Vue and browser utilities](./utils/browser) | Ref and DOM unwrapping, styles, queries, downloads, capture, printing, and menu positioning |
Run downloads and printing in the browser. Create reactive DOM utilities in a Vue scope. Storage and file API generics provide types. Validate data when it crosses a trust boundary.
[Public exports](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/index.ts) · [Implementation and regression index](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/README.md)

View File

@ -0,0 +1,61 @@
# Vue and Browser Utilities {#vue-与浏览器工具}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
## Interactive example {#交互示例}
Change the element's color and dimensions to inspect classes, queries, and styles. You can also start or stop a Vue scope, convert the sample PNG, download a sample file, or open print preview.
<AdminExample path="/docs-browser-utils" title="Vue, DOM, and file utilities" layout :height="570" />
::: details View example source
<<< @/../admin/src/views/demo/docs-browser-utils.tsx
:::
## Resolve Vue targets {#vue-目标解析}
`BasicTarget<T>` can be an element, component instance, ref, getter, or empty value. `unrefElement(target, fallback?)` unwraps it at call time and prefers `$el` for components. A multi-root component's `$el` may be unsuitable for DOM operations. Bind a native element ref for capture, fullscreen, or styling.
| Utility | Behavior |
| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `call(fnOrFns, ...args)` | Calls one function or an array in order, forwarding the arguments. |
| `renderNode(value, { defaultElement }?)` | Normalizes to a render function. Only `null` and `undefined` use the fallback. `0` and empty strings are preserved. |
| `effectDispose(cleanup)` | Registers cleanup and returns `true` in an active effect scope. Otherwise returns `false` and the caller owns cleanup. |
| `watchEffectWithTarget(effect, options?)` | Compatibility entry point for Vue `watchEffect`. Returns a stop handle and stops with its active scope. |
## DOM, styling, and sizing {#dom、样式和尺寸}
| API | Behavior |
| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `setClass(target, names)` / `removeClass(target, names)` | Applies to the current and replacement targets. Accepts whitespace-separated names or an array. `removeAllClass` clears all classes. |
| `hasClass(target, names)` | Reactive Boolean, true if any complete class name matches. Tracks target changes. An external class edit does not trigger recalculation. |
| `setStyle(target, styles)` | Accepts an object, declaration string, or array of strings and preserves other inline styles. Supports camelCase, custom properties, and `!important`. |
| `removeStyle(target, names)` | Removes inline styles by their CSS or camelCase names. |
| `autoPrefixStyle(name)` | Returns a compatibility map of the original property and legacy prefixed names without touching the DOM. |
| `completeSize(value, unit = 'px')` | Adds units to numbers and numeric strings. Keeps percentages, CSS keywords, and expressions. |
| `colorToRgba(color, alpha = 1, fallback?)` | Supports comma-separated RGB and HSL and common Hex values. Hex with alpha retains it. Unknown formats use the given fallback or the original string. |
| `queryElements(selector, { defaultElement }?)` | Returns DOM elements. `attr:data-id` is equivalent to an attribute selector. No matches return an empty array. An empty or invalid selector with no fallback returns `null`. |
| `positionSelectedMenuItem()` | Scrolls a rendered active menu item into view if needed. Expand its ancestors and wait for the DOM first. |
Class and style functions observe target changes. Create them in component setup or an effect scope. With SSR, call APIs that read `document` or `window` after mounting.
## Files, downloads, and printing {#文件、下载和打印}
| API | Behavior |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fileToBase64(file)` | Promise of a Data URL with MIME type. Read failure or abort rejects. |
| `arrayBufferToBase64Image(buffer)` | Adds a PNG Data URL prefix to PNG bytes. It does not convert other formats. |
| `downloadBase64File(url, fileName)` | Starts download through a temporary link, then cleans up. |
| `downloadAnyFile(data, fileName)` | Accepts Data URL, Blob, File, or ArrayBuffer. Binary data uses a temporary object URL. The promise resolves once the download is initiated. |
| `printDom(target, { printOptions?, domToImageOptions? })` | Captures the DOM as JPEG, then opens print preview. Returns `Promise<boolean>`, logs failures and returns `false`, and updates the global Loading Bar if available. |
```ts
import { downloadAnyFile, fileToBase64 } from '@/utils'
export const previewFile = (file: File) => fileToBase64(file)
export const downloadReport = (pdf: Blob) => downloadAnyFile(pdf, 'report.pdf')
```
[DOM utilities](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/element.ts) · [File utilities](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/utils/src/files/index.ts) · [Vue utilities](https://github.com/XiaoDaiGua-Ray/ray-template/tree/main/packages/composables/src/vue) · [Capture and print hooks](../hooks/output)

View File

@ -0,0 +1,99 @@
# Core, Date, and Number Utilities {#基础、日期和数值工具}
Import these utilities from `@/utils`. Core implementations are available from `@/utils/core` and precision functions from `@/utils/precision`.
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
import PrecisionDemo from '../../../examples/PrecisionDemo.vue'
</script>
## Core utilities example {#基础工具交互示例}
Compare PromiseLike values with async functions, try synchronous and asynchronous error callbacks, or inspect paths, date ranges, and object updates.
<AdminExample path="/docs-core-utils" title="Type, identifier, error, path, and date utilities" />
::: details View core example source
<<< @/../admin/src/views/demo/docs-core-utils.tsx
:::
## Types, identifiers, and error handling {#类型、标识和错误处理}
| API | Input and return value |
| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `isValueType<T>(value, type)` | Checks the `Object.prototype.toString` tag. Ordinary and async functions both match `Function`. |
| `isPromise<T>(value)` | Returns `true` for a callable `then`, including custom PromiseLike values. |
| `isAsyncFunction(fn)` | Tests for an `async` declaration. Returning a promise from an ordinary function does not match. |
| `uuid(length = 16, radix = 62)` | Web Crypto random identifier. The character set is digits, uppercase letters, then lowercase letters. Radix is 1–62 and length is a nonnegative safe integer. Invalid input throws `RangeError`. The identifier uses this custom format. |
| `callWithErrorHandling(fn, onError, args?)` | Returns the synchronous result. On exception, calls the callback and returns `undefined`. It does not await promises. |
| `callWithAsyncErrorHandling(fn, onError, args?)` | Awaits the result and handles both synchronous exceptions and rejections. Errors thrown by the callback reach the caller. |
```ts
import { callWithAsyncErrorHandling, uuid } from '@/utils'
export const draftId = () => 'draft-' + uuid(12, 36)
export function loadOrReport<T>(
load: () => Promise<T>,
report: (error: Error) => void,
) {
return callWithAsyncErrorHandling(load, report)
}
```
## Objects, paths, and dates {#对象、路径和日期}
- `updateObjectValue(obj, key, value, callback?)` updates only own properties. If both values are plain objects, it shallow-merges them. Otherwise it replaces the old value. Success invokes the callback.
- `removeDuplicateKeys(obj)` returns a shallow copy of own enumerable properties. Duplicate keys in a JavaScript literal already use the last value by object creation.
- `equalRouterPath(a, b)` ignores query, hash, and trailing slash. Use full paths when filters or tab instances matter.
- `getDateByNaiveDatePicker(value, isRange)` converts an empty range from `null` to `[null, null]` and preserves other values, including units, time zone, and format.
- `getAppEnvironment()` exposes Vite `import.meta.env` for values such as `MODE`, `DEV`, and `PROD`. Keep secrets out of client-visible configuration.
- `detectOperatingSystem()` uses the User-Agent to return an `OperatingSystem` such as iOS (including iPad with a desktop identifier), Android, Windows, macOS, Linux, or Unknown. Use it for display hints and detect capabilities separately.
## Fixed-point arithmetic {#定点运算}
`CurrencyArguments` can be a number, string, or currency.js instance. The template defaults to eight decimal places. Results are currency.js instances with `.value` and `.toString()`.
### Interactive example {#交互示例}
Change both numbers and compare `add` with JavaScript `+`. This example calls `@ray-template/utils/precision` directly.
<PrecisionDemo />
::: details View example source
<<< @/examples/PrecisionDemo.vue
:::
The admin precision demo also provides subtraction, multiplication, division, and allocation.
<AdminExample path="/precision" title="Fixed-point arithmetic and allocation" />
::: details View the complete precision demo source
<<< @/../admin/src/views/demo/precision/index.tsx
:::
### API
| API | Behavior |
| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `add(...values)` | Sum. No arguments return zero. |
| `subtract(first, ...rest)` | Subtract in order. |
| `multiply(first, ...rest)` | Multiply in order, parsing string factors first. |
| `divide(first, ...rest)` | Divide in order. Zero divisors or nonfinite results throw `RangeError`. |
| `format(value, options?)` | Convert at the chosen precision. Defaults to a number. `type: 'string'` returns a string retaining precision. |
| `distribute(value, length, options?)` | Split evenly and assign rounding remainders to the first shares. `0` and `1` both mean one share. Negative or noninteger counts throw. Supports `precision` and `type`. |
| `isCurrency(value)` | Checks for an instance of the current currency.js class. |
```ts
import { add, distribute, format } from '@/utils'
export const amount = format(add('0.1', '0.2'), {
precision: 2,
type: 'string',
})
export const parts = distribute(10, 3, { precision: 2, type: 'string' })
```
Define decimal places and rounding rules for allocation and settlement in the business code. currency.js stores scaled integers as JavaScript numbers, so the amount times `10 ** precision` must remain within the safe integer range. Transfer strings or integer minor units across APIs to avoid binary floating-point artifacts in display.
[Core utilities](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/utils/src/core/index.ts) · [Precision implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/utils/src/precision.ts) · [Date picker helper](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/get-date-by-naive-date-picker.ts)

View File

@ -0,0 +1,58 @@
# Storage and Legacy Encryption {#缓存与兼容加密}
<script setup>
import AdminExample from '../../../examples/AdminExample.vue'
</script>
## Interactive example {#交互示例}
<AdminExample path="/cache-demo" title="Write, read, and remove cached values" />
::: details View example source
<<< @/../admin/src/views/demo/cache-demo/index.tsx
:::
## Web Storage
The default is `sessionStorage`, scoped to the current tab session. Pass `'localStorage'` for persistence beyond that session. Values use JSON serialization. Type parameters affect compile-time typing. Validate the stored shape when needed.
| API | Behavior |
| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `setStorage(key, value, storageType?, options?)` | Writes a serializable value. Empty keys, circular references, and denied writes log an error. |
| `getStorage<T>(key, storageType?, options?)` | Returns `options.defaultValue` or `null` when missing, malformed, or unreadable. An explicit JSON `null` stays `null`. |
| `hasStorage(key, storageType?, options?)` | Checks for a key and returns `false` if storage is inaccessible. JSON content is not validated. |
| `removeStorage(key, storageType?, options?)` | Removes a key. `__all__`, `__all_sessionStorage__`, and `__all_localStorage__` perform bulk removal. |
| `prefixCacheKey(key, { customPrefix }?)` | Prepends the custom prefix or `APP_CATCH_KEY_PREFIX`. Include any separator in the prefix. |
Storage methods call the prefix helper only with `options.prefix: true`. `prefixKey` overrides the default. A nonempty prefix limits bulk removal to matching keys. With an empty prefix, removal clears the corresponding storage area. Use the same prefix options for reads, writes, and removal. Pinia has its own persistence settings, so changing this utility prefix leaves old Pinia data in place.
```ts
import { getStorage, removeStorage, setStorage } from '@/utils'
const options = { prefix: true, prefixKey: 'inventory:' }
export function saveOrderFilter(status: string) {
setStorage('order-filter', { status }, 'sessionStorage', options)
}
export const readOrderFilter = () =>
getStorage<{ status: string }>('order-filter', 'sessionStorage', options)
export const clearOrderFilter = () =>
removeStorage('order-filter', 'sessionStorage', options)
```
The shared package's `createStorage(storage, prefix?)` builds `get`, `set`, and `remove` on a host-provided synchronous store. It uses the same JSON format. Failed reads return `null` and failed writes or removals are contained. Unserializable values such as `undefined`, functions, and circular objects leave existing data intact. The prefix is concatenated directly with the key.
## Legacy AES JSON {#兼容-aes-json}
This example compares cache key prefixes and uses a sample passphrase to encrypt and recover JSON.
<AdminExample path="/docs-storage-utils" title="Cache keys and legacy AES JSON" />
::: details View example source
<<< @/../admin/src/views/demo/docs-storage-utils.tsx
:::
`encrypt(data, key?)` returns serialized JSON ciphertext and `decrypt(ciphertext, key?)` decodes it. Use a passphrase string or CryptoJS `WordArray`. Encryption and decryption require the same key type and contents. Passphrases use the OpenSSL-compatible format. Raw keys use a random IV and serialize to `IV:ciphertext`. An invalid ciphertext or key logs an error and returns `undefined`. Unserializable input throws during encryption.
`CRYPTO_KEY` is a public compatibility constant for existing local data, such as the demo lock screen. Protect server credentials and sessions with server-side mechanisms. Preserve reads of legacy ciphertext when migrating formats.
[Storage implementation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/cache.ts) · [Encryption](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/legacy-crypto/encrypt.ts) · [Decryption](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/utils/legacy-crypto/decrypt.ts)

View File

@ -2,9 +2,11 @@
<DemoFrame>
<div class="ray-demo">
<NButton v-debounce="{ wait: 500, func: increment }">
连续点击 / Click repeatedly
{{ english ? 'Click repeatedly' : '连续点击' }}
</NButton>
<output class="ray-demo-result">执行次数 / Calls: {{ calls }}</output>
<output class="ray-demo-result">
{{ english ? 'Calls' : '执行次数' }}: {{ calls }}
</output>
</div>
</DemoFrame>
</template>
@ -12,9 +14,12 @@
<script setup lang="ts">
import debounce from '@ray-template/directives/debounce'
import { NButton } from 'naive-ui'
import { ref } from 'vue'
import { useData } from 'vitepress'
import { computed, ref } from 'vue'
import DemoFrame from './DemoFrame.vue'
const { lang } = useData()
const english = computed(() => lang.value.startsWith('en'))
const vDebounce = debounce()
const calls = ref(0)
const increment = () => {

View File

@ -4,8 +4,12 @@
<NButton @click="toggleFullscreen">
{{
isFullscreen
? '退出全屏 / Exit full screen'
: '元素全屏 / Full screen'
? english
? 'Exit fullscreen'
: '退出全屏'
: english
? 'Enter fullscreen'
: '元素全屏'
}}
</NButton>
</div>
@ -15,9 +19,12 @@
<script setup lang="ts">
import { useElementFullscreen } from '@ray-template/composables/useElementFullscreen'
import { NButton } from 'naive-ui'
import { useTemplateRef } from 'vue'
import { useData } from 'vitepress'
import { computed, useTemplateRef } from 'vue'
import DemoFrame from './DemoFrame.vue'
const { lang } = useData()
const english = computed(() => lang.value.startsWith('en'))
const { isFullscreen, toggleFullscreen } = useElementFullscreen(
useTemplateRef('preview'),
)

View File

@ -1,7 +1,9 @@
<template>
<div class="ray-demo ray-demo-fields">
<div>
<label :for="id">路由配置 / Route configuration</label>
<label :for="id">{{
english ? 'Route configuration' : '路由配置'
}}</label>
<textarea
:id="id"
v-model="source"
@ -16,8 +18,11 @@
<script setup lang="ts">
import { createRouteContract } from '@ray-template/routing'
import { useData } from 'vitepress'
import { computed, ref, useId } from 'vue'
const { lang } = useData()
const english = computed(() => lang.value.startsWith('en'))
const load = async () => ({})
const { parseRouteConfig } = createRouteContract({
layout: load,
@ -50,7 +55,7 @@ const result = computed(() => {
return {
invalid: false,
message: `有效路由 / Valid routes: ${routes.length}`,
message: `${english.value ? 'Valid routes' : '有效路由'}: ${routes.length}`,
}
} catch (error) {
return {

View File

@ -30,7 +30,7 @@ VITE_API_BASE_URL=https://your-api.example.com/api/
也可以使用同源 `/api/`,由部署代理转发。设置 `VITE_API_BASE_URL` 后默认关闭 Mock,显式 `VITE_API_MOCK=true` 才重新启用。接口基址可以包含版本前缀;页面只通过 `api/admin` 的方法调用,不拼接固定域名。`VITE_*` 会进入浏览器产物,仅用于公开配置。
Mock 在应用启动前完成 Service Worker 注册。每次 API 请求前检查内部健康标记;浏览器回收 worker 后,在同一个 MSW 客户端实例上调用 `stop()` / `start()` 恢复,让同一个客户端管理监听器和拦截状态。恢复失败则阻止业务请求继续发送,表单和演示数据保持原样。内部 `GET /admin/mock-health` 仅由 Mock 使用,关闭 Mock 后不请求这个接口。Worker 脚本路径为 `/ray-template/mockServiceWorker.js`,注册 URL 带有当前 MSW 版本的查询参数,作用域为应用 base。静态服务器须在该路径提供脚本。浏览器需要 HTTPS 或 localhost。GitHub Pages 只托管静态文件,这些 API 由已启动的页面中的 Mock 响应;直接在地址栏打开 API 地址会返回 404。真实后端模式不启动 Mock,也不会在请求失败时返回伪造业务数据。当前锁定 MSW 3.0.4,安装不自动执行其 worker 复制脚本;升级时显式运行 `pnpm exec msw init apps/admin/public --save`,再做契约和浏览器验证。
应用在发送 Mock API 请求前等待 Service Worker 就绪,并检查内部健康标记;浏览器回收 worker 后,在同一个 MSW 客户端实例上调用 `stop()` / `start()` 恢复,让同一个客户端管理监听器和拦截状态。恢复失败则阻止业务请求继续发送,表单和演示数据保持原样。内部 `GET /admin/mock-health` 仅由 Mock 使用,关闭 Mock 后不请求这个接口。Worker 脚本路径为 `/ray-template/mockServiceWorker.js`,注册 URL 带有当前 MSW 版本的查询参数,作用域为应用 base。静态服务器须在该路径提供脚本。浏览器需要 HTTPS 或 localhost。GitHub Pages 只托管静态文件,这些 API 由已启动的页面中的 Mock 响应;直接在地址栏打开 API 地址会返回 404。真实后端模式不启动 Mock,也不会在请求失败时返回伪造业务数据。当前锁定 MSW 3.0.4,安装不自动执行其 worker 复制脚本;升级时显式运行 `pnpm exec msw init apps/admin/public --save`,再做契约和浏览器验证。
<!-- fullstack:start -->

View File

@ -1,6 +1,6 @@
# 应用配置
应用配置与站外文档配置分属两个仓库。这里说明 Ray Template 应用中的 `@/app-config`、Vite 配置和运行期设置。运行期保存的用户偏好可能覆盖源码默认值,验证默认设置时使用干净的浏览器存储。
后台应用和 VitePress 文档站各有自己的配置入口。这里说明 Ray Admin 的 `@/app-config`、Vite 配置和运行期设置。运行期保存的用户偏好可能覆盖源码默认值,验证默认设置时使用干净的浏览器存储。
| 文件 | 配置 |
| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

View File

@ -2,14 +2,14 @@
模板使用 Pinia 管理跨页面状态。业务代码从 `@/store` 导入相应的 Getters / Actions,读取引用用 `.value`,修改走动作。只属于一个组件或页面的状态可以继续用本地 ref。
| Store | 访问入口 | 持久化 |
| ------------------------------------------------ | ----------------------------------------------- | --------------------------------------------------------------------------- |
| [Setting](./store/setting) | `useSettingGetters` / `useSettingActions` | Local Storage `piniaSettingStore`,排除锁屏设置弹窗显隐;当前语言另外保存。 |
| [Menu](./store/navigation#menu-store) | `useMenuGetters` / `useMenuActions` | Local Storage 保存当前菜单和折叠状态;标签列表另存 Session Storage。 |
| [KeepAlive](./store/navigation#keepalive-store) | `useKeepAliveGetters` / `useKeepAliveActions` | Session Storage 保存可缓存组件名。 |
| [Runtime](./store/runtime#runtime-store) | `useRuntimeGetters` / `useRuntimeActions` | 无;随当前 Pinia 实例释放。 |
| [Lock Screen](./store/runtime#lock-screen-store) | `useLockScreenGetters` / `useLockScreenActions` | Local Storage 的历史布尔值,支持跨标签同步。 |
| [Signing](./store/signing) | `useSigningGetters` / `useSigningActions` | Local Storage 持久化账号显示信息,路由守卫另读 token。 |
| Store | 访问入口 | 持久化 |
| ------------------------------------------------ | ----------------------------------------------- | ---------------------------------------------------------------------------------------- |
| [Setting](./store/setting) | `useSettingGetters` / `useSettingActions` | Local Storage `piniaSettingStore`,排除锁屏设置弹窗显隐;当前语言另外保存。 |
| [Menu](./store/navigation#menu-store) | `useMenuGetters` / `useMenuActions` | Local Storage 保存侧栏折叠状态,Session Storage 保存标签列表,菜单选中项由当前路由得出。 |
| [KeepAlive](./store/navigation#keepalive-store) | `useKeepAliveGetters` / `useKeepAliveActions` | Session Storage 保存可缓存组件名。 |
| [Runtime](./store/runtime#runtime-store) | `useRuntimeGetters` / `useRuntimeActions` | 无;随当前 Pinia 实例释放。 |
| [Lock Screen](./store/runtime#lock-screen-store) | `useLockScreenGetters` / `useLockScreenActions` | Local Storage 的历史布尔值,支持跨标签同步。 |
| [Signing](./store/signing) | `useSigningGetters` / `useSigningActions` | 资料和权限保存在内存,刷新后由会话接口恢复。Bearer 模式将令牌保存在 Local Storage。 |
## 初始化与扩展

View File

@ -25,7 +25,7 @@
| `getMenuConfig` | `menuConfig`,侧栏、折叠、图标、手风琴与滚动配置。 |
| `getColorWeakness` / `getDynamicDocumentTitle` | `colorWeakness` 默认关,`dynamicDocumentTitle` 默认开。 |
`layoutConfig` 的 `mode` 为 `side`(默认)、`top`、`mixed`。`contentWidth` 默认 `fluid`,也可取 `fixed`。`contentMaxWidth` 默认 1200,限制在 640–2560;`contentPadding` 默认 16,限制在 0–48;`fixedHeader`、`fixedFooter` 默认开启。旧缓存水合时补齐字段并规范化范围。
`layoutConfig.mode` 支持 `side`(默认)、`top`、`mixed`、`right` 和 `split`。`contentWidth` 支持 `fluid`(默认)或 `fixed`。`contentMaxWidth` 默认 1200,限制在 640–2560。`contentPadding` 默认 24,限制在 0–48。`fixedHeader` 和 `fixedFooter` 默认开启。旧缓存水合时补齐字段并规范化范围。
`menuConfig` 默认菜单宽 272、折叠宽 64、展开与顶部菜单图标 20 px、折叠侧栏图标 22 px、缩进 24。`collapsedMode` 默认 `width`,`transform` 模式改变位置;`accordion`、`inverted`、`nativeScrollbar` 默认关,`menuSiderBarLogo` 默认开。`sideBarLogo.jumpType` 用 `station` 站内跳转或 `outsideStation` 打开外部地址,未传 `url` 时不跳转。旧浏览器缓存中同时为 16 px 的尺寸组合会升级为新默认值;当前应用保存的尺寸和偏好文件中的尺寸会原样保留。缓存中的旧裸图标名会尝试映射成完整名称;需要持久化的 Logo 建议用图标名字符串,VNode 不适合作为缓存值。
@ -38,7 +38,7 @@
| `changePrimaryColor(value?, alpha = 0.85)` | 覆盖当前风格的主色;省略 value 恢复当前风格原色。 |
| `toggleColorWeakness(bool)` | 更新设置并切换 HTML 反色滤镜。 |
切换主题使用 [useTheme](../hooks/appearance#usetheme),切换首页使用 [useAppRoot](../hooks/navigation#useapproot)。修改嵌套配置时传入完整的下一级对象,浅合并不会递归保存更深层字段。
切换主题使用 [useTheme](../hooks/appearance#usetheme)。[useAppRoot](../hooks/navigation#useapproot) 保留历史偏好的兼容读写。修改嵌套配置时传入完整的下一级对象,浅合并不会递归保存更深层字段。
```ts
import { useSettingActions, useSettingGetters } from '@/store'

View File

@ -14,7 +14,7 @@ import AdminExample from '../../examples/AdminExample.vue'
## Web Storage
默认使用 `sessionStorage`,传 `'localStorage'` 跨刷新保存。所有读写值按 JSON 序列化。类型参数仅影响 TypeScript,不能确认缓存格式。
默认使用当前标签会话的 `sessionStorage`。传 `'localStorage'` 可在标签关闭后继续保存。所有值按 JSON 序列化。类型参数仅影响 TypeScript,缓存结构需要按实际边界校验。
| API | 行为 |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------- |