diff --git a/README.md b/README.md index 0def8a5b..dbb6490e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Give developers and coding agents the same path through the project: **find the implementation, understand its contracts, reuse existing capabilities, and verify the change.** -[简体中文](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) @@ -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 `, 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 `, 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).
View the workspace and dark theme previews @@ -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#容器启动) @@ -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. --- diff --git a/apps/docs/.vitepress/config.mts b/apps/docs/.vitepress/config.mts index 2eeebdc0..28b7d322 100644 --- a/apps/docs/.vitepress/config.mts +++ b/apps/docs/.vitepress/config.mts @@ -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` diff --git a/apps/docs/.vitepress/sidebar.mts b/apps/docs/.vitepress/sidebar.mts index 756edcfb..beddddb0 100644 --- a/apps/docs/.vitepress/sidebar.mts +++ b/apps/docs/.vitepress/sidebar.mts @@ -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, + } } diff --git a/apps/docs/.vitepress/theme/RayHome.vue b/apps/docs/.vitepress/theme/RayHome.vue index a9c18060..c569efc3 100644 --- a/apps/docs/.vitepress/theme/RayHome.vue +++ b/apps/docs/.vitepress/theme/RayHome.vue @@ -4,21 +4,26 @@

Ray Template

- 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.', + ) + }}

-

v6 工作区

+

{{ label('v6 工作区', 'v6 workspace') }}

  • - + {{ module.title }} {{ module.name }} @@ -37,12 +42,12 @@
    -

    常用文档

    +

    {{ label('常用文档', 'Popular guides') }}

    • @@ -67,18 +72,30 @@
      TablePro 自适应高度示例,虚拟滚动已开启,分页位于表格底部
      diff --git a/apps/docs/.vitepress/theme/index.ts b/apps/docs/.vitepress/theme/index.ts index 9dcc80d9..8a8031dd 100644 --- a/apps/docs/.vitepress/theme/index.ts +++ b/apps/docs/.vitepress/theme/index.ts @@ -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, ]) }, diff --git a/apps/docs/README.md b/apps/docs/README.md index 8530f9f2..f090729d 100644 --- a/apps/docs/README.md +++ b/apps/docs/README.md @@ -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. diff --git a/apps/docs/en/guide/appearance.md b/apps/docs/en/guide/appearance.md new file mode 100644 index 00000000..20f1f999 --- /dev/null +++ b/apps/docs/en/guide/appearance.md @@ -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 ``. 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 + + + + + +``` + +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/.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) diff --git a/apps/docs/en/guide/architecture.md b/apps/docs/en/guide/architecture.md new file mode 100644 index 00000000..6d5b07f4 --- /dev/null +++ b/apps/docs/en/guide/architecture.md @@ -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) + + + +The full-stack source also includes `apps/server`, which runs independently. [Server architecture](#可选服务端怎样分层) + + + +## 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) + + + +## 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) + + + +## 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/`. + +```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) diff --git a/apps/docs/en/guide/backend.md b/apps/docs/en/guide/backend.md new file mode 100644 index 00000000..8ba57554 --- /dev/null +++ b/apps/docs/en/guide/backend.md @@ -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. + + + +Download the OpenAPI 3.1 contract + +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. + + + +## 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. + + + +## 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: ""`. 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 ` 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. diff --git a/apps/docs/en/guide/distributions.md b/apps/docs/en/guide/distributions.md new file mode 100644 index 00000000..34616d2d --- /dev/null +++ b/apps/docs/en/guide/distributions.md @@ -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-/` 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. + + + +## Full-stack distribution {#全栈发行包} + +Run this command in the complete repository. + +```sh +pnpm dist:fullstack +``` + +The same output directory contains `ray-template-fullstack-/` 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 `. 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. + + diff --git a/apps/docs/en/guide/first-page.md b/apps/docs/en/guide/first-page.md new file mode 100644 index 00000000..5b6a0673 --- /dev/null +++ b/apps/docs/en/guide/first-page.md @@ -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 () => ( + + ) + }, +}) +``` + +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) diff --git a/apps/docs/en/guide/layout.md b/apps/docs/en/guide/layout.md new file mode 100644 index 00000000..5d1cbd40 --- /dev/null +++ b/apps/docs/en/guide/layout.md @@ -0,0 +1,80 @@ +# Layout and state {#应用布局与状态} + + + +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. + +