diff --git a/apps/vben5/.browserslistrc b/apps/vben5/.browserslistrc new file mode 100644 index 000000000..dc3bc09a2 --- /dev/null +++ b/apps/vben5/.browserslistrc @@ -0,0 +1,4 @@ +> 1% +last 2 versions +not dead +not ie 11 diff --git a/apps/vben5/.changeset/README.md b/apps/vben5/.changeset/README.md new file mode 100644 index 000000000..5654e898b --- /dev/null +++ b/apps/vben5/.changeset/README.md @@ -0,0 +1,5 @@ +# Changesets + +Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it [in our repository](https://github.com/changesets/changesets) + +We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/apps/vben5/.changeset/config.json b/apps/vben5/.changeset/config.json new file mode 100644 index 000000000..f954fb4ba --- /dev/null +++ b/apps/vben5/.changeset/config.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://unpkg.com/@changesets/config@3.0.0/schema.json", + "changelog": [ + "@changesets/changelog-github", + { "repo": "vbenjs/vue-vben-admin" } + ], + "commit": false, + "fixed": [["@vben-core/*", "@vben/*"]], + "snapshot": { + "prereleaseTemplate": "{tag}-{datetime}" + }, + "privatePackages": { "version": true, "tag": true }, + "linked": [], + "access": "public", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "ignore": [] +} diff --git a/apps/vben5/.commitlintrc.js b/apps/vben5/.commitlintrc.js new file mode 100644 index 000000000..02e33fa62 --- /dev/null +++ b/apps/vben5/.commitlintrc.js @@ -0,0 +1 @@ +export { default } from '@vben/commitlint-config'; diff --git a/apps/vben5/.dockerignore b/apps/vben5/.dockerignore new file mode 100644 index 000000000..52b833a96 --- /dev/null +++ b/apps/vben5/.dockerignore @@ -0,0 +1,7 @@ +node_modules +.git +.gitignore +*.md +dist +.turbo +dist.zip diff --git a/apps/vben5/.editorconfig b/apps/vben5/.editorconfig new file mode 100644 index 000000000..179aec6f1 --- /dev/null +++ b/apps/vben5/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset=utf-8 +end_of_line=lf +insert_final_newline=true +indent_style=space +indent_size=2 +max_line_length = 100 +trim_trailing_whitespace = true +quote_type = single + +[*.{yml,yaml,json}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/apps/vben5/.gitattributes b/apps/vben5/.gitattributes new file mode 100644 index 000000000..d4e5bd3ed --- /dev/null +++ b/apps/vben5/.gitattributes @@ -0,0 +1,11 @@ +# https://docs.github.com/cn/get-started/getting-started-with-git/configuring-git-to-handle-line-endings + +# Automatically normalize line endings (to LF) for all text-based files. +* text=auto eol=lf + +# Declare files that will always have CRLF line endings on checkout. +*.{cmd,[cC][mM][dD]} text eol=crlf +*.{bat,[bB][aA][tT]} text eol=crlf + +# Denote all files that are truly binary and should not be modified. +*.{ico,png,jpg,jpeg,gif,webp,svg,woff,woff2} binary \ No newline at end of file diff --git a/apps/vben5/.gitconfig b/apps/vben5/.gitconfig new file mode 100644 index 000000000..4b28a69cd --- /dev/null +++ b/apps/vben5/.gitconfig @@ -0,0 +1,2 @@ +[core] + ignorecase = false diff --git a/apps/vben5/.gitignore b/apps/vben5/.gitignore new file mode 100644 index 000000000..c2a8a771f --- /dev/null +++ b/apps/vben5/.gitignore @@ -0,0 +1,51 @@ +node_modules +.DS_Store +dist +dist-ssr +dist.zip +dist.tar +dist.war +.nitro +.output +*-dist.zip +*-dist.tar +*-dist.war +coverage +*.local +**/.vitepress/cache +.cache +.turbo +.temp +dev-dist +.stylelintcache +yarn.lock +package-lock.json +.VSCodeCounter +**/backend-mock/data + +# local env files +.env.local +.env.*.local +.eslintcache + +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* +vite.config.mts.* +vite.config.mjs.* +vite.config.js.* +vite.config.ts.* + +# Editor directories and files +.idea +# .vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? +.history diff --git a/apps/vben5/.gitpod.yml b/apps/vben5/.gitpod.yml new file mode 100644 index 000000000..fb75b433d --- /dev/null +++ b/apps/vben5/.gitpod.yml @@ -0,0 +1,6 @@ +ports: + - port: 5555 + onOpen: open-preview +tasks: + - init: corepack enable && pnpm install + command: pnpm run dev:play diff --git a/apps/vben5/.husky/commit-msg b/apps/vben5/.husky/commit-msg new file mode 100644 index 000000000..270ebb8c1 --- /dev/null +++ b/apps/vben5/.husky/commit-msg @@ -0,0 +1,6 @@ +echo Start running commit-msg hook... + +# Check whether the git commit information is standardized +pnpm exec commitlint --edit "$1" + +echo Run commit-msg hook done. diff --git a/apps/vben5/.husky/post-merge b/apps/vben5/.husky/post-merge new file mode 100644 index 000000000..83fa775d5 --- /dev/null +++ b/apps/vben5/.husky/post-merge @@ -0,0 +1,3 @@ +# 每次 git pull 之后, 安装依赖 + +pnpm install diff --git a/apps/vben5/.husky/pre-commit b/apps/vben5/.husky/pre-commit new file mode 100644 index 000000000..5dccee288 --- /dev/null +++ b/apps/vben5/.husky/pre-commit @@ -0,0 +1,7 @@ +# update `.vscode/vben-admin.code-workspace` file +pnpm vsh code-workspace --auto-commit + +# Format and submit code according to lintstagedrc.js configuration +pnpm exec lint-staged + +echo Run pre-commit hook done. diff --git a/apps/vben5/.lintstagedrc.mjs b/apps/vben5/.lintstagedrc.mjs new file mode 100644 index 000000000..e68d8a3e0 --- /dev/null +++ b/apps/vben5/.lintstagedrc.mjs @@ -0,0 +1,20 @@ +export default { + '*.{js,jsx,ts,tsx}': [ + 'prettier --cache --ignore-unknown --write', + 'eslint --cache --fix', + ], + '*.{scss,less,styl,html,vue,css}': [ + 'prettier --cache --ignore-unknown --write', + 'stylelint --fix --allow-empty-input', + ], + '*.md': ['prettier --cache --ignore-unknown --write'], + '*.vue': [ + 'prettier --write', + 'eslint --cache --fix', + 'stylelint --fix --allow-empty-input', + ], + '{!(package)*.json,*.code-snippets,.!(browserslist)*rc}': [ + 'prettier --cache --write--parser json', + ], + 'package.json': ['prettier --cache --write'], +}; diff --git a/apps/vben5/.node-version b/apps/vben5/.node-version new file mode 100644 index 000000000..48b14e6b2 --- /dev/null +++ b/apps/vben5/.node-version @@ -0,0 +1 @@ +20.14.0 diff --git a/apps/vben5/.npmrc b/apps/vben5/.npmrc new file mode 100644 index 000000000..f4a1ad483 --- /dev/null +++ b/apps/vben5/.npmrc @@ -0,0 +1,13 @@ +registry = "https://registry.npmmirror.com" +public-hoist-pattern[]=husky +public-hoist-pattern[]=eslint +public-hoist-pattern[]=prettier +public-hoist-pattern[]=prettier-plugin-tailwindcss +public-hoist-pattern[]=stylelint +public-hoist-pattern[]=*postcss* +public-hoist-pattern[]=@commitlint/* +public-hoist-pattern[]=czg + +strict-peer-dependencies=false +auto-install-peers=true +dedupe-peer-dependents=true diff --git a/apps/vben5/.prettierignore b/apps/vben5/.prettierignore new file mode 100644 index 000000000..d0b0ca133 --- /dev/null +++ b/apps/vben5/.prettierignore @@ -0,0 +1,18 @@ +dist +dev-dist +.local +.output.js +node_modules +.nvmrc +coverage +CODEOWNERS +.nitro +.output + + +**/*.svg +**/*.sh + +public +.npmrc +*-lock.yaml diff --git a/apps/vben5/.prettierrc.mjs b/apps/vben5/.prettierrc.mjs new file mode 100644 index 000000000..3e25d2cfa --- /dev/null +++ b/apps/vben5/.prettierrc.mjs @@ -0,0 +1 @@ +export { default } from '@vben/prettier-config'; diff --git a/apps/vben5/.stylelintignore b/apps/vben5/.stylelintignore new file mode 100644 index 000000000..f4b2db2c1 --- /dev/null +++ b/apps/vben5/.stylelintignore @@ -0,0 +1,4 @@ +dist +public +__tests__ +coverage diff --git a/apps/vben5/LICENSE b/apps/vben5/LICENSE new file mode 100644 index 000000000..cec5b4274 --- /dev/null +++ b/apps/vben5/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2024-present, Vben + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/apps/vben5/README.ja-JP.md b/apps/vben5/README.ja-JP.md new file mode 100644 index 000000000..baa4cc448 --- /dev/null +++ b/apps/vben5/README.ja-JP.md @@ -0,0 +1,153 @@ +
VbenAdmin Logo

+ +[![license](https://img.shields.io/github/license/anncwb/vue-vben-admin.svg)](LICENSE) + +

Vue Vben Admin

+
+ +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=vbenjs_vue-vben-admin&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=vbenjs_vue-vben-admin) ![codeql](https://github.com/vbenjs/vue-vben-admin/actions/workflows/codeql.yml/badge.svg) ![build](https://github.com/vbenjs/vue-vben-admin/actions/workflows/build.yml/badge.svg) ![ci](https://github.com/vbenjs/vue-vben-admin/actions/workflows/ci.yml/badge.svg) ![deploy](https://github.com/vbenjs/vue-vben-admin/actions/workflows/deploy.yml/badge.svg) + +**日本語** | [English](./README.md) | [中文](./README.zh-CN.md) + +## 紹介 + +Vue Vben Adminは、最新の`vue3`、`vite`、`TypeScript`などの主流技術を使用して開発された、無料でオープンソースの中・後端テンプレートです。すぐに使える中・後端のフロントエンドソリューションとして、学習の参考にもなります。 + +## アップグレード通知 + +これは最新バージョン5.0であり、以前のバージョンとは互換性がありません。新しいプロジェクトを開始する場合は、最新バージョンを使用することをお勧めします。古いバージョンを表示したい場合は、[v2ブランチ](https://github.com/vbenjs/vue-vben-admin/tree/v2)を使用してください。 + +## 特徴 + +- **最新技術スタック**: Vue 3やViteなどの最先端フロントエンド技術で開発 +- **TypeScript**: アプリケーション規模のJavaScriptのための言語 +- **テーマ**: 複数のテーマカラーが利用可能で、カスタマイズオプションも豊富 +- **国際化**: 完全な内蔵国際化サポート +- **権限管理**: 動的ルートベースの権限生成ソリューションを内蔵 + +## プレビュー + +- [Vben Admin](https://vben.pro/) - フルバージョンの中国語サイト + +テストアカウント: vben/123456 + +

+ VbenAdmin Logo + VbenAdmin Logo + VbenAdmin Logo +

+ +### Gitpodを使用 + +Gitpod(GitHub用の無料オンライン開発環境)でプロジェクトを開き、すぐにコーディングを開始します。 + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/vbenjs/vue-vben-admin) + +## ドキュメント + +[ドキュメント](https://doc.vben.pro/) + +## インストールと使用 + +- プロジェクトコードを取得 + +```bash +git clone https://github.com/vbenjs/vue-vben-admin.git +``` + +- 依存関係のインストール + +```bash +cd vue-vben-admin + +corepack enable + +pnpm install + +``` + +- 実行 + +```bash +pnpm dev +``` + +- ビルド + +```bash +pnpm build +``` + +## 変更ログ + +[CHANGELOG](https://github.com/vbenjs/vue-vben-admin/releases) + +## 貢献方法 + +ご参加をお待ちしております![Issueを提出](https://github.com/anncwb/vue-vben-admin/issues/new/choose)するか、Pull Requestを送信してください。 + +**Pull Request:** + +1. コードをフォーク! +2. 自分のブランチを作成: `git checkout -b feat/xxxx` +3. 変更をコミット: `git commit -am 'feat(function): add xxxxx'` +4. ブランチをプッシュ: `git push origin feat/xxxx` +5. `pull request`を送信 + +## Git貢献提出規則 + +- 参考 [vue](https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md) 規則 ([Angular](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular)) + + - `feat` 新機能の追加 + - `fix` 問題/バグの修正 + - `style` コードスタイルに関連し、実行結果に影響しない + - `perf` 最適化/パフォーマンス向上 + - `refactor` リファクタリング + - `revert` 変更の取り消し + - `test` テスト関連 + - `docs` ドキュメント/注釈 + - `chore` 依存関係の更新/スキャフォールディング設定の変更など + - `ci` 継続的インテグレーション + - `types` 型定義ファイルの変更 + - `wip` 開発中 + +## ブラウザサポート + +ローカル開発には`Chrome 80+`ブラウザを推奨します + +モダンブラウザをサポートし、IEはサポートしません + +| [ Edge](http://godban.github.io/browsers-support-badges/)
IE | [ Edge](http://godban.github.io/browsers-support-badges/)
Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | +| :-: | :-: | :-: | :-: | :-: | +| サポートしない | 最新2バージョン | 最新2バージョン | 最新2バージョン | 最新2バージョン | + +## メンテナー + +[@Vben](https://github.com/anncwb) + +## スター歴史 + +[![Star History Chart](https://api.star-history.com/svg?repos=vbenjs/vue-vben-admin&type=Date)](https://star-history.com/#vbenjs/vue-vben-admin&Date) + +## 寄付 + +このプロジェクトが役に立つと思われた場合、作者にコーヒーを一杯おごってサポートを示すことができます! + +![donate](https://unpkg.com/@vbenjs/static-source@0.1.7/source/sponsor.png) + +Paypal Me + +## 貢献者 + + + Contributors + + +## Discord + +- [Github Discussions](https://github.com/anncwb/vue-vben-admin/discussions) + +## ライセンス + +[MIT © Vben-2020](./LICENSE) diff --git a/apps/vben5/README.md b/apps/vben5/README.md new file mode 100644 index 000000000..e84c8392e --- /dev/null +++ b/apps/vben5/README.md @@ -0,0 +1,152 @@ +
VbenAdmin Logo

+ +[![license](https://img.shields.io/github/license/anncwb/vue-vben-admin.svg)](LICENSE) + +

Vue Vben Admin

+
+ +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=vbenjs_vue-vben-admin&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=vbenjs_vue-vben-admin) ![codeql](https://github.com/vbenjs/vue-vben-admin/actions/workflows/codeql.yml/badge.svg) ![build](https://github.com/vbenjs/vue-vben-admin/actions/workflows/build.yml/badge.svg) ![ci](https://github.com/vbenjs/vue-vben-admin/actions/workflows/ci.yml/badge.svg) ![deploy](https://github.com/vbenjs/vue-vben-admin/actions/workflows/deploy.yml/badge.svg) + +**English** | [中文](./README.zh-CN.md) | [日本語](./README.ja-JP.md) + +## Introduction + +Vue Vben Admin is a free and open source middle and back-end template. Using the latest `vue3`, `vite`, `TypeScript` and other mainstream technology development, the out-of-the-box middle and back-end front-end solutions can also be used for learning reference. + +## Upgrade Notice + +This is the latest version, 5.0, and it is not compatible with previous versions. If you are starting a new project, it is recommended to use the latest version. If you wish to view the old version, please use the [v2 branch](https://github.com/vbenjs/vue-vben-admin/tree/v2). + +## Feature + +- **Latest Technology Stack**: Developed with cutting-edge front-end technologies like Vue 3 and Vite +- **TypeScript**: A language for application-scale JavaScript +- **Themes**: Multiple theme colors available with customizable options +- **Internationalization**: Comprehensive built-in internationalization support +- **Permissions**: Built-in solution for dynamic route-based permission generation + +## Preview + +- [Vben Admin](https://vben.pro/) - Full version Chinese site + +Test Account: vben/123456 + +

+ VbenAdmin Logo + VbenAdmin Logo + VbenAdmin Logo +

+ +### Use Gitpod + +Open the project in Gitpod (free online dev environment for GitHub) and start coding immediately. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/vbenjs/vue-vben-admin) + +## Documentation + +[Document](https://doc.vben.pro/) + +## Install and use + +- Get the project code + +```bash +git clone https://github.com/vbenjs/vue-vben-admin.git +``` + +- Installation dependencies + +```bash +cd vue-vben-admin + +corepack enable + +pnpm install +``` + +- run + +```bash +pnpm dev +``` + +- build + +```bash +pnpm build +``` + +## Change Log + +[CHANGELOG](https://github.com/vbenjs/vue-vben-admin/releases) + +## How to contribute + +You are very welcome to join![Raise an issue](https://github.com/anncwb/vue-vben-admin/issues/new/choose) Or submit a Pull Request。 + +**Pull Request:** + +1. Fork code! +2. Create your own branch: `git checkout -b feat/xxxx` +3. Submit your changes: `git commit -am 'feat(function): add xxxxx'` +4. Push your branch: `git push origin feat/xxxx` +5. submit`pull request` + +## Git Contribution submission specification + +- reference [vue](https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md) specification ([Angular](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular)) + + - `feat` Add new features + - `fix` Fix the problem/BUG + - `style` The code style is related and does not affect the running result + - `perf` Optimization/performance improvement + - `refactor` Refactor + - `revert` Undo edit + - `test` Test related + - `docs` Documentation/notes + - `chore` Dependency update/scaffolding configuration modification etc. + - `ci` Continuous integration + - `types` Type definition file changes + - `wip` In development + +## Browser support + +The `Chrome 80+` browser is recommended for local development + +Support modern browsers, not IE + +| [ Edge](http://godban.github.io/browsers-support-badges/)
IE | [ Edge](http://godban.github.io/browsers-support-badges/)
Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | +| :-: | :-: | :-: | :-: | :-: | +| not support | last 2 versions | last 2 versions | last 2 versions | last 2 versions | + +## Maintainer + +[@Vben](https://github.com/anncwb) + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=vbenjs/vue-vben-admin&type=Date)](https://star-history.com/#vbenjs/vue-vben-admin&Date) + +## Donate + +If you think this project is helpful to you, you can help the author buy a cup of coffee to show your support! + +![donate](https://unpkg.com/@vbenjs/static-source@0.1.7/source/sponsor.png) + +Paypal Me + +## Contributor + + + Contributors + + +## Discord + +- [Github Discussions](https://github.com/anncwb/vue-vben-admin/discussions) + +## License + +[MIT © Vben-2020](./LICENSE) diff --git a/apps/vben5/README.zh-CN.md b/apps/vben5/README.zh-CN.md new file mode 100644 index 000000000..e2f05bb98 --- /dev/null +++ b/apps/vben5/README.zh-CN.md @@ -0,0 +1,152 @@ +
VbenAdmin Logo

+ +[![license](https://img.shields.io/github/license/anncwb/vue-vben-admin.svg)](LICENSE) + +

Vue Vben Admin

+
+ +[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=vbenjs_vue-vben-admin&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=vbenjs_vue-vben-admin) ![codeql](https://github.com/vbenjs/vue-vben-admin/actions/workflows/codeql.yml/badge.svg) ![build](https://github.com/vbenjs/vue-vben-admin/actions/workflows/build.yml/badge.svg) ![ci](https://github.com/vbenjs/vue-vben-admin/actions/workflows/ci.yml/badge.svg) ![deploy](https://github.com/vbenjs/vue-vben-admin/actions/workflows/deploy.yml/badge.svg) + +**中文** | [English](./README.md) | [日本語](./README.ja-JP.md) + +## 简介 + +Vue Vben Admin 是 Vue Vben Admin 的升级版本。作为一个免费开源的中后台模板,它采用了最新的 Vue 3、Vite、TypeScript 等主流技术开发,开箱即用,可用于中后台前端开发,也适合学习参考。 + +## 升级提示 + +该版本为最新版本`5.0`, 与其他版本不兼容,如果你是新项目,建议使用最新版本。如果你想查看旧版本,请使用 [v2 分支](https://github.com/vbenjs/vue-vben-admin/tree/v2) + +## 特性 + +- **最新技术栈**:使用 Vue3/vite 等前端前沿技术开发 +- **TypeScript**: 应用程序级 JavaScript 的语言 +- **主题**:提供多套主题色彩,可配置自定义主题 +- **国际化**:内置完善的国际化方案 +- **权限** 内置完善的动态路由权限生成方案 + +## 预览 + +- [Vben Admin](https://vben.pro/) - 完整版中文站点 + +测试账号: vben/123456 + +

+ VbenAdmin Logo + VbenAdmin Logo + VbenAdmin Logo +

+ +### 使用 Gitpod + +在 Gitpod(适用于 GitHub 的免费在线开发环境)中打开项目,并立即开始编码. + +[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/vbenjs/vue-vben-admin) + +## 文档 + +[文档地址](https://doc.vben.pro/) + +## 安装使用 + +- 获取项目代码 + +```bash +git clone https://github.com/vbenjs/vue-vben-admin.git +``` + +- 安装依赖 + +```bash +cd vue-vben-admin + +corepack enable + +pnpm install +``` + +- 运行 + +```bash +pnpm dev +``` + +- 打包 + +```bash +pnpm build +``` + +## 更新日志 + +[CHANGELOG](https://github.com/vbenjs/vue-vben-admin/releases) + +## 如何贡献 + +非常欢迎你的加入![提一个 Issue](https://github.com/anncwb/vue-vben-admin/issues/new/choose) 或者提交一个 Pull Request。 + +**Pull Request:** + +1. Fork 代码! +2. 创建自己的分支: `git checkout -b feature/xxxx` +3. 提交你的修改: `git commit -am 'feat(function): add xxxxx'` +4. 推送您的分支: `git push origin feature/xxxx` +5. 提交`pull request` + +## Git 贡献提交规范 + +- 参考 [vue](https://github.com/vuejs/vue/blob/dev/.github/COMMIT_CONVENTION.md) 规范 ([Angular](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular)) + + - `feat` 增加新功能 + - `fix` 修复问题/BUG + - `style` 代码风格相关无影响运行结果的 + - `perf` 优化/性能提升 + - `refactor` 重构 + - `revert` 撤销修改 + - `test` 测试相关 + - `docs` 文档/注释 + - `chore` 依赖更新/脚手架配置修改等 + - `ci` 持续集成 + - `types` 类型定义文件更改 + - `wip` 开发中 + +## 浏览器支持 + +本地开发推荐使用`Chrome 80+` 浏览器 + +支持现代浏览器, 不支持 IE + +| [ Edge](http://godban.github.io/browsers-support-badges/)
IE | [ Edge](http://godban.github.io/browsers-support-badges/)
Edge | [Firefox](http://godban.github.io/browsers-support-badges/)
Firefox | [Chrome](http://godban.github.io/browsers-support-badges/)
Chrome | [Safari](http://godban.github.io/browsers-support-badges/)
Safari | +| :-: | :-: | :-: | :-: | :-: | +| not support | last 2 versions | last 2 versions | last 2 versions | last 2 versions | + +## 维护者 + +[@Vben](https://github.com/anncwb) + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=vbenjs/vue-vben-admin&type=Date)](https://star-history.com/#vbenjs/vue-vben-admin&Date) + +## 捐赠 + +如果你觉得这个项目对你有帮助,你可以帮作者买一杯咖啡表示支持! + +![donate](https://unpkg.com/@vbenjs/static-source@0.1.7/source/sponsor.png) + +Paypal Me + +## Contributor + + + Contributors + + +## Discord + +- [Github Discussions](https://github.com/anncwb/vue-vben-admin/discussions) + +## License + +[MIT © Vben-2020](./LICENSE) diff --git a/apps/vben5/apps/app-antd/.env b/apps/vben5/apps/app-antd/.env new file mode 100644 index 000000000..c14a467fb --- /dev/null +++ b/apps/vben5/apps/app-antd/.env @@ -0,0 +1,5 @@ +# 应用标题 +VITE_APP_TITLE=Vben Admin Antd + +# 应用命名空间,用于缓存、store等功能的前缀,确保隔离 +VITE_APP_NAMESPACE=vben-web-antd diff --git a/apps/vben5/apps/app-antd/.env.analyze b/apps/vben5/apps/app-antd/.env.analyze new file mode 100644 index 000000000..ffafa8dd5 --- /dev/null +++ b/apps/vben5/apps/app-antd/.env.analyze @@ -0,0 +1,7 @@ +# public path +VITE_BASE=/ + +# Basic interface address SPA +VITE_GLOB_API_URL=/api + +VITE_VISUALIZER=true diff --git a/apps/vben5/apps/app-antd/.env.development b/apps/vben5/apps/app-antd/.env.development new file mode 100644 index 000000000..0692ed288 --- /dev/null +++ b/apps/vben5/apps/app-antd/.env.development @@ -0,0 +1,19 @@ +# 端口号 +VITE_PORT=5666 + +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=/ + +# 是否开启 Nitro Mock服务,true 为开启,false 为关闭 +VITE_NITRO_MOCK=true + +# 是否打开 devtools,true 为打开,false 为关闭 +VITE_DEVTOOLS=false + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true + +VITE_GLOB_CLIENT_ID=vue-admin-client +VITE_GLOB_CLIENT_SECRET=1q2w3e* diff --git a/apps/vben5/apps/app-antd/.env.production b/apps/vben5/apps/app-antd/.env.production new file mode 100644 index 000000000..5375847a6 --- /dev/null +++ b/apps/vben5/apps/app-antd/.env.production @@ -0,0 +1,19 @@ +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=https://mock-napi.vben.pro/api + +# 是否开启压缩,可以设置为 none, brotli, gzip +VITE_COMPRESS=none + +# 是否开启 PWA +VITE_PWA=false + +# vue-router 的模式 +VITE_ROUTER_HISTORY=hash + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true + +# 打包后是否生成dist.zip +VITE_ARCHIVER=true diff --git a/apps/vben5/apps/app-antd/index.html b/apps/vben5/apps/app-antd/index.html new file mode 100644 index 000000000..480eb84de --- /dev/null +++ b/apps/vben5/apps/app-antd/index.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + <%= VITE_APP_TITLE %> + + + + +
+ + + diff --git a/apps/vben5/apps/app-antd/package.json b/apps/vben5/apps/app-antd/package.json new file mode 100644 index 000000000..a4bc65408 --- /dev/null +++ b/apps/vben5/apps/app-antd/package.json @@ -0,0 +1,54 @@ +{ + "name": "@vben/app-antd", + "version": "5.4.8", + "homepage": "https://vben.pro", + "bugs": "https://github.com/vbenjs/vue-vben-admin/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/vbenjs/vue-vben-admin.git", + "directory": "apps/app-antd" + }, + "license": "MIT", + "author": { + "name": "vben", + "email": "ann.vben@gmail.com", + "url": "https://github.com/anncwb" + }, + "type": "module", + "scripts": { + "build": "pnpm vite build --mode production", + "build:analyze": "pnpm vite build --mode analyze", + "dev": "pnpm vite --mode development", + "preview": "vite preview", + "typecheck": "vue-tsc --noEmit --skipLibCheck" + }, + "imports": { + "#/*": "./src/*" + }, + "dependencies": { + "@abp/account": "workspace:*", + "@abp/core": "workspace:*", + "@abp/identity": "workspace:*", + "@abp/request": "workspace:*", + "@vben/access": "workspace:*", + "@vben/common-ui": "workspace:*", + "@vben/constants": "workspace:*", + "@vben/hooks": "workspace:*", + "@vben/icons": "workspace:*", + "@vben/layouts": "workspace:*", + "@vben/locales": "workspace:*", + "@vben/plugins": "workspace:*", + "@vben/preferences": "workspace:*", + "@vben/request": "workspace:*", + "@vben/stores": "workspace:*", + "@vben/styles": "workspace:*", + "@vben/types": "workspace:*", + "@vben/utils": "workspace:*", + "@vueuse/core": "catalog:", + "ant-design-vue": "catalog:", + "dayjs": "catalog:", + "pinia": "catalog:", + "vue": "catalog:", + "vue-router": "catalog:" + } +} diff --git a/apps/vben5/apps/app-antd/postcss.config.mjs b/apps/vben5/apps/app-antd/postcss.config.mjs new file mode 100644 index 000000000..3d8070455 --- /dev/null +++ b/apps/vben5/apps/app-antd/postcss.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config/postcss'; diff --git a/apps/vben5/apps/app-antd/public/favicon.ico b/apps/vben5/apps/app-antd/public/favicon.ico new file mode 100644 index 000000000..fcf9818e2 Binary files /dev/null and b/apps/vben5/apps/app-antd/public/favicon.ico differ diff --git a/apps/vben5/apps/app-antd/src/adapter/component/index.ts b/apps/vben5/apps/app-antd/src/adapter/component/index.ts new file mode 100644 index 000000000..1afa62174 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/adapter/component/index.ts @@ -0,0 +1,127 @@ +/** + * 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用 + * 可用于 vben-form、vben-modal、vben-drawer 等组件使用, + */ + +import type { BaseFormComponentType } from '@vben/common-ui'; + +import type { Component, SetupContext } from 'vue'; +import { h } from 'vue'; + +import { globalShareState } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { + AutoComplete, + Button, + Checkbox, + CheckboxGroup, + DatePicker, + Divider, + Input, + InputNumber, + InputPassword, + Mentions, + notification, + Radio, + RadioGroup, + RangePicker, + Rate, + Select, + Space, + Switch, + Textarea, + TimePicker, + TreeSelect, + Upload, +} from 'ant-design-vue'; + +const withDefaultPlaceholder = ( + component: T, + type: 'input' | 'select', +) => { + return (props: any, { attrs, slots }: Omit) => { + const placeholder = props?.placeholder || $t(`ui.placeholder.${type}`); + return h(component, { ...props, ...attrs, placeholder }, slots); + }; +}; + +// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明 +export type ComponentType = + | 'AutoComplete' + | 'Checkbox' + | 'CheckboxGroup' + | 'DatePicker' + | 'DefaultButton' + | 'Divider' + | 'Input' + | 'InputNumber' + | 'InputPassword' + | 'Mentions' + | 'PrimaryButton' + | 'Radio' + | 'RadioGroup' + | 'RangePicker' + | 'Rate' + | 'Select' + | 'Space' + | 'Switch' + | 'Textarea' + | 'TimePicker' + | 'TreeSelect' + | 'Upload' + | BaseFormComponentType; + +async function initComponentAdapter() { + const components: Partial> = { + // 如果你的组件体积比较大,可以使用异步加载 + // Button: () => + // import('xxx').then((res) => res.Button), + + AutoComplete, + Checkbox, + CheckboxGroup, + DatePicker, + // 自定义默认按钮 + DefaultButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'default' }, slots); + }, + Divider, + Input: withDefaultPlaceholder(Input, 'input'), + InputNumber: withDefaultPlaceholder(InputNumber, 'input'), + InputPassword: withDefaultPlaceholder(InputPassword, 'input'), + Mentions: withDefaultPlaceholder(Mentions, 'input'), + // 自定义主要按钮 + PrimaryButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'primary' }, slots); + }, + Radio, + RadioGroup, + RangePicker, + Rate, + Select: withDefaultPlaceholder(Select, 'select'), + Space, + Switch, + Textarea: withDefaultPlaceholder(Textarea, 'input'), + TimePicker, + TreeSelect: withDefaultPlaceholder(TreeSelect, 'select'), + Upload, + }; + + // 将组件注册到全局共享状态中 + globalShareState.setComponents(components); + + // 定义全局共享状态中的消息提示 + globalShareState.defineMessage({ + // 复制成功消息提示 + copyPreferencesSuccess: (title, content) => { + notification.success({ + description: content, + message: title, + placement: 'bottomRight', + }); + }, + }); +} + +export { initComponentAdapter }; diff --git a/apps/vben5/apps/app-antd/src/adapter/form.ts b/apps/vben5/apps/app-antd/src/adapter/form.ts new file mode 100644 index 000000000..65ff793b6 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/adapter/form.ts @@ -0,0 +1,47 @@ +import type { + VbenFormSchema as FormSchema, + VbenFormProps, +} from '@vben/common-ui'; + +import type { ComponentType } from './component'; + +import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +setupVbenForm({ + config: { + // ant design vue组件库默认都是 v-model:value + baseModelPropName: 'value', + + // 一些组件是 v-model:checked 或者 v-model:fileList + modelPropNameMap: { + Checkbox: 'checked', + Radio: 'checked', + Switch: 'checked', + Upload: 'fileList', + }, + }, + defineRules: { + // 输入项目必填国际化适配 + required: (value, _params, ctx) => { + if (value === undefined || value === null || value.length === 0) { + return $t('ui.formRules.required', [ctx.label]); + } + return true; + }, + // 选择项目必填国际化适配 + selectRequired: (value, _params, ctx) => { + if (value === undefined || value === null) { + return $t('ui.formRules.selectRequired', [ctx.label]); + } + return true; + }, + }, +}); + +const useVbenForm = useForm; + +export { useVbenForm, z }; + +export type VbenFormSchema = FormSchema; +export type { VbenFormProps }; diff --git a/apps/vben5/apps/app-antd/src/adapter/request/index.ts b/apps/vben5/apps/app-antd/src/adapter/request/index.ts new file mode 100644 index 000000000..06284043b --- /dev/null +++ b/apps/vben5/apps/app-antd/src/adapter/request/index.ts @@ -0,0 +1,100 @@ +import { preferences } from '@vben/preferences'; +import { + authenticateResponseInterceptor, + errorMessageResponseInterceptor, +} from '@vben/request'; +import { useAccessStore } from '@vben/stores'; + +import { requestClient } from '@abp/request'; +import { message } from 'ant-design-vue'; + +import { useAuthStore } from '#/store'; + +export function initRequestClient() { + /** + * 重新认证逻辑 + */ + async function doReAuthenticate() { + console.warn('Access token or refresh token is invalid or expired. '); + const accessStore = useAccessStore(); + const authStore = useAuthStore(); + accessStore.setAccessToken(null); + if ( + preferences.app.loginExpiredMode === 'modal' && + accessStore.isAccessChecked + ) { + accessStore.setLoginExpired(true); + } else { + await authStore.logout(); + } + } + + /** + * 刷新token逻辑 + */ + async function doRefreshToken() { + return ''; + } + + function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; + } + // 请求头处理 + requestClient.addRequestInterceptor({ + fulfilled: async (config) => { + const accessStore = useAccessStore(); + if (accessStore.accessToken) { + config.headers.Authorization = `${accessStore.accessToken}`; + } + config.headers['Accept-Language'] = preferences.app.locale; + return config; + }, + }); + + // response数据解构 + requestClient.addResponseInterceptor({ + fulfilled: (response) => { + const { data, status, headers } = response; + + if (headers._abpwrapresult === 'true') { + const { code, result, message, details } = data; + const hasSuccess = data && Reflect.has(data, 'code') && code === '0'; + if (hasSuccess) { + return result; + } + const content = details || message; + + throw Object.assign({}, response, { response, message: content }); + } + + if (status >= 200 && status < 400) { + return data; + } + + throw Object.assign({}, response, { response }); + }, + }); + + // token过期的处理 + requestClient.addResponseInterceptor( + authenticateResponseInterceptor({ + client: requestClient, + doReAuthenticate, + doRefreshToken, + enableRefreshToken: preferences.app.enableRefreshToken, + formatToken, + }), + ); + + // 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里 + requestClient.addResponseInterceptor( + errorMessageResponseInterceptor((msg: string, error) => { + // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg + // 当前mock接口返回的错误字段是 error 或者 message + const responseData = error?.response?.data ?? {}; + const errorMessage = responseData?.error ?? responseData?.message ?? ''; + // 如果没有错误信息,则会根据状态码进行提示 + message.error(errorMessage || msg); + }), + ); +} diff --git a/apps/vben5/apps/app-antd/src/adapter/vxe-table.ts b/apps/vben5/apps/app-antd/src/adapter/vxe-table.ts new file mode 100644 index 000000000..d296b2050 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/adapter/vxe-table.ts @@ -0,0 +1,67 @@ +import { h } from 'vue'; + +import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table'; + +import { Button, Image } from 'ant-design-vue'; + +import { useVbenForm } from './form'; + +setupVbenVxeTable({ + configVxeTable: (vxeUI) => { + vxeUI.setConfig({ + grid: { + align: 'center', + border: false, + columnConfig: { + resizable: true, + }, + minHeight: 180, + formConfig: { + // 全局禁用vxe-table的表单配置,使用formOptions + enabled: false, + }, + proxyConfig: { + autoLoad: true, + response: { + result: 'items', + total: 'total', + list: 'items', + }, + showActiveMsg: true, + showResponseMsg: false, + }, + round: true, + showOverflow: true, + size: 'small', + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellImage' }, + vxeUI.renderer.add('CellImage', { + renderTableDefault(_renderOpts, params) { + const { column, row } = params; + return h(Image, { src: row[column.field] }); + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellLink' }, + vxeUI.renderer.add('CellLink', { + renderTableDefault(renderOpts) { + const { props } = renderOpts; + return h( + Button, + { size: 'small', type: 'link' }, + { default: () => props?.text }, + ); + }, + }); + + // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化 + // vxeUI.formats.add + }, + useVbenForm, +}); + +export { useVbenVxeGrid }; + +export type * from '@vben/plugins/vxe-table'; diff --git a/apps/vben5/apps/app-antd/src/api/core/abp.ts b/apps/vben5/apps/app-antd/src/api/core/abp.ts new file mode 100644 index 000000000..e5fba68f5 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/api/core/abp.ts @@ -0,0 +1,36 @@ +import type { + ApplicationConfigurationDto, + ApplicationLocalizationDto, +} from '@abp/core'; + +import { requestClient } from '@abp/request'; + +/** + * 获取应用程序配置信息 + */ +export function getConfigApi(options?: { + includeLocalizationResources?: boolean; +}): Promise { + return requestClient.get( + '/api/abp/application-configuration', + { + params: options, + }, + ); +} + +/** + * 获取应用程序语言 + * @returns 本地化配置 + */ +export function getLocalizationApi(options: { + cultureName: string; + onlyDynamics?: boolean; +}): Promise { + return requestClient.get( + '/api/abp/application-localization', + { + params: options, + }, + ); +} diff --git a/apps/vben5/apps/app-antd/src/api/core/index.ts b/apps/vben5/apps/app-antd/src/api/core/index.ts new file mode 100644 index 000000000..5fe53ee1e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/api/core/index.ts @@ -0,0 +1,2 @@ +export * from './abp'; +export * from './menu'; diff --git a/apps/vben5/apps/app-antd/src/api/core/menu.ts b/apps/vben5/apps/app-antd/src/api/core/menu.ts new file mode 100644 index 000000000..9ef60b11c --- /dev/null +++ b/apps/vben5/apps/app-antd/src/api/core/menu.ts @@ -0,0 +1,10 @@ +import type { RouteRecordStringComponent } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户所有菜单 + */ +export async function getAllMenusApi() { + return requestClient.get('/menu/all'); +} diff --git a/apps/vben5/apps/app-antd/src/api/index.ts b/apps/vben5/apps/app-antd/src/api/index.ts new file mode 100644 index 000000000..4b0e04137 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/api/index.ts @@ -0,0 +1 @@ +export * from './core'; diff --git a/apps/vben5/apps/app-antd/src/api/request.ts b/apps/vben5/apps/app-antd/src/api/request.ts new file mode 100644 index 000000000..c607daf6e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/api/request.ts @@ -0,0 +1,114 @@ +/** + * 该文件可自行根据业务逻辑进行调整 + */ +import type { HttpResponse } from '@vben/request'; + +import { useAppConfig } from '@vben/hooks'; +import { preferences } from '@vben/preferences'; +import { + authenticateResponseInterceptor, + errorMessageResponseInterceptor, + RequestClient, +} from '@vben/request'; +import { useAccessStore } from '@vben/stores'; + +import { message } from 'ant-design-vue'; + +import { useAuthStore } from '#/store'; + +// import { refreshTokenApi } from './core'; + +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); + +function createRequestClient(baseURL: string) { + const client = new RequestClient({ + baseURL, + }); + + /** + * 重新认证逻辑 + */ + async function doReAuthenticate() { + console.warn('Access token or refresh token is invalid or expired. '); + const accessStore = useAccessStore(); + const authStore = useAuthStore(); + accessStore.setAccessToken(null); + if ( + preferences.app.loginExpiredMode === 'modal' && + accessStore.isAccessChecked + ) { + accessStore.setLoginExpired(true); + } else { + await authStore.logout(); + } + } + + /** + * 刷新token逻辑 + */ + async function doRefreshToken() { + const accessStore = useAccessStore(); + // const resp = await refreshTokenApi(); + // const newToken = resp.data; + // accessStore.setAccessToken(newToken); + return String(accessStore.accessToken); + } + + function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; + } + + // 请求头处理 + client.addRequestInterceptor({ + fulfilled: async (config) => { + const accessStore = useAccessStore(); + + config.headers.Authorization = formatToken(accessStore.accessToken); + config.headers['Accept-Language'] = preferences.app.locale; + return config; + }, + }); + + // response数据解构 + client.addResponseInterceptor({ + fulfilled: (response) => { + const { data: responseData, status } = response; + + const { code, data } = responseData; + if (status >= 200 && status < 400 && code === 0) { + return data; + } + + throw Object.assign({}, response, { response }); + }, + }); + + // token过期的处理 + client.addResponseInterceptor( + authenticateResponseInterceptor({ + client, + doReAuthenticate, + doRefreshToken, + enableRefreshToken: preferences.app.enableRefreshToken, + formatToken, + }), + ); + + // 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里 + client.addResponseInterceptor( + errorMessageResponseInterceptor((msg: string, error) => { + // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg + // 当前mock接口返回的错误字段是 error 或者 message + const responseData = error?.response?.data ?? {}; + const errorMessage = responseData?.error ?? responseData?.message ?? ''; + // 如果没有错误信息,则会根据状态码进行提示 + message.error(errorMessage || msg); + }), + ); + + return client; +} + +export const requestClient = createRequestClient(apiURL); + +export const baseRequestClient = new RequestClient({ baseURL: apiURL }); diff --git a/apps/vben5/apps/app-antd/src/app.vue b/apps/vben5/apps/app-antd/src/app.vue new file mode 100644 index 000000000..bbaccce13 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/app.vue @@ -0,0 +1,39 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/bootstrap.ts b/apps/vben5/apps/app-antd/src/bootstrap.ts new file mode 100644 index 000000000..a0af6fcfe --- /dev/null +++ b/apps/vben5/apps/app-antd/src/bootstrap.ts @@ -0,0 +1,50 @@ +import { createApp, watchEffect } from 'vue'; + +import { registerAccessDirective } from '@vben/access'; +import { preferences } from '@vben/preferences'; +import { initStores } from '@vben/stores'; +import '@vben/styles'; +import '@vben/styles/antd'; + +import { useTitle } from '@vueuse/core'; + +import { $t, setupI18n } from '#/locales'; + +import { initComponentAdapter } from './adapter/component'; +import { initRequestClient } from './adapter/request'; +import App from './app.vue'; +import { router } from './router'; + +async function bootstrap(namespace: string) { + // 初始化组件适配器 + await initComponentAdapter(); + initRequestClient(); + + const app = createApp(App); + + // 配置 pinia-tore + await initStores(app, { namespace }); + + // 国际化 i18n 配置 + await setupI18n(app); + + // 安装权限指令 + registerAccessDirective(app); + + // 配置路由及路由守卫 + app.use(router); + + // 动态更新标题 + watchEffect(() => { + if (preferences.app.dynamicTitle) { + const routeTitle = router.currentRoute.value.meta?.title; + const pageTitle = + (routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name; + useTitle(pageTitle); + } + }); + + app.mount('#app'); +} + +export { bootstrap }; diff --git a/apps/vben5/apps/app-antd/src/layouts/auth.vue b/apps/vben5/apps/app-antd/src/layouts/auth.vue new file mode 100644 index 000000000..18d415bc7 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/layouts/auth.vue @@ -0,0 +1,23 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/layouts/basic.vue b/apps/vben5/apps/app-antd/src/layouts/basic.vue new file mode 100644 index 000000000..51412956a --- /dev/null +++ b/apps/vben5/apps/app-antd/src/layouts/basic.vue @@ -0,0 +1,157 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/layouts/index.ts b/apps/vben5/apps/app-antd/src/layouts/index.ts new file mode 100644 index 000000000..a43207805 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/layouts/index.ts @@ -0,0 +1,6 @@ +const BasicLayout = () => import('./basic.vue'); +const AuthPageLayout = () => import('./auth.vue'); + +const IFrameView = () => import('@vben/layouts').then((m) => m.IFrameView); + +export { AuthPageLayout, BasicLayout, IFrameView }; diff --git a/apps/vben5/apps/app-antd/src/locales/README.md b/apps/vben5/apps/app-antd/src/locales/README.md new file mode 100644 index 000000000..7b451032e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/README.md @@ -0,0 +1,3 @@ +# locale + +每个app使用的国际化可能不同,这里用于扩展国际化的功能,例如扩展 dayjs、antd组件库的多语言切换,以及app本身的国际化文件。 diff --git a/apps/vben5/apps/app-antd/src/locales/index.ts b/apps/vben5/apps/app-antd/src/locales/index.ts new file mode 100644 index 000000000..c71aba29e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/index.ts @@ -0,0 +1,127 @@ +import type { LocaleSetupOptions, SupportedLanguagesType } from '@vben/locales'; +import type { Locale } from 'ant-design-vue/es/locale'; + +import type { App } from 'vue'; +import { ref } from 'vue'; + +import { + $t, + setupI18n as coreSetup, + loadLocalesMapFromDir, +} from '@vben/locales'; +import { preferences } from '@vben/preferences'; + +import { useAbpStore } from '@abp/core'; +import antdEnLocale from 'ant-design-vue/es/locale/en_US'; +import antdDefaultLocale from 'ant-design-vue/es/locale/zh_CN'; +import dayjs from 'dayjs'; + +import { getLocalizationApi } from '#/api/core'; + +const antdLocale = ref(antdDefaultLocale); + +const modules = import.meta.glob('./langs/**/*.json'); + +const localesMap = loadLocalesMapFromDir( + /\.\/langs\/([^/]+)\/(.*)\.json$/, + modules, +); +/** + * 加载应用特有的语言包 + * 这里也可以改造为从服务端获取翻译数据 + * @param lang + */ +async function loadMessages(lang: SupportedLanguagesType) { + const [appLocaleMessages, _, abpLocales] = await Promise.all([ + localesMap[lang]?.(), + loadThirdPartyMessage(lang), + loadAbpLocale(lang), + ]); + return { + ...appLocaleMessages?.default, + ...abpLocales, + }; +} + +/** + * 加载第三方组件库的语言包 + * @param lang + */ +async function loadThirdPartyMessage(lang: SupportedLanguagesType) { + await Promise.all([loadAntdLocale(lang), loadDayjsLocale(lang)]); +} + +/** + * 加载dayjs的语言包 + * @param lang + */ +async function loadDayjsLocale(lang: SupportedLanguagesType) { + let locale; + switch (lang) { + case 'en-US': { + locale = await import('dayjs/locale/en'); + break; + } + case 'zh-CN': { + locale = await import('dayjs/locale/zh-cn'); + break; + } + // 默认使用英语 + default: { + locale = await import('dayjs/locale/en'); + } + } + if (locale) { + dayjs.locale(locale); + } else { + console.error(`Failed to load dayjs locale for ${lang}`); + } +} + +/** + * 加载antd的语言包 + * @param lang + */ +async function loadAntdLocale(lang: SupportedLanguagesType) { + switch (lang) { + case 'en-US': { + antdLocale.value = antdEnLocale; + break; + } + case 'zh-CN': { + antdLocale.value = antdDefaultLocale; + break; + } + } +} + +/** + * 加载abp的语言包 + * @param lang + */ +async function loadAbpLocale(lang: SupportedLanguagesType) { + const abpStore = useAbpStore(); + let localization = abpStore.localization; + + if (lang !== localization?.currentCulture.cultureName) { + localization = await getLocalizationApi({ + cultureName: lang, + onlyDynamics: false, + }); + } + abpStore.setLocalization(localization); + const locales = abpStore.getI18nLocales(); + return locales; +} + +async function setupI18n(app: App, options: LocaleSetupOptions = {}) { + await coreSetup(app, { + defaultLocale: preferences.app.locale, + loadMessages, + // missingWarn: !import.meta.env.PROD, + missingWarn: false, + ...options, + }); +} + +export { $t, antdLocale, setupI18n }; diff --git a/apps/vben5/apps/app-antd/src/locales/langs/en-US/abp.json b/apps/vben5/apps/app-antd/src/locales/langs/en-US/abp.json new file mode 100644 index 000000000..a7a462088 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/langs/en-US/abp.json @@ -0,0 +1,13 @@ +{ + "title": "Abp Framework", + "manage": { + "title": "Manage", + "identity": { + "title": "Identity", + "user": "User", + "role": "Role", + "claimTypes": "Claim Types", + "securityLogs": "Security Logs" + } + } +} diff --git a/apps/vben5/apps/app-antd/src/locales/langs/en-US/demos.json b/apps/vben5/apps/app-antd/src/locales/langs/en-US/demos.json new file mode 100644 index 000000000..071564349 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/langs/en-US/demos.json @@ -0,0 +1,12 @@ +{ + "title": "Demos", + "antd": "Ant Design Vue", + "vben": { + "title": "Project", + "about": "About", + "document": "Document", + "antdv": "Ant Design Vue Version", + "naive-ui": "Naive UI Version", + "element-plus": "Element Plus Version" + } +} diff --git a/apps/vben5/apps/app-antd/src/locales/langs/en-US/page.json b/apps/vben5/apps/app-antd/src/locales/langs/en-US/page.json new file mode 100644 index 000000000..618a258c0 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/langs/en-US/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "Login", + "register": "Register", + "codeLogin": "Code Login", + "qrcodeLogin": "Qr Code Login", + "forgetPassword": "Forget Password" + }, + "dashboard": { + "title": "Dashboard", + "analytics": "Analytics", + "workspace": "Workspace" + } +} diff --git a/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/abp.json b/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/abp.json new file mode 100644 index 000000000..ef6be38c5 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/abp.json @@ -0,0 +1,13 @@ +{ + "title": "Abp框架", + "manage": { + "title": "管理", + "identity": { + "title": "身份认证管理", + "user": "用户", + "role": "角色", + "claimTypes": "身份标识", + "securityLogs": "安全日志" + } + } +} diff --git a/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/demos.json b/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/demos.json new file mode 100644 index 000000000..93ee722f5 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/demos.json @@ -0,0 +1,12 @@ +{ + "title": "演示", + "antd": "Ant Design Vue", + "vben": { + "title": "项目", + "about": "关于", + "document": "文档", + "antdv": "Ant Design Vue 版本", + "naive-ui": "Naive UI 版本", + "element-plus": "Element Plus 版本" + } +} diff --git a/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/page.json b/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/page.json new file mode 100644 index 000000000..4cb67081c --- /dev/null +++ b/apps/vben5/apps/app-antd/src/locales/langs/zh-CN/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "登录", + "register": "注册", + "codeLogin": "验证码登录", + "qrcodeLogin": "二维码登录", + "forgetPassword": "忘记密码" + }, + "dashboard": { + "title": "概览", + "analytics": "分析页", + "workspace": "工作台" + } +} diff --git a/apps/vben5/apps/app-antd/src/main.ts b/apps/vben5/apps/app-antd/src/main.ts new file mode 100644 index 000000000..5d728a02a --- /dev/null +++ b/apps/vben5/apps/app-antd/src/main.ts @@ -0,0 +1,31 @@ +import { initPreferences } from '@vben/preferences'; +import { unmountGlobalLoading } from '@vben/utils'; + +import { overridesPreferences } from './preferences'; + +/** + * 应用初始化完成之后再进行页面加载渲染 + */ +async function initApplication() { + // name用于指定项目唯一标识 + // 用于区分不同项目的偏好设置以及存储数据的key前缀以及其他一些需要隔离的数据 + const env = import.meta.env.PROD ? 'prod' : 'dev'; + const appVersion = import.meta.env.VITE_APP_VERSION; + const namespace = `${import.meta.env.VITE_APP_NAMESPACE}-${appVersion}-${env}`; + + // app偏好设置初始化 + await initPreferences({ + namespace, + overrides: overridesPreferences, + }); + + // 启动应用并挂载 + // vue应用主要逻辑及视图 + const { bootstrap } = await import('./bootstrap'); + await bootstrap(namespace); + + // 移除并销毁loading + unmountGlobalLoading(); +} + +initApplication(); diff --git a/apps/vben5/apps/app-antd/src/preferences.ts b/apps/vben5/apps/app-antd/src/preferences.ts new file mode 100644 index 000000000..b2e9ace43 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/preferences.ts @@ -0,0 +1,13 @@ +import { defineOverridesPreferences } from '@vben/preferences'; + +/** + * @description 项目配置文件 + * 只需要覆盖项目中的一部分配置,不需要的配置不用覆盖,会自动使用默认配置 + * !!! 更改配置后请清空缓存,否则可能不生效 + */ +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + name: import.meta.env.VITE_APP_TITLE, + }, +}); diff --git a/apps/vben5/apps/app-antd/src/router/access.ts b/apps/vben5/apps/app-antd/src/router/access.ts new file mode 100644 index 000000000..3a48be237 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/access.ts @@ -0,0 +1,42 @@ +import type { + ComponentRecordType, + GenerateMenuAndRoutesOptions, +} from '@vben/types'; + +import { generateAccessible } from '@vben/access'; +import { preferences } from '@vben/preferences'; + +import { message } from 'ant-design-vue'; + +import { getAllMenusApi } from '#/api'; +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue'); + +async function generateAccess(options: GenerateMenuAndRoutesOptions) { + const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue'); + + const layoutMap: ComponentRecordType = { + BasicLayout, + IFrameView, + }; + + return await generateAccessible(preferences.app.accessMode, { + ...options, + fetchMenuListAsync: async () => { + message.loading({ + content: `${$t('common.loadingMenu')}...`, + duration: 1.5, + }); + return await getAllMenusApi(); + }, + // 可以指定没有权限跳转403页面 + forbiddenComponent, + // 如果 route.meta.menuVisibleWithForbidden = true + layoutMap, + pageMap, + }); +} + +export { generateAccess }; diff --git a/apps/vben5/apps/app-antd/src/router/guard.ts b/apps/vben5/apps/app-antd/src/router/guard.ts new file mode 100644 index 000000000..fce5a892c --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/guard.ts @@ -0,0 +1,125 @@ +import type { Router } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { preferences } from '@vben/preferences'; +import { useAccessStore, useUserStore } from '@vben/stores'; +import { startProgress, stopProgress } from '@vben/utils'; + +import { accessRoutes, coreRouteNames } from '#/router/routes'; +import { useAuthStore } from '#/store'; + +import { generateAccess } from './access'; + +/** + * 通用守卫配置 + * @param router + */ +function setupCommonGuard(router: Router) { + // 记录已经加载的页面 + const loadedPaths = new Set(); + + router.beforeEach(async (to) => { + to.meta.loaded = loadedPaths.has(to.path); + + // 页面加载进度条 + if (!to.meta.loaded && preferences.transition.progress) { + startProgress(); + } + return true; + }); + + router.afterEach((to) => { + // 记录页面是否加载,如果已经加载,后续的页面切换动画等效果不在重复执行 + + loadedPaths.add(to.path); + + // 关闭页面加载进度条 + if (preferences.transition.progress) { + stopProgress(); + } + }); +} + +/** + * 权限访问守卫配置 + * @param router + */ +function setupAccessGuard(router: Router) { + router.beforeEach(async (to, from) => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const authStore = useAuthStore(); + + // 基本路由,这些路由不需要进入权限拦截 + if (coreRouteNames.includes(to.name as string)) { + if (to.path === LOGIN_PATH && accessStore.accessToken) { + return decodeURIComponent( + (to.query?.redirect as string) || DEFAULT_HOME_PATH, + ); + } + return true; + } + + // accessToken 检查 + if (!accessStore.accessToken) { + // 明确声明忽略权限访问权限,则可以访问 + if (to.meta.ignoreAccess) { + return true; + } + + // 没有访问权限,跳转登录页面 + if (to.fullPath !== LOGIN_PATH) { + return { + path: LOGIN_PATH, + // 如不需要,直接删除 query + query: { redirect: encodeURIComponent(to.fullPath) }, + // 携带当前跳转的页面,登录后重新跳转该页面 + replace: true, + }; + } + return to; + } + + // 是否已经生成过动态路由 + if (accessStore.isAccessChecked) { + return true; + } + + // 生成路由表 + // 当前登录用户拥有的角色标识列表 + const userInfo = userStore.userInfo || (await authStore.fetchUserInfo()); + const userRoles = userInfo.roles ?? []; + + // 生成菜单和路由 + const { accessibleMenus, accessibleRoutes } = await generateAccess({ + roles: userRoles, + router, + // 则会在菜单中显示,但是访问会被重定向到403 + routes: accessRoutes, + }); + + // 保存菜单信息和路由信息 + accessStore.setAccessMenus(accessibleMenus); + accessStore.setAccessRoutes(accessibleRoutes); + accessStore.setIsAccessChecked(true); + const redirectPath = (from.query.redirect ?? to.fullPath) as string; + + return { + ...router.resolve(decodeURIComponent(redirectPath)), + replace: true, + }; + }); +} + +/** + * 项目守卫配置 + * @param router + */ +function createRouterGuard(router: Router) { + /** 通用 */ + setupCommonGuard(router); + /** 权限访问 */ + setupAccessGuard(router); +} + +export { createRouterGuard }; diff --git a/apps/vben5/apps/app-antd/src/router/index.ts b/apps/vben5/apps/app-antd/src/router/index.ts new file mode 100644 index 000000000..484023034 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/index.ts @@ -0,0 +1,37 @@ +import { + createRouter, + createWebHashHistory, + createWebHistory, +} from 'vue-router'; + +import { resetStaticRoutes } from '@vben/utils'; + +import { createRouterGuard } from './guard'; +import { routes } from './routes'; + +/** + * @zh_CN 创建vue-router实例 + */ +const router = createRouter({ + history: + import.meta.env.VITE_ROUTER_HISTORY === 'hash' + ? createWebHashHistory(import.meta.env.VITE_BASE) + : createWebHistory(import.meta.env.VITE_BASE), + // 应该添加到路由的初始路由列表。 + routes, + scrollBehavior: (to, _from, savedPosition) => { + if (savedPosition) { + return savedPosition; + } + return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 }; + }, + // 是否应该禁止尾部斜杠。 + // strict: true, +}); + +const resetRoutes = () => resetStaticRoutes(router, routes); + +// 创建路由守卫 +createRouterGuard(router); + +export { resetRoutes, router }; diff --git a/apps/vben5/apps/app-antd/src/router/routes/core.ts b/apps/vben5/apps/app-antd/src/router/routes/core.ts new file mode 100644 index 000000000..fe030a9a2 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/routes/core.ts @@ -0,0 +1,88 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; + +import { AuthPageLayout } from '#/layouts'; +import { $t } from '#/locales'; +import Login from '#/views/_core/authentication/login.vue'; + +/** 全局404页面 */ +const fallbackNotFoundRoute: RouteRecordRaw = { + component: () => import('#/views/_core/fallback/not-found.vue'), + meta: { + hideInBreadcrumb: true, + hideInMenu: true, + hideInTab: true, + title: '404', + }, + name: 'FallbackNotFound', + path: '/:path(.*)*', +}; + +/** 基本路由,这些路由是必须存在的 */ +const coreRoutes: RouteRecordRaw[] = [ + { + meta: { + title: 'Root', + }, + name: 'Root', + path: '/', + redirect: DEFAULT_HOME_PATH, + }, + { + component: AuthPageLayout, + meta: { + hideInTab: true, + title: 'Authentication', + }, + name: 'Authentication', + path: '/auth', + redirect: LOGIN_PATH, + children: [ + { + name: 'Login', + path: 'login', + component: Login, + meta: { + title: $t('page.auth.login'), + }, + }, + { + name: 'CodeLogin', + path: 'code-login', + component: () => import('#/views/_core/authentication/code-login.vue'), + meta: { + title: $t('page.auth.codeLogin'), + }, + }, + { + name: 'QrCodeLogin', + path: 'qrcode-login', + component: () => + import('#/views/_core/authentication/qrcode-login.vue'), + meta: { + title: $t('page.auth.qrcodeLogin'), + }, + }, + { + name: 'ForgetPassword', + path: 'forget-password', + component: () => + import('#/views/_core/authentication/forget-password.vue'), + meta: { + title: $t('page.auth.forgetPassword'), + }, + }, + { + name: 'Register', + path: 'register', + component: () => import('#/views/_core/authentication/register.vue'), + meta: { + title: $t('page.auth.register'), + }, + }, + ], + }, +]; + +export { coreRoutes, fallbackNotFoundRoute }; diff --git a/apps/vben5/apps/app-antd/src/router/routes/index.ts b/apps/vben5/apps/app-antd/src/router/routes/index.ts new file mode 100644 index 000000000..e6fb14402 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/routes/index.ts @@ -0,0 +1,37 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { mergeRouteModules, traverseTreeValues } from '@vben/utils'; + +import { coreRoutes, fallbackNotFoundRoute } from './core'; + +const dynamicRouteFiles = import.meta.glob('./modules/**/*.ts', { + eager: true, +}); + +// 有需要可以自行打开注释,并创建文件夹 +// const externalRouteFiles = import.meta.glob('./external/**/*.ts', { eager: true }); +// const staticRouteFiles = import.meta.glob('./static/**/*.ts', { eager: true }); + +/** 动态路由 */ +const dynamicRoutes: RouteRecordRaw[] = mergeRouteModules(dynamicRouteFiles); + +/** 外部路由列表,访问这些页面可以不需要Layout,可能用于内嵌在别的系统(不会显示在菜单中) */ +// const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles); +// const staticRoutes: RouteRecordRaw[] = mergeRouteModules(staticRouteFiles); +const staticRoutes: RouteRecordRaw[] = []; +const externalRoutes: RouteRecordRaw[] = []; + +/** 路由列表,由基本路由、外部路由和404兜底路由组成 + * 无需走权限验证(会一直显示在菜单中) */ +const routes: RouteRecordRaw[] = [ + ...coreRoutes, + ...externalRoutes, + fallbackNotFoundRoute, +]; + +/** 基本路由列表,这些路由不需要进入权限拦截 */ +const coreRouteNames = traverseTreeValues(coreRoutes, (route) => route.name); + +/** 有权限校验的路由列表,包含动态路由和静态路由 */ +const accessRoutes = [...dynamicRoutes, ...staticRoutes]; +export { accessRoutes, coreRouteNames, routes }; diff --git a/apps/vben5/apps/app-antd/src/router/routes/modules/abp.ts b/apps/vben5/apps/app-antd/src/router/routes/modules/abp.ts new file mode 100644 index 000000000..acae5784f --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/routes/modules/abp.ts @@ -0,0 +1,80 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'https://abp.io/assets/favicon.ico/favicon-16x16.png', + keepAlive: true, + order: 1000, + title: $t('abp.title'), + }, + name: 'AbpFramework', + path: '/abp', + children: [ + { + meta: { + title: $t('abp.manage.title'), + icon: 'arcticons:activity-manager', + }, + name: 'Manage', + path: '/manage', + children: [ + { + meta: { + title: $t('abp.manage.identity.title'), + icon: 'teenyicons:id-outline', + }, + name: 'Identity', + path: '/manage/identity', + children: [ + { + component: () => import('#/views/identity/user/index.vue'), + name: 'Users', + path: '/manage/identity/users', + meta: { + title: $t('abp.manage.identity.user'), + icon: 'mdi:user-outline', + }, + }, + { + component: () => import('#/views/identity/role/index.vue'), + name: 'Roles', + path: '/manage/identity/roles', + meta: { + title: $t('abp.manage.identity.role'), + icon: 'carbon:user-role', + }, + }, + { + component: () => + import('#/views/identity/claim-types/index.vue'), + name: 'ClaimTypes', + path: '/manage/identity/claim-types', + meta: { + title: $t('abp.manage.identity.claimTypes'), + icon: 'la:id-card-solid', + }, + }, + { + component: () => + import('#/views/identity/security-logs/index.vue'), + name: 'SecurityLogs', + path: '/manage/identity/security-logs', + meta: { + title: $t('abp.manage.identity.securityLogs'), + icon: 'carbon:security', + }, + }, + ], + }, + ], + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/app-antd/src/router/routes/modules/dashboard.ts b/apps/vben5/apps/app-antd/src/router/routes/modules/dashboard.ts new file mode 100644 index 000000000..1bddab9db --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/routes/modules/dashboard.ts @@ -0,0 +1,40 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'lucide:layout-dashboard', + order: -1, + title: $t('page.dashboard.title'), + }, + name: 'Dashboard', + path: '/', + children: [ + { + name: 'Analytics', + path: '/analytics', + component: () => import('#/views/dashboard/analytics/index.vue'), + meta: { + affixTab: true, + icon: 'lucide:area-chart', + title: $t('page.dashboard.analytics'), + }, + }, + { + name: 'Workspace', + path: '/workspace', + component: () => import('#/views/dashboard/workspace/index.vue'), + meta: { + icon: 'carbon:workspace', + title: $t('page.dashboard.workspace'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/app-antd/src/router/routes/modules/demos.ts b/apps/vben5/apps/app-antd/src/router/routes/modules/demos.ts new file mode 100644 index 000000000..32bb338e0 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/routes/modules/demos.ts @@ -0,0 +1,30 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'ic:baseline-view-in-ar', + keepAlive: true, + order: 1000, + title: $t('demos.title'), + }, + name: 'Demos', + path: '/demos', + children: [ + { + meta: { + title: $t('demos.antd'), + }, + name: 'AntDesignDemos', + path: '/demos/ant-design', + component: () => import('#/views/demos/antd/index.vue'), + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/app-antd/src/router/routes/modules/vben.ts b/apps/vben5/apps/app-antd/src/router/routes/modules/vben.ts new file mode 100644 index 000000000..210e8610f --- /dev/null +++ b/apps/vben5/apps/app-antd/src/router/routes/modules/vben.ts @@ -0,0 +1,81 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { + VBEN_DOC_URL, + VBEN_ELE_PREVIEW_URL, + VBEN_GITHUB_URL, + VBEN_LOGO_URL, + VBEN_NAIVE_PREVIEW_URL, +} from '@vben/constants'; + +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + badgeType: 'dot', + icon: VBEN_LOGO_URL, + order: 9999, + title: $t('demos.vben.title'), + }, + name: 'VbenProject', + path: '/vben-admin', + children: [ + { + name: 'VbenAbout', + path: '/vben-admin/about', + component: () => import('#/views/_core/about/index.vue'), + meta: { + icon: 'lucide:copyright', + title: $t('demos.vben.about'), + }, + }, + { + name: 'VbenDocument', + path: '/vben-admin/document', + component: IFrameView, + meta: { + icon: 'lucide:book-open-text', + link: VBEN_DOC_URL, + title: $t('demos.vben.document'), + }, + }, + { + name: 'VbenGithub', + path: '/vben-admin/github', + component: IFrameView, + meta: { + icon: 'mdi:github', + link: VBEN_GITHUB_URL, + title: 'Github', + }, + }, + { + name: 'VbenNaive', + path: '/vben-admin/naive', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: 'logos:naiveui', + link: VBEN_NAIVE_PREVIEW_URL, + title: $t('demos.vben.naive-ui'), + }, + }, + { + name: 'VbenElementPlus', + path: '/vben-admin/ele', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: 'logos:element', + link: VBEN_ELE_PREVIEW_URL, + title: $t('demos.vben.element-plus'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/app-antd/src/store/auth.ts b/apps/vben5/apps/app-antd/src/store/auth.ts new file mode 100644 index 000000000..c4a8670fa --- /dev/null +++ b/apps/vben5/apps/app-antd/src/store/auth.ts @@ -0,0 +1,126 @@ +import type { Recordable, UserInfo } from '@vben/types'; + +import { ref } from 'vue'; +import { useRouter } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores'; + +import { getUserInfoApi, loginApi } from '@abp/account'; +import { useAbpStore } from '@abp/core'; +import { notification } from 'ant-design-vue'; +import { defineStore } from 'pinia'; + +import { getConfigApi } from '#/api/core/abp'; +import { $t } from '#/locales'; + +export const useAuthStore = defineStore('auth', () => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const abpStore = useAbpStore(); + const router = useRouter(); + + const loginLoading = ref(false); + + /** + * 异步处理登录操作 + * Asynchronously handle the login process + * @param params 登录表单数据 + */ + async function authLogin( + params: Recordable, + onSuccess?: () => Promise | void, + ) { + // 异步处理用户登录操作并获取 accessToken + let userInfo: null | UserInfo = null; + try { + loginLoading.value = true; + const loginResult = await loginApi(params as any); + const { accessToken, tokenType, refreshToken } = loginResult; + // 如果成功获取到 accessToken + if (accessToken) { + accessStore.setAccessToken(`${tokenType} ${accessToken}`); + accessStore.setRefreshToken(refreshToken); + + userInfo = await fetchUserInfo(); + + userStore.setUserInfo(userInfo); + + if (accessStore.loginExpired) { + accessStore.setLoginExpired(false); + } else { + onSuccess + ? await onSuccess?.() + : await router.push(userInfo.homePath || DEFAULT_HOME_PATH); + } + + if (userInfo?.realName) { + notification.success({ + description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`, + duration: 3, + message: $t('authentication.loginSuccess'), + }); + } + } + } finally { + loginLoading.value = false; + } + + return { + userInfo, + }; + } + + async function logout(redirect: boolean = true) { + try { + // await logoutApi(); + } catch { + // 不做任何处理 + } + resetAllStores(); + accessStore.setLoginExpired(false); + + // 回登录页带上当前路由地址 + await router.replace({ + path: LOGIN_PATH, + query: redirect + ? { + redirect: encodeURIComponent(router.currentRoute.value.fullPath), + } + : {}, + }); + } + + async function fetchUserInfo() { + let userInfo: ({ [key: string]: any } & UserInfo) | null = null; + const userInfoRes = await getUserInfoApi(); + const abpConfig = await getConfigApi(); + userInfo = { + userId: userInfoRes.sub, + username: userInfoRes.uniqueName, + realName: userInfoRes.name, + avatar: userInfoRes.avatarUrl ?? userInfoRes.picture, + desc: userInfoRes.uniqueName ?? userInfoRes.name, + email: userInfoRes.email ?? userInfoRes.email, + token: '', + roles: abpConfig.currentUser.roles, + homePath: '/', + }; + userStore.setUserInfo(userInfo); + abpStore.setApplication(abpConfig); + accessStore.setAccessCodes(Object.keys(abpConfig.auth.grantedPolicies)); + return userInfo; + } + + function $reset() { + loginLoading.value = false; + } + + return { + $reset, + authLogin, + fetchUserInfo, + loginLoading, + logout, + }; +}); diff --git a/apps/vben5/apps/app-antd/src/store/index.ts b/apps/vben5/apps/app-antd/src/store/index.ts new file mode 100644 index 000000000..269586ee8 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/store/index.ts @@ -0,0 +1 @@ +export * from './auth'; diff --git a/apps/vben5/apps/app-antd/src/views/_core/README.md b/apps/vben5/apps/app-antd/src/views/_core/README.md new file mode 100644 index 000000000..8248afe6c --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/README.md @@ -0,0 +1,3 @@ +# \_core + +此目录包含应用程序正常运行所需的基本视图。这些视图是应用程序布局中使用的视图。 diff --git a/apps/vben5/apps/app-antd/src/views/_core/about/index.vue b/apps/vben5/apps/app-antd/src/views/_core/about/index.vue new file mode 100644 index 000000000..0ee524335 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/about/index.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/authentication/code-login.vue b/apps/vben5/apps/app-antd/src/views/_core/authentication/code-login.vue new file mode 100644 index 000000000..556b273af --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/authentication/code-login.vue @@ -0,0 +1,65 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/authentication/forget-password.vue b/apps/vben5/apps/app-antd/src/views/_core/authentication/forget-password.vue new file mode 100644 index 000000000..fef0d4279 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/authentication/forget-password.vue @@ -0,0 +1,43 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/authentication/login.vue b/apps/vben5/apps/app-antd/src/views/_core/authentication/login.vue new file mode 100644 index 000000000..7fee812fd --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/authentication/login.vue @@ -0,0 +1,45 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/authentication/qrcode-login.vue b/apps/vben5/apps/app-antd/src/views/_core/authentication/qrcode-login.vue new file mode 100644 index 000000000..23f5f2dad --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/authentication/qrcode-login.vue @@ -0,0 +1,10 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/authentication/register.vue b/apps/vben5/apps/app-antd/src/views/_core/authentication/register.vue new file mode 100644 index 000000000..b1a5de726 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/authentication/register.vue @@ -0,0 +1,96 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/fallback/coming-soon.vue b/apps/vben5/apps/app-antd/src/views/_core/fallback/coming-soon.vue new file mode 100644 index 000000000..f394930f2 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/fallback/coming-soon.vue @@ -0,0 +1,7 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/fallback/forbidden.vue b/apps/vben5/apps/app-antd/src/views/_core/fallback/forbidden.vue new file mode 100644 index 000000000..8ea65fedb --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/fallback/forbidden.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/fallback/internal-error.vue b/apps/vben5/apps/app-antd/src/views/_core/fallback/internal-error.vue new file mode 100644 index 000000000..819a47d5e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/fallback/internal-error.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/fallback/not-found.vue b/apps/vben5/apps/app-antd/src/views/_core/fallback/not-found.vue new file mode 100644 index 000000000..4d178e9cb --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/fallback/not-found.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/_core/fallback/offline.vue b/apps/vben5/apps/app-antd/src/views/_core/fallback/offline.vue new file mode 100644 index 000000000..5de4a88de --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/_core/fallback/offline.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-trends.vue b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-trends.vue new file mode 100644 index 000000000..fadfc917c --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-trends.vue @@ -0,0 +1,100 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-data.vue b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-data.vue new file mode 100644 index 000000000..30c4265df --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-data.vue @@ -0,0 +1,84 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-sales.vue b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-sales.vue new file mode 100644 index 000000000..260520b84 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-sales.vue @@ -0,0 +1,48 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-source.vue b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-source.vue new file mode 100644 index 000000000..e0d0aab5e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits-source.vue @@ -0,0 +1,67 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits.vue b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits.vue new file mode 100644 index 000000000..7e1f14ee6 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/analytics-visits.vue @@ -0,0 +1,57 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/analytics/index.vue b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/index.vue new file mode 100644 index 000000000..00b34df1e --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/analytics/index.vue @@ -0,0 +1,90 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/dashboard/workspace/index.vue b/apps/vben5/apps/app-antd/src/views/dashboard/workspace/index.vue new file mode 100644 index 000000000..b95d61381 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/dashboard/workspace/index.vue @@ -0,0 +1,266 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/demos/antd/index.vue b/apps/vben5/apps/app-antd/src/views/demos/antd/index.vue new file mode 100644 index 000000000..b3b05cc15 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/demos/antd/index.vue @@ -0,0 +1,66 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/identity/claim-types/index.vue b/apps/vben5/apps/app-antd/src/views/identity/claim-types/index.vue new file mode 100644 index 000000000..7d36dd612 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/identity/claim-types/index.vue @@ -0,0 +1,11 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/identity/role/index.vue b/apps/vben5/apps/app-antd/src/views/identity/role/index.vue new file mode 100644 index 000000000..725a355e4 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/identity/role/index.vue @@ -0,0 +1,11 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/identity/security-logs/index.vue b/apps/vben5/apps/app-antd/src/views/identity/security-logs/index.vue new file mode 100644 index 000000000..23476a2a0 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/identity/security-logs/index.vue @@ -0,0 +1,11 @@ + + + diff --git a/apps/vben5/apps/app-antd/src/views/identity/user/index.vue b/apps/vben5/apps/app-antd/src/views/identity/user/index.vue new file mode 100644 index 000000000..4c15e5f00 --- /dev/null +++ b/apps/vben5/apps/app-antd/src/views/identity/user/index.vue @@ -0,0 +1,11 @@ + + + diff --git a/apps/vben5/apps/app-antd/tailwind.config.mjs b/apps/vben5/apps/app-antd/tailwind.config.mjs new file mode 100644 index 000000000..f17f556fa --- /dev/null +++ b/apps/vben5/apps/app-antd/tailwind.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config'; diff --git a/apps/vben5/apps/app-antd/tsconfig.json b/apps/vben5/apps/app-antd/tsconfig.json new file mode 100644 index 000000000..02c287fe6 --- /dev/null +++ b/apps/vben5/apps/app-antd/tsconfig.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/web-app.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "#/*": ["./src/*"] + } + }, + "references": [{ "path": "./tsconfig.node.json" }], + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/apps/vben5/apps/app-antd/tsconfig.node.json b/apps/vben5/apps/app-antd/tsconfig.node.json new file mode 100644 index 000000000..c2f0d86cc --- /dev/null +++ b/apps/vben5/apps/app-antd/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/node.json", + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "noEmit": false + }, + "include": ["vite.config.mts"] +} diff --git a/apps/vben5/apps/app-antd/vite.config.mts b/apps/vben5/apps/app-antd/vite.config.mts new file mode 100644 index 000000000..cc4b2bef1 --- /dev/null +++ b/apps/vben5/apps/app-antd/vite.config.mts @@ -0,0 +1,27 @@ +import { defineConfig } from '@vben/vite-config'; + +export default defineConfig(async () => { + return { + application: {}, + vite: { + server: { + proxy: { + '/api': { + changeOrigin: true, + // rewrite: (path) => path.replace(/^\/api/, ''), + // mock代理目标地址 + target: 'http://81.68.64.105:30001/', + ws: true, + }, + '/connect': { + changeOrigin: true, + // rewrite: (path) => path.replace(/^\/api/, ''), + // mock代理目标地址 + target: 'http://81.68.64.105:30001/', + ws: true, + }, + }, + }, + }, + }; +}); diff --git a/apps/vben5/apps/backend-mock/.env b/apps/vben5/apps/backend-mock/.env new file mode 100644 index 000000000..b20c4a65f --- /dev/null +++ b/apps/vben5/apps/backend-mock/.env @@ -0,0 +1,3 @@ +PORT=5320 +ACCESS_TOKEN_SECRET=access_token_secret +REFRESH_TOKEN_SECRET=refresh_token_secret diff --git a/apps/vben5/apps/backend-mock/README.md b/apps/vben5/apps/backend-mock/README.md new file mode 100644 index 000000000..401bda76f --- /dev/null +++ b/apps/vben5/apps/backend-mock/README.md @@ -0,0 +1,15 @@ +# @vben/backend-mock + +## Description + +Vben Admin 数据 mock 服务,没有对接任何的数据库,所有数据都是模拟的,用于前端开发时提供数据支持。线上环境不再提供 mock 集成,可自行部署服务或者对接真实数据,由于 `mock.js` 等工具有一些限制,比如上传文件不行、无法模拟复杂的逻辑等,所以这里使用了真实的后端服务来实现。唯一麻烦的是本地需要同时启动后端服务和前端服务,但是这样可以更好的模拟真实环境。该服务不需要手动启动,已经集成在 vite 插件内,随应用一起启用。 + +## Running the app + +```bash +# development +$ pnpm run start + +# production mode +$ pnpm run build +``` diff --git a/apps/vben5/apps/backend-mock/api/auth/codes.ts b/apps/vben5/apps/backend-mock/api/auth/codes.ts new file mode 100644 index 000000000..7ba012705 --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/auth/codes.ts @@ -0,0 +1,14 @@ +import { verifyAccessToken } from '~/utils/jwt-utils'; +import { unAuthorizedResponse } from '~/utils/response'; + +export default eventHandler((event) => { + const userinfo = verifyAccessToken(event); + if (!userinfo) { + return unAuthorizedResponse(event); + } + + const codes = + MOCK_CODES.find((item) => item.username === userinfo.username)?.codes ?? []; + + return useResponseSuccess(codes); +}); diff --git a/apps/vben5/apps/backend-mock/api/auth/login.post.ts b/apps/vben5/apps/backend-mock/api/auth/login.post.ts new file mode 100644 index 000000000..df5737a25 --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/auth/login.post.ts @@ -0,0 +1,36 @@ +import { + clearRefreshTokenCookie, + setRefreshTokenCookie, +} from '~/utils/cookie-utils'; +import { generateAccessToken, generateRefreshToken } from '~/utils/jwt-utils'; +import { forbiddenResponse } from '~/utils/response'; + +export default defineEventHandler(async (event) => { + const { password, username } = await readBody(event); + if (!password || !username) { + setResponseStatus(event, 400); + return useResponseError( + 'BadRequestException', + 'Username and password are required', + ); + } + + const findUser = MOCK_USERS.find( + (item) => item.username === username && item.password === password, + ); + + if (!findUser) { + clearRefreshTokenCookie(event); + return forbiddenResponse(event, 'Username or password is incorrect.'); + } + + const accessToken = generateAccessToken(findUser); + const refreshToken = generateRefreshToken(findUser); + + setRefreshTokenCookie(event, refreshToken); + + return useResponseSuccess({ + ...findUser, + accessToken, + }); +}); diff --git a/apps/vben5/apps/backend-mock/api/auth/logout.post.ts b/apps/vben5/apps/backend-mock/api/auth/logout.post.ts new file mode 100644 index 000000000..ac6afe940 --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/auth/logout.post.ts @@ -0,0 +1,15 @@ +import { + clearRefreshTokenCookie, + getRefreshTokenFromCookie, +} from '~/utils/cookie-utils'; + +export default defineEventHandler(async (event) => { + const refreshToken = getRefreshTokenFromCookie(event); + if (!refreshToken) { + return useResponseSuccess(''); + } + + clearRefreshTokenCookie(event); + + return useResponseSuccess(''); +}); diff --git a/apps/vben5/apps/backend-mock/api/auth/refresh.post.ts b/apps/vben5/apps/backend-mock/api/auth/refresh.post.ts new file mode 100644 index 000000000..7df4d34f5 --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/auth/refresh.post.ts @@ -0,0 +1,33 @@ +import { + clearRefreshTokenCookie, + getRefreshTokenFromCookie, + setRefreshTokenCookie, +} from '~/utils/cookie-utils'; +import { verifyRefreshToken } from '~/utils/jwt-utils'; +import { forbiddenResponse } from '~/utils/response'; + +export default defineEventHandler(async (event) => { + const refreshToken = getRefreshTokenFromCookie(event); + if (!refreshToken) { + return forbiddenResponse(event); + } + + clearRefreshTokenCookie(event); + + const userinfo = verifyRefreshToken(refreshToken); + if (!userinfo) { + return forbiddenResponse(event); + } + + const findUser = MOCK_USERS.find( + (item) => item.username === userinfo.username, + ); + if (!findUser) { + return forbiddenResponse(event); + } + const accessToken = generateAccessToken(findUser); + + setRefreshTokenCookie(event, refreshToken); + + return accessToken; +}); diff --git a/apps/vben5/apps/backend-mock/api/menu/all.ts b/apps/vben5/apps/backend-mock/api/menu/all.ts new file mode 100644 index 000000000..580cee4f9 --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/menu/all.ts @@ -0,0 +1,13 @@ +import { verifyAccessToken } from '~/utils/jwt-utils'; +import { unAuthorizedResponse } from '~/utils/response'; + +export default eventHandler(async (event) => { + const userinfo = verifyAccessToken(event); + if (!userinfo) { + return unAuthorizedResponse(event); + } + + const menus = + MOCK_MENUS.find((item) => item.username === userinfo.username)?.menus ?? []; + return useResponseSuccess(menus); +}); diff --git a/apps/vben5/apps/backend-mock/api/status.ts b/apps/vben5/apps/backend-mock/api/status.ts new file mode 100644 index 000000000..41773e1d5 --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/status.ts @@ -0,0 +1,5 @@ +export default eventHandler((event) => { + const { status } = getQuery(event); + setResponseStatus(event, Number(status)); + return useResponseError(`${status}`); +}); diff --git a/apps/vben5/apps/backend-mock/api/table/list.ts b/apps/vben5/apps/backend-mock/api/table/list.ts new file mode 100644 index 000000000..4a0db94ec --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/table/list.ts @@ -0,0 +1,48 @@ +import { faker } from '@faker-js/faker'; +import { verifyAccessToken } from '~/utils/jwt-utils'; +import { unAuthorizedResponse } from '~/utils/response'; + +function generateMockDataList(count: number) { + const dataList = []; + + for (let i = 0; i < count; i++) { + const dataItem = { + id: faker.string.uuid(), + imageUrl: faker.image.avatar(), + imageUrl2: faker.image.avatar(), + open: faker.datatype.boolean(), + status: faker.helpers.arrayElement(['success', 'error', 'warning']), + productName: faker.commerce.productName(), + price: faker.commerce.price(), + currency: faker.finance.currencyCode(), + quantity: faker.number.int({ min: 1, max: 100 }), + available: faker.datatype.boolean(), + category: faker.commerce.department(), + releaseDate: faker.date.past(), + rating: faker.number.float({ min: 1, max: 5 }), + description: faker.commerce.productDescription(), + weight: faker.number.float({ min: 0.1, max: 10 }), + color: faker.color.human(), + inProduction: faker.datatype.boolean(), + tags: Array.from({ length: 3 }, () => faker.commerce.productAdjective()), + }; + + dataList.push(dataItem); + } + + return dataList; +} + +const mockData = generateMockDataList(100); + +export default eventHandler(async (event) => { + const userinfo = verifyAccessToken(event); + if (!userinfo) { + return unAuthorizedResponse(event); + } + + await sleep(600); + + const { page, pageSize } = getQuery(event); + return usePageResponseSuccess(page as string, pageSize as string, mockData); +}); diff --git a/apps/vben5/apps/backend-mock/api/test.get.ts b/apps/vben5/apps/backend-mock/api/test.get.ts new file mode 100644 index 000000000..ca4a500be --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/test.get.ts @@ -0,0 +1 @@ +export default defineEventHandler(() => 'Test get handler'); diff --git a/apps/vben5/apps/backend-mock/api/test.post.ts b/apps/vben5/apps/backend-mock/api/test.post.ts new file mode 100644 index 000000000..698cf211e --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/test.post.ts @@ -0,0 +1 @@ +export default defineEventHandler(() => 'Test post handler'); diff --git a/apps/vben5/apps/backend-mock/api/user/info.ts b/apps/vben5/apps/backend-mock/api/user/info.ts new file mode 100644 index 000000000..cfa2346cb --- /dev/null +++ b/apps/vben5/apps/backend-mock/api/user/info.ts @@ -0,0 +1,10 @@ +import { verifyAccessToken } from '~/utils/jwt-utils'; +import { unAuthorizedResponse } from '~/utils/response'; + +export default eventHandler((event) => { + const userinfo = verifyAccessToken(event); + if (!userinfo) { + return unAuthorizedResponse(event); + } + return useResponseSuccess(userinfo); +}); diff --git a/apps/vben5/apps/backend-mock/error.ts b/apps/vben5/apps/backend-mock/error.ts new file mode 100644 index 000000000..e20beac4e --- /dev/null +++ b/apps/vben5/apps/backend-mock/error.ts @@ -0,0 +1,7 @@ +import type { NitroErrorHandler } from 'nitropack'; + +const errorHandler: NitroErrorHandler = function (error, event) { + event.node.res.end(`[Error Handler] ${error.stack}`); +}; + +export default errorHandler; diff --git a/apps/vben5/apps/backend-mock/middleware/1.api.ts b/apps/vben5/apps/backend-mock/middleware/1.api.ts new file mode 100644 index 000000000..84e2ce0e0 --- /dev/null +++ b/apps/vben5/apps/backend-mock/middleware/1.api.ts @@ -0,0 +1,7 @@ +export default defineEventHandler((event) => { + if (event.method === 'OPTIONS') { + event.node.res.statusCode = 204; + event.node.res.statusMessage = 'No Content.'; + return 'OK'; + } +}); diff --git a/apps/vben5/apps/backend-mock/nitro.config.ts b/apps/vben5/apps/backend-mock/nitro.config.ts new file mode 100644 index 000000000..c2d7297fb --- /dev/null +++ b/apps/vben5/apps/backend-mock/nitro.config.ts @@ -0,0 +1,19 @@ +import errorHandler from './error'; + +process.env.COMPATIBILITY_DATE = new Date().toISOString(); +export default defineNitroConfig({ + devErrorHandler: errorHandler, + errorHandler: '~/error', + routeRules: { + '/api/**': { + cors: true, + headers: { + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Allow-Headers': '*', + 'Access-Control-Allow-Methods': 'GET,HEAD,PUT,PATCH,POST,DELETE', + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Expose-Headers': '*', + }, + }, + }, +}); diff --git a/apps/vben5/apps/backend-mock/package.json b/apps/vben5/apps/backend-mock/package.json new file mode 100644 index 000000000..cc0b8d533 --- /dev/null +++ b/apps/vben5/apps/backend-mock/package.json @@ -0,0 +1,21 @@ +{ + "name": "@vben/backend-mock", + "version": "0.0.1", + "description": "", + "private": true, + "license": "MIT", + "author": "", + "scripts": { + "build": "nitro build", + "start": "nitro dev" + }, + "dependencies": { + "@faker-js/faker": "catalog:", + "jsonwebtoken": "catalog:", + "nitropack": "catalog:" + }, + "devDependencies": { + "@types/jsonwebtoken": "catalog:", + "h3": "catalog:" + } +} diff --git a/apps/vben5/apps/backend-mock/routes/[...].ts b/apps/vben5/apps/backend-mock/routes/[...].ts new file mode 100644 index 000000000..70c5f7c74 --- /dev/null +++ b/apps/vben5/apps/backend-mock/routes/[...].ts @@ -0,0 +1,12 @@ +export default defineEventHandler(() => { + return ` +

Hello Vben Admin

+

Mock service is starting

+ +`; +}); diff --git a/apps/vben5/apps/backend-mock/tsconfig.build.json b/apps/vben5/apps/backend-mock/tsconfig.build.json new file mode 100644 index 000000000..64f86c6bd --- /dev/null +++ b/apps/vben5/apps/backend-mock/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] +} diff --git a/apps/vben5/apps/backend-mock/tsconfig.json b/apps/vben5/apps/backend-mock/tsconfig.json new file mode 100644 index 000000000..43008af1c --- /dev/null +++ b/apps/vben5/apps/backend-mock/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "./.nitro/types/tsconfig.json" +} diff --git a/apps/vben5/apps/backend-mock/utils/cookie-utils.ts b/apps/vben5/apps/backend-mock/utils/cookie-utils.ts new file mode 100644 index 000000000..0d92f577d --- /dev/null +++ b/apps/vben5/apps/backend-mock/utils/cookie-utils.ts @@ -0,0 +1,26 @@ +import type { EventHandlerRequest, H3Event } from 'h3'; + +export function clearRefreshTokenCookie(event: H3Event) { + deleteCookie(event, 'jwt', { + httpOnly: true, + sameSite: 'none', + secure: true, + }); +} + +export function setRefreshTokenCookie( + event: H3Event, + refreshToken: string, +) { + setCookie(event, 'jwt', refreshToken, { + httpOnly: true, + maxAge: 24 * 60 * 60 * 1000, + sameSite: 'none', + secure: true, + }); +} + +export function getRefreshTokenFromCookie(event: H3Event) { + const refreshToken = getCookie(event, 'jwt'); + return refreshToken; +} diff --git a/apps/vben5/apps/backend-mock/utils/jwt-utils.ts b/apps/vben5/apps/backend-mock/utils/jwt-utils.ts new file mode 100644 index 000000000..8cfc68436 --- /dev/null +++ b/apps/vben5/apps/backend-mock/utils/jwt-utils.ts @@ -0,0 +1,59 @@ +import type { EventHandlerRequest, H3Event } from 'h3'; + +import jwt from 'jsonwebtoken'; + +import { UserInfo } from './mock-data'; + +// TODO: Replace with your own secret key +const ACCESS_TOKEN_SECRET = 'access_token_secret'; +const REFRESH_TOKEN_SECRET = 'refresh_token_secret'; + +export interface UserPayload extends UserInfo { + iat: number; + exp: number; +} + +export function generateAccessToken(user: UserInfo) { + return jwt.sign(user, ACCESS_TOKEN_SECRET, { expiresIn: '7d' }); +} + +export function generateRefreshToken(user: UserInfo) { + return jwt.sign(user, REFRESH_TOKEN_SECRET, { + expiresIn: '30d', + }); +} + +export function verifyAccessToken( + event: H3Event, +): null | Omit { + const authHeader = getHeader(event, 'Authorization'); + if (!authHeader?.startsWith('Bearer')) { + return null; + } + + const token = authHeader.split(' ')[1]; + try { + const decoded = jwt.verify(token, ACCESS_TOKEN_SECRET) as UserPayload; + + const username = decoded.username; + const user = MOCK_USERS.find((item) => item.username === username); + const { password: _pwd, ...userinfo } = user; + return userinfo; + } catch { + return null; + } +} + +export function verifyRefreshToken( + token: string, +): null | Omit { + try { + const decoded = jwt.verify(token, REFRESH_TOKEN_SECRET) as UserPayload; + const username = decoded.username; + const user = MOCK_USERS.find((item) => item.username === username); + const { password: _pwd, ...userinfo } = user; + return userinfo; + } catch { + return null; + } +} diff --git a/apps/vben5/apps/backend-mock/utils/mock-data.ts b/apps/vben5/apps/backend-mock/utils/mock-data.ts new file mode 100644 index 000000000..71970a285 --- /dev/null +++ b/apps/vben5/apps/backend-mock/utils/mock-data.ts @@ -0,0 +1,186 @@ +export interface UserInfo { + id: number; + password: string; + realName: string; + roles: string[]; + username: string; +} + +export const MOCK_USERS: UserInfo[] = [ + { + id: 0, + password: '123456', + realName: 'Vben', + roles: ['super'], + username: 'vben', + }, + { + id: 1, + password: '123456', + realName: 'Admin', + roles: ['admin'], + username: 'admin', + }, + { + id: 2, + password: '123456', + realName: 'Jack', + roles: ['user'], + username: 'jack', + }, +]; + +export const MOCK_CODES = [ + // super + { + codes: ['AC_100100', 'AC_100110', 'AC_100120', 'AC_100010'], + username: 'vben', + }, + { + // admin + codes: ['AC_100010', 'AC_100020', 'AC_100030'], + username: 'admin', + }, + { + // user + codes: ['AC_1000001', 'AC_1000002'], + username: 'jack', + }, +]; + +const dashboardMenus = [ + { + component: 'BasicLayout', + meta: { + order: -1, + title: 'page.dashboard.title', + }, + name: 'Dashboard', + path: '/', + redirect: '/analytics', + children: [ + { + name: 'Analytics', + path: '/analytics', + component: '/dashboard/analytics/index', + meta: { + affixTab: true, + title: 'page.dashboard.analytics', + }, + }, + { + name: 'Workspace', + path: '/workspace', + component: '/dashboard/workspace/index', + meta: { + title: 'page.dashboard.workspace', + }, + }, + ], + }, +]; + +const createDemosMenus = (role: 'admin' | 'super' | 'user') => { + const roleWithMenus = { + admin: { + component: '/demos/access/admin-visible', + meta: { + icon: 'mdi:button-cursor', + title: 'demos.access.adminVisible', + }, + name: 'AccessAdminVisibleDemo', + path: '/demos/access/admin-visible', + }, + super: { + component: '/demos/access/super-visible', + meta: { + icon: 'mdi:button-cursor', + title: 'demos.access.superVisible', + }, + name: 'AccessSuperVisibleDemo', + path: '/demos/access/super-visible', + }, + user: { + component: '/demos/access/user-visible', + meta: { + icon: 'mdi:button-cursor', + title: 'demos.access.userVisible', + }, + name: 'AccessUserVisibleDemo', + path: '/demos/access/user-visible', + }, + }; + + return [ + { + component: 'BasicLayout', + meta: { + icon: 'ic:baseline-view-in-ar', + keepAlive: true, + order: 1000, + title: 'demos.title', + }, + name: 'Demos', + path: '/demos', + redirect: '/demos/access', + children: [ + { + name: 'AccessDemos', + path: '/demosaccess', + meta: { + icon: 'mdi:cloud-key-outline', + title: 'demos.access.backendPermissions', + }, + redirect: '/demos/access/page-control', + children: [ + { + name: 'AccessPageControlDemo', + path: '/demos/access/page-control', + component: '/demos/access/index', + meta: { + icon: 'mdi:page-previous-outline', + title: 'demos.access.pageAccess', + }, + }, + { + name: 'AccessButtonControlDemo', + path: '/demos/access/button-control', + component: '/demos/access/button-control', + meta: { + icon: 'mdi:button-cursor', + title: 'demos.access.buttonControl', + }, + }, + { + name: 'AccessMenuVisible403Demo', + path: '/demos/access/menu-visible-403', + component: '/demos/access/menu-visible-403', + meta: { + authority: ['no-body'], + icon: 'mdi:button-cursor', + menuVisibleWithForbidden: true, + title: 'demos.access.menuVisible403', + }, + }, + roleWithMenus[role], + ], + }, + ], + }, + ]; +}; + +export const MOCK_MENUS = [ + { + menus: [...dashboardMenus, ...createDemosMenus('super')], + username: 'vben', + }, + { + menus: [...dashboardMenus, ...createDemosMenus('admin')], + username: 'admin', + }, + { + menus: [...dashboardMenus, ...createDemosMenus('user')], + username: 'jack', + }, +]; diff --git a/apps/vben5/apps/backend-mock/utils/response.ts b/apps/vben5/apps/backend-mock/utils/response.ts new file mode 100644 index 000000000..2a5a908f2 --- /dev/null +++ b/apps/vben5/apps/backend-mock/utils/response.ts @@ -0,0 +1,68 @@ +import type { EventHandlerRequest, H3Event } from 'h3'; + +export function useResponseSuccess(data: T) { + return { + code: 0, + data, + error: null, + message: 'ok', + }; +} + +export function usePageResponseSuccess( + page: number | string, + pageSize: number | string, + list: T[], + { message = 'ok' } = {}, +) { + const pageData = pagination( + Number.parseInt(`${page}`), + Number.parseInt(`${pageSize}`), + list, + ); + + return { + ...useResponseSuccess({ + items: pageData, + total: list.length, + }), + message, + }; +} + +export function useResponseError(message: string, error: any = null) { + return { + code: -1, + data: null, + error, + message, + }; +} + +export function forbiddenResponse( + event: H3Event, + message = 'Forbidden Exception', +) { + setResponseStatus(event, 403); + return useResponseError(message, message); +} + +export function unAuthorizedResponse(event: H3Event) { + setResponseStatus(event, 401); + return useResponseError('Unauthorized Exception', 'Unauthorized Exception'); +} + +export function sleep(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export function pagination( + pageNo: number, + pageSize: number, + array: T[], +): T[] { + const offset = (pageNo - 1) * Number(pageSize); + return offset + Number(pageSize) >= array.length + ? array.slice(offset) + : array.slice(offset, offset + Number(pageSize)); +} diff --git a/apps/vben5/apps/web-antd/.env b/apps/vben5/apps/web-antd/.env new file mode 100644 index 000000000..c14a467fb --- /dev/null +++ b/apps/vben5/apps/web-antd/.env @@ -0,0 +1,5 @@ +# 应用标题 +VITE_APP_TITLE=Vben Admin Antd + +# 应用命名空间,用于缓存、store等功能的前缀,确保隔离 +VITE_APP_NAMESPACE=vben-web-antd diff --git a/apps/vben5/apps/web-antd/.env.analyze b/apps/vben5/apps/web-antd/.env.analyze new file mode 100644 index 000000000..ffafa8dd5 --- /dev/null +++ b/apps/vben5/apps/web-antd/.env.analyze @@ -0,0 +1,7 @@ +# public path +VITE_BASE=/ + +# Basic interface address SPA +VITE_GLOB_API_URL=/api + +VITE_VISUALIZER=true diff --git a/apps/vben5/apps/web-antd/.env.development b/apps/vben5/apps/web-antd/.env.development new file mode 100644 index 000000000..c138f4829 --- /dev/null +++ b/apps/vben5/apps/web-antd/.env.development @@ -0,0 +1,16 @@ +# 端口号 +VITE_PORT=5666 + +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=/api + +# 是否开启 Nitro Mock服务,true 为开启,false 为关闭 +VITE_NITRO_MOCK=true + +# 是否打开 devtools,true 为打开,false 为关闭 +VITE_DEVTOOLS=false + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true diff --git a/apps/vben5/apps/web-antd/.env.production b/apps/vben5/apps/web-antd/.env.production new file mode 100644 index 000000000..5375847a6 --- /dev/null +++ b/apps/vben5/apps/web-antd/.env.production @@ -0,0 +1,19 @@ +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=https://mock-napi.vben.pro/api + +# 是否开启压缩,可以设置为 none, brotli, gzip +VITE_COMPRESS=none + +# 是否开启 PWA +VITE_PWA=false + +# vue-router 的模式 +VITE_ROUTER_HISTORY=hash + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true + +# 打包后是否生成dist.zip +VITE_ARCHIVER=true diff --git a/apps/vben5/apps/web-antd/index.html b/apps/vben5/apps/web-antd/index.html new file mode 100644 index 000000000..480eb84de --- /dev/null +++ b/apps/vben5/apps/web-antd/index.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + <%= VITE_APP_TITLE %> + + + + +
+ + + diff --git a/apps/vben5/apps/web-antd/package.json b/apps/vben5/apps/web-antd/package.json new file mode 100644 index 000000000..42afa3c69 --- /dev/null +++ b/apps/vben5/apps/web-antd/package.json @@ -0,0 +1,50 @@ +{ + "name": "@vben/web-antd", + "version": "5.4.8", + "homepage": "https://vben.pro", + "bugs": "https://github.com/vbenjs/vue-vben-admin/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/vbenjs/vue-vben-admin.git", + "directory": "apps/web-antd" + }, + "license": "MIT", + "author": { + "name": "vben", + "email": "ann.vben@gmail.com", + "url": "https://github.com/anncwb" + }, + "type": "module", + "scripts": { + "build": "pnpm vite build --mode production", + "build:analyze": "pnpm vite build --mode analyze", + "dev": "pnpm vite --mode development", + "preview": "vite preview", + "typecheck": "vue-tsc --noEmit --skipLibCheck" + }, + "imports": { + "#/*": "./src/*" + }, + "dependencies": { + "@vben/access": "workspace:*", + "@vben/common-ui": "workspace:*", + "@vben/constants": "workspace:*", + "@vben/hooks": "workspace:*", + "@vben/icons": "workspace:*", + "@vben/layouts": "workspace:*", + "@vben/locales": "workspace:*", + "@vben/plugins": "workspace:*", + "@vben/preferences": "workspace:*", + "@vben/request": "workspace:*", + "@vben/stores": "workspace:*", + "@vben/styles": "workspace:*", + "@vben/types": "workspace:*", + "@vben/utils": "workspace:*", + "@vueuse/core": "catalog:", + "ant-design-vue": "catalog:", + "dayjs": "catalog:", + "pinia": "catalog:", + "vue": "catalog:", + "vue-router": "catalog:" + } +} diff --git a/apps/vben5/apps/web-antd/postcss.config.mjs b/apps/vben5/apps/web-antd/postcss.config.mjs new file mode 100644 index 000000000..3d8070455 --- /dev/null +++ b/apps/vben5/apps/web-antd/postcss.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config/postcss'; diff --git a/apps/vben5/apps/web-antd/public/favicon.ico b/apps/vben5/apps/web-antd/public/favicon.ico new file mode 100644 index 000000000..fcf9818e2 Binary files /dev/null and b/apps/vben5/apps/web-antd/public/favicon.ico differ diff --git a/apps/vben5/apps/web-antd/src/adapter/component/index.ts b/apps/vben5/apps/web-antd/src/adapter/component/index.ts new file mode 100644 index 000000000..1afa62174 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/adapter/component/index.ts @@ -0,0 +1,127 @@ +/** + * 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用 + * 可用于 vben-form、vben-modal、vben-drawer 等组件使用, + */ + +import type { BaseFormComponentType } from '@vben/common-ui'; + +import type { Component, SetupContext } from 'vue'; +import { h } from 'vue'; + +import { globalShareState } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { + AutoComplete, + Button, + Checkbox, + CheckboxGroup, + DatePicker, + Divider, + Input, + InputNumber, + InputPassword, + Mentions, + notification, + Radio, + RadioGroup, + RangePicker, + Rate, + Select, + Space, + Switch, + Textarea, + TimePicker, + TreeSelect, + Upload, +} from 'ant-design-vue'; + +const withDefaultPlaceholder = ( + component: T, + type: 'input' | 'select', +) => { + return (props: any, { attrs, slots }: Omit) => { + const placeholder = props?.placeholder || $t(`ui.placeholder.${type}`); + return h(component, { ...props, ...attrs, placeholder }, slots); + }; +}; + +// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明 +export type ComponentType = + | 'AutoComplete' + | 'Checkbox' + | 'CheckboxGroup' + | 'DatePicker' + | 'DefaultButton' + | 'Divider' + | 'Input' + | 'InputNumber' + | 'InputPassword' + | 'Mentions' + | 'PrimaryButton' + | 'Radio' + | 'RadioGroup' + | 'RangePicker' + | 'Rate' + | 'Select' + | 'Space' + | 'Switch' + | 'Textarea' + | 'TimePicker' + | 'TreeSelect' + | 'Upload' + | BaseFormComponentType; + +async function initComponentAdapter() { + const components: Partial> = { + // 如果你的组件体积比较大,可以使用异步加载 + // Button: () => + // import('xxx').then((res) => res.Button), + + AutoComplete, + Checkbox, + CheckboxGroup, + DatePicker, + // 自定义默认按钮 + DefaultButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'default' }, slots); + }, + Divider, + Input: withDefaultPlaceholder(Input, 'input'), + InputNumber: withDefaultPlaceholder(InputNumber, 'input'), + InputPassword: withDefaultPlaceholder(InputPassword, 'input'), + Mentions: withDefaultPlaceholder(Mentions, 'input'), + // 自定义主要按钮 + PrimaryButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'primary' }, slots); + }, + Radio, + RadioGroup, + RangePicker, + Rate, + Select: withDefaultPlaceholder(Select, 'select'), + Space, + Switch, + Textarea: withDefaultPlaceholder(Textarea, 'input'), + TimePicker, + TreeSelect: withDefaultPlaceholder(TreeSelect, 'select'), + Upload, + }; + + // 将组件注册到全局共享状态中 + globalShareState.setComponents(components); + + // 定义全局共享状态中的消息提示 + globalShareState.defineMessage({ + // 复制成功消息提示 + copyPreferencesSuccess: (title, content) => { + notification.success({ + description: content, + message: title, + placement: 'bottomRight', + }); + }, + }); +} + +export { initComponentAdapter }; diff --git a/apps/vben5/apps/web-antd/src/adapter/form.ts b/apps/vben5/apps/web-antd/src/adapter/form.ts new file mode 100644 index 000000000..65ff793b6 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/adapter/form.ts @@ -0,0 +1,47 @@ +import type { + VbenFormSchema as FormSchema, + VbenFormProps, +} from '@vben/common-ui'; + +import type { ComponentType } from './component'; + +import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +setupVbenForm({ + config: { + // ant design vue组件库默认都是 v-model:value + baseModelPropName: 'value', + + // 一些组件是 v-model:checked 或者 v-model:fileList + modelPropNameMap: { + Checkbox: 'checked', + Radio: 'checked', + Switch: 'checked', + Upload: 'fileList', + }, + }, + defineRules: { + // 输入项目必填国际化适配 + required: (value, _params, ctx) => { + if (value === undefined || value === null || value.length === 0) { + return $t('ui.formRules.required', [ctx.label]); + } + return true; + }, + // 选择项目必填国际化适配 + selectRequired: (value, _params, ctx) => { + if (value === undefined || value === null) { + return $t('ui.formRules.selectRequired', [ctx.label]); + } + return true; + }, + }, +}); + +const useVbenForm = useForm; + +export { useVbenForm, z }; + +export type VbenFormSchema = FormSchema; +export type { VbenFormProps }; diff --git a/apps/vben5/apps/web-antd/src/adapter/vxe-table.ts b/apps/vben5/apps/web-antd/src/adapter/vxe-table.ts new file mode 100644 index 000000000..d296b2050 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/adapter/vxe-table.ts @@ -0,0 +1,67 @@ +import { h } from 'vue'; + +import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table'; + +import { Button, Image } from 'ant-design-vue'; + +import { useVbenForm } from './form'; + +setupVbenVxeTable({ + configVxeTable: (vxeUI) => { + vxeUI.setConfig({ + grid: { + align: 'center', + border: false, + columnConfig: { + resizable: true, + }, + minHeight: 180, + formConfig: { + // 全局禁用vxe-table的表单配置,使用formOptions + enabled: false, + }, + proxyConfig: { + autoLoad: true, + response: { + result: 'items', + total: 'total', + list: 'items', + }, + showActiveMsg: true, + showResponseMsg: false, + }, + round: true, + showOverflow: true, + size: 'small', + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellImage' }, + vxeUI.renderer.add('CellImage', { + renderTableDefault(_renderOpts, params) { + const { column, row } = params; + return h(Image, { src: row[column.field] }); + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellLink' }, + vxeUI.renderer.add('CellLink', { + renderTableDefault(renderOpts) { + const { props } = renderOpts; + return h( + Button, + { size: 'small', type: 'link' }, + { default: () => props?.text }, + ); + }, + }); + + // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化 + // vxeUI.formats.add + }, + useVbenForm, +}); + +export { useVbenVxeGrid }; + +export type * from '@vben/plugins/vxe-table'; diff --git a/apps/vben5/apps/web-antd/src/api/core/auth.ts b/apps/vben5/apps/web-antd/src/api/core/auth.ts new file mode 100644 index 000000000..71d9f9943 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/api/core/auth.ts @@ -0,0 +1,51 @@ +import { baseRequestClient, requestClient } from '#/api/request'; + +export namespace AuthApi { + /** 登录接口参数 */ + export interface LoginParams { + password?: string; + username?: string; + } + + /** 登录接口返回值 */ + export interface LoginResult { + accessToken: string; + } + + export interface RefreshTokenResult { + data: string; + status: number; + } +} + +/** + * 登录 + */ +export async function loginApi(data: AuthApi.LoginParams) { + return requestClient.post('/auth/login', data); +} + +/** + * 刷新accessToken + */ +export async function refreshTokenApi() { + return baseRequestClient.post('/auth/refresh', { + withCredentials: true, + }); +} + +/** + * 退出登录 + */ +export async function logoutApi() { + return baseRequestClient.post('/auth/logout', { + withCredentials: true, + }); +} + +/** + * 获取用户权限码 + */ +export async function getAccessCodesApi() { + return requestClient.get('/auth/codes'); +} diff --git a/apps/vben5/apps/web-antd/src/api/core/index.ts b/apps/vben5/apps/web-antd/src/api/core/index.ts new file mode 100644 index 000000000..28a5aef47 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/api/core/index.ts @@ -0,0 +1,3 @@ +export * from './auth'; +export * from './menu'; +export * from './user'; diff --git a/apps/vben5/apps/web-antd/src/api/core/menu.ts b/apps/vben5/apps/web-antd/src/api/core/menu.ts new file mode 100644 index 000000000..9ef60b11c --- /dev/null +++ b/apps/vben5/apps/web-antd/src/api/core/menu.ts @@ -0,0 +1,10 @@ +import type { RouteRecordStringComponent } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户所有菜单 + */ +export async function getAllMenusApi() { + return requestClient.get('/menu/all'); +} diff --git a/apps/vben5/apps/web-antd/src/api/core/user.ts b/apps/vben5/apps/web-antd/src/api/core/user.ts new file mode 100644 index 000000000..7e28ea848 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/api/core/user.ts @@ -0,0 +1,10 @@ +import type { UserInfo } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户信息 + */ +export async function getUserInfoApi() { + return requestClient.get('/user/info'); +} diff --git a/apps/vben5/apps/web-antd/src/api/index.ts b/apps/vben5/apps/web-antd/src/api/index.ts new file mode 100644 index 000000000..4b0e04137 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/api/index.ts @@ -0,0 +1 @@ +export * from './core'; diff --git a/apps/vben5/apps/web-antd/src/api/request.ts b/apps/vben5/apps/web-antd/src/api/request.ts new file mode 100644 index 000000000..67ef35e44 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/api/request.ts @@ -0,0 +1,114 @@ +/** + * 该文件可自行根据业务逻辑进行调整 + */ +import type { HttpResponse } from '@vben/request'; + +import { useAppConfig } from '@vben/hooks'; +import { preferences } from '@vben/preferences'; +import { + authenticateResponseInterceptor, + errorMessageResponseInterceptor, + RequestClient, +} from '@vben/request'; +import { useAccessStore } from '@vben/stores'; + +import { message } from 'ant-design-vue'; + +import { useAuthStore } from '#/store'; + +import { refreshTokenApi } from './core'; + +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); + +function createRequestClient(baseURL: string) { + const client = new RequestClient({ + baseURL, + }); + + /** + * 重新认证逻辑 + */ + async function doReAuthenticate() { + console.warn('Access token or refresh token is invalid or expired. '); + const accessStore = useAccessStore(); + const authStore = useAuthStore(); + accessStore.setAccessToken(null); + if ( + preferences.app.loginExpiredMode === 'modal' && + accessStore.isAccessChecked + ) { + accessStore.setLoginExpired(true); + } else { + await authStore.logout(); + } + } + + /** + * 刷新token逻辑 + */ + async function doRefreshToken() { + const accessStore = useAccessStore(); + const resp = await refreshTokenApi(); + const newToken = resp.data; + accessStore.setAccessToken(newToken); + return newToken; + } + + function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; + } + + // 请求头处理 + client.addRequestInterceptor({ + fulfilled: async (config) => { + const accessStore = useAccessStore(); + + config.headers.Authorization = formatToken(accessStore.accessToken); + config.headers['Accept-Language'] = preferences.app.locale; + return config; + }, + }); + + // response数据解构 + client.addResponseInterceptor({ + fulfilled: (response) => { + const { data: responseData, status } = response; + + const { code, data } = responseData; + if (status >= 200 && status < 400 && code === 0) { + return data; + } + + throw Object.assign({}, response, { response }); + }, + }); + + // token过期的处理 + client.addResponseInterceptor( + authenticateResponseInterceptor({ + client, + doReAuthenticate, + doRefreshToken, + enableRefreshToken: preferences.app.enableRefreshToken, + formatToken, + }), + ); + + // 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里 + client.addResponseInterceptor( + errorMessageResponseInterceptor((msg: string, error) => { + // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg + // 当前mock接口返回的错误字段是 error 或者 message + const responseData = error?.response?.data ?? {}; + const errorMessage = responseData?.error ?? responseData?.message ?? ''; + // 如果没有错误信息,则会根据状态码进行提示 + message.error(errorMessage || msg); + }), + ); + + return client; +} + +export const requestClient = createRequestClient(apiURL); + +export const baseRequestClient = new RequestClient({ baseURL: apiURL }); diff --git a/apps/vben5/apps/web-antd/src/app.vue b/apps/vben5/apps/web-antd/src/app.vue new file mode 100644 index 000000000..bbaccce13 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/app.vue @@ -0,0 +1,39 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/bootstrap.ts b/apps/vben5/apps/web-antd/src/bootstrap.ts new file mode 100644 index 000000000..963d1c7f7 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/bootstrap.ts @@ -0,0 +1,48 @@ +import { createApp, watchEffect } from 'vue'; + +import { registerAccessDirective } from '@vben/access'; +import { preferences } from '@vben/preferences'; +import { initStores } from '@vben/stores'; +import '@vben/styles'; +import '@vben/styles/antd'; + +import { useTitle } from '@vueuse/core'; + +import { $t, setupI18n } from '#/locales'; + +import { initComponentAdapter } from './adapter/component'; +import App from './app.vue'; +import { router } from './router'; + +async function bootstrap(namespace: string) { + // 初始化组件适配器 + await initComponentAdapter(); + + const app = createApp(App); + + // 国际化 i18n 配置 + await setupI18n(app); + + // 配置 pinia-tore + await initStores(app, { namespace }); + + // 安装权限指令 + registerAccessDirective(app); + + // 配置路由及路由守卫 + app.use(router); + + // 动态更新标题 + watchEffect(() => { + if (preferences.app.dynamicTitle) { + const routeTitle = router.currentRoute.value.meta?.title; + const pageTitle = + (routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name; + useTitle(pageTitle); + } + }); + + app.mount('#app'); +} + +export { bootstrap }; diff --git a/apps/vben5/apps/web-antd/src/layouts/auth.vue b/apps/vben5/apps/web-antd/src/layouts/auth.vue new file mode 100644 index 000000000..18d415bc7 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/layouts/auth.vue @@ -0,0 +1,23 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/layouts/basic.vue b/apps/vben5/apps/web-antd/src/layouts/basic.vue new file mode 100644 index 000000000..51412956a --- /dev/null +++ b/apps/vben5/apps/web-antd/src/layouts/basic.vue @@ -0,0 +1,157 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/layouts/index.ts b/apps/vben5/apps/web-antd/src/layouts/index.ts new file mode 100644 index 000000000..a43207805 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/layouts/index.ts @@ -0,0 +1,6 @@ +const BasicLayout = () => import('./basic.vue'); +const AuthPageLayout = () => import('./auth.vue'); + +const IFrameView = () => import('@vben/layouts').then((m) => m.IFrameView); + +export { AuthPageLayout, BasicLayout, IFrameView }; diff --git a/apps/vben5/apps/web-antd/src/locales/README.md b/apps/vben5/apps/web-antd/src/locales/README.md new file mode 100644 index 000000000..7b451032e --- /dev/null +++ b/apps/vben5/apps/web-antd/src/locales/README.md @@ -0,0 +1,3 @@ +# locale + +每个app使用的国际化可能不同,这里用于扩展国际化的功能,例如扩展 dayjs、antd组件库的多语言切换,以及app本身的国际化文件。 diff --git a/apps/vben5/apps/web-antd/src/locales/index.ts b/apps/vben5/apps/web-antd/src/locales/index.ts new file mode 100644 index 000000000..1972e06ee --- /dev/null +++ b/apps/vben5/apps/web-antd/src/locales/index.ts @@ -0,0 +1,100 @@ +import type { LocaleSetupOptions, SupportedLanguagesType } from '@vben/locales'; +import type { Locale } from 'ant-design-vue/es/locale'; + +import type { App } from 'vue'; +import { ref } from 'vue'; + +import { + $t, + setupI18n as coreSetup, + loadLocalesMapFromDir, +} from '@vben/locales'; +import { preferences } from '@vben/preferences'; + +import antdEnLocale from 'ant-design-vue/es/locale/en_US'; +import antdDefaultLocale from 'ant-design-vue/es/locale/zh_CN'; +import dayjs from 'dayjs'; + +const antdLocale = ref(antdDefaultLocale); + +const modules = import.meta.glob('./langs/**/*.json'); + +const localesMap = loadLocalesMapFromDir( + /\.\/langs\/([^/]+)\/(.*)\.json$/, + modules, +); +/** + * 加载应用特有的语言包 + * 这里也可以改造为从服务端获取翻译数据 + * @param lang + */ +async function loadMessages(lang: SupportedLanguagesType) { + const [appLocaleMessages] = await Promise.all([ + localesMap[lang]?.(), + loadThirdPartyMessage(lang), + ]); + return appLocaleMessages?.default; +} + +/** + * 加载第三方组件库的语言包 + * @param lang + */ +async function loadThirdPartyMessage(lang: SupportedLanguagesType) { + await Promise.all([loadAntdLocale(lang), loadDayjsLocale(lang)]); +} + +/** + * 加载dayjs的语言包 + * @param lang + */ +async function loadDayjsLocale(lang: SupportedLanguagesType) { + let locale; + switch (lang) { + case 'en-US': { + locale = await import('dayjs/locale/en'); + break; + } + case 'zh-CN': { + locale = await import('dayjs/locale/zh-cn'); + break; + } + // 默认使用英语 + default: { + locale = await import('dayjs/locale/en'); + } + } + if (locale) { + dayjs.locale(locale); + } else { + console.error(`Failed to load dayjs locale for ${lang}`); + } +} + +/** + * 加载antd的语言包 + * @param lang + */ +async function loadAntdLocale(lang: SupportedLanguagesType) { + switch (lang) { + case 'en-US': { + antdLocale.value = antdEnLocale; + break; + } + case 'zh-CN': { + antdLocale.value = antdDefaultLocale; + break; + } + } +} + +async function setupI18n(app: App, options: LocaleSetupOptions = {}) { + await coreSetup(app, { + defaultLocale: preferences.app.locale, + loadMessages, + missingWarn: !import.meta.env.PROD, + ...options, + }); +} + +export { $t, antdLocale, setupI18n }; diff --git a/apps/vben5/apps/web-antd/src/locales/langs/en-US/demos.json b/apps/vben5/apps/web-antd/src/locales/langs/en-US/demos.json new file mode 100644 index 000000000..071564349 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/locales/langs/en-US/demos.json @@ -0,0 +1,12 @@ +{ + "title": "Demos", + "antd": "Ant Design Vue", + "vben": { + "title": "Project", + "about": "About", + "document": "Document", + "antdv": "Ant Design Vue Version", + "naive-ui": "Naive UI Version", + "element-plus": "Element Plus Version" + } +} diff --git a/apps/vben5/apps/web-antd/src/locales/langs/en-US/page.json b/apps/vben5/apps/web-antd/src/locales/langs/en-US/page.json new file mode 100644 index 000000000..618a258c0 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/locales/langs/en-US/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "Login", + "register": "Register", + "codeLogin": "Code Login", + "qrcodeLogin": "Qr Code Login", + "forgetPassword": "Forget Password" + }, + "dashboard": { + "title": "Dashboard", + "analytics": "Analytics", + "workspace": "Workspace" + } +} diff --git a/apps/vben5/apps/web-antd/src/locales/langs/zh-CN/demos.json b/apps/vben5/apps/web-antd/src/locales/langs/zh-CN/demos.json new file mode 100644 index 000000000..93ee722f5 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/locales/langs/zh-CN/demos.json @@ -0,0 +1,12 @@ +{ + "title": "演示", + "antd": "Ant Design Vue", + "vben": { + "title": "项目", + "about": "关于", + "document": "文档", + "antdv": "Ant Design Vue 版本", + "naive-ui": "Naive UI 版本", + "element-plus": "Element Plus 版本" + } +} diff --git a/apps/vben5/apps/web-antd/src/locales/langs/zh-CN/page.json b/apps/vben5/apps/web-antd/src/locales/langs/zh-CN/page.json new file mode 100644 index 000000000..4cb67081c --- /dev/null +++ b/apps/vben5/apps/web-antd/src/locales/langs/zh-CN/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "登录", + "register": "注册", + "codeLogin": "验证码登录", + "qrcodeLogin": "二维码登录", + "forgetPassword": "忘记密码" + }, + "dashboard": { + "title": "概览", + "analytics": "分析页", + "workspace": "工作台" + } +} diff --git a/apps/vben5/apps/web-antd/src/main.ts b/apps/vben5/apps/web-antd/src/main.ts new file mode 100644 index 000000000..5d728a02a --- /dev/null +++ b/apps/vben5/apps/web-antd/src/main.ts @@ -0,0 +1,31 @@ +import { initPreferences } from '@vben/preferences'; +import { unmountGlobalLoading } from '@vben/utils'; + +import { overridesPreferences } from './preferences'; + +/** + * 应用初始化完成之后再进行页面加载渲染 + */ +async function initApplication() { + // name用于指定项目唯一标识 + // 用于区分不同项目的偏好设置以及存储数据的key前缀以及其他一些需要隔离的数据 + const env = import.meta.env.PROD ? 'prod' : 'dev'; + const appVersion = import.meta.env.VITE_APP_VERSION; + const namespace = `${import.meta.env.VITE_APP_NAMESPACE}-${appVersion}-${env}`; + + // app偏好设置初始化 + await initPreferences({ + namespace, + overrides: overridesPreferences, + }); + + // 启动应用并挂载 + // vue应用主要逻辑及视图 + const { bootstrap } = await import('./bootstrap'); + await bootstrap(namespace); + + // 移除并销毁loading + unmountGlobalLoading(); +} + +initApplication(); diff --git a/apps/vben5/apps/web-antd/src/preferences.ts b/apps/vben5/apps/web-antd/src/preferences.ts new file mode 100644 index 000000000..b2e9ace43 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/preferences.ts @@ -0,0 +1,13 @@ +import { defineOverridesPreferences } from '@vben/preferences'; + +/** + * @description 项目配置文件 + * 只需要覆盖项目中的一部分配置,不需要的配置不用覆盖,会自动使用默认配置 + * !!! 更改配置后请清空缓存,否则可能不生效 + */ +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + name: import.meta.env.VITE_APP_TITLE, + }, +}); diff --git a/apps/vben5/apps/web-antd/src/router/access.ts b/apps/vben5/apps/web-antd/src/router/access.ts new file mode 100644 index 000000000..3a48be237 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/access.ts @@ -0,0 +1,42 @@ +import type { + ComponentRecordType, + GenerateMenuAndRoutesOptions, +} from '@vben/types'; + +import { generateAccessible } from '@vben/access'; +import { preferences } from '@vben/preferences'; + +import { message } from 'ant-design-vue'; + +import { getAllMenusApi } from '#/api'; +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue'); + +async function generateAccess(options: GenerateMenuAndRoutesOptions) { + const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue'); + + const layoutMap: ComponentRecordType = { + BasicLayout, + IFrameView, + }; + + return await generateAccessible(preferences.app.accessMode, { + ...options, + fetchMenuListAsync: async () => { + message.loading({ + content: `${$t('common.loadingMenu')}...`, + duration: 1.5, + }); + return await getAllMenusApi(); + }, + // 可以指定没有权限跳转403页面 + forbiddenComponent, + // 如果 route.meta.menuVisibleWithForbidden = true + layoutMap, + pageMap, + }); +} + +export { generateAccess }; diff --git a/apps/vben5/apps/web-antd/src/router/guard.ts b/apps/vben5/apps/web-antd/src/router/guard.ts new file mode 100644 index 000000000..fce5a892c --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/guard.ts @@ -0,0 +1,125 @@ +import type { Router } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { preferences } from '@vben/preferences'; +import { useAccessStore, useUserStore } from '@vben/stores'; +import { startProgress, stopProgress } from '@vben/utils'; + +import { accessRoutes, coreRouteNames } from '#/router/routes'; +import { useAuthStore } from '#/store'; + +import { generateAccess } from './access'; + +/** + * 通用守卫配置 + * @param router + */ +function setupCommonGuard(router: Router) { + // 记录已经加载的页面 + const loadedPaths = new Set(); + + router.beforeEach(async (to) => { + to.meta.loaded = loadedPaths.has(to.path); + + // 页面加载进度条 + if (!to.meta.loaded && preferences.transition.progress) { + startProgress(); + } + return true; + }); + + router.afterEach((to) => { + // 记录页面是否加载,如果已经加载,后续的页面切换动画等效果不在重复执行 + + loadedPaths.add(to.path); + + // 关闭页面加载进度条 + if (preferences.transition.progress) { + stopProgress(); + } + }); +} + +/** + * 权限访问守卫配置 + * @param router + */ +function setupAccessGuard(router: Router) { + router.beforeEach(async (to, from) => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const authStore = useAuthStore(); + + // 基本路由,这些路由不需要进入权限拦截 + if (coreRouteNames.includes(to.name as string)) { + if (to.path === LOGIN_PATH && accessStore.accessToken) { + return decodeURIComponent( + (to.query?.redirect as string) || DEFAULT_HOME_PATH, + ); + } + return true; + } + + // accessToken 检查 + if (!accessStore.accessToken) { + // 明确声明忽略权限访问权限,则可以访问 + if (to.meta.ignoreAccess) { + return true; + } + + // 没有访问权限,跳转登录页面 + if (to.fullPath !== LOGIN_PATH) { + return { + path: LOGIN_PATH, + // 如不需要,直接删除 query + query: { redirect: encodeURIComponent(to.fullPath) }, + // 携带当前跳转的页面,登录后重新跳转该页面 + replace: true, + }; + } + return to; + } + + // 是否已经生成过动态路由 + if (accessStore.isAccessChecked) { + return true; + } + + // 生成路由表 + // 当前登录用户拥有的角色标识列表 + const userInfo = userStore.userInfo || (await authStore.fetchUserInfo()); + const userRoles = userInfo.roles ?? []; + + // 生成菜单和路由 + const { accessibleMenus, accessibleRoutes } = await generateAccess({ + roles: userRoles, + router, + // 则会在菜单中显示,但是访问会被重定向到403 + routes: accessRoutes, + }); + + // 保存菜单信息和路由信息 + accessStore.setAccessMenus(accessibleMenus); + accessStore.setAccessRoutes(accessibleRoutes); + accessStore.setIsAccessChecked(true); + const redirectPath = (from.query.redirect ?? to.fullPath) as string; + + return { + ...router.resolve(decodeURIComponent(redirectPath)), + replace: true, + }; + }); +} + +/** + * 项目守卫配置 + * @param router + */ +function createRouterGuard(router: Router) { + /** 通用 */ + setupCommonGuard(router); + /** 权限访问 */ + setupAccessGuard(router); +} + +export { createRouterGuard }; diff --git a/apps/vben5/apps/web-antd/src/router/index.ts b/apps/vben5/apps/web-antd/src/router/index.ts new file mode 100644 index 000000000..484023034 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/index.ts @@ -0,0 +1,37 @@ +import { + createRouter, + createWebHashHistory, + createWebHistory, +} from 'vue-router'; + +import { resetStaticRoutes } from '@vben/utils'; + +import { createRouterGuard } from './guard'; +import { routes } from './routes'; + +/** + * @zh_CN 创建vue-router实例 + */ +const router = createRouter({ + history: + import.meta.env.VITE_ROUTER_HISTORY === 'hash' + ? createWebHashHistory(import.meta.env.VITE_BASE) + : createWebHistory(import.meta.env.VITE_BASE), + // 应该添加到路由的初始路由列表。 + routes, + scrollBehavior: (to, _from, savedPosition) => { + if (savedPosition) { + return savedPosition; + } + return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 }; + }, + // 是否应该禁止尾部斜杠。 + // strict: true, +}); + +const resetRoutes = () => resetStaticRoutes(router, routes); + +// 创建路由守卫 +createRouterGuard(router); + +export { resetRoutes, router }; diff --git a/apps/vben5/apps/web-antd/src/router/routes/core.ts b/apps/vben5/apps/web-antd/src/router/routes/core.ts new file mode 100644 index 000000000..fe030a9a2 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/routes/core.ts @@ -0,0 +1,88 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; + +import { AuthPageLayout } from '#/layouts'; +import { $t } from '#/locales'; +import Login from '#/views/_core/authentication/login.vue'; + +/** 全局404页面 */ +const fallbackNotFoundRoute: RouteRecordRaw = { + component: () => import('#/views/_core/fallback/not-found.vue'), + meta: { + hideInBreadcrumb: true, + hideInMenu: true, + hideInTab: true, + title: '404', + }, + name: 'FallbackNotFound', + path: '/:path(.*)*', +}; + +/** 基本路由,这些路由是必须存在的 */ +const coreRoutes: RouteRecordRaw[] = [ + { + meta: { + title: 'Root', + }, + name: 'Root', + path: '/', + redirect: DEFAULT_HOME_PATH, + }, + { + component: AuthPageLayout, + meta: { + hideInTab: true, + title: 'Authentication', + }, + name: 'Authentication', + path: '/auth', + redirect: LOGIN_PATH, + children: [ + { + name: 'Login', + path: 'login', + component: Login, + meta: { + title: $t('page.auth.login'), + }, + }, + { + name: 'CodeLogin', + path: 'code-login', + component: () => import('#/views/_core/authentication/code-login.vue'), + meta: { + title: $t('page.auth.codeLogin'), + }, + }, + { + name: 'QrCodeLogin', + path: 'qrcode-login', + component: () => + import('#/views/_core/authentication/qrcode-login.vue'), + meta: { + title: $t('page.auth.qrcodeLogin'), + }, + }, + { + name: 'ForgetPassword', + path: 'forget-password', + component: () => + import('#/views/_core/authentication/forget-password.vue'), + meta: { + title: $t('page.auth.forgetPassword'), + }, + }, + { + name: 'Register', + path: 'register', + component: () => import('#/views/_core/authentication/register.vue'), + meta: { + title: $t('page.auth.register'), + }, + }, + ], + }, +]; + +export { coreRoutes, fallbackNotFoundRoute }; diff --git a/apps/vben5/apps/web-antd/src/router/routes/index.ts b/apps/vben5/apps/web-antd/src/router/routes/index.ts new file mode 100644 index 000000000..e6fb14402 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/routes/index.ts @@ -0,0 +1,37 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { mergeRouteModules, traverseTreeValues } from '@vben/utils'; + +import { coreRoutes, fallbackNotFoundRoute } from './core'; + +const dynamicRouteFiles = import.meta.glob('./modules/**/*.ts', { + eager: true, +}); + +// 有需要可以自行打开注释,并创建文件夹 +// const externalRouteFiles = import.meta.glob('./external/**/*.ts', { eager: true }); +// const staticRouteFiles = import.meta.glob('./static/**/*.ts', { eager: true }); + +/** 动态路由 */ +const dynamicRoutes: RouteRecordRaw[] = mergeRouteModules(dynamicRouteFiles); + +/** 外部路由列表,访问这些页面可以不需要Layout,可能用于内嵌在别的系统(不会显示在菜单中) */ +// const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles); +// const staticRoutes: RouteRecordRaw[] = mergeRouteModules(staticRouteFiles); +const staticRoutes: RouteRecordRaw[] = []; +const externalRoutes: RouteRecordRaw[] = []; + +/** 路由列表,由基本路由、外部路由和404兜底路由组成 + * 无需走权限验证(会一直显示在菜单中) */ +const routes: RouteRecordRaw[] = [ + ...coreRoutes, + ...externalRoutes, + fallbackNotFoundRoute, +]; + +/** 基本路由列表,这些路由不需要进入权限拦截 */ +const coreRouteNames = traverseTreeValues(coreRoutes, (route) => route.name); + +/** 有权限校验的路由列表,包含动态路由和静态路由 */ +const accessRoutes = [...dynamicRoutes, ...staticRoutes]; +export { accessRoutes, coreRouteNames, routes }; diff --git a/apps/vben5/apps/web-antd/src/router/routes/modules/dashboard.ts b/apps/vben5/apps/web-antd/src/router/routes/modules/dashboard.ts new file mode 100644 index 000000000..1bddab9db --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/routes/modules/dashboard.ts @@ -0,0 +1,40 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'lucide:layout-dashboard', + order: -1, + title: $t('page.dashboard.title'), + }, + name: 'Dashboard', + path: '/', + children: [ + { + name: 'Analytics', + path: '/analytics', + component: () => import('#/views/dashboard/analytics/index.vue'), + meta: { + affixTab: true, + icon: 'lucide:area-chart', + title: $t('page.dashboard.analytics'), + }, + }, + { + name: 'Workspace', + path: '/workspace', + component: () => import('#/views/dashboard/workspace/index.vue'), + meta: { + icon: 'carbon:workspace', + title: $t('page.dashboard.workspace'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-antd/src/router/routes/modules/demos.ts b/apps/vben5/apps/web-antd/src/router/routes/modules/demos.ts new file mode 100644 index 000000000..32bb338e0 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/routes/modules/demos.ts @@ -0,0 +1,30 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'ic:baseline-view-in-ar', + keepAlive: true, + order: 1000, + title: $t('demos.title'), + }, + name: 'Demos', + path: '/demos', + children: [ + { + meta: { + title: $t('demos.antd'), + }, + name: 'AntDesignDemos', + path: '/demos/ant-design', + component: () => import('#/views/demos/antd/index.vue'), + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-antd/src/router/routes/modules/vben.ts b/apps/vben5/apps/web-antd/src/router/routes/modules/vben.ts new file mode 100644 index 000000000..210e8610f --- /dev/null +++ b/apps/vben5/apps/web-antd/src/router/routes/modules/vben.ts @@ -0,0 +1,81 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { + VBEN_DOC_URL, + VBEN_ELE_PREVIEW_URL, + VBEN_GITHUB_URL, + VBEN_LOGO_URL, + VBEN_NAIVE_PREVIEW_URL, +} from '@vben/constants'; + +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + badgeType: 'dot', + icon: VBEN_LOGO_URL, + order: 9999, + title: $t('demos.vben.title'), + }, + name: 'VbenProject', + path: '/vben-admin', + children: [ + { + name: 'VbenAbout', + path: '/vben-admin/about', + component: () => import('#/views/_core/about/index.vue'), + meta: { + icon: 'lucide:copyright', + title: $t('demos.vben.about'), + }, + }, + { + name: 'VbenDocument', + path: '/vben-admin/document', + component: IFrameView, + meta: { + icon: 'lucide:book-open-text', + link: VBEN_DOC_URL, + title: $t('demos.vben.document'), + }, + }, + { + name: 'VbenGithub', + path: '/vben-admin/github', + component: IFrameView, + meta: { + icon: 'mdi:github', + link: VBEN_GITHUB_URL, + title: 'Github', + }, + }, + { + name: 'VbenNaive', + path: '/vben-admin/naive', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: 'logos:naiveui', + link: VBEN_NAIVE_PREVIEW_URL, + title: $t('demos.vben.naive-ui'), + }, + }, + { + name: 'VbenElementPlus', + path: '/vben-admin/ele', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: 'logos:element', + link: VBEN_ELE_PREVIEW_URL, + title: $t('demos.vben.element-plus'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-antd/src/store/auth.ts b/apps/vben5/apps/web-antd/src/store/auth.ts new file mode 100644 index 000000000..9d64d2058 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/store/auth.ts @@ -0,0 +1,115 @@ +import type { Recordable, UserInfo } from '@vben/types'; + +import { ref } from 'vue'; +import { useRouter } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores'; + +import { notification } from 'ant-design-vue'; +import { defineStore } from 'pinia'; + +import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api'; +import { $t } from '#/locales'; + +export const useAuthStore = defineStore('auth', () => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const router = useRouter(); + + const loginLoading = ref(false); + + /** + * 异步处理登录操作 + * Asynchronously handle the login process + * @param params 登录表单数据 + */ + async function authLogin( + params: Recordable, + onSuccess?: () => Promise | void, + ) { + // 异步处理用户登录操作并获取 accessToken + let userInfo: null | UserInfo = null; + try { + loginLoading.value = true; + const { accessToken } = await loginApi(params); + + // 如果成功获取到 accessToken + if (accessToken) { + accessStore.setAccessToken(accessToken); + + // 获取用户信息并存储到 accessStore 中 + const [fetchUserInfoResult, accessCodes] = await Promise.all([ + fetchUserInfo(), + getAccessCodesApi(), + ]); + + userInfo = fetchUserInfoResult; + + userStore.setUserInfo(userInfo); + accessStore.setAccessCodes(accessCodes); + + if (accessStore.loginExpired) { + accessStore.setLoginExpired(false); + } else { + onSuccess + ? await onSuccess?.() + : await router.push(userInfo.homePath || DEFAULT_HOME_PATH); + } + + if (userInfo?.realName) { + notification.success({ + description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`, + duration: 3, + message: $t('authentication.loginSuccess'), + }); + } + } + } finally { + loginLoading.value = false; + } + + return { + userInfo, + }; + } + + async function logout(redirect: boolean = true) { + try { + await logoutApi(); + } catch { + // 不做任何处理 + } + resetAllStores(); + accessStore.setLoginExpired(false); + + // 回登录页带上当前路由地址 + await router.replace({ + path: LOGIN_PATH, + query: redirect + ? { + redirect: encodeURIComponent(router.currentRoute.value.fullPath), + } + : {}, + }); + } + + async function fetchUserInfo() { + let userInfo: null | UserInfo = null; + userInfo = await getUserInfoApi(); + userStore.setUserInfo(userInfo); + return userInfo; + } + + function $reset() { + loginLoading.value = false; + } + + return { + $reset, + authLogin, + fetchUserInfo, + loginLoading, + logout, + }; +}); diff --git a/apps/vben5/apps/web-antd/src/store/index.ts b/apps/vben5/apps/web-antd/src/store/index.ts new file mode 100644 index 000000000..269586ee8 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/store/index.ts @@ -0,0 +1 @@ +export * from './auth'; diff --git a/apps/vben5/apps/web-antd/src/views/_core/README.md b/apps/vben5/apps/web-antd/src/views/_core/README.md new file mode 100644 index 000000000..8248afe6c --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/README.md @@ -0,0 +1,3 @@ +# \_core + +此目录包含应用程序正常运行所需的基本视图。这些视图是应用程序布局中使用的视图。 diff --git a/apps/vben5/apps/web-antd/src/views/_core/about/index.vue b/apps/vben5/apps/web-antd/src/views/_core/about/index.vue new file mode 100644 index 000000000..0ee524335 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/about/index.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/authentication/code-login.vue b/apps/vben5/apps/web-antd/src/views/_core/authentication/code-login.vue new file mode 100644 index 000000000..556b273af --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/authentication/code-login.vue @@ -0,0 +1,65 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/authentication/forget-password.vue b/apps/vben5/apps/web-antd/src/views/_core/authentication/forget-password.vue new file mode 100644 index 000000000..fef0d4279 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/authentication/forget-password.vue @@ -0,0 +1,43 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/authentication/login.vue b/apps/vben5/apps/web-antd/src/views/_core/authentication/login.vue new file mode 100644 index 000000000..099e4c8c0 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/authentication/login.vue @@ -0,0 +1,98 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/authentication/qrcode-login.vue b/apps/vben5/apps/web-antd/src/views/_core/authentication/qrcode-login.vue new file mode 100644 index 000000000..23f5f2dad --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/authentication/qrcode-login.vue @@ -0,0 +1,10 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/authentication/register.vue b/apps/vben5/apps/web-antd/src/views/_core/authentication/register.vue new file mode 100644 index 000000000..b1a5de726 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/authentication/register.vue @@ -0,0 +1,96 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/fallback/coming-soon.vue b/apps/vben5/apps/web-antd/src/views/_core/fallback/coming-soon.vue new file mode 100644 index 000000000..f394930f2 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/fallback/coming-soon.vue @@ -0,0 +1,7 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/fallback/forbidden.vue b/apps/vben5/apps/web-antd/src/views/_core/fallback/forbidden.vue new file mode 100644 index 000000000..8ea65fedb --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/fallback/forbidden.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/fallback/internal-error.vue b/apps/vben5/apps/web-antd/src/views/_core/fallback/internal-error.vue new file mode 100644 index 000000000..819a47d5e --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/fallback/internal-error.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/fallback/not-found.vue b/apps/vben5/apps/web-antd/src/views/_core/fallback/not-found.vue new file mode 100644 index 000000000..4d178e9cb --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/fallback/not-found.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/_core/fallback/offline.vue b/apps/vben5/apps/web-antd/src/views/_core/fallback/offline.vue new file mode 100644 index 000000000..5de4a88de --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/_core/fallback/offline.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-trends.vue b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-trends.vue new file mode 100644 index 000000000..fadfc917c --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-trends.vue @@ -0,0 +1,100 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-data.vue b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-data.vue new file mode 100644 index 000000000..30c4265df --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-data.vue @@ -0,0 +1,84 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-sales.vue b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-sales.vue new file mode 100644 index 000000000..260520b84 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-sales.vue @@ -0,0 +1,48 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-source.vue b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-source.vue new file mode 100644 index 000000000..e0d0aab5e --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits-source.vue @@ -0,0 +1,67 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits.vue b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits.vue new file mode 100644 index 000000000..7e1f14ee6 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/analytics-visits.vue @@ -0,0 +1,57 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/analytics/index.vue b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/index.vue new file mode 100644 index 000000000..00b34df1e --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/analytics/index.vue @@ -0,0 +1,90 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/dashboard/workspace/index.vue b/apps/vben5/apps/web-antd/src/views/dashboard/workspace/index.vue new file mode 100644 index 000000000..b95d61381 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/dashboard/workspace/index.vue @@ -0,0 +1,266 @@ + + + diff --git a/apps/vben5/apps/web-antd/src/views/demos/antd/index.vue b/apps/vben5/apps/web-antd/src/views/demos/antd/index.vue new file mode 100644 index 000000000..b3b05cc15 --- /dev/null +++ b/apps/vben5/apps/web-antd/src/views/demos/antd/index.vue @@ -0,0 +1,66 @@ + + + diff --git a/apps/vben5/apps/web-antd/tailwind.config.mjs b/apps/vben5/apps/web-antd/tailwind.config.mjs new file mode 100644 index 000000000..f17f556fa --- /dev/null +++ b/apps/vben5/apps/web-antd/tailwind.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config'; diff --git a/apps/vben5/apps/web-antd/tsconfig.json b/apps/vben5/apps/web-antd/tsconfig.json new file mode 100644 index 000000000..02c287fe6 --- /dev/null +++ b/apps/vben5/apps/web-antd/tsconfig.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/web-app.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "#/*": ["./src/*"] + } + }, + "references": [{ "path": "./tsconfig.node.json" }], + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/apps/vben5/apps/web-antd/tsconfig.node.json b/apps/vben5/apps/web-antd/tsconfig.node.json new file mode 100644 index 000000000..c2f0d86cc --- /dev/null +++ b/apps/vben5/apps/web-antd/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/node.json", + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "noEmit": false + }, + "include": ["vite.config.mts"] +} diff --git a/apps/vben5/apps/web-antd/vite.config.mts b/apps/vben5/apps/web-antd/vite.config.mts new file mode 100644 index 000000000..b6360f1d4 --- /dev/null +++ b/apps/vben5/apps/web-antd/vite.config.mts @@ -0,0 +1,20 @@ +import { defineConfig } from '@vben/vite-config'; + +export default defineConfig(async () => { + return { + application: {}, + vite: { + server: { + proxy: { + '/api': { + changeOrigin: true, + rewrite: (path) => path.replace(/^\/api/, ''), + // mock代理目标地址 + target: 'http://localhost:5320/api', + ws: true, + }, + }, + }, + }, + }; +}); diff --git a/apps/vben5/apps/web-ele/.env b/apps/vben5/apps/web-ele/.env new file mode 100644 index 000000000..87cb3df14 --- /dev/null +++ b/apps/vben5/apps/web-ele/.env @@ -0,0 +1,5 @@ +# 应用标题 +VITE_APP_TITLE=Vben Admin Ele + +# 应用命名空间,用于缓存、store等功能的前缀,确保隔离 +VITE_APP_NAMESPACE=vben-web-ele diff --git a/apps/vben5/apps/web-ele/.env.analyze b/apps/vben5/apps/web-ele/.env.analyze new file mode 100644 index 000000000..ffafa8dd5 --- /dev/null +++ b/apps/vben5/apps/web-ele/.env.analyze @@ -0,0 +1,7 @@ +# public path +VITE_BASE=/ + +# Basic interface address SPA +VITE_GLOB_API_URL=/api + +VITE_VISUALIZER=true diff --git a/apps/vben5/apps/web-ele/.env.development b/apps/vben5/apps/web-ele/.env.development new file mode 100644 index 000000000..8bcb432e6 --- /dev/null +++ b/apps/vben5/apps/web-ele/.env.development @@ -0,0 +1,16 @@ +# 端口号 +VITE_PORT=5777 + +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=/api + +# 是否开启 Nitro Mock服务,true 为开启,false 为关闭 +VITE_NITRO_MOCK=true + +# 是否打开 devtools,true 为打开,false 为关闭 +VITE_DEVTOOLS=false + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true diff --git a/apps/vben5/apps/web-ele/.env.production b/apps/vben5/apps/web-ele/.env.production new file mode 100644 index 000000000..5375847a6 --- /dev/null +++ b/apps/vben5/apps/web-ele/.env.production @@ -0,0 +1,19 @@ +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=https://mock-napi.vben.pro/api + +# 是否开启压缩,可以设置为 none, brotli, gzip +VITE_COMPRESS=none + +# 是否开启 PWA +VITE_PWA=false + +# vue-router 的模式 +VITE_ROUTER_HISTORY=hash + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true + +# 打包后是否生成dist.zip +VITE_ARCHIVER=true diff --git a/apps/vben5/apps/web-ele/index.html b/apps/vben5/apps/web-ele/index.html new file mode 100644 index 000000000..2b59b8d75 --- /dev/null +++ b/apps/vben5/apps/web-ele/index.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + <%= VITE_APP_TITLE %> + + + + +
+ + + diff --git a/apps/vben5/apps/web-ele/package.json b/apps/vben5/apps/web-ele/package.json new file mode 100644 index 000000000..430156951 --- /dev/null +++ b/apps/vben5/apps/web-ele/package.json @@ -0,0 +1,53 @@ +{ + "name": "@vben/web-ele", + "version": "5.4.8", + "homepage": "https://vben.pro", + "bugs": "https://github.com/vbenjs/vue-vben-admin/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/vbenjs/vue-vben-admin.git", + "directory": "apps/web-ele" + }, + "license": "MIT", + "author": { + "name": "vben", + "email": "ann.vben@gmail.com", + "url": "https://github.com/anncwb" + }, + "type": "module", + "scripts": { + "build": "pnpm vite build --mode production", + "build:analyze": "pnpm vite build --mode analyze", + "dev": "pnpm vite --mode development", + "preview": "vite preview", + "typecheck": "vue-tsc --noEmit --skipLibCheck" + }, + "imports": { + "#/*": "./src/*" + }, + "dependencies": { + "@vben/access": "workspace:*", + "@vben/common-ui": "workspace:*", + "@vben/constants": "workspace:*", + "@vben/hooks": "workspace:*", + "@vben/icons": "workspace:*", + "@vben/layouts": "workspace:*", + "@vben/locales": "workspace:*", + "@vben/plugins": "workspace:*", + "@vben/preferences": "workspace:*", + "@vben/request": "workspace:*", + "@vben/stores": "workspace:*", + "@vben/styles": "workspace:*", + "@vben/types": "workspace:*", + "@vben/utils": "workspace:*", + "@vueuse/core": "catalog:", + "dayjs": "catalog:", + "element-plus": "catalog:", + "pinia": "catalog:", + "vue": "catalog:", + "vue-router": "catalog:" + }, + "devDependencies": { + "unplugin-element-plus": "catalog:" + } +} diff --git a/apps/vben5/apps/web-ele/postcss.config.mjs b/apps/vben5/apps/web-ele/postcss.config.mjs new file mode 100644 index 000000000..3d8070455 --- /dev/null +++ b/apps/vben5/apps/web-ele/postcss.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config/postcss'; diff --git a/apps/vben5/apps/web-ele/public/favicon.ico b/apps/vben5/apps/web-ele/public/favicon.ico new file mode 100644 index 000000000..fcf9818e2 Binary files /dev/null and b/apps/vben5/apps/web-ele/public/favicon.ico differ diff --git a/apps/vben5/apps/web-ele/src/adapter/component/index.ts b/apps/vben5/apps/web-ele/src/adapter/component/index.ts new file mode 100644 index 000000000..ebf9dd3e1 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/adapter/component/index.ts @@ -0,0 +1,106 @@ +/** + * 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用 + * 可用于 vben-form、vben-modal、vben-drawer 等组件使用, + */ + +import type { BaseFormComponentType } from '@vben/common-ui'; + +import type { Component, SetupContext } from 'vue'; +import { h } from 'vue'; + +import { globalShareState } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { + ElButton, + ElCheckbox, + ElCheckboxGroup, + ElDatePicker, + ElDivider, + ElInput, + ElInputNumber, + ElNotification, + ElRadioGroup, + ElSelect, + ElSpace, + ElSwitch, + ElTimePicker, + ElTreeSelect, + ElUpload, +} from 'element-plus'; + +const withDefaultPlaceholder = ( + component: T, + type: 'input' | 'select', +) => { + return (props: any, { attrs, slots }: Omit) => { + const placeholder = props?.placeholder || $t(`ui.placeholder.${type}`); + return h(component, { ...props, ...attrs, placeholder }, slots); + }; +}; + +// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明 +export type ComponentType = + | 'Checkbox' + | 'CheckboxGroup' + | 'DatePicker' + | 'Divider' + | 'Input' + | 'InputNumber' + | 'RadioGroup' + | 'Select' + | 'Space' + | 'Switch' + | 'TimePicker' + | 'TreeSelect' + | 'Upload' + | BaseFormComponentType; + +async function initComponentAdapter() { + const components: Partial> = { + // 如果你的组件体积比较大,可以使用异步加载 + // Button: () => + // import('xxx').then((res) => res.Button), + + Checkbox: ElCheckbox, + CheckboxGroup: ElCheckboxGroup, + // 自定义默认按钮 + DefaultButton: (props, { attrs, slots }) => { + return h(ElButton, { ...props, attrs, type: 'info' }, slots); + }, + // 自定义主要按钮 + PrimaryButton: (props, { attrs, slots }) => { + return h(ElButton, { ...props, attrs, type: 'primary' }, slots); + }, + Divider: ElDivider, + Input: withDefaultPlaceholder(ElInput, 'input'), + InputNumber: withDefaultPlaceholder(ElInputNumber, 'input'), + RadioGroup: ElRadioGroup, + Select: withDefaultPlaceholder(ElSelect, 'select'), + Space: ElSpace, + Switch: ElSwitch, + TimePicker: ElTimePicker, + DatePicker: ElDatePicker, + TreeSelect: withDefaultPlaceholder(ElTreeSelect, 'select'), + Upload: ElUpload, + }; + + // 将组件注册到全局共享状态中 + globalShareState.setComponents(components); + + // 定义全局共享状态中的消息提示 + globalShareState.defineMessage({ + // 复制成功消息提示 + copyPreferencesSuccess: (title, content) => { + ElNotification({ + title, + message: content, + position: 'bottom-right', + duration: 0, + type: 'success', + }); + }, + }); +} + +export { initComponentAdapter }; diff --git a/apps/vben5/apps/web-ele/src/adapter/form.ts b/apps/vben5/apps/web-ele/src/adapter/form.ts new file mode 100644 index 000000000..1b6e04719 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/adapter/form.ts @@ -0,0 +1,38 @@ +import type { + VbenFormSchema as FormSchema, + VbenFormProps, +} from '@vben/common-ui'; + +import type { ComponentType } from './component'; + +import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +setupVbenForm({ + config: { + modelPropNameMap: { + Upload: 'fileList', + }, + }, + defineRules: { + required: (value, _params, ctx) => { + if (value === undefined || value === null || value.length === 0) { + return $t('ui.formRules.required', [ctx.label]); + } + return true; + }, + selectRequired: (value, _params, ctx) => { + if (value === undefined || value === null) { + return $t('ui.formRules.selectRequired', [ctx.label]); + } + return true; + }, + }, +}); + +const useVbenForm = useForm; + +export { useVbenForm, z }; + +export type VbenFormSchema = FormSchema; +export type { VbenFormProps }; diff --git a/apps/vben5/apps/web-ele/src/adapter/vxe-table.ts b/apps/vben5/apps/web-ele/src/adapter/vxe-table.ts new file mode 100644 index 000000000..44b31eaed --- /dev/null +++ b/apps/vben5/apps/web-ele/src/adapter/vxe-table.ts @@ -0,0 +1,68 @@ +import { h } from 'vue'; + +import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table'; + +import { ElButton, ElImage } from 'element-plus'; + +import { useVbenForm } from './form'; + +setupVbenVxeTable({ + configVxeTable: (vxeUI) => { + vxeUI.setConfig({ + grid: { + align: 'center', + border: false, + columnConfig: { + resizable: true, + }, + minHeight: 180, + formConfig: { + // 全局禁用vxe-table的表单配置,使用formOptions + enabled: false, + }, + proxyConfig: { + autoLoad: true, + response: { + result: 'items', + total: 'total', + list: 'items', + }, + showActiveMsg: true, + showResponseMsg: false, + }, + round: true, + showOverflow: true, + size: 'small', + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellImage' }, + vxeUI.renderer.add('CellImage', { + renderTableDefault(_renderOpts, params) { + const { column, row } = params; + const src = row[column.field]; + return h(ElImage, { src, previewSrcList: [src] }); + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellLink' }, + vxeUI.renderer.add('CellLink', { + renderTableDefault(renderOpts) { + const { props } = renderOpts; + return h( + ElButton, + { size: 'small', link: true }, + { default: () => props?.text }, + ); + }, + }); + + // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化 + // vxeUI.formats.add + }, + useVbenForm, +}); + +export { useVbenVxeGrid }; + +export type * from '@vben/plugins/vxe-table'; diff --git a/apps/vben5/apps/web-ele/src/api/core/auth.ts b/apps/vben5/apps/web-ele/src/api/core/auth.ts new file mode 100644 index 000000000..71d9f9943 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/api/core/auth.ts @@ -0,0 +1,51 @@ +import { baseRequestClient, requestClient } from '#/api/request'; + +export namespace AuthApi { + /** 登录接口参数 */ + export interface LoginParams { + password?: string; + username?: string; + } + + /** 登录接口返回值 */ + export interface LoginResult { + accessToken: string; + } + + export interface RefreshTokenResult { + data: string; + status: number; + } +} + +/** + * 登录 + */ +export async function loginApi(data: AuthApi.LoginParams) { + return requestClient.post('/auth/login', data); +} + +/** + * 刷新accessToken + */ +export async function refreshTokenApi() { + return baseRequestClient.post('/auth/refresh', { + withCredentials: true, + }); +} + +/** + * 退出登录 + */ +export async function logoutApi() { + return baseRequestClient.post('/auth/logout', { + withCredentials: true, + }); +} + +/** + * 获取用户权限码 + */ +export async function getAccessCodesApi() { + return requestClient.get('/auth/codes'); +} diff --git a/apps/vben5/apps/web-ele/src/api/core/index.ts b/apps/vben5/apps/web-ele/src/api/core/index.ts new file mode 100644 index 000000000..28a5aef47 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/api/core/index.ts @@ -0,0 +1,3 @@ +export * from './auth'; +export * from './menu'; +export * from './user'; diff --git a/apps/vben5/apps/web-ele/src/api/core/menu.ts b/apps/vben5/apps/web-ele/src/api/core/menu.ts new file mode 100644 index 000000000..9ef60b11c --- /dev/null +++ b/apps/vben5/apps/web-ele/src/api/core/menu.ts @@ -0,0 +1,10 @@ +import type { RouteRecordStringComponent } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户所有菜单 + */ +export async function getAllMenusApi() { + return requestClient.get('/menu/all'); +} diff --git a/apps/vben5/apps/web-ele/src/api/core/user.ts b/apps/vben5/apps/web-ele/src/api/core/user.ts new file mode 100644 index 000000000..7e28ea848 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/api/core/user.ts @@ -0,0 +1,10 @@ +import type { UserInfo } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户信息 + */ +export async function getUserInfoApi() { + return requestClient.get('/user/info'); +} diff --git a/apps/vben5/apps/web-ele/src/api/index.ts b/apps/vben5/apps/web-ele/src/api/index.ts new file mode 100644 index 000000000..4b0e04137 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/api/index.ts @@ -0,0 +1 @@ +export * from './core'; diff --git a/apps/vben5/apps/web-ele/src/api/request.ts b/apps/vben5/apps/web-ele/src/api/request.ts new file mode 100644 index 000000000..a9514c817 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/api/request.ts @@ -0,0 +1,113 @@ +/** + * 该文件可自行根据业务逻辑进行调整 + */ +import type { HttpResponse } from '@vben/request'; + +import { useAppConfig } from '@vben/hooks'; +import { preferences } from '@vben/preferences'; +import { + authenticateResponseInterceptor, + errorMessageResponseInterceptor, + RequestClient, +} from '@vben/request'; +import { useAccessStore } from '@vben/stores'; + +import { ElMessage } from 'element-plus'; + +import { useAuthStore } from '#/store'; + +import { refreshTokenApi } from './core'; + +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); + +function createRequestClient(baseURL: string) { + const client = new RequestClient({ + baseURL, + }); + + /** + * 重新认证逻辑 + */ + async function doReAuthenticate() { + console.warn('Access token or refresh token is invalid or expired. '); + const accessStore = useAccessStore(); + const authStore = useAuthStore(); + accessStore.setAccessToken(null); + if ( + preferences.app.loginExpiredMode === 'modal' && + accessStore.isAccessChecked + ) { + accessStore.setLoginExpired(true); + } else { + await authStore.logout(); + } + } + + /** + * 刷新token逻辑 + */ + async function doRefreshToken() { + const accessStore = useAccessStore(); + const resp = await refreshTokenApi(); + const newToken = resp.data; + accessStore.setAccessToken(newToken); + return newToken; + } + + function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; + } + + // 请求头处理 + client.addRequestInterceptor({ + fulfilled: async (config) => { + const accessStore = useAccessStore(); + + config.headers.Authorization = formatToken(accessStore.accessToken); + config.headers['Accept-Language'] = preferences.app.locale; + return config; + }, + }); + + // response数据解构 + client.addResponseInterceptor({ + fulfilled: (response) => { + const { data: responseData, status } = response; + + const { code, data } = responseData; + if (status >= 200 && status < 400 && code === 0) { + return data; + } + throw Object.assign({}, response, { response }); + }, + }); + + // token过期的处理 + client.addResponseInterceptor( + authenticateResponseInterceptor({ + client, + doReAuthenticate, + doRefreshToken, + enableRefreshToken: preferences.app.enableRefreshToken, + formatToken, + }), + ); + + // 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里 + client.addResponseInterceptor( + errorMessageResponseInterceptor((msg: string, error) => { + // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg + // 当前mock接口返回的错误字段是 error 或者 message + const responseData = error?.response?.data ?? {}; + const errorMessage = responseData?.error ?? responseData?.message ?? ''; + // 如果没有错误信息,则会根据状态码进行提示 + ElMessage.error(errorMessage || msg); + }), + ); + + return client; +} + +export const requestClient = createRequestClient(apiURL); + +export const baseRequestClient = new RequestClient({ baseURL: apiURL }); diff --git a/apps/vben5/apps/web-ele/src/app.vue b/apps/vben5/apps/web-ele/src/app.vue new file mode 100644 index 000000000..1217658da --- /dev/null +++ b/apps/vben5/apps/web-ele/src/app.vue @@ -0,0 +1,17 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/bootstrap.ts b/apps/vben5/apps/web-ele/src/bootstrap.ts new file mode 100644 index 000000000..de1884730 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/bootstrap.ts @@ -0,0 +1,47 @@ +import { createApp, watchEffect } from 'vue'; + +import { registerAccessDirective } from '@vben/access'; +import { preferences } from '@vben/preferences'; +import { initStores } from '@vben/stores'; +import '@vben/styles'; +import '@vben/styles/ele'; + +import { useTitle } from '@vueuse/core'; + +import { $t, setupI18n } from '#/locales'; + +import { initComponentAdapter } from './adapter/component'; +import App from './app.vue'; +import { router } from './router'; + +async function bootstrap(namespace: string) { + // 初始化组件适配器 + await initComponentAdapter(); + const app = createApp(App); + + // 国际化 i18n 配置 + await setupI18n(app); + + // 配置 pinia-tore + await initStores(app, { namespace }); + + // 安装权限指令 + registerAccessDirective(app); + + // 配置路由及路由守卫 + app.use(router); + + // 动态更新标题 + watchEffect(() => { + if (preferences.app.dynamicTitle) { + const routeTitle = router.currentRoute.value.meta?.title; + const pageTitle = + (routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name; + useTitle(pageTitle); + } + }); + + app.mount('#app'); +} + +export { bootstrap }; diff --git a/apps/vben5/apps/web-ele/src/layouts/auth.vue b/apps/vben5/apps/web-ele/src/layouts/auth.vue new file mode 100644 index 000000000..18d415bc7 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/layouts/auth.vue @@ -0,0 +1,23 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/layouts/basic.vue b/apps/vben5/apps/web-ele/src/layouts/basic.vue new file mode 100644 index 000000000..51412956a --- /dev/null +++ b/apps/vben5/apps/web-ele/src/layouts/basic.vue @@ -0,0 +1,157 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/layouts/index.ts b/apps/vben5/apps/web-ele/src/layouts/index.ts new file mode 100644 index 000000000..a43207805 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/layouts/index.ts @@ -0,0 +1,6 @@ +const BasicLayout = () => import('./basic.vue'); +const AuthPageLayout = () => import('./auth.vue'); + +const IFrameView = () => import('@vben/layouts').then((m) => m.IFrameView); + +export { AuthPageLayout, BasicLayout, IFrameView }; diff --git a/apps/vben5/apps/web-ele/src/locales/README.md b/apps/vben5/apps/web-ele/src/locales/README.md new file mode 100644 index 000000000..7b451032e --- /dev/null +++ b/apps/vben5/apps/web-ele/src/locales/README.md @@ -0,0 +1,3 @@ +# locale + +每个app使用的国际化可能不同,这里用于扩展国际化的功能,例如扩展 dayjs、antd组件库的多语言切换,以及app本身的国际化文件。 diff --git a/apps/vben5/apps/web-ele/src/locales/index.ts b/apps/vben5/apps/web-ele/src/locales/index.ts new file mode 100644 index 000000000..1f3e22c91 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/locales/index.ts @@ -0,0 +1,100 @@ +import type { LocaleSetupOptions, SupportedLanguagesType } from '@vben/locales'; +import type { Language } from 'element-plus/es/locale'; + +import type { App } from 'vue'; +import { ref } from 'vue'; + +import { + $t, + setupI18n as coreSetup, + loadLocalesMapFromDir, +} from '@vben/locales'; +import { preferences } from '@vben/preferences'; + +import dayjs from 'dayjs'; +import enLocale from 'element-plus/es/locale/lang/en'; +import defaultLocale from 'element-plus/es/locale/lang/zh-cn'; + +const elementLocale = ref(defaultLocale); + +const modules = import.meta.glob('./langs/**/*.json'); + +const localesMap = loadLocalesMapFromDir( + /\.\/langs\/([^/]+)\/(.*)\.json$/, + modules, +); +/** + * 加载应用特有的语言包 + * 这里也可以改造为从服务端获取翻译数据 + * @param lang + */ +async function loadMessages(lang: SupportedLanguagesType) { + const [appLocaleMessages] = await Promise.all([ + localesMap[lang]?.(), + loadThirdPartyMessage(lang), + ]); + return appLocaleMessages?.default; +} + +/** + * 加载第三方组件库的语言包 + * @param lang + */ +async function loadThirdPartyMessage(lang: SupportedLanguagesType) { + await Promise.all([loadElementLocale(lang), loadDayjsLocale(lang)]); +} + +/** + * 加载dayjs的语言包 + * @param lang + */ +async function loadDayjsLocale(lang: SupportedLanguagesType) { + let locale; + switch (lang) { + case 'en-US': { + locale = await import('dayjs/locale/en'); + break; + } + case 'zh-CN': { + locale = await import('dayjs/locale/zh-cn'); + break; + } + // 默认使用英语 + default: { + locale = await import('dayjs/locale/en'); + } + } + if (locale) { + dayjs.locale(locale); + } else { + console.error(`Failed to load dayjs locale for ${lang}`); + } +} + +/** + * 加载element-plus的语言包 + * @param lang + */ +async function loadElementLocale(lang: SupportedLanguagesType) { + switch (lang) { + case 'en-US': { + elementLocale.value = enLocale; + break; + } + case 'zh-CN': { + elementLocale.value = defaultLocale; + break; + } + } +} + +async function setupI18n(app: App, options: LocaleSetupOptions = {}) { + await coreSetup(app, { + defaultLocale: preferences.app.locale, + loadMessages, + missingWarn: !import.meta.env.PROD, + ...options, + }); +} + +export { $t, elementLocale, setupI18n }; diff --git a/apps/vben5/apps/web-ele/src/locales/langs/en-US/demos.json b/apps/vben5/apps/web-ele/src/locales/langs/en-US/demos.json new file mode 100644 index 000000000..056da0dae --- /dev/null +++ b/apps/vben5/apps/web-ele/src/locales/langs/en-US/demos.json @@ -0,0 +1,12 @@ +{ + "title": "Demos", + "elementPlus": "Element Plus", + "vben": { + "title": "Project", + "about": "About", + "document": "Document", + "antdv": "Ant Design Vue Version", + "naive-ui": "Naive UI Version", + "element-plus": "Element Plus Version" + } +} diff --git a/apps/vben5/apps/web-ele/src/locales/langs/en-US/page.json b/apps/vben5/apps/web-ele/src/locales/langs/en-US/page.json new file mode 100644 index 000000000..618a258c0 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/locales/langs/en-US/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "Login", + "register": "Register", + "codeLogin": "Code Login", + "qrcodeLogin": "Qr Code Login", + "forgetPassword": "Forget Password" + }, + "dashboard": { + "title": "Dashboard", + "analytics": "Analytics", + "workspace": "Workspace" + } +} diff --git a/apps/vben5/apps/web-ele/src/locales/langs/zh-CN/demos.json b/apps/vben5/apps/web-ele/src/locales/langs/zh-CN/demos.json new file mode 100644 index 000000000..0620e16a1 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/locales/langs/zh-CN/demos.json @@ -0,0 +1,12 @@ +{ + "title": "演示", + "elementPlus": "Element Plus", + "vben": { + "title": "项目", + "about": "关于", + "document": "文档", + "antdv": "Ant Design Vue 版本", + "naive-ui": "Naive UI 版本", + "element-plus": "Element Plus 版本" + } +} diff --git a/apps/vben5/apps/web-ele/src/locales/langs/zh-CN/page.json b/apps/vben5/apps/web-ele/src/locales/langs/zh-CN/page.json new file mode 100644 index 000000000..4cb67081c --- /dev/null +++ b/apps/vben5/apps/web-ele/src/locales/langs/zh-CN/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "登录", + "register": "注册", + "codeLogin": "验证码登录", + "qrcodeLogin": "二维码登录", + "forgetPassword": "忘记密码" + }, + "dashboard": { + "title": "概览", + "analytics": "分析页", + "workspace": "工作台" + } +} diff --git a/apps/vben5/apps/web-ele/src/main.ts b/apps/vben5/apps/web-ele/src/main.ts new file mode 100644 index 000000000..5d728a02a --- /dev/null +++ b/apps/vben5/apps/web-ele/src/main.ts @@ -0,0 +1,31 @@ +import { initPreferences } from '@vben/preferences'; +import { unmountGlobalLoading } from '@vben/utils'; + +import { overridesPreferences } from './preferences'; + +/** + * 应用初始化完成之后再进行页面加载渲染 + */ +async function initApplication() { + // name用于指定项目唯一标识 + // 用于区分不同项目的偏好设置以及存储数据的key前缀以及其他一些需要隔离的数据 + const env = import.meta.env.PROD ? 'prod' : 'dev'; + const appVersion = import.meta.env.VITE_APP_VERSION; + const namespace = `${import.meta.env.VITE_APP_NAMESPACE}-${appVersion}-${env}`; + + // app偏好设置初始化 + await initPreferences({ + namespace, + overrides: overridesPreferences, + }); + + // 启动应用并挂载 + // vue应用主要逻辑及视图 + const { bootstrap } = await import('./bootstrap'); + await bootstrap(namespace); + + // 移除并销毁loading + unmountGlobalLoading(); +} + +initApplication(); diff --git a/apps/vben5/apps/web-ele/src/preferences.ts b/apps/vben5/apps/web-ele/src/preferences.ts new file mode 100644 index 000000000..b2e9ace43 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/preferences.ts @@ -0,0 +1,13 @@ +import { defineOverridesPreferences } from '@vben/preferences'; + +/** + * @description 项目配置文件 + * 只需要覆盖项目中的一部分配置,不需要的配置不用覆盖,会自动使用默认配置 + * !!! 更改配置后请清空缓存,否则可能不生效 + */ +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + name: import.meta.env.VITE_APP_TITLE, + }, +}); diff --git a/apps/vben5/apps/web-ele/src/router/access.ts b/apps/vben5/apps/web-ele/src/router/access.ts new file mode 100644 index 000000000..2d07c892b --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/access.ts @@ -0,0 +1,42 @@ +import type { + ComponentRecordType, + GenerateMenuAndRoutesOptions, +} from '@vben/types'; + +import { generateAccessible } from '@vben/access'; +import { preferences } from '@vben/preferences'; + +import { ElMessage } from 'element-plus'; + +import { getAllMenusApi } from '#/api'; +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue'); + +async function generateAccess(options: GenerateMenuAndRoutesOptions) { + const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue'); + + const layoutMap: ComponentRecordType = { + BasicLayout, + IFrameView, + }; + + return await generateAccessible(preferences.app.accessMode, { + ...options, + fetchMenuListAsync: async () => { + ElMessage({ + duration: 1500, + message: `${$t('common.loadingMenu')}...`, + }); + return await getAllMenusApi(); + }, + // 可以指定没有权限跳转403页面 + forbiddenComponent, + // 如果 route.meta.menuVisibleWithForbidden = true + layoutMap, + pageMap, + }); +} + +export { generateAccess }; diff --git a/apps/vben5/apps/web-ele/src/router/guard.ts b/apps/vben5/apps/web-ele/src/router/guard.ts new file mode 100644 index 000000000..fce5a892c --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/guard.ts @@ -0,0 +1,125 @@ +import type { Router } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { preferences } from '@vben/preferences'; +import { useAccessStore, useUserStore } from '@vben/stores'; +import { startProgress, stopProgress } from '@vben/utils'; + +import { accessRoutes, coreRouteNames } from '#/router/routes'; +import { useAuthStore } from '#/store'; + +import { generateAccess } from './access'; + +/** + * 通用守卫配置 + * @param router + */ +function setupCommonGuard(router: Router) { + // 记录已经加载的页面 + const loadedPaths = new Set(); + + router.beforeEach(async (to) => { + to.meta.loaded = loadedPaths.has(to.path); + + // 页面加载进度条 + if (!to.meta.loaded && preferences.transition.progress) { + startProgress(); + } + return true; + }); + + router.afterEach((to) => { + // 记录页面是否加载,如果已经加载,后续的页面切换动画等效果不在重复执行 + + loadedPaths.add(to.path); + + // 关闭页面加载进度条 + if (preferences.transition.progress) { + stopProgress(); + } + }); +} + +/** + * 权限访问守卫配置 + * @param router + */ +function setupAccessGuard(router: Router) { + router.beforeEach(async (to, from) => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const authStore = useAuthStore(); + + // 基本路由,这些路由不需要进入权限拦截 + if (coreRouteNames.includes(to.name as string)) { + if (to.path === LOGIN_PATH && accessStore.accessToken) { + return decodeURIComponent( + (to.query?.redirect as string) || DEFAULT_HOME_PATH, + ); + } + return true; + } + + // accessToken 检查 + if (!accessStore.accessToken) { + // 明确声明忽略权限访问权限,则可以访问 + if (to.meta.ignoreAccess) { + return true; + } + + // 没有访问权限,跳转登录页面 + if (to.fullPath !== LOGIN_PATH) { + return { + path: LOGIN_PATH, + // 如不需要,直接删除 query + query: { redirect: encodeURIComponent(to.fullPath) }, + // 携带当前跳转的页面,登录后重新跳转该页面 + replace: true, + }; + } + return to; + } + + // 是否已经生成过动态路由 + if (accessStore.isAccessChecked) { + return true; + } + + // 生成路由表 + // 当前登录用户拥有的角色标识列表 + const userInfo = userStore.userInfo || (await authStore.fetchUserInfo()); + const userRoles = userInfo.roles ?? []; + + // 生成菜单和路由 + const { accessibleMenus, accessibleRoutes } = await generateAccess({ + roles: userRoles, + router, + // 则会在菜单中显示,但是访问会被重定向到403 + routes: accessRoutes, + }); + + // 保存菜单信息和路由信息 + accessStore.setAccessMenus(accessibleMenus); + accessStore.setAccessRoutes(accessibleRoutes); + accessStore.setIsAccessChecked(true); + const redirectPath = (from.query.redirect ?? to.fullPath) as string; + + return { + ...router.resolve(decodeURIComponent(redirectPath)), + replace: true, + }; + }); +} + +/** + * 项目守卫配置 + * @param router + */ +function createRouterGuard(router: Router) { + /** 通用 */ + setupCommonGuard(router); + /** 权限访问 */ + setupAccessGuard(router); +} + +export { createRouterGuard }; diff --git a/apps/vben5/apps/web-ele/src/router/index.ts b/apps/vben5/apps/web-ele/src/router/index.ts new file mode 100644 index 000000000..484023034 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/index.ts @@ -0,0 +1,37 @@ +import { + createRouter, + createWebHashHistory, + createWebHistory, +} from 'vue-router'; + +import { resetStaticRoutes } from '@vben/utils'; + +import { createRouterGuard } from './guard'; +import { routes } from './routes'; + +/** + * @zh_CN 创建vue-router实例 + */ +const router = createRouter({ + history: + import.meta.env.VITE_ROUTER_HISTORY === 'hash' + ? createWebHashHistory(import.meta.env.VITE_BASE) + : createWebHistory(import.meta.env.VITE_BASE), + // 应该添加到路由的初始路由列表。 + routes, + scrollBehavior: (to, _from, savedPosition) => { + if (savedPosition) { + return savedPosition; + } + return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 }; + }, + // 是否应该禁止尾部斜杠。 + // strict: true, +}); + +const resetRoutes = () => resetStaticRoutes(router, routes); + +// 创建路由守卫 +createRouterGuard(router); + +export { resetRoutes, router }; diff --git a/apps/vben5/apps/web-ele/src/router/routes/core.ts b/apps/vben5/apps/web-ele/src/router/routes/core.ts new file mode 100644 index 000000000..fe030a9a2 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/routes/core.ts @@ -0,0 +1,88 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; + +import { AuthPageLayout } from '#/layouts'; +import { $t } from '#/locales'; +import Login from '#/views/_core/authentication/login.vue'; + +/** 全局404页面 */ +const fallbackNotFoundRoute: RouteRecordRaw = { + component: () => import('#/views/_core/fallback/not-found.vue'), + meta: { + hideInBreadcrumb: true, + hideInMenu: true, + hideInTab: true, + title: '404', + }, + name: 'FallbackNotFound', + path: '/:path(.*)*', +}; + +/** 基本路由,这些路由是必须存在的 */ +const coreRoutes: RouteRecordRaw[] = [ + { + meta: { + title: 'Root', + }, + name: 'Root', + path: '/', + redirect: DEFAULT_HOME_PATH, + }, + { + component: AuthPageLayout, + meta: { + hideInTab: true, + title: 'Authentication', + }, + name: 'Authentication', + path: '/auth', + redirect: LOGIN_PATH, + children: [ + { + name: 'Login', + path: 'login', + component: Login, + meta: { + title: $t('page.auth.login'), + }, + }, + { + name: 'CodeLogin', + path: 'code-login', + component: () => import('#/views/_core/authentication/code-login.vue'), + meta: { + title: $t('page.auth.codeLogin'), + }, + }, + { + name: 'QrCodeLogin', + path: 'qrcode-login', + component: () => + import('#/views/_core/authentication/qrcode-login.vue'), + meta: { + title: $t('page.auth.qrcodeLogin'), + }, + }, + { + name: 'ForgetPassword', + path: 'forget-password', + component: () => + import('#/views/_core/authentication/forget-password.vue'), + meta: { + title: $t('page.auth.forgetPassword'), + }, + }, + { + name: 'Register', + path: 'register', + component: () => import('#/views/_core/authentication/register.vue'), + meta: { + title: $t('page.auth.register'), + }, + }, + ], + }, +]; + +export { coreRoutes, fallbackNotFoundRoute }; diff --git a/apps/vben5/apps/web-ele/src/router/routes/index.ts b/apps/vben5/apps/web-ele/src/router/routes/index.ts new file mode 100644 index 000000000..e6fb14402 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/routes/index.ts @@ -0,0 +1,37 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { mergeRouteModules, traverseTreeValues } from '@vben/utils'; + +import { coreRoutes, fallbackNotFoundRoute } from './core'; + +const dynamicRouteFiles = import.meta.glob('./modules/**/*.ts', { + eager: true, +}); + +// 有需要可以自行打开注释,并创建文件夹 +// const externalRouteFiles = import.meta.glob('./external/**/*.ts', { eager: true }); +// const staticRouteFiles = import.meta.glob('./static/**/*.ts', { eager: true }); + +/** 动态路由 */ +const dynamicRoutes: RouteRecordRaw[] = mergeRouteModules(dynamicRouteFiles); + +/** 外部路由列表,访问这些页面可以不需要Layout,可能用于内嵌在别的系统(不会显示在菜单中) */ +// const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles); +// const staticRoutes: RouteRecordRaw[] = mergeRouteModules(staticRouteFiles); +const staticRoutes: RouteRecordRaw[] = []; +const externalRoutes: RouteRecordRaw[] = []; + +/** 路由列表,由基本路由、外部路由和404兜底路由组成 + * 无需走权限验证(会一直显示在菜单中) */ +const routes: RouteRecordRaw[] = [ + ...coreRoutes, + ...externalRoutes, + fallbackNotFoundRoute, +]; + +/** 基本路由列表,这些路由不需要进入权限拦截 */ +const coreRouteNames = traverseTreeValues(coreRoutes, (route) => route.name); + +/** 有权限校验的路由列表,包含动态路由和静态路由 */ +const accessRoutes = [...dynamicRoutes, ...staticRoutes]; +export { accessRoutes, coreRouteNames, routes }; diff --git a/apps/vben5/apps/web-ele/src/router/routes/modules/dashboard.ts b/apps/vben5/apps/web-ele/src/router/routes/modules/dashboard.ts new file mode 100644 index 000000000..1bddab9db --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/routes/modules/dashboard.ts @@ -0,0 +1,40 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'lucide:layout-dashboard', + order: -1, + title: $t('page.dashboard.title'), + }, + name: 'Dashboard', + path: '/', + children: [ + { + name: 'Analytics', + path: '/analytics', + component: () => import('#/views/dashboard/analytics/index.vue'), + meta: { + affixTab: true, + icon: 'lucide:area-chart', + title: $t('page.dashboard.analytics'), + }, + }, + { + name: 'Workspace', + path: '/workspace', + component: () => import('#/views/dashboard/workspace/index.vue'), + meta: { + icon: 'carbon:workspace', + title: $t('page.dashboard.workspace'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-ele/src/router/routes/modules/demos.ts b/apps/vben5/apps/web-ele/src/router/routes/modules/demos.ts new file mode 100644 index 000000000..223efcf9d --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/routes/modules/demos.ts @@ -0,0 +1,30 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'ic:baseline-view-in-ar', + keepAlive: true, + order: 1000, + title: $t('demos.title'), + }, + name: 'Demos', + path: '/demos', + children: [ + { + meta: { + title: $t('demos.elementPlus'), + }, + name: 'NaiveDemos', + path: '/demos/element', + component: () => import('#/views/demos/element/index.vue'), + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-ele/src/router/routes/modules/vben.ts b/apps/vben5/apps/web-ele/src/router/routes/modules/vben.ts new file mode 100644 index 000000000..2cfef5498 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/router/routes/modules/vben.ts @@ -0,0 +1,82 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { + VBEN_ANT_PREVIEW_URL, + VBEN_DOC_URL, + VBEN_GITHUB_URL, + VBEN_LOGO_URL, + VBEN_NAIVE_PREVIEW_URL, +} from '@vben/constants'; +import { SvgAntdvLogoIcon } from '@vben/icons'; + +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + badgeType: 'dot', + icon: VBEN_LOGO_URL, + order: 9999, + title: $t('demos.vben.title'), + }, + name: 'VbenProject', + path: '/vben-admin', + children: [ + { + name: 'VbenAbout', + path: '/vben-admin/about', + component: () => import('#/views/_core/about/index.vue'), + meta: { + icon: 'lucide:copyright', + title: $t('demos.vben.about'), + }, + }, + { + name: 'VbenDocument', + path: '/vben-admin/document', + component: IFrameView, + meta: { + icon: 'lucide:book-open-text', + link: VBEN_DOC_URL, + title: $t('demos.vben.document'), + }, + }, + { + name: 'VbenGithub', + path: '/vben-admin/github', + component: IFrameView, + meta: { + icon: 'mdi:github', + link: VBEN_GITHUB_URL, + title: 'Github', + }, + }, + { + name: 'VbenNaive', + path: '/vben-admin/naive', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: 'logos:naiveui', + link: VBEN_NAIVE_PREVIEW_URL, + title: $t('demos.vben.naive-ui'), + }, + }, + { + name: 'VbenAntd', + path: '/vben-admin/antd', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: SvgAntdvLogoIcon, + link: VBEN_ANT_PREVIEW_URL, + title: $t('demos.vben.antdv'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-ele/src/store/auth.ts b/apps/vben5/apps/web-ele/src/store/auth.ts new file mode 100644 index 000000000..639fb0372 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/store/auth.ts @@ -0,0 +1,116 @@ +import type { Recordable, UserInfo } from '@vben/types'; + +import { ref } from 'vue'; +import { useRouter } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores'; + +import { ElNotification } from 'element-plus'; +import { defineStore } from 'pinia'; + +import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api'; +import { $t } from '#/locales'; + +export const useAuthStore = defineStore('auth', () => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const router = useRouter(); + + const loginLoading = ref(false); + + /** + * 异步处理登录操作 + * Asynchronously handle the login process + * @param params 登录表单数据 + */ + async function authLogin( + params: Recordable, + onSuccess?: () => Promise | void, + ) { + // 异步处理用户登录操作并获取 accessToken + let userInfo: null | UserInfo = null; + try { + loginLoading.value = true; + const { accessToken } = await loginApi(params); + + // 如果成功获取到 accessToken + if (accessToken) { + // 将 accessToken 存储到 accessStore 中 + accessStore.setAccessToken(accessToken); + + // 获取用户信息并存储到 accessStore 中 + const [fetchUserInfoResult, accessCodes] = await Promise.all([ + fetchUserInfo(), + getAccessCodesApi(), + ]); + + userInfo = fetchUserInfoResult; + + userStore.setUserInfo(userInfo); + accessStore.setAccessCodes(accessCodes); + + if (accessStore.loginExpired) { + accessStore.setLoginExpired(false); + } else { + onSuccess + ? await onSuccess?.() + : await router.push(userInfo.homePath || DEFAULT_HOME_PATH); + } + + if (userInfo?.realName) { + ElNotification({ + message: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`, + title: $t('authentication.loginSuccess'), + type: 'success', + }); + } + } + } finally { + loginLoading.value = false; + } + + return { + userInfo, + }; + } + + async function logout(redirect: boolean = true) { + try { + await logoutApi(); + } catch { + // 不做任何处理 + } + resetAllStores(); + accessStore.setLoginExpired(false); + + // 回登录页带上当前路由地址 + await router.replace({ + path: LOGIN_PATH, + query: redirect + ? { + redirect: encodeURIComponent(router.currentRoute.value.fullPath), + } + : {}, + }); + } + + async function fetchUserInfo() { + let userInfo: null | UserInfo = null; + userInfo = await getUserInfoApi(); + userStore.setUserInfo(userInfo); + return userInfo; + } + + function $reset() { + loginLoading.value = false; + } + + return { + $reset, + authLogin, + fetchUserInfo, + loginLoading, + logout, + }; +}); diff --git a/apps/vben5/apps/web-ele/src/store/index.ts b/apps/vben5/apps/web-ele/src/store/index.ts new file mode 100644 index 000000000..269586ee8 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/store/index.ts @@ -0,0 +1 @@ +export * from './auth'; diff --git a/apps/vben5/apps/web-ele/src/views/_core/README.md b/apps/vben5/apps/web-ele/src/views/_core/README.md new file mode 100644 index 000000000..8248afe6c --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/README.md @@ -0,0 +1,3 @@ +# \_core + +此目录包含应用程序正常运行所需的基本视图。这些视图是应用程序布局中使用的视图。 diff --git a/apps/vben5/apps/web-ele/src/views/_core/about/index.vue b/apps/vben5/apps/web-ele/src/views/_core/about/index.vue new file mode 100644 index 000000000..0ee524335 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/about/index.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/authentication/code-login.vue b/apps/vben5/apps/web-ele/src/views/_core/authentication/code-login.vue new file mode 100644 index 000000000..556b273af --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/authentication/code-login.vue @@ -0,0 +1,65 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/authentication/forget-password.vue b/apps/vben5/apps/web-ele/src/views/_core/authentication/forget-password.vue new file mode 100644 index 000000000..fef0d4279 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/authentication/forget-password.vue @@ -0,0 +1,43 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/authentication/login.vue b/apps/vben5/apps/web-ele/src/views/_core/authentication/login.vue new file mode 100644 index 000000000..099e4c8c0 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/authentication/login.vue @@ -0,0 +1,98 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/authentication/qrcode-login.vue b/apps/vben5/apps/web-ele/src/views/_core/authentication/qrcode-login.vue new file mode 100644 index 000000000..23f5f2dad --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/authentication/qrcode-login.vue @@ -0,0 +1,10 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/authentication/register.vue b/apps/vben5/apps/web-ele/src/views/_core/authentication/register.vue new file mode 100644 index 000000000..b1a5de726 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/authentication/register.vue @@ -0,0 +1,96 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/fallback/coming-soon.vue b/apps/vben5/apps/web-ele/src/views/_core/fallback/coming-soon.vue new file mode 100644 index 000000000..f394930f2 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/fallback/coming-soon.vue @@ -0,0 +1,7 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/fallback/forbidden.vue b/apps/vben5/apps/web-ele/src/views/_core/fallback/forbidden.vue new file mode 100644 index 000000000..8ea65fedb --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/fallback/forbidden.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/fallback/internal-error.vue b/apps/vben5/apps/web-ele/src/views/_core/fallback/internal-error.vue new file mode 100644 index 000000000..819a47d5e --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/fallback/internal-error.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/fallback/not-found.vue b/apps/vben5/apps/web-ele/src/views/_core/fallback/not-found.vue new file mode 100644 index 000000000..4d178e9cb --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/fallback/not-found.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/_core/fallback/offline.vue b/apps/vben5/apps/web-ele/src/views/_core/fallback/offline.vue new file mode 100644 index 000000000..5de4a88de --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/_core/fallback/offline.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-trends.vue b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-trends.vue new file mode 100644 index 000000000..fadfc917c --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-trends.vue @@ -0,0 +1,100 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-data.vue b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-data.vue new file mode 100644 index 000000000..30c4265df --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-data.vue @@ -0,0 +1,84 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-sales.vue b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-sales.vue new file mode 100644 index 000000000..260520b84 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-sales.vue @@ -0,0 +1,48 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-source.vue b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-source.vue new file mode 100644 index 000000000..e0d0aab5e --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits-source.vue @@ -0,0 +1,67 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits.vue b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits.vue new file mode 100644 index 000000000..7e1f14ee6 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/analytics-visits.vue @@ -0,0 +1,57 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/analytics/index.vue b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/index.vue new file mode 100644 index 000000000..00b34df1e --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/analytics/index.vue @@ -0,0 +1,90 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/dashboard/workspace/index.vue b/apps/vben5/apps/web-ele/src/views/dashboard/workspace/index.vue new file mode 100644 index 000000000..b95d61381 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/dashboard/workspace/index.vue @@ -0,0 +1,266 @@ + + + diff --git a/apps/vben5/apps/web-ele/src/views/demos/element/index.vue b/apps/vben5/apps/web-ele/src/views/demos/element/index.vue new file mode 100644 index 000000000..55bc25713 --- /dev/null +++ b/apps/vben5/apps/web-ele/src/views/demos/element/index.vue @@ -0,0 +1,109 @@ + + + diff --git a/apps/vben5/apps/web-ele/tailwind.config.mjs b/apps/vben5/apps/web-ele/tailwind.config.mjs new file mode 100644 index 000000000..f17f556fa --- /dev/null +++ b/apps/vben5/apps/web-ele/tailwind.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config'; diff --git a/apps/vben5/apps/web-ele/tsconfig.json b/apps/vben5/apps/web-ele/tsconfig.json new file mode 100644 index 000000000..02c287fe6 --- /dev/null +++ b/apps/vben5/apps/web-ele/tsconfig.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/web-app.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "#/*": ["./src/*"] + } + }, + "references": [{ "path": "./tsconfig.node.json" }], + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/apps/vben5/apps/web-ele/tsconfig.node.json b/apps/vben5/apps/web-ele/tsconfig.node.json new file mode 100644 index 000000000..c2f0d86cc --- /dev/null +++ b/apps/vben5/apps/web-ele/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/node.json", + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "noEmit": false + }, + "include": ["vite.config.mts"] +} diff --git a/apps/vben5/apps/web-ele/vite.config.mts b/apps/vben5/apps/web-ele/vite.config.mts new file mode 100644 index 000000000..9f1e72353 --- /dev/null +++ b/apps/vben5/apps/web-ele/vite.config.mts @@ -0,0 +1,27 @@ +import { defineConfig } from '@vben/vite-config'; + +import ElementPlus from 'unplugin-element-plus/vite'; + +export default defineConfig(async () => { + return { + application: {}, + vite: { + plugins: [ + ElementPlus({ + format: 'esm', + }), + ], + server: { + proxy: { + '/api': { + changeOrigin: true, + rewrite: (path) => path.replace(/^\/api/, ''), + // mock代理目标地址 + target: 'http://localhost:5320/api', + ws: true, + }, + }, + }, + }, + }; +}); diff --git a/apps/vben5/apps/web-naive/.env b/apps/vben5/apps/web-naive/.env new file mode 100644 index 000000000..350660c0e --- /dev/null +++ b/apps/vben5/apps/web-naive/.env @@ -0,0 +1,5 @@ +# 应用标题 +VITE_APP_TITLE=Vben Admin Naive + +# 应用命名空间,用于缓存、store等功能的前缀,确保隔离 +VITE_APP_NAMESPACE=vben-web-naive diff --git a/apps/vben5/apps/web-naive/.env.analyze b/apps/vben5/apps/web-naive/.env.analyze new file mode 100644 index 000000000..ffafa8dd5 --- /dev/null +++ b/apps/vben5/apps/web-naive/.env.analyze @@ -0,0 +1,7 @@ +# public path +VITE_BASE=/ + +# Basic interface address SPA +VITE_GLOB_API_URL=/api + +VITE_VISUALIZER=true diff --git a/apps/vben5/apps/web-naive/.env.development b/apps/vben5/apps/web-naive/.env.development new file mode 100644 index 000000000..11c5254ae --- /dev/null +++ b/apps/vben5/apps/web-naive/.env.development @@ -0,0 +1,16 @@ +# 端口号 +VITE_PORT=5888 + +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=/api + +# 是否开启 Nitro Mock服务,true 为开启,false 为关闭 +VITE_NITRO_MOCK=true + +# 是否打开 devtools,true 为打开,false 为关闭 +VITE_DEVTOOLS=false + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true diff --git a/apps/vben5/apps/web-naive/.env.production b/apps/vben5/apps/web-naive/.env.production new file mode 100644 index 000000000..5375847a6 --- /dev/null +++ b/apps/vben5/apps/web-naive/.env.production @@ -0,0 +1,19 @@ +VITE_BASE=/ + +# 接口地址 +VITE_GLOB_API_URL=https://mock-napi.vben.pro/api + +# 是否开启压缩,可以设置为 none, brotli, gzip +VITE_COMPRESS=none + +# 是否开启 PWA +VITE_PWA=false + +# vue-router 的模式 +VITE_ROUTER_HISTORY=hash + +# 是否注入全局loading +VITE_INJECT_APP_LOADING=true + +# 打包后是否生成dist.zip +VITE_ARCHIVER=true diff --git a/apps/vben5/apps/web-naive/index.html b/apps/vben5/apps/web-naive/index.html new file mode 100644 index 000000000..7ea638418 --- /dev/null +++ b/apps/vben5/apps/web-naive/index.html @@ -0,0 +1,35 @@ + + + + + + + + + + + + <%= VITE_APP_TITLE %> + + + + +
+ + + diff --git a/apps/vben5/apps/web-naive/package.json b/apps/vben5/apps/web-naive/package.json new file mode 100644 index 000000000..0710c3415 --- /dev/null +++ b/apps/vben5/apps/web-naive/package.json @@ -0,0 +1,49 @@ +{ + "name": "@vben/web-naive", + "version": "5.4.8", + "homepage": "https://vben.pro", + "bugs": "https://github.com/vbenjs/vue-vben-admin/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/vbenjs/vue-vben-admin.git", + "directory": "apps/web-naive" + }, + "license": "MIT", + "author": { + "name": "vben", + "email": "ann.vben@gmail.com", + "url": "https://github.com/anncwb" + }, + "type": "module", + "scripts": { + "build": "pnpm vite build --mode production", + "build:analyze": "pnpm vite build --mode analyze", + "dev": "pnpm vite --mode development", + "preview": "vite preview", + "typecheck": "vue-tsc --noEmit --skipLibCheck" + }, + "imports": { + "#/*": "./src/*" + }, + "dependencies": { + "@vben/access": "workspace:*", + "@vben/common-ui": "workspace:*", + "@vben/constants": "workspace:*", + "@vben/hooks": "workspace:*", + "@vben/icons": "workspace:*", + "@vben/layouts": "workspace:*", + "@vben/locales": "workspace:*", + "@vben/plugins": "workspace:*", + "@vben/preferences": "workspace:*", + "@vben/request": "workspace:*", + "@vben/stores": "workspace:*", + "@vben/styles": "workspace:*", + "@vben/types": "workspace:*", + "@vben/utils": "workspace:*", + "@vueuse/core": "catalog:", + "naive-ui": "catalog:", + "pinia": "catalog:", + "vue": "catalog:", + "vue-router": "catalog:" + } +} diff --git a/apps/vben5/apps/web-naive/postcss.config.mjs b/apps/vben5/apps/web-naive/postcss.config.mjs new file mode 100644 index 000000000..3d8070455 --- /dev/null +++ b/apps/vben5/apps/web-naive/postcss.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config/postcss'; diff --git a/apps/vben5/apps/web-naive/public/favicon.ico b/apps/vben5/apps/web-naive/public/favicon.ico new file mode 100644 index 000000000..fcf9818e2 Binary files /dev/null and b/apps/vben5/apps/web-naive/public/favicon.ico differ diff --git a/apps/vben5/apps/web-naive/src/adapter/component/index.ts b/apps/vben5/apps/web-naive/src/adapter/component/index.ts new file mode 100644 index 000000000..c5dffddb8 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/adapter/component/index.ts @@ -0,0 +1,103 @@ +/** + * 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用 + * 可用于 vben-form、vben-modal、vben-drawer 等组件使用, + */ + +import type { BaseFormComponentType } from '@vben/common-ui'; + +import type { Component, SetupContext } from 'vue'; +import { h } from 'vue'; + +import { globalShareState } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { + NButton, + NCheckbox, + NCheckboxGroup, + NDatePicker, + NDivider, + NInput, + NInputNumber, + NRadioGroup, + NSelect, + NSpace, + NSwitch, + NTimePicker, + NTreeSelect, + NUpload, +} from 'naive-ui'; + +import { message } from '#/adapter/naive'; + +const withDefaultPlaceholder = ( + component: T, + type: 'input' | 'select', +) => { + return (props: any, { attrs, slots }: Omit) => { + const placeholder = props?.placeholder || $t(`ui.placeholder.${type}`); + return h(component, { ...props, ...attrs, placeholder }, slots); + }; +}; + +// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明 +export type ComponentType = + | 'Checkbox' + | 'CheckboxGroup' + | 'DatePicker' + | 'Divider' + | 'Input' + | 'InputNumber' + | 'RadioGroup' + | 'Select' + | 'Space' + | 'Switch' + | 'TimePicker' + | 'TreeSelect' + | 'Upload' + | BaseFormComponentType; + +async function initComponentAdapter() { + const components: Partial> = { + // 如果你的组件体积比较大,可以使用异步加载 + // Button: () => + // import('xxx').then((res) => res.Button), + + Checkbox: NCheckbox, + CheckboxGroup: NCheckboxGroup, + DatePicker: NDatePicker, + // 自定义默认按钮 + DefaultButton: (props, { attrs, slots }) => { + return h(NButton, { ...props, attrs, type: 'default' }, slots); + }, + // 自定义主要按钮 + PrimaryButton: (props, { attrs, slots }) => { + return h(NButton, { ...props, attrs, type: 'primary' }, slots); + }, + Divider: NDivider, + Input: withDefaultPlaceholder(NInput, 'input'), + InputNumber: withDefaultPlaceholder(NInputNumber, 'input'), + RadioGroup: NRadioGroup, + Select: withDefaultPlaceholder(NSelect, 'select'), + Space: NSpace, + Switch: NSwitch, + TimePicker: NTimePicker, + TreeSelect: withDefaultPlaceholder(NTreeSelect, 'select'), + Upload: NUpload, + }; + + // 将组件注册到全局共享状态中 + globalShareState.setComponents(components); + + // 定义全局共享状态中的消息提示 + globalShareState.defineMessage({ + // 复制成功消息提示 + copyPreferencesSuccess: (title, content) => { + message.success(content || title, { + duration: 0, + }); + }, + }); +} + +export { initComponentAdapter }; diff --git a/apps/vben5/apps/web-naive/src/adapter/form.ts b/apps/vben5/apps/web-naive/src/adapter/form.ts new file mode 100644 index 000000000..2c3cee875 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/adapter/form.ts @@ -0,0 +1,45 @@ +import type { + VbenFormSchema as FormSchema, + VbenFormProps, +} from '@vben/common-ui'; + +import type { ComponentType } from './component'; + +import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +setupVbenForm({ + config: { + // naive-ui组件不接受onChang事件,所以需要禁用 + disabledOnChangeListener: true, + // naive-ui组件的空值为null,不能是undefined,否则重置表单时不生效 + emptyStateValue: null, + baseModelPropName: 'value', + modelPropNameMap: { + Checkbox: 'checked', + Radio: 'checked', + Upload: 'fileList', + }, + }, + defineRules: { + required: (value, _params, ctx) => { + if (value === undefined || value === null || value.length === 0) { + return $t('ui.formRules.required', [ctx.label]); + } + return true; + }, + selectRequired: (value, _params, ctx) => { + if (value === undefined || value === null) { + return $t('ui.formRules.selectRequired', [ctx.label]); + } + return true; + }, + }, +}); + +const useVbenForm = useForm; + +export { useVbenForm, z }; + +export type VbenFormSchema = FormSchema; +export type { VbenFormProps }; diff --git a/apps/vben5/apps/web-naive/src/adapter/naive.ts b/apps/vben5/apps/web-naive/src/adapter/naive.ts new file mode 100644 index 000000000..1eb7b7b6e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/adapter/naive.ts @@ -0,0 +1,25 @@ +import { computed } from 'vue'; + +import { preferences } from '@vben/preferences'; +import '@vben/styles'; + +import { createDiscreteApi, darkTheme, lightTheme } from 'naive-ui'; + +const themeOverridesProviderProps = computed(() => ({ + themeOverrides: preferences.theme.mode === 'light' ? lightTheme : darkTheme, +})); + +const themeProviderProps = computed(() => ({ + theme: preferences.theme.mode === 'light' ? lightTheme : darkTheme, +})); + +export const { dialog, loadingBar, message, modal, notification } = + createDiscreteApi( + ['message', 'dialog', 'notification', 'loadingBar', 'modal'], + { + configProviderProps: themeProviderProps, + loadingBarProviderProps: themeOverridesProviderProps, + messageProviderProps: themeOverridesProviderProps, + notificationProviderProps: themeOverridesProviderProps, + }, + ); diff --git a/apps/vben5/apps/web-naive/src/adapter/vxe-table.ts b/apps/vben5/apps/web-naive/src/adapter/vxe-table.ts new file mode 100644 index 000000000..081cfb29e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/adapter/vxe-table.ts @@ -0,0 +1,67 @@ +import { h } from 'vue'; + +import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table'; + +import { NButton, NImage } from 'naive-ui'; + +import { useVbenForm } from './form'; + +setupVbenVxeTable({ + configVxeTable: (vxeUI) => { + vxeUI.setConfig({ + grid: { + align: 'center', + border: false, + columnConfig: { + resizable: true, + }, + minHeight: 180, + formConfig: { + // 全局禁用vxe-table的表单配置,使用formOptions + enabled: false, + }, + proxyConfig: { + autoLoad: true, + response: { + result: 'items', + total: 'total', + list: 'items', + }, + showActiveMsg: true, + showResponseMsg: false, + }, + round: true, + showOverflow: true, + size: 'small', + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellImage' }, + vxeUI.renderer.add('CellImage', { + renderTableDefault(_renderOpts, params) { + const { column, row } = params; + return h(NImage, { src: row[column.field] }); + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellLink' }, + vxeUI.renderer.add('CellLink', { + renderTableDefault(renderOpts) { + const { props } = renderOpts; + return h( + NButton, + { size: 'small', type: 'primary', quaternary: true }, + { default: () => props?.text }, + ); + }, + }); + + // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化 + // vxeUI.formats.add + }, + useVbenForm, +}); + +export { useVbenVxeGrid }; + +export type * from '@vben/plugins/vxe-table'; diff --git a/apps/vben5/apps/web-naive/src/api/core/auth.ts b/apps/vben5/apps/web-naive/src/api/core/auth.ts new file mode 100644 index 000000000..71d9f9943 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/api/core/auth.ts @@ -0,0 +1,51 @@ +import { baseRequestClient, requestClient } from '#/api/request'; + +export namespace AuthApi { + /** 登录接口参数 */ + export interface LoginParams { + password?: string; + username?: string; + } + + /** 登录接口返回值 */ + export interface LoginResult { + accessToken: string; + } + + export interface RefreshTokenResult { + data: string; + status: number; + } +} + +/** + * 登录 + */ +export async function loginApi(data: AuthApi.LoginParams) { + return requestClient.post('/auth/login', data); +} + +/** + * 刷新accessToken + */ +export async function refreshTokenApi() { + return baseRequestClient.post('/auth/refresh', { + withCredentials: true, + }); +} + +/** + * 退出登录 + */ +export async function logoutApi() { + return baseRequestClient.post('/auth/logout', { + withCredentials: true, + }); +} + +/** + * 获取用户权限码 + */ +export async function getAccessCodesApi() { + return requestClient.get('/auth/codes'); +} diff --git a/apps/vben5/apps/web-naive/src/api/core/index.ts b/apps/vben5/apps/web-naive/src/api/core/index.ts new file mode 100644 index 000000000..28a5aef47 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/api/core/index.ts @@ -0,0 +1,3 @@ +export * from './auth'; +export * from './menu'; +export * from './user'; diff --git a/apps/vben5/apps/web-naive/src/api/core/menu.ts b/apps/vben5/apps/web-naive/src/api/core/menu.ts new file mode 100644 index 000000000..9ef60b11c --- /dev/null +++ b/apps/vben5/apps/web-naive/src/api/core/menu.ts @@ -0,0 +1,10 @@ +import type { RouteRecordStringComponent } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户所有菜单 + */ +export async function getAllMenusApi() { + return requestClient.get('/menu/all'); +} diff --git a/apps/vben5/apps/web-naive/src/api/core/user.ts b/apps/vben5/apps/web-naive/src/api/core/user.ts new file mode 100644 index 000000000..7e28ea848 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/api/core/user.ts @@ -0,0 +1,10 @@ +import type { UserInfo } from '@vben/types'; + +import { requestClient } from '#/api/request'; + +/** + * 获取用户信息 + */ +export async function getUserInfoApi() { + return requestClient.get('/user/info'); +} diff --git a/apps/vben5/apps/web-naive/src/api/index.ts b/apps/vben5/apps/web-naive/src/api/index.ts new file mode 100644 index 000000000..4b0e04137 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/api/index.ts @@ -0,0 +1 @@ +export * from './core'; diff --git a/apps/vben5/apps/web-naive/src/api/request.ts b/apps/vben5/apps/web-naive/src/api/request.ts new file mode 100644 index 000000000..72056e198 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/api/request.ts @@ -0,0 +1,112 @@ +/** + * 该文件可自行根据业务逻辑进行调整 + */ +import type { HttpResponse } from '@vben/request'; + +import { useAppConfig } from '@vben/hooks'; +import { preferences } from '@vben/preferences'; +import { + authenticateResponseInterceptor, + errorMessageResponseInterceptor, + RequestClient, +} from '@vben/request'; +import { useAccessStore } from '@vben/stores'; + +import { message } from '#/adapter/naive'; +import { useAuthStore } from '#/store'; + +import { refreshTokenApi } from './core'; + +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); + +function createRequestClient(baseURL: string) { + const client = new RequestClient({ + baseURL, + }); + + /** + * 重新认证逻辑 + */ + async function doReAuthenticate() { + console.warn('Access token or refresh token is invalid or expired. '); + const accessStore = useAccessStore(); + const authStore = useAuthStore(); + accessStore.setAccessToken(null); + if ( + preferences.app.loginExpiredMode === 'modal' && + accessStore.isAccessChecked + ) { + accessStore.setLoginExpired(true); + } else { + await authStore.logout(); + } + } + + /** + * 刷新token逻辑 + */ + async function doRefreshToken() { + const accessStore = useAccessStore(); + const resp = await refreshTokenApi(); + const newToken = resp.data; + accessStore.setAccessToken(newToken); + return newToken; + } + + function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; + } + + // 请求头处理 + client.addRequestInterceptor({ + fulfilled: async (config) => { + const accessStore = useAccessStore(); + + config.headers.Authorization = formatToken(accessStore.accessToken); + config.headers['Accept-Language'] = preferences.app.locale; + return config; + }, + }); + + // response数据解构 + client.addResponseInterceptor({ + fulfilled: (response) => { + const { data: responseData, status } = response; + + const { code, data } = responseData; + if (status >= 200 && status < 400 && code === 0) { + return data; + } + throw Object.assign({}, response, { response }); + }, + }); + + // token过期的处理 + client.addResponseInterceptor( + authenticateResponseInterceptor({ + client, + doReAuthenticate, + doRefreshToken, + enableRefreshToken: preferences.app.enableRefreshToken, + formatToken, + }), + ); + + // 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里 + client.addResponseInterceptor( + errorMessageResponseInterceptor((msg: string, error) => { + // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg + // 当前mock接口返回的错误字段是 error 或者 message + const responseData = error?.response?.data ?? {}; + const errorMessage = responseData?.error ?? responseData?.message ?? ''; + // 如果没有错误信息,则会根据状态码进行提示 + message.error(errorMessage || msg); + }), + ); + + return client; +} + +export const requestClient = createRequestClient(apiURL); + +export const baseRequestClient = new RequestClient({ baseURL: apiURL }); diff --git a/apps/vben5/apps/web-naive/src/app.vue b/apps/vben5/apps/web-naive/src/app.vue new file mode 100644 index 000000000..23983c55c --- /dev/null +++ b/apps/vben5/apps/web-naive/src/app.vue @@ -0,0 +1,56 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/bootstrap.ts b/apps/vben5/apps/web-naive/src/bootstrap.ts new file mode 100644 index 000000000..fc7f961d6 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/bootstrap.ts @@ -0,0 +1,46 @@ +import { createApp, watchEffect } from 'vue'; + +import { registerAccessDirective } from '@vben/access'; +import { preferences } from '@vben/preferences'; +import { initStores } from '@vben/stores'; +import '@vben/styles'; + +import { useTitle } from '@vueuse/core'; + +import { $t, setupI18n } from '#/locales'; + +import { initComponentAdapter } from './adapter/component'; +import App from './app.vue'; +import { router } from './router'; + +async function bootstrap(namespace: string) { + // 初始化组件适配器 + initComponentAdapter(); + const app = createApp(App); + + // 国际化 i18n 配置 + await setupI18n(app); + + // 配置 pinia-tore + await initStores(app, { namespace }); + + // 安装权限指令 + registerAccessDirective(app); + + // 配置路由及路由守卫 + app.use(router); + + // 动态更新标题 + watchEffect(() => { + if (preferences.app.dynamicTitle) { + const routeTitle = router.currentRoute.value.meta?.title; + const pageTitle = + (routeTitle ? `${$t(routeTitle)} - ` : '') + preferences.app.name; + useTitle(pageTitle); + } + }); + + app.mount('#app'); +} + +export { bootstrap }; diff --git a/apps/vben5/apps/web-naive/src/layouts/auth.vue b/apps/vben5/apps/web-naive/src/layouts/auth.vue new file mode 100644 index 000000000..18d415bc7 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/layouts/auth.vue @@ -0,0 +1,23 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/layouts/basic.vue b/apps/vben5/apps/web-naive/src/layouts/basic.vue new file mode 100644 index 000000000..f75b3ddc6 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/layouts/basic.vue @@ -0,0 +1,158 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/layouts/index.ts b/apps/vben5/apps/web-naive/src/layouts/index.ts new file mode 100644 index 000000000..a43207805 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/layouts/index.ts @@ -0,0 +1,6 @@ +const BasicLayout = () => import('./basic.vue'); +const AuthPageLayout = () => import('./auth.vue'); + +const IFrameView = () => import('@vben/layouts').then((m) => m.IFrameView); + +export { AuthPageLayout, BasicLayout, IFrameView }; diff --git a/apps/vben5/apps/web-naive/src/locales/README.md b/apps/vben5/apps/web-naive/src/locales/README.md new file mode 100644 index 000000000..7b451032e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/locales/README.md @@ -0,0 +1,3 @@ +# locale + +每个app使用的国际化可能不同,这里用于扩展国际化的功能,例如扩展 dayjs、antd组件库的多语言切换,以及app本身的国际化文件。 diff --git a/apps/vben5/apps/web-naive/src/locales/index.ts b/apps/vben5/apps/web-naive/src/locales/index.ts new file mode 100644 index 000000000..3d77913ad --- /dev/null +++ b/apps/vben5/apps/web-naive/src/locales/index.ts @@ -0,0 +1,38 @@ +import type { LocaleSetupOptions, SupportedLanguagesType } from '@vben/locales'; + +import type { App } from 'vue'; + +import { + $t, + setupI18n as coreSetup, + loadLocalesMapFromDir, +} from '@vben/locales'; +import { preferences } from '@vben/preferences'; + +const modules = import.meta.glob('./langs/**/*.json'); + +const localesMap = loadLocalesMapFromDir( + /\.\/langs\/([^/]+)\/(.*)\.json$/, + modules, +); + +/** + * 加载应用特有的语言包 + * 这里也可以改造为从服务端获取翻译数据 + * @param lang + */ +async function loadMessages(lang: SupportedLanguagesType) { + const appLocaleMessages = await localesMap[lang]?.(); + return appLocaleMessages?.default; +} + +async function setupI18n(app: App, options: LocaleSetupOptions = {}) { + await coreSetup(app, { + defaultLocale: preferences.app.locale, + loadMessages, + missingWarn: !import.meta.env.PROD, + ...options, + }); +} + +export { $t, setupI18n }; diff --git a/apps/vben5/apps/web-naive/src/locales/langs/en-US/demos.json b/apps/vben5/apps/web-naive/src/locales/langs/en-US/demos.json new file mode 100644 index 000000000..9fdffc765 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/locales/langs/en-US/demos.json @@ -0,0 +1,13 @@ +{ + "title": "Demos", + "naive": "Naive UI", + "table": "Table", + "vben": { + "title": "Project", + "about": "About", + "document": "Document", + "antdv": "Ant Design Vue Version", + "naive-ui": "Naive UI Version", + "element-plus": "Element Plus Version" + } +} diff --git a/apps/vben5/apps/web-naive/src/locales/langs/en-US/page.json b/apps/vben5/apps/web-naive/src/locales/langs/en-US/page.json new file mode 100644 index 000000000..618a258c0 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/locales/langs/en-US/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "Login", + "register": "Register", + "codeLogin": "Code Login", + "qrcodeLogin": "Qr Code Login", + "forgetPassword": "Forget Password" + }, + "dashboard": { + "title": "Dashboard", + "analytics": "Analytics", + "workspace": "Workspace" + } +} diff --git a/apps/vben5/apps/web-naive/src/locales/langs/zh-CN/demos.json b/apps/vben5/apps/web-naive/src/locales/langs/zh-CN/demos.json new file mode 100644 index 000000000..79b54fa21 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/locales/langs/zh-CN/demos.json @@ -0,0 +1,13 @@ +{ + "title": "演示", + "naive": "Naive UI", + "table": "Table", + "vben": { + "title": "项目", + "about": "关于", + "document": "文档", + "antdv": "Ant Design Vue 版本", + "naive-ui": "Naive UI 版本", + "element-plus": "Element Plus 版本" + } +} diff --git a/apps/vben5/apps/web-naive/src/locales/langs/zh-CN/page.json b/apps/vben5/apps/web-naive/src/locales/langs/zh-CN/page.json new file mode 100644 index 000000000..4cb67081c --- /dev/null +++ b/apps/vben5/apps/web-naive/src/locales/langs/zh-CN/page.json @@ -0,0 +1,14 @@ +{ + "auth": { + "login": "登录", + "register": "注册", + "codeLogin": "验证码登录", + "qrcodeLogin": "二维码登录", + "forgetPassword": "忘记密码" + }, + "dashboard": { + "title": "概览", + "analytics": "分析页", + "workspace": "工作台" + } +} diff --git a/apps/vben5/apps/web-naive/src/main.ts b/apps/vben5/apps/web-naive/src/main.ts new file mode 100644 index 000000000..5d728a02a --- /dev/null +++ b/apps/vben5/apps/web-naive/src/main.ts @@ -0,0 +1,31 @@ +import { initPreferences } from '@vben/preferences'; +import { unmountGlobalLoading } from '@vben/utils'; + +import { overridesPreferences } from './preferences'; + +/** + * 应用初始化完成之后再进行页面加载渲染 + */ +async function initApplication() { + // name用于指定项目唯一标识 + // 用于区分不同项目的偏好设置以及存储数据的key前缀以及其他一些需要隔离的数据 + const env = import.meta.env.PROD ? 'prod' : 'dev'; + const appVersion = import.meta.env.VITE_APP_VERSION; + const namespace = `${import.meta.env.VITE_APP_NAMESPACE}-${appVersion}-${env}`; + + // app偏好设置初始化 + await initPreferences({ + namespace, + overrides: overridesPreferences, + }); + + // 启动应用并挂载 + // vue应用主要逻辑及视图 + const { bootstrap } = await import('./bootstrap'); + await bootstrap(namespace); + + // 移除并销毁loading + unmountGlobalLoading(); +} + +initApplication(); diff --git a/apps/vben5/apps/web-naive/src/preferences.ts b/apps/vben5/apps/web-naive/src/preferences.ts new file mode 100644 index 000000000..b2e9ace43 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/preferences.ts @@ -0,0 +1,13 @@ +import { defineOverridesPreferences } from '@vben/preferences'; + +/** + * @description 项目配置文件 + * 只需要覆盖项目中的一部分配置,不需要的配置不用覆盖,会自动使用默认配置 + * !!! 更改配置后请清空缓存,否则可能不生效 + */ +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + name: import.meta.env.VITE_APP_TITLE, + }, +}); diff --git a/apps/vben5/apps/web-naive/src/router/access.ts b/apps/vben5/apps/web-naive/src/router/access.ts new file mode 100644 index 000000000..7a80bac09 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/access.ts @@ -0,0 +1,40 @@ +import type { + ComponentRecordType, + GenerateMenuAndRoutesOptions, +} from '@vben/types'; + +import { generateAccessible } from '@vben/access'; +import { preferences } from '@vben/preferences'; + +import { message } from '#/adapter/naive'; +import { getAllMenusApi } from '#/api'; +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue'); + +async function generateAccess(options: GenerateMenuAndRoutesOptions) { + const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue'); + + const layoutMap: ComponentRecordType = { + BasicLayout, + IFrameView, + }; + + return await generateAccessible(preferences.app.accessMode, { + ...options, + fetchMenuListAsync: async () => { + message.loading(`${$t('common.loadingMenu')}...`, { + duration: 1.5, + }); + return await getAllMenusApi(); + }, + // 可以指定没有权限跳转403页面 + forbiddenComponent, + // 如果 route.meta.menuVisibleWithForbidden = true + layoutMap, + pageMap, + }); +} + +export { generateAccess }; diff --git a/apps/vben5/apps/web-naive/src/router/guard.ts b/apps/vben5/apps/web-naive/src/router/guard.ts new file mode 100644 index 000000000..c95d994ec --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/guard.ts @@ -0,0 +1,124 @@ +import type { Router } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { preferences } from '@vben/preferences'; +import { useAccessStore, useUserStore } from '@vben/stores'; +import { startProgress, stopProgress } from '@vben/utils'; + +import { accessRoutes, coreRouteNames } from '#/router/routes'; +import { useAuthStore } from '#/store'; + +import { generateAccess } from './access'; + +/** + * 通用守卫配置 + * @param router + */ +function setupCommonGuard(router: Router) { + // 记录已经加载的页面 + const loadedPaths = new Set(); + + router.beforeEach(async (to) => { + to.meta.loaded = loadedPaths.has(to.path); + + // 页面加载进度条 + if (!to.meta.loaded && preferences.transition.progress) { + startProgress(); + } + return true; + }); + + router.afterEach((to) => { + // 记录页面是否加载,如果已经加载,后续的页面切换动画等效果不在重复执行 + + loadedPaths.add(to.path); + + // 关闭页面加载进度条 + if (preferences.transition.progress) { + stopProgress(); + } + }); +} + +/** + * 权限访问守卫配置 + * @param router + */ +function setupAccessGuard(router: Router) { + router.beforeEach(async (to, from) => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const authStore = useAuthStore(); + + // 基本路由,这些路由不需要进入权限拦截 + if (coreRouteNames.includes(to.name as string)) { + if (to.path === LOGIN_PATH && accessStore.accessToken) { + return decodeURIComponent( + (to.query?.redirect as string) || DEFAULT_HOME_PATH, + ); + } + return true; + } + + // accessToken 检查 + if (!accessStore.accessToken) { + // 明确声明忽略权限访问权限,则可以访问 + if (to.meta.ignoreAccess) { + return true; + } + + // 没有访问权限,跳转登录页面 + if (to.fullPath !== LOGIN_PATH) { + return { + path: LOGIN_PATH, + // 如不需要,直接删除 query + query: { redirect: encodeURIComponent(to.fullPath) }, + // 携带当前跳转的页面,登录后重新跳转该页面 + replace: true, + }; + } + return to; + } + + // 是否已经生成过动态路由 + if (accessStore.isAccessChecked) { + return true; + } + // 生成路由表 + // 当前登录用户拥有的角色标识列表 + const userInfo = userStore.userInfo || (await authStore.fetchUserInfo()); + const userRoles = userInfo.roles ?? []; + + // 生成菜单和路由 + const { accessibleMenus, accessibleRoutes } = await generateAccess({ + roles: userRoles, + router, + // 则会在菜单中显示,但是访问会被重定向到403 + routes: accessRoutes, + }); + + // 保存菜单信息和路由信息 + accessStore.setAccessMenus(accessibleMenus); + accessStore.setAccessRoutes(accessibleRoutes); + accessStore.setIsAccessChecked(true); + const redirectPath = (from.query.redirect ?? to.fullPath) as string; + + return { + ...router.resolve(decodeURIComponent(redirectPath)), + replace: true, + }; + }); +} + +/** + * 项目守卫配置 + * @param router + */ +function createRouterGuard(router: Router) { + /** 通用 */ + setupCommonGuard(router); + /** 权限访问 */ + setupAccessGuard(router); +} + +export { createRouterGuard }; diff --git a/apps/vben5/apps/web-naive/src/router/index.ts b/apps/vben5/apps/web-naive/src/router/index.ts new file mode 100644 index 000000000..484023034 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/index.ts @@ -0,0 +1,37 @@ +import { + createRouter, + createWebHashHistory, + createWebHistory, +} from 'vue-router'; + +import { resetStaticRoutes } from '@vben/utils'; + +import { createRouterGuard } from './guard'; +import { routes } from './routes'; + +/** + * @zh_CN 创建vue-router实例 + */ +const router = createRouter({ + history: + import.meta.env.VITE_ROUTER_HISTORY === 'hash' + ? createWebHashHistory(import.meta.env.VITE_BASE) + : createWebHistory(import.meta.env.VITE_BASE), + // 应该添加到路由的初始路由列表。 + routes, + scrollBehavior: (to, _from, savedPosition) => { + if (savedPosition) { + return savedPosition; + } + return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 }; + }, + // 是否应该禁止尾部斜杠。 + // strict: true, +}); + +const resetRoutes = () => resetStaticRoutes(router, routes); + +// 创建路由守卫 +createRouterGuard(router); + +export { resetRoutes, router }; diff --git a/apps/vben5/apps/web-naive/src/router/routes/core.ts b/apps/vben5/apps/web-naive/src/router/routes/core.ts new file mode 100644 index 000000000..fe030a9a2 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/routes/core.ts @@ -0,0 +1,88 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; + +import { AuthPageLayout } from '#/layouts'; +import { $t } from '#/locales'; +import Login from '#/views/_core/authentication/login.vue'; + +/** 全局404页面 */ +const fallbackNotFoundRoute: RouteRecordRaw = { + component: () => import('#/views/_core/fallback/not-found.vue'), + meta: { + hideInBreadcrumb: true, + hideInMenu: true, + hideInTab: true, + title: '404', + }, + name: 'FallbackNotFound', + path: '/:path(.*)*', +}; + +/** 基本路由,这些路由是必须存在的 */ +const coreRoutes: RouteRecordRaw[] = [ + { + meta: { + title: 'Root', + }, + name: 'Root', + path: '/', + redirect: DEFAULT_HOME_PATH, + }, + { + component: AuthPageLayout, + meta: { + hideInTab: true, + title: 'Authentication', + }, + name: 'Authentication', + path: '/auth', + redirect: LOGIN_PATH, + children: [ + { + name: 'Login', + path: 'login', + component: Login, + meta: { + title: $t('page.auth.login'), + }, + }, + { + name: 'CodeLogin', + path: 'code-login', + component: () => import('#/views/_core/authentication/code-login.vue'), + meta: { + title: $t('page.auth.codeLogin'), + }, + }, + { + name: 'QrCodeLogin', + path: 'qrcode-login', + component: () => + import('#/views/_core/authentication/qrcode-login.vue'), + meta: { + title: $t('page.auth.qrcodeLogin'), + }, + }, + { + name: 'ForgetPassword', + path: 'forget-password', + component: () => + import('#/views/_core/authentication/forget-password.vue'), + meta: { + title: $t('page.auth.forgetPassword'), + }, + }, + { + name: 'Register', + path: 'register', + component: () => import('#/views/_core/authentication/register.vue'), + meta: { + title: $t('page.auth.register'), + }, + }, + ], + }, +]; + +export { coreRoutes, fallbackNotFoundRoute }; diff --git a/apps/vben5/apps/web-naive/src/router/routes/index.ts b/apps/vben5/apps/web-naive/src/router/routes/index.ts new file mode 100644 index 000000000..e6fb14402 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/routes/index.ts @@ -0,0 +1,37 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { mergeRouteModules, traverseTreeValues } from '@vben/utils'; + +import { coreRoutes, fallbackNotFoundRoute } from './core'; + +const dynamicRouteFiles = import.meta.glob('./modules/**/*.ts', { + eager: true, +}); + +// 有需要可以自行打开注释,并创建文件夹 +// const externalRouteFiles = import.meta.glob('./external/**/*.ts', { eager: true }); +// const staticRouteFiles = import.meta.glob('./static/**/*.ts', { eager: true }); + +/** 动态路由 */ +const dynamicRoutes: RouteRecordRaw[] = mergeRouteModules(dynamicRouteFiles); + +/** 外部路由列表,访问这些页面可以不需要Layout,可能用于内嵌在别的系统(不会显示在菜单中) */ +// const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles); +// const staticRoutes: RouteRecordRaw[] = mergeRouteModules(staticRouteFiles); +const staticRoutes: RouteRecordRaw[] = []; +const externalRoutes: RouteRecordRaw[] = []; + +/** 路由列表,由基本路由、外部路由和404兜底路由组成 + * 无需走权限验证(会一直显示在菜单中) */ +const routes: RouteRecordRaw[] = [ + ...coreRoutes, + ...externalRoutes, + fallbackNotFoundRoute, +]; + +/** 基本路由列表,这些路由不需要进入权限拦截 */ +const coreRouteNames = traverseTreeValues(coreRoutes, (route) => route.name); + +/** 有权限校验的路由列表,包含动态路由和静态路由 */ +const accessRoutes = [...dynamicRoutes, ...staticRoutes]; +export { accessRoutes, coreRouteNames, routes }; diff --git a/apps/vben5/apps/web-naive/src/router/routes/modules/dashboard.ts b/apps/vben5/apps/web-naive/src/router/routes/modules/dashboard.ts new file mode 100644 index 000000000..1bddab9db --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/routes/modules/dashboard.ts @@ -0,0 +1,40 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'lucide:layout-dashboard', + order: -1, + title: $t('page.dashboard.title'), + }, + name: 'Dashboard', + path: '/', + children: [ + { + name: 'Analytics', + path: '/analytics', + component: () => import('#/views/dashboard/analytics/index.vue'), + meta: { + affixTab: true, + icon: 'lucide:area-chart', + title: $t('page.dashboard.analytics'), + }, + }, + { + name: 'Workspace', + path: '/workspace', + component: () => import('#/views/dashboard/workspace/index.vue'), + meta: { + icon: 'carbon:workspace', + title: $t('page.dashboard.workspace'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-naive/src/router/routes/modules/demos.ts b/apps/vben5/apps/web-naive/src/router/routes/modules/demos.ts new file mode 100644 index 000000000..cf5658800 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/routes/modules/demos.ts @@ -0,0 +1,38 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'ic:baseline-view-in-ar', + keepAlive: true, + order: 1000, + title: $t('demos.title'), + }, + name: 'Demos', + path: '/demos', + children: [ + { + meta: { + title: $t('demos.naive'), + }, + name: 'NaiveDemos', + path: '/demos/naive', + component: () => import('#/views/demos/naive/index.vue'), + }, + { + meta: { + title: $t('demos.table'), + }, + name: 'Table', + path: '/demos/table', + component: () => import('#/views/demos/table/index.vue'), + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-naive/src/router/routes/modules/vben.ts b/apps/vben5/apps/web-naive/src/router/routes/modules/vben.ts new file mode 100644 index 000000000..44461a7fd --- /dev/null +++ b/apps/vben5/apps/web-naive/src/router/routes/modules/vben.ts @@ -0,0 +1,82 @@ +import type { RouteRecordRaw } from 'vue-router'; + +import { + VBEN_ANT_PREVIEW_URL, + VBEN_DOC_URL, + VBEN_ELE_PREVIEW_URL, + VBEN_GITHUB_URL, + VBEN_LOGO_URL, +} from '@vben/constants'; +import { SvgAntdvLogoIcon } from '@vben/icons'; + +import { BasicLayout, IFrameView } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + badgeType: 'dot', + icon: VBEN_LOGO_URL, + order: 9999, + title: $t('demos.vben.title'), + }, + name: 'VbenProject', + path: '/vben-admin', + children: [ + { + name: 'VbenAbout', + path: '/vben-admin/about', + component: () => import('#/views/_core/about/index.vue'), + meta: { + icon: 'lucide:copyright', + title: $t('demos.vben.about'), + }, + }, + { + name: 'VbenDocument', + path: '/vben-admin/document', + component: IFrameView, + meta: { + icon: 'lucide:book-open-text', + link: VBEN_DOC_URL, + title: $t('demos.vben.document'), + }, + }, + { + name: 'VbenGithub', + path: '/vben-admin/github', + component: IFrameView, + meta: { + icon: 'mdi:github', + link: VBEN_GITHUB_URL, + title: 'Github', + }, + }, + { + name: 'VbenAntd', + path: '/vben-admin/antd', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: SvgAntdvLogoIcon, + link: VBEN_ANT_PREVIEW_URL, + title: $t('demos.vben.antdv'), + }, + }, + { + name: 'VbenElementPlus', + path: '/vben-admin/ele', + component: IFrameView, + meta: { + badgeType: 'dot', + icon: 'logos:element', + link: VBEN_ELE_PREVIEW_URL, + title: $t('demos.vben.element-plus'), + }, + }, + ], + }, +]; + +export default routes; diff --git a/apps/vben5/apps/web-naive/src/store/auth.ts b/apps/vben5/apps/web-naive/src/store/auth.ts new file mode 100644 index 000000000..20aac5622 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/store/auth.ts @@ -0,0 +1,116 @@ +import type { Recordable, UserInfo } from '@vben/types'; + +import { ref } from 'vue'; +import { useRouter } from 'vue-router'; + +import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants'; +import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores'; + +import { defineStore } from 'pinia'; + +import { notification } from '#/adapter/naive'; +import { getAccessCodesApi, getUserInfoApi, loginApi, logoutApi } from '#/api'; +import { $t } from '#/locales'; + +export const useAuthStore = defineStore('auth', () => { + const accessStore = useAccessStore(); + const userStore = useUserStore(); + const router = useRouter(); + + const loginLoading = ref(false); + + /** + * 异步处理登录操作 + * Asynchronously handle the login process + * @param params 登录表单数据 + */ + async function authLogin( + params: Recordable, + onSuccess?: () => Promise | void, + ) { + // 异步处理用户登录操作并获取 accessToken + let userInfo: null | UserInfo = null; + try { + loginLoading.value = true; + const { accessToken } = await loginApi(params); + + // 如果成功获取到 accessToken + if (accessToken) { + // 将 accessToken 存储到 accessStore 中 + accessStore.setAccessToken(accessToken); + + // 获取用户信息并存储到 accessStore 中 + const [fetchUserInfoResult, accessCodes] = await Promise.all([ + fetchUserInfo(), + getAccessCodesApi(), + ]); + + userInfo = fetchUserInfoResult; + + userStore.setUserInfo(userInfo); + accessStore.setAccessCodes(accessCodes); + + if (accessStore.loginExpired) { + accessStore.setLoginExpired(false); + } else { + onSuccess + ? await onSuccess?.() + : await router.push(userInfo.homePath || DEFAULT_HOME_PATH); + } + + if (userInfo?.realName) { + notification.success({ + content: $t('authentication.loginSuccess'), + description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`, + duration: 3000, + }); + } + } + } finally { + loginLoading.value = false; + } + + return { + userInfo, + }; + } + + async function logout(redirect: boolean = true) { + try { + await logoutApi(); + } catch { + // 不做任何处理 + } + resetAllStores(); + accessStore.setLoginExpired(false); + + // 回登录页带上当前路由地址 + await router.replace({ + path: LOGIN_PATH, + query: redirect + ? { + redirect: encodeURIComponent(router.currentRoute.value.fullPath), + } + : {}, + }); + } + + async function fetchUserInfo() { + let userInfo: null | UserInfo = null; + userInfo = await getUserInfoApi(); + userStore.setUserInfo(userInfo); + return userInfo; + } + + function $reset() { + loginLoading.value = false; + } + + return { + $reset, + authLogin, + fetchUserInfo, + loginLoading, + logout, + }; +}); diff --git a/apps/vben5/apps/web-naive/src/store/index.ts b/apps/vben5/apps/web-naive/src/store/index.ts new file mode 100644 index 000000000..269586ee8 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/store/index.ts @@ -0,0 +1 @@ +export * from './auth'; diff --git a/apps/vben5/apps/web-naive/src/views/_core/README.md b/apps/vben5/apps/web-naive/src/views/_core/README.md new file mode 100644 index 000000000..8248afe6c --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/README.md @@ -0,0 +1,3 @@ +# \_core + +此目录包含应用程序正常运行所需的基本视图。这些视图是应用程序布局中使用的视图。 diff --git a/apps/vben5/apps/web-naive/src/views/_core/about/index.vue b/apps/vben5/apps/web-naive/src/views/_core/about/index.vue new file mode 100644 index 000000000..0ee524335 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/about/index.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/authentication/code-login.vue b/apps/vben5/apps/web-naive/src/views/_core/authentication/code-login.vue new file mode 100644 index 000000000..556b273af --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/authentication/code-login.vue @@ -0,0 +1,65 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/authentication/forget-password.vue b/apps/vben5/apps/web-naive/src/views/_core/authentication/forget-password.vue new file mode 100644 index 000000000..fef0d4279 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/authentication/forget-password.vue @@ -0,0 +1,43 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/authentication/login.vue b/apps/vben5/apps/web-naive/src/views/_core/authentication/login.vue new file mode 100644 index 000000000..099e4c8c0 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/authentication/login.vue @@ -0,0 +1,98 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/authentication/qrcode-login.vue b/apps/vben5/apps/web-naive/src/views/_core/authentication/qrcode-login.vue new file mode 100644 index 000000000..23f5f2dad --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/authentication/qrcode-login.vue @@ -0,0 +1,10 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/authentication/register.vue b/apps/vben5/apps/web-naive/src/views/_core/authentication/register.vue new file mode 100644 index 000000000..daf89c447 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/authentication/register.vue @@ -0,0 +1,96 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/fallback/coming-soon.vue b/apps/vben5/apps/web-naive/src/views/_core/fallback/coming-soon.vue new file mode 100644 index 000000000..f394930f2 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/fallback/coming-soon.vue @@ -0,0 +1,7 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/fallback/forbidden.vue b/apps/vben5/apps/web-naive/src/views/_core/fallback/forbidden.vue new file mode 100644 index 000000000..8ea65fedb --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/fallback/forbidden.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/fallback/internal-error.vue b/apps/vben5/apps/web-naive/src/views/_core/fallback/internal-error.vue new file mode 100644 index 000000000..819a47d5e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/fallback/internal-error.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/fallback/not-found.vue b/apps/vben5/apps/web-naive/src/views/_core/fallback/not-found.vue new file mode 100644 index 000000000..4d178e9cb --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/fallback/not-found.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/_core/fallback/offline.vue b/apps/vben5/apps/web-naive/src/views/_core/fallback/offline.vue new file mode 100644 index 000000000..5de4a88de --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/_core/fallback/offline.vue @@ -0,0 +1,9 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-trends.vue b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-trends.vue new file mode 100644 index 000000000..fadfc917c --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-trends.vue @@ -0,0 +1,100 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-data.vue b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-data.vue new file mode 100644 index 000000000..30c4265df --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-data.vue @@ -0,0 +1,84 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-sales.vue b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-sales.vue new file mode 100644 index 000000000..260520b84 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-sales.vue @@ -0,0 +1,48 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-source.vue b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-source.vue new file mode 100644 index 000000000..e0d0aab5e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits-source.vue @@ -0,0 +1,67 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits.vue b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits.vue new file mode 100644 index 000000000..7e1f14ee6 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/analytics-visits.vue @@ -0,0 +1,57 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/analytics/index.vue b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/index.vue new file mode 100644 index 000000000..00b34df1e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/analytics/index.vue @@ -0,0 +1,90 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/dashboard/workspace/index.vue b/apps/vben5/apps/web-naive/src/views/dashboard/workspace/index.vue new file mode 100644 index 000000000..b95d61381 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/dashboard/workspace/index.vue @@ -0,0 +1,266 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/demos/naive/index.vue b/apps/vben5/apps/web-naive/src/views/demos/naive/index.vue new file mode 100644 index 000000000..41d55109e --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/demos/naive/index.vue @@ -0,0 +1,68 @@ + + + diff --git a/apps/vben5/apps/web-naive/src/views/demos/table/index.vue b/apps/vben5/apps/web-naive/src/views/demos/table/index.vue new file mode 100644 index 000000000..ddc958bc3 --- /dev/null +++ b/apps/vben5/apps/web-naive/src/views/demos/table/index.vue @@ -0,0 +1,38 @@ + + + + + diff --git a/apps/vben5/apps/web-naive/tailwind.config.mjs b/apps/vben5/apps/web-naive/tailwind.config.mjs new file mode 100644 index 000000000..f17f556fa --- /dev/null +++ b/apps/vben5/apps/web-naive/tailwind.config.mjs @@ -0,0 +1 @@ +export { default } from '@vben/tailwind-config'; diff --git a/apps/vben5/apps/web-naive/tsconfig.json b/apps/vben5/apps/web-naive/tsconfig.json new file mode 100644 index 000000000..02c287fe6 --- /dev/null +++ b/apps/vben5/apps/web-naive/tsconfig.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/web-app.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "#/*": ["./src/*"] + } + }, + "references": [{ "path": "./tsconfig.node.json" }], + "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] +} diff --git a/apps/vben5/apps/web-naive/tsconfig.node.json b/apps/vben5/apps/web-naive/tsconfig.node.json new file mode 100644 index 000000000..c2f0d86cc --- /dev/null +++ b/apps/vben5/apps/web-naive/tsconfig.node.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://json.schemastore.org/tsconfig", + "extends": "@vben/tsconfig/node.json", + "compilerOptions": { + "composite": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + "noEmit": false + }, + "include": ["vite.config.mts"] +} diff --git a/apps/vben5/apps/web-naive/vite.config.mts b/apps/vben5/apps/web-naive/vite.config.mts new file mode 100644 index 000000000..b6360f1d4 --- /dev/null +++ b/apps/vben5/apps/web-naive/vite.config.mts @@ -0,0 +1,20 @@ +import { defineConfig } from '@vben/vite-config'; + +export default defineConfig(async () => { + return { + application: {}, + vite: { + server: { + proxy: { + '/api': { + changeOrigin: true, + rewrite: (path) => path.replace(/^\/api/, ''), + // mock代理目标地址 + target: 'http://localhost:5320/api', + ws: true, + }, + }, + }, + }, + }; +}); diff --git a/apps/vben5/cspell.json b/apps/vben5/cspell.json new file mode 100644 index 000000000..89545b432 --- /dev/null +++ b/apps/vben5/cspell.json @@ -0,0 +1,68 @@ +{ + "$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json", + "version": "0.2", + "language": "en,en-US", + "allowCompoundWords": true, + "words": [ + "acmr", + "antd", + "antdv", + "astro", + "brotli", + "clsx", + "defu", + "demi", + "echarts", + "ependencies", + "esno", + "etag", + "execa", + "iconify", + "iconoir", + "intlify", + "lockb", + "lucide", + "minh", + "minw", + "mkdist", + "mockjs", + "naiveui", + "nocheck", + "noopener", + "noreferrer", + "nprogress", + "nuxt", + "pinia", + "prefixs", + "publint", + "qrcode", + "shadcn", + "sonner", + "sortablejs", + "styl", + "taze", + "ui-kit", + "uicons", + "unplugin", + "unref", + "vben", + "vbenjs", + "vite", + "vitejs", + "vitepress", + "vnode", + "vueuse", + "yxxx" + ], + "ignorePaths": [ + "**/node_modules/**", + "**/dist/**", + "**/*-dist/**", + "**/icons/**", + "pnpm-lock.yaml", + "**/*.log", + "**/*.test.ts", + "**/*.spec.ts", + "**/__tests__/**" + ] +} diff --git a/apps/vben5/docs/.vitepress/components/demo-preview.vue b/apps/vben5/docs/.vitepress/components/demo-preview.vue new file mode 100644 index 000000000..4c8829f88 --- /dev/null +++ b/apps/vben5/docs/.vitepress/components/demo-preview.vue @@ -0,0 +1,45 @@ + + + diff --git a/apps/vben5/docs/.vitepress/components/index.ts b/apps/vben5/docs/.vitepress/components/index.ts new file mode 100644 index 000000000..9430871e6 --- /dev/null +++ b/apps/vben5/docs/.vitepress/components/index.ts @@ -0,0 +1 @@ +export { default as DemoPreview } from './demo-preview.vue'; diff --git a/apps/vben5/docs/.vitepress/components/preview-group.vue b/apps/vben5/docs/.vitepress/components/preview-group.vue new file mode 100644 index 000000000..c8c6e83c7 --- /dev/null +++ b/apps/vben5/docs/.vitepress/components/preview-group.vue @@ -0,0 +1,108 @@ + + + diff --git a/apps/vben5/docs/.vitepress/config/en.mts b/apps/vben5/docs/.vitepress/config/en.mts new file mode 100644 index 000000000..3f7dd4fa8 --- /dev/null +++ b/apps/vben5/docs/.vitepress/config/en.mts @@ -0,0 +1,229 @@ +import { type DefaultTheme, defineConfig } from 'vitepress'; + +import { version } from '../../../package.json'; + +export const en = defineConfig({ + description: 'Vben Admin & Enterprise level management system framework', + lang: 'en-US', + themeConfig: { + darkModeSwitchLabel: 'Theme', + darkModeSwitchTitle: 'Switch to Dark Mode', + docFooter: { + next: 'Next Page', + prev: 'Previous Page', + }, + editLink: { + pattern: + 'https://github.com/vbenjs/vue-vben-admin/edit/main/docs/src/:path', + text: 'Edit this page on GitHub', + }, + footer: { + copyright: `Copyright © 2020-${new Date().getFullYear()} Vben`, + message: 'Released under the MIT License.', + }, + langMenuLabel: 'Language', + lastUpdated: { + formatOptions: { + dateStyle: 'short', + timeStyle: 'medium', + }, + text: 'Last updated on', + }, + lightModeSwitchTitle: 'Switch to Light Mode', + nav: nav(), + outline: { + label: 'Navigate', + }, + returnToTopLabel: 'Back to top', + sidebar: { + '/en/commercial/': { + base: '/en/commercial/', + items: sidebarCommercial(), + }, + '/en/guide/': { base: '/en/guide/', items: sidebarGuide() }, + }, + }, +}); + +function sidebarGuide(): DefaultTheme.SidebarItem[] { + return [ + { + collapsed: false, + text: 'Introduction', + items: [ + { + link: 'introduction/vben', + text: 'About Vben Admin', + }, + { + link: 'introduction/why', + text: 'Why Choose Us?', + }, + { link: 'introduction/quick-start', text: 'Quick Start' }, + { link: 'introduction/thin', text: 'Lite Version' }, + ], + }, + { + text: 'Basics', + items: [ + { link: 'essentials/concept', text: 'Basic Concepts' }, + { link: 'essentials/development', text: 'Local Development' }, + { link: 'essentials/route', text: 'Routing and Menu' }, + { link: 'essentials/settings', text: 'Configuration' }, + { link: 'essentials/icons', text: 'Icons' }, + { link: 'essentials/styles', text: 'Styles' }, + { link: 'essentials/external-module', text: 'External Modules' }, + { link: 'essentials/build', text: 'Build and Deployment' }, + { link: 'essentials/server', text: 'Server Interaction and Data Mock' }, + ], + }, + { + text: 'Advanced', + items: [ + { link: 'in-depth/login', text: 'Login' }, + { link: 'in-depth/theme', text: 'Theme' }, + { link: 'in-depth/access', text: 'Access Control' }, + { link: 'in-depth/locale', text: 'Internationalization' }, + { link: 'in-depth/features', text: 'Common Features' }, + { link: 'in-depth/check-updates', text: 'Check Updates' }, + { link: 'in-depth/loading', text: 'Global Loading' }, + { link: 'in-depth/ui-framework', text: 'UI Framework Switching' }, + ], + }, + { + text: 'Engineering', + items: [ + { link: 'project/standard', text: 'Standards' }, + { link: 'project/cli', text: 'CLI' }, + { link: 'project/dir', text: 'Directory Explanation' }, + { link: 'project/test', text: 'Unit Testing' }, + { link: 'project/tailwindcss', text: 'Tailwind CSS' }, + { link: 'project/changeset', text: 'Changeset' }, + { link: 'project/vite', text: 'Vite Config' }, + ], + }, + { + text: 'Others', + items: [ + { link: 'other/project-update', text: 'Project Update' }, + { link: 'other/remove-code', text: 'Remove Code' }, + { link: 'other/faq', text: 'FAQ' }, + ], + }, + ]; +} + +function sidebarCommercial(): DefaultTheme.SidebarItem[] { + return [ + { + link: 'community', + text: 'Community', + }, + { + link: 'technical-support', + text: 'Technical-support', + }, + { + link: 'customized', + text: 'Customized', + }, + ]; +} + +function nav(): DefaultTheme.NavItem[] { + return [ + { + activeMatch: '^/en/(guide|components)/', + text: 'Doc', + items: [ + { + activeMatch: '^/en/guide/', + link: '/en/guide/introduction/vben', + text: 'Guide', + }, + // { + // activeMatch: '^/en/components/', + // link: '/en/components/introduction', + // text: 'Components', + // }, + { + text: 'Historical Versions', + items: [ + { + link: 'https://doc.vvbin.cn', + text: '2.x Version Documentation', + }, + ], + }, + ], + }, + { + text: 'Demo', + items: [ + { + text: 'Vben Admin', + items: [ + { + link: 'https://www.vben.pro', + text: 'Demo Version', + }, + { + link: 'https://ant.vben.pro', + text: 'Ant Design Vue Version', + }, + { + link: 'https://naive.vben.pro', + text: 'Naive Version', + }, + { + link: 'https://ele.vben.pro', + text: 'Element Plus Version', + }, + ], + }, + { + text: 'Others', + items: [ + { + link: 'https://vben.vvbin.cn', + text: 'Vben Admin 2.x', + }, + ], + }, + ], + }, + { + text: version, + items: [ + { + link: 'https://github.com/vbenjs/vue-vben-admin/releases', + text: 'Changelog', + }, + { + link: 'https://github.com/orgs/vbenjs/projects/5', + text: 'Roadmap', + }, + { + link: 'https://github.com/vbenjs/vue-vben-admin/blob/main/.github/contributing.md', + text: 'Contribution', + }, + ], + }, + { + link: '/commercial/technical-support', + text: '🦄 Tech Support', + }, + { + link: '/sponsor/personal', + text: '✨ Sponsor', + }, + { + link: '/commercial/community', + text: '👨‍👦‍👦 Community', + }, + // { + // link: '/friend-links/', + // text: '🤝 Friend Links', + // }, + ]; +} diff --git a/apps/vben5/docs/.vitepress/config/index.mts b/apps/vben5/docs/.vitepress/config/index.mts new file mode 100644 index 000000000..6b8cb81d8 --- /dev/null +++ b/apps/vben5/docs/.vitepress/config/index.mts @@ -0,0 +1,25 @@ +import { withPwa } from '@vite-pwa/vitepress'; +import { defineConfigWithTheme } from 'vitepress'; + +import { en } from './en.mts'; +import { shared } from './shared.mts'; +import { zh } from './zh.mts'; + +export default withPwa( + defineConfigWithTheme({ + ...shared, + locales: { + en: { + label: 'English', + lang: 'en', + link: '/en/', + ...en, + }, + root: { + label: '简体中文', + lang: 'zh-CN', + ...zh, + }, + }, + }), +); diff --git a/apps/vben5/docs/.vitepress/config/plugins/demo-preview.ts b/apps/vben5/docs/.vitepress/config/plugins/demo-preview.ts new file mode 100644 index 000000000..03b1698ca --- /dev/null +++ b/apps/vben5/docs/.vitepress/config/plugins/demo-preview.ts @@ -0,0 +1,143 @@ +import type { MarkdownEnv, MarkdownRenderer } from 'vitepress'; + +import crypto from 'node:crypto'; +import { readdirSync } from 'node:fs'; +import { join } from 'node:path'; + +export const rawPathRegexp = + // eslint-disable-next-line regexp/no-super-linear-backtracking, regexp/strict + /^(.+?(?:\.([\da-z]+))?)(#[\w-]+)?(?: ?{(\d+(?:[,-]\d+)*)? ?(\S+)?})? ?(?:\[(.+)])?$/; + +function rawPathToToken(rawPath: string) { + const [ + filepath = '', + extension = '', + region = '', + lines = '', + lang = '', + rawTitle = '', + ] = (rawPathRegexp.exec(rawPath) || []).slice(1); + + const title = rawTitle || filepath.split('/').pop() || ''; + + return { extension, filepath, lang, lines, region, title }; +} + +export const demoPreviewPlugin = (md: MarkdownRenderer) => { + md.core.ruler.after('inline', 'demo-preview', (state) => { + const insertComponentImport = (importString: string) => { + const index = state.tokens.findIndex( + (i) => i.type === 'html_block' && i.content.match(/\n`; + state.tokens.splice(0, 0, importComponent); + } else { + if (state.tokens[index]) { + const content = state.tokens[index].content; + state.tokens[index].content = content.replace( + '', + `${importString}\n`, + ); + } + } + }; + // Define the regular expression to match the desired pattern + const regex = /]*\sdir="([^"]*)"/g; + // Iterate through the Markdown content and replace the pattern + state.src = state.src.replaceAll(regex, (_match, dir) => { + const componentDir = join(process.cwd(), 'src', dir).replaceAll( + '\\', + '/', + ); + + let childFiles: string[] = []; + let dirExists = true; + + try { + childFiles = + readdirSync(componentDir, { + encoding: 'utf8', + recursive: false, + withFileTypes: false, + }) || []; + } catch { + dirExists = false; + } + + if (!dirExists) { + return ''; + } + + const uniqueWord = generateContentHash(componentDir); + + const ComponentName = `DemoComponent_${uniqueWord}`; + insertComponentImport( + `import ${ComponentName} from '${componentDir}/index.vue'`, + ); + const { path: _path } = state.env as MarkdownEnv; + + const index = state.tokens.findIndex((i) => i.content.match(regex)); + + if (!state.tokens[index]) { + return ''; + } + const firstString = 'index.vue'; + childFiles = childFiles.sort((a, b) => { + if (a === firstString) return -1; + if (b === firstString) return 1; + return a.localeCompare(b, 'en', { sensitivity: 'base' }); + }); + state.tokens[index].content = + `<${ComponentName}/> + `; + + const _dummyToken = new state.Token('', '', 0); + const tokenArray: Array = []; + childFiles.forEach((filename) => { + // const slotName = filename.replace(extname(filename), ''); + + const templateStart = new state.Token('html_inline', '', 0); + templateStart.content = `'; + tokenArray.push(templateEnd); + }); + const endTag = new state.Token('html_inline', '', 0); + endTag.content = ''; + tokenArray.push(endTag); + + state.tokens.splice(index + 1, 0, ...tokenArray); + + // console.log( + // state.md.renderer.render(state.tokens, state?.options ?? [], state.env), + // ); + return ''; + }); + }); +}; + +function generateContentHash(input: string, length: number = 10): string { + // 使用 SHA-256 生成哈希值 + const hash = crypto.createHash('sha256').update(input).digest('hex'); + + // 将哈希值转换为 Base36 编码,并取指定长度的字符作为结果 + return Number.parseInt(hash, 16).toString(36).slice(0, length); +} diff --git a/apps/vben5/docs/.vitepress/config/shared.mts b/apps/vben5/docs/.vitepress/config/shared.mts new file mode 100644 index 000000000..c48cc6097 --- /dev/null +++ b/apps/vben5/docs/.vitepress/config/shared.mts @@ -0,0 +1,172 @@ +import type { PwaOptions } from '@vite-pwa/vitepress'; +import type { HeadConfig } from 'vitepress'; + +import { resolve } from 'node:path'; + +import { + viteArchiverPlugin, + viteVxeTableImportsPlugin, +} from '@vben/vite-config'; + +import { + GitChangelog, + GitChangelogMarkdownSection, +} from '@nolebase/vitepress-plugin-git-changelog/vite'; +import tailwind from 'tailwindcss'; +import { defineConfig, postcssIsolateStyles } from 'vitepress'; +import { + groupIconMdPlugin, + groupIconVitePlugin, +} from 'vitepress-plugin-group-icons'; + +import { demoPreviewPlugin } from './plugins/demo-preview'; +import { search as zhSearch } from './zh.mts'; + +export const shared = defineConfig({ + appearance: 'dark', + head: head(), + markdown: { + preConfig(md) { + md.use(demoPreviewPlugin); + md.use(groupIconMdPlugin); + }, + }, + pwa: pwa(), + srcDir: 'src', + themeConfig: { + i18nRouting: true, + logo: 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/logo-v1.webp', + search: { + options: { + locales: { + ...zhSearch, + }, + }, + provider: 'local', + }, + siteTitle: 'Vben Admin', + socialLinks: [ + { icon: 'github', link: 'https://github.com/vbenjs/vue-vben-admin' }, + ], + }, + title: 'Vben Admin', + vite: { + build: { + chunkSizeWarningLimit: Infinity, + minify: 'terser', + }, + css: { + postcss: { + plugins: [ + tailwind(), + postcssIsolateStyles({ includeFiles: [/vp-doc\.css/] }), + ], + }, + preprocessorOptions: { + scss: { + api: 'modern', + }, + }, + }, + json: { + stringify: true, + }, + plugins: [ + GitChangelog({ + mapAuthors: [ + { + mapByNameAliases: ['Vben'], + name: 'vben', + username: 'anncwb', + }, + { + name: 'vince', + username: 'vince292007', + }, + { + name: 'Li Kui', + username: 'likui628', + }, + ], + repoURL: () => 'https://github.com/vbenjs/vue-vben-admin', + }), + GitChangelogMarkdownSection(), + viteArchiverPlugin({ outputDir: '.vitepress' }), + groupIconVitePlugin(), + await viteVxeTableImportsPlugin(), + ], + server: { + fs: { + allow: ['../..'], + }, + host: true, + port: 6173, + }, + + ssr: { + external: ['@vue/repl'], + }, + }, +}); + +function head(): HeadConfig[] { + return [ + ['meta', { content: 'Vbenjs Team', name: 'author' }], + [ + 'meta', + { + content: 'vben, vitejs, vite, shacdn-ui, vue', + name: 'keywords', + }, + ], + ['link', { href: '/favicon.ico', rel: 'icon', type: 'image/svg+xml' }], + [ + 'meta', + { + content: + 'width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no', + name: 'viewport', + }, + ], + ['meta', { content: 'vben admin docs', name: 'keywords' }], + ['link', { href: '/favicon.ico', rel: 'icon' }], + // [ + // 'script', + // { + // src: 'https://cdn.tailwindcss.com', + // }, + // ], + ]; +} + +function pwa(): PwaOptions { + return { + includeManifestIcons: false, + manifest: { + description: + 'Vben Admin is a modern admin dashboard template based on Vue 3. ', + icons: [ + { + sizes: '192x192', + src: 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/pwa-icon-192.png', + type: 'image/png', + }, + { + sizes: '512x512', + src: 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/pwa-icon-512.png', + type: 'image/png', + }, + ], + id: '/', + name: 'Vben Admin Doc', + short_name: 'vben_admin_doc', + theme_color: '#ffffff', + }, + outDir: resolve(process.cwd(), '.vitepress/dist'), + registerType: 'autoUpdate', + workbox: { + globPatterns: ['**/*.{css,js,html,svg,png,ico,txt,woff2}'], + maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, + }, + }; +} diff --git a/apps/vben5/docs/.vitepress/config/zh.mts b/apps/vben5/docs/.vitepress/config/zh.mts new file mode 100644 index 000000000..6b31658ed --- /dev/null +++ b/apps/vben5/docs/.vitepress/config/zh.mts @@ -0,0 +1,334 @@ +import { type DefaultTheme, defineConfig } from 'vitepress'; + +import { version } from '../../../package.json'; + +export const zh = defineConfig({ + description: 'Vben Admin & 企业级管理系统框架', + lang: 'zh-Hans', + themeConfig: { + darkModeSwitchLabel: '主题', + darkModeSwitchTitle: '切换到深色模式', + docFooter: { + next: '下一页', + prev: '上一页', + }, + editLink: { + pattern: + 'https://github.com/vbenjs/vue-vben-admin/edit/main/docs/src/:path', + text: '在 GitHub 上编辑此页面', + }, + footer: { + copyright: `Copyright © 2020-${new Date().getFullYear()} Vben`, + message: '基于 MIT 许可发布.', + }, + langMenuLabel: '多语言', + lastUpdated: { + formatOptions: { + dateStyle: 'short', + timeStyle: 'medium', + }, + text: '最后更新于', + }, + lightModeSwitchTitle: '切换到浅色模式', + nav: nav(), + + outline: { + label: '页面导航', + }, + returnToTopLabel: '回到顶部', + + sidebar: { + '/commercial/': { base: '/commercial/', items: sidebarCommercial() }, + '/components/': { base: '/components/', items: sidebarComponents() }, + '/guide/': { base: '/guide/', items: sidebarGuide() }, + }, + sidebarMenuLabel: '菜单', + }, +}); + +function sidebarGuide(): DefaultTheme.SidebarItem[] { + return [ + { + collapsed: false, + text: '简介', + items: [ + { + link: 'introduction/vben', + text: '关于 Vben Admin', + }, + { + link: 'introduction/why', + text: '为什么选择我们?', + }, + { link: 'introduction/quick-start', text: '快速开始' }, + { link: 'introduction/thin', text: '精简版本' }, + { + base: '/', + link: 'components/introduction', + text: '组件文档', + }, + ], + }, + { + text: '基础', + items: [ + { link: 'essentials/concept', text: '基础概念' }, + { link: 'essentials/development', text: '本地开发' }, + { link: 'essentials/route', text: '路由和菜单' }, + { link: 'essentials/settings', text: '配置' }, + { link: 'essentials/icons', text: '图标' }, + { link: 'essentials/styles', text: '样式' }, + { link: 'essentials/external-module', text: '外部模块' }, + { link: 'essentials/build', text: '构建与部署' }, + { link: 'essentials/server', text: '服务端交互与数据Mock' }, + ], + }, + { + text: '深入', + items: [ + { link: 'in-depth/login', text: '登录' }, + // { link: 'in-depth/layout', text: '布局' }, + { link: 'in-depth/theme', text: '主题' }, + { link: 'in-depth/access', text: '权限' }, + { link: 'in-depth/locale', text: '国际化' }, + { link: 'in-depth/features', text: '常用功能' }, + { link: 'in-depth/check-updates', text: '检查更新' }, + { link: 'in-depth/loading', text: '全局loading' }, + { link: 'in-depth/ui-framework', text: '组件库切换' }, + ], + }, + { + text: '工程', + items: [ + { link: 'project/standard', text: '规范' }, + { link: 'project/cli', text: 'CLI' }, + { link: 'project/dir', text: '目录说明' }, + { link: 'project/test', text: '单元测试' }, + { link: 'project/tailwindcss', text: 'Tailwind CSS' }, + { link: 'project/changeset', text: 'Changeset' }, + { link: 'project/vite', text: 'Vite Config' }, + ], + }, + { + text: '其他', + items: [ + { link: 'other/project-update', text: '项目更新' }, + { link: 'other/remove-code', text: '移除代码' }, + { link: 'other/faq', text: '常见问题' }, + ], + }, + ]; +} + +function sidebarCommercial(): DefaultTheme.SidebarItem[] { + return [ + { + link: 'community', + text: '交流群', + }, + { + link: 'technical-support', + text: '技术支持', + }, + { + link: 'customized', + text: '定制开发', + }, + ]; +} + +function sidebarComponents(): DefaultTheme.SidebarItem[] { + return [ + { + text: '组件', + items: [ + { + link: 'introduction', + text: '介绍', + }, + ], + }, + { + collapsed: false, + text: '通用组件', + items: [ + { + link: 'common-ui/vben-modal', + text: 'Modal 模态框', + }, + { + link: 'common-ui/vben-drawer', + text: 'Drawer 抽屉', + }, + { + link: 'common-ui/vben-form', + text: 'Form 表单', + }, + { + link: 'common-ui/vben-vxe-table', + text: 'Vxe Table 表格', + }, + { + link: 'common-ui/vben-count-to-animator', + text: 'CountToAnimator 数字动画', + }, + ], + }, + ]; +} + +function nav(): DefaultTheme.NavItem[] { + return [ + { + activeMatch: '^/(guide|components)/', + text: '文档', + items: [ + { + activeMatch: '^/guide/', + link: '/guide/introduction/vben', + text: '指南', + }, + { + activeMatch: '^/components/', + link: '/components/introduction', + text: '组件', + }, + { + text: '历史版本', + items: [ + { + link: 'https://doc.vvbin.cn', + text: '2.x版本文档', + }, + ], + }, + ], + }, + { + text: '演示', + items: [ + { + text: 'Vben Admin', + items: [ + { + link: 'https://www.vben.pro', + text: '演示版本', + }, + { + link: 'https://ant.vben.pro', + text: 'Ant Design Vue 版本', + }, + { + link: 'https://naive.vben.pro', + text: 'Naive 版本', + }, + { + link: 'https://ele.vben.pro', + text: 'Element Plus版本', + }, + ], + }, + { + text: '其他', + items: [ + { + link: 'https://vben.vvbin.cn', + text: 'Vben Admin 2.x', + }, + ], + }, + ], + }, + { + text: version, + items: [ + { + link: 'https://github.com/vbenjs/vue-vben-admin/releases', + text: '更新日志', + }, + { + link: 'https://github.com/orgs/vbenjs/projects/5', + text: '路线图', + }, + { + link: 'https://github.com/vbenjs/vue-vben-admin/blob/main/.github/contributing.md', + text: '贡献', + }, + ], + }, + { + link: '/commercial/technical-support', + text: '🦄 技术支持', + }, + { + link: '/sponsor/personal', + text: '✨ 赞助', + }, + { + link: '/commercial/community', + text: '👨‍👦‍👦 交流群', + // items: [ + // { + // link: 'https://qun.qq.com/qqweb/qunpro/share?_wv=3&_wwv=128&appChannel=share&inviteCode=22ySzj7pKiw&businessType=9&from=246610&biz=ka&mainSourceId=share&subSourceId=others&jumpsource=shorturl#/pc', + // text: 'QQ频道', + // }, + // { + // link: 'https://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=mjZmlhgVzzUxvdxllB6C1vHpX8O8QRL0&authKey=DBdFbBwERmfaKY95JvRWqLCJIRGJAmKyZbrpzZ41EKDMZ5SR6MfbjOBaaNRN73fr&noverify=0&group_code=4286109', + // text: 'QQ群', + // }, + // { + // link: 'https://discord.gg/VU62jTecad', + // text: 'Discord', + // }, + // ], + }, + // { + // link: '/friend-links/', + // text: '🤝 友情链接', + // }, + ]; +} + +export const search: DefaultTheme.AlgoliaSearchOptions['locales'] = { + root: { + placeholder: '搜索文档', + translations: { + button: { + buttonAriaLabel: '搜索文档', + buttonText: '搜索文档', + }, + modal: { + errorScreen: { + helpText: '你可能需要检查你的网络连接', + titleText: '无法获取结果', + }, + footer: { + closeText: '关闭', + navigateText: '切换', + searchByText: '搜索提供者', + selectText: '选择', + }, + noResultsScreen: { + noResultsText: '无法找到相关结果', + reportMissingResultsLinkText: '点击反馈', + reportMissingResultsText: '你认为该查询应该有结果?', + suggestedQueryText: '你可以尝试查询', + }, + searchBox: { + cancelButtonAriaLabel: '取消', + cancelButtonText: '取消', + resetButtonAriaLabel: '清除查询条件', + resetButtonTitle: '清除查询条件', + }, + startScreen: { + favoriteSearchesTitle: '收藏', + noRecentSearchesText: '没有搜索历史', + recentSearchesTitle: '搜索历史', + removeFavoriteSearchButtonTitle: '从收藏中移除', + removeRecentSearchButtonTitle: '从搜索历史中移除', + saveRecentSearchButtonTitle: '保存至搜索历史', + }, + }, + }, + }, +}; diff --git a/apps/vben5/docs/.vitepress/theme/components/site-layout.vue b/apps/vben5/docs/.vitepress/theme/components/site-layout.vue new file mode 100644 index 000000000..d643cae98 --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/components/site-layout.vue @@ -0,0 +1,97 @@ + + + + + diff --git a/apps/vben5/docs/.vitepress/theme/components/vben-contributors.vue b/apps/vben5/docs/.vitepress/theme/components/vben-contributors.vue new file mode 100644 index 000000000..9b887d925 --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/components/vben-contributors.vue @@ -0,0 +1,29 @@ + + + + + diff --git a/apps/vben5/docs/.vitepress/theme/index.ts b/apps/vben5/docs/.vitepress/theme/index.ts new file mode 100644 index 000000000..7d4d3dc2d --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/index.ts @@ -0,0 +1,29 @@ +// https://vitepress.dev/guide/custom-theme +import type { EnhanceAppContext, Theme } from 'vitepress'; + +import { NolebaseGitChangelogPlugin } from '@nolebase/vitepress-plugin-git-changelog/client'; +import DefaultTheme from 'vitepress/theme'; + +import { DemoPreview } from '../components'; +import SiteLayout from './components/site-layout.vue'; +import VbenContributors from './components/vben-contributors.vue'; +import { initHmPlugin } from './plugins/hm'; + +import './styles'; + +import 'virtual:group-icons.css'; +import '@nolebase/vitepress-plugin-git-changelog/client/style.css'; + +export default { + async enhanceApp(ctx: EnhanceAppContext) { + const { app } = ctx; + app.component('VbenContributors', VbenContributors); + app.component('DemoPreview', DemoPreview); + app.use(NolebaseGitChangelogPlugin); + + // 百度统计 + initHmPlugin(); + }, + extends: DefaultTheme, + Layout: SiteLayout, +} satisfies Theme; diff --git a/apps/vben5/docs/.vitepress/theme/plugins/hm.ts b/apps/vben5/docs/.vitepress/theme/plugins/hm.ts new file mode 100644 index 000000000..5e0a93182 --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/plugins/hm.ts @@ -0,0 +1,28 @@ +import { inBrowser } from 'vitepress'; + +const SITE_ID = '2e443a834727c065877c01d89921545e'; + +declare global { + interface Window { + _hmt: any; + } +} + +function registerAnalytics() { + window._hmt = window._hmt || []; + const script = document.createElement('script'); + script.innerHTML = `var _hmt = _hmt || []; + (function() { + var hm = document.createElement("script"); + hm.src = "https://hm.baidu.com/hm.js?${SITE_ID}"; + var s = document.getElementsByTagName("script")[0]; + s.parentNode.insertBefore(hm, s); + })()`; + document.querySelector('head')?.append(script); +} + +export function initHmPlugin() { + if (inBrowser && import.meta.env.PROD) { + registerAnalytics(); + } +} diff --git a/apps/vben5/docs/.vitepress/theme/styles/base.css b/apps/vben5/docs/.vitepress/theme/styles/base.css new file mode 100644 index 000000000..8eb423afa --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/styles/base.css @@ -0,0 +1,22 @@ +html.dark { + color-scheme: dark; +} + +.dark .VPContent { + /* background-color: #14161a; */ +} + +.form-valid-error p { + margin: 0; +} + +/* 顶部导航栏选中项样式 */ +.VPNavBarMenuLink, +.VPNavBarMenuGroup { + border-bottom: 1px solid transparent; +} + +.VPNavBarMenuLink.active, +.VPNavBarMenuGroup.active { + border-bottom-color: var(--vp-c-brand-1); +} diff --git a/apps/vben5/docs/.vitepress/theme/styles/index.ts b/apps/vben5/docs/.vitepress/theme/styles/index.ts new file mode 100644 index 000000000..566e63f8c --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/styles/index.ts @@ -0,0 +1,4 @@ +import '@vben/styles'; + +import './variables.css'; +import './base.css'; diff --git a/apps/vben5/docs/.vitepress/theme/styles/variables.css b/apps/vben5/docs/.vitepress/theme/styles/variables.css new file mode 100644 index 000000000..d633803ce --- /dev/null +++ b/apps/vben5/docs/.vitepress/theme/styles/variables.css @@ -0,0 +1,127 @@ +/** + * Customize default theme styling by overriding CSS variables: + * https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css + */ + +/** + * Colors + * + * Each colors have exact same color scale system with 3 levels of solid + * colors with different brightness, and 1 soft color. + * + * - `XXX-1`: The most solid color used mainly for colored text. It must + * satisfy the contrast ratio against when used on top of `XXX-soft`. + * + * - `XXX-2`: The color used mainly for hover state of the button. + * + * - `XXX-3`: The color for solid background, such as bg color of the button. + * It must satisfy the contrast ratio with pure white (#ffffff) text on + * top of it. + * + * - `XXX-soft`: The color used for subtle background such as custom container + * or badges. It must satisfy the contrast ratio when putting `XXX-1` colors + * on top of it. + * + * The soft color must be semi transparent alpha channel. This is crucial + * because it allows adding multiple "soft" colors on top of each other + * to create a accent, such as when having inline code block inside + * custom containers. + * + * - `default`: The color used purely for subtle indication without any + * special meanings attched to it such as bg color for menu hover state. + * + * - `brand`: Used for primary brand colors, such as link text, button with + * brand theme, etc. + * + * - `tip`: Used to indicate useful information. The default theme uses the + * brand color for this by default. + * + * - `warning`: Used to indicate warning to the users. Used in custom + * container, badges, etc. + * + * - `danger`: Used to show error, or dangerous message to the users. Used + * in custom container, badges, etc. + * -------------------------------------------------------------------------- */ + +:root { + /* --vp-c-indigo-1: #4f69fd; */ + --vp-c-default-1: var(--vp-c-gray-1); + --vp-c-default-2: var(--vp-c-gray-2); + --vp-c-default-3: var(--vp-c-gray-3); + --vp-c-default-soft: var(--vp-c-gray-soft); + --vp-c-brand-1: var(--vp-c-indigo-1); + --vp-c-brand-2: var(--vp-c-indigo-2); + --vp-c-brand-3: var(--vp-c-indigo-3); + --vp-c-brand-soft: var(--vp-c-indigo-soft); + --vp-c-tip-1: var(--vp-c-brand-1); + --vp-c-tip-2: var(--vp-c-brand-2); + --vp-c-tip-3: var(--vp-c-brand-3); + --vp-c-tip-soft: var(--vp-c-brand-soft); + --vp-c-warning-1: var(--vp-c-yellow-1); + --vp-c-warning-2: var(--vp-c-yellow-2); + --vp-c-warning-3: var(--vp-c-yellow-3); + --vp-c-warning-soft: var(--vp-c-yellow-soft); + --vp-c-danger-1: var(--vp-c-red-1); + --vp-c-danger-2: var(--vp-c-red-2); + --vp-c-danger-3: var(--vp-c-red-3); + --vp-c-danger-soft: var(--vp-c-red-soft); + + /** + * Component: Button + * -------------------------------------------------------------------------- */ + + --vp-button-brand-border: transparent; + --vp-button-brand-text: var(--vp-c-white); + --vp-button-brand-bg: var(--vp-c-brand-3); + --vp-button-brand-hover-border: transparent; + --vp-button-brand-hover-text: var(--vp-c-white); + --vp-button-brand-hover-bg: var(--vp-c-brand-2); + --vp-button-brand-active-border: transparent; + --vp-button-brand-active-text: var(--vp-c-white); + --vp-button-brand-active-bg: var(--vp-c-brand-1); + + /** + * Component: Home + * -------------------------------------------------------------------------- */ + + --vp-home-hero-name-color: transparent; + --vp-home-hero-name-background: linear-gradient( + 120deg, + var(--vp-c-indigo-1) 30%, + #18cefe + ); + --vp-home-hero-image-background-image: linear-gradient( + -45deg, + #18cefe 50%, + #c279ed 50% + ); + --vp-home-hero-image-filter: blur(44px); + + /** + * Component: Custom Block + * -------------------------------------------------------------------------- */ + --vp-custom-block-tip-border: transparent; + --vp-custom-block-tip-text: var(--vp-c-text-1); + --vp-custom-block-tip-bg: var(--vp-c-brand-soft); + --vp-custom-block-tip-code-bg: var(--vp-c-brand-soft); +} + +@media (min-width: 640px) { + :root { + --vp-home-hero-image-filter: blur(56px); + } +} + +@media (min-width: 960px) { + :root { + --vp-home-hero-image-filter: blur(68px); + } +} + +/** + * Component: Algolia + * -------------------------------------------------------------------------- */ + +.DocSearch { + --docsearch-primary-color: var(--vp-c-brand-1) !important; +} diff --git a/apps/vben5/docs/package.json b/apps/vben5/docs/package.json new file mode 100644 index 000000000..15a87bb97 --- /dev/null +++ b/apps/vben5/docs/package.json @@ -0,0 +1,35 @@ +{ + "name": "@vben/docs", + "version": "5.4.8", + "private": true, + "scripts": { + "build": "vitepress build", + "dev": "vitepress dev", + "docs:preview": "vitepress preview" + }, + "imports": { + "#/*": { + "node": "./src/_env/node/*", + "default": "./src/_env/*" + } + }, + "dependencies": { + "@vben-core/shadcn-ui": "workspace:*", + "@vben/common-ui": "workspace:*", + "@vben/locales": "workspace:*", + "@vben/plugins": "workspace:*", + "@vben/styles": "workspace:*", + "ant-design-vue": "catalog:", + "lucide-vue-next": "catalog:", + "medium-zoom": "catalog:", + "radix-vue": "catalog:", + "vitepress-plugin-group-icons": "catalog:" + }, + "devDependencies": { + "@nolebase/vitepress-plugin-git-changelog": "catalog:", + "@vben/vite-config": "workspace:*", + "@vite-pwa/vitepress": "catalog:", + "vitepress": "catalog:", + "vue": "catalog:" + } +} diff --git a/apps/vben5/docs/src/_env/adapter/component.ts b/apps/vben5/docs/src/_env/adapter/component.ts new file mode 100644 index 000000000..1afa62174 --- /dev/null +++ b/apps/vben5/docs/src/_env/adapter/component.ts @@ -0,0 +1,127 @@ +/** + * 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用 + * 可用于 vben-form、vben-modal、vben-drawer 等组件使用, + */ + +import type { BaseFormComponentType } from '@vben/common-ui'; + +import type { Component, SetupContext } from 'vue'; +import { h } from 'vue'; + +import { globalShareState } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { + AutoComplete, + Button, + Checkbox, + CheckboxGroup, + DatePicker, + Divider, + Input, + InputNumber, + InputPassword, + Mentions, + notification, + Radio, + RadioGroup, + RangePicker, + Rate, + Select, + Space, + Switch, + Textarea, + TimePicker, + TreeSelect, + Upload, +} from 'ant-design-vue'; + +const withDefaultPlaceholder = ( + component: T, + type: 'input' | 'select', +) => { + return (props: any, { attrs, slots }: Omit) => { + const placeholder = props?.placeholder || $t(`ui.placeholder.${type}`); + return h(component, { ...props, ...attrs, placeholder }, slots); + }; +}; + +// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明 +export type ComponentType = + | 'AutoComplete' + | 'Checkbox' + | 'CheckboxGroup' + | 'DatePicker' + | 'DefaultButton' + | 'Divider' + | 'Input' + | 'InputNumber' + | 'InputPassword' + | 'Mentions' + | 'PrimaryButton' + | 'Radio' + | 'RadioGroup' + | 'RangePicker' + | 'Rate' + | 'Select' + | 'Space' + | 'Switch' + | 'Textarea' + | 'TimePicker' + | 'TreeSelect' + | 'Upload' + | BaseFormComponentType; + +async function initComponentAdapter() { + const components: Partial> = { + // 如果你的组件体积比较大,可以使用异步加载 + // Button: () => + // import('xxx').then((res) => res.Button), + + AutoComplete, + Checkbox, + CheckboxGroup, + DatePicker, + // 自定义默认按钮 + DefaultButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'default' }, slots); + }, + Divider, + Input: withDefaultPlaceholder(Input, 'input'), + InputNumber: withDefaultPlaceholder(InputNumber, 'input'), + InputPassword: withDefaultPlaceholder(InputPassword, 'input'), + Mentions: withDefaultPlaceholder(Mentions, 'input'), + // 自定义主要按钮 + PrimaryButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'primary' }, slots); + }, + Radio, + RadioGroup, + RangePicker, + Rate, + Select: withDefaultPlaceholder(Select, 'select'), + Space, + Switch, + Textarea: withDefaultPlaceholder(Textarea, 'input'), + TimePicker, + TreeSelect: withDefaultPlaceholder(TreeSelect, 'select'), + Upload, + }; + + // 将组件注册到全局共享状态中 + globalShareState.setComponents(components); + + // 定义全局共享状态中的消息提示 + globalShareState.defineMessage({ + // 复制成功消息提示 + copyPreferencesSuccess: (title, content) => { + notification.success({ + description: content, + message: title, + placement: 'bottomRight', + }); + }, + }); +} + +export { initComponentAdapter }; diff --git a/apps/vben5/docs/src/_env/adapter/form.ts b/apps/vben5/docs/src/_env/adapter/form.ts new file mode 100644 index 000000000..67e2483e5 --- /dev/null +++ b/apps/vben5/docs/src/_env/adapter/form.ts @@ -0,0 +1,49 @@ +import type { + VbenFormSchema as FormSchema, + VbenFormProps, +} from '@vben/common-ui'; + +import type { ComponentType } from './component'; + +import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { initComponentAdapter } from './component'; + +initComponentAdapter(); +setupVbenForm({ + config: { + baseModelPropName: 'value', + // naive-ui组件不接受onChang事件,所以需要禁用 + disabledOnChangeListener: true, + // naive-ui组件的空值为null,不能是undefined,否则重置表单时不生效 + emptyStateValue: null, + modelPropNameMap: { + Checkbox: 'checked', + Radio: 'checked', + Switch: 'checked', + Upload: 'fileList', + }, + }, + defineRules: { + required: (value, _params, ctx) => { + if (value === undefined || value === null || value.length === 0) { + return $t('ui.formRules.required', [ctx.label]); + } + return true; + }, + selectRequired: (value, _params, ctx) => { + if (value === undefined || value === null) { + return $t('ui.formRules.selectRequired', [ctx.label]); + } + return true; + }, + }, +}); + +const useVbenForm = useForm; + +export { useVbenForm, z }; + +export type VbenFormSchema = FormSchema; +export type { VbenFormProps }; diff --git a/apps/vben5/docs/src/_env/adapter/vxe-table.ts b/apps/vben5/docs/src/_env/adapter/vxe-table.ts new file mode 100644 index 000000000..bab7f3d38 --- /dev/null +++ b/apps/vben5/docs/src/_env/adapter/vxe-table.ts @@ -0,0 +1,70 @@ +import { h } from 'vue'; + +import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table'; + +import { Button, Image } from 'ant-design-vue'; + +import { useVbenForm } from './form'; + +if (!import.meta.env.SSR) { + setupVbenVxeTable({ + configVxeTable: (vxeUI) => { + vxeUI.setConfig({ + grid: { + align: 'center', + border: false, + columnConfig: { + resizable: true, + }, + + formConfig: { + // 全局禁用vxe-table的表单配置,使用formOptions + enabled: false, + }, + minHeight: 180, + proxyConfig: { + autoLoad: true, + response: { + result: 'items', + total: 'total', + list: 'items', + }, + showActiveMsg: true, + showResponseMsg: false, + }, + round: true, + showOverflow: true, + size: 'small', + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellImage' }, + vxeUI.renderer.add('CellImage', { + renderTableDefault(_renderOpts, params) { + const { column, row } = params; + return h(Image, { src: row[column.field] }); + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellLink' }, + vxeUI.renderer.add('CellLink', { + renderTableDefault(renderOpts) { + const { props } = renderOpts; + return h( + Button, + { size: 'small', type: 'link' }, + { default: () => props?.text }, + ); + }, + }); + + // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化 + // vxeUI.formats.add + }, + useVbenForm, + }); +} + +export { useVbenVxeGrid }; + +export type * from '@vben/plugins/vxe-table'; diff --git a/apps/vben5/docs/src/_env/node/adapter/form.ts b/apps/vben5/docs/src/_env/node/adapter/form.ts new file mode 100644 index 000000000..a206c0d8b --- /dev/null +++ b/apps/vben5/docs/src/_env/node/adapter/form.ts @@ -0,0 +1,4 @@ +export const useVbenForm = () => {}; +export const z = {}; +export type VbenFormSchema = any; +export type VbenFormProps = any; diff --git a/apps/vben5/docs/src/_env/node/adapter/vxe-table.ts b/apps/vben5/docs/src/_env/node/adapter/vxe-table.ts new file mode 100644 index 000000000..5ec409fb2 --- /dev/null +++ b/apps/vben5/docs/src/_env/node/adapter/vxe-table.ts @@ -0,0 +1,3 @@ +export type * from '@vben/plugins/vxe-table'; + +export const useVbenVxeGrid = () => {}; diff --git a/apps/vben5/docs/src/commercial/community.md b/apps/vben5/docs/src/commercial/community.md new file mode 100644 index 000000000..c5b7b7db9 --- /dev/null +++ b/apps/vben5/docs/src/commercial/community.md @@ -0,0 +1,30 @@ +# 社区交流 + +社区交流群主要是为了方便大家交流,提问,解答问题,分享经验等。偏自助方式,如果你有问题,可以通过以下方式加入社区交流群: + +- [QQ频道](https://pd.qq.com/s/16p8lvvob):推荐!!!主要提供问题解答,分享经验等。 +- QQ群:[大群](https://qm.qq.com/q/MEmHoCLbG0),[1群](https://qm.qq.com/q/YacMHPYAMu)、[2群](https://qm.qq.com/q/ajVKZvFICk)、[3群](https://qm.qq.com/q/36zdwThP2E),[4群](https://qm.qq.com/q/sCzSlm3504),主要使用者的交流群。 +- [Discord](https://discord.com/invite/VU62jTecad): 主要提供问题解答,分享经验等。 + +::: tip + +免费QQ群人数上限200,将会不定期清理。推荐加入QQ频道进行交流 + +::: + +## 微信群 + +作者主要通过微信群提供帮助,如果你有问题,可以通过以下方式加入微信群。 + +通过微信联系作者,注明加群来意: + +::: tip + +因为微信群人数有限制,加微信群要求: + +- 通过[赞助](../sponsor/personal.md)任意金额。 +- 发送赞助`截图`,备注`加入微信群`即可。 + +::: + + diff --git a/apps/vben5/docs/src/commercial/customized.md b/apps/vben5/docs/src/commercial/customized.md new file mode 100644 index 000000000..1f0bcecaf --- /dev/null +++ b/apps/vben5/docs/src/commercial/customized.md @@ -0,0 +1,12 @@ +# 定制开发 + +我们提供基于 Vben Admin 的技术支持服务及定制开发,基本需求我们都可以满足。 + +详细需求可添加作者了解,并注明来意: + +- 通过邮箱联系开发者: [ann.vben@gmail.com](mailto:ann.vben@gmail.com) +- 通过微信联系开发者: + + + +我们会在第一时间回复您,定制费用根据需求而定。 diff --git a/apps/vben5/docs/src/commercial/technical-support.md b/apps/vben5/docs/src/commercial/technical-support.md new file mode 100644 index 000000000..ded9bf2db --- /dev/null +++ b/apps/vben5/docs/src/commercial/technical-support.md @@ -0,0 +1,8 @@ +# 技术支持 + +## 问题反馈 + +在使用项目的过程中,如果遇到问题,你可以先详细阅读本文档,未找到解决方案时,可以通过以下方式获取技术支持: + +- 通过 [GitHub Issues](https://github.com/vbenjs/vue-vben-admin/issues) +- 通过 [GitHub Discussions](https://github.com/vbenjs/vue-vben-admin/discussions) diff --git a/apps/vben5/docs/src/components/common-ui/vben-count-to-animator.md b/apps/vben5/docs/src/components/common-ui/vben-count-to-animator.md new file mode 100644 index 000000000..301e1a41c --- /dev/null +++ b/apps/vben5/docs/src/components/common-ui/vben-count-to-animator.md @@ -0,0 +1,52 @@ +--- +outline: deep +--- + +# Vben CountToAnimator 数字动画 + +框架提供的数字动画组件,支持数字动画效果。 + +> 如果文档内没有参数说明,可以尝试在在线示例内寻找 + +::: info 写在前面 + +如果你觉得现有组件的封装不够理想,或者不完全符合你的需求,大可以直接使用原生组件,亦或亲手封装一个适合的组件。框架提供的组件并非束缚,使用与否,完全取决于你的需求与自由。 + +::: + +## 基础用法 + +通过 `start-val` 和 `end-val`设置数字动画的开始值和结束值, 持续时间`3000`ms。 + + + +## 自定义前缀及分隔符 + +通过 `prefix` 和 `separator` 设置数字动画的前缀和分隔符。 + + + +### Props + +| 属性名 | 描述 | 类型 | 默认值 | +| ---------- | -------------- | --------- | -------- | +| startVal | 起始值 | `number` | `0` | +| endVal | 结束值 | `number` | `2021` | +| duration | 动画持续时间 | `number` | `1500` | +| autoplay | 自动执行 | `boolean` | `true` | +| prefix | 前缀 | `string` | - | +| suffix | 后缀 | `string` | - | +| separator | 分隔符 | `string` | `,` | +| color | 字体颜色 | `string` | - | +| useEasing | 是否开启动画 | `boolean` | `true` | +| transition | 动画效果 | `string` | `linear` | +| decimals | 保留小数点位数 | `number` | `0` | + +### Methods + +以下事件,只有在 `useVbenModal({onCancel:()=>{}})` 中传入才会生效。 + +| 事件名 | 描述 | 类型 | +| ------ | ------------ | ---------- | +| start | 开始执行动画 | `()=>void` | +| reset | 重置 | `()=>void` | diff --git a/apps/vben5/docs/src/components/common-ui/vben-drawer.md b/apps/vben5/docs/src/components/common-ui/vben-drawer.md new file mode 100644 index 000000000..939593fa9 --- /dev/null +++ b/apps/vben5/docs/src/components/common-ui/vben-drawer.md @@ -0,0 +1,129 @@ +--- +outline: deep +--- + +# Vben Drawer 抽屉 + +框架提供的抽屉组件,支持`自动高度`、`loading`等功能。 + +> 如果文档内没有参数说明,可以尝试在在线示例内寻找 + +::: info 写在前面 + +如果你觉得现有组件的封装不够理想,或者不完全符合你的需求,大可以直接使用原生组件,亦或亲手封装一个适合的组件。框架提供的组件并非束缚,使用与否,完全取决于你的需求与自由。 + +::: + +::: tip README + +下方示例代码中的,存在一些国际化、主题色未适配问题,这些问题只在文档内会出现,实际使用并不会有这些问题,可忽略,不必纠结。 + +::: + +## 基础用法 + +使用 `useVbenDrawer` 创建最基础的模态框。 + + + +## 组件抽离 + +Drawer 内的内容一般业务中,会比较复杂,所以我们可以将 drawer 内的内容抽离出来,也方便复用。通过 `connectedComponent` 参数,可以将内外组件进行连接,而不用其他任何操作。 + + + +## 自动计算高度 + +弹窗会自动计算内容高度,超过一定高度会出现滚动条,同时结合 `loading` 效果以及使用 `prepend-footer` 插槽。 + + + +## 使用 Api + +通过 `drawerApi` 可以调用 drawer 的方法以及使用 `setState` 更新 drawer 的状态。 + + + +## 数据共享 + +如果你使用了 `connectedComponent` 参数,那么内外组件会共享数据,比如一些表单回填等操作。可以用 `drawerApi` 来获取数据和设置数据,配合 `onOpenChange`,可以满足大部分的需求。 + + + +::: info 注意 + +- `VbenDrawer` 组件对与参数的处理优先级是 `slot` > `props` > `state`(通过api更新的状态以及useVbenDrawer参数)。如果你已经传入了 `slot` 或者 `props`,那么 `setState` 将不会生效,这种情况下你可以通过 `slot` 或者 `props` 来更新状态。 +- 如果你使用到了 `connectedComponent` 参数,那么会存在 2 个`useVbenDrawer`, 此时,如果同时设置了相同的参数,那么以内部为准(也就是没有设置 connectedComponent 的代码)。比如 同时设置了 `onConfirm`,那么以内部的 `onConfirm` 为准。`onOpenChange`事件除外,内外都会触发。 + +::: + +## API + +```ts +// Drawer 为弹窗组件 +// drawerApi 为弹窗的方法 +const [Drawer, drawerApi] = useVbenDrawer({ + // 属性 + // 事件 +}); +``` + +### Props + +所有属性都可以传入 `useVbenDrawer` 的第一个参数中。 + +| 属性名 | 描述 | 类型 | 默认值 | +| --- | --- | --- | --- | +| title | 标题 | `string\|slot` | - | +| titleTooltip | 标题提示信息 | `string\|slot` | - | +| description | 描述信息 | `string\|slot` | - | +| isOpen | 弹窗打开状态 | `boolean` | `false` | +| loading | 弹窗加载状态 | `boolean` | `false` | +| closable | 显示关闭按钮 | `boolean` | `true` | +| modal | 显示遮罩 | `boolean` | `true` | +| header | 显示header | `boolean` | `true` | +| footer | 显示footer | `boolean\|slot` | `true` | +| confirmLoading | 确认按钮loading状态 | `boolean` | `false` | +| closeOnClickModal | 点击遮罩关闭弹窗 | `boolean` | `true` | +| closeOnPressEscape | esc 关闭弹窗 | `boolean` | `true` | +| confirmText | 确认按钮文本 | `string\|slot` | `确认` | +| cancelText | 取消按钮文本 | `string\|slot` | `取消` | +| placement | 抽屉弹出位置 | `'left'\|'right'\|'top'\|'bottom'` | `right` | +| showCancelButton | 显示取消按钮 | `boolean` | `true` | +| showConfirmButton | 显示确认按钮文本 | `boolean` | `true` | +| class | modal的class,宽度通过这个配置 | `string` | - | +| contentClass | modal内容区域的class | `string` | - | +| footerClass | modal底部区域的class | `string` | - | +| headerClass | modal顶部区域的class | `string` | - | + +### Event + +以下事件,只有在 `useVbenDrawer({onCancel:()=>{}})` 中传入才会生效。 + +| 事件名 | 描述 | 类型 | +| --- | --- | --- | +| onBeforeClose | 关闭前触发,返回 `false`则禁止关闭 | `()=>boolean` | +| onCancel | 点击取消按钮触发 | `()=>void` | +| onConfirm | 点击确认按钮触发 | `()=>void` | +| onOpenChange | 关闭或者打开弹窗时触发 | `(isOpen:boolean)=>void` | + +### Slots + +除了上面的属性类型包含`slot`,还可以通过插槽来自定义弹窗的内容。 + +| 插槽名 | 描述 | +| -------------- | ------------------- | +| default | 默认插槽 - 弹窗内容 | +| prepend-footer | 取消按钮左侧 | +| append-footer | 取消按钮右侧 | + +### modalApi + +| 事件名 | 描述 | 类型 | +| --- | --- | --- | +| setState | 动态设置弹窗状态属性 | `setState(props) \| setState((prev)=>(props))` | +| open | 打开弹窗 | `()=>void` | +| close | 关闭弹窗 | `()=>void` | +| setData | 设置共享数据 | `(data:T)=>void` | +| getData | 获取共享数据 | `()=>T` | +| useStore | 获取可响应式状态 | - | diff --git a/apps/vben5/docs/src/components/common-ui/vben-form.md b/apps/vben5/docs/src/components/common-ui/vben-form.md new file mode 100644 index 000000000..34e96adfd --- /dev/null +++ b/apps/vben5/docs/src/components/common-ui/vben-form.md @@ -0,0 +1,519 @@ +--- +outline: deep +--- + +# Vben Form 表单 + +框架提供的表单组件,可适配 `Element Plus`、`Ant Design Vue`、`Naive UI` 等框架。 + +> 如果文档内没有参数说明,可以尝试在在线示例内寻找 + +::: info 写在前面 + +如果你觉得现有组件的封装不够理想,或者不完全符合你的需求,大可以直接使用原生组件,亦或亲手封装一个适合的组件。框架提供的组件并非束缚,使用与否,完全取决于你的需求与自由。 + +::: + +## 适配器 + +表单底层使用 [vee-validate](https://vee-validate.logaretm.com/v4/) 进行表单验证,所以你可以使用 `vee-validate` 的所有功能。对于不同的 UI 框架,我们提供了适配器,以便更好的适配不同的 UI 框架。 + +### 适配器说明 + +每个应用都有不同的 UI 框架,所以在应用的 `src/adapter/form` 和 `src/adapter/component` 内部,你可以根据自己的需求,进行组件适配。下面是 `Ant Design Vue` 的适配器示例代码,可根据注释查看说明: + +::: details ant design vue 表单适配器 + +```ts +import type { + VbenFormSchema as FormSchema, + VbenFormProps, +} from '@vben/common-ui'; + +import type { ComponentType } from './component'; + +import { setupVbenForm, useVbenForm as useForm, z } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +setupVbenForm({ + config: { + // ant design vue组件库默认都是 v-model:value + baseModelPropName: 'value', + // 一些组件是 v-model:checked 或者 v-model:fileList + modelPropNameMap: { + Checkbox: 'checked', + Radio: 'checked', + Switch: 'checked', + Upload: 'fileList', + }, + }, + defineRules: { + // 输入项目必填国际化适配 + required: (value, _params, ctx) => { + if (value === undefined || value === null || value.length === 0) { + return $t('ui.formRules.required', [ctx.label]); + } + return true; + }, + // 选择项目必填国际化适配 + selectRequired: (value, _params, ctx) => { + if (value === undefined || value === null) { + return $t('ui.formRules.selectRequired', [ctx.label]); + } + return true; + }, + }, +}); + +const useVbenForm = useForm; + +export { useVbenForm, z }; +export type VbenFormSchema = FormSchema; +export type { VbenFormProps }; +``` + +::: + +::: details ant design vue 组件适配器 + +```ts +/** + * 通用组件共同的使用的基础组件,原先放在 adapter/form 内部,限制了使用范围,这里提取出来,方便其他地方使用 + * 可用于 vben-form、vben-modal、vben-drawer 等组件使用, + */ + +import type { BaseFormComponentType } from '@vben/common-ui'; + +import type { Component, SetupContext } from 'vue'; +import { h } from 'vue'; + +import { globalShareState } from '@vben/common-ui'; +import { $t } from '@vben/locales'; + +import { + AutoComplete, + Button, + Checkbox, + CheckboxGroup, + DatePicker, + Divider, + Input, + InputNumber, + InputPassword, + Mentions, + notification, + Radio, + RadioGroup, + RangePicker, + Rate, + Select, + Space, + Switch, + Textarea, + TimePicker, + TreeSelect, + Upload, +} from 'ant-design-vue'; + +const withDefaultPlaceholder = ( + component: T, + type: 'input' | 'select', +) => { + return (props: any, { attrs, slots }: Omit) => { + const placeholder = props?.placeholder || $t(`ui.placeholder.${type}`); + return h(component, { ...props, ...attrs, placeholder }, slots); + }; +}; + +// 这里需要自行根据业务组件库进行适配,需要用到的组件都需要在这里类型说明 +export type ComponentType = + | 'AutoComplete' + | 'Checkbox' + | 'CheckboxGroup' + | 'DatePicker' + | 'DefaultButton' + | 'Divider' + | 'Input' + | 'InputNumber' + | 'InputPassword' + | 'Mentions' + | 'PrimaryButton' + | 'Radio' + | 'RadioGroup' + | 'RangePicker' + | 'Rate' + | 'Select' + | 'Space' + | 'Switch' + | 'Textarea' + | 'TimePicker' + | 'TreeSelect' + | 'Upload' + | BaseFormComponentType; + +async function initComponentAdapter() { + const components: Partial> = { + // 如果你的组件体积比较大,可以使用异步加载 + // Button: () => + // import('xxx').then((res) => res.Button), + + AutoComplete, + Checkbox, + CheckboxGroup, + DatePicker, + // 自定义默认按钮 + DefaultButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'default' }, slots); + }, + Divider, + Input: withDefaultPlaceholder(Input, 'input'), + InputNumber: withDefaultPlaceholder(InputNumber, 'input'), + InputPassword: withDefaultPlaceholder(InputPassword, 'input'), + Mentions: withDefaultPlaceholder(Mentions, 'input'), + // 自定义主要按钮 + PrimaryButton: (props, { attrs, slots }) => { + return h(Button, { ...props, attrs, type: 'primary' }, slots); + }, + Radio, + RadioGroup, + RangePicker, + Rate, + Select: withDefaultPlaceholder(Select, 'select'), + Space, + Switch, + Textarea: withDefaultPlaceholder(Textarea, 'input'), + TimePicker, + TreeSelect: withDefaultPlaceholder(TreeSelect, 'select'), + Upload, + }; + + // 将组件注册到全局共享状态中 + globalShareState.setComponents(components); + + // 定义全局共享状态中的消息提示 + globalShareState.defineMessage({ + // 复制成功消息提示 + copyPreferencesSuccess: (title, content) => { + notification.success({ + description: content, + message: title, + placement: 'bottomRight', + }); + }, + }); +} + +export { initComponentAdapter }; +``` + +::: + +## 基础用法 + +::: tip README + +下方示例代码中的,存在一些国际化、主题色未适配问题,这些问题只在文档内会出现,实际使用并不会有这些问题,可忽略,不必纠结。 + +::: + +使用 `useVbenForm` 创建最基础的表单。 + + + +## 查询表单 + +查询表单是一种特殊的表单,用于查询数据。查询表单不会触发表单验证,只会触发查询事件。 + + + +## 表单校验 + +表单校验是一个非常重要的功能,可以通过 `rules` 属性进行校验。 + + + +## 表单联动 + +表单联动是一个非常常见的功能,可以通过 `dependencies` 属性进行联动。 + +_注意_ 需要指定 `dependencies` 的 `triggerFields` 属性,设置由谁的改动来触发,以便表单组件能够正确的联动。 + + + +## 自定义组件 + +如果你的业务组件库没有提供某个组件,你可以自行封装一个组件,然后加到表单内部。 + + + +## 操作 + +一些常见的表单操作。 + + + +## API + +`useVbenForm` 返回一个数组,第一个元素是表单组件,第二个元素是表单的方法。 + +```vue + + + +``` + +### FormApi + +useVbenForm 返回的第二个参数,是一个对象,包含了一些表单的方法。 + +| 方法名 | 描述 | 类型 | +| --- | --- | --- | +| submitForm | 提交表单 | `(e:Event)=>Promise>` | +| validateAndSubmitForm | 提交并校验表单 | `(e:Event)=>Promise>` | +| resetForm | 重置表单 | `()=>Promise` | +| setValues | 设置表单值, 默认会过滤不在schema中定义的field, 可通过filterFields形参关闭过滤 | `(fields: Record, filterFields?: boolean, shouldValidate?: boolean) => Promise` | +| getValues | 获取表单值 | `(fields:Record,shouldValidate: boolean = false)=>Promise` | +| validate | 表单校验 | `()=>Promise` | +| resetValidate | 重置表单校验 | `()=>Promise` | +| updateSchema | 更新formSchema | `(schema:FormSchema[])=>void` | +| setFieldValue | 设置字段值 | `(field: string, value: any, shouldValidate?: boolean)=>Promise` | +| setState | 设置组件状态(props) | `(stateOrFn:\| ((prev: VbenFormProps) => Partial)\| Partial)=>Promise` | +| getState | 获取组件状态(props) | `()=>Promise` | +| form | 表单对象实例,可以操作表单,见 [useForm](https://vee-validate.logaretm.com/v4/api/use-form/) | - | + +## Props + +所有属性都可以传入 `useVbenForm` 的第一个参数中。 + +| 属性名 | 描述 | 类型 | 默认值 | +| --- | --- | --- | --- | +| layout | 表单项布局 | `'horizontal' \| 'vertical'` | `horizontal` | +| showCollapseButton | 是否显示折叠按钮 | `boolean` | `false` | +| wrapperClass | 表单的布局,基于tailwindcss | `any` | - | +| actionWrapperClass | 表单操作区域class | `any` | - | +| handleReset | 表单重置回调 | `(values: Record,) => Promise \| void` | - | +| handleSubmit | 表单提交回调 | `(values: Record,) => Promise \| void` | - | +| resetButtonOptions | 重置按钮组件参数 | `ActionButtonOptions` | - | +| submitButtonOptions | 提交按钮组件参数 | `ActionButtonOptions` | - | +| showDefaultActions | 是否显示默认操作按钮 | `boolean` | `true` | +| collapsed | 是否折叠,在`是否展开,在showCollapseButton=true`时生效 | `boolean` | `false` | +| collapseTriggerResize | 折叠时,触发`resize`事件 | `boolean` | `false` | +| collapsedRows | 折叠时保持的行数 | `number` | `1` | +| fieldMappingTime | 用于将表单内时间区域的应设成 2 个字段 | `[string, [string, string], string?][]` | - | +| commonConfig | 表单项的通用配置,每个配置都会传递到每个表单项,表单项可覆盖 | `FormCommonConfig` | - | +| schema | 表单项的每一项配置 | `FormSchema` | - | +| submitOnEnter | 按下回车健时提交表单 | `boolean` | false | + +### TS 类型说明 + +::: details ActionButtonOptions + +```ts +export interface ActionButtonOptions { + /** 样式 */ + class?: ClassType; + /** 是否禁用 */ + disabled?: boolean; + /** 是否加载中 */ + loading?: boolean; + /** 按钮大小 */ + size?: ButtonVariantSize; + /** 按钮类型 */ + variant?: ButtonVariants; + /** 是否显示 */ + show?: boolean; + /** 按钮文本 */ + text?: string; + /** 任意属性 */ + [key: string]: any; +} +``` + +::: + +::: details FormCommonConfig + +```ts +export interface FormCommonConfig { + /** + * 所有表单项的props + */ + componentProps?: ComponentProps; + /** + * 所有表单项的控件样式 + */ + controlClass?: string; + /** + * 所有表单项的禁用状态 + * @default false + */ + disabled?: boolean; + /** + * 所有表单项的控件样式 + * @default {} + */ + formFieldProps?: Partial; + /** + * 所有表单项的栅格布局 + * @default "" + */ + formItemClass?: string; + /** + * 隐藏所有表单项label + * @default false + */ + hideLabel?: boolean; + /** + * 是否隐藏必填标记 + * @default false + */ + hideRequiredMark?: boolean; + /** + * 所有表单项的label样式 + * @default "" + */ + labelClass?: string; + /** + * 所有表单项的label宽度 + */ + labelWidth?: number; + /** + * 所有表单项的wrapper样式 + */ + wrapperClass?: string; +} +``` + +::: + +::: details FormSchema + +```ts +export interface FormSchema< + T extends BaseFormComponentType = BaseFormComponentType, +> extends FormCommonConfig { + /** 组件 */ + component: Component | T; + /** 组件参数 */ + componentProps?: ComponentProps; + /** 默认值 */ + defaultValue?: any; + /** 依赖 */ + dependencies?: FormItemDependencies; + /** 描述 */ + description?: string; + /** 字段名 */ + fieldName: string; + /** 帮助信息 */ + help?: string; + /** 表单项 */ + label?: string; + /** 自定义组件内部渲染 */ + renderComponentContent?: RenderComponentContentType; + /** 字段规则 */ + rules?: FormSchemaRuleType; + /** 后缀 */ + suffix?: CustomRenderType; +} +``` + +::: + +### 表单联动 + +表单联动需要通过 schema 内的 `dependencies` 属性进行联动,允许您添加字段之间的依赖项,以根据其他字段的值控制字段。 + +```ts +dependencies: { + // 只有当 name 字段的值变化时,才会触发联动 + triggerFields: ['name'], + // 动态判断当前字段是否需要显示,不显示则直接销毁 + if(values,formApi){}, + // 动态判断当前字段是否需要显示,不显示用css隐藏 + show(values,formApi){}, + // 动态判断当前字段是否需要禁用 + disabled(values,formApi){}, + // 字段变更时,都会触发该函数 + trigger(values,formApi){}, + // 动态rules + rules(values,formApi){}, + // 动态必填 + required(values,formApi){}, + // 动态组件参数 + componentProps(values,formApi){}, +} +``` + +### 表单校验 + +表单联动需要通过 schema 内的 `rules` 属性进行配置。 + +rules的值可以是一个字符串,也可以是一个zod的schema。 + +#### 字符串 + +```ts +// 表示字段必填,默认会根据适配器的required进行国际化 +{ + rules: 'required'; +} + +// 表示字段必填,默认会根据适配器的required进行国际化,用于下拉选择之类 +{ + rules: 'selectRequired'; +} +``` + +#### zod + +rules也支持 zod 的 schema,可以进行更复杂的校验,zod 的使用请查看 [zod文档](https://zod.dev/)。 + +```ts +import { z } from '#/adapter/form'; + +// 基础类型 +{ + rules: z.string().min(1, { message: '请输入字符串' }); +} + +// 可选,并且携带默认值 +{ + rules: z.string().default('默认值').optional(), +} + +// 复杂校验 +{ + z.string().min(1, { message: "请输入" }) + .refine((value) => value === "123", { + message: "值必须为123", + }); +} +``` + +## Slots + +可以使用以下插槽在表单中插入自定义的内容 + +| 插槽名 | 描述 | +| ------------- | ------------------ | +| reset-before | 重置按钮之前的位置 | +| submit-before | 提交按钮之前的位置 | +| expand-before | 展开按钮之前的位置 | +| expand-after | 展开按钮之后的位置 | + +::: tip 字段插槽 + +除了以上内置插槽之外,`schema`属性中每个字段的`fieldName`都可以作为插槽名称,这些字段插槽的优先级高于`component`定义的组件。也就是说,当提供了与`fieldName`同名的插槽时,这些插槽的内容将会作为这些字段的组件,此时`component`的值将会被忽略。 + +::: diff --git a/apps/vben5/docs/src/components/common-ui/vben-modal.md b/apps/vben5/docs/src/components/common-ui/vben-modal.md new file mode 100644 index 000000000..75f620ae5 --- /dev/null +++ b/apps/vben5/docs/src/components/common-ui/vben-modal.md @@ -0,0 +1,142 @@ +--- +outline: deep +--- + +# Vben Modal 模态框 + +框架提供的模态框组件,支持`拖拽`、`全屏`、`自动高度`、`loading`等功能。 + +> 如果文档内没有参数说明,可以尝试在在线示例内寻找 + +::: info 写在前面 + +如果你觉得现有组件的封装不够理想,或者不完全符合你的需求,大可以直接使用原生组件,亦或亲手封装一个适合的组件。框架提供的组件并非束缚,使用与否,完全取决于你的需求与自由。 + +::: + +::: tip README + +下方示例代码中的,存在一些国际化、主题色未适配问题,这些问题只在文档内会出现,实际使用并不会有这些问题,可忽略,不必纠结。 + +::: + +## 基础用法 + +使用 `useVbenModal` 创建最基础的模态框。 + + + +## 组件抽离 + +Modal 内的内容一般业务中,会比较复杂,所以我们可以将 modal 内的内容抽离出来,也方便复用。通过 `connectedComponent` 参数,可以将内外组件进行连接,而不用其他任何操作。 + + + +## 开启拖拽 + +通过 `draggable` 参数,可开启拖拽功能。 + + + +## 自动计算高度 + +弹窗会自动计算内容高度,超过一定高度会出现滚动条,同时结合 `loading` 效果以及使用 `prepend-footer` 插槽。 + + + +## 使用 Api + +通过 `modalApi` 可以调用 modal 的方法以及使用 `setState` 更新 modal 的状态。 + + + +## 数据共享 + +如果你使用了 `connectedComponent` 参数,那么内外组件会共享数据,比如一些表单回填等操作。可以用 `modalApi` 来获取数据和设置数据,配合 `onOpenChange`,可以满足大部分的需求。 + + + +::: info 注意 + +- `VbenModal` 组件对与参数的处理优先级是 `slot` > `props` > `state`(通过api更新的状态以及useVbenModal参数)。如果你已经传入了 `slot` 或者 `props`,那么 `setState` 将不会生效,这种情况下你可以通过 `slot` 或者 `props` 来更新状态。 +- 如果你使用到了 `connectedComponent` 参数,那么会存在 2 个`useVbenModal`, 此时,如果同时设置了相同的参数,那么以内部为准(也就是没有设置 connectedComponent 的代码)。比如 同时设置了 `onConfirm`,那么以内部的 `onConfirm` 为准。`onOpenChange`事件除外,内外都会触发。 + +::: + +## API + +```ts +// Modal 为弹窗组件 +// modalApi 为弹窗的方法 +const [Modal, modalApi] = useVbenModal({ + // 属性 + // 事件 +}); +``` + +### Props + +所有属性都可以传入 `useVbenModal` 的第一个参数中。 + +| 属性名 | 描述 | 类型 | 默认值 | +| --- | --- | --- | --- | +| title | 标题 | `string\|slot` | - | +| titleTooltip | 标题提示信息 | `string\|slot` | - | +| description | 描述信息 | `string\|slot` | - | +| isOpen | 弹窗打开状态 | `boolean` | `false` | +| loading | 弹窗加载状态 | `boolean` | `false` | +| fullscreen | 全屏显示 | `boolean` | `false` | +| fullscreenButton | 显示全屏按钮 | `boolean` | `true` | +| draggable | 可拖拽 | `boolean` | `false` | +| closable | 显示关闭按钮 | `boolean` | `true` | +| centered | 居中显示 | `boolean` | `false` | +| modal | 显示遮罩 | `boolean` | `true` | +| header | 显示header | `boolean` | `true` | +| footer | 显示footer | `boolean\|slot` | `true` | +| confirmDisabled | 禁用确认按钮 | `boolean` | `false` | +| confirmLoading | 确认按钮loading状态 | `boolean` | `false` | +| closeOnClickModal | 点击遮罩关闭弹窗 | `boolean` | `true` | +| closeOnPressEscape | esc 关闭弹窗 | `boolean` | `true` | +| confirmText | 确认按钮文本 | `string\|slot` | `确认` | +| cancelText | 取消按钮文本 | `string\|slot` | `取消` | +| showCancelButton | 显示取消按钮 | `boolean` | `true` | +| showConfirmButton | 显示确认按钮 | `boolean` | `true` | +| class | modal的class,宽度通过这个配置 | `string` | - | +| contentClass | modal内容区域的class | `string` | - | +| footerClass | modal底部区域的class | `string` | - | +| headerClass | modal顶部区域的class | `string` | - | +| bordered | 是否显示border | `boolean` | `false` | + +### Event + +以下事件,只有在 `useVbenModal({onCancel:()=>{}})` 中传入才会生效。 + +| 事件名 | 描述 | 类型 | 版本号 | +| --- | --- | --- | --- | +| onBeforeClose | 关闭前触发,返回 `false`则禁止关闭 | `()=>boolean` | | +| onCancel | 点击取消按钮触发 | `()=>void` | | +| onClosed | 关闭动画播放完毕时触发 | `()=>void` | >5.4.3 | +| onConfirm | 点击确认按钮触发 | `()=>void` | | +| onOpenChange | 关闭或者打开弹窗时触发 | `(isOpen:boolean)=>void` | | +| onOpened | 打开动画播放完毕时触发 | `()=>void` | >5.4.3 | + +### Slots + +除了上面的属性类型包含`slot`,还可以通过插槽来自定义弹窗的内容。 + +| 插槽名 | 描述 | +| -------------- | ------------------- | +| default | 默认插槽 - 弹窗内容 | +| prepend-footer | 取消按钮左侧 | +| append-footer | 取消按钮右侧 | + +### modalApi + +| 事件名 | 描述 | 类型 | +| --- | --- | --- | +| setState | 动态设置弹窗状态属性 | `setState(props) \| setState((prev)=>(props))` | +| open | 打开弹窗 | `()=>void` | +| close | 关闭弹窗 | `()=>void` | +| setData | 设置共享数据 | `(data:T)=>void` | +| getData | 获取共享数据 | `()=>T` | +| useStore | 获取可响应式状态 | - | diff --git a/apps/vben5/docs/src/components/common-ui/vben-vxe-table.md b/apps/vben5/docs/src/components/common-ui/vben-vxe-table.md new file mode 100644 index 000000000..29f679f6a --- /dev/null +++ b/apps/vben5/docs/src/components/common-ui/vben-vxe-table.md @@ -0,0 +1,238 @@ +--- +outline: deep +--- + +# Vben Vxe Table 表格 + +框架提供的Table 列表组件基于 [vxe-table](https://vxetable.cn/v4/#/grid/api?apiKey=grid),结合`Vben Form 表单`进行了二次封装。 + +其中,表头的 **表单搜索** 部分采用了`Vben Form表单`,表格主体部分使用了`vxe-grid`组件,支持表格的分页、排序、筛选等功能。 + +> 如果文档内没有参数说明,可以尝试在在线示例或者在 [vxe-grid 官方API 文档](https://vxetable.cn/v4/#/grid/api?apiKey=grid) 内寻找 + +::: info 写在前面 + +如果你觉得现有组件的封装不够理想,或者不完全符合你的需求,大可以直接使用原生组件,亦或亲手封装一个适合的组件。框架提供的组件并非束缚,使用与否,完全取决于你的需求与自由。 + +::: + +## 适配器 + +表格底层使用 [vxe-table](https://vxetable.cn/#/start/install) 进行实现,所以你可以使用 `vxe-table` 的所有功能。对于不同的 UI 框架,我们提供了适配器,以便更好的适配不同的 UI 框架。 + +### 适配器说明 + +每个应用都可以自己配置`vxe-table`的适配器,你可以根据自己的需求。下面是一个简单的配置示例: + +::: details vxe-table 表格适配器 + +```ts +import { h } from 'vue'; + +import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table'; + +import { Button, Image } from 'ant-design-vue'; + +import { useVbenForm } from './form'; + +setupVbenVxeTable({ + configVxeTable: (vxeUI) => { + vxeUI.setConfig({ + grid: { + align: 'center', + border: false, + columnConfig: { + resizable: true, + }, + minHeight: 180, + formConfig: { + // 全局禁用vxe-table的表单配置,使用formOptions + enabled: false, + }, + proxyConfig: { + autoLoad: true, + response: { + result: 'items', + total: 'total', + list: 'items', + }, + showActiveMsg: true, + showResponseMsg: false, + }, + round: true, + showOverflow: true, + size: 'small', + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellImage' }, + vxeUI.renderer.add('CellImage', { + renderTableDefault(_renderOpts, params) { + const { column, row } = params; + return h(Image, { src: row[column.field] }); + }, + }); + + // 表格配置项可以用 cellRender: { name: 'CellLink' }, + vxeUI.renderer.add('CellLink', { + renderTableDefault(renderOpts) { + const { props } = renderOpts; + return h( + Button, + { size: 'small', type: 'link' }, + { default: () => props?.text }, + ); + }, + }); + + // 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化 + // vxeUI.formats.add + }, + useVbenForm, +}); + +export { useVbenVxeGrid }; + +export type * from '@vben/plugins/vxe-table'; +``` + +::: + +## 基础表格 + +使用 `useVbenVxeGrid` 创建最基础的表格。 + + + +## 远程加载 + +通过指定 `proxyConfig.ajax` 的 `query` 方法,可以实现远程加载数据。 + + + +## 树形表格 + +树形表格的数据源为扁平结构,可以指定`treeConfig`配置项,实现树形表格。 + +```typescript +treeConfig: { + transform: true, // 指定表格为树形表格 + parentField: 'parentId', // 父节点字段名 + rowField: 'id', // 行数据字段名 +}, +``` + + + +## 固定表头/列 + +列固定可选参数: `'left' | 'right' | '' | null` + + + +## 自定义单元格 + +自定义单元格有两种实现方式 + +- 通过 `slots` 插槽 +- 通过 `customCell` 自定义单元格,但是要先添加渲染器 + +```typescript +// 表格配置项可以用 cellRender: { name: 'CellImage' }, +vxeUI.renderer.add('CellImage', { + renderDefault(_renderOpts, params) { + const { column, row } = params; + return h(Image, { src: row[column.field] } as any); // 注意此处的Image 组件,来源于Antd,需要自行引入,否则会使用js的Image类 + }, +}); + +// 表格配置项可以用 cellRender: { name: 'CellLink' }, +vxeUI.renderer.add('CellLink', { + renderDefault(renderOpts) { + const { props } = renderOpts; + return h( + Button, + { size: 'small', type: 'link' }, + { default: () => props?.text }, + ); + }, +}); +``` + + + +## 搜索表单 + +**表单搜索** 部分采用了`Vben Form 表单`,参考 [Vben Form 表单文档](/components/common-ui/vben-form)。 + + + +## 单元格编辑 + +通过指定`editConfig.mode`为`cell`,可以实现单元格编辑。 + + + +## 行编辑 + +通过指定`editConfig.mode`为`row`,可以实现行编辑。 + + + +## 虚拟滚动 + +通过 scroll-y.enabled 与 scroll-y.gt 组合开启,其中 enabled 为总开关,gt 是指当总行数大于指定行数时自动开启。 + +> 参考 [vxe-table 官方文档 - 虚拟滚动](https://vxetable.cn/v4/#/component/grid/scroll/vertical)。 + + + +## API + +`useVbenVxeGrid` 返回一个数组,第一个元素是表格组件,第二个元素是表格的方法。 + +```vue + + + +``` + +### GridApi + +useVbenVxeGrid 返回的第二个参数,是一个对象,包含了一些表单的方法。 + +| 方法名 | 描述 | 类型 | +| --- | --- | --- | +| setLoading | 设置loading状态 | `(loading)=>void` | +| setGridOptions | 设置vxe-table grid组件参数 | `(options: Partialvoid` | +| reload | 重载表格,会进行初始化 | `(params:any)=>void` | +| query | 重载表格,会保留当前分页 | `(params:any)=>void` | +| grid | vxe-table grid实例 | `VxeGridInstance` | +| formApi | vbenForm api实例 | `FormApi` | + +## Props + +所有属性都可以传入 `useVbenVxeGrid` 的第一个参数中。 + +| 属性名 | 描述 | 类型 | +| -------------- | ------------------ | ------------------- | +| tableTitle | 表格标题 | `string` | +| tableTitleHelp | 表格标题帮助信息 | `string` | +| gridClass | grid组件的class | `string` | +| gridOptions | grid组件的参数 | `VxeTableGridProps` | +| gridEvents | grid组件的触发的⌚️ | `VxeGridListeners` | +| formOptions | 表单参数 | `VbenFormProps` | diff --git a/apps/vben5/docs/src/components/introduction.md b/apps/vben5/docs/src/components/introduction.md new file mode 100644 index 000000000..039ec8cd8 --- /dev/null +++ b/apps/vben5/docs/src/components/introduction.md @@ -0,0 +1,11 @@ +# 介绍 + +::: info README + +该文档介绍的是框架组件的使用方法、属性、事件等。如果你觉得现有组件的封装不够理想,或者不完全符合你的需求,大可以直接使用原生组件,亦或亲手封装一个适合的组件。框架提供的组件并非束缚,使用与否,完全取决于你的需求与自由。 + +::: + +## 通用组件 + +通用组件是一些常用的组件,比如弹窗、抽屉、表单等。大部分基于 `Tailwind CSS` 实现,可适用于不同 UI 组件库的应用。 diff --git a/apps/vben5/docs/src/demos/vben-count-to-animator/basic/index.vue b/apps/vben5/docs/src/demos/vben-count-to-animator/basic/index.vue new file mode 100644 index 000000000..acc76edaa --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-count-to-animator/basic/index.vue @@ -0,0 +1,6 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-count-to-animator/custom/index.vue b/apps/vben5/docs/src/demos/vben-count-to-animator/custom/index.vue new file mode 100644 index 000000000..5a2434058 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-count-to-animator/custom/index.vue @@ -0,0 +1,12 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/auto-height/drawer.vue b/apps/vben5/docs/src/demos/vben-drawer/auto-height/drawer.vue new file mode 100644 index 000000000..9ab433ccb --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/auto-height/drawer.vue @@ -0,0 +1,45 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/auto-height/index.vue b/apps/vben5/docs/src/demos/vben-drawer/auto-height/index.vue new file mode 100644 index 000000000..59294e538 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/auto-height/index.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/basic/index.vue b/apps/vben5/docs/src/demos/vben-drawer/basic/index.vue new file mode 100644 index 000000000..bd7d92750 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/basic/index.vue @@ -0,0 +1,11 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/dynamic/drawer.vue b/apps/vben5/docs/src/demos/vben-drawer/dynamic/drawer.vue new file mode 100644 index 000000000..50f628316 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/dynamic/drawer.vue @@ -0,0 +1,26 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/dynamic/index.vue b/apps/vben5/docs/src/demos/vben-drawer/dynamic/index.vue new file mode 100644 index 000000000..ad7e6565d --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/dynamic/index.vue @@ -0,0 +1,30 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/extra/drawer.vue b/apps/vben5/docs/src/demos/vben-drawer/extra/drawer.vue new file mode 100644 index 000000000..e84c1939f --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/extra/drawer.vue @@ -0,0 +1,8 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/extra/index.vue b/apps/vben5/docs/src/demos/vben-drawer/extra/index.vue new file mode 100644 index 000000000..59294e538 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/extra/index.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/shared-data/drawer.vue b/apps/vben5/docs/src/demos/vben-drawer/shared-data/drawer.vue new file mode 100644 index 000000000..629199b67 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/shared-data/drawer.vue @@ -0,0 +1,26 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-drawer/shared-data/index.vue b/apps/vben5/docs/src/demos/vben-drawer/shared-data/index.vue new file mode 100644 index 000000000..04885f157 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-drawer/shared-data/index.vue @@ -0,0 +1,26 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-form/api/index.vue b/apps/vben5/docs/src/demos/vben-form/api/index.vue new file mode 100644 index 000000000..786dc89e5 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-form/api/index.vue @@ -0,0 +1,236 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-form/basic/index.vue b/apps/vben5/docs/src/demos/vben-form/basic/index.vue new file mode 100644 index 000000000..88d014256 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-form/basic/index.vue @@ -0,0 +1,231 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-form/custom/index.vue b/apps/vben5/docs/src/demos/vben-form/custom/index.vue new file mode 100644 index 000000000..e4da38dcc --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-form/custom/index.vue @@ -0,0 +1,68 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-form/dynamic/index.vue b/apps/vben5/docs/src/demos/vben-form/dynamic/index.vue new file mode 100644 index 000000000..83d1a7110 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-form/dynamic/index.vue @@ -0,0 +1,168 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-form/query/index.vue b/apps/vben5/docs/src/demos/vben-form/query/index.vue new file mode 100644 index 000000000..a0b64f5dd --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-form/query/index.vue @@ -0,0 +1,94 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-form/rules/index.vue b/apps/vben5/docs/src/demos/vben-form/rules/index.vue new file mode 100644 index 000000000..7abcc6f6c --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-form/rules/index.vue @@ -0,0 +1,189 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-modal/auto-height/index.vue b/apps/vben5/docs/src/demos/vben-modal/auto-height/index.vue new file mode 100644 index 000000000..2addf2e90 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/auto-height/index.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-modal/auto-height/modal.vue b/apps/vben5/docs/src/demos/vben-modal/auto-height/modal.vue new file mode 100644 index 000000000..8757d5ef0 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/auto-height/modal.vue @@ -0,0 +1,45 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-modal/basic/index.vue b/apps/vben5/docs/src/demos/vben-modal/basic/index.vue new file mode 100644 index 000000000..9f8997085 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/basic/index.vue @@ -0,0 +1,11 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-modal/draggable/index.vue b/apps/vben5/docs/src/demos/vben-modal/draggable/index.vue new file mode 100644 index 000000000..2addf2e90 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/draggable/index.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-modal/draggable/modal.vue b/apps/vben5/docs/src/demos/vben-modal/draggable/modal.vue new file mode 100644 index 000000000..ecca497b1 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/draggable/modal.vue @@ -0,0 +1,10 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-modal/dynamic/index.vue b/apps/vben5/docs/src/demos/vben-modal/dynamic/index.vue new file mode 100644 index 000000000..718e532bc --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/dynamic/index.vue @@ -0,0 +1,30 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-modal/dynamic/modal.vue b/apps/vben5/docs/src/demos/vben-modal/dynamic/modal.vue new file mode 100644 index 000000000..d46128965 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/dynamic/modal.vue @@ -0,0 +1,38 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-modal/extra/index.vue b/apps/vben5/docs/src/demos/vben-modal/extra/index.vue new file mode 100644 index 000000000..2addf2e90 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/extra/index.vue @@ -0,0 +1,21 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-modal/extra/modal.vue b/apps/vben5/docs/src/demos/vben-modal/extra/modal.vue new file mode 100644 index 000000000..488fd4a0d --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/extra/modal.vue @@ -0,0 +1,8 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-modal/shared-data/index.vue b/apps/vben5/docs/src/demos/vben-modal/shared-data/index.vue new file mode 100644 index 000000000..58c35e24d --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/shared-data/index.vue @@ -0,0 +1,26 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-modal/shared-data/modal.vue b/apps/vben5/docs/src/demos/vben-modal/shared-data/modal.vue new file mode 100644 index 000000000..806585d99 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-modal/shared-data/modal.vue @@ -0,0 +1,26 @@ + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/basic/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/basic/index.vue new file mode 100644 index 000000000..4b6b5a632 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/basic/index.vue @@ -0,0 +1,85 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/custom-cell/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/custom-cell/index.vue new file mode 100644 index 000000000..517e73f38 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/custom-cell/index.vue @@ -0,0 +1,105 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/edit-cell/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/edit-cell/index.vue new file mode 100644 index 000000000..711941de3 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/edit-cell/index.vue @@ -0,0 +1,55 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/edit-row/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/edit-row/index.vue new file mode 100644 index 000000000..f317f69d1 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/edit-row/index.vue @@ -0,0 +1,92 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/fixed/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/fixed/index.vue new file mode 100644 index 000000000..6067a5ebe --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/fixed/index.vue @@ -0,0 +1,67 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/form/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/form/index.vue new file mode 100644 index 000000000..a5e8a547b --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/form/index.vue @@ -0,0 +1,120 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/mock-api.ts b/apps/vben5/docs/src/demos/vben-vxe-table/mock-api.ts new file mode 100644 index 000000000..e5c40b61e --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/mock-api.ts @@ -0,0 +1,36 @@ +import { MOCK_API_DATA } from './table-data'; + +export namespace DemoTableApi { + export interface PageFetchParams { + [key: string]: any; + page: number; + pageSize: number; + } +} + +export function sleep(time = 1000) { + return new Promise((resolve) => { + setTimeout(() => { + resolve(true); + }, time); + }); +} + +/** + * 获取示例表格数据 + */ +async function getExampleTableApi(params: DemoTableApi.PageFetchParams) { + return new Promise<{ items: any; total: number }>((resolve) => { + const { page, pageSize } = params; + const items = MOCK_API_DATA.slice((page - 1) * pageSize, page * pageSize); + + sleep(1000).then(() => { + resolve({ + total: items.length, + items, + }); + }); + }); +} + +export { getExampleTableApi }; diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/remote/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/remote/index.vue new file mode 100644 index 000000000..bc93d29a9 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/remote/index.vue @@ -0,0 +1,112 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/table-data.ts b/apps/vben5/docs/src/demos/vben-vxe-table/table-data.ts new file mode 100644 index 000000000..c37b88ade --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/table-data.ts @@ -0,0 +1,384 @@ +interface TableRowData { + address: string; + age: number; + id: number; + name: string; + nickname: string; + role: string; +} + +const roles = ['User', 'Admin', 'Manager', 'Guest']; + +export const MOCK_TABLE_DATA: TableRowData[] = (() => { + const data: TableRowData[] = []; + for (let i = 0; i < 10; i++) { + data.push({ + address: `New York${i}`, + age: i + 1, + id: i, + name: `Test${i}`, + nickname: `Test${i}`, + role: roles[Math.floor(Math.random() * roles.length)] as string, + }); + } + return data; +})(); + +export const MOCK_TREE_TABLE_DATA = [ + { + date: '2020-08-01', + id: 10_000, + name: 'Test1', + parentId: null, + size: 1024, + type: 'mp3', + }, + { + date: '2021-04-01', + id: 10_050, + name: 'Test2', + parentId: null, + size: 0, + type: 'mp4', + }, + { + date: '2020-03-01', + id: 24_300, + name: 'Test3', + parentId: 10_050, + size: 1024, + type: 'avi', + }, + { + date: '2021-04-01', + id: 20_045, + name: 'Test4', + parentId: 24_300, + size: 600, + type: 'html', + }, + { + date: '2021-04-01', + id: 10_053, + name: 'Test5', + parentId: 24_300, + size: 0, + type: 'avi', + }, + { + date: '2021-10-01', + id: 24_330, + name: 'Test6', + parentId: 10_053, + size: 25, + type: 'txt', + }, + { + date: '2020-01-01', + id: 21_011, + name: 'Test7', + parentId: 10_053, + size: 512, + type: 'pdf', + }, + { + date: '2021-06-01', + id: 22_200, + name: 'Test8', + parentId: 10_053, + size: 1024, + type: 'js', + }, + { + date: '2020-11-01', + id: 23_666, + name: 'Test9', + parentId: null, + size: 2048, + type: 'xlsx', + }, + { + date: '2021-06-01', + id: 23_677, + name: 'Test10', + parentId: 23_666, + size: 1024, + type: 'js', + }, + { + date: '2021-06-01', + id: 23_671, + name: 'Test11', + parentId: 23_677, + size: 1024, + type: 'js', + }, + { + date: '2021-06-01', + id: 23_672, + name: 'Test12', + parentId: 23_677, + size: 1024, + type: 'js', + }, + { + date: '2021-06-01', + id: 23_688, + name: 'Test13', + parentId: 23_666, + size: 1024, + type: 'js', + }, + { + date: '2021-06-01', + id: 23_681, + name: 'Test14', + parentId: 23_688, + size: 1024, + type: 'js', + }, + { + date: '2021-06-01', + id: 23_682, + name: 'Test15', + parentId: 23_688, + size: 1024, + type: 'js', + }, + { + date: '2020-10-01', + id: 24_555, + name: 'Test16', + parentId: null, + size: 224, + type: 'avi', + }, + { + date: '2021-06-01', + id: 24_566, + name: 'Test17', + parentId: 24_555, + size: 1024, + type: 'js', + }, + { + date: '2021-06-01', + id: 24_577, + name: 'Test18', + parentId: 24_555, + size: 1024, + type: 'js', + }, +]; + +export const MOCK_API_DATA = [ + { + available: true, + category: 'Computers', + color: 'purple', + currency: 'NAD', + description: + 'Ergonomic executive chair upholstered in bonded black leather and PVC padded seat and back for all-day comfort and support', + id: '45a613df-227a-4907-a89f-4a7f1252ca0c', + imageUrl: 'https://avatars.githubusercontent.com/u/62715097', + imageUrl2: 'https://avatars.githubusercontent.com/u/75395683', + inProduction: false, + open: true, + price: '48.89', + productName: 'Handcrafted Steel Salad', + quantity: 70, + rating: 3.780_582_329_574_367, + releaseDate: '2024-09-09T04:06:57.793Z', + status: 'error', + tags: ['Bespoke', 'Handmade', 'Luxurious'], + weight: 1.031_015_671_912_002_5, + }, + { + available: true, + category: 'Toys', + color: 'green', + currency: 'CZK', + description: + 'The Nagasaki Lander is the trademarked name of several series of Nagasaki sport bikes, that started with the 1984 ABC800J', + id: 'd02e5ee9-bc98-4de2-98fa-25a6567ecc19', + imageUrl: 'https://avatars.githubusercontent.com/u/51512330', + imageUrl2: 'https://avatars.githubusercontent.com/u/58698113', + inProduction: false, + open: false, + price: '68.15', + productName: 'Generic Cotton Gloves', + quantity: 3, + rating: 1.681_749_367_682_703_3, + releaseDate: '2024-06-16T09:00:36.806Z', + status: 'warning', + tags: ['Rustic', 'Handcrafted', 'Recycled'], + weight: 9.601_076_149_300_575, + }, + { + available: true, + category: 'Beauty', + color: 'teal', + currency: 'OMR', + description: + 'The Apollotech B340 is an affordable wireless mouse with reliable connectivity, 12 months battery life and modern design', + id: '2b72521c-225c-4e64-8030-611b76b10b37', + imageUrl: 'https://avatars.githubusercontent.com/u/50300075', + imageUrl2: 'https://avatars.githubusercontent.com/u/36541691', + inProduction: true, + open: true, + price: '696.94', + productName: 'Gorgeous Soft Ball', + quantity: 50, + rating: 2.361_581_777_372_057_5, + releaseDate: '2024-06-03T13:24:19.809Z', + status: 'warning', + tags: ['Gorgeous', 'Ergonomic', 'Licensed'], + weight: 8.882_340_049_286_19, + }, + { + available: true, + category: 'Games', + color: 'silver', + currency: 'SOS', + description: + 'Carbonite web goalkeeper gloves are ergonomically designed to give easy fit', + id: 'bafab694-3801-452c-b102-9eb519bd1143', + imageUrl: 'https://avatars.githubusercontent.com/u/89827115', + imageUrl2: 'https://avatars.githubusercontent.com/u/55952747', + inProduction: false, + open: false, + price: '553.84', + productName: 'Bespoke Soft Computer', + quantity: 29, + rating: 2.176_412_873_760_271_7, + releaseDate: '2024-09-17T12:16:27.034Z', + status: 'error', + tags: ['Elegant', 'Rustic', 'Recycled'], + weight: 9.653_285_869_978_038, + }, + { + available: true, + category: 'Toys', + color: 'indigo', + currency: 'BIF', + description: + 'Andy shoes are designed to keeping in mind durability as well as trends, the most stylish range of shoes & sandals', + id: 'bf6dea6b-2a55-441d-8773-937e03d99389', + imageUrl: 'https://avatars.githubusercontent.com/u/21431092', + imageUrl2: 'https://avatars.githubusercontent.com/u/3771350', + inProduction: true, + open: true, + price: '237.39', + productName: 'Handcrafted Cotton Mouse', + quantity: 54, + rating: 4.363_265_388_265_461, + releaseDate: '2023-10-23T13:42:34.947Z', + status: 'error', + tags: ['Unbranded', 'Handmade', 'Generic'], + weight: 9.513_203_612_535_571, + }, + { + available: false, + category: 'Tools', + color: 'violet', + currency: 'TZS', + description: + 'New ABC 13 9370, 13.3, 5th Gen CoreA5-8250U, 8GB RAM, 256GB SSD, power UHD Graphics, OS 10 Home, OS Office A & J 2016', + id: '135ba6ab-32ee-4989-8189-5cfa658ef970', + imageUrl: 'https://avatars.githubusercontent.com/u/29946092', + imageUrl2: 'https://avatars.githubusercontent.com/u/23842994', + inProduction: false, + open: false, + price: '825.25', + productName: 'Awesome Bronze Ball', + quantity: 94, + rating: 4.251_159_804_726_753, + releaseDate: '2023-12-30T07:31:43.464Z', + status: 'warning', + tags: ['Handmade', 'Elegant', 'Unbranded'], + weight: 2.247_473_385_732_636_8, + }, + { + available: true, + category: 'Automotive', + color: 'teal', + currency: 'BOB', + description: 'The Football Is Good For Training And Recreational Purposes', + id: '652ef256-7d4e-48b7-976c-7afaa781ea92', + imageUrl: 'https://avatars.githubusercontent.com/u/2531904', + imageUrl2: 'https://avatars.githubusercontent.com/u/15215990', + inProduction: false, + open: false, + price: '780.49', + productName: 'Oriental Rubber Pants', + quantity: 70, + rating: 2.636_323_417_377_916, + releaseDate: '2024-02-23T23:30:49.628Z', + status: 'success', + tags: ['Unbranded', 'Elegant', 'Unbranded'], + weight: 4.812_965_858_018_838, + }, + { + available: false, + category: 'Garden', + color: 'plum', + currency: 'LRD', + description: + 'The slim & simple Maple Gaming Keyboard from Dev Byte comes with a sleek body and 7- Color RGB LED Back-lighting for smart functionality', + id: '3ea24798-6589-40cc-85f0-ab78752244a0', + imageUrl: 'https://avatars.githubusercontent.com/u/23165285', + imageUrl2: 'https://avatars.githubusercontent.com/u/14595665', + inProduction: false, + open: true, + price: '583.85', + productName: 'Handcrafted Concrete Hat', + quantity: 15, + rating: 1.371_600_527_752_802_7, + releaseDate: '2024-03-02T19:40:50.255Z', + status: 'error', + tags: ['Rustic', 'Sleek', 'Ergonomic'], + weight: 4.926_949_366_405_728_4, + }, + { + available: false, + category: 'Industrial', + color: 'salmon', + currency: 'AUD', + description: + 'The Apollotech B340 is an affordable wireless mouse with reliable connectivity, 12 months battery life and modern design', + id: '997113dd-f6e4-4acc-9790-ef554c7498d1', + imageUrl: 'https://avatars.githubusercontent.com/u/49021914', + imageUrl2: 'https://avatars.githubusercontent.com/u/4690621', + inProduction: true, + open: false, + price: '67.99', + productName: 'Generic Rubber Bacon', + quantity: 68, + rating: 4.129_840_682_128_08, + releaseDate: '2023-12-17T01:40:25.415Z', + status: 'error', + tags: ['Oriental', 'Small', 'Handcrafted'], + weight: 1.080_114_331_801_906_4, + }, + { + available: false, + category: 'Tools', + color: 'sky blue', + currency: 'NOK', + description: + 'The Nagasaki Lander is the trademarked name of several series of Nagasaki sport bikes, that started with the 1984 ABC800J', + id: 'f697a250-6cb2-46c8-b0f7-871ab1f2fa8d', + imageUrl: 'https://avatars.githubusercontent.com/u/95928385', + imageUrl2: 'https://avatars.githubusercontent.com/u/47588244', + inProduction: false, + open: false, + price: '613.89', + productName: 'Gorgeous Frozen Ball', + quantity: 55, + rating: 1.646_947_205_998_534_6, + releaseDate: '2024-10-13T12:31:04.929Z', + status: 'warning', + tags: ['Handmade', 'Unbranded', 'Unbranded'], + weight: 9.430_690_557_758_114, + }, +]; diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/tree/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/tree/index.vue new file mode 100644 index 000000000..0024765a8 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/tree/index.vue @@ -0,0 +1,80 @@ + + + diff --git a/apps/vben5/docs/src/demos/vben-vxe-table/virtual/index.vue b/apps/vben5/docs/src/demos/vben-vxe-table/virtual/index.vue new file mode 100644 index 000000000..81fa00af2 --- /dev/null +++ b/apps/vben5/docs/src/demos/vben-vxe-table/virtual/index.vue @@ -0,0 +1,64 @@ + + + diff --git a/apps/vben5/docs/src/en/guide/essentials/build.md b/apps/vben5/docs/src/en/guide/essentials/build.md new file mode 100644 index 000000000..7f5c95321 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/build.md @@ -0,0 +1,243 @@ +# Build and Deployment + +::: tip Preface + +Since this is a demonstration project, the package size after building is relatively large. If there are plugins in the project that are not used, you can delete the corresponding files or routes. If they are not referenced, they will not be packaged. + +::: + +## Building + +After the project development is completed, execute the following command to build: + +**Note:** Please execute the following command in the project root directory. + +```bash +pnpm build +``` + +After the build is successful, a `dist` folder for the corresponding application will be generated in the root directory, which contains the built and packaged files, for example: `apps/web-antd/dist/` + +## Preview + +Before publishing, you can preview it locally in several ways, here are two: + +- Using the project's custom command for preview (recommended) + +**Note:** Please execute the following command in the project root directory. + +```bash +pnpm preview +``` + +After waiting for the build to succeed, visit `http://localhost:4173` to view the effect. + +- Local server preview + +You can globally install a `serve` service on your computer, such as `live-server`, + +```bash +npm i -g live-server +``` + +Then execute the `live-server` command in the `dist` directory to view the effect locally. + +```bash +cd apps/web-antd/dist +# Local preview, default port 8080 +live-server +# Specify port +live-server --port 9000 +``` + +## Compression + +### Enable `gzip` Compression + +To enable during the build process, change the `.env.production` configuration: + +```bash +VITE_COMPRESS=gzip +``` + +### Enable `brotli` Compression + +To enable during the build process, change the `.env.production` configuration: + +```bash +VITE_COMPRESS=brotli +``` + +### Enable Both `gzip` and `brotli` Compression + +To enable during the build process, change the `.env.production` configuration: + +```bash +VITE_COMPRESS=gzip,brotli +``` + +::: tip Note + +Both `gzip` and `brotli` require specific modules to be installed for use. + +::: + +::: details gzip 与 brotli 在 nginx 内的配置 + +```bash +http { + # Enable gzip + gzip on; + # Enable gzip_static + # After enabling gzip_static, there might be errors, requiring the installation of specific modules. The installation method can be researched independently. + # Only with this enabled, the .gz files packaged by vue files will be effective; otherwise, there is no need to enable gzip for packaging. + gzip_static on; + gzip_proxied any; + gzip_min_length 1k; + gzip_buffers 4 16k; + # If nginx uses multiple layers of proxy, this must be set to enable gzip. + gzip_http_version 1.0; + gzip_comp_level 2; + gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; + gzip_vary off; + gzip_disable "MSIE [1-6]\."; + + # Enable brotli compression + # Requires the installation of the corresponding nginx module, which can be researched independently. + # Can coexist with gzip without conflict. + brotli on; + brotli_comp_level 6; + brotli_buffers 16 8k; + brotli_min_length 20; + brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml; +} +``` + +::: + +## Build Analysis + +If your build files are large, you can optimize your code by analyzing the code size with the built-in [rollup-plugin-analyzer](https://github.com/doesdev/rollup-plugin-analyzer) plugin. Just execute the following command in the `root directory`: + +```bash +pnpm run build:analyze +``` + +After running, you can see the specific distribution of sizes on the automatically opened page to analyze which dependencies are problematic. + +![Build analysis report](/guide/report.png) + +## Deployment + +A simple deployment only requires publishing the final static files, the static files in the dist folder, to your CDN or static server. It's important to note that the index.html is usually the entry page for your backend service. After determining the static js and css, you may need to change the page's import path. + +For example, to upload to an nginx server, you can upload the files under the dist folder to the server's `/srv/www/project/index.html` directory, and then access the configured domain name. + +```bash +# nginx configuration +location / { + # Do not cache html to prevent cache from continuing to be effective after program updates + if ($request_filename ~* .*\.(?:htm|html)$) { + add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate"; + access_log on; + } + # This is the storage path for the files inside the vue packaged dist folder + root /srv/www/project/; + index index.html index.htm; +} +``` + +If you find the resource path is incorrect during deployment, you just need to modify the `.env.production` file. + +```bash +# Configure the change according to your own path +# Note that it needs to start and end with / +VITE_BASE=/ +VITE_BASE=/xxx/ +``` + +### Integration of Frontend Routing and Server + +The project uses vue-router for frontend routing, so you can choose between two modes: history and hash. + +- `hash` mode will append `#` to the URL by default. +- `history` mode will not, but `history` mode requires server-side support. + +You can modify the mode in `.env.production`: + +```bash +VITE_ROUTER_HISTORY=hash +``` + +### Server Configuration for History Mode Routing + +Enabling `history` mode requires server configuration. For more details on server configuration, see [history-mode](https://router.vuejs.org/guide/essentials/history-mode.html#html5-mode) + +Here is an example of `nginx` configuration: + +#### Deployment at the Root Directory + +```bash {5} +server { + listen 80; + location / { + # For use with History mode + try_files $uri $uri/ /index.html; + } +} +``` + +#### Deployment to a Non-root Directory + +- First, you need to change the `.env.production` configuration during packaging: + +```bash +VITE_BASE = /sub/ +``` + +- Then configure in the nginx configuration file + +```bash {8} +server { + listen 80; + server_name localhost; + location /sub/ { + # This is the path where the vue packaged dist files are stored + alias /srv/www/project/; + index index.html index.htm; + try_files $uri $uri/ /sub/index.html; + } +} +``` + +## Cross-Domain Handling + +Using nginx to handle cross-domain issues after project deployment + +1. Configure the frontend project API address in the `.env.production` file in the project directory: + +```bash +VITE_GLOB_API_URL=/api +``` + +2. Configure nginx to forward requests to the backend + +```bash {10-11} +server { + listen 8080; + server_name localhost; + # API proxy for solving cross-domain issues + location /api { + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + # Backend API address + proxy_pass http://110.110.1.1:8080/api; + rewrite "^/api/(.*)$" /$1 break; + proxy_redirect default; + add_header Access-Control-Allow-Origin *; + add_header Access-Control-Allow-Headers X-Requested-With; + add_header Access-Control-Allow-Methods GET,POST,OPTIONS; + } +} +``` diff --git a/apps/vben5/docs/src/en/guide/essentials/concept.md b/apps/vben5/docs/src/en/guide/essentials/concept.md new file mode 100644 index 000000000..8c940a943 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/concept.md @@ -0,0 +1,70 @@ +# Basic Concepts + +In the new version, the entire project has been restructured. Now, we will introduce some basic concepts to help you better understand the entire document. Please make sure to read this section first. + +## Monorepo + +Monorepo refers to the repository of the entire project, which includes all code, packages, applications, standards, documentation, configurations, etc., that is, the entire content of a `Monorepo` directory. + +## Applications + +Applications refer to a complete project; a project can contain multiple applications, which can reuse the code, packages, standards, etc., within the monorepo. Applications are placed in the `apps` directory. Each application is independent and can be run, built, tested, and deployed separately; it can also include different component libraries, etc. + +::: tip + +Applications are not limited to front-end applications; they can also be back-end applications, mobile applications, etc. For example, `apps/backend-mock` is a back-end service. + +::: + +## Packages + +A package refers to an independent module, which can be a component, a tool, a library, etc. Packages can be referenced by multiple applications or other packages. Packages are placed in the `packages` directory. + +You can consider these packages as independent `npm` packages, and they are used in the same way as `npm` packages. + +### Package Import + +Importing a package in `package.json`: + +```json {3} +{ + "dependencies": { + "@vben/utils": "workspace:*" + } +} +``` + +### Package Usage + +Importing a package in the code: + +```ts +import { isString } from '@vben/utils'; +``` + +## Aliases + +In the project, you can see some paths starting with `#`, such as `#/api`, `#/views`. These paths are aliases, used for quickly locating a certain directory. They are not implemented through `vite`'s `alias`, but through the principle of [subpath imports](https://nodejs.org/api/packages.html#subpath-imports) in `Node.js` itself. You only need to configure the `imports` field in `package.json`. + +```json {3} +{ + "imports": { + "#/*": "./src/*" + } +} +``` + +To make these aliases recognizable by the IDE, we also need to configure them in `tsconfig.json`: + +```json {5} +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "#/*": ["src/*"] + } + } +} +``` + +This way, you can use aliases in your code. diff --git a/apps/vben5/docs/src/en/guide/essentials/development.md b/apps/vben5/docs/src/en/guide/essentials/development.md new file mode 100644 index 000000000..da7cfd8ce --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/development.md @@ -0,0 +1,188 @@ +# Local Development {#development} + +::: tip Code Acquisition + +If you haven't acquired the code yet, you can start by reading the documentation from [Quick Start](../introduction/quick-start.md). + +::: + +## Prerequisites + +For a better development experience, we provide some tool configurations and project descriptions to facilitate your development. + +### Required Basic Knowledge + +This project requires some basic frontend knowledge. Please ensure you are familiar with the basics of Vue to handle common issues. It is recommended to learn the following topics before development. Understanding these will be very helpful for the project: + +- [Vue3](https://vuejs.org/) +- [Tailwind CSS](https://tailwindcss.com/) +- [TypeScript](https://www.typescriptlang.org/) +- [Vue Router](https://router.vuejs.org/) +- [Vitejs](https://vitejs.dev/) +- [Pnpm](https://pnpm.io/) +- [Turbo](https://turbo.build/) + +### Tool Configuration + +If you are using [vscode](https://code.visualstudio.com/) (recommended) as your IDE, you can install the following tools to improve development efficiency and code formatting: + +- [Vue - Official](https://marketplace.visualstudio.com/items?itemName=Vue.volar) - Official Vue plugin (essential). +- [Tailwind CSS](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) - Tailwind CSS autocomplete plugin. +- [CSS Variable Autocomplete](https://marketplace.visualstudio.com/items?itemName=vunguyentuan.vscode-css-variables) - CSS variable autocomplete plugin. +- [Iconify IntelliSense](https://marketplace.visualstudio.com/items?itemName=antfu.iconify) - Iconify icon plugin. +- [i18n Ally](https://marketplace.visualstudio.com/items?itemName=Lokalise.i18n-ally) - i18n plugin. +- [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) - Script code linting. +- [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) - Code formatting. +- [Stylelint](https://marketplace.visualstudio.com/items?itemName=stylelint.vscode-stylelint) - CSS formatting. +- [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) - Spelling checker. +- [DotENV](https://marketplace.visualstudio.com/items?itemName=mikestead.dotenv) - .env file highlighting. + +## Npm Scripts + +Npm scripts are common configurations used in the project to perform common tasks such as starting the project, building the project, etc. The following scripts can be found in the `package.json` file at the root of the project. + +The execution command is: `pnpm run [script]` or `npm run [script]`. + +```json +{ + "scripts": { + // Build the project + "build": "cross-env NODE_OPTIONS=--max-old-space-size=8192 turbo build", + // Build the project with analysis + "build:analyze": "turbo build:analyze", + // Build a local Docker image + "build:docker": "./build-local-docker-image.sh", + // Build the web-antd application separately + "build:antd": "pnpm run build --filter=@vben/web-antd", + // Build the documentation separately + "build:docs": "pnpm run build --filter=@vben/docs", + // Build the web-ele application separately + "build:ele": "pnpm run build --filter=@vben/web-ele", + // Build the web-naive application separately + "build:naive": "pnpm run build --filter=@vben/naive", + // Build the playground application separately + "build:play": "pnpm run build --filter=@vben/playground", + // Changeset version management + "changeset": "pnpm exec changeset", + // Check for various issues in the project + "check": "pnpm run check:circular && pnpm run check:dep && pnpm run check:type && pnpm check:cspell", + // Check for circular dependencies + "check:circular": "vsh check-circular", + // Check spelling + "check:cspell": "cspell lint **/*.ts **/README.md .changeset/*.md --no-progress" + // Check dependencies + "check:dep": "vsh check-dep", + // Check types + "check:type": "turbo run typecheck", + // Clean the project (delete node_modules, dist, .turbo, etc.) + "clean": "node ./scripts/clean.mjs", + // Commit code + "commit": "czg", + // Start the project (by default, the dev scripts of all packages in the entire repository will run) + "dev": "turbo-run dev", + // Start the web-antd application + "dev:antd": "pnpm -F @vben/web-antd run dev", + // Start the documentation + "dev:docs": "pnpm -F @vben/docs run dev", + // Start the web-ele application + "dev:ele": "pnpm -F @vben/web-ele run dev", + // Start the web-naive application + "dev:naive": "pnpm -F @vben/web-naive run dev", + // Start the playground application + "dev:play": "pnpm -F @vben/playground run dev", + // Format code + "format": "vsh lint --format", + // Lint code + "lint": "vsh lint", + // After installing dependencies, execute the stub script for all packages + "postinstall": "pnpm -r run stub --if-present", + // Only allow using pnpm + "preinstall": "npx only-allow pnpm", + // Install husky + "prepare": "is-ci || husky", + // Preview the application + "preview": "turbo-run preview", + // Package specification check + "publint": "vsh publint", + // Delete all node_modules, yarn.lock, package.lock.json, and reinstall dependencies + "reinstall": "pnpm clean --del-lock && pnpm install", + // Run vitest unit tests + "test:unit": "vitest run --dom", + // Update project dependencies + "update:deps": " pnpm update --latest --recursive", + // Changeset generation and versioning + "version": "pnpm exec changeset version && pnpm install --no-frozen-lockfile" + } +} +``` + +## Running the Project Locally + +To run the documentation locally and make adjustments, you can execute the following command. This command allows you to select the application you want to develop: + +```bash +pnpm dev +``` + +If you want to run a specific application directly, you can execute the following commands: + +To run the `web-antd` application: + +```bash +pnpm dev:antd +``` + +To run the `web-naive` application: + +```bash +pnpm dev:naive +``` + +To run the `web-ele` application: + +```bash +pnpm dev:ele +``` + +To run the `docs` application: + +```bash +pnpm dev:docs +``` + +## Public Static Resources + +If you need to use public static resources in the project, such as images, static HTML, etc., and you want to directly import them in the development process through `src="/xxx.png"`. + +You need to put the resource in the corresponding project's `public/static` directory. The import path for the resource should be `src="/static/xxx.png"`. + +## DevTools + +The project has a built-in [Vue DevTools](https://github.com/vuejs/devtools-next) plugin, which can be used during development. It is disabled by default, but can be enabled in the `.env.development` file. After enabling it, restart the project: + +```bash +VITE_DEVTOOLS=true +``` + +Once enabled, a Vue DevTools icon will appear at the bottom of the page during project runtime. Click it to open the DevTools. + +![Vue DevTools](/guide/devtools.png) + +## Running Documentation Locally + +To run the documentation locally and make adjustments, you can execute the following command: + +```bash +pnpm dev:docs +``` + +## Troubleshooting + +If you encounter dependency-related issues, you can try reinstalling the dependencies: + +```bash +# Execute this command at the root of the project. +# This command will delete all node_modules, yarn.lock, and package.lock.json files +# and then reinstall dependencies (this process will be noticeably slower). +pnpm reinstall +``` diff --git a/apps/vben5/docs/src/en/guide/essentials/external-module.md b/apps/vben5/docs/src/en/guide/essentials/external-module.md new file mode 100644 index 000000000..f0a6d6e3f --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/external-module.md @@ -0,0 +1,58 @@ +# External Modules + +In addition to the external modules that are included by default in the project, sometimes we need to import other external modules. Let's take [ant-design-vue](https://antdv.com/components/overview) as an example: + +## Installing Dependencies + +::: tip Install dependencies into a specific package + +- Since the project uses [pnpm](https://pnpm.io/) as the package management tool, we need to use the `pnpm` command to install dependencies. +- As the project is managed using a Monorepo module, we need to install dependencies under a specific package. Please make sure you have entered the specific package directory before installing dependencies. + +::: + +```bash +# cd /path/to/your/package +pnpm add ant-design-vue +``` + +## Usage + +### Global Import + +```ts +import { createApp } from 'vue'; +import Antd from 'ant-design-vue'; +import App from './App'; +import 'ant-design-vue/dist/reset.css'; + +const app = createApp(App); + +app.use(Antd).mount('#app'); +``` + +#### Usage + +```vue + +``` + +### Partial Import + +```vue + + + +``` + +::: warning Note + +- If the component depends on styles, you also need to import the style file. + +::: diff --git a/apps/vben5/docs/src/en/guide/essentials/icons.md b/apps/vben5/docs/src/en/guide/essentials/icons.md new file mode 100644 index 000000000..0c1631fe8 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/icons.md @@ -0,0 +1,78 @@ +# Icons + +::: tip About Icon Management + +- The icons in the project are mainly provided by the `@vben/icons` package. It is recommended to manage them within this package for unified management and maintenance. +- If you are using `Vscode`, it is recommended to install the [Iconify IntelliSense](https://marketplace.visualstudio.com/items?itemName=antfu.iconify) plugin, which makes it easy to find and use icons. + +::: + +There are several ways to use icons in the project, you can choose according to the actual situation: + +## Iconify Icons + +Integrated with the [iconify](https://github.com/iconify/iconify) icon library + +### Adding New Icons + +You can add new icons in the `packages/icons/src/iconify` directory: + +```ts +// packages/icons/src/iconify/index.ts +import { createIconifyIcon } from '@vben-core/icons'; + +export const MdiKeyboardEsc = createIconifyIcon('mdi:keyboard-esc'); +``` + +### Usage + +```vue + + + +``` + +## SVG Icons + +Instead of using Svg Sprite, SVG icons are directly imported, + +### Adding New Icons + +You can add new icon files `test.svg` in the `packages/icons/src/svg/icons` directory, and then import it in `packages/icons/src/svg/index.ts`: + +```ts +// packages/icons/src/svg/index.ts +import { createIconifyIcon } from '@vben-core/icons'; + +const SvgTestIcon = createIconifyIcon('svg:test'); + +export { SvgTestIcon }; +``` + +### Usage + +```vue + + + +``` + +## Tailwind CSS Icons + +### Usage + +You can use the icons by directly adding the Tailwind CSS icon class names, which can be found on [iconify](https://github.com/iconify/iconify) : + +```vue + +``` diff --git a/apps/vben5/docs/src/en/guide/essentials/route.md b/apps/vben5/docs/src/en/guide/essentials/route.md new file mode 100644 index 000000000..bef40d691 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/route.md @@ -0,0 +1,606 @@ +--- +outline: deep +--- + +# Routes and Menus + +::: info + +This page is translated by machine translation and may not be very accurate. + +::: + +In the project, the framework provides a basic routing system and **automatically generates the corresponding menu structure based on the routing files**. + +## Types of Routes + +Routes are divided into core routes, static routes, and dynamic routes. Core routes are built-in routes of the framework, including root routes, login routes, 404 routes, etc.; static routes are routes that are determined when the project starts; dynamic routes are generally generated dynamically based on the user's permissions after the user logs in. + +Both static and dynamic routes go through permission control, which can be controlled by configuring the `authority` field in the `meta` property of the route. + +### Core Routes + +Core routes are built-in routes of the framework, including root routes, login routes, 404 routes, etc. The configuration of core routes is in the `src/router/routes/core` directory under the application. + +::: tip + +Core routes are mainly used for the basic functions of the framework, so it is not recommended to put business-related routes in core routes. It is recommended to put business-related routes in static or dynamic routes. + +::: + +### Static Routes + +The configuration of static routes is in the `src/router/routes/index` directory under the application. Open the commented file content: + +::: tip + +Permission control is controlled by the `authority` field in the `meta` property of the route. If your page project does not require permission control, you can omit the `authority` field. + +::: + +```ts +// Uncomment if needed and create the folder +// const externalRouteFiles = import.meta.glob('./external/**/*.ts', { eager: true }); // [!code --] +const staticRouteFiles = import.meta.glob('./static/**/*.ts', { eager: true }); // [!code ++] +/** Dynamic routes */ +const dynamicRoutes: RouteRecordRaw[] = mergeRouteModules(dynamicRouteFiles); + +/** External route list, these pages can be accessed without Layout, possibly used for embedding in other systems */ +// const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles) // [!code --] +const externalRoutes: RouteRecordRaw[] = []; // [!code --] +const externalRoutes: RouteRecordRaw[] = mergeRouteModules(externalRouteFiles); // [!code ++] +``` + +### Dynamic Routes + +The configuration of dynamic routes is in the `src/router/routes/modules` directory under the corresponding application. This directory contains all the route files. The content format of each file is consistent with the Vue Router route configuration format. Below is the configuration of secondary and multi-level routes. + +## Route Definition + +The configuration method of static routes and dynamic routes is the same. Below is the configuration of secondary and multi-level routes: + +### Secondary Routes + +::: details Secondary Route Example Code + +```ts +import type { RouteRecordRaw } from 'vue-router'; + +import { VBEN_LOGO_URL } from '@vben/constants'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + badgeType: 'dot', + badgeVariants: 'destructive', + icon: VBEN_LOGO_URL, + order: 9999, + title: $t('page.vben.title'), + }, + name: 'VbenProject', + path: '/vben-admin', + redirect: '/vben-admin/about', + children: [ + { + name: 'VbenAbout', + path: '/vben-admin/about', + component: () => import('#/views/_core/about/index.vue'), + meta: { + badgeType: 'dot', + badgeVariants: 'destructive', + icon: 'lucide:copyright', + title: $t('page.vben.about'), + }, + }, + ], + }, +]; + +export default routes; +``` + +::: + +### Multi-level Routes + +::: tip + +- The parent route of multi-level routes does not need to set the `component` property, just set the `children` property. Unless you really need to display content nested under the parent route. +- In most cases, the `redirect` property of the parent route does not need to be specified, it will default to the first child route. + +::: + +::: details Multi-level Route Example Code + +```ts +import type { RouteRecordRaw } from 'vue-router'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'ic:baseline-view-in-ar', + keepAlive: true, + order: 1000, + title: $t('demos.title'), + }, + name: 'Demos', + path: '/demos', + redirect: '/demos/access', + children: [ + // Nested menu + { + meta: { + icon: 'ic:round-menu', + title: $t('demos.nested.title'), + }, + name: 'NestedDemos', + path: '/demos/nested', + redirect: '/demos/nested/menu1', + children: [ + { + name: 'Menu1Demo', + path: '/demos/nested/menu1', + component: () => import('#/views/demos/nested/menu-1.vue'), + meta: { + icon: 'ic:round-menu', + keepAlive: true, + title: $t('demos.nested.menu1'), + }, + }, + { + name: 'Menu2Demo', + path: '/demos/nested/menu2', + meta: { + icon: 'ic:round-menu', + keepAlive: true, + title: $t('demos.nested.menu2'), + }, + redirect: '/demos/nested/menu2/menu2-1', + children: [ + { + name: 'Menu21Demo', + path: '/demos/nested/menu2/menu2-1', + component: () => import('#/views/demos/nested/menu-2-1.vue'), + meta: { + icon: 'ic:round-menu', + keepAlive: true, + title: $t('demos.nested.menu2_1'), + }, + }, + ], + }, + { + name: 'Menu3Demo', + path: '/demos/nested/menu3', + meta: { + icon: 'ic:round-menu', + title: $t('demos.nested.menu3'), + }, + redirect: '/demos/nested/menu3/menu3-1', + children: [ + { + name: 'Menu31Demo', + path: 'menu3-1', + component: () => import('#/views/demos/nested/menu-3-1.vue'), + meta: { + icon: 'ic:round-menu', + keepAlive: true, + title: $t('demos.nested.menu3_1'), + }, + }, + { + name: 'Menu32Demo', + path: 'menu3-2', + meta: { + icon: 'ic:round-menu', + title: $t('demos.nested.menu3_2'), + }, + redirect: '/demos/nested/menu3/menu3-2/menu3-2-1', + children: [ + { + name: 'Menu321Demo', + path: '/demos/nested/menu3/menu3-2/menu3-2-1', + component: () => + import('#/views/demos/nested/menu-3-2-1.vue'), + meta: { + icon: 'ic:round-menu', + keepAlive: true, + title: $t('demos.nested.menu3_2_1'), + }, + }, + ], + }, + ], + }, + ], + }, + ], + }, +]; + +export default routes; +``` + +::: + +## Adding a New Page + +To add a new page, you only need to add a route and the corresponding page component. + +### Adding a Route + +Add a route object in the corresponding route file, as follows: + +```ts +import type { RouteRecordRaw } from 'vue-router'; + +import { VBEN_LOGO_URL } from '@vben/constants'; + +import { BasicLayout } from '#/layouts'; +import { $t } from '#/locales'; + +const routes: RouteRecordRaw[] = [ + { + component: BasicLayout, + meta: { + icon: 'mdi:home', + title: $t('page.home.title'), + }, + name: 'Home', + path: '/home', + redirect: '/home/index', + children: [ + { + name: 'HomeIndex', + path: '/home/index', + component: () => import('#/views/home/index.vue'), + meta: { + icon: 'mdi:home', + title: $t('page.home.index'), + }, + }, + ], + }, +]; + +export default routes; +``` + +### Adding a Page Component + +In `#/views/home/`, add a new `index.vue` file, as follows: + +```vue + +``` + +### Verification + +At this point, the page has been added. Visit `http://localhost:5555/home/index` to see the corresponding page. + +## Route Configuration + +The route configuration items are mainly in the `meta` property of the route object. The following are common configuration items: + +```ts {5-8} +const routes = [ + { + name: 'HomeIndex', + path: '/home/index', + meta: { + icon: 'mdi:home', + title: $t('page.home.index'), + }, + }, +]; +``` + +::: details Route Meta Configuration Type Definition + +```ts +interface RouteMeta { + /** + * Active icon (menu) + */ + activeIcon?: string; + /** + * The currently active menu, sometimes you don't want to activate the existing menu, use this to activate the parent menu + */ + activePath?: string; + /** + * Whether to fix the tab + * @default false + */ + affixTab?: boolean; + /** + * The order of fixed tabs + * @default 0 + */ + affixTabOrder?: number; + /** + * Specific roles required to access + * @default [] + */ + authority?: string[]; + /** + * Badge + */ + badge?: string; + /** + * Badge type + */ + badgeType?: 'dot' | 'normal'; + /** + * Badge color + */ + badgeVariants?: + | 'default' + | 'destructive' + | 'primary' + | 'success' + | 'warning' + | string; + /** + * The children of the current route are not displayed in the menu + * @default false + */ + hideChildrenInMenu?: boolean; + /** + * The current route is not displayed in the breadcrumb + * @default false + */ + hideInBreadcrumb?: boolean; + /** + * The current route is not displayed in the menu + * @default false + */ + hideInMenu?: boolean; + /** + * The current route is not displayed in the tab + * @default false + */ + hideInTab?: boolean; + /** + * Icon (menu/tab) + */ + icon?: string; + /** + * iframe address + */ + iframeSrc?: string; + /** + * Ignore permissions, can be accessed directly + * @default false + */ + ignoreAccess?: boolean; + /** + * Enable KeepAlive cache + */ + keepAlive?: boolean; + /** + * External link - jump path + */ + link?: string; + /** + * Whether the route has been loaded + */ + loaded?: boolean; + /** + * Maximum number of open tabs + * @default false + */ + maxNumOfOpenTab?: number; + /** + * The menu can be seen, but access will be redirected to 403 + */ + menuVisibleWithForbidden?: boolean; + /** + * Open in a new window + */ + openInNewWindow?: boolean; + /** + * Used for route -> menu sorting + */ + order?: number; + /** + * Parameters carried by the menu + */ + query?: Recordable; + /** + * Title name + */ + title: string; +} +``` + +::: + +### title + +- Type: `string` +- Default: `''` + +Used to configure the title of the page, which will be displayed in the menu and tab. Generally used with internationalization. + +### icon + +- Type: `string` +- Default: `''` + +Used to configure the icon of the page, which will be displayed in the menu and tab. Generally used with an icon library, if it is an `http` link, the image will be loaded automatically. + +### activeIcon + +- Type: `string` +- Default: `''` + +Used to configure the active icon of the page, which will be displayed in the menu. Generally used with an icon library, if it is an `http` link, the image will be loaded automatically. + +### keepAlive + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page cache is enabled. When enabled, the page will be cached and will not reload, only effective when the tab is enabled. + +### hideInMenu + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page is hidden in the menu. When hidden, the page will not be displayed in the menu. + +### hideInTab + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page is hidden in the tab. When hidden, the page will not be displayed in the tab. + +### hideInBreadcrumb + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page is hidden in the breadcrumb. When hidden, the page will not be displayed in the breadcrumb. + +### hideChildrenInMenu + +- Type: `boolean` +- Default: `false` + +Used to configure whether the subpages of the page are hidden in the menu. When hidden, the subpages will not be displayed in the menu. + +### authority + +- Type: `string[]` +- Default: `[]` + +Used to configure the permissions of the page. Only users with the corresponding permissions can access the page. If not configured, no permissions are required. + +### badge + +- Type: `string` +- Default: `''` + +Used to configure the badge of the page, which will be displayed in the menu. + +### badgeType + +- Type: `'dot' | 'normal'` +- Default: `'normal'` + +Used to configure the badge type of the page. `dot` is a small red dot, `normal` is text. + +### badgeVariants + +- Type: `'default' | 'destructive' | 'primary' | 'success' | 'warning' | string` +- Default: `'success'` + +Used to configure the badge color of the page. + +### activePath + +- Type: `string` +- Default: `''` + +Used to configure the currently active menu. Sometimes the page is not displayed in the menu, and this is used to activate the parent menu. + +### affixTab + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page is fixed in the tab. When fixed, the page cannot be closed. + +### affixTabOrder + +- Type: `number` +- Default: `0` + +Used to configure the order of fixed tabs, sorted in ascending order. + +### iframeSrc + +- Type: `string` +- Default: `''` + +Used to configure the `iframe` address of the embedded page. When set, the corresponding page will be embedded in the current page. + +### ignoreAccess + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page ignores permissions and can be accessed directly. + +### link + +- Type: `string` +- Default: `''` + +Used to configure the external link jump path, which will open in a new window. + +### maxNumOfOpenTab + +- Type: `number` +- Default: `-1` + +Used to configure the maximum number of open tabs. When set, the earliest opened tab will be automatically closed when opening a new tab (only effective when opening tabs with the same name). + +### menuVisibleWithForbidden + +- Type: `boolean` +- Default: `false` + +Used to configure whether the page can be seen in the menu, but access will be redirected to 403. + +### openInNewWindow + +- Type: `boolean` +- Default: `false` + +When set to `true`, the page will open in a new window. + +### order + +- Type: `number` +- Default: `0` + +Used to configure the sorting of the page, used for route to menu sorting. + +_Note:_ Sorting is only effective for first-level menus. The sorting of second-level menus needs to be set in the corresponding first-level menu in code order. + +### query + +- Type: `Recordable` +- Default: `{}` + +Used to configure the menu parameters of the page, which will be passed to the page in the menu. + +## Route Refresh + +The route refresh method is as follows: + +```vue + +``` diff --git a/apps/vben5/docs/src/en/guide/essentials/server.md b/apps/vben5/docs/src/en/guide/essentials/server.md new file mode 100644 index 000000000..95d505c0a --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/server.md @@ -0,0 +1,356 @@ +# Server Interaction and Data Mocking + +::: tip Note + +This document explains how to use Mock data and interact with the server in a development environment, involving technologies such as: + +- [Nitro](https://nitro.unjs.io/) A lightweight backend server that can be deployed anywhere, used as a Mock server in the project. +- [axios](https://axios-http.com/docs/intro) Used to send HTTP requests to interact with the server. + +::: + +## Interaction in Development Environment + +If the frontend application and the backend API server are not running on the same host, you need to proxy the API requests to the API server in the development environment. If they are on the same host, you can directly request the specific API endpoint. + +### Local Development CORS Configuration + +::: tip Hint + +The CORS configuration for local development has already been set up. If you have other requirements, you can add or adjust the configuration as needed. + +::: + +#### Configuring Local Development API Endpoint + +Configure the API endpoint in the `.env.development` file at the project root directory, here it is set to `/api`: + +```bash +VITE_GLOB_API_URL=/api +``` + +#### Configuring Development Server Proxy + +In the development environment, if you need to handle CORS, configure the API endpoint in the `vite.config.mts` file under the corresponding application directory: + +```ts{8-16} +// apps/web-antd/vite.config.mts +import { defineConfig } from '@vben/vite-config'; + +export default defineConfig(async () => { + return { + vite: { + server: { + proxy: {// [!code focus:11] + '/api': { + changeOrigin: true, + rewrite: (path) => path.replace(/^\/api/, ''), + // mock proxy + target: 'http://localhost:5320/api', + ws: true, + }, + }, + }, + }, + }; +}); +``` + +#### API Requests + +Based on the above configuration, we can use `/api` as the prefix for API requests in our frontend project, for example: + +```ts +import axios from 'axios'; + +axios.get('/api/user').then((res) => { + console.log(res); +}); +``` + +At this point, the request will be proxied to `http://localhost:5320/api/user`. + +::: warning Note + +From the browser's console Network tab, the request appears as `http://localhost:5555/api/user`. This is because the proxy configuration does not change the local request's URL. + +::: + +### Configuration Without CORS + +If there is no CORS issue, you can directly ignore the [Configure Development Server Proxy](./server.md#configure-development-server-proxy) settings and set the API endpoint directly in `VITE_GLOB_API_URL`. + +Configure the API endpoint in the `.env.development` file at the project root directory: + +```bash +VITE_GLOB_API_URL=https://mock-napi.vben.pro/api +``` + +## Production Environment Interaction + +### API Endpoint Configuration + +Configure the API endpoint in the `.env.production` file at the project root directory: + +```bash +VITE_GLOB_API_URL=https://mock-napi.vben.pro/api +``` + +::: tip How to Dynamically Modify API Endpoint in Production + +Variables starting with `VITE_GLOB_*` in the `.env` file are injected into the `_app.config.js` file during packaging. After packaging, you can modify the corresponding API addresses in `dist/_app.config.js` and refresh the page to apply the changes. This eliminates the need to package multiple times for different environments, allowing a single package to be deployed across multiple API environments. + +::: + +### Cross-Origin Resource Sharing (CORS) Handling + +In the production environment, if CORS issues arise, you can use `nginx` to proxy the API address or enable `cors` on the backend to handle it (refer to the mock service for examples). + +## API Request Configuration + +The project comes with a default basic request configuration based on `axios`, provided by the `@vben/request` package. The project does not overly complicate things but simply wraps some common configurations. If there are other requirements, you can add or adjust the configurations as needed. Depending on the app, different component libraries and `store` might be used, so under the `src/api/request.ts` folder in the application directory, there are corresponding request configuration files. For example, in the `web-antd` project, there's a `src/api/request.ts` file where you can configure according to your needs. + +### Request Examples + +#### GET Request + +```ts +import { requestClient } from '#/api/request'; + +export async function getUserInfoApi() { + return requestClient.get('/user/info'); +} +``` + +#### POST/PUT Request + +```ts +import { requestClient } from '#/api/request'; + +export async function saveUserApi(user: UserInfo) { + return requestClient.post('/user', user); +} + +export async function saveUserApi(user: UserInfo) { + return requestClient.put('/user', user); +} + +export async function saveUserApi(user: UserInfo) { + const url = user.id ? `/user/${user.id}` : '/user/'; + return requestClient.request(url, { + data: user, + // OR PUT + method: user.id ? 'PUT' : 'POST', + }); +} +``` + +#### DELETE Request + +```ts +import { requestClient } from '#/api/request'; + +export async function deleteUserApi(user: UserInfo) { + return requestClient.delete(`/user/${user.id}`, user); +} +``` + +### Request Configuration + +The `src/api/request.ts` within the application can be configured according to the needs of your application: + +```ts +/** + * This file can be adjusted according to business logic + */ +import type { HttpResponse } from '@vben/request'; + +import { useAppConfig } from '@vben/hooks'; +import { preferences } from '@vben/preferences'; +import { + authenticateResponseInterceptor, + errorMessageResponseInterceptor, + RequestClient, +} from '@vben/request'; +import { useAccessStore } from '@vben/stores'; + +import { message } from 'ant-design-vue'; + +import { useAuthStore } from '#/store'; + +import { refreshTokenApi } from './core'; + +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); + +function createRequestClient(baseURL: string) { + const client = new RequestClient({ + baseURL, + }); + + /** + * Re-authentication Logic + */ + async function doReAuthenticate() { + console.warn('Access token or refresh token is invalid or expired. '); + const accessStore = useAccessStore(); + const authStore = useAuthStore(); + accessStore.setAccessToken(null); + if (preferences.app.loginExpiredMode === 'modal') { + accessStore.setLoginExpired(true); + } else { + await authStore.logout(); + } + } + + /** + * Refresh token Logic + */ + async function doRefreshToken() { + const accessStore = useAccessStore(); + const resp = await refreshTokenApi(); + const newToken = resp.data; + accessStore.setAccessToken(newToken); + return newToken; + } + + function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; + } + + // Request Header Processing + client.addRequestInterceptor({ + fulfilled: async (config) => { + const accessStore = useAccessStore(); + + config.headers.Authorization = formatToken(accessStore.accessToken); + config.headers['Accept-Language'] = preferences.app.locale; + return config; + }, + }); + + // Deal Response Data + client.addResponseInterceptor({ + fulfilled: (response) => { + const { data: responseData, status } = response; + + const { code, data } = responseData; + + if (status >= 200 && status < 400 && code === 0) { + return data; + } + throw Object.assign({}, response, { response }); + }, + }); + + // Handling Token Expiration + client.addResponseInterceptor( + authenticateResponseInterceptor({ + client, + doReAuthenticate, + doRefreshToken, + enableRefreshToken: preferences.app.enableRefreshToken, + formatToken, + }), + ); + + // Generic error handling; if none of the above error handling logic is triggered, it will fall back to this. + client.addResponseInterceptor( + errorMessageResponseInterceptor((msg: string, error) => { + // 这里可以根据业务进行定制,你可以拿到 error 内的信息进行定制化处理,根据不同的 code 做不同的提示,而不是直接使用 message.error 提示 msg + // 当前mock接口返回的错误字段是 error 或者 message + const responseData = error?.response?.data ?? {}; + const errorMessage = responseData?.error ?? responseData?.message ?? ''; + // 如果没有错误信息,则会根据状态码进行提示 + message.error(errorMessage || msg); + }), + ); + + return client; +} + +export const requestClient = createRequestClient(apiURL); + +export const baseRequestClient = new RequestClient({ baseURL: apiURL }); +``` + +### Multiple API Endpoints + +To handle multiple API endpoints, simply create multiple `requestClient` instances, as follows: + +```ts +const { apiURL, otherApiURL } = useAppConfig( + import.meta.env, + import.meta.env.PROD, +); + +export const requestClient = createRequestClient(apiURL); + +export const otherRequestClient = createRequestClient(otherApiURL); +``` + +## Refresh Token + +The project provides a default logic for refreshing tokens. To enable it, follow the configuration below: + +- Ensure the refresh token feature is enabled + +Adjust the `preferences.ts` in the corresponding application directory to ensure `enableRefreshToken='true'`. + +```ts +import { defineOverridesPreferences } from '@vben/preferences'; + +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + enableRefreshToken: true, + }, +}); +``` + +Configure the `doRefreshToken` method in `src/api/request.ts` as follows: + +```ts +// Adjust this to your token format +function formatToken(token: null | string) { + return token ? `Bearer ${token}` : null; +} + +/** + * Refresh token logic + */ +async function doRefreshToken() { + const accessStore = useAccessStore(); + // Adjust this to your refresh token API + const resp = await refreshTokenApi(); + const newToken = resp.data; + accessStore.setAccessToken(newToken); + return newToken; +} +``` + +## Data Mocking + +::: tip Production Environment Mock + +The new version no longer supports mock in the production environment. Please use real interfaces. + +::: + +Mock data is an indispensable part of frontend development, serving as a key link in separating frontend and backend development. By agreeing on interfaces with the server side in advance and simulating request data and even logic, frontend development can proceed independently, without being blocked by the backend development process. + +The project uses [Nitro](https://nitro.unjs.io/) for local mock data processing. The principle is to start an additional backend service locally, which is a real backend service that can handle requests and return data. + +### Using Nitro + +The mock service code is located in the `apps/backend-mock` directory. It does not need to be started manually and is already integrated into the project. You only need to run `pnpm dev` in the project root directory. After running successfully, the console will print `http://localhost:5320/api`, and you can access this address to view the mock service. + +[Nitro](https://nitro.unjs.io/) syntax is simple, and you can configure and develop according to your needs. For specific configurations, you can refer to the [Nitro documentation](https://nitro.unjs.io/). + +## Disabling Mock Service + +Since mock is essentially a real backend service, if you do not need the mock service, you can configure `VITE_NITRO_MOCK=false` in the `.env.development` file in the project root directory to disable the mock service. + +```bash +# .env.development +VITE_NITRO_MOCK=false +``` diff --git a/apps/vben5/docs/src/en/guide/essentials/settings.md b/apps/vben5/docs/src/en/guide/essentials/settings.md new file mode 100644 index 000000000..68fef3e7e --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/settings.md @@ -0,0 +1,514 @@ +# Configuration + +## Environment Variable Configuration + +The project's environment variable configuration is located in the application directory under `.env`, `.env.development`, `.env.production`. + +The rules are consistent with [Vite Env Variables and Modes](https://vitejs.dev/guide/env-and-mode.html). The format is as follows: + +```bash +.env # Loaded in all environments +.env.local # Loaded in all environments, but ignored by git +.env.[mode] # Only loaded in the specified mode +.env.[mode].local # Only loaded in the specified mode, but ignored by git +``` + +::: tip + +- Only variables starting with `VITE_` will be embedded into the client-side package. You can access them in the project code like this: + + ```ts + console.log(import.meta.env.VITE_PROT); + ``` + +- Variables starting with `VITE_GLOB_*` will be added to the `_app.config.js` configuration file during packaging. ::: + +::: + +## Environment Configuration Description + +::: code-group + +```bash [.env] +# Application title +VITE_APP_TITLE=Vben Admin + +# Application namespace, used as a prefix for caching, store, etc., to ensure isolation +VITE_APP_NAMESPACE=vben-web-antd +``` + +```bash [.env.development] +# Port Number +VITE_PORT=5555 + +# Public Path for Resources, must start and end with / +VITE_BASE=/ + +# API URL +VITE_GLOB_API_URL=/api + +# Whether to enable Nitro Mock service, true to enable, false to disable +VITE_NITRO_MOCK=true + +# Whether to open devtools, true to open, false to close +VITE_DEVTOOLS=true + +# Whether to inject global loading +VITE_INJECT_APP_LOADING=true + +# Whether to generate after packaging dist.zip +VITE_ARCHIVER=true +``` + +::: + +## Dynamic Configuration in Production Environment + +When executing `pnpm build` in the root directory of the monorepo, a `dist/_app.config.js` file will be automatically generated in the corresponding application and inserted into `index.html`. + +`_app.config.js` is a dynamic configuration file that allows for modifications to the configuration dynamically based on different environments after the project has been built. The content is as follows: + +```ts +window._VBEN_ADMIN_PRO_APP_CONF_ = { + VITE_GLOB_API_URL: 'https://mock-napi.vben.pro/api', +}; +Object.freeze(window._VBEN_ADMIN_PRO_APP_CONF_); +Object.defineProperty(window, '_VBEN_ADMIN_PRO_APP_CONF_', { + configurable: false, + writable: false, +}); +``` + +### Purpose + +`_app.config.js` is used for projects that need to dynamically modify configurations after packaging, such as API endpoints. There's no need to repackage; you can simply modify the variables in `/dist/_app.config.js` after packaging, and refresh to update the variables in the code. A `js` file is used to ensure that the configuration file is loaded early in the order. + +### Usage + +To access the variables inside `_app.config.js`, you need to use the `useAppConfig` method provided by `@vben/hooks`. + +```ts +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); +``` + +### Adding New + +To add a new dynamically modifiable configuration item, simply follow the steps below: + +- First, add the variable that needs to be dynamically configurable in the `.env` file or the corresponding development environment configuration file. The variable must start with `VITE_GLOB_*`, for example: + + ```bash + VITE_GLOB_OTHER_API_URL=https://mock-napi.vben.pro/other-api + ``` + +- In `packages/types/global.d.ts`, add the corresponding type definition, such as: + + ```ts + export interface VbenAdminProAppConfigRaw { + VITE_GLOB_API_URL: string; + VITE_GLOB_OTHER_API_URL: string; // [!code ++] + } + + export interface ApplicationConfig { + apiURL: string; + otherApiURL: string; // [!code ++] + } + ``` + +At this point, you can use the `useAppConfig` method within the project to access the newly added configuration item. + +```ts +const { otherApiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); +``` + +::: warning Warning + +The `useAppConfig` method should only be used within the application and not be coupled with the internals of a package. The reason for passing `import.meta.env` and `import.meta.env.PROD` is to avoid such coupling. A pure package should avoid using variables specific to a particular build tool. + +::: + +## Preferences + +The project offers a wide range of preference settings for dynamically configuring various features of the project: + +![](/guide/preferences.png) + +If you cannot find documentation for a setting, you can try configuring it yourself and then click `Copy Preferences` to override the project defaults. The configuration file is located in the application directory under `preferences.ts`, where you can override the framework's default configurations to achieve custom settings. + +```ts +import { useAppConfig } from '@vben/hooks'; +import { defineOverridesPreferences } from '@vben/preferences'; + +/** + * @description Project configuration file + * Only a part of the configuration in the project needs to be covered, and unnecessary configurations do not need to be covered. The default configuration will be automatically used + */ +export const overridesPreferences = defineOverridesPreferences({ + // overrides +}); +``` + +### Framework default configuration + +::: details View the default configuration of the framework + +```ts +const defaultPreferences: Preferences = { + app: { + accessMode: 'frontend', + authPageLayout: 'panel-right', + checkUpdatesInterval: 1, + colorGrayMode: false, + colorWeakMode: false, + compact: false, + contentCompact: 'wide', + defaultAvatar: + 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/avatar-v1.webp', + dynamicTitle: true, + enableCheckUpdates: true, + enablePreferences: true, + enableRefreshToken: false, + isMobile: false, + layout: 'sidebar-nav', + locale: 'zh-CN', + loginExpiredMode: 'modal', + name: 'Vben Admin', + preferencesButtonPosition: 'auto', + watermark: false, + }, + breadcrumb: { + enable: true, + hideOnlyOne: false, + showHome: false, + showIcon: true, + styleType: 'normal', + }, + copyright: { + companyName: 'Vben', + companySiteLink: 'https://www.vben.pro', + date: '2024', + enable: true, + icp: '', + icpLink: '', + }, + footer: { + enable: true, + fixed: false, + }, + header: { + enable: true, + hidden: false, + mode: 'fixed', + }, + logo: { + enable: true, + source: 'https://unpkg.com/@vbenjs/static-source@0.1.7/source/logo-v1.webp', + }, + navigation: { + accordion: true, + split: true, + styleType: 'rounded', + }, + shortcutKeys: { + enable: true, + globalLockScreen: true, + globalLogout: true, + globalPreferences: true, + globalSearch: true, + }, + sidebar: { + collapsed: false, + collapsedShowTitle: false, + enable: true, + expandOnHover: true, + extraCollapse: true, + hidden: false, + width: 230, + }, + tabbar: { + draggable: true, + enable: true, + height: 36, + keepAlive: true, + persist: true, + showIcon: true, + showMaximize: true, + showMore: true, + styleType: 'chrome', + }, + theme: { + builtinType: 'default', + colorDestructive: 'hsl(348 100% 61%)', + colorPrimary: 'hsl(212 100% 45%)', + colorSuccess: 'hsl(144 57% 58%)', + colorWarning: 'hsl(42 84% 61%)', + mode: 'dark', + radius: '0.5', + semiDarkHeader: false, + semiDarkSidebar: true, + }, + transition: { + enable: true, + loading: true, + name: 'fade-slide', + progress: true, + }, + widget: { + fullscreen: true, + globalSearch: true, + languageToggle: true, + lockScreen: true, + notification: true, + sidebarToggle: true, + themeToggle: true, + refresh: true, + }, +}; +``` + +::: + +::: details View the default configuration type of the framework + +```ts +interface AppPreferences { + /** Permission mode */ + accessMode: AccessModeType; + /** Layout of the login/registration page */ + authPageLayout: AuthPageLayoutType; + /** Interval for checking updates */ + checkUpdatesInterval: number; + /** Whether to enable gray mode */ + colorGrayMode: boolean; + /** Whether to enable color weakness mode */ + colorWeakMode: boolean; + /** Whether to enable compact mode */ + compact: boolean; + /** Whether to enable content compact mode */ + contentCompact: ContentCompactType; + // /** Default application avatar */ + defaultAvatar: string; + // /** Enable dynamic title */ + dynamicTitle: boolean; + /** Whether to enable update checks */ + enableCheckUpdates: boolean; + /** Whether to display preferences */ + enablePreferences: boolean; + /** + * @zh_CN Whether to enable refreshToken + */ + enableRefreshToken: boolean; + /** Whether it's mobile */ + isMobile: boolean; + /** Layout method */ + layout: LayoutType; + /** Supported languages */ + locale: SupportedLanguagesType; + /** Login expiration mode */ + loginExpiredMode: LoginExpiredModeType; + /** Application name */ + name: string; + /** Position of the preferences button */ + preferencesButtonPosition: PreferencesButtonPositionType; + /** + * @zh_CN Whether to enable watermark + */ + watermark: boolean; +} +interface BreadcrumbPreferences { + /** Whether breadcrumbs are enabled */ + enable: boolean; + /** Whether to hide breadcrumbs when there is only one */ + hideOnlyOne: boolean; + /** Whether the home icon in breadcrumbs is visible */ + showHome: boolean; + /** Whether the icon in breadcrumbs is visible */ + showIcon: boolean; + /** Breadcrumb style */ + styleType: BreadcrumbStyleType; +} + +interface CopyrightPreferences { + /** Copyright company name */ + companyName: string; + /** Link to the copyright company's site */ + companySiteLink: string; + /** Copyright date */ + date: string; + /** Whether copyright is visible */ + enable: boolean; + /** ICP number */ + icp: string; + /** Link to the ICP */ + icpLink: string; +} + +interface FooterPreferences { + /** Whether the footer is visible */ + enable: boolean; + /** Whether the footer is fixed */ + fixed: boolean; +} + +interface HeaderPreferences { + /** Whether the header is enabled */ + enable: boolean; + /** Whether the header is hidden, css-hidden */ + hidden: boolean; + /** Header display mode */ + mode: LayoutHeaderModeType; +} + +interface LogoPreferences { + /** Whether the logo is visible */ + enable: boolean; + /** Logo URL */ + source: string; +} + +interface NavigationPreferences { + /** Navigation menu accordion mode */ + accordion: boolean; + /** Whether the navigation menu is split, only effective in layout=mixed-nav */ + split: boolean; + /** Navigation menu style */ + styleType: NavigationStyleType; +} +interface SidebarPreferences { + /** Whether the sidebar is collapsed */ + collapsed: boolean; + /** Whether to show title when sidebar is collapsed */ + collapsedShowTitle: boolean; + /** Whether the sidebar is visible */ + enable: boolean; + /** Menu auto-expand state */ + expandOnHover: boolean; + /** Whether the sidebar extension area is collapsed */ + extraCollapse: boolean; + /** Whether the sidebar is hidden - css */ + hidden: boolean; + /** Sidebar width */ + width: number; +} + +interface ShortcutKeyPreferences { + /** Whether shortcut keys are enabled globally */ + enable: boolean; + /** Whether the global lock screen shortcut is enabled */ + globalLockScreen: boolean; + /** Whether the global logout shortcut is enabled */ + globalLogout: boolean; + /** Whether the global preferences shortcut is enabled */ + globalPreferences: boolean; + /** Whether the global search shortcut is enabled */ + globalSearch: boolean; +} + +interface TabbarPreferences { + /** Whether dragging of multiple tabs is enabled */ + draggable: boolean; + /** Whether multiple tabs are enabled */ + enable: boolean; + /** Tab height */ + height: number; + /** Whether tab caching is enabled */ + keepAlive: boolean; + /** Whether tabs are persistent */ + persist: boolean; + /** Whether icons in multiple tabs are enabled */ + showIcon: boolean; + /** Whether to show the maximize button */ + showMaximize: boolean; + /** Whether to show the more button */ + showMore: boolean; + /** Tab style */ + styleType: TabsStyleType; +} +interface ThemePreferences { + /** Built-in theme name */ + builtinType: BuiltinThemeType; + /** Destructive color */ + colorDestructive: string; + /** Primary color */ + colorPrimary: string; + /** Success color */ + colorSuccess: string; + /** Warning color */ + colorWarning: string; + /** Current theme */ + mode: ThemeModeType; + /** Radius */ + radius: string; + /** Whether to enable semi-dark header (only effective when theme='light') */ + semiDarkHeader: boolean; + /** Whether to enable semi-dark sidebar (only effective when theme='light') */ + semiDarkSidebar: boolean; +} + +interface TransitionPreferences { + /** Whether page transition animations are enabled */ + enable: boolean; + // /** Whether page loading loading is enabled */ + loading: boolean; + /** Page transition animation */ + name: PageTransitionType | string; + /** Whether page loading progress animation is enabled */ + progress: boolean; +} + +interface WidgetPreferences { + /** Whether fullscreen widgets are enabled */ + fullscreen: boolean; + /** Whether global search widget is enabled */ + globalSearch: boolean; + /** Whether language switch widget is enabled */ + languageToggle: boolean; + /** Whether lock screen functionality is enabled */ + lockScreen: boolean; + /** Whether notification widget is displayed */ + notification: boolean; + /** Whether to show the refresh button */ + refresh: boolean; + /** Whether sidebar show/hide widget is displayed */ + sidebarToggle: boolean; + /** Whether theme switch widget is displayed */ + themeToggle: boolean; +} +interface Preferences { + /** Global configuration */ + app: AppPreferences; + /** Header configuration */ + breadcrumb: BreadcrumbPreferences; + /** Copyright configuration */ + copyright: CopyrightPreferences; + /** Footer configuration */ + footer: FooterPreferences; + /** Breadcrumb configuration */ + header: HeaderPreferences; + /** Logo configuration */ + logo: LogoPreferences; + /** Navigation configuration */ + navigation: NavigationPreferences; + /** Shortcut key configuration */ + shortcutKeys: ShortcutKeyPreferences; + /** Sidebar configuration */ + sidebar: SidebarPreferences; + /** Tab bar configuration */ + tabbar: TabbarPreferences; + /** Theme configuration */ + theme: ThemePreferences; + /** Animation configuration */ + transition: TransitionPreferences; + /** Widget configuration */ + widget: WidgetPreferences; +} +``` + +::: + +::: warning Warning + +- The `overridesPreferences` method only needs to override a part of the configurations in the project. There's no need to override configurations that are not needed; they will automatically use the default settings. +- Any configuration item can be overridden. You just need to override it within the `overridesPreferences` method. Do not modify the default configuration file. + +::: diff --git a/apps/vben5/docs/src/en/guide/essentials/styles.md b/apps/vben5/docs/src/en/guide/essentials/styles.md new file mode 100644 index 000000000..16f6681d2 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/essentials/styles.md @@ -0,0 +1,106 @@ +# Styles + +::: tip Preface + +For Vue projects, the [official documentation](https://vuejs.org/api/sfc-css-features.html#deep-selectors) already provides a detailed introduction to the syntax. Here, we mainly introduce the structure and usage of style files in the project. + +::: + +## Project Structure + +The style files in the project are stored in `@vben/styles`, which includes some global styles, such as reset styles, global variables, etc. It inherits the styles and capabilities of `@vben-core/design` and can be overridden according to project needs. + +## Scss + +The project uses `scss` as the style preprocessor, allowing the use of `scss` features such as variables, functions, mixins, etc., within the project. + +```vue + +``` + +## Postcss + +If you're not accustomed to using `scss`, you can also use `postcss`, which is a more powerful style processor that supports a wider range of plugins. The project includes the [postcss-nested](https://github.com/postcss/postcss-nested) plugin and is configured with `Css Variables`, making it a complete substitute for `scss`. + +```vue + +``` + +## Tailwind CSS + +The project integrates [Tailwind CSS](https://tailwindcss.com/), allowing the use of `tailwindcss` class names to quickly build pages. + +```vue + +``` + +## BEM Standard + +Another option to avoid style conflicts is to use the `BEM` standard. If you choose `scss`, it is recommended to use the `BEM` naming convention for better style management. The project provides a default `useNamespace` function to easily generate namespaces. + +```vue + + + +``` + +## CSS Modules + +Another solution to address style conflicts is to use the `CSS Modules` modular approach. The usage method is as follows. + +```vue + + + +``` + +For more usage, see the [CSS Modules official documentation](https://vuejs.org/api/sfc-css-features.html#css-modules). diff --git a/apps/vben5/docs/src/en/guide/in-depth/access.md b/apps/vben5/docs/src/en/guide/in-depth/access.md new file mode 100644 index 000000000..05997d7d5 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/access.md @@ -0,0 +1,318 @@ +--- +outline: deep +--- + +# Access Control + +The framework has built-in two types of access control methods: + +- Determining whether a menu or button can be accessed based on user roles +- Determining whether a menu or button can be accessed through an API + +## Frontend Access Control + +**Implementation Principle**: The permissions for routes are hardcoded on the frontend, specifying which permissions are required to view certain routes. Only general routes are initialized, and routes that require permissions are not added to the route table. After logging in or obtaining user roles through other means, the roles are used to traverse the route table to generate a route table that the role can access. This table is then added to the router instance using `router.addRoute`, achieving permission filtering. + +**Disadvantage**: The permissions are relatively inflexible; if the backend changes roles, the frontend needs to be adjusted accordingly. This is suitable for systems with relatively fixed roles. + +### Steps + +- Ensure the current mode is set to frontend access control + +Adjust `preferences.ts` in the corresponding application directory to ensure `accessMode='frontend'`. + +```ts +import { defineOverridesPreferences } from '@vben/preferences'; + +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + // Default value, optional + accessMode: 'frontend', + }, +}); +``` + +- Configure route permissions + +#### If not configured, it is visible by default + +```ts {3} + { + meta: { + authority: ['super'], + }, +}, +``` + +- Ensure the roles returned by the interface match the permissions in the route table + +You can look under `src/store/auth` in the application to find the following code: + +```ts +// Set the login user information, ensuring that userInfo.roles is an array and contains permissions from the route table +// For example: userInfo.roles=['super', 'admin'] +authStore.setUserInfo(userInfo); +``` + +At this point, the configuration is complete. You need to ensure that the roles returned by the interface after login match the permissions in the route table; otherwise, access will not be possible. + +### Menu Visible but Access Forbidden + +Sometimes, we need the menu to be visible but access to it forbidden. This can be achieved by setting `menuVisibleWithForbidden` to `true`. In this case, the menu will be visible, but access will be forbidden, redirecting to a 403 page. + +```ts +{ + meta: { + menuVisibleWithForbidden: true, + }, +}, +``` + +## Backend Access Control + +**Implementation Principle**: It is achieved by dynamically generating a routing table through an API, which returns data following a certain structure. The frontend processes this data into a recognizable structure, then adds it to the routing instance using `router.addRoute`, realizing the dynamic generation of permissions. + +**Disadvantage**: The backend needs to provide a data structure that meets the standards, and the frontend needs to process this structure. This is suitable for systems with more complex permissions. + +### Steps + +- Ensure the current mode is set to backend access control + +Adjust `preferences.ts` in the corresponding application directory to ensure `accessMode='backend'`. + +```ts +import { defineOverridesPreferences } from '@vben/preferences'; + +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + accessMode: 'backend', + }, +}); +``` + +- Ensure the structure of the menu data returned by the interface is correct + +You can look under `src/router/access.ts` in the application to find the following code: + +```ts +async function generateAccess(options: GenerateMenuAndRoutesOptions) { + return await generateAccessible(preferences.app.accessMode, { + fetchMenuListAsync: async () => { + // This interface is for the menu data returned by the backend + return await getAllMenus(); + }, + }); +} +``` + +- Interface returns menu data, see comments for explanation + +::: details Example of Interface Returning Menu Data + +```ts +const dashboardMenus = [ + { + // Here, 'BasicLayout' is hardcoded and cannot be changed + component: 'BasicLayout', + meta: { + order: -1, + title: 'page.dashboard.title', + }, + name: 'Dashboard', + path: '/', + redirect: '/analytics', + children: [ + { + name: 'Analytics', + path: '/analytics', + // Here is the path of the page, need to remove 'views/' and '.vue' + component: '/dashboard/analytics/index', + meta: { + affixTab: true, + title: 'page.dashboard.analytics', + }, + }, + { + name: 'Workspace', + path: '/workspace', + component: '/dashboard/workspace/index', + meta: { + title: 'page.dashboard.workspace', + }, + }, + ], + }, +]; +``` + +::: + +At this point, the configuration is complete. You need to ensure that after logging in, the format of the menu returned by the interface is correct; otherwise, access will not be possible. + +## Fine-grained Control of Buttons + +In some cases, we need to control the display of buttons with fine granularity. We can control the display of buttons through interfaces or roles. + +### Permission Code + +The permission code is the code returned by the interface. The logic to determine whether a button is displayed is located under `src/store/auth`: + +```ts +const [fetchUserInfoResult, accessCodes] = await Promise.all([ + fetchUserInfo(), + getAccessCodes(), +]); + +userInfo = fetchUserInfoResult; +authStore.setUserInfo(userInfo); +accessStore.setAccessCodes(accessCodes); +``` + +Locate the `getAccessCodes` corresponding interface, which can be adjusted according to business logic. + +The data structure returned by the permission code is an array of strings, for example: `['AC_100100', 'AC_100110', 'AC_100120', 'AC_100010']` + +With the permission codes, you can use the `AccessControl` component and API provided by `@vben/access` to show and hide buttons. + +#### Component Method + +```vue + + + +``` + +#### API Method + +```vue + + + +``` + +#### Directive Method + +> The directive supports binding single or multiple permission codes. For a single one, you can pass a string or an array containing one permission code, and for multiple permission codes, you can pass an array. + +```vue + +``` + +### Roles + +The method of determining roles does not require permission codes returned by the interface; it directly determines whether buttons are displayed based on roles. + +#### Component Method + +```vue + + + +``` + +#### API Method + +```vue + + + +``` + +#### Directive Method + +> The directive supports binding single or multiple permission codes. For a single one, you can pass a string or an array containing one permission code, and for multiple permission codes, you can pass an array. + +```vue + +``` diff --git a/apps/vben5/docs/src/en/guide/in-depth/check-updates.md b/apps/vben5/docs/src/en/guide/in-depth/check-updates.md new file mode 100644 index 000000000..1e5b679dc --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/check-updates.md @@ -0,0 +1,48 @@ +# Check Updates + +## Introduction + +When there are updates to the website, you might need to check for updates. The framework provides this functionality. By periodically checking for updates, you can configure the `checkUpdatesInterval` and `enableCheckUpdates` fields in your application's preferences.ts file to enable and set the interval for checking updates (in minutes). + +```ts +import { defineOverridesPreferences } from '@vben/preferences'; + +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + // Whether to enable check for updates + enableCheckUpdates: true, + // The interval for checking updates, in minutes + checkUpdatesInterval: 1, + }, +}); +``` + +## Effect + +When an update is detected, a prompt will pop up asking the user whether to refresh the page: + +![check-updates](/guide/update-notice.png) + +## Replacing with Other Update Checking Methods + +If you need to check for updates in other ways, such as through an API to more flexibly control the update logic (such as force refresh, display update content, etc.), you can do so by modifying the `src/widgets/check-updates/check-updates.vue` file under `@vben/layouts`. + +```ts +// Replace this with your update checking logic +async function getVersionTag() { + try { + const response = await fetch('/', { + cache: 'no-cache', + method: 'HEAD', + }); + + return ( + response.headers.get('etag') || response.headers.get('last-modified') + ); + } catch { + console.error('Failed to fetch version tag'); + return null; + } +} +``` diff --git a/apps/vben5/docs/src/en/guide/in-depth/features.md b/apps/vben5/docs/src/en/guide/in-depth/features.md new file mode 100644 index 000000000..24fecea96 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/features.md @@ -0,0 +1,84 @@ +# Common Features + +A collection of some commonly used features. + +## Login Authentication Expiry + +When the interface returns a `401` status code, the framework will consider the login authentication to have expired. Upon login timeout, it will redirect to the login page or open a login popup. This can be configured in `preferences.ts` in the application directory: + +### Redirect to Login Page + +Upon login timeout, it will redirect to the login page. + +```ts +import { defineOverridesPreferences } from '@vben/preferences'; + +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + loginExpiredMode: 'page', + }, +}); +``` + +### Open Login Popup + +When login times out, a login popup will open. + +![login-expired](/guide/login-expired.png) + +Configuration: + +```ts +import { defineOverridesPreferences } from '@vben/preferences'; + +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + loginExpiredMode: 'modal', + }, +}); +``` + +## Dynamic Title + +- Default value: `true` + +When enabled, the webpage title changes according to the route's `title`. You can enable or disable this in the `preferences.ts` file in your application directory. + +```ts +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + dynamicTitle: true, + }, +}); +``` + +## Page Watermark + +- Default value: `false` + +When enabled, the webpage will display a watermark. You can enable or disable this in the `preferences.ts` file in your application directory. + +```ts +export const overridesPreferences = defineOverridesPreferences({ + // overrides + app: { + watermark: true, + }, +}); +``` + +If you want to update the content of the watermark, you can do so. The parameters can be referred to [watermark-js-plus](https://zhensherlock.github.io/watermark-js-plus/): + +```ts +import { useWatermark } from '@vben/hooks'; + +const { destroyWatermark, updateWatermark } = useWatermark(); + +await updateWatermark({ + // watermark content + content: 'hello my watermark', +}); +``` diff --git a/apps/vben5/docs/src/en/guide/in-depth/layout.md b/apps/vben5/docs/src/en/guide/in-depth/layout.md new file mode 100644 index 000000000..412c1cf07 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/layout.md @@ -0,0 +1 @@ +# Layout diff --git a/apps/vben5/docs/src/en/guide/in-depth/loading.md b/apps/vben5/docs/src/en/guide/in-depth/loading.md new file mode 100644 index 000000000..0f1cff6ee --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/loading.md @@ -0,0 +1,44 @@ +# Global Loading + +Global loading refers to the loading effect that appears when the page is refreshed, usually a spinning icon: + +![Global loading spinner](/guide/loading.png) + +## Principle + +Implemented by the `vite-plugin-inject-app-loading` plugin, the plugin injects a global `loading html` into each application. + +## Disable + +If you do not need global loading, you can disable it in the `.env` file: + +```bash +VITE_INJECT_APP_LOADING=false +``` + +## Customization + +If you want to customize the global loading, you can create a `loading.html` file in the application directory, at the same level as `index.html`. The plugin will automatically read and inject this HTML. You can define the style and animation of this HTML as you wish. + +::: tip + +- You can use the same syntax as in `index.html`, such as the `VITE_APP_TITLE` variable, to get the application's title. +- You must ensure there is an element with `id="__app-loading__"`. +- Add a `hidden` class to the element with `id="__app-loading__"`. +- You must ensure there is a `style[data-app-loading="inject-css"]` element. + +```html{1,4} + +
+ +
<%= VITE_APP_TITLE %>
+
+``` diff --git a/apps/vben5/docs/src/en/guide/in-depth/locale.md b/apps/vben5/docs/src/en/guide/in-depth/locale.md new file mode 100644 index 000000000..549bc83f5 --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/locale.md @@ -0,0 +1,227 @@ +# Internationalization + +The project has integrated [Vue i18n](https://kazupon.github.io/vue-i18n/), and Chinese and English language packs have been configured. + +## IDE Plugin + +If you are using vscode as your development tool, it is recommended to install the [i18n Ally](https://marketplace.visualstudio.com/items?itemName=Lokalise.i18n-ally) plugin. It can help you manage internationalization copy more conveniently. After installing this plugin, you can see the corresponding language content in your code in real-time: + +![](/public/guide/locale.png) + +## Configure Default Language + +You just need to override the default preferences. In the corresponding application, find the `src/preferences.ts` file and modify the value of `locale`: + +```ts {3} +export const overridesPreferences = defineOverridesPreferences({ + app: { + locale: 'en-US', + }, +}); +``` + +## Dynamic Language Switching + +Switching languages consists of two parts: + +- Updating preferences +- Loading the corresponding language pack + +```ts +import type { SupportedLanguagesType } from '@vben/locales'; +import { loadLocaleMessages } from '@vben/locales'; +import { updatePreferences } from '@vben/preferences'; + +async function updateLocale(value: string) { + // 1. Update preferences + const locale = value as SupportedLanguagesType; + updatePreferences({ + app: { + locale, + }, + }); + // 2. Load the corresponding language pack + await loadLocaleMessages(locale); +} + +updateLocale('en-US'); +``` + +## Adding Translation Texts + +::: warning Attention + +- Do not place business translation texts inside `@vben/locales` to better manage business and general translation texts. +- When adding new translation texts and multiple language packs are available, ensure to add the corresponding texts in all language packs. + +::: + +To add new translation texts, simply find `src/locales/langs/` in the corresponding application and add the texts accordingly, for example: + +**src/locales/langs/zh-CN/\*.json** + +````ts +```json +{ + "about": { + "desc": "Vben Admin 是一个现代的管理模版。" + } +} +```` + +**src/locales/langs/en-US.ts** + +````ts +```json +{ + "about": { + "desc": "Vben Admin is a modern management template." + } +} +```` + +## Using Translation Texts + +With `@vben/locales`, you can easily use translation texts: + +### In Code + +```vue + + +``` + +## Adding a New Language Pack + +If you need to add a new language pack, follow these steps: + +- Add the corresponding language pack file in the `packages/locales/langs` directory, for example, `zh-TW.json`, and translate the respective texts. +- In the corresponding application, locate the `src/locales/langs` file and add the new language pack `zh-TW.json`. +- Add the corresponding language in `packages/constants/src/core.ts`: + + ```ts + export interface LanguageOption { + label: string; + value: 'en-US' | 'zh-CN'; // [!code --] + value: 'en-US' | 'zh-CN' | 'zh-TW'; // [!code ++] + } + export const SUPPORT_LANGUAGES: LanguageOption[] = [ + { + label: '简体中文', + value: 'zh-CN', + }, + { + label: 'English', + value: 'en-US', + }, + { + label: '繁体中文', // [!code ++] + value: 'zh-TW', // [!code ++] + }, + ]; + ``` + +- In `packages/locales/typing.ts`, add a new TypeScript type: + + ```ts + export type SupportedLanguagesType = 'en-US' | 'zh-CN'; // [!code --] + export type SupportedLanguagesType = 'en-US' | 'zh-CN' | 'zh-TW'; // [!code ++] + ``` + +At this point, you can use the newly added language pack in the project. + +## Interface Language Switching Function + +If you want to disable the language switching display button on the interface, in the corresponding application, find the `src/preferences.ts` file and modify the value of `locale` accordingly: + +```ts {3} +export const overridesPreferences = defineOverridesPreferences({ + widget: { + languageToggle: false, + }, +}); +``` + +## Remote Loading of Language Packs + +::: tip Tip + +When making interface requests through the project's built-in `request` tool, the default request header will include [Accept-Language](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language), allowing the server to dynamically internationalize data based on the request header. + +::: + +Each application has an independent language pack that can override the general language configuration. You can remotely load the corresponding language pack by finding the `src/locales/index.ts` file in the corresponding application and modifying the `loadMessages` method accordingly: + +```ts {3-4} +async function loadMessages(lang: SupportedLanguagesType) { + const [appLocaleMessages] = await Promise.all([ + // Modify here to load data via a remote interface + localesMap[lang](), + loadThirdPartyMessage(lang), + ]); + return appLocaleMessages.default; +} +``` + +## Third-Party Language Packs + +Different applications may use third-party component libraries or plugins with varying internationalization methods, so they need to be handled differently. If you need to introduce a third-party language pack, you can find the `src/locales/index.ts` file in the corresponding application and modify the `loadThirdPartyMessage` method accordingly: + +```ts +/** + * Load the dayjs language pack + * @param lang + */ +async function loadDayjsLocale(lang: SupportedLanguagesType) { + let locale; + switch (lang) { + case 'zh-CN': { + locale = await import('dayjs/locale/zh-cn'); + break; + } + case 'en-US': { + locale = await import('dayjs/locale/en'); + break; + } + // Default to using English + default: { + locale = await import('dayjs/locale/en'); + } + } + if (locale) { + dayjs.locale(locale); + } else { + console.error(`Failed to load dayjs locale for ${lang}`); + } +} +``` + +## Removing Internationalization + +Firstly, it is not recommended to remove internationalization, as it is a good development practice. However, if you really need to remove it, you can directly use Chinese copy and then retain the project's built-in language pack, which will not affect the overall development experience. The steps to remove internationalization are as follows: + +- Hide the language switching button on the interface, see: [Interface Language Switching Function](#interface-language-switching-function) +- Modify the default language, see: [Configure Default Language](#configure-default-language) +- Disable `vue-i18n` warning prompts, in the `src/locales/index.ts` file, modify `missingWarn` to `false`: + + ```ts + async function setupI18n(app: App, options: LocaleSetupOptions = {}) { + await coreSetup(app, { + defaultLocale: preferences.app.locale, + loadMessages, + missingWarn: !import.meta.env.PROD, // [!code --] + missingWarn: false, // [!code ++] + ...options, + }); + } + ``` diff --git a/apps/vben5/docs/src/en/guide/in-depth/login.md b/apps/vben5/docs/src/en/guide/in-depth/login.md new file mode 100644 index 000000000..7fdac2c6f --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/login.md @@ -0,0 +1,119 @@ +# Login + +This document explains how to customize the login page of your application. + +## Login Page Adjustment + +If you want to adjust the title, description, icon, and toolbar of the login page, you can do so by configuring the `props` parameter of the `AuthPageLayout` component. + +![login](/guide/login.png) + +You just need to configure the `props` parameter of `AuthPageLayout` in `src/router/routes/core.ts` within your application: + +```ts {4-8} + { + component: AuthPageLayout, + props: { + sloganImage: "xxx/xxx.png", + pageTitle: "开箱即用的大型中后台管理系统", + pageDescription: "工程化、高性能、跨组件库的前端模版", + toolbar: true, + toolbarList: ['color', 'language', 'layout', 'theme'], + } + // ... + }, +``` + +::: tip + +If these configurations do not meet your needs, you can implement your own login page. Simply implement your own `AuthPageLayout`. + +::: + +## Login Form Adjustment + +If you want to adjust the content of the login form, you can configure the `AuthenticationLogin` component parameters in `src/views/_core/authentication/login.vue` within your application: + +```vue + +``` + +::: details AuthenticationLogin Component Props + +```ts +{ + /** + * @en Verification code login path + */ + codeLoginPath?: string; + /** + * @en Forget password path + */ + forgetPasswordPath?: string; + + /** + * @en Whether it is in loading state + */ + loading?: boolean; + + /** + * @en QR code login path + */ + qrCodeLoginPath?: string; + + /** + * @en Registration path + */ + registerPath?: string; + + /** + * @en Whether to show verification code login + */ + showCodeLogin?: boolean; + /** + * @en Whether to show forget password + */ + showForgetPassword?: boolean; + + /** + * @en Whether to show QR code login + */ + showQrcodeLogin?: boolean; + + /** + * @en Whether to show registration button + */ + showRegister?: boolean; + + /** + * @en Whether to show remember account + */ + showRememberMe?: boolean; + + /** + * @en Whether to show third-party login + */ + showThirdPartyLogin?: boolean; + + /** + * @en Login box subtitle + */ + subTitle?: string; + + /** + * @en Login box title + */ + title?: string; +} +``` + +::: + +::: tip + +If these configurations do not meet your needs, you can implement your own login form and related login logic. + +::: diff --git a/apps/vben5/docs/src/en/guide/in-depth/theme.md b/apps/vben5/docs/src/en/guide/in-depth/theme.md new file mode 100644 index 000000000..11c9c992b --- /dev/null +++ b/apps/vben5/docs/src/en/guide/in-depth/theme.md @@ -0,0 +1,1293 @@ +# Theme + +The framework is built on [shadcn-vue](https://www.shadcn-vue.com/themes.html) and [tailwindcss](https://tailwindcss.com/), offering a rich theme configuration. You can easily switch between various themes through simple configuration to meet personalized needs. You can choose to use CSS variables or Tailwind CSS utility classes for theme settings. + +## CSS Variables + +The project follows the theme configuration of [shadcn-vue](https://www.shadcn-vue.com/themes.html), for example: + +```html +
+``` + +We use a simple convention for colors. The `background` variable is used for the background color of components, and the `foreground` variable is used for text color. + +For the following components, `background` will be `hsl(var(--primary))`, and `foreground` will be `hsl(var(--primary-foreground))`. + +## Detailed List of CSS Variables + +::: warning Note + +The colors inside CSS variables must use the `hsl` format, such as `0 0% 100%`, without adding `hsl()` and `,`. + +::: + +You can check the list below to understand all the available variables. + +::: details Default theme CSS variables + +```css +:root { + --font-family: -apple-system, blinkmacsystemfont, 'Segoe UI', roboto, + 'Helvetica Neue', arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', + 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; + + /* Default background color of ...etc */ + --background: 0 0% 100%; + + /* Main area background color */ + --background-deep: 216 20.11% 95.47%; + --foreground: 210 6% 21%; + + /* Background color for */ + --card: 0 0% 100%; + --card-foreground: 222.2 84% 4.9%; + + /* Background color for popovers such as , , */ + --popover: 0 0% 100%; + --popover-foreground: 222.2 84% 4.9%; + + /* Muted backgrounds such as , and */ + --muted: 210 40% 96.1%; + --muted-foreground: 215.4 16.3% 46.9%; + + /* Theme Colors */ + + --primary: 212 100% 45%; + --primary-foreground: 0 0% 98%; + + /* Used for destructive actions such as